-
Notifications
You must be signed in to change notification settings - Fork 46
Feat: SPIFFE authentication for operator client registration (Admin API) #349
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7e991ed
feat: Add JWT-SVID authentication method to Keycloak Admin client
Alan-Cha 1826877
feat: Integrate SPIFFE authentication into ClientRegistrationReconciler
Alan-Cha 23c4e9c
fix: address security review comments in SPIFFE authentication
Alan-Cha 0b958e7
feat: add operator-spiffe-helper-config Helm template
Alan-Cha 618780f
fix(charts): use correct helper names in configmap-spiffe-helper.yaml
Alan-Cha 1c43e7a
fix(operator): wire use-spiffe-auth flags into main.go
Alan-Cha 2b83ee3
fix(charts): correct cmd_args separator in spiffe-helper config
Alan-Cha 8f021d0
fix(charts): fix JWT-SVID file permissions for manager access
Alan-Cha File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
24 changes: 24 additions & 0 deletions
24
charts/kagenti-operator/templates/manager/configmap-spiffe-helper.yaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| {{- if and .Values.spiffe .Values.spiffe.enabled .Values.spiffe.operatorAuth .Values.spiffe.operatorAuth.enabled }} | ||
| --- | ||
| apiVersion: v1 | ||
| kind: ConfigMap | ||
| metadata: | ||
| name: operator-spiffe-helper-config | ||
| namespace: {{ .Release.Namespace }} | ||
| labels: | ||
| {{- include "chart.labels" . | nindent 4 }} | ||
| data: | ||
| config.hcl: | | ||
| agent_address = "/spiffe-workload-api/spire-agent.sock" | ||
| # cmd/cmd_args fire on X.509 SVID renewals only, not JWT SVIDs. | ||
| # File permissions are handled by running spiffe-helper as the same UID | ||
| # as the manager container (65532) so it can read the 600-mode file. | ||
| renew_signal = "" | ||
| cert_dir = "" | ||
| svid_file_name = "" | ||
| svid_bundle_file_name = "" | ||
| jwt_svids = [{ | ||
| jwt_audience = "{{ .Values.spiffe.operatorAuth.jwtAudience | default (printf "%s/realms/%s" .Values.keycloak.publicUrl .Values.keycloak.realm) }}" | ||
| jwt_svid_file_name = "/opt/jwt_svid.token" | ||
| }] | ||
| {{- end }} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,8 @@ package controller | |
| import ( | ||
| "context" | ||
| "fmt" | ||
| "os" | ||
| "path/filepath" | ||
| "strings" | ||
| "time" | ||
|
|
||
|
|
@@ -20,6 +22,7 @@ import ( | |
| "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" | ||
| "k8s.io/apimachinery/pkg/runtime" | ||
| "k8s.io/apimachinery/pkg/types" | ||
| "k8s.io/client-go/tools/record" | ||
| "k8s.io/client-go/util/retry" | ||
| ctrl "sigs.k8s.io/controller-runtime" | ||
| "sigs.k8s.io/controller-runtime/pkg/builder" | ||
|
|
@@ -72,7 +75,24 @@ type ClientRegistrationReconciler struct { | |
| SpireTrustDomain string | ||
| // KeycloakAdminTokenCache caches admin password-grant tokens by Keycloak URL and credentials to | ||
| // avoid a token request on every reconcile. If nil, PasswordGrantToken is used without caching. | ||
| // Only used when UseSpiffeAuth is false. | ||
| KeycloakAdminTokenCache *keycloak.CachedAdminTokenProvider | ||
|
|
||
| // UseSpiffeAuth enables JWT-SVID authentication instead of admin credentials. | ||
| // When true, the operator authenticates to Keycloak with its JWT-SVID and uses | ||
| // the Admin API with manage-clients role. When false, uses admin credentials. | ||
| UseSpiffeAuth bool | ||
|
|
||
| // JWTSVIDPath is the file path to read the operator's JWT-SVID from. | ||
| // Only used when UseSpiffeAuth is true. Default: /opt/jwt_svid.token | ||
| JWTSVIDPath string | ||
|
|
||
| // OperatorClientID is the operator's SPIFFE ID (e.g., spiffe://localtest.me/ns/kagenti-operator-system/sa/...). | ||
| // Only used when UseSpiffeAuth is true. | ||
| OperatorClientID string | ||
|
|
||
| // Recorder emits Kubernetes Events to surface configuration issues visible in kubectl describe. | ||
| Recorder record.EventRecorder | ||
| } | ||
|
|
||
| func (r *ClientRegistrationReconciler) uncachedReader() client.Reader { | ||
|
|
@@ -228,19 +248,6 @@ func (r *ClientRegistrationReconciler) reconcileOne( | |
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| } | ||
|
|
||
| adminUser, adminPass, err := r.resolveKeycloakAdminCredentials(ctx) | ||
| if err != nil { | ||
| if apierrors.IsNotFound(err) { | ||
| logger.Info("waiting for Keycloak admin secret") | ||
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| } | ||
| return ctrl.Result{}, err | ||
| } | ||
| if adminUser == "" || adminPass == "" { | ||
| logger.Info("Keycloak admin secret missing credentials") | ||
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| } | ||
|
|
||
| spireEnabled := strings.EqualFold(strings.TrimSpace(ab.SpireEnabled), "true") | ||
| clientName := ns + "/" + workloadName | ||
| clientID, err := resolveKeycloakClientID(ns, workloadName, template.Spec.ServiceAccountName, spireEnabled, r.SpireTrustDomain) | ||
|
|
@@ -258,14 +265,84 @@ func (r *ClientRegistrationReconciler) reconcileOne( | |
|
|
||
| kc := keycloak.Admin{BaseURL: ab.KeycloakURL, HTTPClient: keycloak.DefaultHTTPClient()} | ||
| var token string | ||
| if r.KeycloakAdminTokenCache != nil { | ||
| token, err = r.KeycloakAdminTokenCache.Token(ctx, &kc, adminUser, adminPass) | ||
|
|
||
| // Authenticate to Keycloak: use JWT-SVID if enabled, otherwise admin credentials | ||
| if r.UseSpiffeAuth { | ||
| // SPIFFE authentication path | ||
| // Validate OperatorClientID before file I/O to fail fast on misconfiguration | ||
| if r.OperatorClientID == "" { | ||
| err := fmt.Errorf("OperatorClientID not configured") | ||
| logger.Error(err, "SPIFFE auth requires OperatorClientID") | ||
| if r.Recorder != nil { | ||
| r.Recorder.Event(owner, corev1.EventTypeWarning, "OperatorClientIDMissing", | ||
| "UseSpiffeAuth=true but OperatorClientID is empty. Check operator configuration.") | ||
| } | ||
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| } | ||
|
|
||
| jwtSVIDPath := r.JWTSVIDPath | ||
| if jwtSVIDPath == "" { | ||
| jwtSVIDPath = "/opt/jwt_svid.token" | ||
| } | ||
|
|
||
| // Path traversal protection: only allow reading from designated directories | ||
| cleanPath := filepath.Clean(jwtSVIDPath) | ||
| if !strings.HasPrefix(cleanPath, "/opt/") && !strings.HasPrefix(cleanPath, "/var/run/secrets/") { | ||
| err := fmt.Errorf("JWT-SVID path %q outside allowed directories (/opt/, /var/run/secrets/)", jwtSVIDPath) | ||
| logger.Error(err, "invalid JWT-SVID path") | ||
| if r.Recorder != nil { | ||
| r.Recorder.Eventf(owner, corev1.EventTypeWarning, "InvalidJWTSVIDPath", | ||
| "JWT-SVID path %q rejected: must be under /opt/ or /var/run/secrets/", jwtSVIDPath) | ||
| } | ||
| return ctrl.Result{}, err // fail permanently on config error | ||
| } | ||
|
|
||
| jwtSVID, err := os.ReadFile(cleanPath) | ||
| if err != nil { | ||
| logger.Error(err, "read JWT-SVID failed", "path", cleanPath) | ||
| if r.Recorder != nil { | ||
| r.Recorder.Eventf(owner, corev1.EventTypeWarning, "JWTSVIDReadFailed", | ||
| "Failed to read JWT-SVID from %s: %v. Check spiffe-helper sidecar configuration.", cleanPath, err) | ||
| } | ||
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| } | ||
|
|
||
| // WARNING: JWT-SVID is a bearer token - must never appear in logs or error messages | ||
| // to prevent token exposure. All code paths must handle jwtSVID as sensitive data. | ||
| token, err = kc.JWTSVIDGrantToken(ctx, ab.KeycloakRealm, r.OperatorClientID, string(jwtSVID)) | ||
|
Alan-Cha marked this conversation as resolved.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [SUGGESTION] Add basic JWT format validation Validate the JWT-SVID has the expected structure before sending to Keycloak. This provides faster feedback for malformed tokens. Fix: import "bytes"
// Basic JWT format check (header.payload.signature)
if bytes.Count(jwtSVID, []byte{'.'}) != 2 {
logger.Error(nil, "invalid JWT-SVID format", "path", jwtSVIDPath)
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
} |
||
| if err != nil { | ||
| logger.Error(err, "Keycloak JWT-SVID authentication failed") | ||
| if r.Recorder != nil { | ||
| r.Recorder.Event(owner, corev1.EventTypeWarning, "KeycloakAuthFailed", | ||
| "Failed to authenticate to Keycloak with JWT-SVID. Check SPIFFE IdP configuration in Keycloak.") | ||
| } | ||
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| } | ||
| logger.V(1).Info("authenticated with JWT-SVID", "clientId", r.OperatorClientID) | ||
| } else { | ||
| token, err = kc.PasswordGrantToken(ctx, adminUser, adminPass) | ||
| } | ||
| if err != nil { | ||
| logger.Error(err, "Keycloak admin token failed") | ||
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| // Admin credentials path (legacy) | ||
| adminUser, adminPass, err := r.resolveKeycloakAdminCredentials(ctx) | ||
| if err != nil { | ||
| if apierrors.IsNotFound(err) { | ||
| logger.Info("waiting for Keycloak admin secret") | ||
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| } | ||
| return ctrl.Result{}, err | ||
| } | ||
| if adminUser == "" || adminPass == "" { | ||
| logger.Info("Keycloak admin secret missing credentials") | ||
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| } | ||
| if r.KeycloakAdminTokenCache != nil { | ||
| token, err = r.KeycloakAdminTokenCache.Token(ctx, &kc, adminUser, adminPass) | ||
| } else { | ||
| token, err = kc.PasswordGrantToken(ctx, adminUser, adminPass) | ||
| } | ||
| if err != nil { | ||
| logger.Error(err, "Keycloak admin token failed") | ||
| return ctrl.Result{RequeueAfter: 30 * time.Second}, nil | ||
| } | ||
| logger.V(1).Info("authenticated with admin credentials") | ||
| } | ||
| agentClientUUID, clientSecret, err := kc.RegisterOrFetchClientWithToken(ctx, token, keycloak.ClientRegistrationParams{ | ||
| Realm: ab.KeycloakRealm, | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.