Reset
This commit is contained in:
16
security/basic.go
Normal file
16
security/basic.go
Normal file
@ -0,0 +1,16 @@
|
||||
package security
|
||||
|
||||
// BasicConfig is the configuration for Basic authentication
|
||||
type BasicConfig struct {
|
||||
// Username is the name which will need to be used for a successful authentication
|
||||
Username string `yaml:"username"`
|
||||
|
||||
// PasswordBcryptHashBase64Encoded is the base64 encoded string of the Bcrypt hash of the password to use to
|
||||
// authenticate using basic auth.
|
||||
PasswordBcryptHashBase64Encoded string `yaml:"password-bcrypt-base64"`
|
||||
}
|
||||
|
||||
// isValid returns whether the basic security configuration is valid or not
|
||||
func (c *BasicConfig) isValid() bool {
|
||||
return len(c.Username) > 0 && len(c.PasswordBcryptHashBase64Encoded) > 0
|
||||
}
|
23
security/basic_test.go
Normal file
23
security/basic_test.go
Normal file
@ -0,0 +1,23 @@
|
||||
package security
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestBasicConfig_IsValidUsingBcrypt(t *testing.T) {
|
||||
basicConfig := &BasicConfig{
|
||||
Username: "admin",
|
||||
PasswordBcryptHashBase64Encoded: "JDJhJDA4JDFoRnpPY1hnaFl1OC9ISlFsa21VS09wOGlPU1ZOTDlHZG1qeTFvb3dIckRBUnlHUmNIRWlT",
|
||||
}
|
||||
if !basicConfig.isValid() {
|
||||
t.Error("basicConfig should've been valid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicConfig_IsValidWhenPasswordIsInvalidUsingBcrypt(t *testing.T) {
|
||||
basicConfig := &BasicConfig{
|
||||
Username: "admin",
|
||||
PasswordBcryptHashBase64Encoded: "",
|
||||
}
|
||||
if basicConfig.isValid() {
|
||||
t.Error("basicConfig shouldn't have been valid")
|
||||
}
|
||||
}
|
110
security/config.go
Normal file
110
security/config.go
Normal file
@ -0,0 +1,110 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
|
||||
g8 "github.com/TwiN/g8/v2"
|
||||
"github.com/TwiN/logr"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/adaptor"
|
||||
"github.com/gofiber/fiber/v2/middleware/basicauth"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
cookieNameState = "gatus_state"
|
||||
cookieNameNonce = "gatus_nonce"
|
||||
cookieNameSession = "gatus_session"
|
||||
)
|
||||
|
||||
// Config is the security configuration for Gatus
|
||||
type Config struct {
|
||||
Basic *BasicConfig `yaml:"basic,omitempty"`
|
||||
OIDC *OIDCConfig `yaml:"oidc,omitempty"`
|
||||
|
||||
gate *g8.Gate
|
||||
}
|
||||
|
||||
// IsValid returns whether the security configuration is valid or not
|
||||
func (c *Config) IsValid() bool {
|
||||
return (c.Basic != nil && c.Basic.isValid()) || (c.OIDC != nil && c.OIDC.isValid())
|
||||
}
|
||||
|
||||
// RegisterHandlers registers all handlers required based on the security configuration
|
||||
func (c *Config) RegisterHandlers(router fiber.Router) error {
|
||||
if c.OIDC != nil {
|
||||
if err := c.OIDC.initialize(); err != nil {
|
||||
return err
|
||||
}
|
||||
router.All("/oidc/login", c.OIDC.loginHandler)
|
||||
router.All("/authorization-code/callback", adaptor.HTTPHandlerFunc(c.OIDC.callbackHandler))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplySecurityMiddleware applies an authentication middleware to the router passed.
|
||||
// The router passed should be a sub-router in charge of handlers that require authentication.
|
||||
func (c *Config) ApplySecurityMiddleware(router fiber.Router) error {
|
||||
if c.OIDC != nil {
|
||||
// We're going to use g8 for session handling
|
||||
clientProvider := g8.NewClientProvider(func(token string) *g8.Client {
|
||||
if _, exists := sessions.Get(token); exists {
|
||||
return g8.NewClient(token)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
customTokenExtractorFunc := func(request *http.Request) string {
|
||||
sessionCookie, err := request.Cookie(cookieNameSession)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return sessionCookie.Value
|
||||
}
|
||||
// TODO: g8: Add a way to update cookie after? would need the writer
|
||||
authorizationService := g8.NewAuthorizationService().WithClientProvider(clientProvider)
|
||||
c.gate = g8.New().WithAuthorizationService(authorizationService).WithCustomTokenExtractor(customTokenExtractorFunc)
|
||||
router.Use(adaptor.HTTPMiddleware(c.gate.Protect))
|
||||
} else if c.Basic != nil {
|
||||
var decodedBcryptHash []byte
|
||||
if len(c.Basic.PasswordBcryptHashBase64Encoded) > 0 {
|
||||
var err error
|
||||
decodedBcryptHash, err = base64.URLEncoding.DecodeString(c.Basic.PasswordBcryptHashBase64Encoded)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
router.Use(basicauth.New(basicauth.Config{
|
||||
Authorizer: func(username, password string) bool {
|
||||
if len(c.Basic.PasswordBcryptHashBase64Encoded) > 0 {
|
||||
if username != c.Basic.Username || bcrypt.CompareHashAndPassword(decodedBcryptHash, []byte(password)) != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
},
|
||||
Unauthorized: func(ctx *fiber.Ctx) error {
|
||||
ctx.Set("WWW-Authenticate", "Basic")
|
||||
return ctx.Status(401).SendString("Unauthorized")
|
||||
},
|
||||
}))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsAuthenticated checks whether the user is authenticated
|
||||
// If the Config does not warrant authentication, it will always return true.
|
||||
func (c *Config) IsAuthenticated(ctx *fiber.Ctx) bool {
|
||||
if c.gate != nil {
|
||||
// TODO: Update g8 to support fasthttp natively? (see g8's fasthttp branch)
|
||||
request, err := adaptor.ConvertRequest(ctx, false)
|
||||
if err != nil {
|
||||
logr.Errorf("[security.IsAuthenticated] Unexpected error converting request: %v", err)
|
||||
return false
|
||||
}
|
||||
token := c.gate.ExtractTokenFromRequest(request)
|
||||
_, hasSession := sessions.Get(token)
|
||||
return hasSession
|
||||
}
|
||||
return false
|
||||
}
|
136
security/config_test.go
Normal file
136
security/config_test.go
Normal file
@ -0,0 +1,136 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
func TestConfig_IsValid(t *testing.T) {
|
||||
c := &Config{
|
||||
Basic: nil,
|
||||
OIDC: nil,
|
||||
}
|
||||
if c.IsValid() {
|
||||
t.Error("expected empty config to be valid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfig_ApplySecurityMiddleware(t *testing.T) {
|
||||
///////////
|
||||
// BASIC //
|
||||
///////////
|
||||
t.Run("basic", func(t *testing.T) {
|
||||
// Bcrypt
|
||||
c := &Config{Basic: &BasicConfig{
|
||||
Username: "john.doe",
|
||||
PasswordBcryptHashBase64Encoded: "JDJhJDA4JDFoRnpPY1hnaFl1OC9ISlFsa21VS09wOGlPU1ZOTDlHZG1qeTFvb3dIckRBUnlHUmNIRWlT",
|
||||
}}
|
||||
app := fiber.New()
|
||||
if err := c.ApplySecurityMiddleware(app); err != nil {
|
||||
t.Error("expected no error, got", err)
|
||||
}
|
||||
app.Get("/test", func(c *fiber.Ctx) error {
|
||||
return c.SendStatus(200)
|
||||
})
|
||||
// Try to access the route without basic auth
|
||||
request := httptest.NewRequest("GET", "/test", http.NoBody)
|
||||
response, err := app.Test(request)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error, got", err)
|
||||
}
|
||||
if response.StatusCode != 401 {
|
||||
t.Error("expected code to be 401, but was", response.StatusCode)
|
||||
}
|
||||
// Try again, but with basic auth
|
||||
request = httptest.NewRequest("GET", "/test", http.NoBody)
|
||||
request.SetBasicAuth("john.doe", "hunter2")
|
||||
response, err = app.Test(request)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error, got", err)
|
||||
}
|
||||
if response.StatusCode != 200 {
|
||||
t.Error("expected code to be 200, but was", response.StatusCode)
|
||||
}
|
||||
})
|
||||
//////////
|
||||
// OIDC //
|
||||
//////////
|
||||
t.Run("oidc", func(t *testing.T) {
|
||||
c := &Config{OIDC: &OIDCConfig{
|
||||
IssuerURL: "https://sso.gatus.io/",
|
||||
RedirectURL: "http://localhost:80/authorization-code/callback",
|
||||
Scopes: []string{"openid"},
|
||||
AllowedSubjects: []string{"user1@example.com"},
|
||||
oauth2Config: oauth2.Config{},
|
||||
verifier: nil,
|
||||
}}
|
||||
app := fiber.New()
|
||||
if err := c.ApplySecurityMiddleware(app); err != nil {
|
||||
t.Error("expected no error, got", err)
|
||||
}
|
||||
app.Get("/test", func(c *fiber.Ctx) error {
|
||||
return c.SendStatus(200)
|
||||
})
|
||||
// Try without any session cookie
|
||||
request := httptest.NewRequest("GET", "/test", http.NoBody)
|
||||
response, err := app.Test(request)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error, got", err)
|
||||
}
|
||||
if response.StatusCode != 401 {
|
||||
t.Error("expected code to be 401, but was", response.StatusCode)
|
||||
}
|
||||
// Try with a session cookie
|
||||
request = httptest.NewRequest("GET", "/test", http.NoBody)
|
||||
request.AddCookie(&http.Cookie{Name: "session", Value: "123"})
|
||||
response, err = app.Test(request)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error, got", err)
|
||||
}
|
||||
if response.StatusCode != 401 {
|
||||
t.Error("expected code to be 401, but was", response.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfig_RegisterHandlers(t *testing.T) {
|
||||
c := &Config{}
|
||||
app := fiber.New()
|
||||
c.RegisterHandlers(app)
|
||||
// Try to access the OIDC handler. This should fail, because the security config doesn't have OIDC
|
||||
request := httptest.NewRequest("GET", "/oidc/login", http.NoBody)
|
||||
response, err := app.Test(request)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error, got", err)
|
||||
}
|
||||
if response.StatusCode != 404 {
|
||||
t.Error("expected code to be 404, but was", response.StatusCode)
|
||||
}
|
||||
// Set an empty OIDC config. This should fail, because the IssuerURL is required.
|
||||
c.OIDC = &OIDCConfig{}
|
||||
if err := c.RegisterHandlers(app); err == nil {
|
||||
t.Fatal("expected an error, but got none")
|
||||
}
|
||||
// Set the OIDC config and try again
|
||||
c.OIDC = &OIDCConfig{
|
||||
IssuerURL: "https://sso.gatus.io/",
|
||||
RedirectURL: "http://localhost:80/authorization-code/callback",
|
||||
Scopes: []string{"openid"},
|
||||
AllowedSubjects: []string{"user1@example.com"},
|
||||
}
|
||||
if err := c.RegisterHandlers(app); err != nil {
|
||||
t.Fatal("expected no error, but got", err)
|
||||
}
|
||||
request = httptest.NewRequest("GET", "/oidc/login", http.NoBody)
|
||||
response, err = app.Test(request)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error, got", err)
|
||||
}
|
||||
if response.StatusCode != 302 {
|
||||
t.Error("expected code to be 302, but was", response.StatusCode)
|
||||
}
|
||||
}
|
142
security/oidc.go
Normal file
142
security/oidc.go
Normal file
@ -0,0 +1,142 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/TwiN/logr"
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// OIDCConfig is the configuration for OIDC authentication
|
||||
type OIDCConfig struct {
|
||||
IssuerURL string `yaml:"issuer-url"` // e.g. https://dev-12345678.okta.com
|
||||
RedirectURL string `yaml:"redirect-url"` // e.g. http://localhost:8080/authorization-code/callback
|
||||
ClientID string `yaml:"client-id"`
|
||||
ClientSecret string `yaml:"client-secret"`
|
||||
Scopes []string `yaml:"scopes"` // e.g. ["openid"]
|
||||
AllowedSubjects []string `yaml:"allowed-subjects"` // e.g. ["user1@example.com"]. If empty, all subjects are allowed
|
||||
|
||||
oauth2Config oauth2.Config
|
||||
verifier *oidc.IDTokenVerifier
|
||||
}
|
||||
|
||||
// isValid returns whether the basic security configuration is valid or not
|
||||
func (c *OIDCConfig) isValid() bool {
|
||||
return len(c.IssuerURL) > 0 && len(c.RedirectURL) > 0 && strings.HasSuffix(c.RedirectURL, "/authorization-code/callback") && len(c.ClientID) > 0 && len(c.ClientSecret) > 0 && len(c.Scopes) > 0
|
||||
}
|
||||
|
||||
func (c *OIDCConfig) initialize() error {
|
||||
provider, err := oidc.NewProvider(context.Background(), c.IssuerURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.verifier = provider.Verifier(&oidc.Config{ClientID: c.ClientID})
|
||||
// Configure an OpenID Connect aware OAuth2 client.
|
||||
c.oauth2Config = oauth2.Config{
|
||||
ClientID: c.ClientID,
|
||||
ClientSecret: c.ClientSecret,
|
||||
Scopes: c.Scopes,
|
||||
RedirectURL: c.RedirectURL,
|
||||
Endpoint: provider.Endpoint(),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *OIDCConfig) loginHandler(ctx *fiber.Ctx) error {
|
||||
state, nonce := uuid.NewString(), uuid.NewString()
|
||||
ctx.Cookie(&fiber.Cookie{
|
||||
Name: cookieNameState,
|
||||
Value: state,
|
||||
Path: "/",
|
||||
MaxAge: int(time.Hour.Seconds()),
|
||||
SameSite: "lax",
|
||||
HTTPOnly: true,
|
||||
})
|
||||
ctx.Cookie(&fiber.Cookie{
|
||||
Name: cookieNameNonce,
|
||||
Value: nonce,
|
||||
Path: "/",
|
||||
MaxAge: int(time.Hour.Seconds()),
|
||||
SameSite: "lax",
|
||||
HTTPOnly: true,
|
||||
})
|
||||
return ctx.Redirect(c.oauth2Config.AuthCodeURL(state, oidc.Nonce(nonce)), http.StatusFound)
|
||||
}
|
||||
|
||||
func (c *OIDCConfig) callbackHandler(w http.ResponseWriter, r *http.Request) { // TODO: Migrate to a native fiber handler
|
||||
// Check if there's an error
|
||||
if len(r.URL.Query().Get("error")) > 0 {
|
||||
http.Error(w, r.URL.Query().Get("error")+": "+r.URL.Query().Get("error_description"), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Ensure that the state has the expected value
|
||||
state, err := r.Cookie(cookieNameState)
|
||||
if err != nil {
|
||||
http.Error(w, "state not found", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if r.URL.Query().Get("state") != state.Value {
|
||||
http.Error(w, "state did not match", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Validate token
|
||||
oauth2Token, err := c.oauth2Config.Exchange(r.Context(), r.URL.Query().Get("code"))
|
||||
if err != nil {
|
||||
http.Error(w, "Error exchanging token: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
http.Error(w, "Missing 'id_token' in oauth2 token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
idToken, err := c.verifier.Verify(r.Context(), rawIDToken)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to verify id_token: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// Validate nonce
|
||||
nonce, err := r.Cookie(cookieNameNonce)
|
||||
if err != nil {
|
||||
http.Error(w, "nonce not found", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if idToken.Nonce != nonce.Value {
|
||||
http.Error(w, "nonce did not match", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(c.AllowedSubjects) == 0 {
|
||||
// If there's no allowed subjects, all subjects are allowed.
|
||||
c.setSessionCookie(w, idToken)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
for _, subject := range c.AllowedSubjects {
|
||||
if strings.ToLower(subject) == strings.ToLower(idToken.Subject) {
|
||||
c.setSessionCookie(w, idToken)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
logr.Debugf("[security.callbackHandler] Subject %s is not in the list of allowed subjects", idToken.Subject)
|
||||
http.Redirect(w, r, "/?error=access_denied", http.StatusFound)
|
||||
}
|
||||
|
||||
func (c *OIDCConfig) setSessionCookie(w http.ResponseWriter, idToken *oidc.IDToken) {
|
||||
// At this point, the user has been confirmed. All that's left to do is create a session.
|
||||
sessionID := uuid.NewString()
|
||||
sessions.SetWithTTL(sessionID, idToken.Subject, time.Hour)
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: cookieNameSession,
|
||||
Value: sessionID,
|
||||
Path: "/",
|
||||
MaxAge: int(time.Hour.Seconds()),
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
})
|
||||
}
|
70
security/oidc_test.go
Normal file
70
security/oidc_test.go
Normal file
@ -0,0 +1,70 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
)
|
||||
|
||||
func TestOIDCConfig_isValid(t *testing.T) {
|
||||
c := &OIDCConfig{
|
||||
IssuerURL: "https://sso.gatus.io/",
|
||||
RedirectURL: "http://localhost:80/authorization-code/callback",
|
||||
ClientID: "client-id",
|
||||
ClientSecret: "client-secret",
|
||||
Scopes: []string{"openid"},
|
||||
AllowedSubjects: []string{"user1@example.com"},
|
||||
}
|
||||
if !c.isValid() {
|
||||
t.Error("OIDCConfig should be valid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCConfig_callbackHandler(t *testing.T) {
|
||||
c := &OIDCConfig{
|
||||
IssuerURL: "https://sso.gatus.io/",
|
||||
RedirectURL: "http://localhost:80/authorization-code/callback",
|
||||
ClientID: "client-id",
|
||||
ClientSecret: "client-secret",
|
||||
Scopes: []string{"openid"},
|
||||
AllowedSubjects: []string{"user1@example.com"},
|
||||
}
|
||||
if err := c.initialize(); err != nil {
|
||||
t.Fatal("expected no error, but got", err)
|
||||
}
|
||||
// Try with no state cookie
|
||||
request, _ := http.NewRequest("GET", "/authorization-code/callback", nil)
|
||||
responseRecorder := httptest.NewRecorder()
|
||||
c.callbackHandler(responseRecorder, request)
|
||||
if responseRecorder.Code != http.StatusBadRequest {
|
||||
t.Error("expected code to be 400, but was", responseRecorder.Code)
|
||||
}
|
||||
// Try with state cookie
|
||||
request, _ = http.NewRequest("GET", "/authorization-code/callback", nil)
|
||||
request.AddCookie(&http.Cookie{Name: cookieNameState, Value: "fake-state"})
|
||||
responseRecorder = httptest.NewRecorder()
|
||||
c.callbackHandler(responseRecorder, request)
|
||||
if responseRecorder.Code != http.StatusBadRequest {
|
||||
t.Error("expected code to be 400, but was", responseRecorder.Code)
|
||||
}
|
||||
// Try with state cookie and state query parameter
|
||||
request, _ = http.NewRequest("GET", "/authorization-code/callback?state=fake-state", nil)
|
||||
request.AddCookie(&http.Cookie{Name: cookieNameState, Value: "fake-state"})
|
||||
responseRecorder = httptest.NewRecorder()
|
||||
c.callbackHandler(responseRecorder, request)
|
||||
// Exchange should fail, so 500.
|
||||
if responseRecorder.Code != http.StatusInternalServerError {
|
||||
t.Error("expected code to be 500, but was", responseRecorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCConfig_setSessionCookie(t *testing.T) {
|
||||
c := &OIDCConfig{}
|
||||
responseRecorder := httptest.NewRecorder()
|
||||
c.setSessionCookie(responseRecorder, &oidc.IDToken{Subject: "test@example.com"})
|
||||
if len(responseRecorder.Result().Cookies()) == 0 {
|
||||
t.Error("expected cookie to be set")
|
||||
}
|
||||
}
|
5
security/sessions.go
Normal file
5
security/sessions.go
Normal file
@ -0,0 +1,5 @@
|
||||
package security
|
||||
|
||||
import "github.com/TwiN/gocache/v2"
|
||||
|
||||
var sessions = gocache.NewCache().WithEvictionPolicy(gocache.LeastRecentlyUsed) // TODO: Move this to storage
|
Reference in New Issue
Block a user