← Back to Pull requests

feat(sandbox): give the agent a scoped credential and make GKE and vcluster work #15

Closed
unknown closed this pull request without merging on Sep 09, 2026 21:26 UTC
View on GitHub
unknown unknown commented on Sep 08, 2026 20:22 UTC
Author

Makes the first scoreable sandboxed run possible. 1731 tests pass, ruff clean.

Why this is needed

PR 1 built the boundary but could only reach kind, and it mounted the operator's admin client certificate as the agent's cluster credential. Two consequences made it unscoreable:

  • build_network_plan raised SandboxError for any non-kind context, and scored runs must use remote-node clusters — co-located kind is dev-only. That is observed incident 1: a privileged pod on a kind node read the bench checkout off the host disk.

  • GKE could not work in-container at all, because its kubeconfig authenticates through gke-gcloud-auth-plugin, which needs a gcloud binary and ADC the container deliberately lacks.
  • Pradeep's #14 makes the boundary reachable for all four CLI arms. This PR makes it hold.

    What lands

    A scoped credential instead of the admin cert. New devops_bench/k8s/agent_credentials.py creates a bench-agent ServiceAccount in bench-system, binds built-in edit cluster-wide plus a small cluster-scoped supplement, and mints a short-lived token (run timeout + slack, clamped to [10m, 2h]). The rendered kubeconfig carries that token and no exec: block. The admin path survives only behind BENCH_SANDBOX_ALLOW_ADMIN_CREDS=1; without it, a failure to mint raises rather than falling back.

    Per-provider network plans. New Provider.sandbox_network_plan hook — default is a plain bridge, so a new provider gets a working sandbox for free and only kind carries special knowledge. build_network_plan(provider, cluster_info) applies the hook, then a generic loopback normalisation rewrites 127.0.0.1/localhost/::1 to host.docker.internal. GKE and vcluster stop raising.

    Pod security. PSA baseline labels on provision-time namespaces, plus a ValidatingAdmissionPolicy backstop covering namespaces the agent creates later — which a label cannot, and which deploy-hello-app literally asks the agent to do. Two further policies guard the exemptions that policy needs, and a fourth covers pods that predate it (both below). New agent_pod_security: task key (baseline default, privileged opts out); an unrecognised value is a load-time error, not a silent fall-back.

    Kubernetes 1.30 is a floor. admissionregistration.k8s.io/v1 only reached GA there, and both node_image defaults still pointed at kindest/node:v1.29.2 — so every sandboxed kind task failed on a module-built cluster, which validation on GKE and vcluster could not see. Raised to the digest-pinned v1.30.0 five tf/prebuilt stacks already use, and the version is now a checked precondition rather than only a default: left to the apply it surfaces as no matches for kind, which reads like a typo in our own manifest. Deliberately a SandboxError and not routed through BENCH_SANDBOX_ALLOW_ADMIN_CREDS — that hatch is for an operator who cannot write cluster-scoped objects, and no credential makes a 1.29 apiserver serve a v1 policy. Thanks @pradeepvrd.

    The metadata endpoint is blocked for containers on the bastion (DOCKER-USER -d 169.254.169.254 -j REJECT). That is observed incident 2. Minting a scoped model token is pointless while the container can curl the VM service account's unscoped one.

    Refusal to run unpinned. If the plan carries no context pin — --no-infra, the no-op deployer — provisioning would write a cluster-wide admission policy and ClusterRoleBindings to whatever the ambient current-context names. It refuses and says which cluster it declined to touch.

    Interim state, please read

    A sandboxed Vertex run cannot authenticate. The metadata block plus _matrix_lib.sh unsetting API keys means Vertex falls back to ADC through exactly the blocked endpoint. It fails loud rather than degrading to an unsandboxed run, which is correct under that invariant — but it means sandboxing is usable with AGENT_PROVIDER=google + AGENT_API_KEY and unavailable for the matrix default until PR 2.5 (a metadata-server emulator; needs a roles/iam.serviceAccountTokenCreator grant that does not exist yet). Ambient runs are unaffected by the block — they are host processes, so DOCKER-USER is never consulted for them. Note this is a statement about the metadata rule only; see Validation for what ambient Vertex on the bastion actually needed before it would run at all.

    Operator prerequisite on GKE

    The runner identity needs roles/container.admin. GKE gates admission-policy resources behind container.thirdPartyObjects., which roles/container.developer lacks — without it the pod-security backstop silently is not installed. Measured, not assumed: this blocked validation until the grant was made.

    Known residuals

    Documented in docs/components/agents.md rather than left implicit:

  • edit bound cluster-wide reaches system namespaces: impersonate on serviceaccounts and create on serviceaccounts/token, so the agent can mint a token for a ServiceAccount bound to cluster-admin. A path to cluster-admin, and RBAC has no deny rule, so nothing in the supplement can subtract it. The pods/exec route alongside it is now denied by the exempt-namespace guard, but that is a patch over one exit rather than a fix for the scope.

  • edit carries read and write on secrets in every namespace. Inherited from the built-in role, not narrowed anywhere.

  • The supplement grants update/patch on namespaces, so PSA labels can be stripped. The admission policies are unaffected, so this removes the non-load-bearing half. Measured: on the GKE run the labels were byte-identical before and after — a capability held, not a behaviour seen.

  • Nothing is torn down. bench-system, the bindings, the admission policies and the PSA labels outlive the run. Fine on a disposable cluster; on a reused one the labeller looks inert because it finds its work already done.

  • On a reused cluster the surviving policy applies to the operator too, and can deny the next run's fixtures. The pod-security policy is deliberately not username-scoped — a pod is often created on the agent's behalf by a controller under another identity — so combined with the line above it outlives the run that made it and refuses everyone. The probe found this the hard way: seeding a privileged pod host-side was denied by the previous run's policy. On a fresh cluster it does not arise, since the deployer runs before any of this exists, but a tf/prebuilt fixture that deploys privileged pods (opa-remediation ships two) would fail to come up on a second run against the same cluster. Teardown of the policies belongs in PR 3 with the rest of the lifecycle work; flagging it rather than letting someone rediscover it as a flaky fixture.
  • Narrowing is not a blind edit — the tasks were authored against admin, and too tight a scope fails them in ways that read as agent error. The A/B soak is what produces the verb set.

    The scope is already too tight in one place

    edit covers Kubernetes' own API groups, not the CRDs an operator installs — the agent gets whatever that operator aggregated into edit, usually nothing. Kyverno v1.12.7 labels policy reads aggregate-to-view and policy writes aggregate-to-admin, with no aggregate-to-edit on either, so the agent reads ClusterPolicy objects and cannot write them.

    Two of opa-remediation's objectives ask it to flip both policies from Audit to Enforce. That task cannot be fully passed under the default scope — one of its three deterministic objective groups is unreachable, and its sandboxed score is not comparable to its ambient one.

    Nothing in a trajectory reveals this: neither agent attempted the flip, so there is no forbidden in the logs and the objective reads as an agent miss. An A/B soak that infers scope gaps from failures will not find this class. The fix is a per-task RBAC supplement — a task.yaml key naming existing ClusterRoles to bind, validated against a deny-list and recorded in capabilities_granted — which is its own PR, since it lets the artifact under test widen its own sandbox and deserves review on that basis rather than as a footnote here.

    Gotcha worth flagging up front

    AGENT_API_KEY, not GEMINI_API_KEY. The provider's own names are where the key is written inside the container; the host only ever reads AGENT_API_KEY. Unsandboxed the distinction is invisible, because the agent subprocess inherits the whole host environment. Sandboxed, only the explicit overlay crosses — so a host-side GEMINI_API_KEY is absent and the CLI exits naming the very variable you exported. Corrected in the docs in this PR.

    Validation

    Run on the bastion, docker only.

  • A scored run on plain GKE. This is the deliverable — the case PR 1 could not run at all. The agent audited the cluster, edited the GitOps repo, applied manifests, watched rollouts and pushed. Every deterministic remediation objective passed, all three policy reports came back clear, and all four safeguards held. Zero forbidden / denied across 41 trajectory steps: edit plus the supplement covered everything the agent reached for.

  • A scored run on vcluster, same shape.

  • The scoped token is self-proving on GKE. Its kubeconfig authenticates through gke-gcloud-auth-plugin; the container has no gcloud, so had it been handed the ambient config every kubectl would have failed. They all worked. kind cannot prove this — a client cert works there.

  • PSA labels land correctly and survive the run. get ns --show-labels before and after was byte-identical but for AGE.

  • Metadata block proven three ways: container blocked (exit 7), host still working (exit 0 + token, which is what guards ambient Vertex), rule present in the chain.

  • 18/18 boundary probes green on GKE, controls first, so a dead token cannot make every denial "pass". The exempt-namespace denials landed on real GKE-managed components — a pod and an unprivileged Deployment refused in gmp-system, and kubectl exec into a live event-exporter-gke pod in kube-system — which kind cannot demonstrate, having no managed components to guard. The first attempt failed, and failed correctly: with container.admin absent the run raised SandboxError and refused rather than proceeding with a boundary that would not hold, independently reproducing the container.thirdPartyObjects. prerequisite from a cold start.

  • Both exempt-namespace bindings are now exercised, separately. An earlier GKE run was green with by-label appearing zero times: every managed namespace on GKE is also on the exempt name list, so by-name matched first and half the guard had never run. The new probe holds a namespace that carries the addon manager's label and is absent from the name list, so only by-label can deny it — and the apiserver names the binding that fired: ValidatingAdmissionPolicy 'bench-agent-exempt-namespace-guard' with binding 'bench-agent-exempt-namespace-guard-by-label' denied request. Getting there took a fix of its own: GKE's addon manager prunes namespaces carrying its label, and on the probe's first run it deleted the namespace 2.5 seconds before the agent's create landed (audit log, to the millisecond).

  • The shell guard is proven on a pod admission never saw. The probe builds the situation the guard exists for, in the right order: a privileged pod and a conformant one, both in a non-exempt namespace, both created before provisioning. The agent's exec into the privileged one is refused — ValidatingAdmissionPolicy 'bench-agent-nonconformant-pod-guard' ... this pod was created before the benchmark's pod-security policy was applied — and its exec into the conformant one beside it succeeds. They differ only in conformance, so that pair is the guard discriminating rather than exec being broken wholesale, which is how a fail-closed policy looks if you only probe the deny.

  • vcluster host-isolation is measured, not argued. The agent token minted inside the vcluster authenticates against the vcluster apiserver (200) and is rejected by the host apiserver (401 Unauthorized), with no same-named ServiceAccount on the host to confound it. Control first: a dead token would produce the same 401.

  • 15/15 boundary probes green on kind, controls first, so a dead token cannot make every denial "pass". Both observed escapes denied. The pods/ephemeralcontainers rule was proven under deliberately widened RBAC, because it was otherwise passing for the wrong reason — RBAC, not the policy. One of these probes failed on its first run and produced the last commit in this branch — see below.

  • The unpinned-cluster refusal fired on a real run and named the cluster it declined to touch.

  • Flag-off parity, measured. Base (e13d52e) and this branch (3ed87db) each ran opa-remediation on the bastion with BENCH_AGENT_SANDBOX unset, ambient Vertex, same model and judge. All 15 deterministic verification entries are identical — 13 pass, and the same 2 fail on both — with identical capabilities_granted and no parse errors on either side. The judge-scored items differ in both directions (one checklist item down, OutcomeValidity 0.4 → 0.7) across trajectories of 28 and 38 steps, which is agent and judge nondeterminism rather than a systematic shift. n=1 per arm, so this shows the deterministic surface is unchanged, not that two stochastic runs are byte-identical.

  • Unit suite green at every commit in the stack.
  • A probe found a real hole, and it is fixed here

    The pod-security policy exempts the namespaces holding the cluster's own components, because kube-proxy and the CNI legitimately run privileged with host mounts and a fail-closed policy over them breaks the cluster rather than the agent. The module asserted the property that makes that safe — every exempt name must be one the agent cannot write to — and nothing enforced it. edit is bound cluster-wide.

    So kubectl run --privileged -n kube-system was an admitted request on a cluster carrying the full policy set. The escape the whole stack exists to deny, reachable by appending a flag. That is not a derivation from reading the RBAC; the probe ran and the pod was created.

    A third policy closes it: the agent's own username may not create or update anything that can produce a pod inside an exempt namespace, nor exec into one already there. Every workload kind rather than pods alone, because a Deployment reaches the same place with its pod made by the ReplicaSet controller under another identity — the workload object is the last point the agent's name is on the request. pods/exec, pods/attach and pods/portforward too, because edit grants exec and these are precisely the namespaces whose pods are privileged; a shell in kube-proxy is the same escape by a longer route. Config is untouched: a ConfigMap in kube-system is a blast-radius question, not an escape, and denying it would fail tasks for no boundary gain.

    Re-probed on the cluster that failed the original: the privileged pod, an unprivileged Deployment (which only this guard can deny, so it cannot pass on the pod policy's back) and kubectl exec into a running coredns are all refused by name, and control:ordinary-pod / control:ordinary-namespace still pass — the guard is not simply failing closed over everything.

    A fourth policy closes the route the same reasoning leaves open in the other direction, and @pradeepvrd caught it in review: admission only sees requests, so nothing retracts a pod that already exists — and the deployer runs before credentials are provisioned. tf/prebuilt/opa-remediation leaves privileged: true pods in team-alpha and team-beta, neither exempt, so the policy is in scope for them and simply arrived too late. kubectl debug and pod UPDATE were already closed; CONNECT was the one left, and admission there is nearly blind — the object on a pods/exec request is a PodExecOptions, so there is nothing to test a property against. The run scans every namespace before the agent starts, finds the pods the policy would have rejected, and names them. Applied even when the list is empty, with a constant true: nothing is torn down, so a reused cluster would otherwise keep the previous run's list, and an empty CEL list literal has no element type to infer — a policy that fails to compile under failurePolicy: Fail denies every exec the agent attempts, which is the opposite of inert.

    This also closes the exec half of the first known residual above. The impersonate / serviceaccounts/token half stays open — RBAC has no deny rule, so only replacing edit with a derived role fixes the scope itself.

    Worth saying plainly: I had written this hole up as a reasoned concern from reading the RBAC and was ready to ship with it documented. The probe is what turned it into a merge blocker, and it is the argument for PR 4 promoting these into an e2e test.

    Two more things only a real cluster found

    The GKE run also earned its keep by finding two things a kind run could not. It exposed the stale exempt list fixed in this branch — the labeller had stamped enforce=baseline on four GKE-managed namespaces and the fail-closed pod policy had them in scope. And a blanket metadata REJECT turned out to take container DNS down with it, because on a GCP VM the metadata address is the resolver; kind conceals that, since containers on a user-defined network resolve through Docker's embedded server instead. Both are fixed here.

    Still open, and I'd rather say so than imply otherwise:

  • The by-label binding is proven on GKE only. Nothing on kind or vcluster carries the addon manager's label, so there the binding matches nothing and the probe cannot run at all. That is the intended shape — the name list is what covers those providers — but it does mean one of the two bindings is exercised on exactly one provider.

  • The 1.30 floor is enforced by a check, not exercised against a 1.29 cluster. The refusal has a unit test; nobody stood up a 1.29 apiserver to watch it fire. The failure it replaces (no matches for kind) is the one that was observed.

  • The parity pair is n=1 per arm. The deterministic half matched exactly, all 15 entries; the judge-scored half moved in both directions. Repeating it is what would separate that variance from a small systematic effect, and I judged the deterministic match to be the load-bearing evidence and not worth more matrix time. Saying so rather than leaving it implied.
  • Probes live on validation/sandbox-probes (hack/sandbox_probe.py), deliberately not in this PR — dev tooling, not shipped surface. PR 4 promotes them into an e2e test.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: isadominguez314 Review duration: 1503m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #15"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%