Repository navigation
feat(controller): env-fed credential bindings merged into sandbox policy (#264) - #269
Merged
Merged
Conversation
…icy (#264) ParseBindings decodes KAPE_CREDENTIAL_BINDINGS ([{provider,hosts[]}], handoff H1) and MergePolicy merges one NetworkEndpoint{credential_binding: <provider>} per host pattern into the per-sandbox policy through the existing ApplyModelGatewayPolicy seam, allowlisting git/gh/pi on the bound rule. The merge is additive only: the model-gateway egress rule is submitted byte-identical and the binding rule is a sibling, never a replacement. Fail-closed: a malformed table fails startup, and a binding that cannot be materialised (parse or gateway rejection) aborts the apply before any policy lands, so Create deletes the sandbox and surfaces the error. v0.1.0 carries on_error only on policy-level NetworkMiddlewareConfig, which the MergeOperations seam cannot reach — see the PR note (handoff H6).
…g table
Live v0.1.0 rejects a "rest" endpoint with no allowed traffic ("protocol
requires rules or access to define allowed traffic"), so MergePolicy emits
method "*" / path "**" on every bound endpoint — the host pattern is the
credential boundary, not the path.
Also name the configured providers at controller startup: one log line, no
secret material.
dzungtr
force-pushed
the
pi/264-credential-binding-merge
branch
from
October 19, 2026 17:09
4b01ef4 to
7095ff7
Compare
Owner
Author
Rebase onto
|
dzungtr
added a commit
that referenced
this pull request
Oct 19, 2026
…viders, degrade-loud rotation (#265) (#270) * feat(operator): credential automation — Secret transit, OpenShell providers, degrade-loud rotation Closes #265 (final slice of epic #261). The operator now turns a KapeAgentServer's credentials[] registry into OpenShell provider records and hands the controller an env table that names only providers the gateway actually holds. Secret resolver (M4, operator/infra/k8s/secret_resolver.go) - Same-namespace reads only, gated on kape.io/credential=true; values stay in memory and never reach the CR, the env contract, or a log line. - Missing, unlabelled, empty, or unreadable Secrets are per-credential failures naming the entry — never a silent skip. Renderer credentials section (M2, operator/domain/agentserver) - Provider names follow handoff H2 (kape-<ns>-<cr>-<cred>); the git-https provider-profile document ships as operator code (endpointless: the CR's hostPatterns are the credential boundary, #269 finding 3). - KAPE_CREDENTIAL_BINDINGS carries [{provider, hosts[]}] (handoff H1) for pushed credentials only, in CR order. OpenShell writer (M3, operator/infra/openshell) - Lint → import → create/update per provider type, platform-scoped profiles so every workspace resolves them without profile_workspace. - Idempotent: an existing profile is neither re-imported nor re-linted (the gateway answers both with "already exists" — verified live), and unchanged credential values perform no write. Rotation is UpdateProvider with the new value; RotateProviderCredential only refreshes gateway-owned material and answers NotFound "provider refresh state not found" for pushed credentials. - Conflicts and transient unavailability retry with exponential backoff; a rejected credential fails alone. Watches and status - Labelled Secret edits requeue every KapeAgentServer in the namespace that references them (rotation = edit the Secret). - status.credentials[] carries Pushed per entry plus the H6 fail-closed gap; the aggregate Degraded condition names the entries that failed while the healthy rest of the profile keeps serving. Module wiring: the operator imports the v0.1.0 client generated into the controller module (handoff H3), so operator/go.mod gains a require + local replace, go.work includes ./controller, and the image build copies the module. The operator's k8s libraries unify on v0.34.2 as a result; the golden files were regenerated for that serializer. Chart: the operator Deployment gets its own mTLS gateway connection (operator.openshell.*, disabled unless a creds Secret is set) and the ClusterRole grants Secrets get/list/watch only. Also fixes the operator image build: `go build ./cmd/...` matched two packages. * fix(chart): correct KAPE_OPERATOR_OPENSHELL_* env spelling so the credential writer can be enabled The operator deployment rendered KAPE_OPERATOR_OPENSHHELL_* (double H) while ff derives env names from the flag names (--openshell-gateway-addr → KAPE_OPERATOR_OPENSHELL_GATEWAY_ADDR), so setting operator.openshell.credsSecret never enabled the credential writer. The render-test asserted the same misspelling, locking the bug in. - rename the three chart env vars to the single-H spelling and fix the two user-facing Go messages that named the same var - fix the three render-test assertions - hoist flag registration/parsing in operator/cmd into newFlagSet/parseConfig so a new test can derive env names from the flag definitions: every chart KAPE_OPERATOR_* var must resolve to a real flag, every flag must bind to its derived env name, and the openshell trio must land in config --------- Co-authored-by: dzungtr <dzungtr@users.noreply.github.com>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Closes #264
Slice of epic #261. Two halves: the controller-side binding merge (code, complete and green) and the manual profile-backed credential proof against the live v0.1.0 gateway (executed; see the evidence table and the unverified list at the bottom).
What changed
Binding merge module (
controller/credentials.go)ParseBindings(KAPE_CREDENTIAL_BINDINGS) ([]Binding, error)— decodes the env table, rejects unknown fields / trailing data / non-DNS hosts / missing or out-of-range ports, and fails closed: an unreadable table is a startup error, never a silent empty one.MergePolicy(policy, []Binding) (*v1.NetworkPolicyRule, error)— pure, additive-only: the input rule's name, endpoints and binaries are carried over verbatim and in order; oneNetworkEndpoint{Host, Port, Protocol: "rest", Rules: allow * / **, CredentialBinding: {Provider}}is appended per host pattern;git/gh/piare allowlisted on the same rule (OPA denies unlisted binaries — M1 spike finding); duplicate hosts/binaries merge once, so re-application is idempotent.ApplyModelGatewayPolicyseam (controller/policy.go) as a sibling rulem1_credential_bindingsin the sameUpdateConfigrequest:m1_model_gatewayis submitted byte-identical, never rewritten, never removed. Binaries stay scoped to their own rule, so credential-bearing egress cannot widen the model-gateway binary set.Config.CredentialBindings(env-only —KAPE_CREDENTIAL_BINDINGSis the operator→controller contract, ADR-0087) →Gateway.WithCredentialBindings; one startup log line names the providers (no host tables, no secrets).agent.Createdeletes the just-created sandbox and returns the named error (apply network policy: …) — never swallowed, never retried-and-ignored.Tests (
controller/credentials_test.go,controller/config_test.go)TestParseBindings(16 cases)*.github.com:443,**.github.com:8443)TestParseBindings_HostGlobPassthroughTestMergePolicy_AdditiveOnlyTestMergePolicy_BoundEndpointsTestMergePolicy_BinariesAllowlistTestMergePolicy_NoBindingsLeavesPolicyUnchangedTestMergePolicy_FailClosedTestApplyModelGatewayPolicy_MergesCredentialsTestApplyModelGatewayPolicy_NoBindingsKeepsModelGatewayOnlyTestApplyModelGatewayPolicy_FailClosedOnBadBindingTestApplyModelGatewayPolicy_FailClosedOnGatewayRejectionCreatedeletes the sandbox and returns the named errorTestCreateRollsBackSandboxWhenBindingPolicyRejectedTestConfigFromEnvReadsCredentialBindings,TestConfigFromEnvRejectsGarbageCredentialBindings(
TestLiveSmokeis the pre-existing live-OpenRouter SLM smoke; it needs an API key and network and flakes independently of this change — it failed once and passed on re-run with no code difference.)Live proof (gateway
k8s, OpenShell v0.1.0, CLI 0.1.4)Everything below was executed against the live cluster. Credential path was profile-backed only —
openshell provider create --type genericwas never used.1. Profile import + provider create. A minimal git-https profile (no secrets) linted clean and imported; the provider was created from the imported profile with the dev-host
gh auth token:2. Sandbox + effective policy. With the provider attached, the gateway composes the credential boundary into the policy (
openshell policy get <sbx> --full):3.
gh api userinside the sandbox (no real token anywhere in the sandbox — only the resolver placeholder):4. Private
git cloneover HTTPS inside the sandbox:gitwith no credential position at all fails (could not read Username), confirming the placeholder is what the proxy resolves — injection is proxy-layer, not sandbox-local.5. Token absence in the sandbox:
6. Controller-shaped policy accepted (no controller in the loop). An endpointless profile provider plus exactly the rule
MergePolicyemits (hosts,protocol: rest,rules: allow * / **,credential_binding, binaries git/gh/pi) was accepted bysandbox createand, afterpolicy set, the sandbox rangh api user→dzungtrand cloned the private repo.policy get --fullshowsm1_credential_bindingswith both bound endpoints next tom1_model_gateway.7. Fail-closed, gateway side (both variants):
8. Unbound egress stays denied —
gh api userbeforeapi.github.com:443was bound:NET:OPEN DENIED /usr/bin/gh(0) -> api.github.com:443 [reason:transparent_tcp_policy_denied].Cleanup: all live artefacts were prefixed
k264-. Sandboxesk264-proof/k264-binding, providerskape-openshell-kape-github{,-ep}and both test profiles were deleted after the runs;openrouter/openrouter-spikewere never touched. The gateway is back to the state it had before this PR.Live findings that change the design (for #265 / #261)
on_error: fail_closedis not reachable through the merge seam — handoff H6 (open gap). D11/Spec: KapeAgentServer — runtime credential injection via OpenShell credential bindings #261 putson_error: fail_closedon the endpoint. On OpenShell v0.1.0on_errorexists only onNetworkMiddlewareConfig(policy-levelSandboxPolicy.network_middlewares), andUpdateConfigRequest.MergeOperationsoffers only AddRule / RemoveEndpoint / RemoveRule / AddDenyRules / AddAllowRules / RemoveBinary — no middleware operation (openshell policy updatehas no middleware/on-error flag either). A fullUpdateConfigRequest.Policyreplace would need the create-time static fields the controller does not hold and would risk dropping the model-gateway rule, i.e. it would violate the additive-only invariant. Enforced instead on the controller side: parse errors and gateway rejections abort the apply, andCreatedeletes the sandbox and surfaces the named error — a sandbox never egresses with a silently-degraded binding. Proposal for Operator credential automation: registry → OpenShell providers → env, rotation, degrade-loud #265: keep controller-side fail-closed and add an explicit per-credential status condition naming the missing gateway-side enforcement; revisit only if upstream adds a middleware merge op. Do not resurrect a full-policy replace for this.protocol requires rules or access to define allowed traffic) — discovered live, hence theallow * / **rule on every bound endpoint. The host pattern, not the path, is the credential boundary.host:portin the policy withcredential_bindingis rejected:network endpoint ambiguity validation failed: … enforcement=1 vs 2; credential_binding.provider="…" vs "". The proto says it explicitly — "profiles that already define endpoints continue to use those profile endpoints as their credential boundary";credential_bindingis the authority for endpointless profiles. Operator credential automation: registry → OpenShell providers → env, rotation, degrade-loud #265 must pick one posture per credential: profile-declares-endpoints (no policy endpoints, as in the git-https profile above) or endpointless profile +KAPE_CREDENTIAL_BINDINGSendpoints (the shape the controller emits). The controller code is correct for the second; if Operator credential automation: registry → OpenShell providers → env, rotation, degrade-loud #265 lands the first, the env table for that credential becomes redundant — flag before building the renderer.token=openshell:resolve:env:<id>_token; the proxy swaps it for the real credential when it sees the placeholder in an outbound request (gh:AuthorizationfromGH_TOKEN; git: credential position in the URL/helper). Nobody in the sandbox can read the secret, but callers must forward the placeholder. Operator credential automation: registry → OpenShell providers → env, rotation, degrade-loud #265's profile document should state this, and the epic note "no credential material in sandbox env" should say no real credential material — the indirection token is present by design.policy set/ version change can returnpolicy_dns_upstream_error_response; a retry seconds later succeeds. Not a code issue, but smoke scripts need one retry.git-https provider profile document (verified lint + import; input to H5)
Endpointless variant used to exercise the controller-emitted rule: same document minus
endpoints:.Handoffs for #261
KAPE_CREDENTIAL_BINDINGS= JSON array[{"provider": "<provider-name>", "hosts": ["<host>:<port>", …]}].providermust match[A-Za-z0-9._-]+;hostsis non-empty, each entryhost:portwith port 1–65535, host may be a DNS glob (*.github.com,**.github.com), passed to the gateway verbatim. No unknown fields (unknown keys are a startup error). Empty/unset value ⇒ no bindings, policy byte-identical to pre-#264. Malformed value ⇒ controller fails to start (fail closed).kape-<crNamespace>-<crName>-<credName>. Strings used in the live proof:kape-openshell-kape-github(namespaceopenshell, CRkape, credentialgithub) and its endpointless twinkape-openshell-kape-github-ep. The controller consumes provider names verbatim and never derives them.on_error: fail_closedhas no endpoint-level representation on v0.1.0 and no merge-ops path toNetworkMiddlewareConfig. Controller-side fail-closed is the enforced substitute; #265 should surface the gap as a per-credential status condition rather than a full-policy replace.Unverified / blocked
KAPE_CREDENTIAL_BINDINGSset on a deployed controller — unverified. Blocked by Proto re-pin to OpenShell v0.1.0 + workspace_scope fix (cluster upgrade done) #262 (the deployed controller is still not v0.1.0-compatible) and by shared-cluster coordination: patching the sharedkape-controllerDeployment while Proto re-pin to OpenShell v0.1.0 + workspace_scope fix (cluster upgrade done) #262 is in flight would collide with that agent's verification, so the env was not rolled out and no controller create was attempted. The code path is covered by unit tests (ApplyModelGatewayPolicyseam,Createrollback) and its emitted policy shape was validated against the live gateway by hand (evidence 6 above).KAPE_CREDENTIAL_BINDINGSon the controller env.