Skip to content
This repository was archived by the owner on Nov 12, 2026. It is now read-only.

feat(operator): operator-managed Keycloak client registration - #247

Merged
pdettori merged 9 commits into
rossoctl:mainfrom
akram:feature/operator-managed-client-registration
Mar 31, 2026
Merged

pdettori merged 9 commits into
rossoctl:mainfrom
akram:feature/operator-managed-client-registration

Conversation

@akram

@akram akram commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Registers Keycloak OAuth clients for agent/tool workloads that set kagenti.io/client-registration-inject: "false", creates a Secret with client-id.txt / client-secret.txt, and annotates the pod template so the kagenti-webhook mounts credentials into shared-data.

requires:

oc patch deployment weather-service  --type merge \
   -p '{"spec": { "template": { "metadata": { "labels": {"kagenti.io/client-registration-inject": "false" }}}}}'

requires: rossoctl/cortex#262

Changes

  • ClientRegistrationReconciler for Deployment/StatefulSet; Keycloak admin client (internal/keycloak).
  • Deterministic Secret name: kagenti-keycloak-client-credentials-<hash>; annotation kagenti.io/keycloak-client-credentials-secret-name.
  • Feature flag --enable-operator-client-registration; APIReader for authbridge-config / keycloak-admin-secret; RBAC for Secrets.
  • Docs: docs/operator-managed-client-registration.md.

Related

  • Requires matching kagenti-extensions / kagenti-webhook PR (mount + reinvocation).

Testing

  • Controller unit tests; deploy operator + webhook together on a cluster with Keycloak and namespace secrets.

fixes rossoctl/rossoctl#397

@akram
akram requested a review from a team as a code owner March 27, 2026 12:39
@akram
akram force-pushed the feature/operator-managed-client-registration branch from d8863ed to 3d8c0b5 Compare March 27, 2026 12:41

@cwiklik cwiklik left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

Well-designed Keycloak client registration controller with sound architecture: Secret-before-annotation ordering, owner references for GC, feature-gated, and uncached API reads for namespace config. Thorough documentation.

Key concerns: (1) indentation bug in the StatefulSet path, (2) Made-with: Cursor trailer violates commit conventions, (3) defaulting the feature to true is aggressive for a new controller. The Keycloak client is create-only (no update path).

Areas reviewed: Go, Helm/K8s RBAC, Makefile, Docs
Commits: 3 commits, all signed-off: yes
CI status: DCO passing

Comment thread kagenti-operator/cmd/main.go Resolved
Comment thread kagenti-operator/config/rbac/role.yaml Resolved
akram added 4 commits March 27, 2026 16:45
Introduce ClientRegistrationReconciler for Deployments and StatefulSets
that use kagenti.io/client-registration-inject=false: register the workload
as an OAuth client in Keycloak, create credentials secrets, and annotate
the pod template so the webhook can mount them without injecting the
registration sidecar. Add a small Keycloak admin API client and RBAC;
gate the controller behind --enable-operator-client-registration.

Signed-off-by: Akram <[email protected]>
Describe motivation, webhook/operator contract, requirements,
rollout and rollback, and pointers to source files.

Signed-off-by: Akram <[email protected]>
- Use kagenti.io/keycloak-client-credentials-secret-name and kagenti-keycloak-client-credentials-<uniq-id> Secrets
- Rename inject/annotation helpers for Keycloak client credentials; update docs

Assisted-by: Cursor

Signed-off-by: Akram <[email protected]>
- Cache admin tokens via CachedAdminTokenProvider; wire from main when client registration is enabled.
- Default --enable-operator-client-registration to false (opt-in).
- Reconcile Keycloak client settings: GET client, PUT when desired state drifts from Keycloak.
- Add HTTPClientConfig / NewHTTPClient for TLS and custom transport (e.g. private CA).
- Document feature-gate ConfigMap iteration; fix StatefulSet branch indentation.
- Add integration-style reconciler tests and expand admin tests (drift, HTTP client).

Addresses review comments.

Assisted-by: Cursor

Signed-off-by: Akram <[email protected]>
@akram
akram force-pushed the feature/operator-managed-client-registration branch 2 times, most recently from 3d8c0b5 to 7d9d86f Compare March 27, 2026 15:46

@Alan-Cha Alan-Cha left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

This PR adds operator-managed Keycloak client registration as an alternative to sidecar-based registration. The implementation is well-designed with proper controller patterns, comprehensive tests (including envtest-style reconciler tests and mock Keycloak server), token caching, drift reconciliation, and thorough documentation.

The latest commit (7d9d86f) successfully addressed most of the previous review feedback: feature flag now defaults to false (opt-in), token caching is implemented, TLS config support added, indentation bug fixed, and test coverage expanded significantly.

One must-fix issue remains: Documentation inconsistency about the feature flag default value.

Areas reviewed: Go (controller, Keycloak admin client, tests), Makefile, RBAC, Documentation, Commit conventions

Commits: 4 commits, all DCO signed ✅

CI status: DCO passing ✅


Must-Fix Issues

Documentation default value mismatch (docs/operator-managed-client-registration.md, line ~77 in new file):

Line states the default is true, but cmd/main.go:112 sets the flag default to false. The docs should match the code:

-| Operator | `--enable-operator-client-registration` (default **true**) | Master switch for the ClientRegistration controller. |
+| Operator | `--enable-operator-client-registration` (default **false**) | Master switch for the ClientRegistration controller. |

Praise

Excellent reconciler patterns (clientregistration_controller.go):

  • ✅ CreateOrUpdate with owner references ensures proper GC
  • ✅ Secret-before-annotation ordering prevents pods from referencing missing Secrets
  • ✅ Clean reconciler structure following controller-runtime best practices

Well-implemented drift reconciliation (internal/keycloak/admin.go):

  • ✅ GET client, compare managed fields, merge desired state, PUT only when drifted
  • ✅ Properly handles Keycloak's JSON shape quirks (string arrays in attributes)

Strong test coverage (clientregistration_controller_test.go):

  • ✅ Reconciler integration tests with fake clients and mock Keycloak server
  • ✅ Covers feature gates disabled, missing dependencies (requeue), and happy path
  • ✅ Addresses previous review's testing concern

Suggestions

Token cache tuning (cmd/main.go): Token cache is instantiated with a hardcoded tokenCacheSkew. Consider exposing this as a flag if operators need to tune it for their Keycloak instance characteristics.

Commit 3 convention: Subject lacks emoji prefix: operator: Keycloak client credentials Secret naming and annotation. Should be feat(operator): or refactor(operator): per Kagenti conventions. Not blocking since commits can be squashed on merge.


Once the documentation is corrected, this PR is ready to merge. The implementation quality is high, test coverage is comprehensive, and all previous review concerns have been addressed.

akram added 2 commits March 30, 2026 10:20
…tion

Add section 3.4 explaining why manager-role uses cluster-scoped Secret rules, optional per-namespace ClusterRole pattern, and renumber webhook configuration to 3.5. Align --enable-operator-client-registration default with cmd/main (false). Add inline comment on the secrets rule in config/rbac/role.yaml.

Signed-off-by: Akram <[email protected]>
…egacy label=true

- Operator manages Keycloak registration unless kagenti.io/client-registration-inject=true
- Update docs and --enable-operator-client-registration flag help

Signed-off-by: Akram <[email protected]>

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All previous review comments have been addressed:

  • Feature flag defaults to false (opt-in) ✅
  • Docs default value matches code ✅
  • StatefulSet indentation fixed ✅
  • Token caching implemented (CachedAdminTokenProvider) ✅
  • Drift reconciliation (GET+compare+PUT) ✅
  • Cluster-wide Secret RBAC documented with rationale (section 3.4) ✅
  • TLS config support added ✅
  • Reconciler integration tests added ✅

Note on latest commit (6136613): The label logic inversion (operator reconciles by default, skips on inject=true) is well-guarded by three layers of opt-in (CLI flag, feature gate ConfigMap, label predicates). One minor inconsistency: the PR description still says "workloads that set kagenti.io/client-registration-inject: "false"" but the code now reconciles by default unless "true". Consider updating the PR description to match.

LGTM pending CI completion.

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CI lint is failing — all 8 errors are in files introduced by this PR. Please fix before merge.

Lint failures summary

Rule File Issue
gofmt admin_test.go, token_cache_test.go, clientregistration_controller_test.go Files not formatted — run gofmt -w
errcheck admin.go:95,211,249 resp.Body.Close return value unchecked
lll cmd/main.go:113 Line is 135 chars (max 120) — wrap the flag help string
goconst admin_test.go:33 /realms/master/protocol/openid-connect/token repeated 4x — extract to a constant
unparam clientregistration_controller_test.go:156 ns param of testDeploymentForClientReg always receives "test-ns"

Quickest fix: gofmt -w ./... for formatting, then address the remaining 5 issues individually.

Comment thread kagenti-operator/cmd/main.go Resolved
akram added 2 commits March 31, 2026 17:51
- Split long flag help string; remove RBAC comment block from role.yaml
- Ignore Close() errors in defer for Keycloak admin HTTP responses
- Centralize test token path in const_test.go; align formatting in tests

Signed-off-by: Akram <[email protected]>
- Use explicit Body.Close ignore in audience.go HTTP defers
- Collapse test deployment helper to fixed namespace/name constants

Signed-off-by: Akram <[email protected]>

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeQL: High severity security alert

The CodeQL check is failing with 1 new high severity alert introduced by this PR.

Rule: Use of a broken or weak cryptographic hashing algorithm on sensitive data
File: internal/keycloak/token_cache.go:36

adminTokenCacheKey() hashes baseURL + username + password with SHA256. CodeQL flags this because SHA256 is not computationally expensive and the input includes a password.

The fix is straightforward — the password doesn't add meaningful cache differentiation since the operator uses a single admin credential set. Drop it from the key:

func adminTokenCacheKey(baseURL, username, password string) string {
	base := strings.TrimRight(strings.TrimSpace(baseURL), "/")
	return base + "\x00" + username
}

Or remove the password parameter entirely and update the call site.

Alternatively, if you want to keep the password in the key for multi-credential scenarios, use the raw concatenation as the map key directly (it's in-memory only, no security benefit from hashing).

Do not include the password in the cache key so it is not used for
key derivation. Cached entries still refresh through adminToken when
near expiry, using the current credentials from the reconciler.

Signed-off-by: Akram <[email protected]>
@akram
akram force-pushed the feature/operator-managed-client-registration branch from 5484a3f to bd2e67e Compare March 31, 2026 18:17

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/lgtm

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feature: Refactor Keycloak secrets handling for agent operator and centralized credential management

5 participants