diff --git a/README.md b/README.md index 105ba4ab4..4b72fe84d 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/backend/auth/handler.go b/backend/auth/handler.go index 006654241..2eb3ecef3 100644 --- a/backend/auth/handler.go +++ b/backend/auth/handler.go @@ -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, } } @@ -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) @@ -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 @@ -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 { @@ -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) { diff --git a/backend/auth/middleware.go b/backend/auth/middleware.go index d377d8d11..c19c2fe1b 100644 --- a/backend/auth/middleware.go +++ b/backend/auth/middleware.go @@ -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 @@ -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()) @@ -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) @@ -93,7 +124,7 @@ 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") @@ -101,12 +132,13 @@ func (am *AuthMiddleware) AuthenticateRequest(next http.Handler) http.Handler { 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) } } } @@ -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) +} + func GetAuthContext(ctx context.Context) *AuthContext { if authCtx, ok := ctx.Value(AuthContextKey).(*AuthContext); ok { return authCtx @@ -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 } diff --git a/backend/http/handler.go b/backend/http/handler.go index cd696e46e..95d87f0af 100644 --- a/backend/http/handler.go +++ b/backend/http/handler.go @@ -26,6 +26,7 @@ import ( "time" "github.com/gorilla/mux" + apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" componentbaseversion "k8s.io/component-base/version" @@ -35,6 +36,7 @@ import ( "github.com/kube-bind/kube-bind/backend/client" "github.com/kube-bind/kube-bind/backend/kubernetes" "github.com/kube-bind/kube-bind/backend/oidc" + "github.com/kube-bind/kube-bind/backend/session" "github.com/kube-bind/kube-bind/backend/spaserver" bindversion "github.com/kube-bind/kube-bind/pkg/version" kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" @@ -48,6 +50,36 @@ var noCacheHeaders = map[string]string{ "X-Accel-Expires": "0", // https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/ } +// 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) + } +} + +// mapErrorToCode maps common errors to structured error codes +func mapErrorToCode(err error) (statusCode int, code string, details string) { + if apierrors.IsNotFound(err) { + return http.StatusNotFound, kubebindv1alpha2.ErrorCodeResourceNotFound, err.Error() + } + if apierrors.IsUnauthorized(err) { + return http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, err.Error() + } + if apierrors.IsForbidden(err) { + return http.StatusForbidden, kubebindv1alpha2.ErrorCodeAuthorizationFailed, err.Error() + } + if apierrors.IsBadRequest(err) { + return http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, err.Error() + } + // Default to internal server error + return http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, err.Error() +} + type handler struct { oidcProvider auth.OIDCProvider authHandler auth.AuthHandlerInterface @@ -79,6 +111,7 @@ func NewHandler( scope kubebindv1alpha2.InformerScope, mgr *kubernetes.Manager, frontend string, + tokenExpiry time.Duration, ) (*handler, error) { // Create JWT service for CLI authentication jwtService, err := auth.NewJWTService("kube-bind-backend") @@ -86,11 +119,13 @@ func NewHandler( return nil, fmt.Errorf("failed to create JWT service: %w", err) } - // Create auth handler with OIDC provider - authHandler := auth.NewAuthHandler(oidcProvider, jwtService, cookieSigningKey, cookieEncryptionKey) + sessionStore := session.NewInMemoryStore() // Create auth middleware for request authentication - authMiddleware := auth.NewAuthMiddleware(jwtService, cookieSigningKey, cookieEncryptionKey) + authMiddleware := auth.NewAuthMiddleware(jwtService, cookieSigningKey, cookieEncryptionKey, mgr, sessionStore) + + // Create auth handler with OIDC provider + authHandler := auth.NewAuthHandler(oidcProvider, jwtService, cookieSigningKey, cookieEncryptionKey, sessionStore, tokenExpiry) return &handler{ oidcProvider: oidcProvider, @@ -239,7 +274,7 @@ func (h *handler) handleServiceExport(w http.ResponseWriter, r *http.Request) { bs, err := json.Marshal(provider) if err != nil { logger.Error(err, "failed to marshal provider") - http.Error(w, err.Error(), http.StatusInternalServerError) + writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal provider information", err.Error()) return } @@ -252,13 +287,20 @@ func (h *handler) handleTemplates(w http.ResponseWriter, r *http.Request) { prepareNoCache(w) logger.Info("getting templates") + authenticated := auth.GetAuthContext(r.Context()).IsValid + if !authenticated { + logger.Info("unauthenticated request to get templates") + writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Valid authentication credentials are required to access templates") + return + } + params := client.GetQueryParams(r) templates, err := h.listTemplates(r.Context(), params.ClusterID) if err != nil { logger.Error(err, "failed to get template resources") - http.Error(w, "internal error", http.StatusInternalServerError) - + statusCode, code, details := mapErrorToCode(err) + writeErrorResponse(w, statusCode, code, "Failed to retrieve templates", details) return } @@ -266,7 +308,7 @@ func (h *handler) handleTemplates(w http.ResponseWriter, r *http.Request) { // For UI, return direct result as before if err := json.NewEncoder(w).Encode(templates); err != nil { logger.Error(err, "failed to encode JSON response") - http.Error(w, "internal error", http.StatusInternalServerError) + writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to encode response", err.Error()) } } @@ -280,7 +322,8 @@ func (h *handler) handleCollections(w http.ResponseWriter, r *http.Request) { collections, err := h.listCollections(r.Context(), params.ClusterID) if err != nil { logger.Error(err, "failed to get collection resources") - http.Error(w, "internal error", http.StatusInternalServerError) + statusCode, code, details := mapErrorToCode(err) + writeErrorResponse(w, statusCode, code, "Failed to retrieve collections", details) return } @@ -288,7 +331,7 @@ func (h *handler) handleCollections(w http.ResponseWriter, r *http.Request) { // For UI, return direct result as before if err := json.NewEncoder(w).Encode(collections); err != nil { logger.Error(err, "failed to encode JSON response") - http.Error(w, "internal error", http.StatusInternalServerError) + writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to encode response", err.Error()) } } @@ -305,7 +348,8 @@ func (h *handler) handleBind(w http.ResponseWriter, r *http.Request) { kfg, err := h.kubeManager.HandleResources(r.Context(), state.Token.Subject+"#"+state.ClusterID, params.ClusterID) if err != nil { logger.Error(err, "failed to handle resources") - http.Error(w, "internal error", http.StatusInternalServerError) + statusCode, code, details := mapErrorToCode(err) + writeErrorResponse(w, statusCode, code, "Failed to handle cluster resources", details) return } @@ -317,9 +361,9 @@ func (h *handler) handleBind(w http.ResponseWriter, r *http.Request) { logger.Error(err, "failed to parse JSON request body") var maxBytesError *http.MaxBytesError if errors.As(err, &maxBytesError) { - http.Error(w, "request body too large", http.StatusRequestEntityTooLarge) + writeErrorResponse(w, http.StatusRequestEntityTooLarge, kubebindv1alpha2.ErrorCodeBadRequest, "Request body too large", "The request body exceeds the maximum allowed size") } else { - http.Error(w, "invalid JSON request body", http.StatusBadRequest) + writeErrorResponse(w, http.StatusBadRequest, kubebindv1alpha2.ErrorCodeBadRequest, "Invalid JSON request body", err.Error()) } return } @@ -328,7 +372,8 @@ func (h *handler) handleBind(w http.ResponseWriter, r *http.Request) { template, err := h.kubeManager.GetTemplates(r.Context(), params.ClusterID, bindRequest.TemplateRef.Name) if err != nil { logger.Error(err, "failed to get template", "template", bindRequest.TemplateRef.Name, "cluster", params.ClusterID) - http.Error(w, "internal error", http.StatusInternalServerError) + statusCode, code, details := mapErrorToCode(err) + writeErrorResponse(w, statusCode, code, "Failed to retrieve template", details) return } @@ -351,7 +396,7 @@ func (h *handler) handleBind(w http.ResponseWriter, r *http.Request) { requestBytes, err := json.Marshal(&request) if err != nil { logger.Error(err, "failed to marshal request") - http.Error(w, "internal error", http.StatusInternalServerError) + writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal request", err.Error()) return } @@ -373,7 +418,7 @@ func (h *handler) handleBind(w http.ResponseWriter, r *http.Request) { payload, err := json.Marshal(&response) if err != nil { logger.Error(err, "failed to marshal binding response") - http.Error(w, "internal error", http.StatusInternalServerError) + writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal binding response", err.Error()) return } @@ -408,7 +453,7 @@ func (h *handler) handleBindableResources(w http.ResponseWriter, r *http.Request bs, err := json.Marshal(&kubebindv1alpha2.ClaimableAPIs) if err != nil { logger.Error(err, "failed to marshal resources") - http.Error(w, "internal error", http.StatusInternalServerError) + writeErrorResponse(w, http.StatusInternalServerError, kubebindv1alpha2.ErrorCodeInternalError, "Failed to marshal bindable resources", err.Error()) return } diff --git a/backend/oidc/oidc.go b/backend/oidc/oidc.go index a617b6047..568042545 100644 --- a/backend/oidc/oidc.go +++ b/backend/oidc/oidc.go @@ -47,15 +47,28 @@ func New(caBundleFile string, listener net.Listener, addrOverride string) (*Serv s.tlsConfig = tlsConfig } + staticUserProvider := NewStaticUserProvider() + staticUserProvider.Set(&mockoidc.MockUser{ + Subject: "kube-bind-embedded-user", + Email: "embedded@kube-bind.io", + PreferredUsername: "kube-bind", + Phone: "+1234567890", + Address: "123 Kube St, Bind City, KB 12345", + Groups: []string{"engineering", "devops"}, + EmailVerified: true, + }) + server, err := mockoidc.NewServer(&mockoidc.ServerConfig{ TLSConfig: tlsConfig, Listener: listener, AddrOverride: addrOverride, + UserProvider: staticUserProvider, }) if err != nil { return nil, fmt.Errorf("failed to create mock OIDC server: %w", err) } s.server = server + return s, nil } diff --git a/backend/oidc/user.go b/backend/oidc/user.go new file mode 100644 index 000000000..f60c47c62 --- /dev/null +++ b/backend/oidc/user.go @@ -0,0 +1,39 @@ +/* +Copyright 2025 The Kube Bind Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package oidc + +import "github.com/xrstf/mockoidc" + +var _ mockoidc.UserProvider = (*staticUserProvider)(nil) + +type staticUserProvider struct { + user mockoidc.User +} + +func (s *staticUserProvider) Get() mockoidc.User { + return s.user +} + +func (s *staticUserProvider) Set(user mockoidc.User) { + s.user = user +} + +func NewStaticUserProvider() *staticUserProvider { + return &staticUserProvider{ + user: &mockoidc.MockUser{}, + } +} diff --git a/backend/options/oidc.go b/backend/options/oidc.go index 5e3bc8c61..214360ec3 100644 --- a/backend/options/oidc.go +++ b/backend/options/oidc.go @@ -24,13 +24,7 @@ import ( "github.com/spf13/pflag" "github.com/kube-bind/kube-bind/backend/oidc" -) - -type OIDCType string - -const ( - OIDCTypeEmbedded OIDCType = "embedded" - OIDCTypeExternal OIDCType = "external" + kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2" ) type OIDC struct { @@ -49,7 +43,7 @@ type OIDC struct { func NewOIDC() *OIDC { return &OIDC{ - Type: string(OIDCTypeExternal), + Type: string(kubebindv1alpha2.OIDCProviderTypeExternal), } } @@ -64,7 +58,7 @@ func (options *OIDC) AddFlags(fs *pflag.FlagSet) { } func (options *OIDC) Complete(listener net.Listener) error { - if options.Type == string(OIDCTypeEmbedded) { + if options.Type == string(kubebindv1alpha2.OIDCProviderTypeEmbedded) { oidcServer, err := oidc.New(options.CAFile, listener, options.IssuerURL) if err != nil { return err @@ -111,5 +105,9 @@ func (options *OIDC) Validate() error { return fmt.Errorf("cannot use both CA file and embedded OIDC server") } + if options.Type != string(kubebindv1alpha2.OIDCProviderTypeEmbedded) && options.Type != string(kubebindv1alpha2.OIDCProviderTypeExternal) { + return fmt.Errorf("invalid OIDC provider type: %s", options.Type) + } + return nil } diff --git a/backend/options/options.go b/backend/options/options.go index 18ba5bbc6..0f1b1b216 100644 --- a/backend/options/options.go +++ b/backend/options/options.go @@ -21,6 +21,7 @@ import ( "net/url" "os" "strings" + "time" "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/sets" @@ -67,6 +68,8 @@ type ExtraOptions struct { // If ControllerFrontend starts with http:// it is treated as a URL to a SPA server // Else - it is treated as a path to static files to be served. Frontend string + + TokenExpiry time.Duration } type completedOptions struct { @@ -105,6 +108,7 @@ func NewOptions() *Options { ClusterScopedIsolation: string(kubebindv1alpha2.IsolationPrefixed), SchemaSource: CustomResourceDefinitionSource.String(), Frontend: "embedded", // Not used, but indicates to use embedded frontend using SPA. + TokenExpiry: 1 * time.Hour, }, } return opts @@ -152,6 +156,7 @@ func (options *Options) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&options.ExternalCAFile, "external-ca-file", options.ExternalCAFile, "The external CA file for the service provider cluster. If not specified, service account's CA is used.") fs.StringVar(&options.TLSExternalServerName, "external-server-name", options.TLSExternalServerName, "The external (TLS) server name used by consumers to talk to the service provider cluster. This can be useful to select the right certificate via SNI.") fs.StringVar(&options.Frontend, "frontend", options.Frontend, "If starts with http:// it is treated as a URL to a SPA server Else - it is treated as a path to static files to be served.") + fs.DurationVar(&options.TokenExpiry, "token-expiry", options.TokenExpiry, "The duration for which tokens are valid. Default is 1h.") fs.StringVar(&options.Provider, "multicluster-runtime-provider", options.Provider, fmt.Sprintf("The multicluster runtime provider. Possible values are: %v", sets.List(sets.Set[string](sets.StringKeySet(providerAliases)))), diff --git a/backend/server.go b/backend/server.go index d17e985f4..10e314ace 100644 --- a/backend/server.go +++ b/backend/server.go @@ -127,6 +127,7 @@ func NewServer(ctx context.Context, c *Config) (*Server, error) { kubebindv1alpha2.InformerScope(c.Options.ConsumerScope), s.Kubernetes, c.Options.Frontend, + c.Options.TokenExpiry, ) if err != nil { return nil, fmt.Errorf("error setting up HTTP Handler: %w", err) diff --git a/backend/session/session.go b/backend/session/session.go index ab38cd97b..4ab0d5e38 100644 --- a/backend/session/session.go +++ b/backend/session/session.go @@ -17,6 +17,8 @@ limitations under the License. package session import ( + "time" + "github.com/vmihailenco/msgpack/v4" ) @@ -31,13 +33,27 @@ type State struct { SessionID string `msgpack:"sid,omitempty"` ClusterID string `msgpack:"cid,omitempty"` RedirectURL string `msgpack:"red,omitempty"` + CreatedAt time.Time `msgpack:"cat,omitempty"` + ExpiresAt time.Time `msgpack:"eat,omitempty"` } type TokenInfo struct { - Subject string `msgpack:"sub,omitempty"` - Issuer string `msgpack:"iss,omitempty"` + Subject string `msgpack:"sub,omitempty"` + Issuer string `msgpack:"iss,omitempty"` + Groups []string `msgpack:"grp,omitempty"` } func (s *State) Encode() ([]byte, error) { return msgpack.Marshal(s) } + +// IsExpired checks if the session has expired +func (s *State) IsExpired() bool { + return s.ExpiresAt.IsZero() || time.Now().After(s.ExpiresAt) +} + +// SetExpiration sets the session expiration time +func (s *State) SetExpiration(duration time.Duration) { + s.CreatedAt = time.Now() + s.ExpiresAt = s.CreatedAt.Add(duration) +} diff --git a/backend/session/store.go b/backend/session/store.go new file mode 100644 index 000000000..0a36cd046 --- /dev/null +++ b/backend/session/store.go @@ -0,0 +1,65 @@ +/* +Copyright 2025 The Kube Bind Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package session + +import ( + "fmt" + "sync" +) + +var ErrSessionNotFound = fmt.Errorf("session not found") + +type Store interface { + Save(state *State) error + Load(sessionID string) (*State, error) + Delete(sessionID string) error +} + +type InMemoryStore struct { + lock sync.RWMutex + sessions map[string]*State +} + +func NewInMemoryStore() *InMemoryStore { + return &InMemoryStore{ + sessions: make(map[string]*State), + } +} + +func (s *InMemoryStore) Save(state *State) error { + s.lock.Lock() + defer s.lock.Unlock() + s.sessions[state.SessionID] = state + return nil +} + +func (s *InMemoryStore) Load(sessionID string) (*State, error) { + s.lock.RLock() + defer s.lock.RUnlock() + state, exists := s.sessions[sessionID] + if !exists { + return nil, ErrSessionNotFound + } + return state, nil +} + +func (s *InMemoryStore) Delete(sessionID string) error { + s.lock.Lock() + defer s.lock.Unlock() + delete(s.sessions, sessionID) + return nil +} diff --git a/contrib/kcp/go.mod b/contrib/kcp/go.mod index 63ae41525..cbf49ae18 100644 --- a/contrib/kcp/go.mod +++ b/contrib/kcp/go.mod @@ -86,7 +86,6 @@ require ( github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/kcp-dev/apimachinery/v2 v2.29.1-0.20251209121225-cf3c0b624983 // indirect - github.com/kcp-dev/kcp/pkg/apis v0.11.0 // indirect github.com/kcp-dev/multicluster-provider v0.3.3 // indirect github.com/kube-bind/kube-bind/web v0.0.0-00010101000000-000000000000 // indirect github.com/kylelemons/godebug v1.1.0 // indirect diff --git a/contrib/kcp/go.sum b/contrib/kcp/go.sum index ea880cc40..1f54343b2 100644 --- a/contrib/kcp/go.sum +++ b/contrib/kcp/go.sum @@ -128,8 +128,6 @@ github.com/kcp-dev/client-go v0.0.0-20251211053925-0c25555f33dd h1:jFb6BJ1msx8hy github.com/kcp-dev/client-go v0.0.0-20251211053925-0c25555f33dd/go.mod h1:SWYbL1dVmUvLQ8DpcQq+tIH14R1i5e4wh1NTW4YaUYc= github.com/kcp-dev/kcp v0.0.0-20251211081525-180afa9d0125 h1:nu7sZ9EXtA94cyZ82iLE/30AgWIwhoat3uT+Dyikagc= github.com/kcp-dev/kcp v0.0.0-20251211081525-180afa9d0125/go.mod h1:wltrdBFiWiEu+IpM94pe8zl/Ubq4re5ENbEpjbfYfJI= -github.com/kcp-dev/kcp/pkg/apis v0.11.0 h1:K6p+tNHNcvfACCPLcHgY0EMLeaIwR1jS491FyLfXMII= -github.com/kcp-dev/kcp/pkg/apis v0.11.0/go.mod h1:8cUAmfMJcksauz53UtsLYG8Phhx62rvuCnd/5t/Zihk= github.com/kcp-dev/kubernetes/staging/src/k8s.io/api v0.0.0-20251209073509-71e0f2506325 h1:xjt3y1Uw+x1LQbtBesGohvyoQ2YRzz4c0rv3BwG0vkA= github.com/kcp-dev/kubernetes/staging/src/k8s.io/api v0.0.0-20251209073509-71e0f2506325/go.mod h1:3Y5V97lz2MrKYzHlUaXejkj+coCmqde9E9WwVFuWRXE= github.com/kcp-dev/kubernetes/staging/src/k8s.io/apiextensions-apiserver v0.0.0-20251209073509-71e0f2506325 h1:MmzvuhedtyTW49qG0VWf9X54OwaRslUk6KyC7vhsuI4= diff --git a/docs/content/developers/backend/index.md b/docs/content/developers/backend/index.md index 5542288d9..06e3dced6 100644 --- a/docs/content/developers/backend/index.md +++ b/docs/content/developers/backend/index.md @@ -24,7 +24,7 @@ The backend can be configured to use different providers: ```bash ./bin/backend \ --multicluster-runtime-provider kcp \ - --server-url=$(kubectl get apiexportendpointslice kube-bind.io -o jsonpath="{.status.endpoints[0].url}") \ + --apiexport-endpointslice-name=kube-bind.io \ # ... other options ``` @@ -63,3 +63,17 @@ The backend includes several controllers for managing the export/binding lifecyc - **ServiceExport Controller**: Handles APIServiceExport resources - **ServiceExportRequest Controller**: Processes export requests - **ServiceNamespace Controller**: Manages namespace isolation + +## Deployment Limitations + +### Session Storage + +The backend currently uses in-memory session storage for OIDC authentication sessions. This creates the following limitation: + +- **Single Replica Constraint**: The backend cannot be run with replicas > 1 due to the lack of external session storage implementation +- **Session Persistence**: Sessions are not persisted across backend restarts +- **Load Balancer Issues**: If deployed behind a load balancer with multiple replicas, users may lose their sessions when requests are routed to different backend instances + +**Workaround**: Deploy the backend as a single replica (replicas: 1) until external session storage support is implemented. + +**Future Enhancement**: Implementation of external session storage (Redis, database, etc.) would resolve this limitation and enable high availability deployments. See https://github.com/kube-bind/kube-bind/issues/424 diff --git a/docs/content/developers/dev-environments.md b/docs/content/developers/dev-environments.md index 2def8249b..a533e1022 100644 --- a/docs/content/developers/dev-environments.md +++ b/docs/content/developers/dev-environments.md @@ -53,9 +53,8 @@ All the instructions assume you have already cloned the kube-bind repository and ``` k ws use :root:kube-bind - ./bin/backend \ + go run ./cmd/backend \ --multicluster-runtime-provider kcp \ - --server-url=$(kubectl get apiexportendpointslice kube-bind.io -o jsonpath="{.status.endpoints[0].url}") \ --oidc-issuer-url=http://127.0.0.1:8080/oidc \ --oidc-callback-url=http://127.0.0.1:8080/api/callback \ --oidc-type=embedded \ @@ -64,6 +63,7 @@ All the instructions assume you have already cloned the kube-bind repository and --schema-source apiresourceschemas \ --consumer-scope=cluster ``` + optionally add `--fronend=http://localhost:3000` to point to local frontend (must be running separately). This process will keep running, so open a new terminal. diff --git a/docs/content/setup/kcp-setup.md b/docs/content/setup/kcp-setup.md index 01dc53886..eda3dfad0 100644 --- a/docs/content/setup/kcp-setup.md +++ b/docs/content/setup/kcp-setup.md @@ -44,15 +44,13 @@ kubectl apply -f deploy/examples/template-sheriffs.yaml 3. Run the backend: ``` -make build - -bin/backend \ +go run ./cmd/backend \ --oidc-issuer-url=http://127.0.0.1:8080/oidc \ --oidc-callback-url=http://127.0.0.1:8080/api/callback \ --oidc-type=embedded \ --pretty-name="BigCorp.com" \ --namespace-prefix="kube-bind-" \ - --consumer-scope=cluster + --consumer-scope=cluster --frontend http://localhost:3000 ``` This process will keep running, so open a new terminal. diff --git a/go.mod b/go.mod index 612bcd0d2..ff27f31d4 100644 --- a/go.mod +++ b/go.mod @@ -28,7 +28,6 @@ require ( github.com/gorilla/mux v1.8.1 github.com/gorilla/securecookie v1.1.1 github.com/headzoo/surf v1.0.1 - github.com/kcp-dev/kcp/pkg/apis v0.11.0 github.com/kcp-dev/multicluster-provider v0.3.3 github.com/kcp-dev/sdk v0.28.1-0.20251209130449-436a0347809b github.com/kube-bind/kube-bind/cli v0.0.0-20250515145715-d9f20e7c840d diff --git a/go.sum b/go.sum index 552947c5d..6b9780cf4 100644 --- a/go.sum +++ b/go.sum @@ -124,8 +124,6 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kcp-dev/apimachinery/v2 v2.29.1-0.20251209121225-cf3c0b624983 h1:4hCauFTFMwvIhwL9fqZ5omjeZ+vsOUNO1tLsrCeprxM= github.com/kcp-dev/apimachinery/v2 v2.29.1-0.20251209121225-cf3c0b624983/go.mod h1:DOv0iw5tcgzFBhudwLFe2WHCLqtlgNkuO4AcqbZ4zVo= -github.com/kcp-dev/kcp/pkg/apis v0.11.0 h1:K6p+tNHNcvfACCPLcHgY0EMLeaIwR1jS491FyLfXMII= -github.com/kcp-dev/kcp/pkg/apis v0.11.0/go.mod h1:8cUAmfMJcksauz53UtsLYG8Phhx62rvuCnd/5t/Zihk= github.com/kcp-dev/logicalcluster/v3 v3.0.5 h1:JbYakokb+5Uinz09oTXomSUJVQsqfxEvU4RyHUYxHOU= github.com/kcp-dev/logicalcluster/v3 v3.0.5/go.mod h1:EWBUBxdr49fUB1cLMO4nOdBWmYifLbP1LfoL20KkXYY= github.com/kcp-dev/multicluster-provider v0.3.3 h1:wTu1Zbk6+kVlB/d/K9TM7KPjUEe/Dg8SYzKQsVDiDFY= diff --git a/hack/tools.checksums b/hack/tools.checksums index d13423a16..af558850b 100644 --- a/hack/tools.checksums +++ b/hack/tools.checksums @@ -1,9 +1,11 @@ golangci-lint|GOARCH=amd64;GOOS=linux|7009324a8aad93c1f84dce1c3cf61181bdd6b68e5f1b8b5d6971662258255050 +golangci-lint|GOARCH=arm64;GOOS=darwin|96dc1dbbb686fc7982b9ea4b800f3d234a2d9fb78b0344f287e8d28ee11bc72b golangci-lint|GOARCH=arm64;GOOS=linux|c51ff5b21be688b043baea44de7dd855cf07b855c14f0de405bfaf922b1d7634 goreleaser|ARCH=x86_64;OS=Linux|8de4a7d97d9b2b62e8186bcd28f7a203ba55ecfaaa4329e14264d3235095faed gotestsum|GOARCH=amd64;GOOS=linux|ee25248e6f5073cad0b7a712c97ed473adb7420f7eefad534177de0113a8a505 gotestsum|GOARCH=arm64;GOOS=linux|7a5e7f8cb5e2126be563b7c7182cc4522fbc65408a99df82d156d30e997b8705 helm|GOARCH=amd64;GOOS=linux|c153fd9c1173f39aefe8e9aa9f00fd3daf6b40c8ea01e94a0d2f2c1787fc60e0 kcp|GOARCH=amd64;GOOS=linux|41149ef78d2092243b14164a363dfdacc3e0f2bece8c00b715457c21c423a80b +kcp|GOARCH=arm64;GOOS=darwin|3ce40db499e2bc06eb383cde94be553c0b587b1c99997663bf31877be3fd45d0 kcp|GOARCH=arm64;GOOS=linux|bd2412179c1e3294dc81641630e0a2184892d4b45c6ef5bed7dc15fbd2c333fe verify_boilerplate.py||6928a807e2ffc2e6902de705ce7a7cddbbbf5ef61a43901432c4f4551b4e9a7b diff --git a/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile.go b/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile.go index c1e6856f6..f1ac084cc 100644 --- a/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile.go +++ b/pkg/konnector/controllers/cluster/serviceexport/serviceexport_reconcile.go @@ -275,6 +275,9 @@ func (r *reconciler) ensureControllerForSchema(ctx context.Context, export *kube case export.Spec.ClusterScopedIsolation == kubebindv1alpha2.IsolationNamespaced: isolationStrategy = isolation.NewNamespaced(r.providerNamespace) + default: + // Default to None isolation strategy if no valid isolation strategy is specified + isolationStrategy = isolation.NewNone(r.providerNamespace, providerNamespaceUID) } specCtrl, err := spec.NewController( diff --git a/sdk/apis/kubebind/v1alpha2/error_types.go b/sdk/apis/kubebind/v1alpha2/error_types.go new file mode 100644 index 000000000..51d498df8 --- /dev/null +++ b/sdk/apis/kubebind/v1alpha2/error_types.go @@ -0,0 +1,68 @@ +/* +Copyright 2025 The Kube Bind Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// Error represents a structured error response from the kube-bind backend +// +kubebuilder:object:root=true +type Error struct { + metav1.TypeMeta `json:",inline"` + // Message is the human-readable error message + Message string `json:"message"` + // Code is the error code that can be used for programmatic handling + Code string `json:"code"` + // Details provides additional context about the error + // +optional + Details string `json:"details,omitempty"` +} + +// Common error codes +const ( + // ErrorCodeAuthenticationFailed indicates authentication failure + ErrorCodeAuthenticationFailed = "AUTHENTICATION_FAILED" + // ErrorCodeAuthorizationFailed indicates authorization failure + ErrorCodeAuthorizationFailed = "AUTHORIZATION_FAILED" + // ErrorCodeResourceNotFound indicates a requested resource was not found + ErrorCodeResourceNotFound = "RESOURCE_NOT_FOUND" + // ErrorCodeInternalError indicates an internal server error + ErrorCodeInternalError = "INTERNAL_ERROR" + // ErrorCodeBadRequest indicates a malformed request + ErrorCodeBadRequest = "BAD_REQUEST" + // ErrorCodeClusterConnectionFailed indicates failure to connect to cluster + ErrorCodeClusterConnectionFailed = "CLUSTER_CONNECTION_FAILED" +) + +// NewError creates a new Error with the specified code, message and optional details +func NewError(code, message, details string) *Error { + return &Error{ + TypeMeta: metav1.TypeMeta{ + APIVersion: SchemeGroupVersion.String(), + Kind: "Error", + }, + Code: code, + Message: message, + Details: details, + } +} + +// Error implements the error interface +func (e *Error) Error() string { + return e.Message +} diff --git a/sdk/apis/kubebind/v1alpha2/types.go b/sdk/apis/kubebind/v1alpha2/types.go new file mode 100644 index 000000000..8ef71cbb4 --- /dev/null +++ b/sdk/apis/kubebind/v1alpha2/types.go @@ -0,0 +1,24 @@ +/* +Copyright 2025 The Kube Bind Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package v1alpha2 + +const ( + // OIDCProviderTypeEmbedded represents an embedded OIDC provider managed by kube-bind. + OIDCProviderTypeEmbedded = "embedded" + // OIDCProviderTypeExternal represents an external OIDC provider managed outside of kube-bind. + OIDCProviderTypeExternal = "external" +) diff --git a/sdk/apis/kubebind/v1alpha2/zz_generated.deepcopy.go b/sdk/apis/kubebind/v1alpha2/zz_generated.deepcopy.go index 4f96c56ee..550646334 100644 --- a/sdk/apis/kubebind/v1alpha2/zz_generated.deepcopy.go +++ b/sdk/apis/kubebind/v1alpha2/zz_generated.deepcopy.go @@ -1248,6 +1248,23 @@ func (in *CustomResourceConversion) DeepCopy() *CustomResourceConversion { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Error) DeepCopyInto(out *Error) { + *out = *in + out.TypeMeta = in.TypeMeta + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Error. +func (in *Error) DeepCopy() *Error { + if in == nil { + return nil + } + out := new(Error) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in ExportedSchemas) DeepCopyInto(out *ExportedSchemas) { { diff --git a/test/e2e/framework/backend.go b/test/e2e/framework/backend.go index a98e94ec4..89a40e7b3 100644 --- a/test/e2e/framework/backend.go +++ b/test/e2e/framework/backend.go @@ -66,7 +66,7 @@ func StartBackend(t testing.TB, args ...string) (net.Addr, *backend.Server) { require.NoError(t, err) addr := opts.Serve.Listener.Addr() - opts.OIDC.Type = string(options.OIDCTypeEmbedded) + opts.OIDC.Type = string(kubebindv1alpha2.OIDCProviderTypeEmbedded) opts.OIDC.IssuerURL = fmt.Sprintf("http://%s/oidc", addr.String()) opts.OIDC.CallbackURL = fmt.Sprintf("http://%s/api/callback", addr.String()) diff --git a/test/e2e/framework/kcp.go b/test/e2e/framework/kcp.go index f9945834c..cb06e8755 100644 --- a/test/e2e/framework/kcp.go +++ b/test/e2e/framework/kcp.go @@ -26,8 +26,8 @@ import ( "testing" "time" - corev1alpha1 "github.com/kcp-dev/kcp/pkg/apis/core/v1alpha1" - tenancyv1alpha1 "github.com/kcp-dev/kcp/pkg/apis/tenancy/v1alpha1" + corev1alpha1 "github.com/kcp-dev/sdk/apis/core/v1alpha1" + tenancyv1alpha1 "github.com/kcp-dev/sdk/apis/tenancy/v1alpha1" "github.com/martinlindhe/base36" "github.com/stretchr/testify/require" "k8s.io/apimachinery/pkg/api/errors" @@ -126,8 +126,14 @@ func NewWorkspace(t *testing.T, config *rest.Config, options ...ClusterWorkspace for _, opt := range options { opt(ws) } - err = tenancyClient.Create(ctx, ws) - require.NoError(t, err) + // retry as on startup kcp might be busy + require.Eventually(t, func() bool { + err = tenancyClient.Create(ctx, ws) + if err != nil && !errors.IsAlreadyExists(err) { + return false + } + return true + }, wait.ForeverTestTimeout, time.Millisecond*100, "failed to create workspace %s", ws.Name) ret := rest.CopyConfig(config) ret.Host += ":" + ws.Name diff --git a/web/src/App.vue b/web/src/App.vue index 50480a3a0..b062ce6ee 100644 --- a/web/src/App.vue +++ b/web/src/App.vue @@ -32,8 +32,18 @@

Authentication Required

-

Please authenticate to access resources.

- +
+
⚠️
+
+

Authentication Error

+

{{ authStatus.error }}

+
+
+

Please authenticate to access resources.

+
@@ -44,7 +54,7 @@ @@ -264,4 +291,38 @@ onMounted(() => { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4); } + +.auth-error { + display: flex; + align-items: flex-start; + gap: 1rem; + padding: 1rem 1.5rem; + margin: 1.5rem 0; + background: #fef2f2; + border: 1px solid #fecaca; + border-radius: 12px; + max-width: 500px; + text-align: left; + box-shadow: 0 2px 8px rgba(239, 68, 68, 0.1); +} + +.error-icon { + font-size: 1.5rem; + line-height: 1; + margin-top: 0.125rem; +} + +.error-content h3 { + margin: 0 0 0.5rem 0; + color: #dc2626; + font-size: 1rem; + font-weight: 600; +} + +.error-content p { + margin: 0; + color: #991b1b; + font-size: 0.875rem; + line-height: 1.5; +} \ No newline at end of file diff --git a/web/src/services/auth.ts b/web/src/services/auth.ts index 87753697a..10834c6eb 100644 --- a/web/src/services/auth.ts +++ b/web/src/services/auth.ts @@ -1,12 +1,25 @@ +import { httpClient, StructuredError } from './http' +import { ErrorCodes } from '../types/binding' + export interface AuthStatus { isAuthenticated: boolean sessionId?: string clusterId?: string } +export interface AuthCheckResult { + isAuthenticated: boolean + error?: string +} + class AuthService { async isAuthenticated(): Promise { + const result = await this.checkAuthentication() + return result.isAuthenticated + } + + async checkAuthentication(): Promise { try { // Since cookies are HTTP-only, we need to check authentication by making an API call const urlParams = new URLSearchParams(window.location.search) @@ -15,18 +28,40 @@ class AuthService { // Make a simple API call to check if we're authenticated const authCheckUrl = clusterId ? `/ping?cluster_id=${clusterId}` : '/ping' - const response = await fetch(`/api${authCheckUrl}`, { - method: 'GET', - credentials: 'include' // Include cookies - }) + const response = await httpClient.get(authCheckUrl) const isAuth = response.status === 200 console.log('Auth check:', { clusterId, status: response.status, isAuth }) - return isAuth + return { isAuthenticated: isAuth } } catch (error) { + // Handle structured errors + if (error instanceof StructuredError) { + const kubeError = error.kubeBindError + + // Return structured error message for auth/authorization failures + if (kubeError.code === ErrorCodes.AUTHENTICATION_FAILED || kubeError.code === ErrorCodes.AUTHORIZATION_FAILED) { + return { + isAuthenticated: false, + error: kubeError.message + } + } + } + + // Handle cases where we get 401/403 but don't have the expected structured error + if ((error as any)?.response?.status === 401 || (error as any)?.response?.status === 403) { + console.log('Auth check failed with authentication error but no structured response') + return { + isAuthenticated: false, + error: 'Authentication required' + } + } + console.error('Auth check error:', error) - return false + return { + isAuthenticated: false, + error: 'Authentication check failed' + } } } @@ -65,10 +100,7 @@ class AuthService { : '/api/logout' // Make POST request to logout endpoint - const response = await fetch(logoutUrl, { - method: 'POST', - credentials: 'include' // Include cookies in the request - }) + const response = await httpClient.post(logoutUrl) console.log('Logout response:', { status: response.status, clusterId }) @@ -76,6 +108,7 @@ class AuthService { window.location.href = window.location.origin + window.location.pathname } catch (error) { console.error('Logout error:', error) + // Still try to reload even if there was an error window.location.reload() } diff --git a/web/src/services/http.ts b/web/src/services/http.ts index 996cb6ea2..f61db4b9d 100644 --- a/web/src/services/http.ts +++ b/web/src/services/http.ts @@ -1,5 +1,18 @@ import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios' -import { authService } from './auth' +import { isKubeBindError, type KubeBindError, ErrorCodes } from '../types/binding' + +// Custom error class for structured errors +export class StructuredError extends Error { + public readonly kubeBindError: KubeBindError + public readonly httpStatus: number + + constructor(kubeBindError: KubeBindError, httpStatus: number) { + super(kubeBindError.message) + this.kubeBindError = kubeBindError + this.httpStatus = httpStatus + this.name = 'StructuredError' + } +} class HttpClient { private client: AxiosInstance @@ -30,15 +43,26 @@ class HttpClient { } ) - // Response interceptor to handle auth errors + // Response interceptor to handle structured errors this.client.interceptors.response.use( (response) => response, (error) => { - if (error.response?.status === 401) { - // Session expired or invalid - emit event for App.vue to handle - console.warn('Authentication expired, need to re-authenticate') - window.dispatchEvent(new CustomEvent('auth-expired')) + const status = error.response?.status + const responseData = error.response?.data + + // Check if we received a structured error from the backend + if (responseData && isKubeBindError(responseData)) { + // Handle specific error codes + if (responseData.code === ErrorCodes.AUTHENTICATION_FAILED) { + // Session expired or invalid - emit event for App.vue to handle + console.warn('Authentication expired, need to re-authenticate') + window.dispatchEvent(new CustomEvent('auth-expired')) + } + + // Throw our custom structured error + return Promise.reject(new StructuredError(responseData, status)) } + return Promise.reject(error) } ) diff --git a/web/src/types/binding.ts b/web/src/types/binding.ts index be9c675e0..f8393cfa4 100644 --- a/web/src/types/binding.ts +++ b/web/src/types/binding.ts @@ -42,4 +42,30 @@ export interface BindingResult { data?: BindingResponse message?: string error?: string +} + +// Structured error response from backend +export interface KubeBindError { + kind: 'Error' + apiVersion: string + message: string + code: string + details?: string +} + +// Common error codes from backend +export const ErrorCodes = { + AUTHENTICATION_FAILED: 'AUTHENTICATION_FAILED', + AUTHORIZATION_FAILED: 'AUTHORIZATION_FAILED', + RESOURCE_NOT_FOUND: 'RESOURCE_NOT_FOUND', + INTERNAL_ERROR: 'INTERNAL_ERROR', + BAD_REQUEST: 'BAD_REQUEST', + CLUSTER_CONNECTION_FAILED: 'CLUSTER_CONNECTION_FAILED' +} as const + +export type ErrorCode = typeof ErrorCodes[keyof typeof ErrorCodes] + +// Helper function to check if an error response is a structured KubeBindError +export function isKubeBindError(error: any): error is KubeBindError { + return error && typeof error === 'object' && error.kind === 'Error' && error.apiVersion && error.message && error.code } \ No newline at end of file diff --git a/web/src/views/Resources.vue b/web/src/views/Resources.vue index ffa5aa9ed..7bf8ad053 100644 --- a/web/src/views/Resources.vue +++ b/web/src/views/Resources.vue @@ -149,6 +149,7 @@ import { ref, computed, onMounted } from 'vue' import { useRoute } from 'vue-router' import { httpClient } from '../services/http' import type { BindableResourcesRequest, BindingResponse } from '../types/binding' +import { StructuredError } from '../services/http' import BindingResult from '../components/BindingResult.vue' import TemplateBindingModal from '../components/TemplateBindingModal.vue' import { authService } from '../services/auth' @@ -235,13 +236,37 @@ const loadResources = async () => { collections.value = collectionsResponse.data.items || [] } catch (err: any) { console.error('Failed to load resources:', err) - // Don't show generic error for auth failures - let the HTTP interceptor handle them - if (err.response?.status === 401) { - // Authentication error - the HTTP interceptor will handle logout/redirect - // Don't set error state, just let the auth flow take over - return + + // Handle structured errors + if (err instanceof StructuredError) { + const kubeError = err.kubeBindError + + // Don't show error for auth failures - let the HTTP interceptor handle them + if (kubeError.code === 'AUTHENTICATION_FAILED') { + return + } + + // Show specific error messages based on error code + switch (kubeError.code) { + case 'AUTHORIZATION_FAILED': + error.value = `Authorization failed: ${kubeError.details || kubeError.message}` + break + case 'CLUSTER_CONNECTION_FAILED': + error.value = `Could not connect to cluster: ${kubeError.details || kubeError.message}` + break + case 'RESOURCE_NOT_FOUND': + error.value = `Resources not found: ${kubeError.details || kubeError.message}` + break + default: + error.value = `Error: ${kubeError.message}` + } + } else { + // Fallback for non-structured errors + if (err.response?.status === 401) { + return + } + error.value = 'Failed to load resources. Please try again.' } - error.value = 'Failed to load resources. Please try again.' } finally { loading.value = false } @@ -298,12 +323,40 @@ const handleBind = async (templateName: string, bindingName: string) => { } } catch (err: any) { console.error('Failed to bind template:', err) - // Don't show alert for auth failures - let the HTTP interceptor handle them - if (err.response?.status === 401) { - // Authentication error - the HTTP interceptor will handle logout/redirect - return + + // Handle structured errors + if (err instanceof StructuredError) { + const kubeError = err.kubeBindError + + // Don't show alert for auth failures - let the HTTP interceptor handle them + if (kubeError.code === 'AUTHENTICATION_FAILED') { + return + } + + // Show specific error messages based on error code + let errorMessage: string + switch (kubeError.code) { + case 'AUTHORIZATION_FAILED': + errorMessage = `Authorization failed: You don't have permission to bind resources in this cluster.\n\nDetails: ${kubeError.details || kubeError.message}` + break + case 'CLUSTER_CONNECTION_FAILED': + errorMessage = `Cluster connection failed: Unable to connect to the target cluster.\n\nDetails: ${kubeError.details || kubeError.message}` + break + case 'RESOURCE_NOT_FOUND': + errorMessage = `Template not found: The requested template could not be found.\n\nDetails: ${kubeError.details || kubeError.message}` + break + default: + errorMessage = `Failed to bind template: ${kubeError.message}\n\nDetails: ${kubeError.details || 'No additional details available'}` + } + + alert(errorMessage) + } else { + // Fallback for non-structured errors + if (err.response?.status === 401) { + return + } + alert(`Failed to bind template: ${templateName}. Check console for details.`) } - alert(`Failed to bind template: ${templateName}. Check console for details.`) } }