Skip to content

Environment egress policies ​

Network permission is the intersection of platform policy, project narrowing and admitted run needs. Environment compiles that intent into Cilium policy and verifies the saved generation. A matching policy object is necessary evidence for readiness, not proof that packets were filtered.

Current source boundary ​

Agentweaver supports three distinct egress facts:

  1. Environment compiles the intersection of platform policy, project narrowing, and admitted run needs, then reads and verifies the exact Cilium policy object.
  2. With Azure network-log collection and the Environment importer enabled, Environment reads bounded flow batches from the configured cluster and workspace. It stores records with and without workload attribution.
  3. Canonical policy mode reads an approved, exactly pinned Platform Policy and verifies the applicable network rules before it permits gated workload starts.

Policy-object readback confirms that Kubernetes stored the expected object. Packet enforcement requires a separate datapath observation. The stored egress read API reports coverage: "Unavailable" and returns the records collected so far.

The optional Platform Policy source client is off by default. Enabling it registers and validates the client without making a policy request at startup. Canonical-gated operations read the approved policy when they check the run's network permissions.

Sandbox egress audit persistence ​

Environment stores Sandbox owner mappings and flow records in PostgreSQL. Before it calls the Sandbox provider, Environment commits a mapping from the Sandbox owner fingerprint to the tenant, project, run, and Environment IDs. The fingerprint is the first 40 lowercase hexadecimal characters of the SHA-256 hash of those four IDs, separated by NUL characters. It matches the fingerprint in the AgentSandbox label agentweaver.dev/sandbox-owner. A conflicting owner mapping stops provisioning.

Environment stores each flow with a stable ID. A flow whose WorkloadRef matches a saved owner fingerprint goes to environment.sandbox_egress_flows_attributed. A flow with an unknown or missing reference goes to environment.sandbox_egress_flows_unattributed. Repeated observations are idempotent. Environment normalizes timestamps to UTC before it creates the flow ID.

Environment commits a flow before it returns success. A reader must advance its source cursor only after that commit succeeds. A failed write returns an error, so the same flow can be retried. The runtime role has SELECT, INSERT on the three audit tables. It cannot update, delete, or truncate their rows.

Audit records are append-only and have no automatic expiry.

Flow collection and ingestion ​

Deploy-time configuration enables the Azure Monitor ContainerNetworkLog collector and forwarding of AgentHost flow logs to Log Analytics. Normal new and existing AKS installs default to allowed; explicit off and denied modes remain available. Environment's importer is separately disabled by default and requires the selected AKS resource ID and Log Analytics workspace ID. See the deployment settings.

When enabled, the Environment background importer uses the install workspace customer ID with the supported Azure Monitor Logs client and the existing workload identity. The workspace query filters _ResourceId to the exact selected AKS cluster. It reads the confirmed TimeGenerated, UUID, TrafficDirection, Verdict, EgressFlowCount, IP, Layer4, and AdditionalFlowData fields. The importer sets WorkloadRef from the collector's source.labels entry. A destination name is optional, so an address-only Kata record remains valid.

Environment first saves one 24-hour initial query boundary and a fixed scan end. That state remains unchanged if the first batch fails, so advancing wall time does not move the lower boundary past an unread row. Each query returns at most 100 source rows and orders by TimeGenerated and UUID. The continuation cursor can skip unmatched rows without dropping a later match. Each PostgreSQL transaction inserts that bounded flow batch and advances the continuation in the same commit. A failure leaves the previous continuation in place.

After a scan ends, the next scan starts at scan end - 24 hours. This fixed overlap catches late Log Analytics rows, while the page continuation prevents the query from returning to page one. Stable source-row IDs remove replay duplicates. Unknown and missing owner fingerprints stay unattributed and do not appear in run results.

The current run egress read returns stored attributed flows with coverage: "Unavailable". Collector and importer configuration do not prove that a particular deployment has ingested live flow records.

Activation egress evidence ​

AzureContainerNetworkLogActivationEvidenceReader reads bounded ContainerNetworkLogs rows through IContainerNetworkLogQuery for one owner probe. The owner supplies the pinned AKS cluster resource ID, Log Analytics workspace ID, Pod namespace, Pod name, node name (NodeName), source IP, source port, Cilium SourceIdentity, required agentweaver.dev/probe-attempt identity, observation window (at most 15 minutes), expected destination IP, port, protocol (TCP or UDP), verdict, and expected policy (name, namespace, and kind). Operators cannot submit flow JSON as evidence.

The matcher requires at least one matching EGRESS policy-verdict row (EventType.type == 5) in the window with exact node, source, and destination bindings (including source_port), Reply not true, and the expected verdict. For FORWARDED, it requires Reply equal to false, an empty DropReason, matching entries in Policies.egress_allowed_by, and an empty Policies.egress_denied_by. For DROPPED, it requires DropReason equal to POLICY_DENY (Cilium v1.19.6 explicit policy-deny attribution; default POLICY_DENIED is rejected), matching entries in Policies.egress_denied_by, and an empty Policies.egress_allowed_by. Because Cilium v1.19.6decodeIsReply emits nil for drops, a null Reply is accepted only on an explicit POLICY_DENY policy-verdict record whose node, source/destination tuple, attempt, and policy attribution already match. Every matching policy entry must report one consistent positive Cilium revision across the probe (integer or protobuf decimal string); this Cilium revision is separate from Kubernetes resourceVersion.

Azure ContainerNetworkLogs documents EventType, NodeName, FlowType, Reply, and Policies arrays, but does not document how AdditionalFlowData nests source.labels (and Cilium v1.19.6 endpoints have no Pod UID). The reader fails closed when AdditionalFlowData lacks the expected source.labels attempt entry.

One per-tuple result does not prove a whole multi-case activation window. A caller verifying multiple required cases must require one consistent CiliumRevision across all required cases or aggregate them in one check.

The reader fails closed on partial query errors, saturated results (more than 100 rows), missing Reply flags on FORWARDED rows, duplicate or ambiguous JSON fields, malformed or coerced labels, stale or out-of-window rows, generic or unattributed drops (POLICY_DENIED), mismatched identities, nodes, event types, or connection ports, conflicting verdicts, missing or mixed Cilium revisions. Workload starts remain disabled in canonical mode.

Platform egress snapshot compiler ​

The canonical egress conversion decision uses the native Platform Policy as the source for egress mode and approved destinations. Conversion preserves the deployment's effective egress policy. Widening access to PublicHttps requires authorized activation of that Policy. Separately, importing model bindings creates inactive provider Drafts.

The Platform Policy write gate is disabled by default. When NativeAcsPolicy:HeadWritesEnabled is true, PUT /api/policies/platform validates the artifact and stores an immutable preparation. Its receipt has state: "pending" and checkpoint: null. The preparation stores the expected head identity, revision and hash, plus the complete proposed artifact. It does not change the canonical head, revision history, audit log or outbox.

The private Environment source reads only the committed canonical artifact. It does not return preparations. An exact retry returns the saved preparation after Projects checks current authority and the expected head. If the head has moved, submit a new request with a new idempotency key. A preparation does not grant permission, admit a policy, start a worker or change provider policy.

The Environment source client reads the private Projects route only when code calls it. The client validates the pinned TLS peer, response bounds, pending admission, and complete artifact hash. CompileCandidate validates the fixed manifest, Rego module, and JSON data, then returns an unadmitted candidate. The candidate keeps approved destinations separate from protected System destinations. CompileSystemOnlyCandidate validates the complete original artifact, then returns an Allowlist candidate with no approved destinations and the validated System catalog. It preserves the source ID, revision, full artifact hash, and compiler version. The existing Compile method still requires a genuine admission checkpoint before it creates a PlatformEgressPolicySnapshot. The snapshot keeps approved and release-managed System destinations in both Allowlist and PublicHttps mode. It sorts their combined destinations before snapshot creation, so the public output stays stable when source order changes. Its source hash covers the manifest, module, and data.

Environment:PlatformEgress:Source:Enabled defaults to false. Enabling it registers the client and its dedicated TLS identity; startup sends no source request. The source certificate must differ from the Environment Remote MCP local identities and every configured Projects peer pin.

The client returns only the pending observation. Environment registers no admitted policy source, reconciler worker, or shared egress provider from that observation. The candidate carries no authority to change provider policy or approve an artifact.

When Environment:PlatformEgress:Mode is "canonical", EnvironmentEgressManager uses a scoped, serialized authenticated reader (ICanonicalPlatformPolicySourceReader) that binds the head observation to Environment:PlatformEgress:Pin (PolicyId, Revision, ContentSha256), compiles the unadmitted candidate before additive deploy-host merging, rejects any Environment:NetworkPolicy:Cilium:DeployTimeModelHosts entry outside the approved destinations, and validates that each run's ModelEndpoint rules match an exact TCP/443 host in both the approved policy and the deployment configuration. In the authenticated first-start path (ApplyCoordinatorFirstStartAndVerifyAsync and ApplyChildFirstStartAndVerifyAsync), Environment also verifies the workload's RuntimeOwnerContext model route, RuntimeModelBindingPin, ModelProviderBindingRevision, and PlatformEgressHostValidator host/port rules before reservation, and projects an owner-scoped CompiledEgressIntent inside ApplyAndVerifyCoreAsync: HostedCopilot routes project no ModelEndpoint rule, Byok routes keep only the owner's exact TCP/443 ModelEndpoint rule when permitted by the pinned policy, deployment ceiling, and admitted run intent, non-model admitted rules are preserved, incomplete DNS remains rejected without adding DNS rules after compilation, and PurposeGroups and RequiresL7Mediation are rebuilt from the projected rules. Because scoped private-range protection and guarded activation are not yet verified in this slice, canonical non-System (ModelEndpoint) grant writes in the admitted run intent remain refused fail-closed before reservation (canonical_non_system_grant_unverified), including for a brokered workload in a mixed direct run. System-only checks run before reservation, at the provider write boundary, and before authoritative completion (Completed or Reconciled) or verification receipts; head drift after provider I/O records ReconciliationRequired without accepting a stale grant. Authorized revocations (RevokeAsync and ReconcileAsync for Revoke) do not depend on the policy head; unresolved Apply reservations fail pre-mutation in canonical mode when the head is unavailable or drifted. For coordinator and child first-start, EnvironmentRuntimeRunStartManager and EnvironmentSandboxManager carry the authenticated RuntimeOwnerContext into VerifyNetworkForSandboxAsync and first-start runtime placement reads, validate that owner context, verify the projected CompiledEgressIntent on Cilium readback, and recheck that the post-readback projected intent hash matches the observed policy object. Replacement, resume, BuildTest, EnvironmentRuntimePlacementReader, and public placement reads keep existing unprojected behavior because those routes do not carry a first-start RuntimeOwnerContext. Before normal Sandbox provisioning, Sandbox recovery provisioning, and BuildTest command and output-collector pod creation and scheduling-gate release in "canonical" mode, Environment verifies the current pinned Platform Policy approval, the applied workload policy generation and owner binding, and the complete applicable Kubernetes policy inventory (NetworkPolicy, CiliumNetworkPolicy, and CiliumClusterwideNetworkPolicy). Unexpected overlapping egress grants, shared agenthost-platform-egress rules outside the System-only ceiling, or any egress grant matching a BuildTest workload keep workload starts closed without falling back to legacy grants, while observe and cleanup paths remain unblocked. The canonical evaluator reads the approved policy only when a canonical-gated operation invokes it. The canonical mode is an evaluated and audited policy boundary that admits only starts whose required policy and network rules pass verification.

mermaid
sequenceDiagram
    participant Admin as Platform administrator
    participant Projects as Projects & Config
    participant Caller as Internal Environment code
    participant Client as Policy source client
    participant Compiler as Finite-network compiler
    opt Platform Policy write gate is enabled
        Admin->>Projects: PUT /api/policies/platform (expected revision, artifact)
        Projects->>Projects: Check current authority and head; validate artifact
        Projects->>Projects: Commit pending preparation only
        Projects-->>Admin: Preparation receipt (pending/null)
    end
    Caller->>Client: ReadAsync()
    Client->>Projects: GET /internal/policy-source/platform (mTLS)
    Projects-->>Client: Committed artifact with pending/null admission
    Client->>Client: Check TLS, bounds, envelope, and artifact hashes
    Client-->>Caller: Pending observation
    Caller->>Compiler: CompileCandidate(artifact, source ID, revision)
    Compiler-->>Caller: Unadmitted candidate or coded failure
    Caller->>Compiler: CompileSystemOnlyCandidate(artifact, source ID, revision)
    Compiler->>Compiler: Validate the complete original artifact
    Compiler-->>Caller: Allowlist candidate with System destinations or coded failure
    Note over Client,Compiler: Source client is off by default; enabling it sends no startup request
    Note over Caller,Compiler: Candidate compilation has no provider effect
    Note over Projects,Client: Preparations are not source authority and do not reach providers
    Note over Caller,Projects: This source-read flow makes no reservation and issues no Kubernetes write

The System-only candidate is input for the later admission barrier. This flow does not install the barrier or admit a policy. A later commit must wait until the barrier is installed on every affected target.

Full policy-set proof ​

Environment can capture a source-only proof of the complete policy set that can affect AgentHost. The capture reads every networking.k8s.io/v1 NetworkPolicy and cilium.io/v2CiliumNetworkPolicy in the AgentHost namespace, plus every CiliumClusterwideNetworkPolicy. It reads through all pages without a label or name filter. The capture reads the namespace UID and binds the lists to a supplied physical target, sealed epoch, guard digest, profile digest, evaluator version, and System-only ceiling.

The inventory hashes all listed objects, including policies whose selectors do not match AgentHost. Object keys are canonical, array order is retained, and duplicate identities or deleting objects fail the capture. A list resourceVersion is diagnostic data. The snapshot hash does not act as a cross-kind Kubernetes clock.

The evaluator models the union of selected Kubernetes and Cilium egress allows. It supports exact pod and namespace identities, numeric TCP and UDP ports, exact Cilium endpoint and FQDN destinations, and exact Cilium denies. It treats omitted peers or ports as wildcards. Selected unsupported semantics, extra destination labels, CiliumNetworkPolicy namespace mismatches, and namespaced CiliumClusterwideNetworkPolicy objects stop the proof. Disjoint selectors are ignored only after the selector itself is validated.

AgentHost egress must remain inside the System-only ceiling:

  • exact protected System destinations on TCP 443;
  • kube-dns on UDP and TCP 53;
  • Environment, Events & Sessions, Identity Broker, Orchestrator, and Projects & Config on TCP 8443;
  • Identity Broker on TCP 8444; and
  • the shared identity-broker Gateway in agentweaver-gateway with label gateway.networking.k8s.io/gateway-name=identity-broker on TCP 443.

The proof requires default-deny egress across the full admitted AgentHost population; a narrowed selector never satisfies default-deny. A Cilium deny subtracts an allow only when its source selector covers the full allow (full-population or identical narrowed source). It rejects any remaining combined allow outside the ceiling. DNS narrowing does not make a broader packet allow safe, and a CIDR deny cannot subtract an FQDN or endpoint grant. An extra exact grant in an ordinary input such as agenthost-model-egress blocks the proof.

The optional proof bundle is under deploy/k8s/rbac/platform-egress-proof/. It creates the environment-platform-policy-reader ServiceAccount with only the three policy list operations, get on namespace agentweaver, and named get on CiliumNetworkPolicy/agenthost-platform-egress. It gives the separate environment-platform-egress-writer ServiceAccount only get and update on CiliumNetworkPolicy/agenthost-platform-egress. It also defines the private environment-platform-policy-worker Service, the read-only secret and CA mounts, the CiliumNetworkPolicy routes between Projects & Config, the Worker, the Reader, the Writer, and PostgreSQL, and the ValidatingAdmissionPolicy/environment-platform-policy-sealed-epoch definition. The ValidatingAdmissionPolicyBinding that seals policy writes lives separately under deploy/k8s/rbac/platform-egress-proof/seal/ so peer setup completes before the epoch is sealed. Neither bundle is part of the default Kustomize apply set. Because Kubernetes does not invoke a ValidatingAdmissionPolicy on writes to ValidatingAdmissionPolicy or ValidatingAdmissionPolicyBinding objects, platform-policy-fence.yaml contains no self-match rules; protecting the seal relies on existing authorized cluster-administrator RBAC boundaries. Checked-in ClusterRole and ClusterRoleBinding manifests grant none of the workload, proof, or migration identities effective write access (including via wildcards or ServiceAccount group bindings) to ValidatingAdmissionPolicy/environment-platform-policy-sealed-epoch or ValidatingAdmissionPolicyBinding/environment-platform-policy-sealed-epoch. Operators verify live cluster grants (including wildcard and group-derived bindings) before relying on the seal, and point-in-time checks or snapshots do not prove continuous enforcement.

When the optional proof bundle is explicitly installed, the reader, writer, and isolated preparation worker run in three separate Pods using role-specific early host startup (Environment:PlatformPolicyProof:Role set to Reader, Writer, or Worker) with only their health endpoints (Kestrel:Endpoints:Https:Url on port 8443) and private proof routes (Kestrel:Endpoints:PlatformPolicyReaderPeer:Url on port 8444, Kestrel:Endpoints:PlatformPolicyWriterPeer:Url on port 8445, and Kestrel:Endpoints:PlatformPolicyProof:Url on port 8444), without legacy Environment lifecycle services. Each Pod uses its own ServiceAccount, short-lived projected token, and Kubernetes SelfSubjectReview check before proof work and after token rotation. The Reader uses no database connection. The Worker and Writer each run a distinct narrow database authority check (VerifyPlatformPolicyWorkerAuthorityAsync and VerifyPlatformPolicyWriterAuthorityAsync) that rejects the schema owner and the ordinary Environment runtime principal. An operator creates the distinct agentweaver-id-environment-platform-policy-worker and agentweaver-id-environment-platform-policy-writer database roles, and the schema owner provisions their exact reviewed grants with dotnet Agentweaver.Environment.dll --provision-platform-policy-peer-roles using Environment:Migration:PlanSha256. The ordinary agentweaver-id-environment role is unchanged. The worker calls the reader and writer over mutual TLS using two private calls (Read evidence and Apply saved operation). At the receipt boundary, EvaluateForReceipt requires a universal Kubernetes NetworkPolicy egress default-deny witness (podSelector: {}, explicit Egress in policyTypes, and no egress allow rules) without subtracting unaccepted Cilium denies. Reserved writes and abort-handoff markers use PlatformPolicyDocumentGuard to preserve metadata outside the render. Cross-schema SECURITY DEFINER routines (environment.require_current_platform_policy_receipts and environment.retire_platform_policy_claims_on_commit, granted only to the Projects schema owner) fence against the enrolled target singleton and retire active claims atomically when invoked by the narrow SECURITY DEFINER owner commit operation projects_config.commit_guarded_platform_policy. Database triggers reject direct runtime writes to protected Platform Policy heads, revisions, audit, outbox, idempotency receipts, and initial or updated freeze Committed rows while preserving Project Policy writes and freeze aborts.

The normal Environment Deployment runs the standard Environment role. The separate proof roles require the optional bundle; no parked initializer forms part of normal startup. The loopback CRL listener described below serves certificate-revocation data for the provider-host relay.

When ProjectsConfig:PlatformPolicyProof:Tls is enabled, PUT /api/policies/platform with a preparationId triggers POST /internal/egress/platform-policy/prove on the dedicated Platform Policy Worker (Environment:PlatformPolicyProof:ProjectsTls and Kestrel:Endpoints:PlatformPolicyProof:Url) over its pinned mutual TLS channel before calling projects_config.commit_guarded_platform_policy. The Worker verifies its service-account identity and reads the committed Platform head over its head-only PlatformPolicySourceHttpClient identity (404 means no first head; other errors fail closed), validates the artifact hash, compiles the System-only candidate, freezes the enrolled target via FreezeEnrolledTargetAsync, and runs PlatformPolicyProofCoordinator.ProveAsync. If proof fails or no target is enrolled, Projects & Config rejects the commit without advancing the Policy head. After the guarded commit succeeds (or on exact replay of the current committed head), Projects & Config triggers POST /internal/egress/platform-policy/reconcile on the Worker, which reads the committed Policy with any Environment:NetworkPolicy:Cilium:DeployTimeModelHosts into Allowlist mode, delegates the update to the dedicated Writer peer, and reports Applied or Converged only when independent readback matches IntentHash and SourceHash.

mermaid
sequenceDiagram
    participant E as Preparation worker
    participant DB as Environment PostgreSQL
    participant R as Policy reader Pod
    participant W as Policy writer Pod
    participant K as Kubernetes API
    participant V as Full policy-set evaluator
    E->>DB: Persist provider reservation
    DB-->>E: Current reservation
    E->>E: Verify worker, reader, and writer projected identities
    E->>DB: Compare complete reservation and acquire hold under target lock
    DB-->>E: Saved current reservation and durable hold
    E->>R: Read evidence through the one private read call
    R->>K: Paged raw inventory and independent named GET
    K-->>R: Namespace UID, inventories, and named object
    R-->>E: Exact bounded evidence
    E->>V: Substitute the exact System-only render
    V-->>E: Safe candidate or coded failure
    E->>E: Check serialized current and candidate snapshot sizes
    E->>DB: Pin pre-write, request, and expected readback digests
    E->>W: Apply the saved operation through the one private apply call
    W->>K: Validate and send the reserved UID and resourceVersion PUT
    K-->>W: Reserved write result or conflict
    W-->>E: Bounded saved-operation result
    E->>R: Independent readback through the same read call
    R->>K: Named GET and complete fresh inventory
    K-->>R: Observed object and complete snapshot
    R-->>E: Exact observed evidence
    E->>V: Evaluate the observed combined set
    V-->>E: Safe observed set or coded failure
    E->>E: Check serialized observed snapshot size
    E->>DB: Insert immutable per-target receipt and snapshot only for active freeze evidence
    DB-->>E: Durable current receipt
    Note over E,K: An inventory, readback, or epoch conflict creates no successful receipt

Provider host access requests ​

When a PlatformAdmin or project Owner saves a platform or project BYOK model provider draft, Projects rechecks current membership, qualifying role, project state, and expected revision under its local credential-publication authority lock. Projects commits the immutable provider revision and a bound host request (projects_config.model_provider_host_requests) in the same transaction.

A single-slot Projects relay claims one pending request at a time when ready to send, keeps the lease live during the send and completion, and sends the request over pinned mutual TLS (POST /internal/egress/host-requests) to Environment. When enabled via the --provider-host-request overlay, each service validates the peer certificate against /var/run/service-backend-ca/ca.crt and fetches the signed DER CRL from its loopback Kestrel listener (http://127.0.0.1:8445/ca.crl), backed by the directory-mounted service-backend-crl ConfigMap. Environment stores an immutable receipt (environment.provider_host_request_receipts) in requested state. Projects marks the request delivered only when the receipt matches every bound field under the live lease.

GET /api/v1/platform/egress/destinations requires unbound PlatformAdmin authority. Environment pages its immutable receipts in stable order and queries Projects (POST /internal/egress/host-requests/proof) over pinned mutual TLS. Environment skips stale rows from superseded revisions or inactive projects and advances the cursor past the last examined row. If Projects proof is unavailable, Environment returns 503 with Cache-Control: no-store and does not advance the cursor.

mermaid
sequenceDiagram
    participant Saver as PlatformAdmin or Project Owner
    participant Admin as PlatformAdmin
    participant Projects as Projects & Config
    participant Relay as Projects Outbox Relay
    participant Env as Environment
    Saver->>Projects: Save BYOK provider (create or update)
    Projects->>Projects: Lock current authority and expected revision
    Projects->>Projects: Commit revision and pending host request
    Projects-->>Saver: Saved metadata (egress.deliveryStatus = pending)
    Relay->>Env: POST /internal/egress/host-requests (pinned mTLS)
    Env->>Env: Save immutable receipt (state = requested)
    Env-->>Relay: Exact receipt
    Relay->>Projects: Mark Delivered under live lease
    Admin->>Env: GET /api/v1/platform/egress/destinations
    Env->>Projects: POST /internal/egress/host-requests/proof (pinned mTLS)
    Projects-->>Env: Current-scope proof per requestId
    Env-->>Admin: Current requested destinations (or 503 on proof outage)

PostgreSQL binds a nonexpiring hold to the current reservation for one logical target ID. Reservation and hold inserts use the same target lock. A new reservation is rejected while a hold exists. The coordinator compares the provider target ID with the frozen target and reservation before acquiring the hold. Under the target lock, it compares every persisted reservation field and the ordered policy destinations before returning a hold or replaying a receipt. An exact retry uses the saved reservation.

The proof factory creates reader and writer clients for one HTTPS API origin with path /, using the same CA snapshot and separate token files. Both clients reject redirects. The factory rejects token paths that normalize to the same path. A non-root origin fails before hold acquisition. Historical receipts for non-root origins remain available through ReadCurrentReceiptAsync; a new root origin has a different target ID and cannot reuse the old reservation.

Read stored run egress ​

Call GET /api/v1/runs/{runId}/egress through the Gateway to read stored attributed outbound traffic for one run. Gateway sets Cache-Control: no-store early and forwards the caller bearer token and optional X-Agentweaver-Tenant header to Orchestrator (GET /api/runs/{runId}/egress). Use the agentweaver run egress guide for CLI authentication, one-page output, and cursor handling.

Orchestrator validates the caller token, scopes, and explicit tenant_id, project_id, and run_id bindings, rejects purpose-bound or duplicate-claim tokens, and reads current authority from Projects & Config. The caller needs either:

  • api.read and a current project or tenant ReadProjects grant with a positive revision; or
  • an unbound token with api.read and projects.admin, plus the current Platform/default ReadPlatformRuntimeDefaults grant with a positive revision.

Orchestrator resolves at most two visible matches for runId in the selected tenant's accepted_runs table, ignoring hidden duplicates in projects the caller cannot read. Zero or multiple visible matches return 404 run_not_found.

Orchestrator forwards the original caller bearer and validated tenant selector to Environment (GET /api/projects/{projectId}/runs/{runId}/egress). Environment rejects duplicate X-Agentweaver-Tenant headers, revalidates the token claims and current Projects & Config authority, and joins environment.sandbox_egress_flows_attributed with environment.sandbox_owner_mappings filtered by the authorized tenant, project, and run.

Responses return Cache-Control: no-store, coverage: "Unavailable", delayedUntil: null, and attributed records ordered by first_seen DESC, flow_id DESC. Each record contains nullable host and address, port, verdict, firstSeen, lastSeen, and count. Raw workload labels, owner fingerprints, flow IDs, and unattributed rows are excluded. Page size (limit) defaults to 50 and accepts 1–100. The opaque nextCursor is bound to the authorized scope, sort order, page size, and anchor.

mermaid
sequenceDiagram
    participant Caller as Caller
    participant Gateway as Gateway
    participant Orch as Orchestrator
    participant Projects as Projects & Config
    participant Env as Environment
    participant DB as Environment PostgreSQL
    Caller->>Gateway: GET /api/v1/runs/{runId}/egress
    Gateway->>Gateway: Set no-store; validate bearer
    Gateway->>Orch: GET /api/runs/{runId}/egress (bearer, tenant)
    Orch->>Projects: GET /api/authorization/context
    Projects-->>Orch: Current tenant, grants, bindings
    Orch->>Orch: Resolve <= 2 visible runs in accepted_runs
    Orch->>Env: GET /api/projects/{projectId}/runs/{runId}/egress (bearer, tenant)
    Env->>Projects: GET /api/authorization/context
    Projects-->>Env: Current tenant, grants, bindings
    Env->>DB: Query attributed flows joined on owner_fingerprint
    DB-->>Env: Bounded page (first_seen DESC, flow_id DESC)
    Env-->>Orch: RunEgressPage (no-store, coverage Unavailable)
    Orch-->>Gateway: RunEgressPage (no-store)
    Gateway-->>Caller: 200 RunEgressPage (no-store)

The logical ID includes the configured Kubernetes API origin, namespace, and policy name. Different API origins can refer to the same physical cluster; the database fence does not recognize those aliases. The saved physical target, namespace UID, registry revision, and preparation are supplied bindings, not a trusted enrollment registry. A future authenticated terminal protocol is needed to release a hold.

The coordinator checks the serialized UTF-8 snapshot size for the current inventory and rendered candidate before the reserved PUT. The candidate size includes metadata retained from the named object and inventory. The limit is 1,048,576 bytes. An oversized snapshot returns policy_semantics_unsupported and retains the hold without a PUT. The coordinator checks the independently captured snapshot again after the PUT and compares the named read with the policy list element. Growth beyond the limit retains the hold and writes no receipt. Retry with the identical reservation; the provider uses the reserved UID and resourceVersion. A changed set returns policy_readback_mismatch; a stale or competing hold returns policy_fence_conflict.

Receipt rows are append-only and unique per hold and target. An identical retry returns the current receipt. A changed input, stale hold, or different snapshot does not return success. The source-only receipt check requires a current receipt and retained hold for each supplied target. The supplied list is not an authoritative target registry. The check is not connected to the canonical Platform Policy commit.

This source slice does not register an HTTP route, install the optional fence, write a cluster policy, connect the all-target gate to Projects, or prove packet enforcement. Packet evidence and policy activation remain separate work.

The existing provider capability check still requires exact-host support for Allowlist, and private-range exclusions remain a separate provider safety gate.

The finite-network-v1 profile accepts only its fixed manifest and module and one policy/data.json file. The file names a trusted, versioned System catalog. The validator rejects changed catalog entries, duplicate destinations, unknown fields, and other modules or data files.

The composable-domains-v1 profile adds the fixed actions and platform_network domains. It keeps action data in policy/actions/data.json and network data in policy/data.json. Its explicit Environment candidate compiler reads only the network domain to build an egress candidate; the candidate hash still covers the full artifact. The existing compiler entrypoints keep accepting only finite-network-v1. Neither profile changes the deployed policy path or enables a policy write. DNS and private-address checks remain separate from compilation; the compiler does not resolve DNS.

The same Environment owner manages workspace-volume lifecycle routes and registers the Azure Files CSI Storage provider. This article covers only egress; the foundation overview summarizes volume lifecycle, pinned provider bindings, and Replace cleanup. See the Environment deep dive for the combined placement path.

The same owner schema contains the Sandbox lease state. The placement read verifies its active lifecycle, full owner tuple, provider reference, lease revision, expiry, and separate provider/current fences. It rereads the lease after the final awaited authorization check. Profile lookup matches that exact provider reference against server configuration; it does not deliver a configure nonce. Public placement/profile reads keep the existing WriteProjects gate. The separate run-bound read-only lookup is integration work, not an egress mutation permission.

Ownership and operation ​

For provider selection and Environment settings, see the provider configuration guide and runtime configuration reference.

EnvironmentEgressManager is the operation entry point. Each apply, verify, revoke, or reconciliation reads the current caller from Projects & Config at GET /api/authorization/context; authorization and run-selection responses must be Cache-Control: no-store. The caller token is sent only to Projects & Config, whose resource-server authentication validates the token audience and purpose; it is not stored in the policy or provider pin. An optional tenant selector is forwarded for Projects & Config to validate. Any token-bound tenant must match the environment owner, and any bound project/run must match the requested owner. An unbound project-level grant is still intersected with the exact Environment tenant/project/run and immutable admitted selection.

The consumer uses current WriteProjects on the target project for Apply/Verify/Revoke/Reconcile. It does not use ReadProjects as mutation authority; ReadProjects remains metadata inspect/describe authority only. Apply, Verify, and Apply reconciliation also require the separate positive ReadRunSelection grant to retrieve the admitted run selection. That grant is not implied by WriteProjects; the Projects selection endpoint independently enforces its existing Orchestrator scope/role. If the caller has project write authority but lacks run-selection access, the operation fails explicitly before Kubernetes access. Revoke and Revoke reconciliation need only WriteProjects and the Environment owner identity; they do not read or compile the run selection.

ProjectsConfig:BaseAddress must be an absolute HTTPS URI without user info, query, or fragment. The authenticated Projects and Kubernetes clients disable automatic redirects and reject every 3xx response, so credentials are not forwarded to a redirect target.

Every operation fetches fresh context before effects. Apply, Verify, and Apply reconciliation recheck it after selection retrieval and after Kubernetes readback, before pinning or recording reconciliation; Revoke and Revoke reconciliation recheck it after the tombstone readback. A changed membership, binding, or effective grant rejects the callback and cannot mark the Environment ready.

EnvironmentOwnerIdentity carries the tenant, project, run, and environment IDs needed to bind policy operations to the current Projects context and selection. EnvironmentGenerationFence carries that owner identity and its LifecycleGeneration. The Cilium API separately receives PolicyGeneration and ExpectedPreviousPolicyGeneration; these fence the policy resource and must not be conflated with the Environment lifecycle generation. Policy generations are positive, owner-CAS-checked values and need not be contiguous.

The Environment host, lifecycle store, and environment schema are owned by Agentweaver.Environment. EnvironmentGenerationFence.LifecycleGeneration is the owner-controlled CAS fence; it is distinct from every Cilium policy generation and Storage resource/data generation. Registration and lifecycle advancement use an explicit expected generation and idempotency key. Network effects reserve before provider work, then complete only against the current owner fence. A stale callback remains unresolved and blocks further effects until the active owner verifies the exact current provider object and records that observation through /api/network-egress/reconcile. Reconciliation requires current target-project write authority, an active owner fence, matching operation/resource identity, and exact generation/hash/revocation readback; Apply reconciliation also requires the separately admitted run selection. It cannot revive an unknown, released, stale, or foreign owner.

Verify also requires the owner's latest verified policy generation to match the requested generation, with no reserved or unresolved network effect. A provider readback alone cannot make an untracked generation ready. Failed or stale operations that never started a provider call do not block release; operations with possible provider-state changes remain unresolved until exact reconciliation.

The read-only POST /api/network-egress/verify owner contract lets Orchestrator ask Environment to verify current egress using the caller's existing bearer. The request carries the complete lifecycle fence, policy generation, and expected authorized run-selection ContextRevision. Environment compares that revision with the selection it freshly compiles, verifies the exact owner-recorded generation and Cilium object, and refreshes authorization and selection after provider readback. A receipt returns the same complete fence, generation, ContextRevision, and policy IntentHash; Orchestrator rejects a receipt that differs from any requested binding. Missing owners, stale fences, unverified generations, changed authorization or selection, and unavailable dependencies are distinct fail-closed outcomes. This request is read-only: it does not apply, revoke, reconcile, or otherwise mutate egress, and the receipt is not a live-action or dispatch authorization. Dispatch wiring remains a separate Orchestrator integration.

The owner producer is registered in the host, but the existing run/environment registration producer is not yet bound to it. No public lifecycle-registration endpoint exists: Apply and Bind cannot create or default an Environment owner, so unknown Environments remain denied until the producer integration is supplied.

The compiler checks platform baseline ∩ project narrowing ∩ admitted run needs. Rules carry purpose, destination kind, FQDN pattern or CIDR/Kubernetes service, port, and protocol. Wildcards and network ranges are normalized, and a project or run cannot widen its parent set. Malformed and unrepresentable rules fail closed. FQDN rules require both admitted TCP/53 and UDP/53 rules to the configured kube-system/kube-dns service. Direct FQDN egress to Azure Key Vault or Entra endpoints—and wildcard ancestors broad enough to include those destinations—is rejected; agent credentials must not be sent directly to those services.

Previously persisted egress rules with only host, port, and protocol are read as PublicHttps FQDN rules. Their old effective allow list is retained as the baseline, narrowing, and run needs, so this compatibility path cannot widen access. PublicHttps requires L7 mediation; this Cilium-only slice therefore fails closed for those legacy selections instead of treating unclassified destinations as ordinary L3/L4 egress.

The selected layered Network Policy binding must include exactly one L3/L4 provider. Cilium options are accepted only when provider ID, adapter version, schema version, and options revision match the immutable selection. The provider must advertise all capabilities required by the compiled intent before any Kubernetes mutation. Cilium supports the compiled L3/L4/FQDN constraints here; it does not supply L7 mediation for PublicHttps or RemoteMcp, so those requirements fail rather than becoming a blanket HTTPS rule. This slice contains no L7 adapter; if the immutable selection contains an L7 candidate, the operation also fails explicitly rather than silently ignoring or pinning an unapplied layer. The Environment connection and parser source boundary is described in Remote MCP connections. It does not add L7 mediation or prove a remote MCP request.

The Cilium adapter assigns a hashed environment/owner selector and derives its resource name from the full owner tuple. It applies a positive policy generation against the explicit expected predecessor and observed Kubernetes resource version, then verifies the exact policy object, selector, spec, intent hash, and generation on readback. It pins through the existing ProviderResolver.PinNetworkPolicy only after that verification. Revoke advances the generation to a verified empty-egress egressDeny: [{}] tombstone instead of deleting the policy, so a delayed apply cannot recreate a revoked generation—even when revoke is the first observed operation. The operation's current request trace records the selected layer/provider/adapter version and observed intent/resource generations, verification, and revoke state. It does not tag the owner tuple, bearer token, destination rules, or raw provider options. ReadyForDispatch reports policy-object verification and L3/L4 pinning only; it is not permission to start a model run. Any automated/model-run execution must separately validate its existing Orchestrator action grant. DatapathEnforcementVerified remains false because an API readback is not datapath evidence.

BuildTest uses separate Cilium policies for command and output-collector Pods. Each policy binds the stable operation ID, role, owner, and current Sandbox/Workspace fences; neither policy permits egress. Environment persists the policy binding and checks its UID and specification before it releases the corresponding Pod scheduling gate. The policy-object readback is evidence, not proof that a deployed Cilium datapath enforced the policy.

The credential-less sandbox proposal extends this layered design with a required trusted L7 gateway for that mode, not a new credential-sourcing provider. L3/L4 enforcement must force protected traffic through it and deny guest credential acquisition and direct bypass. The gateway independently validates current action/resource authority before trusted-side credential injection. Proxy environment variables and static allow lists are insufficient. The current Cilium-only candidate has no L7 adapter and cannot report credential-less readiness; existing generation, owner fences, and explicit unsupported behavior remain unchanged.

mermaid
sequenceDiagram
    participant O as Orchestrator
    participant E as Environment manager
    participant P as Projects & Config
    participant C as Egress compiler
    participant K as Kubernetes Cilium API
    participant R as ProviderResolver
    opt Orchestrator requests current egress evidence
        O->>E: POST /api/network-egress/verify with caller authorization, fence, generation, ContextRevision
        E->>P: Read fresh authorization and immutable project/run selection
        P-->>E: Current grants and selection revision
        E->>E: Compare requested ContextRevision and exact owner fence
        E->>C: Compile current admitted selection
        C-->>E: Purpose-grouped intent or explicit failure
        E->>E: Require latest owner-recorded policy generation
        E->>K: Read and verify the exact policy object
        K-->>E: Verified policy object or explicit failure
        E->>P: Recheck current authorization and selection
        P-->>E: Same grants and selection revision or changed outcome
        E-->>O: No-store receipt bound to fence, generation, revision, and intent hash
    end
    E->>P: GET authorization context (fresh validated caller, optional tenant)
    P-->>E: Current grouped permission and revisions (no-store)
    E->>E: Require target-project WriteProjects and owner intersection
    opt Apply, verify, or reconcile
        E->>E: Require separate ReadRunSelection grant
    E->>P: GET immutable project/run selection (no-store)
    P-->>E: Baseline, narrowing, admitted needs, layered providers
    E->>C: Compile baseline ∩ narrowing ∩ run needs
    C-->>E: Purpose-grouped intent or explicit failure
    E->>P: Recheck fresh context before Kubernetes effect
    P-->>E: Same current membership and effective grants
    end
    alt Apply or verify
        E->>K: Apply generation with resourceVersion fence
        K-->>E: Applied policy object
        E->>K: Read and verify exact selector, spec, hash, and generation
        K-->>E: Verified Kubernetes object; datapath remains unproven
        E->>P: Recheck fresh context after async Kubernetes work
        P-->>E: Same current membership and effective grants
        E->>R: Pin L3/L4 resource and applied intent generation
        R-->>E: Pinned binding or explicit failure
        E-->>E: Report policy readiness only after verified pin
    else Revoke
        E->>K: Replace with next-generation deny-all tombstone
        K-->>E: Tombstone object
        E->>K: Read and verify owner, empty egress, hash, and generation
        K-->>E: Verified revocation fence or explicit failure
        E->>P: Recheck fresh WriteProjects authority
        P-->>E: Same current membership and effective grants
    else Reconcile
        E->>K: Read and verify the operation's exact current policy/tombstone
        K-->>E: Verified generation, hash, owner selector, and effect
        E->>P: Recheck WriteProjects and ReadRunSelection
        P-->>E: Same current membership and effective grants
        E->>E: Record reconciliation under the current owner fence
    end

Integration and evidence boundary ​

Runtime bootstrap profiles ​

The separate runtime bootstrap profile registry belongs to Environment. A static profile identifies HTTPS configure and observation endpoints for an exact tenant, project, run, Environment, and Sandbox resource UID/generation. The optional global Environment:RuntimeBootstrap:DefaultSourceProfileId also permits a source derived from the authorized lease and observed receiver configure URL, with the Orchestrator owner /internal/runtime/observations. Static source lookup takes precedence. Both paths require the existing immutable replacement and its actor, selection, hash, endpoint, and lease checks. Unknown profiles or a different placement fail explicitly.

The runtime profile route uses the canonical EnvironmentSandboxManager placement reader. Its callback retains the actual lease transaction while it reads the current Orchestrator work item and resolves the registered profile. It does not request the full runtime registration recursively or dispatch provider effects. The internal route requires current ReadRunSelection for the exact signed run. The public placement route still requires WriteProjects. Run-bound tokens do not gain public write permission.

A profile match does not create a lease, prove current owner authority, or authorize an SDK session. Delivery must verify the Identity pending nonce and fresh Projects, Orchestrator, and lease state before and after transport. The local integration harness covers nonce delivery and native SDK source accounting. It does not prove cloud deployment. See the separate runtime credential contract.

The Environment-owned Sandbox composition propagates these selector labels into the owner-specific Sandbox template and checks them on the actual Pod. The Network provider remains responsible only for Cilium policy; it does not create or own Sandbox resources. See the Environment Sandbox architecture for that separate composition. Kubernetes RBAC, workload identity and run/environment registration are separate prerequisites, not results of applying a Cilium policy. Policy verification proves only that the expected Kubernetes object was persisted and observed. Real datapath probes and live cluster evidence are reserved for the separate network-acceptance work; no probe or deployment is performed by these tests.

The focused compiler and fake-Kubernetes tests cover FQDN wildcard and CIDR intersection, ports/protocols, widening rejection, exact selector isolation, generation races, and apply/readback failures. They cover positive and negative WriteProjects and ReadRunSelection checks, unbound project authority narrowing, stale authorization callbacks, Cilium option and capability negotiation, absent-policy revocation fences, and the explicit L7 limitation. The testing guide lists the command and what the tests cannot prove.

Platform egress provider and reconciler ​

Projects exposes the private route for the canonical Platform artifact. Its response has pending admission and a null checkpoint. The opt-in Environment client validates that response and compiles an unadmitted candidate. It does not register an admitted source or connect the reconciler to a provider.

The parts are:

  • IPlatformEgressPolicySource returns the admitted snapshot: the source ID, the source revision, the source hash, the compiler version, the checkpoint, the mode (PublicHttps or Allowlist), and the exact hosts. If no admitted snapshot exists, it returns null.
  • PlatformEgressReconciler reads the snapshot and applies it to the selected IPlatformEgressProvider. It fails closed. If the source is absent, cannot be read, or is invalid, or if the provider cannot apply the mode, the reconciler does not apply or remove provider rules. It returns Failed with policy_source_unavailable, policy_source_invalid, or capability_unavailable. It never uses a table, the configuration, or a default mode in place of the source.
  • The reconciler reads the source again immediately before an apply. If the snapshot changed, it uses the new snapshot. A change to the source hash alone creates a new generation, even when the mode and the hosts are the same.
  • The provider object stores the generation, the intent hash, and the source hash. The reconciler therefore keeps no local state. Two replicas are fenced by the Kubernetes object UID and resourceVersion.
  • CiliumPlatformEgressProvider owns one object: CiliumNetworkPolicy/agenthost-platform-egress in the AgentHost namespace, with the selector agentweaver.io/workload: agenthost. The deploy creates the object with a DNS-only spec only when it is missing. The deploy reads the exact object first, does not write an existing object, and keeps the seed outside the Kustomize bundle. If another create wins the race, the deploy treats AlreadyExists as a no-op. Other read or create errors stop the deployment. The provider only reads and replaces the object. If the object is missing, the apply fails with policy_object_missing.
  • A separate administrator-applied Role grants the environment ServiceAccount get, update, and patch on that named policy. Kubernetes combines this grant with existing Environment permissions. The bundle stays outside default workload deployment and does not select or activate Cilium. The provider uses the named grant to read and replace the policy; deployment continues to create the DNS-only seed only when the policy is missing.
  • PublicHttps renders one toCIDRSet rule for 0.0.0.0/0 and ::/0 on TCP 443, with the excluded ranges in except. Allowlist renders DNS matchName rules and toFQDNs matchName rules for each exact host on TCP 443. Both modes add an egressDeny rule for the excluded ranges. An empty Allowlist renders no allow rule.
  • Cilium allow rules from different policies add together. Deny rules take precedence over allow rules in every policy. The deploy-managed AgentHost egress policies stay in place, so Allowlist does not narrow egress until the deploy removes those policies (#2640). The egressDeny rule for the excluded ranges applies to the selected AgentHost pods even when another policy allows those ranges.
  • GetStatusAsync reads the object back, renders it again, and compares the spec and the hashes. A match gives Accepted. Accepted proves only the Kubernetes object. It does not prove enforcement in the datapath.
  • The provider advertises egress.exact-host only when ExactHostVerifiedForKata is true. That value stays false until the Kata spike (#2633) and the install probe prove exact-host rules. While it is false, the reconciler refuses an Allowlist snapshot.
mermaid
sequenceDiagram
    participant R as Reconciler
    participant S as Policy source
    participant C as Cilium provider
    participant K as Kubernetes API
    R->>S: Read admitted snapshot
    alt No snapshot, read error, or invalid snapshot
        R-->>R: Failed, no provider change
    else Snapshot is valid
        R->>C: Read status
        C->>K: Read agenthost-platform-egress
        alt Status matches intent hash and source hash
            R-->>R: Converged
        else Different or not applied
            R->>S: Read snapshot again
            R->>C: Apply generation + 1
            C->>K: Replace with UID and resourceVersion preconditions
            K-->>C: Stored object
            C-->>R: Accepted or Failed
        end
    end
    Note over C,K: Environment Role grants get, update, and patch on the named policy; deploy creates the seed only when missing
    Note over R,K: This reconciler flow is not registered

Durable apply reservations ​

PlatformEgressApplyReservationStore saves the exact provider request before a caller sends a Kubernetes write. Each append-only row binds the Kubernetes target, source epoch, policy generation, source ID and revision, policy hashes, full policy request, object UID, and observed resourceVersion. A target and idempotency key name one exact request. Multiple attempts can share a target, source epoch, and generation only when source identity, revision, hashes, and policy content match. Each attempt keeps its own object UID and resourceVersion.

An exact retry returns the saved reservation. Reusing its idempotency key with different request content fails. A new policy generation must advance the target's generation. The source epoch cannot move backwards, and one source epoch and generation cannot identify different source or policy content. After a restart, retrieve the reservation by target ID and idempotency key before retrying.

CiliumPlatformEgressProvider.ApplyReservedAsync loads the saved request and rejects it when a newer reservation exists. Before it replaces the object, it checks the target, UID, source epoch, generation, and resourceVersion. The Kubernetes PUT carries both UID and resourceVersion. If a newer write updates the object first, Kubernetes rejects an older delayed PUT because its resource version is stale. A reservation cannot cancel a Kubernetes request that is already in flight.

The legacy EnvironmentEgressManager calls to Cilium ApplyAsync and RemoveAsync do not use the hold fence. A hold therefore does not block all changes to the target or establish a packet-level barrier.

If Kubernetes stores a request but its response is lost, retry the same reservation. The provider reads the object and accepts it only when the UID, source epoch, generation, hashes, and policy spec match. Do not refresh the saved resourceVersion on that retry. If an already-issued older request wins first and makes the saved version stale, read the current object and create a new attempt with a new idempotency key. The store accepts that attempt only when its source and policy content match the existing source epoch and generation.

The source epoch is an ordering token supplied by the caller. It does not prove that the caller read the current source. The reservation store and reserved apply path are not registered or called by the service. They do not install a System-only barrier, commit a policy preparation, or admit a policy. The client still returns a pending observation and an unadmitted candidate. The deployment owns the DNS-only seed and AgentHost egress policies; those paths remain separate from the candidate.

The client integration test reads the actual Projects route and PostgreSQL artifact through the production client, then checks candidate compilation. Reconciler tests use a fake policy source and a fake Kubernetes store. They include a conformance kit that every IPlatformEgressProvider must pass. Datapath enforcement requires separate live-network evidence.

Trade-offs and limits ​

Intersecting intent prevents project settings from widening platform egress, but cannot express or prove application-layer mediation through the Cilium-only adapter. A policy generation is a control-plane observation, not an observed network flow. Keep L7 requirements and native datapath verification explicit.

Use the Environment runtime view to connect egress to placement and the deployment view to locate controller, network and identity prerequisites.