Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,4 @@ These limitations are part of the roadmap and will be addressed in the future.

* Currently we don't support related resources, like ConfigMaps, Secrets.
* We don't support lifecycle of `BoundSchema` resources, like schema changes.
* The backend currently does not support running with replicas > 1 due to missing external session storage implementation. Session storage is currently in-memory only, which prevents proper session sharing across multiple backend instances.
28 changes: 22 additions & 6 deletions backend/auth/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,18 @@ type AuthHandler struct {
jwtService *JWTService
cookieSigningKey []byte
cookieEncryptionKey []byte
sessionStore session.Store
tokenExpiry time.Duration
}

func NewAuthHandler(oidc OIDCProvider, jwtService *JWTService, cookieSigningKey, cookieEncryptionKey []byte) *AuthHandler {
func NewAuthHandler(oidc OIDCProvider, jwtService *JWTService, cookieSigningKey, cookieEncryptionKey []byte, sessionStore session.Store, tokenExpiry time.Duration) *AuthHandler {
return &AuthHandler{
oidc: oidc,
jwtService: jwtService,
cookieSigningKey: cookieSigningKey,
cookieEncryptionKey: cookieEncryptionKey,
sessionStore: sessionStore,
tokenExpiry: tokenExpiry,
}
}

Expand Down Expand Up @@ -87,7 +91,7 @@ func (ah *AuthHandler) HandleAuthorize(w http.ResponseWriter, r *http.Request) {
return
}

scopes := []string{"openid", "profile", "email", "offline_access"}
scopes := []string{"openid", "profile", "email", "offline_access", "groups"}
dataCode, err := json.Marshal(authReq)
if err != nil {
logger.Info("failed to marshal auth code", "error", err)
Expand Down Expand Up @@ -181,6 +185,13 @@ func (ah *AuthHandler) HandleCallback(w http.ResponseWriter, r *http.Request) {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
// Set session expiration and store in middleware
err = ah.sessionStore.Save(sessionState)
if err != nil {
logger.Error(err, "failed to save session state")
http.Error(w, "internal error", http.StatusInternalServerError)
return
}

// Detect client type from redirect URL or user agent
clientType := authCode.ClientType
Expand Down Expand Up @@ -224,6 +235,7 @@ func (ah *AuthHandler) HandleCallback(w http.ResponseWriter, r *http.Request) {

// UI flow - set cookie and redirect to UI
cookieName := ah.generateCookieName(authCode.ClusterID)

s := securecookie.New(ah.cookieSigningKey, ah.cookieEncryptionKey)
encoded, err := s.Encode(cookieName, sessionState)
if err != nil {
Expand Down Expand Up @@ -282,22 +294,26 @@ func (ah *AuthHandler) createSessionState(authCode *AuthorizeRequest, token *oau
}

var idToken struct {
Subject string `json:"sub"`
Issuer string `json:"iss"`
Subject string `json:"sub"`
Issuer string `json:"iss"`
Groups []string `json:"groups,omitempty"`
}
if err := json.Unmarshal(jwt, &idToken); err != nil {
return nil, fmt.Errorf("failed to parse ID token: %w", err)
}

return &session.State{
s := &session.State{
Token: session.TokenInfo{
Subject: idToken.Subject,
Issuer: idToken.Issuer,
Groups: idToken.Groups,
},
SessionID: authCode.SessionID,
ClusterID: authCode.ClusterID,
RedirectURL: authCode.RedirectURL,
}, nil
}
s.SetExpiration(ah.tokenExpiry)
return s, nil
}

func (ah *AuthHandler) unwrapJWT(p string) ([]byte, error) {
Expand Down
97 changes: 83 additions & 14 deletions backend/auth/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@ import (
"encoding/json"
"net/http"
"strings"
"time"

"github.com/gorilla/securecookie"
"k8s.io/klog/v2"

"github.com/kube-bind/kube-bind/backend/kubernetes"
"github.com/kube-bind/kube-bind/backend/session"
kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2"
)

type contextKey string
Expand All @@ -49,19 +52,48 @@ type AuthContext struct {

type AuthMiddleware struct {
jwtService *JWTService
kubernetesManager *kubernetes.Manager
cookieSigningKey []byte
cookieEncryptionKey []byte
sessionStore session.Store
}

func NewAuthMiddleware(jwtService *JWTService, cookieSigningKey, cookieEncryptionKey []byte) *AuthMiddleware {
// writeErrorResponse writes a structured error response to the HTTP response writer
func writeErrorResponse(w http.ResponseWriter, statusCode int, code, message, details string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)

errorResponse := kubebindv1alpha2.NewError(code, message, details)
if err := json.NewEncoder(w).Encode(errorResponse); err != nil {
// Fallback to plain text if JSON encoding fails
http.Error(w, message, statusCode)
}
}

func NewAuthMiddleware(
jwtService *JWTService,
cookieSigningKey, cookieEncryptionKey []byte,
kubernetesManager *kubernetes.Manager,
sessionStore session.Store,
) *AuthMiddleware {
return &AuthMiddleware{
jwtService: jwtService,
cookieSigningKey: cookieSigningKey,
cookieEncryptionKey: cookieEncryptionKey,
kubernetesManager: kubernetesManager,
sessionStore: sessionStore,
}
}

func (am *AuthMiddleware) AuthenticateRequest(next http.Handler) http.Handler {
return am.authenticate(
am.verifyState(
next,
),
)
}

func (am *AuthMiddleware) authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger := klog.FromContext(r.Context())

Expand All @@ -84,7 +116,6 @@ func (am *AuthMiddleware) AuthenticateRequest(next http.Handler) http.Handler {
ClusterID: claims.ClusterID,
RedirectURL: claims.RedirectURL,
}
authCtx.IsValid = true
authCtx.ClientType = ClientTypeCLI
} else {
logger.V(2).Info("Invalid JWT token", "error", err)
Expand All @@ -93,20 +124,21 @@ func (am *AuthMiddleware) AuthenticateRequest(next http.Handler) http.Handler {
}

// Fall back to cookie authentication (for UI clients)
if !authCtx.IsValid {
if authCtx.SessionState == nil {
cookieName := "kube-bind"
if r.URL.Query().Get("cluster_id") != "" {
cookieName = "kube-bind-" + r.URL.Query().Get("cluster_id")
}
if cookie, err := r.Cookie(cookieName); err == nil {
s := securecookie.New(am.cookieSigningKey, am.cookieEncryptionKey)
state := &session.State{}
if err := s.Decode(cookieName, cookie.Value, state); err == nil {
err := s.Decode(cookieName, cookie.Value, state)
if err != nil {
logger.V(2).Info("Failed to decode session cookie", "error", err)
} else {
// Only set as valid after all checks pass
authCtx.SessionState = state
authCtx.IsValid = true
authCtx.ClientType = ClientTypeUI
} else {
logger.V(2).Info("Failed to decode session cookie", "error", err)
}
Comment thread
cnvergence marked this conversation as resolved.
Resolved
}
}
Expand All @@ -117,6 +149,48 @@ func (am *AuthMiddleware) AuthenticateRequest(next http.Handler) http.Handler {
})
}

func (am *AuthMiddleware) verifyState(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger := klog.FromContext(r.Context())

authCtx := GetAuthContext(r.Context())
if authCtx.SessionState == nil {
logger.V(2).Info("No session state found in auth context")
writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "No valid session found")
return
}

state := authCtx.SessionState
// Validate session fields are present
if state.Token.Subject == "" || state.Token.Issuer == "" || state.SessionID == "" {
logger.V(2).Info("Invalid session state: missing required fields")
writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Invalid session state: missing required fields")
return
}

if state.IsExpired() || !am.isValidSession(state.SessionID) {
logger.V(2).Info("Session expired or invalid", "sessionID", state.SessionID)
writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Session has expired or is invalid")
return
}

// Session is valid
authCtx.IsValid = true

ctx := context.WithValue(r.Context(), AuthContextKey, authCtx)
next.ServeHTTP(w, r.WithContext(ctx))
})
}

// isValidSession checks if a session ID exists and hasn't expired
func (am *AuthMiddleware) isValidSession(sessionID string) bool {
sessionInfo, err := am.sessionStore.Load(sessionID)
if err != nil {
return false
}
return time.Now().Before(sessionInfo.ExpiresAt)
Comment thread
gman0 marked this conversation as resolved.
Resolved
}

func GetAuthContext(ctx context.Context) *AuthContext {
if authCtx, ok := ctx.Value(AuthContextKey).(*AuthContext); ok {
return authCtx
Expand All @@ -129,14 +203,9 @@ func RequireAuth(next http.Handler) http.Handler {
authCtx := GetAuthContext(r.Context())
if !authCtx.IsValid {
if authCtx.ClientType == ClientTypeCLI {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
err := json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized", "message": "Valid JWT token required"})
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
}
writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Valid JWT token required")
} else {
http.Error(w, "unauthorized", http.StatusUnauthorized)
writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Valid authentication credentials required")
}
return
}
Expand Down
Loading
Loading