Skip to content

feat(controller): env-fed credential bindings merged into sandbox policy (#264) - #269

Merged
dzungtr merged 2 commits into
mainfrom
pi/264-credential-binding-merge
Oct 19, 2026
Merged

dzungtr merged 2 commits into
mainfrom
pi/264-credential-binding-merge

Conversation

@dzungtr

@dzungtr dzungtr commented Oct 19, 2026

Copy link
Copy Markdown
Owner

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; one NetworkEndpoint{Host, Port, Protocol: "rest", Rules: allow * / **, CredentialBinding: {Provider}} is appended per host pattern; git/gh/pi are allowlisted on the same rule (OPA denies unlisted binaries — M1 spike finding); duplicate hosts/binaries merge once, so re-application is idempotent.
  • The merge rides the existing ApplyModelGatewayPolicy seam (controller/policy.go) as a sibling rule m1_credential_bindings in the same UpdateConfig request: m1_model_gateway is 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.
  • Wiring: Config.CredentialBindings (env-only — KAPE_CREDENTIAL_BINDINGS is the operator→controller contract, ADR-0087) → Gateway.WithCredentialBindings; one startup log line names the providers (no host tables, no secrets).
  • Fail-closed behaviour: a binding that cannot be materialised aborts the apply before anything reaches the gateway; a gateway rejection fails the single atomic merge. Either way agent.Create deletes 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)

Contract Test
parse errors (JSON, shape, unknown field, trailing data, provider, hosts, port range, host chars) TestParseBindings (16 cases)
host glob passthrough (*.github.com:443, **.github.com:8443) TestParseBindings_HostGlobPassthrough
additive-only — model-gateway rule survives byte-identical, input not mutated, L7 allow intact TestMergePolicy_AdditiveOnly
merge semantics (one/two providers, dedupe, protocol, binding authority) TestMergePolicy_BoundEndpoints
binaries allowlist on bound endpoints, exactly once, originals kept TestMergePolicy_BinariesAllowlist
no bindings ⇒ policy unchanged TestMergePolicy_NoBindingsLeavesPolicyUnchanged
fail-closed at merge (nil rule, bad host ⇒ nil rule + error naming the provider) TestMergePolicy_FailClosed
seam: one request, two ops, model-gateway rule unchanged TestApplyModelGatewayPolicy_MergesCredentials
seam: empty table ⇒ pre-#264 request shape TestApplyModelGatewayPolicy_NoBindingsKeepsModelGatewayOnly
fail-closed: parse error ⇒ zero gateway calls (no half-applied policy) TestApplyModelGatewayPolicy_FailClosedOnBadBinding
fail-closed: gateway rejection ⇒ single call, diagnostics surfaced TestApplyModelGatewayPolicy_FailClosedOnGatewayRejection
Create deletes the sandbox and returns the named error TestCreateRollsBackSandboxWhenBindingPolicyRejected
env wiring + startup rejection of a malformed table TestConfigFromEnvReadsCredentialBindings, TestConfigFromEnvRejectsGarbageCredentialBindings
$ GOWORK=off CGO_ENABLED=0 go test -count=1 -skip TestLiveSmoke ./...   # controller module
ok   github.com/dzungtr/kape/controller  50.1s

(TestLiveSmoke is 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 generic was 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:

openshell profile lint   -f git-https.yaml       → Provider profile lint passed.
openshell profile import -f git-https.yaml       → Imported 1 provider profile.
openshell profile describe git-https             → endpoints github.com:443, api.github.com:443 (rest);
                                                   token (required) bearer / header Authorization;
                                                   binaries /usr/bin/git, /usr/bin/gh
env token="$(gh auth token)" openshell provider create \
  --name kape-openshell-kape-github --type git-https --credential token
                                                 → ✓ Created provider kape-openshell-kape-github
openshell provider list                          → kape-openshell-kape-github  git-https  1  0

2. Sandbox + effective policy. With the provider attached, the gateway composes the credential boundary into the policy (openshell policy get <sbx> --full):

network_policies:
  _provider_kape_openshell_kape_github:
    name: _provider_kape_openshell_kape_github
    endpoints:
      - {host: github.com, port: 443, protocol: rest, rules: [{allow: {method: "*", path: "**"}}]}
      - {host: api.github.com, port: 443, protocol: rest, rules: [{allow: {method: "*", path: "**"}}]}
    binaries: [{path: /usr/bin/git}, {path: /usr/bin/gh}]

3. gh api user inside the sandbox (no real token anywhere in the sandbox — only the resolver placeholder):

$ openshell sandbox exec <sbx> -- sh -lc 'GH_TOKEN="$token" gh api user'
{"login":"dzungtr","id":171466767, … ,"name":"Dzung Tran (Tony)", …}

4. Private git clone over HTTPS inside the sandbox:

$ openshell sandbox exec <sbx> -- sh -lc \
    'git clone --depth 1 https://x-access-token:$token@github.com/dzungtr/cc-harness.git probe'
Cloning into 'probe'...
CLAUDE.md  CONTEXT.md  README.md  agents  docs      # private repo, cloned

git with 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:

env values matching gh[pousr]_… / github_pat_…   → (none)
token-ish env keys                               → token=openshell:resolve:env:v…_token   # placeholder only
grep -rIl -E "gh[pousr]_…|github_pat_…" / (minus /proc,/sys,/dev) → no files
/root/.config/gh/hosts.yml                       → absent

6. Controller-shaped policy accepted (no controller in the loop). An endpointless profile provider plus exactly the rule MergePolicy emits (hosts, protocol: rest, rules: allow * / **, credential_binding, binaries git/gh/pi) was accepted by sandbox create and, after policy set, the sandbox ran gh api user → dzungtr and cloned the private repo. policy get --full shows m1_credential_bindings with both bound endpoints next to m1_model_gateway.

7. Fail-closed, gateway side (both variants):

# nonexistent provider at create
Error: provider 'kape-openshell-kape-nonexistent' not found and no provider profile
       named 'kape-openshell-kape-nonexistent' is available.

# nonexistent provider referenced by credential_binding at policy-apply
Error: credential_binding references provider 'kape-openshell-kape-nonexistent',
       but that provider is not attached to the sandbox

8. Unbound egress stays denied — gh api user before api.github.com:443 was bound:
NET:OPEN DENIED /usr/bin/gh(0) -> api.github.com:443 [reason:transparent_tcp_policy_denied].

Cleanup: all live artefacts were prefixed k264-. Sandboxes k264-proof / k264-binding, providers kape-openshell-kape-github{,-ep} and both test profiles were deleted after the runs; openrouter / openrouter-spike were never touched. The gateway is back to the state it had before this PR.

Live findings that change the design (for #265 / #261)

  1. on_error: fail_closed is not reachable through the merge seam — handoff H6 (open gap). D11/Spec: KapeAgentServer — runtime credential injection via OpenShell credential bindings #261 puts on_error: fail_closed on the endpoint. On OpenShell v0.1.0 on_error exists only on NetworkMiddlewareConfig (policy-level SandboxPolicy.network_middlewares), and UpdateConfigRequest.MergeOperations offers only AddRule / RemoveEndpoint / RemoveRule / AddDenyRules / AddAllowRules / RemoveBinary — no middleware operation (openshell policy update has no middleware/on-error flag either). A full UpdateConfigRequest.Policy replace 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, and Create deletes 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.
  2. A "rest" endpoint with no allowed traffic is rejected by v0.1.0 (protocol requires rules or access to define allowed traffic) — discovered live, hence the allow * / ** rule on every bound endpoint. The host pattern, not the path, is the credential boundary.
  3. Profile-with-endpoints vs explicit binding conflicts. If the provider profile itself declares endpoints, restating the same host:port in the policy with credential_binding is 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_binding is 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_BINDINGS endpoints (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.
  4. Injection is placeholder resolution, not blind header insertion. The sandbox env carries token=openshell:resolve:env:<id>_token; the proxy swaps it for the real credential when it sees the placeholder in an outbound request (gh: Authorization from GH_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.
  5. DNS warm-up after a policy revision. The first lookups right after policy set / version change can return policy_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)

id: git-https
display_name: Git over HTTPS (GitHub)
description: GitHub git and REST API over HTTPS with proxy-layer auth-header injection
category: source_control
credentials:
  - name: token
    description: GitHub token injected at the egress proxy
    required: true
    auth_style: bearer
    header_name: Authorization
endpoints:
  - host: github.com
    port: 443
    protocol: rest
    rules:
      - allow: {method: "*", path: "**"}
  - host: api.github.com
    port: 443
    protocol: rest
    rules:
      - allow: {method: "*", path: "**"}
binaries:
  - path: /usr/bin/git
  - path: /usr/bin/gh

Endpointless variant used to exercise the controller-emitted rule: same document minus endpoints:.

Handoffs for #261

ID Producer → consumer Value
H1 #264 → #265 KAPE_CREDENTIAL_BINDINGS = JSON array [{"provider": "<provider-name>", "hosts": ["<host>:<port>", …]}]. provider must match [A-Za-z0-9._-]+; hosts is non-empty, each entry host:port with 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).
H2 #264 → #265 Provider/profile naming convention kape-<crNamespace>-<crName>-<credName>. Strings used in the live proof: kape-openshell-kape-github (namespace openshell, CR kape, credential github) and its endpointless twin kape-openshell-kape-github-ep. The controller consumes provider names verbatim and never derives them.
H6 (new, open gap) #264 → #265 on_error: fail_closed has no endpoint-level representation on v0.1.0 and no merge-ops path to NetworkMiddlewareConfig. 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

…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
dzungtr force-pushed the pi/264-credential-binding-merge branch from 4b01ef4 to 7095ff7 Compare October 19, 2026 17:09
@dzungtr

dzungtr commented Oct 19, 2026

Copy link
Copy Markdown
Owner Author

Rebase onto main (post #267 + #268) — resolved, gate green

Rebased pi/264-credential-binding-merge onto origin/main (c4319fe, after #267 ee75378 and #268 c4319fe). PR is now MERGEABLE.

Conflicts and resolution

Generated protos/CRDs untouched — no regen needed for this slice.

Gate (local; CI has no runners)

$ cd controller && GOWORK=off CGO_ENABLED=0 go build ./...   # BUILD OK
$ GOWORK=off CGO_ENABLED=0 go vet ./...                       # VET OK
$ GOWORK=off CGO_ENABLED=0 go test -count=1 -skip TestLiveSmoke ./...
ok  github.com/dzungtr/kape/controller  50.150s

Targeted #264 suite all PASS: 16-case parse table, TestParseBindings_HostGlobPassthrough, TestMergePolicy_AdditiveOnly, TestMergePolicy_BinariesAllowlist, TestMergePolicy_FailClosed, TestApplyModelGatewayPolicy_FailClosedOnBadBinding, TestApplyModelGatewayPolicy_FailClosedOnGatewayRejection, TestCreateRollsBackSandboxWhenBindingPolicyRejected. gw.ApplyModelGatewayPolicy now carries WorkspaceScope on every call (v0.1.0).

H6 unchanged: no policy-level middleware route attempted — fail-closed is enforced controller-side.

@dzungtr
dzungtr merged commit 518f645 into main Oct 19, 2026
@dzungtr
dzungtr deleted the pi/264-credential-binding-merge branch October 19, 2026 17:12
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Credential-injection mechanism proof: controller binding merge + profile-backed manual provider

1 participant