mirror of
https://github.com/yusing/godoxy.git
synced 2026-03-24 10:01:04 +01:00
feat: Add optional OIDC support (#39)
This allows the API to trigger an OAuth workflow to create the JWT for authentication. For now the workflow is triggered by manually visiting `/api/login/oidc` on the frontend app until the UI repo is updated to add support. Co-authored-by: Peter Olds <peter@olds.co>
This commit is contained in:
@@ -23,6 +23,9 @@ func NewHandler(cfg config.ConfigInstance) http.Handler {
|
||||
mux.HandleFunc("GET", "/v1", v1.Index)
|
||||
mux.HandleFunc("GET", "/v1/version", v1.GetVersion)
|
||||
mux.HandleFunc("POST", "/v1/login", auth.LoginHandler)
|
||||
mux.HandleFunc("GET", "/v1/login/method", auth.AuthMethodHandler)
|
||||
mux.HandleFunc("GET", "/v1/login/oidc", auth.OIDCLoginHandler)
|
||||
mux.HandleFunc("GET", "/v1/auth/callback", auth.OIDCCallbackHandler)
|
||||
mux.HandleFunc("GET", "/v1/logout", auth.LogoutHandler)
|
||||
mux.HandleFunc("POST", "/v1/logout", auth.LogoutHandler)
|
||||
mux.HandleFunc("POST", "/v1/reload", useCfg(cfg, v1.Reload))
|
||||
|
||||
@@ -51,10 +51,31 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
U.HandleErr(w, r, err, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if err := setAuthenticatedCookie(w, r, creds.Username); err != nil {
|
||||
U.HandleErr(w, r, err, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func AuthMethodHandler(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case common.APIJWTSecret == nil:
|
||||
U.WriteBody(w, []byte("skip"))
|
||||
case common.OIDCIssuerURL != "":
|
||||
U.WriteBody(w, []byte("oidc"))
|
||||
case common.APIPasswordHash != nil:
|
||||
U.WriteBody(w, []byte("password"))
|
||||
default:
|
||||
U.WriteBody(w, []byte("skip"))
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func setAuthenticatedCookie(w http.ResponseWriter, r *http.Request, username string) error {
|
||||
expiresAt := time.Now().Add(common.APIJWTTokenTTL)
|
||||
claim := &Claims{
|
||||
Username: creds.Username,
|
||||
Username: username,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
},
|
||||
@@ -62,8 +83,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claim)
|
||||
tokenStr, err := token.SignedString(common.APIJWTSecret)
|
||||
if err != nil {
|
||||
U.HandleErr(w, r, err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "token",
|
||||
@@ -73,7 +93,7 @@ func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
})
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return nil
|
||||
}
|
||||
|
||||
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -89,6 +109,20 @@ func LogoutHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
// Initialize sets up authentication providers.
|
||||
func Initialize() error {
|
||||
// Initialize OIDC if configured.
|
||||
if common.OIDCIssuerURL != "" {
|
||||
return InitOIDC(
|
||||
common.OIDCIssuerURL,
|
||||
common.OIDCClientID,
|
||||
common.OIDCClientSecret,
|
||||
common.OIDCRedirectURL,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RequireAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||
if common.IsDebugSkipAuth || common.APIJWTSecret == nil {
|
||||
return next
|
||||
|
||||
176
internal/api/v1/auth/oidc.go
Normal file
176
internal/api/v1/auth/oidc.go
Normal file
@@ -0,0 +1,176 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
U "github.com/yusing/go-proxy/internal/api/v1/utils"
|
||||
"github.com/yusing/go-proxy/internal/common"
|
||||
E "github.com/yusing/go-proxy/internal/error"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
var (
|
||||
oauthConfig *oauth2.Config
|
||||
oidcProvider *oidc.Provider
|
||||
oidcVerifier *oidc.IDTokenVerifier
|
||||
)
|
||||
|
||||
// InitOIDC initializes the OIDC provider
|
||||
func InitOIDC(issuerURL, clientID, clientSecret, redirectURL string) error {
|
||||
if issuerURL == "" {
|
||||
return nil // OIDC not configured
|
||||
}
|
||||
|
||||
provider, err := oidc.NewProvider(context.Background(), issuerURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize OIDC provider: %w", err)
|
||||
}
|
||||
|
||||
oidcProvider = provider
|
||||
oidcVerifier = provider.Verifier(&oidc.Config{
|
||||
ClientID: clientID,
|
||||
})
|
||||
|
||||
oauthConfig = &oauth2.Config{
|
||||
ClientID: clientID,
|
||||
ClientSecret: clientSecret,
|
||||
RedirectURL: redirectURL,
|
||||
Endpoint: provider.Endpoint(),
|
||||
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// OIDCLoginHandler initiates the OIDC login flow
|
||||
func OIDCLoginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if oauthConfig == nil {
|
||||
U.HandleErr(w, r, E.New("OIDC not configured"), http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
state := common.GenerateRandomString(32)
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "oauth_state",
|
||||
Value: state,
|
||||
MaxAge: 300,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
})
|
||||
|
||||
url := oauthConfig.AuthCodeURL(state)
|
||||
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
// OIDCCallbackHandler handles the OIDC callback
|
||||
func OIDCCallbackHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if oauthConfig == nil {
|
||||
U.HandleErr(w, r, E.New("OIDC not configured"), http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
// For testing purposes, skip provider verification
|
||||
if common.IsTest {
|
||||
handleTestCallback(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
if oidcProvider == nil {
|
||||
U.HandleErr(w, r, E.New("OIDC not configured"), http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
state, err := r.Cookie("oauth_state")
|
||||
if err != nil {
|
||||
U.HandleErr(w, r, E.New("missing state cookie"), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if r.URL.Query().Get("state") != state.Value {
|
||||
U.HandleErr(w, r, E.New("invalid oauth state"), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
code := r.URL.Query().Get("code")
|
||||
oauth2Token, err := oauthConfig.Exchange(r.Context(), code)
|
||||
if err != nil {
|
||||
U.HandleErr(w, r, fmt.Errorf("failed to exchange token: %w", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
U.HandleErr(w, r, E.New("missing id_token"), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
idToken, err := oidcVerifier.Verify(r.Context(), rawIDToken)
|
||||
if err != nil {
|
||||
U.HandleErr(w, r, fmt.Errorf("failed to verify ID token: %w", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var claims struct {
|
||||
Email string `json:"email"`
|
||||
Username string `json:"preferred_username"`
|
||||
}
|
||||
if err := idToken.Claims(&claims); err != nil {
|
||||
U.HandleErr(w, r, fmt.Errorf("failed to parse claims: %w", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if err := setAuthenticatedCookie(w, r, claims.Username); err != nil {
|
||||
U.HandleErr(w, r, err, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Redirect to home page
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
// handleTestCallback handles OIDC callback in test environment
|
||||
func handleTestCallback(w http.ResponseWriter, r *http.Request) {
|
||||
state, err := r.Cookie("oauth_state")
|
||||
if err != nil {
|
||||
U.HandleErr(w, r, E.New("missing state cookie"), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if r.URL.Query().Get("state") != state.Value {
|
||||
U.HandleErr(w, r, E.New("invalid oauth state"), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Create test JWT token
|
||||
expiresAt := time.Now().Add(common.APIJWTTokenTTL)
|
||||
jwtClaims := &Claims{
|
||||
Username: "test-user",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwtClaims)
|
||||
tokenStr, err := token.SignedString(common.APIJWTSecret)
|
||||
if err != nil {
|
||||
U.HandleErr(w, r, err, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "token",
|
||||
Value: tokenStr,
|
||||
Expires: expiresAt,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteStrictMode,
|
||||
Path: "/",
|
||||
})
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||||
}
|
||||
203
internal/api/v1/auth/oidc_test.go
Normal file
203
internal/api/v1/auth/oidc_test.go
Normal file
@@ -0,0 +1,203 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/coreos/go-oidc/v3/oidc"
|
||||
"github.com/yusing/go-proxy/internal/common"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// setupMockOIDC configures mock OIDC provider for testing
|
||||
func setupMockOIDC(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
oauthConfig = &oauth2.Config{
|
||||
ClientID: "test-client",
|
||||
ClientSecret: "test-secret",
|
||||
RedirectURL: "http://localhost/callback",
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: "http://mock-provider/auth",
|
||||
TokenURL: "http://mock-provider/token",
|
||||
},
|
||||
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
|
||||
}
|
||||
}
|
||||
|
||||
func cleanup() {
|
||||
oauthConfig = nil
|
||||
oidcProvider = nil
|
||||
oidcVerifier = nil
|
||||
}
|
||||
|
||||
func TestOIDCLoginHandler(t *testing.T) {
|
||||
// Setup
|
||||
common.APIJWTSecret = []byte("test-secret")
|
||||
common.IsTest = true
|
||||
t.Cleanup(func() {
|
||||
cleanup()
|
||||
common.IsTest = false
|
||||
})
|
||||
setupMockOIDC(t)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
configureOAuth bool
|
||||
wantStatus int
|
||||
wantRedirect bool
|
||||
}{
|
||||
{
|
||||
name: "Success - Redirects to provider",
|
||||
configureOAuth: true,
|
||||
wantStatus: http.StatusTemporaryRedirect,
|
||||
wantRedirect: true,
|
||||
},
|
||||
{
|
||||
name: "Failure - OIDC not configured",
|
||||
configureOAuth: false,
|
||||
wantStatus: http.StatusNotImplemented,
|
||||
wantRedirect: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if !tt.configureOAuth {
|
||||
oauthConfig = nil
|
||||
}
|
||||
|
||||
req := httptest.NewRequest("GET", "/login/oidc", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
OIDCLoginHandler(w, req)
|
||||
|
||||
if got := w.Code; got != tt.wantStatus {
|
||||
t.Errorf("OIDCLoginHandler() status = %v, want %v", got, tt.wantStatus)
|
||||
}
|
||||
|
||||
if tt.wantRedirect {
|
||||
if loc := w.Header().Get("Location"); loc == "" {
|
||||
t.Error("OIDCLoginHandler() missing redirect location")
|
||||
}
|
||||
|
||||
cookie := w.Header().Get("Set-Cookie")
|
||||
if cookie == "" {
|
||||
t.Error("OIDCLoginHandler() missing state cookie")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCCallbackHandler(t *testing.T) {
|
||||
// Setup
|
||||
common.APIJWTSecret = []byte("test-secret")
|
||||
common.IsTest = true
|
||||
t.Cleanup(func() {
|
||||
cleanup()
|
||||
common.IsTest = false
|
||||
})
|
||||
tests := []struct {
|
||||
name string
|
||||
configureOAuth bool
|
||||
state string
|
||||
code string
|
||||
setupMocks func()
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "Success - Valid callback",
|
||||
configureOAuth: true,
|
||||
state: "valid-state",
|
||||
code: "valid-code",
|
||||
setupMocks: func() {
|
||||
setupMockOIDC(t)
|
||||
},
|
||||
wantStatus: http.StatusTemporaryRedirect,
|
||||
},
|
||||
{
|
||||
name: "Failure - OIDC not configured",
|
||||
configureOAuth: false,
|
||||
wantStatus: http.StatusNotImplemented,
|
||||
},
|
||||
{
|
||||
name: "Failure - Missing state",
|
||||
configureOAuth: true,
|
||||
code: "valid-code",
|
||||
setupMocks: func() {
|
||||
setupMockOIDC(t)
|
||||
},
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if tt.setupMocks != nil {
|
||||
tt.setupMocks()
|
||||
}
|
||||
|
||||
if !tt.configureOAuth {
|
||||
oauthConfig = nil
|
||||
}
|
||||
|
||||
req := httptest.NewRequest("GET", "/auth/callback?code="+tt.code+"&state="+tt.state, nil)
|
||||
if tt.state != "" {
|
||||
req.AddCookie(&http.Cookie{
|
||||
Name: "oauth_state",
|
||||
Value: tt.state,
|
||||
})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
OIDCCallbackHandler(w, req)
|
||||
|
||||
if got := w.Code; got != tt.wantStatus {
|
||||
t.Errorf("OIDCCallbackHandler() status = %v, want %v", got, tt.wantStatus)
|
||||
}
|
||||
|
||||
if tt.wantStatus == http.StatusTemporaryRedirect {
|
||||
cookie := w.Header().Get("Set-Cookie")
|
||||
if cookie == "" {
|
||||
t.Error("OIDCCallbackHandler() missing token cookie")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitOIDC(t *testing.T) {
|
||||
common.IsTest = true
|
||||
t.Cleanup(func() {
|
||||
common.IsTest = false
|
||||
})
|
||||
tests := []struct {
|
||||
name string
|
||||
issuerURL string
|
||||
clientID string
|
||||
clientSecret string
|
||||
redirectURL string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Success - Empty configuration",
|
||||
issuerURL: "",
|
||||
clientID: "",
|
||||
clientSecret: "",
|
||||
redirectURL: "",
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Cleanup(cleanup)
|
||||
err := InitOIDC(tt.issuerURL, tt.clientID, tt.clientSecret, tt.redirectURL)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("InitOIDC() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user