Skip to content
Closed
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
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,10 @@ update-tools: clean-tools install-golangci-lint install-gotestsum install-boiler
.PHONY: lint
lint: install-golangci-lint install-logcheck ## Run golangci-lint
@if [ -n "$(WHAT)" ]; then \
$(GOLANGCI_LINT) run $(GOLANGCI_LINT_FLAGS) -c $(ROOT_DIR)/.golangci.yaml --timeout 20m $(WHAT); \
$(GOLANGCI_LINT) run $(GOLANGCI_LINT_FLAGS) -c $(ROOT_DIR)/.golangci.yaml --timeout 20m $(WHAT) --fix; \
else \
for MOD in $(GOMODS); do \
(cd $$MOD; echo "Linting $$MOD"; $(GOLANGCI_LINT) run $(GOLANGCI_LINT_FLAGS) -c $(ROOT_DIR)/.golangci.yaml --timeout 20m); \
(cd $$MOD; echo "Linting $$MOD"; $(GOLANGCI_LINT) run $(GOLANGCI_LINT_FLAGS) -c $(ROOT_DIR)/.golangci.yaml --timeout 20m --fix); \
done; \
fi

Expand Down
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.
26 changes: 20 additions & 6 deletions backend/auth/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,16 @@ type AuthHandler struct {
jwtService *JWTService
cookieSigningKey []byte
cookieEncryptionKey []byte
sessionStore session.Store
}

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

Expand Down Expand Up @@ -87,7 +89,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 +183,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 +233,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 +292,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(time.Hour)
return s, nil
}

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

"github.com/gorilla/securecookie"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"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 +53,65 @@ type AuthContext struct {

type AuthMiddleware struct {
jwtService *JWTService
kubernetesMananger *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)
}
}

// 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()
}

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

func (am *AuthMiddleware) AuthenticateRequest(next http.Handler) http.Handler {
return am.authenticate(
am.verifyState(
am.authorizeK8S(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 +134,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,7 +142,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")
Expand All @@ -102,12 +151,12 @@ func (am *AuthMiddleware) AuthenticateRequest(next http.Handler) http.Handler {
s := securecookie.New(am.cookieSigningKey, am.cookieEncryptionKey)
state := &session.State{}
if err := s.Decode(cookieName, cookie.Value, state); err == nil {
// 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)
}
} else {
logger.V(2).Info("Failed to decode session cookie", "error", err)
}
}

Expand All @@ -117,6 +166,74 @@ 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
switch {
case 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
case state.IsExpired():
logger.V(2).Info("Session expired", "sessionID", state.SessionID)
writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Session has expired")
return
case !am.isValidSession(state.SessionID):
logger.V(2).Info("Session ID not found or expired", "sessionID", state.SessionID)
writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Session ID not found or expired")
return
default:
// 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 (am *AuthMiddleware) authorizeK8S(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.IsValid { // should not happen if AuthenticateRequest is used before
logger.V(2).Info("Authentication context is not valid")
writeErrorResponse(w, http.StatusUnauthorized, kubebindv1alpha2.ErrorCodeAuthenticationFailed, "Authentication required", "Authentication context is not valid")
return
}

// Authorize against Kubernetes RBAC
err := am.kubernetesMananger.AuthorizeRequest(r.Context(), authCtx.SessionState.Token.Subject, authCtx.SessionState.Token.Groups, authCtx.SessionState.ClusterID, r.Method, r.URL.Path)
if err != nil {
logger.V(2).Info("Kubernetes RBAC authorization failed", "error", err)
statusCode, code, details := mapErrorToCode(err)
writeErrorResponse(w, statusCode, code, "Cluster authorization failed. Missing required permissions in the cluster to access bindings.", details)
return
}

next.ServeHTTP(w, r)
})
}

func GetAuthContext(ctx context.Context) *AuthContext {
if authCtx, ok := ctx.Value(AuthContextKey).(*AuthContext); ok {
return authCtx
Expand All @@ -129,14 +246,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
14 changes: 7 additions & 7 deletions backend/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import (
"net/url"
"strings"

apisv1alpha1 "github.com/kcp-dev/kcp/sdk/apis/apis/v1alpha1"
apisv1alpha2 "github.com/kcp-dev/kcp/sdk/apis/apis/v1alpha2"
"github.com/kcp-dev/multicluster-provider/apiexport"
apisv1alpha1 "github.com/kcp-dev/sdk/apis/apis/v1alpha1"
apisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
Expand All @@ -39,6 +39,7 @@ import (

kuberesources "github.com/kube-bind/kube-bind/backend/kubernetes/resources"
"github.com/kube-bind/kube-bind/backend/options"
kcpprovider "github.com/kube-bind/kube-bind/backend/provider/kcp"
kubebindv1alpha1 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha1"
kubebindv1alpha2 "github.com/kube-bind/kube-bind/sdk/apis/kubebind/v1alpha2"
)
Expand Down Expand Up @@ -70,10 +71,6 @@ func NewConfig(options *options.CompletedOptions) (*Config, error) {
config.ClientConfig = rest.CopyConfig(config.ClientConfig)
config.ClientConfig = rest.AddUserAgent(config.ClientConfig, "kube-bind-backend")

if options.ServerURL != "" {
config.ClientConfig.Host = options.ServerURL
}

// Set up controller-runtime manager
scheme := runtime.NewScheme()
if err := clientgoscheme.AddToScheme(scheme); err != nil {
Expand All @@ -93,13 +90,16 @@ func NewConfig(options *options.CompletedOptions) (*Config, error) {

switch options.Provider {
case "kcp":
if options.ProviderKcp == nil {
return nil, fmt.Errorf("kcp provider options must be provided when provider is kcp")
}
if err := apisv1alpha1.AddToScheme(scheme); err != nil {
return nil, fmt.Errorf("error adding apis scheme: %w", err)
}
if err := apisv1alpha2.AddToScheme(scheme); err != nil {
return nil, fmt.Errorf("error adding apis scheme: %w", err)
}
provider, err := apiexport.New(config.ClientConfig, apiexport.Options{
provider, err := kcpprovider.New(config.ClientConfig, options.ProviderKcp.APIExportEndpointSliceName, apiexport.Options{
Scheme: scheme,
})
if err != nil {
Expand Down
Loading