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

fix: watch Sandbox resources in ClientRegistration controller - #338

Merged
cwiklik merged 2 commits into
mainfrom
fix/sandbox-client-registration
May 8, 2026
Merged

cwiklik merged 2 commits into
mainfrom
fix/sandbox-client-registration

Conversation

@cwiklik

@cwiklik cwiklik commented May 8, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add Sandbox (agents.x-k8s.io/v1alpha1) as a watched resource type in ClientRegistrationReconciler
  • Conditionally registers the watch only when the Sandbox CRD exists (mirrors AgentRuntimeReconciler pattern)
  • Extracts pod template labels and serviceAccountName from the unstructured Sandbox spec
  • Registers Keycloak OAuth client and patches kagenti.io/keycloak-client-credentials-secret-name annotation on the Sandbox podTemplate

Why: The controller only watched Deployment and StatefulSet, so Sandbox workloads deployed via the Sandbox epic (#1155) never got OAuth credentials registered — breaking AuthBridge authentication.

Test plan

  • go build ./... — compiles clean
  • go vet ./... — no issues
  • Existing TestClientRegistrationReconciler_Reconcile tests pass (6/6)
  • Deploy a Sandbox workload with kagenti.io/type: agent label → verify operator watches Sandbox
  • Verify kagenti.io/keycloak-client-credentials-secret-name annotation appears on Sandbox podTemplate (requires workload without legacy sidecar label)

Verification (Kind cluster, v0.6.0-rc.1)

Operator built from this branch (rebased on v0.2.0-alpha.34) and deployed to Kind cluster.

Controller now watches Sandbox resources (3 event sources instead of 2):

$ kubectl logs deployment/kagenti-controller-manager -n kagenti-system | grep "Starting EventSource.*clientregistration"

{"msg":"Starting EventSource","controller":"clientregistration","source":"kind source: *unstructured.Unstructured"}
{"msg":"Starting EventSource","controller":"clientregistration","source":"kind source: *v1.Deployment"}
{"msg":"Starting EventSource","controller":"clientregistration","source":"kind source: *v1.StatefulSet"}

Sandbox workload weather-service-new running 4/4 in team1:

$ kubectl get pod weather-service-new -n team1

Init containers:
  proxy-init  ghcr.io/kagenti/kagenti-extensions/proxy-init:v0.5.0-alpha.11

Containers:
  agent                        registry.cr-system.svc.cluster.local:5000/weather-service-new:v0.0.1
  envoy-proxy                  ghcr.io/kagenti/kagenti-extensions/authbridge-envoy:v0.5.0-alpha.11
  spiffe-helper                ghcr.io/kagenti/kagenti-extensions/spiffe-helper:v0.5.0-alpha.11
  kagenti-client-registration  ghcr.io/kagenti/kagenti-extensions/client-registration:v0.5.0-alpha.11

This workload uses the legacy sidecar path (kagenti.io/client-registration-inject: "true"), so the operator-managed path correctly skips it. The fix enables the operator-managed path for Sandbox workloads that opt out of the legacy sidecar — matching Deployment/StatefulSet behavior.

Workaround for local testing

The Helm chart passes --enable-operator-client-registration=true which requires building from the v0.2.0-alpha.34 base (not latest main). To test locally on Kind:

# Build from this branch (already rebased on v0.2.0-alpha.34)
cd kagenti-operator/
docker build -t ghcr.io/kagenti/kagenti-operator/kagenti-operator:sandbox-fix .

# Push to ghcr.io (Kind can't use kind load due to containerd snapshotter issue)
docker push ghcr.io/kagenti/kagenti-operator/kagenti-operator:sandbox-fix

# Patch the operator deployment
kubectl set image deployment/kagenti-controller-manager \
  manager=ghcr.io/kagenti/kagenti-operator/kagenti-operator:sandbox-fix \
  -n kagenti-system

Important: Use a unique tag each time (e.g. sandbox-fix-v2) because Kind nodes cache images by tag and imagePullPolicy: IfNotPresent won't repull a changed digest under the same tag.

Assisted-By: Claude Code

The ClientRegistrationReconciler only watched Deployment and StatefulSet,
so Sandbox workloads never got Keycloak OAuth clients registered. This
broke AuthBridge authentication for sandbox-deployed agents.

Add Sandbox as a third watched resource type using the same unstructured
pattern established by AgentRuntimeReconciler. The controller now:
- Conditionally watches Sandbox CRs (guarded by SandboxCRDExists)
- Extracts pod template labels/SA from spec.podTemplate
- Registers Keycloak client and patches the annotation

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>

@mrsabath mrsabath 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.

Clean fix that extends ClientRegistration to watch Sandbox resources, correctly mirroring the unstructured pattern from AgentRuntimeReconciler. Reuses sandboxGVK and SandboxCRDExists, conditionally registers the watch, and follows the cascading Deployment→StatefulSet→Sandbox structure. Annotation patching for unstructured Sandbox handles the read-check-write cycle correctly.

Areas reviewed: Go (controller logic, error handling, RBAC markers, predicate, manager setup)
CI: All 16 checks pass (Build, Unit, Integration, E2E, Lint)

annotations = map[string]string{}
}
annotations[AnnotationKeycloakClientSecretName] = secretName
_ = unstructured.SetNestedStringMap(fresh.Object, annotations, "spec", "podTemplate", "metadata", "annotations")

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.

nit: SetNestedStringMap error is discarded. Unlikely to fail for map[string]string but a one-line log at debug level would help if someone hits an edge case:

Suggested change
_ = unstructured.SetNestedStringMap(fresh.Object, annotations, "spec", "podTemplate", "metadata", "annotations")
if err := unstructured.SetNestedStringMap(fresh.Object, annotations, "spec", "podTemplate", "metadata", "annotations"); err != nil {
return err
}

Non-blocking — up to you.

@huang195 huang195 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.

Watch plumbing and predicate are fine. Ale reconcile path added by this PR is unreachable — an err-scoping bug silently returns before we ever hit the Sandbox branch. See inline on line 137.

Same pattern bug at line 117 is pre-existing on main (StatefulSet path), but this PR propagates it to Sandbox — the one workload you're adding support for. Worth fixing both in the same PR.

Test coverage gap. The existing deployment and statefulset not found case in clientregistration_controller_test.go only asserts err == nil + zero Result, which the buggy reconcile also satisfies. That's why 6/6 pass without exercising the added path. Add a happy-path Sandbox test: set up a Sandbox unstructured with kagenti.io/type: agent, run Reconcile, assert kagenti.io/keycloak-client-credentials-secret-name landed on spec.podTemplate.metadata.annotations. That covers the unchecked item in your test plan and would have caught the scope bug before merge.

Areas reviewed: Go (clientregistration_controller.go)
Commits: 1, signed-off: yes
CI: green, but the coverage gap above means CI can't catch this class of bug today.

})
})
}
if !apierrors.IsNotFound(err) {

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.

must-fix. err here is the outer one from readClusterFeatureGates on line 91 — the err declared at line 122 (if err := r.Get…) went out of scope at the closing } on line 136. Outer err is guaranteed nil by the early return on lines 92-95, so !apierrors.IsNotFound(nil) is always true and we return (ctrl.Result{}, nil) right here. The Sandbox branch below (141-169) never runs.

Same bug at line 117 is pre-existing on main (StatefulSet path), but this PR propagates it to Sandbox.

Fix: drop := and assign to the outer err (err = r.Get(...)), or go back to the pre-PR StatefulSet shape:

if err := r.Get(ctx, req.NamespacedName, sts); err != nil {
    if !apierrors.IsNotFound(err) { return ctrl.Result{}, err }
    // fall through to Sandbox
} else {
    return r.reconcileOne(...)
}

Fix line 117 in the same PR — same bug, just the older victim.

return r.reconcileOne(ctx, sts, injectTools, sts.Name, &sts.Spec.Template,
podLabels, _, _ := unstructured.NestedStringMap(sbx.Object, "spec", "podTemplate", "metadata", "labels")
saName, _, _ := unstructured.NestedString(sbx.Object, "spec", "podTemplate", "spec", "serviceAccountName")
syntheticTemplate := &corev1.PodTemplateSpec{

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.

Synthetic template omits existing annotations from the real Sandbox. reconcileOne's short-circuit at line 293 (template.Annotations != nil && ... == secretName) therefore never fires for this path, so every reconcile falls through to the Update callback. Callback is idempotent (checks fresh before Update), so not a correctness bug, ale wasteful on steady state.

Pull spec.podTemplate.metadata.annotations into the synthetic template next to labels and SA.

@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.

Clean extension of the existing pattern. Single file, mirrors AgentRuntimeReconciler's unstructured Sandbox handling exactly — same field paths, same conditional CRD watch, same retry-on-conflict flow. RBAC marker added. All 16 CI checks pass including E2E.

One minor suggestion inline (non-blocking).

return nil
}
return r.Update(ctx, s)
if annotations == nil {

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.

suggestion: SetNestedStringMap error is discarded here. Unlike the read helpers (where a missing field is normal), a write failure means the annotation won't persist and the retry loop will spin silently until the conflict limit. Consider returning the error:

if err := unstructured.SetNestedStringMap(fresh.Object, annotations, "spec", "podTemplate", "metadata", "annotations"); err != nil {
    return err
}

Non-blocking since AgentRuntimeReconciler uses the same _ = pattern — just flagging for awareness.

The Deployment and StatefulSet Get() calls used `err :=` (block-scoped),
so the subsequent `if !apierrors.IsNotFound(err)` checks referenced the
outer `err` from readClusterFeatureGates (always nil after passing the
gate check). This prevented the StatefulSet and Sandbox branches from
ever executing.

Fix: reuse the outer `err` via `err = r.Get(...)` with if/else-if to
properly fall through when the resource is NotFound.

Also addresses review feedback:
- Include podTemplate annotations in the Sandbox synthetic template so
  reconcileOne's short-circuit check fires correctly
- Return error from SetNestedStringMap instead of discarding it

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
@cwiklik

cwiklik commented May 8, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review! All feedback addressed in 1e9b1ba:

@huang195 (MUST-FIX) — err variable scoping bug:
Fixed. Changed from if err := r.Get(...) to err = r.Get(...) (reusing the outer err declared on line 86), with if/else if pattern so the fallthrough from Deployment → StatefulSet → Sandbox works correctly. Good catch — this was a pre-existing bug in the StatefulSet path too.

@huang195 (suggestion) — synthetic template missing annotations:
Fixed. Now extracting spec.podTemplate.metadata.annotations and including it in the synthetic PodTemplateSpec, so reconcileOne's short-circuit check can fire correctly.

@mrsabath / @pdettori (nit) — discarded SetNestedStringMap error:
Fixed. Now returns a wrapped error: fmt.Errorf("setting podTemplate annotations: %w", err).

@huang195 huang195 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.

Dobra robota — must-fix from prior review is resolved correctly.

1e9b1ba switches both Deployment and StatefulSet Get calls to err = r.Get(...) with if err == nil { ... } else if !apierrors.IsNotFound(err) { return err }. Outer err now carries state across blocks and the Sandbox branch is reachable.

Both prior suggestions also addressed:

  • Synthetic template now pulls podTemplate annotations, so reconcileOne's short-circuit fires on steady state (no more wasted Update calls).
  • SetNestedStringMap error is wrapped with fmt.Errorf(... %w) instead of discarded.

Remaining non-blocking gap: no unit test covers the Sandbox reconcile happy path — the coverage that would have caught the original scope bug. Worth adding in a follow-up if not this PR (set up a Sandbox unstructured with kagenti.io/type: agent, run Reconcile, assert kagenti.io/keycloak-client-credentials-secret-name landed on spec.podTemplate.metadata.annotations).

Commits: 2, both signed-off
CI: 15/15 green

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

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants