diff --git a/Cargo.lock b/Cargo.lock index 3054921..00330f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2479,6 +2479,7 @@ dependencies = [ "sendbox-boundary", "sendbox-config", "sendbox-core", + "sendbox-governance", "sendbox-policy", "sendbox-protocol", "sendbox-runtime", @@ -2518,6 +2519,7 @@ version = "0.2.7" dependencies = [ "sendbox-config", "sendbox-core", + "sendbox-governance", "sendbox-security", "serde", "serde_json", @@ -2565,6 +2567,7 @@ dependencies = [ "sendbox-agent", "sendbox-config", "sendbox-core", + "sendbox-governance", "sendbox-host", "sendbox-mcp", "sendbox-policy", @@ -2572,11 +2575,13 @@ dependencies = [ "sendbox-registry", "sendbox-runtime", "sendbox-secrets", + "sendbox-security", "serde", "serde_json", "sha2 0.11.0", "tempfile", "tokio", + "zeroize", ] [[package]] @@ -2612,6 +2617,8 @@ dependencies = [ "reqwest", "sendbox-config", "sendbox-egress", + "sendbox-governance", + "sendbox-protocol", "sendbox-runtime", "sendbox-secrets", "serde", @@ -2689,6 +2696,20 @@ dependencies = [ "url", ] +[[package]] +name = "sendbox-governance" +version = "0.2.7" +dependencies = [ + "proptest", + "sendbox-core", + "serde", + "serde_json", + "serde_json_canonicalizer", + "sha2 0.11.0", + "thiserror", + "yaml_serde", +] + [[package]] name = "sendbox-guest" version = "0.2.7" @@ -2697,6 +2718,7 @@ dependencies = [ "clap", "ed25519-dalek", "getrandom 0.3.4", + "http", "libc", "proptest", "rustix", @@ -2704,6 +2726,7 @@ dependencies = [ "sendbox-bpf", "sendbox-config", "sendbox-core", + "sendbox-credentials", "sendbox-egress", "sendbox-exec", "sendbox-git", @@ -2711,6 +2734,7 @@ dependencies = [ "sendbox-policy", "sendbox-protocol", "sendbox-registry", + "sendbox-runtime", "sendbox-secrets", "serde", "serde_json", @@ -2727,6 +2751,7 @@ name = "sendbox-host" version = "0.2.7" dependencies = [ "getrandom 0.3.4", + "ipnet", "reqwest", "rustix", "sendbox-agent", @@ -2740,8 +2765,10 @@ dependencies = [ "sendbox-egress", "sendbox-exec", "sendbox-git", + "sendbox-governance", "sendbox-mcp", "sendbox-policy", + "sendbox-protocol", "sendbox-registry", "sendbox-runtime", "sendbox-runtime-apple", @@ -2756,6 +2783,7 @@ dependencies = [ "thiserror", "tokio", "url", + "yaml_serde", "zeroize", ] diff --git a/Cargo.toml b/Cargo.toml index 0488e06..4801c15 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "crates/sendbox-egress", "crates/sendbox-exec", "crates/sendbox-git", + "crates/sendbox-governance", "crates/sendbox-mcp", "crates/sendbox-policy", "crates/sendbox-project", diff --git a/README.md b/README.md index 712c1a4..cfe8bea 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,8 @@ too. Package inspection, Safe Outputs, and syscall tracing are opt-in. Use the [configuration guide](docs/configuration.md) and [annotated YAML reference](config/example-sandbox.yaml) for individual settings. +Operators can require signed policy profiles and keep model provider keys on +the host with [governed sessions](docs/architecture/governed-sessions.md). These commands do not launch a VM or require an agent login: ```bash diff --git a/ROADMAP.md b/ROADMAP.md index f981f8c..7b27959 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -286,7 +286,9 @@ Features planned after core platform and agent support is solid. ### Policy as Code - [ ] OPA/Rego policy language support for complex rules -- [ ] Policy inheritance (org → team → project) +- [x] Operator-signed governance profiles that projects can only narrow ([governed sessions](docs/architecture/governed-sessions.md), single host) +- [x] Host-side brokered model provider credentials with leased, revocable grants (Anthropic, OpenAI) +- [ ] Policy inheritance (org → team → project) with shared multi-user management (`sendbox-fleet`) - [ ] Policy testing framework - [ ] Community policy library diff --git a/Tests/qualification/inventory.v1.json b/Tests/qualification/inventory.v1.json index f70cf8e..1b62295 100644 --- a/Tests/qualification/inventory.v1.json +++ b/Tests/qualification/inventory.v1.json @@ -53,8 +53,11 @@ {"id":"module.rust-host","category":"source_module","name":"Rust authenticated host runtime composition","disposition":"preserve","rationale":"Retain verified boundary-plan preparation, capability-aware provider dispatch, authenticated security-service composition, session lifecycle enforcement, cleanup aggregation, package-report persistence, shared GitHub Meta seeding, and post-runtime Safe Outputs processing.","evidence":["crates/sendbox-host/src/lib.rs#prepare PreparedHostRun and provider-neutral runtime composition","crates/sendbox-host/src/security.rs#host session security lifecycle and package report persistence","crates/sendbox-host/src/safe_outputs.rs#host-only verification ledger GitHub writer and isolated pull-request transport","crates/sendbox-host/src/github_meta.rs#machine-wide file-locked GitHub Meta cache seeding guest gateways"],"target_crate":"sendbox-host","target_phase":10,"conformance":{"status":"implemented","fixture_ids":["runtime.contracts","policy.decisions","persisted.formats","known-defects.negative"],"compatibility_note":null}}, {"id":"module.rust-security","category":"source_module","name":"Rust security records foundation","disposition":"preserve","rationale":"Retain descriptor-relative persistence, canonical records, Merkle audit integrity, Ed25519 provenance and trust policies, versioned snapshots, and legacy Swift readers.","evidence":["crates/sendbox-security/src/audit.rs#audit records and Merkle tree","crates/sendbox-security/src/canonical.rs#canonical JSON","crates/sendbox-security/src/error.rs#SecurityError","crates/sendbox-security/src/fs.rs#descriptor-relative persistence","crates/sendbox-security/src/legacy.rs#legacy Swift readers","crates/sendbox-security/src/lib.rs#public exports","crates/sendbox-security/src/provenance.rs#Ed25519 provenance and trust policy","crates/sendbox-security/src/snapshot.rs#versioned snapshots"],"target_crate":"sendbox-security","target_phase":9,"conformance":{"status":"implemented","fixture_ids":["persisted.formats"],"compatibility_note":null}}, {"id":"module.rust-secrets","category":"source_module","name":"Rust secrets and credential foundation","disposition":"preserve","rationale":"Retain typed credential scope, authenticated envelopes, versioned records, and platform-specific secure storage foundations.","evidence":["crates/sendbox-secrets/src/credential.rs#credential scope","crates/sendbox-secrets/src/envelope.rs#authenticated envelope","crates/sendbox-secrets/src/error.rs#SecretsError","crates/sendbox-secrets/src/lib.rs#public exports","crates/sendbox-secrets/src/linux.rs#Linux secure store","crates/sendbox-secrets/src/macos.rs#macOS secure store","crates/sendbox-secrets/src/record.rs#versioned secret record","crates/sendbox-secrets/src/types.rs#secret types"],"target_crate":"sendbox-secrets","target_phase":9,"conformance":{"status":"implemented","fixture_ids":["policy.decisions","persisted.formats"],"compatibility_note":null}}, - {"id":"module.rust-credentials","category":"source_module","name":"Rust production credential broker and guarded GitHub auth","disposition":"preserve","rationale":"Retain explicit loopback credential endpoints, strict bounded HTTP/1.1 parsing, pinned certificate-verifying HTTPS forwarding, repository-scope authorization, exact-shape gh metadata execution, cancellation, redaction, and session-bound configuration.","evidence":["crates/sendbox-credentials/src/broker.rs#CredentialBroker","crates/sendbox-credentials/src/config.rs#BrokerConfiguration","crates/sendbox-credentials/src/error.rs#CredentialBrokerError","crates/sendbox-credentials/src/github.rs#GitHubMetadataClient","crates/sendbox-credentials/src/http1.rs#ParsedRequest","crates/sendbox-credentials/src/lib.rs#public exports","crates/sendbox-credentials/src/session.rs#SessionCredentialConfiguration","crates/sendbox-credentials/src/upstream.rs#PinnedHttpsTransport"],"target_crate":"sendbox-credentials","target_phase":9,"conformance":{"status":"implemented","fixture_ids":["policy.decisions","runtime.contracts","known-defects.negative"],"compatibility_note":"The broker requires agents to use explicit per-rule HTTP base URLs; transparent TLS interception and CONNECT credential injection are intentionally unsupported."}}, + {"id":"module.rust-credentials","category":"source_module","name":"Rust production credential broker and guarded GitHub auth","disposition":"preserve","rationale":"Retain explicit loopback credential endpoints, strict bounded HTTP/1.1 parsing, pinned certificate-verifying HTTPS forwarding, repository-scope authorization, exact-shape gh metadata execution, cancellation, redaction, and session-bound configuration.","evidence":["crates/sendbox-credentials/src/broker.rs#CredentialBroker","crates/sendbox-credentials/src/config.rs#BrokerConfiguration","crates/sendbox-credentials/src/error.rs#CredentialBrokerError","crates/sendbox-credentials/src/github.rs#GitHubMetadataClient","crates/sendbox-credentials/src/http1.rs#ParsedRequest","crates/sendbox-credentials/src/lib.rs#public exports","crates/sendbox-credentials/src/session.rs#SessionCredentialConfiguration","crates/sendbox-credentials/src/upstream.rs#PinnedHttpsTransport","crates/sendbox-credentials/src/relay.rs#RelayEndpoint streamed governed credential relay"],"target_crate":"sendbox-credentials","target_phase":9,"conformance":{"status":"implemented","fixture_ids":["policy.decisions","runtime.contracts","known-defects.negative"],"compatibility_note":"The broker requires agents to use explicit per-rule HTTP base URLs; transparent TLS interception and CONNECT credential injection are intentionally unsupported."}}, {"id":"module.rust-session-security","category":"source_module","name":"Rust session security lifecycle","disposition":"preserve","rationale":"Retain adapter-neutral lifecycle orchestration, audit anchoring, supervisor grants, secret envelopes, and explicit migration reports.","evidence":["crates/sendbox-session-security/src/lib.rs#public exports","crates/sendbox-session-security/src/lifecycle.rs#SecuritySession","crates/sendbox-session-security/src/supervisor.rs#PermissionSupervisor","crates/sendbox-session-security/src/migration.rs#MigrationReport"],"target_crate":"sendbox-session-security","target_phase":9,"conformance":{"status":"implemented","fixture_ids":["persisted.formats"],"compatibility_note":null}}, + {"id":"module.rust-governance","category":"source_module","name":"Rust governance contract","disposition":"redesign","rationale":"Define the versioned, dependency-light contract shared by local governance and a future fleet authority: identities, signed operator profiles, governance bindings, leased credential grants, revocation, and the grant authority interface.","evidence":["crates/sendbox-governance/src/lib.rs#public exports and CONTRACT_VERSION","crates/sendbox-governance/src/identity.rs#PrincipalId ProjectId and SessionRef","crates/sendbox-governance/src/digest.rs#canonical_digest","crates/sendbox-governance/src/profile.rs#GovernanceProfile and CredentialProvider","crates/sendbox-governance/src/binding.rs#GovernanceBinding","crates/sendbox-governance/src/grant.rs#CredentialGrant RequestContext and Decision","crates/sendbox-governance/src/authority.rs#GrantAuthority and LocalGrantAuthority","docs/architecture/governed-sessions.md#Binding"],"target_crate":"sendbox-governance","target_phase":10,"conformance":{"status":"implemented","fixture_ids":["config.contracts","persisted.formats","policy.decisions"],"compatibility_note":"Governance is opt-in or operator-managed; standalone sessions keep identical boundary plan bytes because the binding is omitted when absent."}}, + {"id":"module.protocol-credential-relay","category":"source_module","name":"Protocol credential relay payloads","disposition":"redesign","rationale":"Carry brokered provider requests and streamed responses over the authenticated guest channel with per-stream credit, bounded chunks, and no credential material.","evidence":["crates/sendbox-protocol/src/relay.rs#CredentialRelayRequestV1 and credit window constants","crates/sendbox-protocol/src/types.rs#EventKind credential relay kinds","docs/architecture/governed-sessions.md#Relay"],"target_crate":"sendbox-protocol","target_phase":10,"conformance":{"status":"implemented","fixture_ids":["protocol.contracts","runtime.contracts"],"compatibility_note":"Authenticated CBOR framing remains v1; relay events use new event kinds that are only accepted after the guest reports a live credential_relay service."}}, + {"id":"module.rust-governed-sessions","category":"source_module","name":"Rust governed session admission and credential relay wiring","disposition":"redesign","rationale":"Verify operator-signed profiles from a root-owned managed configuration or explicit opt-in, admit only narrowing compositions, bind the admission into the signed boundary plan, broker provider credentials host-side with leased grants, and record governance audit evidence.","evidence":["crates/sendbox-host/src/governance/mod.rs#GovernedSession and GovernedRun","crates/sendbox-host/src/governance/composition.rs#check and apply_denials","crates/sendbox-host/src/governance/operator.rs#GovernanceSource OperatorConfiguration and RevisionHighWater","crates/sendbox-host/src/governance/relay.rs#HostCredentialRelay","crates/sendbox-cli/src/governance.rs#governance keygen sign verify check","guest/sendbox-guest/src/credential_relay.rs#loopback credential relay listener","docs/architecture/governed-sessions.md#Admission and composition"],"target_crate":"sendbox-host","target_phase":10,"conformance":{"status":"implemented","fixture_ids":["config.contracts","policy.decisions","cli.contracts","runtime.contracts"],"compatibility_note":"Brokered credentials require a persistent Apple or Kata session; Hyperlight and legacy MCP fields are rejected for governed sessions."}}, {"id":"module.rust-exec-broker","category":"source_module","name":"Rust production execution broker","disposition":"preserve","rationale":"Retain exact argv admission, compiled policy, authenticated sessions, bounded streaming, cancellation, environment construction, and cleanup outcomes.","evidence":["crates/sendbox-exec/src/lib.rs#public exports","crates/sendbox-exec/src/api.rs#ExecutionRequest and ExecutionResult","crates/sendbox-exec/src/broker.rs#Broker and CancellationFlag","crates/sendbox-exec/src/environment.rs#EnvironmentPolicy","crates/sendbox-exec/src/error.rs#ExecError and KernelPrimitive","crates/sendbox-exec/src/policy.rs#CompiledCommandPolicy","crates/sendbox-exec/src/runtime.rs#AuthenticatedUnixListener","crates/sendbox-exec/src/service.rs#BrokerService and startup_health_connection_does_not_consume_the_execution_session","crates/sendbox-exec/src/session.rs#BrokerSession","crates/sendbox-exec/src/bin/sendbox-exec-launcher.rs#sendbox-exec-launcher"],"target_crate":"sendbox-exec","target_phase":7,"conformance":{"status":"implemented","fixture_ids":["runtime.contracts","policy.decisions","known-defects.negative"],"compatibility_note":"Connection-only startup health probes do not consume an execution session; only an empty pre-request disconnect is retried, with peer and request authentication unchanged."}}, {"id":"module.rust-exec-linux","category":"source_module","name":"Rust Linux execution containment","disposition":"preserve","rationale":"Retain descriptor-relative resolution, atomic cgroup placement, pidfd lifecycle, cgroup-wide cleanup, capability removal, resource limits, and TSYNC seccomp enforcement.","evidence":["crates/sendbox-exec/src/platform/mod.rs#LiveGate","crates/sendbox-exec/src/platform/linux/mod.rs#Linux platform modules","crates/sendbox-exec/src/platform/linux/agent.rs#AgentBootstrap","crates/sendbox-exec/src/platform/linux/capabilities.rs#drop_all","crates/sendbox-exec/src/platform/linux/cgroup.rs#CgroupManager","crates/sendbox-exec/src/platform/linux/launcher.rs#DedicatedLauncherBackend","crates/sendbox-exec/src/platform/linux/pty.rs#PseudoTerminal","crates/sendbox-exec/src/platform/linux/raw.rs#audited Linux syscall adapter","crates/sendbox-exec/src/platform/linux/resolver.rs#ResolvedCommand","crates/sendbox-exec/src/platform/linux/rlimits.rs#apply","crates/sendbox-exec/src/platform/linux/seccomp.rs#TSYNC seccomp profiles"],"target_crate":"sendbox-exec","target_phase":7,"conformance":{"status":"implemented","fixture_ids":["runtime.contracts"],"compatibility_note":null}}, {"id":"module.rust-git","category":"source_module","name":"Rust native Git branch guard","disposition":"preserve","rationale":"Retain typed repository/workspace identity, exact supported Git parsing, bounded probes, clean environment policy, trusted binary discovery and verification, standalone policy delivery, and native execution replacement.","evidence":["crates/sendbox-git/src/argv.rs#Git argv and alias parsing","crates/sendbox-git/src/bin/sendbox-git-guard.rs#native guard protocol","crates/sendbox-git/src/discovery.rs#trusted Git discovery","crates/sendbox-git/src/error.rs#GuardError","crates/sendbox-git/src/identity.rs#repository and workspace identity","crates/sendbox-git/src/lib.rs#public policy API","crates/sendbox-git/src/pattern.rs#branch policy","crates/sendbox-git/src/process.rs#bounded injected process runner","crates/sendbox-git/src/service.rs#selected repository admission","crates/sendbox-git/src/standalone.rs#signed standalone guard policy","crates/sendbox-git/src/trusted.rs#trusted Git binary"],"target_crate":"sendbox-git","target_phase":7,"conformance":{"status":"implemented","fixture_ids":["policy.decisions","known-defects.negative"],"compatibility_note":null}}, diff --git a/config/example-sandbox.yaml b/config/example-sandbox.yaml index 64b9713..57b8f69 100644 --- a/config/example-sandbox.yaml +++ b/config/example-sandbox.yaml @@ -296,6 +296,13 @@ policy: secrets: - DATABASE_URL +# Brokered model provider credentials (governed sessions only). Each id must be +# offered by the operator's signed governance profile. The provider key stays +# on the host; the agent receives a loopback base URL and a placeholder key. +# Rejected when no governance configuration is active. +# See docs/architecture/governed-sessions.md. +# credential_services: [anthropic] + # ───────────────────────────────────────────────────────────────────────────── # DevContainer Configuration # ───────────────────────────────────────────────────────────────────────────── diff --git a/crates/sendbox-agent/Cargo.toml b/crates/sendbox-agent/Cargo.toml index 89bfa0b..b0c76b0 100644 --- a/crates/sendbox-agent/Cargo.toml +++ b/crates/sendbox-agent/Cargo.toml @@ -22,6 +22,7 @@ zeroize.workspace = true [dev-dependencies] proptest.workspace = true +sendbox-governance = { path = "../sendbox-governance" } sendbox-policy = { path = "../sendbox-policy" } sendbox-security = { path = "../sendbox-security" } sendbox-testkit = { path = "../sendbox-testkit" } diff --git a/crates/sendbox-agent/src/lib.rs b/crates/sendbox-agent/src/lib.rs index 1618b91..21a1a0f 100644 --- a/crates/sendbox-agent/src/lib.rs +++ b/crates/sendbox-agent/src/lib.rs @@ -14,9 +14,9 @@ pub use plan::{ }; pub use protocol::{ProtocolGuestConnector, ProtocolGuestExecution, ProtocolGuestSession}; pub use traits::{ - AgentSignal, BoxFuture, CollectedSafeOutputs, GuestConnectionConfiguration, GuestConnector, - GuestEvent, GuestExecution, GuestLaunchRequest, GuestNetworkReport, GuestPackageReport, - GuestSecretEnvelope, GuestSession, GuestSyscallReport, GuestTerminal, GuestTerminalSize, - HostTerminalCommand, NoSignals, NoTerminal, OutputSink, SecretEnvelope, SecretResolver, - SignalSource, TerminalSource, + AgentSignal, BoxFuture, CollectedSafeOutputs, CredentialRelayHandler, CredentialRelayOutbound, + GuestConnectionConfiguration, GuestConnector, GuestEvent, GuestExecution, GuestLaunchRequest, + GuestNetworkReport, GuestPackageReport, GuestSecretEnvelope, GuestSession, GuestSyscallReport, + GuestTerminal, GuestTerminalSize, HostTerminalCommand, NoSignals, NoTerminal, OutputSink, + SecretEnvelope, SecretResolver, SignalSource, TerminalSource, }; diff --git a/crates/sendbox-agent/src/orchestrator.rs b/crates/sendbox-agent/src/orchestrator.rs index f16e40f..99c8692 100644 --- a/crates/sendbox-agent/src/orchestrator.rs +++ b/crates/sendbox-agent/src/orchestrator.rs @@ -1,4 +1,5 @@ use std::sync::Arc; +use std::time::Duration; use sendbox_protocol::agent_host_capabilities; use sendbox_runtime::{ @@ -92,6 +93,7 @@ pub struct AgentOrchestrator { signals: Arc, terminal: Arc, terminal_size: Option, + credential_relay: Option>, } impl AgentOrchestrator { @@ -111,6 +113,24 @@ impl AgentOrchestrator { signals, terminal: Arc::new(crate::NoTerminal), terminal_size: None, + credential_relay: None, + } + } + + /// Serves brokered credential requests from the guest relay. Required + /// when the signed plan admits brokered credential services. + #[must_use] + pub fn with_credential_relay( + mut self, + handler: Arc, + ) -> Self { + self.credential_relay = Some(handler); + self + } + + async fn close_credential_relay(&self) { + if let Some(relay) = &self.credential_relay { + relay.close(Duration::ZERO).await; } } @@ -183,6 +203,11 @@ impl AgentOrchestrator { context: &mut RunContext, ) -> Result<(GuestTerminal, Option), AgentError> { check_cancelled(cancellation)?; + if plan.credential_relay() != self.credential_relay.is_some() { + return Err(AgentError::InvalidPlan( + "brokered credential services require exactly one host relay handler".to_owned(), + )); + } let preflight = self .runtime .preflight( @@ -308,6 +333,7 @@ impl AgentOrchestrator { required_capabilities: plan.required_guest_capabilities().clone(), safe_outputs_required: plan.safe_outputs(), syscall_tracing_required: plan.syscall_tracing(), + credential_relay_required: plan.credential_relay(), bootstrap_secret: bootstrap.as_bytes().to_vec(), policy_digest: plan.policy_digest(), }, @@ -353,6 +379,12 @@ impl AgentOrchestrator { cancellation, ) .await?; + if let Some(relay) = &self.credential_relay { + let outbound = execution.credential_relay_outbound().ok_or_else(|| { + AgentError::Guest("guest execution did not provide a credential relay".to_owned()) + })?; + relay.attach(outbound); + } context.execution = Some(execution); context.transition(AgentState::Running)?; let terminal = self @@ -436,7 +468,17 @@ impl AgentOrchestrator { GuestEvent::TerminalInputCredit { credits } => { self.terminal.grant_input_credit(credits)?; } + GuestEvent::CredentialRelay(event) => match &self.credential_relay { + Some(relay) => relay.handle(event)?, + None => { + return Err(AgentError::Guest( + "guest sent a credential relay event without a relay" + .to_owned(), + )); + } + }, GuestEvent::Terminal(terminal) => { + self.close_credential_relay().await; if let Some(maximum_bytes) = package_report_maximum_bytes { context.package_report = Some( execution @@ -480,6 +522,7 @@ impl AgentOrchestrator { ) -> Vec { let cleanup_cancellation = CancellationToken::new(); let mut failures = Vec::new(); + self.close_credential_relay().await; if context.state != AgentState::Cleaning && context.state.can_transition_to(AgentState::Cleaning) { diff --git a/crates/sendbox-agent/src/plan.rs b/crates/sendbox-agent/src/plan.rs index b1ceee1..8945817 100644 --- a/crates/sendbox-agent/src/plan.rs +++ b/crates/sendbox-agent/src/plan.rs @@ -109,6 +109,7 @@ pub struct RunPlan { safe_outputs: bool, syscall_tracing: bool, network_report: bool, + credential_relay: bool, } impl RunPlan { @@ -197,6 +198,10 @@ impl RunPlan { .or_else(|_| ContainerId::new(format!("sendbox-{}", boundary.session_id))) .map_err(AgentError::Runtime)?; let safe_outputs = configuration.github.safe_outputs.enabled; + let credential_relay = boundary + .governance + .as_ref() + .is_some_and(|governance| !governance.brokered_services.is_empty()); Ok(Self { verified_boundary_plan: request.boundary_plan, resolved_runtime: boundary.selection.selected, @@ -240,6 +245,7 @@ impl RunPlan { safe_outputs, syscall_tracing, network_report, + credential_relay, }) } @@ -259,6 +265,13 @@ impl RunPlan { self.syscall_tracing } + /// Whether the signed plan admits brokered credential services, which + /// require a live guest relay and a host relay handler. + #[must_use] + pub const fn credential_relay(&self) -> bool { + self.credential_relay + } + #[must_use] pub const fn network_report(&self) -> bool { self.network_report diff --git a/crates/sendbox-agent/src/protocol.rs b/crates/sendbox-agent/src/protocol.rs index 1a89beb..4d8f34f 100644 --- a/crates/sendbox-agent/src/protocol.rs +++ b/crates/sendbox-agent/src/protocol.rs @@ -55,6 +55,7 @@ impl GuestConnector for ProtocolGuestConnector { })?; let safe_outputs_required = configuration.safe_outputs_required; let syscall_tracing_required = configuration.syscall_tracing_required; + let credential_relay = configuration.credential_relay_required; let handshake = HandshakeConfig::new( configuration.session_id, VersionRange::default(), @@ -84,6 +85,7 @@ impl GuestConnector for ProtocolGuestConnector { &readiness.payload, safe_outputs_required, syscall_tracing_required, + credential_relay, )?; Ok(Box::new(ProtocolGuestSession { negotiated, @@ -94,6 +96,7 @@ impl GuestConnector for ProtocolGuestConnector { boundary_plan_digest: configuration.boundary_plan_digest, secret_cipher, next_secret_sequence: 1, + credential_relay, }) as Box) }) } @@ -108,6 +111,7 @@ pub struct ProtocolGuestSession { boundary_plan_digest: sendbox_core::BoundaryPlanDigest, secret_cipher: EnvelopeCipher, next_secret_sequence: u64, + credential_relay: bool, } impl GuestSession for ProtocolGuestSession { @@ -210,6 +214,7 @@ impl GuestSession for ProtocolGuestSession { report_fetched: false, syscall_report_fetched: false, network_report_fetched: false, + credential_relay: self.credential_relay, }) as Box) }) } @@ -317,6 +322,7 @@ pub struct ProtocolGuestExecution { report_fetched: bool, syscall_report_fetched: bool, network_report_fetched: bool, + credential_relay: bool, } #[derive(Debug, Default)] @@ -371,6 +377,10 @@ const WRITER_CONTROL_DEPTH: usize = 4; /// Queue depth for the credited input window plus its FIFO EOF reservation. const WRITER_INPUT_DEPTH: usize = sendbox_core::TERMINAL_INPUT_WINDOW_CREDITS as usize + 1; +/// Queue depth for host-to-guest credential relay events. Relay tasks await +/// capacity, so this bounds memory without ever blocking the event loop. +const WRITER_RELAY_DEPTH: usize = 64; + struct WriterMessage { message: Message, ack: Option>>, @@ -386,6 +396,7 @@ struct WriterHandle { control: tokio::sync::mpsc::Sender, input: tokio::sync::mpsc::Sender, resize: tokio::sync::watch::Sender>, + relay: tokio::sync::mpsc::Sender, task: tokio::task::JoinHandle<()>, } @@ -397,6 +408,8 @@ impl WriterHandle { let (input, mut input_receiver) = tokio::sync::mpsc::channel::(WRITER_INPUT_DEPTH); let (resize, mut resize_receiver) = tokio::sync::watch::channel::>(None); + let (relay, mut relay_receiver) = + tokio::sync::mpsc::channel::(WRITER_RELAY_DEPTH); let task = tokio::spawn(async move { loop { let queued = tokio::select! { @@ -419,6 +432,10 @@ impl WriterHandle { Some(queued) => queued, None => continue, }, + relay = relay_receiver.recv() => match relay { + Some(queued) => queued, + None => continue, + }, }; let WriterMessage { message, ack } = queued; let result = writer.send(&message).await; @@ -437,6 +454,7 @@ impl WriterHandle { control, input, resize, + relay, task, } } @@ -479,6 +497,34 @@ impl WriterHandle { } } +/// Host-to-guest relay sender. Only host relay event kinds are accepted, so a +/// relay endpoint can never inject terminal input or control messages. +struct RelaySender(tokio::sync::mpsc::Sender); + +impl crate::CredentialRelayOutbound for RelaySender { + fn send(&self, event: Event) -> BoxFuture<'_, Result<(), AgentError>> { + Box::pin(async move { + if !matches!( + event.kind, + EventKind::CredentialRelayResponseHead + | EventKind::CredentialRelayResponseBody + | EventKind::CredentialRelayEnd + ) { + return Err(AgentError::Guest( + "only host credential relay events may use the relay sender".to_owned(), + )); + } + self.0 + .send(WriterMessage { + message: Message::Event(event), + ack: None, + }) + .await + .map_err(|_| AgentError::Guest("guest connection writer stopped".to_owned())) + }) + } +} + impl Drop for WriterHandle { fn drop(&mut self) { self.task.abort(); @@ -529,6 +575,14 @@ impl GuestExecution for ProtocolGuestExecution { credits: credit.credits, }) } + sendbox_protocol::EventKind::CredentialRelayRequest + | sendbox_protocol::EventKind::CredentialRelayRequestBody + | sendbox_protocol::EventKind::CredentialRelayEnd + | sendbox_protocol::EventKind::CredentialRelayCredit + if self.credential_relay => + { + Ok(GuestEvent::CredentialRelay(event)) + } kind => Err(AgentError::Guest(format!( "unexpected guest event kind {kind:?}" ))), @@ -617,6 +671,15 @@ impl GuestExecution for ProtocolGuestExecution { }) } + fn credential_relay_outbound( + &self, + ) -> Option> { + self.credential_relay.then(|| { + std::sync::Arc::new(RelaySender(self.writer.relay.clone())) + as std::sync::Arc + }) + } + fn send_terminal<'a>( &'a mut self, command: HostTerminalCommand, @@ -969,6 +1032,7 @@ fn validate_operational_readiness( payload: &[u8], safe_outputs_required: bool, syscall_tracing_required: bool, + credential_relay_required: bool, ) -> Result<(), AgentError> { let readiness: serde_json::Value = serde_json::from_slice(payload) .map_err(|error| AgentError::Guest(format!("decode guest readiness: {error}")))?; @@ -1005,6 +1069,11 @@ fn validate_operational_readiness( "guest readiness did not prove a live mandatory syscall tracing service".to_owned(), )); } + if credential_relay_required && !service_live("credential_relay") { + return Err(AgentError::Guest( + "guest readiness did not prove a live mandatory credential relay".to_owned(), + )); + } Ok(()) } @@ -1070,10 +1139,12 @@ mod tests { let (control, _control) = tokio::sync::mpsc::channel(WRITER_CONTROL_DEPTH); let (input, mut receiver) = tokio::sync::mpsc::channel(WRITER_INPUT_DEPTH); let (resize, mut resize_receiver) = tokio::sync::watch::channel::>(None); + let (relay, _relay) = tokio::sync::mpsc::channel(WRITER_RELAY_DEPTH); let writer = WriterHandle { control, input, resize, + relay, task: tokio::spawn(std::future::pending()), }; @@ -1165,18 +1236,60 @@ mod tests { fn required_safe_outputs_service_must_be_present_and_healthy() { let exec_only = br#"{"state":"ready","services":[{"id":"exec","mandatory":true,"healthy":true}]}"#; - validate_operational_readiness(exec_only, false, false).expect("ordinary readiness"); - assert!(validate_operational_readiness(exec_only, true, false).is_err()); + validate_operational_readiness(exec_only, false, false, false).expect("ordinary readiness"); + assert!(validate_operational_readiness(exec_only, true, false, false).is_err()); let complete = br#"{"state":"ready","services":[{"id":"exec","mandatory":true,"healthy":true},{"id":"safe_outputs","mandatory":true,"healthy":true}]}"#; - validate_operational_readiness(complete, true, false).expect("Safe Outputs readiness"); + validate_operational_readiness(complete, true, false, false) + .expect("Safe Outputs readiness"); + } + + #[test] + fn brokered_credentials_require_a_live_guest_relay() { + let exec_only = + br#"{"state":"ready","services":[{"id":"exec","mandatory":true,"healthy":true}]}"#; + assert!(validate_operational_readiness(exec_only, false, false, true).is_err()); + let unhealthy = br#"{"state":"ready","services":[{"id":"exec","mandatory":true,"healthy":true},{"id":"credential_relay","mandatory":true,"healthy":false}]}"#; + assert!(validate_operational_readiness(unhealthy, false, false, true).is_err()); + let relayed = br#"{"state":"ready","services":[{"id":"exec","mandatory":true,"healthy":true},{"id":"credential_relay","mandatory":true,"healthy":true}]}"#; + validate_operational_readiness(relayed, false, false, true).expect("relay readiness"); + } + + #[tokio::test] + async fn relay_sender_only_carries_host_relay_events() { + use crate::CredentialRelayOutbound as _; + let (relay, mut receiver) = tokio::sync::mpsc::channel(WRITER_RELAY_DEPTH); + let sender = RelaySender(relay); + let event = |kind| Event { + stream_id: sendbox_protocol::relay::CREDENTIAL_RELAY_STREAM_BASE, + kind, + payload: vec![1], + }; + sender + .send(event(EventKind::CredentialRelayResponseBody)) + .await + .expect("relay body"); + assert!(matches!( + receiver.recv().await.expect("queued").message, + Message::Event(Event { + kind: EventKind::CredentialRelayResponseBody, + .. + }) + )); + for kind in [ + EventKind::StandardInput, + EventKind::CredentialRelayRequest, + EventKind::CredentialRelayCredit, + ] { + assert!(sender.send(event(kind)).await.is_err()); + } } #[test] fn requested_tracing_must_be_present_in_authenticated_readiness() { let exec_only = br#"{"state":"ready","services":[{"id":"exec","mandatory":true,"healthy":true}]}"#; - assert!(validate_operational_readiness(exec_only, false, true).is_err()); + assert!(validate_operational_readiness(exec_only, false, true, false).is_err()); let traced = br#"{"state":"ready","services":[{"id":"exec","mandatory":true,"healthy":true},{"id":"bpf","mandatory":true,"healthy":true}]}"#; - validate_operational_readiness(traced, false, true).expect("traced readiness"); + validate_operational_readiness(traced, false, true, false).expect("traced readiness"); } } diff --git a/crates/sendbox-agent/src/traits.rs b/crates/sendbox-agent/src/traits.rs index bf4b78d..404f71f 100644 --- a/crates/sendbox-agent/src/traits.rs +++ b/crates/sendbox-agent/src/traits.rs @@ -1,6 +1,6 @@ -use std::{fmt, future::Future, pin::Pin}; +use std::{fmt, future::Future, pin::Pin, sync::Arc, time::Duration}; -use sendbox_protocol::CapabilitySet; +use sendbox_protocol::{CapabilitySet, Event}; use sendbox_runtime::{CancellationToken, ControlStream, OutputStream}; use serde::{Deserialize, Serialize}; use zeroize::Zeroizing; @@ -116,9 +116,29 @@ pub enum GuestEvent { TerminalInputCredit { credits: u16, }, + /// A guest-to-host brokered credential relay event. + CredentialRelay(Event), Terminal(GuestTerminal), } +/// Sends host-to-guest credential relay events on the authenticated channel. +pub trait CredentialRelayOutbound: Send + Sync { + fn send(&self, event: Event) -> BoxFuture<'_, Result<(), AgentError>>; +} + +/// Host endpoint for brokered credential requests from the guest relay. +pub trait CredentialRelayHandler: Send + Sync { + /// Connects the handler to the running workload's channel. + fn attach(&self, outbound: Arc); + + /// Accepts one guest relay event without blocking the event loop. An + /// error means the channel was misused and the run must fail. + fn handle(&self, event: Event) -> Result<(), AgentError>; + + /// Stops accepting requests and ends in-flight streams after `grace`. + fn close(&self, grace: Duration) -> BoxFuture<'_, ()>; +} + #[derive(Clone, PartialEq, Eq)] pub struct CollectedSafeOutputs { pub artifact: Vec, @@ -179,6 +199,7 @@ pub struct GuestConnectionConfiguration { pub required_capabilities: CapabilitySet, pub safe_outputs_required: bool, pub syscall_tracing_required: bool, + pub credential_relay_required: bool, pub bootstrap_secret: Vec, pub policy_digest: [u8; 32], } @@ -193,6 +214,7 @@ impl fmt::Debug for GuestConnectionConfiguration { .field("required_capabilities", &self.required_capabilities) .field("safe_outputs_required", &self.safe_outputs_required) .field("syscall_tracing_required", &self.syscall_tracing_required) + .field("credential_relay_required", &self.credential_relay_required) .field("bootstrap_secret", &"[REDACTED]") .field("policy_digest", &self.policy_digest) .finish() @@ -275,6 +297,12 @@ pub trait GuestExecution: Send { }) } + /// Returns the host-to-guest sender for credential relay events when the + /// guest proved a live relay during readiness. + fn credential_relay_outbound(&self) -> Option> { + None + } + /// Forwards one host terminal command to the guest. /// /// The default rejects the command, so a transport that never negotiated diff --git a/crates/sendbox-agent/tests/agent.rs b/crates/sendbox-agent/tests/agent.rs index b0b18d5..9ec9aef 100644 --- a/crates/sendbox-agent/tests/agent.rs +++ b/crates/sendbox-agent/tests/agent.rs @@ -231,6 +231,7 @@ fn verified_boundary_plan( * 1024, }, features: BTreeMap::new(), + governance: None, }; let key = SigningKeyMaterial::generate().expect("signing key"); let fingerprint = key.identity("test", None, 0, None).fingerprint.clone(); @@ -1358,6 +1359,7 @@ async fn protocol_connector_authenticates_over_unix_stream() { required_capabilities: sendbox_protocol::agent_host_required_capabilities(), safe_outputs_required: false, syscall_tracing_required: false, + credential_relay_required: false, bootstrap_secret: vec![7; 32], policy_digest: [9; 32], }, @@ -1684,3 +1686,214 @@ fn headless_plan_does_not_require_the_runtime_terminal_capability() { assert!(!plan.interactive()); } + +struct RelayLog { + attached: std::sync::atomic::AtomicBool, + handled: Mutex>, + closed: std::sync::atomic::AtomicUsize, +} + +impl sendbox_agent::CredentialRelayHandler for RelayLog { + fn attach(&self, _outbound: Arc) { + self.attached + .store(true, std::sync::atomic::Ordering::SeqCst); + } + + fn handle(&self, event: Event) -> Result<(), AgentError> { + self.handled + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .push(event); + Ok(()) + } + + fn close(&self, _grace: std::time::Duration) -> BoxFuture<'_, ()> { + self.closed + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Box::pin(async {}) + } +} + +struct NullOutbound; + +impl sendbox_agent::CredentialRelayOutbound for NullOutbound { + fn send(&self, _event: Event) -> BoxFuture<'_, Result<(), AgentError>> { + Box::pin(async { Ok(()) }) + } +} + +struct RelayConnector; + +struct RelaySession; + +struct RelayExecution { + events: VecDeque, +} + +fn relay_event() -> Event { + Event { + stream_id: sendbox_protocol::relay::CREDENTIAL_RELAY_STREAM_BASE, + kind: sendbox_protocol::EventKind::CredentialRelayCredit, + payload: b"{}".to_vec(), + } +} + +impl GuestConnector for RelayConnector { + fn connect<'a>( + &'a self, + _stream: Box, + configuration: GuestConnectionConfiguration, + _cancellation: &'a CancellationToken, + ) -> BoxFuture<'a, Result, AgentError>> { + Box::pin(async move { + assert!(configuration.credential_relay_required); + Ok(Box::new(RelaySession) as Box) + }) + } +} + +impl GuestSession for RelaySession { + fn negotiated_capabilities(&self) -> &CapabilitySet { + static CAPABILITIES: std::sync::OnceLock = std::sync::OnceLock::new(); + CAPABILITIES.get_or_init(negotiated_agent_capabilities) + } + + fn start<'a>( + &'a mut self, + _request: GuestLaunchRequest<'a>, + _cancellation: &'a CancellationToken, + ) -> BoxFuture<'a, Result, AgentError>> { + Box::pin(async { + Ok(Box::new(RelayExecution { + events: VecDeque::from([ + GuestEvent::CredentialRelay(relay_event()), + GuestEvent::Terminal(GuestTerminal::Exited { code: 0 }), + ]), + }) as Box) + }) + } + + fn cleanup<'a>( + &'a mut self, + _cancellation: &'a CancellationToken, + ) -> BoxFuture<'a, Result<(), AgentError>> { + Box::pin(async { Ok(()) }) + } +} + +impl GuestExecution for RelayExecution { + fn next_event<'a>( + &'a mut self, + _cancellation: &'a CancellationToken, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.events + .pop_front() + .ok_or_else(|| AgentError::Guest("event stream ended".to_owned())) + }) + } + + fn cancel<'a>( + &'a mut self, + _cancellation: &'a CancellationToken, + ) -> BoxFuture<'a, Result<(), AgentError>> { + Box::pin(async { Ok(()) }) + } + + fn credential_relay_outbound(&self) -> Option> { + Some(Arc::new(NullOutbound)) + } +} + +fn brokered_plan(resources: &TempResource, capabilities: &RuntimeCapabilities) -> RunPlan { + use sendbox_governance::{ + AuthorityRef, CONTRACT_VERSION, GovernanceBinding, PrincipalId, ProfileId, ProfileRef, + ProjectId, ServiceId, Sha256Digest, + }; + let session_id = SessionId::from_bytes([21; 16]); + let configuration = configuration(resources.path().to_path_buf()); + let mut request = request_for_configuration(resources, session_id, &configuration); + let mut boundary = request.boundary_plan.plan().clone(); + boundary.governance = Some(GovernanceBinding { + contract_version: CONTRACT_VERSION, + authority: AuthorityRef { + id: "local".to_owned(), + trust_sha256: Sha256Digest::of(b"trust"), + }, + profile: ProfileRef { + id: ProfileId::new("acme").unwrap(), + revision: 1, + sha256: Sha256Digest::of(b"profile"), + }, + principal: PrincipalId::local_user(501), + project: ProjectId::new("github:octo/api").unwrap(), + effective_policy_sha256: Sha256Digest::parse_hex(&boundary.policy_sha256).unwrap(), + brokered_services: vec![ServiceId::new("anthropic").unwrap()], + }); + let signing_key = SigningKeyMaterial::generate().unwrap(); + let fingerprint = signing_key + .identity("test", None, 0, None) + .fingerprint + .clone(); + request.boundary_plan = SignedBoundaryPlan::sign(boundary, &signing_key, plan_time()) + .unwrap() + .verify(&fingerprint, plan_time()) + .unwrap(); + RunPlan::compile(&configuration, request, capabilities, plan_time()).expect("brokered plan") +} + +#[tokio::test] +async fn brokered_plans_dispatch_relay_events_and_close_the_relay() { + let resources = TempResource::new().expect("resources"); + resources.create_directory("state").expect("state"); + let runtime = Arc::new(FakeRuntime::new(runtime_capabilities()).expect("runtime")); + let (host, _guest) = tokio::io::duplex(4096); + runtime.set_control_stream(Box::new(host)); + let plan = brokered_plan(&resources, &runtime.capabilities()); + assert!(plan.credential_relay()); + + let without_handler = AgentOrchestrator::new( + runtime.clone(), + Arc::new(FakeSecrets), + Arc::new(RelayConnector), + Arc::new(RecordingOutput::default()), + Arc::new(NoSignals), + ) + .run(&plan, &CancellationToken::new()) + .await + .expect_err("relay handler is mandatory"); + assert!(matches!( + without_handler.primary, + AgentError::InvalidPlan(_) + )); + + let log = Arc::new(RelayLog { + attached: std::sync::atomic::AtomicBool::new(false), + handled: Mutex::new(Vec::new()), + closed: std::sync::atomic::AtomicUsize::new(0), + }); + let runtime = Arc::new(FakeRuntime::new(runtime_capabilities()).expect("runtime")); + let (host, _guest) = tokio::io::duplex(4096); + runtime.set_control_stream(Box::new(host)); + let report = AgentOrchestrator::new( + runtime, + Arc::new(FakeSecrets), + Arc::new(RelayConnector), + Arc::new(RecordingOutput::default()), + Arc::new(NoSignals), + ) + .with_credential_relay(log.clone()) + .run(&plan, &CancellationToken::new()) + .await + .expect("brokered run"); + assert_eq!(report.terminal, GuestTerminal::Exited { code: 0 }); + assert!(log.attached.load(std::sync::atomic::Ordering::SeqCst)); + assert_eq!( + log.handled + .lock() + .unwrap_or_else(|poison| poison.into_inner()) + .as_slice(), + &[relay_event()] + ); + assert!(log.closed.load(std::sync::atomic::Ordering::SeqCst) >= 1); +} diff --git a/crates/sendbox-bootstrap/src/lib.rs b/crates/sendbox-bootstrap/src/lib.rs index b3d734e..4518b39 100644 --- a/crates/sendbox-bootstrap/src/lib.rs +++ b/crates/sendbox-bootstrap/src/lib.rs @@ -68,6 +68,7 @@ pub enum ServiceId { Audit, Bpf, SafeOutputs, + CredentialRelay, } impl ServiceId { @@ -81,6 +82,7 @@ impl ServiceId { Self::Audit => "audit", Self::Bpf => "bpf", Self::SafeOutputs => "safe_outputs", + Self::CredentialRelay => "credential_relay", } } } @@ -312,6 +314,84 @@ pub struct RegistryProxyConfiguration { pub credentials: Vec, } +pub const MAX_CREDENTIAL_RELAY_SERVICES: usize = 16; +pub const MAX_CREDENTIAL_RELAY_STREAMS: u32 = 64; +pub const MAX_CREDENTIAL_RELAY_REQUEST_BYTES: u64 = 16 * 1024 * 1024; + +/// Guest relay listener for brokered credential services. It routes +/// `//...` requests to the host broker and never carries a credential. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialRelayBootstrap { + pub port: u16, + pub services: Vec, + pub max_streams: u32, + pub max_request_bytes: u64, +} + +impl CredentialRelayBootstrap { + pub fn validate(&self) -> Result<(), BootstrapError> { + let invalid = |message: &str| Err(BootstrapError::Invalid(message.to_owned())); + if self.port == 0 { + return invalid("credential relay port must be non-zero"); + } + let unique = self + .services + .iter() + .collect::>(); + if self.services.is_empty() + || self.services.len() > MAX_CREDENTIAL_RELAY_SERVICES + || unique.len() != self.services.len() + || !self.services.iter().all(|service| { + let bytes = service.as_bytes(); + !bytes.is_empty() + && bytes.len() <= 32 + && bytes[0].is_ascii_lowercase() + && bytes.iter().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-' + }) + }) + { + return invalid("credential relay services must be 1-16 unique service ids"); + } + if !(1..=MAX_CREDENTIAL_RELAY_STREAMS).contains(&self.max_streams) { + return invalid("credential relay stream limit is out of range"); + } + if !(1..=MAX_CREDENTIAL_RELAY_REQUEST_BYTES).contains(&self.max_request_bytes) { + return invalid("credential relay request limit is out of range"); + } + Ok(()) + } +} + +fn validate_credential_relay( + relay: Option<&CredentialRelayBootstrap>, + egress: Option<&EgressRuntimePolicyDocument>, + has_broker: bool, +) -> Result<(), BootstrapError> { + let egress_port = egress.and_then(|policy| policy.credential_relay_port); + match relay { + None if egress_port.is_some() => Err(BootstrapError::Invalid( + "egress admits a credential relay port without a relay".to_owned(), + )), + None => Ok(()), + Some(relay) => { + relay.validate()?; + if !has_broker { + return Err(BootstrapError::Invalid( + "credential relay requires the authenticated execution broker".to_owned(), + )); + } + if egress.is_some() && egress_port != Some(relay.port) { + return Err(BootstrapError::Invalid( + "credential relay port does not match the signed egress policy".to_owned(), + )); + } + Ok(()) + } + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct BootstrapDocumentConfiguration { pub session_id: SessionId, @@ -328,6 +408,7 @@ pub struct BootstrapDocumentConfiguration { pub github_meta: Option, pub gateway_credentials: Vec, pub registry_proxy: Option, + pub credential_relay: Option, } pub struct BootstrapDocument { @@ -347,6 +428,7 @@ pub struct BootstrapDocument { pub github_meta: Option, pub gateway_credentials: Vec, pub registry_proxy: Option, + pub credential_relay: Option, } #[derive(Debug, Error)] @@ -389,6 +471,8 @@ struct BootstrapWire { gateway_credentials: Vec, #[serde(default)] registry_proxy: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + credential_relay: Option, } struct SecretBytes(Zeroizing<[u8; 32]>); @@ -493,6 +577,7 @@ pub fn encode_bootstrap_document( github_meta: configuration.github_meta, gateway_credentials: configuration.gateway_credentials, registry_proxy: configuration.registry_proxy, + credential_relay: configuration.credential_relay, }; let encoded = serde_json::to_vec(&wire).map_err(BootstrapError::Encode)?; if encoded.len() > MAX_BOOTSTRAP_BYTES { @@ -647,6 +732,11 @@ fn validate_configuration( .as_ref() .map(|broker| (broker.workload_uid, broker.workload_gid)), )?; + validate_credential_relay( + configuration.credential_relay.as_ref(), + configuration.egress_policy.as_ref(), + configuration.execution_broker.is_some(), + )?; Ok(()) } @@ -718,6 +808,11 @@ fn validate_wire(wire: BootstrapWire) -> Result Result RuntimePolicyDocument { RuntimePolicyDocument { schema_version: RUNTIME_POLICY_SCHEMA_VERSION, diff --git a/crates/sendbox-boundary/Cargo.toml b/crates/sendbox-boundary/Cargo.toml index 1770889..836a4c2 100644 --- a/crates/sendbox-boundary/Cargo.toml +++ b/crates/sendbox-boundary/Cargo.toml @@ -9,6 +9,7 @@ repository.workspace = true [dependencies] sendbox-config = { path = "../sendbox-config" } sendbox-core = { path = "../sendbox-core" } +sendbox-governance = { path = "../sendbox-governance" } sendbox-security = { path = "../sendbox-security" } serde.workspace = true serde_json.workspace = true diff --git a/crates/sendbox-boundary/src/lib.rs b/crates/sendbox-boundary/src/lib.rs index 72d21e5..626ac02 100644 --- a/crates/sendbox-boundary/src/lib.rs +++ b/crates/sendbox-boundary/src/lib.rs @@ -5,6 +5,7 @@ use std::path::{Path, PathBuf}; use sendbox_config::RuntimeProvider; use sendbox_core::{BoundaryPlanDigest, SessionId}; +pub use sendbox_governance::GovernanceBinding; use sendbox_security::SecurityError; use sendbox_security::provenance::{ DetachedSignature, Identity, SignedSubject, SigningKeyMaterial, SubjectKind, TrustPolicy, @@ -341,6 +342,10 @@ pub struct BoundaryPlan { pub artifacts: Vec, pub resources: ResourceDeclaration, pub features: BTreeMap, + /// Present only for governed sessions. Omitted entirely otherwise so + /// standalone plans keep their existing canonical bytes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub governance: Option, } impl BoundaryPlan { @@ -391,6 +396,16 @@ impl BoundaryPlan { "runtime resources must be greater than zero".to_owned(), )); } + if let Some(governance) = &self.governance { + governance + .validate() + .map_err(|error| BoundaryError::Invalid(error.to_string()))?; + if governance.effective_policy_sha256.to_string() != self.policy_sha256 { + return Err(BoundaryError::Invalid( + "governance binding does not match the signed policy digest".to_owned(), + )); + } + } for (feature, admission) in &self.features { if feature.is_empty() || feature.chars().any(char::is_control) @@ -988,6 +1003,7 @@ mod tests { mechanism: "authenticated guest broker".to_owned(), }, )]), + governance: None, } } @@ -1078,4 +1094,57 @@ mod tests { .expect("verified plan"); assert!(verified.reverify(now + 301).is_err()); } + + #[test] + fn governance_binding_is_omitted_when_absent_and_must_match_the_policy() { + use sendbox_governance::{ + AuthorityRef, CONTRACT_VERSION, PrincipalId, ProfileId, ProfileRef, ProjectId, + Sha256Digest, + }; + + let now = 50_000; + let standalone = plan(now); + let encoded = String::from_utf8(standalone.encode().expect("encode")).expect("utf8"); + assert!(!encoded.contains("governance")); + + let mut governed = plan(now); + governed.governance = Some(GovernanceBinding { + contract_version: CONTRACT_VERSION, + authority: AuthorityRef { + id: "local".to_owned(), + trust_sha256: Sha256Digest::of(b"trust"), + }, + profile: ProfileRef { + id: ProfileId::new("acme").expect("profile id"), + revision: 2, + sha256: Sha256Digest::of(b"profile"), + }, + principal: PrincipalId::local_user(501), + project: ProjectId::new("github:octo/api").expect("project id"), + effective_policy_sha256: Sha256Digest::parse_hex(&governed.policy_sha256) + .expect("policy digest"), + brokered_services: Vec::new(), + }); + governed.validate(now).expect("governed plan"); + assert_ne!( + governed.digest().expect("digest"), + standalone.digest().expect("digest") + ); + let key = SigningKeyMaterial::generate().expect("signing key"); + let signed = SignedBoundaryPlan::sign(governed.clone(), &key, now).expect("signed plan"); + assert_eq!( + SignedBoundaryPlan::decode(&signed.encode().expect("encode")) + .expect("decode") + .plan + .governance, + governed.governance + ); + + governed + .governance + .as_mut() + .expect("binding") + .effective_policy_sha256 = Sha256Digest::of(b"other policy"); + assert!(governed.validate(now).is_err()); + } } diff --git a/crates/sendbox-cli/Cargo.toml b/crates/sendbox-cli/Cargo.toml index f20879c..bea45a6 100644 --- a/crates/sendbox-cli/Cargo.toml +++ b/crates/sendbox-cli/Cargo.toml @@ -17,6 +17,7 @@ rpassword.workspace = true sendbox-agent = { path = "../sendbox-agent" } sendbox-config = { path = "../sendbox-config" } sendbox-core = { path = "../sendbox-core" } +sendbox-governance = { path = "../sendbox-governance" } sendbox-host = { path = "../sendbox-host" } sendbox-mcp = { path = "../sendbox-mcp" } sendbox-policy = { path = "../sendbox-policy" } @@ -24,10 +25,12 @@ sendbox-project = { path = "../sendbox-project" } sendbox-registry = { path = "../sendbox-registry" } sendbox-runtime = { path = "../sendbox-runtime" } sendbox-secrets = { path = "../sendbox-secrets" } +sendbox-security = { path = "../sendbox-security" } serde.workspace = true serde_json.workspace = true sha2.workspace = true tokio = { workspace = true, features = ["io-std", "rt", "signal", "sync"] } +zeroize.workspace = true [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["event", "pipe", "stdio", "termios"] } diff --git a/crates/sendbox-cli/src/governance.rs b/crates/sendbox-cli/src/governance.rs new file mode 100644 index 0000000..78a99d1 --- /dev/null +++ b/crates/sendbox-cli/src/governance.rs @@ -0,0 +1,458 @@ +use std::collections::BTreeMap; +use std::fs::{self, OpenOptions}; +use std::io::Write as _; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::time::{SystemTime, UNIX_EPOCH}; + +use clap::{Args, Subcommand, ValueEnum}; +use sendbox_config::SandboxConfiguration; +use sendbox_governance::{GovernanceProfile, RuntimeKind}; +use sendbox_host::governance::{ + GovernanceCheckRequest, MANAGED_CONFIGURATION_PATH, SIGNATURES_FORMAT, check, + encode_signatures, verify_active, +}; +use sendbox_security::provenance::{ + DetachedSignature, SignedSubject, SigningKeyMaterial, SubjectKind, +}; +use serde::{Deserialize, Serialize}; +use zeroize::Zeroizing; + +use crate::{GOVERNANCE_EXIT, INVALID_CONFIGURATION_EXIT, print_json}; + +#[derive(Debug, Args)] +pub(crate) struct GovernanceArgs { + #[command(subcommand)] + command: GovernanceCommand, +} + +#[derive(Debug, Subcommand)] +enum GovernanceCommand { + /// Create an Ed25519 profile-signing key and print its public identity. + Keygen(KeygenArgs), + /// Sign the exact bytes of a governance profile. + Sign(SignArgs), + /// Verify the active governance profile and its signatures. + Verify(VerifyArgs), + /// Explain whether a project configuration fits the active profile. + Check(CheckArgs), +} + +#[derive(Debug, Args)] +struct KeygenArgs { + /// New private key file; created with mode 0600 and never overwritten. + #[arg(long, value_name = "PATH")] + output: PathBuf, + #[arg(long, default_value = "SendBox governance operator")] + name: String, + #[arg(long)] + email: Option, + #[arg(long, value_name = "UNIX_SECONDS")] + expires_at_unix: Option, + #[arg(long, help = "Emit a deterministic JSON result")] + json: bool, +} + +#[derive(Debug, Args)] +struct SignArgs { + #[arg(value_name = "PROFILE")] + profile: PathBuf, + #[arg(long, value_name = "PATH")] + key: PathBuf, + /// Signature bundle path. Defaults to PROFILE.sig.json. + #[arg(long, value_name = "PATH")] + output: Option, + /// Add this signature to an existing bundle for threshold signing. + #[arg(long)] + append: bool, + #[arg(long, value_name = "UNIX_SECONDS")] + expires_at_unix: Option, + #[arg(long, help = "Emit a deterministic JSON result")] + json: bool, +} + +#[derive(Debug, Args)] +struct VerifyArgs { + /// Opt-in operator configuration. Ignored in favor of the managed + /// configuration when one exists. + #[arg(long, value_name = "PATH")] + governance_config: Option, + #[arg(long, help = "Emit a deterministic JSON result")] + json: bool, +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum CheckRuntime { + Apple, + Kata, +} + +#[derive(Debug, Args)] +struct CheckArgs { + #[arg(long, value_name = "PATH")] + config: PathBuf, + #[arg(long, value_name = "PATH")] + governance_config: Option, + #[arg(long, value_enum)] + runtime: Option, + #[arg(long, value_name = "IMAGE@sha256:DIGEST")] + image: Option, + #[arg(long, help = "Emit a deterministic JSON result")] + json: bool, +} + +#[derive(Debug, Serialize)] +struct KeygenResult { + schema_version: u32, + ok: bool, + key: String, + identity: sendbox_security::provenance::Identity, +} + +#[derive(Debug, Serialize)] +struct SignResult { + schema_version: u32, + ok: bool, + profile: String, + revision: u64, + sha256: String, + signatures: String, + signer: String, + signature_count: usize, +} + +#[derive(Debug, Serialize)] +struct VerifyResult { + schema_version: u32, + ok: bool, + governed: bool, + mode: Option, + authority: Option, + profile: Option, + revision: Option, + sha256: Option, + expires_at_unix: Option, + signers: Vec, + credential_services: Vec, +} + +#[derive(Debug, Deserialize)] +struct SignatureBundle { + signatures: Vec, +} + +pub(crate) fn execute(arguments: GovernanceArgs) -> ExitCode { + let (json, result) = match arguments.command { + GovernanceCommand::Keygen(arguments) => (arguments.json, keygen(&arguments)), + GovernanceCommand::Sign(arguments) => (arguments.json, sign(&arguments)), + GovernanceCommand::Verify(arguments) => (arguments.json, verify(&arguments)), + GovernanceCommand::Check(arguments) => (arguments.json, check_configuration(&arguments)), + }; + match result { + Ok(code) => code, + Err((code, message)) => { + if json { + print_json(&serde_json::json!({ + "schema_version": sendbox_core::CONFIG_SCHEMA_VERSION, + "ok": false, + "exit_code": code, + "message": message, + })); + } else { + eprintln!("sendbox governance: {message}"); + } + ExitCode::from(code) + } + } +} + +type CommandResult = Result; + +fn invalid(message: impl ToString) -> (u8, String) { + (INVALID_CONFIGURATION_EXIT, message.to_string()) +} + +fn governance(message: impl ToString) -> (u8, String) { + (GOVERNANCE_EXIT, message.to_string()) +} + +fn now_unix() -> Result { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs()) + .map_err(|error| invalid(format!("system clock is before the Unix epoch: {error}"))) +} + +fn keygen(arguments: &KeygenArgs) -> CommandResult { + let now = now_unix()?; + let key = SigningKeyMaterial::generate().map_err(invalid)?; + let exported = key.export(); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&arguments.output) + .map_err(|error| { + invalid(format!( + "create private key {}: {error}", + arguments.output.display() + )) + })?; + file.write_all(exported.as_bytes()) + .and_then(|()| file.write_all(b"\n")) + .and_then(|()| file.sync_all()) + .map_err(|error| invalid(format!("write private key: {error}")))?; + let identity = key.identity( + arguments.name.clone(), + arguments.email.clone(), + now, + arguments.expires_at_unix, + ); + if arguments.json { + print_json(&KeygenResult { + schema_version: sendbox_core::CONFIG_SCHEMA_VERSION, + ok: true, + key: arguments.output.display().to_string(), + identity, + }); + } else { + eprintln!( + "private key written to {}; keep it offline. Add this identity to trust.signers:", + arguments.output.display() + ); + println!( + "{}", + serde_json::to_string_pretty(&identity).map_err(invalid)? + ); + } + Ok(ExitCode::SUCCESS) +} + +fn read_private_key(path: &Path) -> Result { + let metadata = fs::symlink_metadata(path) + .map_err(|error| invalid(format!("inspect private key {}: {error}", path.display())))?; + if metadata.file_type().is_symlink() + || !metadata.is_file() + || metadata.permissions().mode() & 0o077 != 0 + || metadata.uid() != rustix_uid() + { + return Err(invalid( + "private key must be a regular file owned by you with mode 0600", + )); + } + let text = Zeroizing::new( + fs::read_to_string(path).map_err(|error| invalid(format!("read private key: {error}")))?, + ); + SigningKeyMaterial::import(text.trim()).map_err(invalid) +} + +fn rustix_uid() -> u32 { + rustix::process::getuid().as_raw() +} + +fn sign(arguments: &SignArgs) -> CommandResult { + let bytes = fs::read(&arguments.profile) + .map_err(|error| invalid(format!("read {}: {error}", arguments.profile.display())))?; + let profile = GovernanceProfile::parse(&bytes).map_err(invalid)?; + let key = read_private_key(&arguments.key)?; + let now = now_unix()?; + let signature = DetachedSignature::sign( + SignedSubject::from_bytes(SubjectKind::Configuration, None, &bytes), + &key, + now, + arguments.expires_at_unix, + BTreeMap::new(), + ) + .map_err(invalid)?; + let signer = signature.signer_fingerprint.clone(); + let output = arguments.output.clone().unwrap_or_else(|| { + let mut path = arguments.profile.clone().into_os_string(); + path.push(".sig.json"); + PathBuf::from(path) + }); + let mut signatures = Vec::new(); + if arguments.append { + let existing = fs::read(&output) + .map_err(|error| invalid(format!("read {}: {error}", output.display())))?; + let bundle: SignatureBundle = serde_json::from_slice(&existing) + .map_err(|error| invalid(format!("{SIGNATURES_FORMAT}: {error}")))?; + let reference = profile.reference(&bytes); + for existing in bundle.signatures { + if existing.subject.sha256 != reference.sha256.to_string() { + return Err(invalid( + "existing signatures cover different profile bytes; re-sign every signer", + )); + } + if existing.signer_fingerprint != signer { + signatures.push(existing); + } + } + } else if output.exists() { + return Err(invalid(format!( + "{} exists; pass --append to add a signature", + output.display() + ))); + } + signatures.push(signature); + let encoded = encode_signatures(&signatures).map_err(invalid)?; + let temporary = output.with_extension("json.tmp"); + let write = || -> std::io::Result<()> { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o644) + .open(&temporary)?; + file.write_all(&encoded)?; + file.sync_all()?; + fs::rename(&temporary, &output) + }; + if let Err(error) = write() { + let _ = fs::remove_file(&temporary); + return Err(invalid(format!("write {}: {error}", output.display()))); + } + let reference = profile.reference(&bytes); + if arguments.json { + print_json(&SignResult { + schema_version: sendbox_core::CONFIG_SCHEMA_VERSION, + ok: true, + profile: reference.id.to_string(), + revision: reference.revision, + sha256: reference.sha256.to_string(), + signatures: output.display().to_string(), + signer, + signature_count: signatures.len(), + }); + } else { + println!( + "signed {} revision {} ({}) -> {} [{} signature(s)]", + reference.id, + reference.revision, + reference.sha256, + output.display(), + signatures.len() + ); + } + Ok(ExitCode::SUCCESS) +} + +fn verify(arguments: &VerifyArgs) -> CommandResult { + let active = verify_active( + Path::new(MANAGED_CONFIGURATION_PATH), + arguments.governance_config.as_deref(), + ) + .map_err(governance)?; + let result = match &active { + None => VerifyResult { + schema_version: sendbox_core::CONFIG_SCHEMA_VERSION, + ok: true, + governed: false, + mode: None, + authority: None, + profile: None, + revision: None, + sha256: None, + expires_at_unix: None, + signers: Vec::new(), + credential_services: Vec::new(), + }, + Some(active) => VerifyResult { + schema_version: sendbox_core::CONFIG_SCHEMA_VERSION, + ok: true, + governed: true, + mode: serde_json::to_value(active.source.mode) + .ok() + .and_then(|value| value.as_str().map(str::to_owned)), + authority: Some(active.verified.authority.id.clone()), + profile: Some(active.verified.reference.id.to_string()), + revision: Some(active.verified.reference.revision), + sha256: Some(active.verified.reference.sha256.to_string()), + expires_at_unix: Some(active.verified.profile.expires_at_unix), + signers: active.verified.signers.iter().cloned().collect(), + credential_services: active + .verified + .profile + .credential_services + .iter() + .map(|service| service.id.to_string()) + .collect(), + }, + }; + if arguments.json { + print_json(&result); + } else if !result.governed { + println!( + "no governance configured ({MANAGED_CONFIGURATION_PATH} is absent and no --governance-config was given)" + ); + } else { + println!( + "verified {} profile {} revision {} ({}) signed by {} trusted signer(s); expires at {}", + result.mode.as_deref().unwrap_or_default(), + result.profile.as_deref().unwrap_or_default(), + result.revision.unwrap_or_default(), + result.sha256.as_deref().unwrap_or_default(), + result.signers.len(), + result.expires_at_unix.unwrap_or_default(), + ); + if !result.credential_services.is_empty() { + println!( + "brokered credential services: {}", + result.credential_services.join(", ") + ); + } + } + Ok(ExitCode::SUCCESS) +} + +fn check_configuration(arguments: &CheckArgs) -> CommandResult { + let configuration = SandboxConfiguration::load(&arguments.config).map_err(invalid)?; + let report = check(GovernanceCheckRequest { + configuration, + managed_path: PathBuf::from(MANAGED_CONFIGURATION_PATH), + governance_config: arguments.governance_config.clone(), + runtime: arguments.runtime.map(|runtime| match runtime { + CheckRuntime::Apple => RuntimeKind::Apple, + CheckRuntime::Kata => RuntimeKind::Kata, + }), + image: arguments.image.clone(), + }) + .map_err(governance)?; + if arguments.json { + print_json(&serde_json::json!({ + "schema_version": sendbox_core::CONFIG_SCHEMA_VERSION, + "ok": report.admitted, + "report": report, + })); + } else { + match &report.profile { + None => println!("no governance configured"), + Some(profile) => println!( + "profile {profile} revision {} ({})", + report.profile_revision.unwrap_or_default(), + report.profile_sha256.as_deref().unwrap_or_default() + ), + } + for (label, entries) in [ + ("denied commands", &report.applied_denials.commands), + ("blocked domains", &report.applied_denials.domains), + ("blocked networks", &report.applied_denials.networks), + ] { + if !entries.is_empty() { + println!("adds {label}: {}", entries.join(", ")); + } + } + if report.admitted { + println!("admitted"); + } else { + println!("rejected:"); + for violation in &report.violations { + println!(" - {violation}"); + } + } + } + Ok(if report.admitted { + ExitCode::SUCCESS + } else { + ExitCode::from(GOVERNANCE_EXIT) + }) +} diff --git a/crates/sendbox-cli/src/main.rs b/crates/sendbox-cli/src/main.rs index aafa1fc..4a29baa 100644 --- a/crates/sendbox-cli/src/main.rs +++ b/crates/sendbox-cli/src/main.rs @@ -2,6 +2,7 @@ mod boundary; mod completions; +mod governance; mod mcp; mod package; mod secrets; @@ -35,6 +36,7 @@ const INVALID_CONFIGURATION_EXIT: u8 = 2; const ANALYSIS_EXIT: u8 = 3; const OUTPUT_EXIT: u8 = 4; const RUNTIME_EXIT: u8 = 5; +const GOVERNANCE_EXIT: u8 = 6; #[derive(Debug, Parser)] #[command( @@ -54,6 +56,8 @@ enum Command { Boundary(boundary::BoundaryArgs), Completions(CompletionsArgs), Devcontainer(Box), + /// Sign, verify, and check operator governance profiles. + Governance(governance::GovernanceArgs), Init(InitArgs), Mcp(mcp::McpArgs), Package(package::PackageArgs), @@ -87,6 +91,10 @@ struct RunArgs { trust_root_id: String, #[arg(long, default_value_t = 1)] minimum_release_sequence: u64, + /// Opt-in governance configuration for an unmanaged host. Rejected when an + /// operator-managed configuration exists. + #[arg(long, value_name = "PATH")] + governance_config: Option, #[arg(long)] json: bool, /// Run the workload on a pseudoterminal and forward this terminal's @@ -435,6 +443,7 @@ async fn main() -> ExitCode { Command::Devcontainer(arguments) => match arguments.command { DevContainerCommand::Generate(arguments) => generate_devcontainer(arguments), }, + Command::Governance(arguments) => governance::execute(arguments), Command::Init(arguments) => init(arguments), Command::Mcp(arguments) => mcp::execute(arguments), Command::Package(arguments) => match runtime_state_directory() { @@ -525,6 +534,10 @@ async fn run(arguments: RunArgs) -> ExitCode { state_root, readiness_timeout: Duration::from_secs(60), terminal: terminal_size, + managed_governance_path: PathBuf::from( + sendbox_host::governance::MANAGED_CONFIGURATION_PATH, + ), + governance_config: arguments.governance_config, }) .await { @@ -1320,7 +1333,13 @@ fn host_error_exit_code(error: &HostError) -> u8 { { INVALID_CONFIGURATION_EXIT } + HostError::CredentialMasked { kind, .. } + if matches!(*kind, "governance" | "governance_rejected") => + { + GOVERNANCE_EXIT + } HostError::OutputFinalization { runtime, .. } => host_error_exit_code(runtime), + HostError::Governance(_) | HostError::GovernanceRejected { .. } => GOVERNANCE_EXIT, error if error.is_github_meta_policy_denial() => INVALID_CONFIGURATION_EXIT, HostError::Invalid(_) | HostError::Boundary(_) diff --git a/crates/sendbox-config/src/lib.rs b/crates/sendbox-config/src/lib.rs index 8150dce..24360d6 100644 --- a/crates/sendbox-config/src/lib.rs +++ b/crates/sendbox-config/src/lib.rs @@ -397,6 +397,11 @@ pub struct SandboxConfiguration { pub resources: ResourceConfiguration, pub policy: PolicyConfiguration, pub secrets: Vec, + /// Brokered credential services, by governance-profile service id, that + /// this project requests. Only governed sessions can use them; the + /// credential itself never enters the guest. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub credential_services: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub devcontainer: Option, pub github: GitHubConfiguration, @@ -477,6 +482,7 @@ impl SandboxConfiguration { resources: ResourceConfiguration::default(), policy, secrets: Vec::new(), + credential_services: Vec::new(), devcontainer: Some(DevContainerConfiguration { config_path: None, auto_generate: true, @@ -561,6 +567,7 @@ impl SandboxConfiguration { ); } } + self.validate_credential_services(&mut diagnostics); if diagnostics.is_empty() { Ok(()) @@ -605,6 +612,32 @@ impl SandboxConfiguration { }) } + fn validate_credential_services(&self, diagnostics: &mut Vec) { + let mut seen = std::collections::BTreeSet::new(); + for (index, service) in self.credential_services.iter().enumerate() { + let bytes = service.as_bytes(); + let valid = !bytes.is_empty() + && bytes.len() <= 32 + && bytes[0].is_ascii_lowercase() + && bytes.iter().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-' + }); + if !valid { + invalid_value( + diagnostics, + format!("credential_services[{index}]"), + "must be a governance-profile service id: 1-32 lowercase letters, digits, or '-', starting with a letter", + ); + } else if !seen.insert(service) { + invalid_value( + diagnostics, + format!("credential_services[{index}]"), + "is listed more than once", + ); + } + } + } + fn validate_runtime(&self, diagnostics: &mut Vec) { let Some(runtime) = &self.runtime else { return; diff --git a/crates/sendbox-credentials/Cargo.toml b/crates/sendbox-credentials/Cargo.toml index dc9f8c1..96a67e1 100644 --- a/crates/sendbox-credentials/Cargo.toml +++ b/crates/sendbox-credentials/Cargo.toml @@ -13,6 +13,8 @@ http.workspace = true reqwest.workspace = true sendbox-config = { path = "../sendbox-config" } sendbox-egress = { path = "../sendbox-egress" } +sendbox-governance = { path = "../sendbox-governance" } +sendbox-protocol = { path = "../sendbox-protocol" } sendbox-runtime = { path = "../sendbox-runtime" } sendbox-secrets = { path = "../sendbox-secrets" } serde.workspace = true diff --git a/crates/sendbox-credentials/src/http1.rs b/crates/sendbox-credentials/src/http1.rs index ecbda7c..211bf71 100644 --- a/crates/sendbox-credentials/src/http1.rs +++ b/crates/sendbox-credentials/src/http1.rs @@ -12,14 +12,14 @@ const HEADER_END: &[u8] = b"\r\n\r\n"; const READ_CHUNK_BYTES: usize = 1024; #[derive(Debug)] -pub(crate) struct ParsedRequest { +pub struct ParsedRequest { pub method: Method, pub target: String, pub headers: Vec<(HeaderName, HeaderValue)>, pub body: Vec, } -pub(crate) async fn read_request( +pub async fn read_request( reader: &mut (impl AsyncRead + Unpin), limits: &BrokerLimits, max_body_bytes: usize, @@ -337,9 +337,7 @@ fn find_header_end(bytes: &[u8]) -> Option { .position(|window| window == HEADER_END) } -pub(crate) fn strip_hop_by_hop( - headers: &[(HeaderName, HeaderValue)], -) -> Vec<(HeaderName, HeaderValue)> { +pub fn strip_hop_by_hop(headers: &[(HeaderName, HeaderValue)]) -> Vec<(HeaderName, HeaderValue)> { let mut connection_named = Vec::new(); for (name, value) in headers { if name == http::header::CONNECTION diff --git a/crates/sendbox-credentials/src/lib.rs b/crates/sendbox-credentials/src/lib.rs index 8984aba..fa3b251 100644 --- a/crates/sendbox-credentials/src/lib.rs +++ b/crates/sendbox-credentials/src/lib.rs @@ -4,7 +4,8 @@ mod broker; mod config; mod error; mod github; -mod http1; +pub mod http1; +pub mod relay; mod session; mod upstream; @@ -25,8 +26,8 @@ pub use session::{ SessionCredentialConfiguration, }; pub use upstream::{ - PinnedHttpsTransport, SystemResolver, UpstreamRequest, UpstreamResolver, UpstreamResponse, - UpstreamTransport, + PinnedHttpsTransport, ResponseBody, StreamingLimits, StreamingResponse, StreamingTransport, + SystemResolver, UpstreamRequest, UpstreamResolver, UpstreamResponse, UpstreamTransport, }; #[doc(hidden)] diff --git a/crates/sendbox-credentials/src/relay.rs b/crates/sendbox-credentials/src/relay.rs new file mode 100644 index 0000000..f85cdfa --- /dev/null +++ b/crates/sendbox-credentials/src/relay.rs @@ -0,0 +1,1574 @@ +//! Host side of the brokered credential relay. +//! +//! The guest forwards one HTTP request per relay stream over the +//! authenticated control channel. This endpoint authorizes every request +//! against the session's grants, injects the provider credential that only +//! the host holds, streams the verified HTTPS response back under credit flow +//! control, and records redacted audit evidence. The workload never receives +//! the credential and cannot choose the upstream, identity, or secret. + +use std::collections::{BTreeMap, HashMap}; +use std::fmt; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use http::{HeaderName, Method}; +use sendbox_governance::{CredentialProvider, CredentialServiceProfile, ProviderInjection}; +use sendbox_protocol::relay::{ + CREDENTIAL_RELAY_CHUNK_BYTES, CREDENTIAL_RELAY_SCHEMA_VERSION, CREDENTIAL_RELAY_WINDOW_CHUNKS, + CredentialRelayCreditV1, CredentialRelayEndV1, CredentialRelayHeaderV1, + CredentialRelayOutcomeV1, CredentialRelayRequestV1, CredentialRelayResponseHeadV1, + valid_credential_relay_stream, +}; +use sendbox_protocol::{Event, EventKind}; +use sendbox_runtime::CancellationToken; +use sendbox_secrets::{ + BrokerRequest, CredentialInjection, CredentialPolicy, RedirectPolicy, SecretName, +}; +use tokio::sync::Semaphore; +use tokio::task::JoinSet; +use url::Url; +use zeroize::Zeroizing; + +use crate::{ + CredentialBrokerError, SecretResolver, StreamingLimits, StreamingTransport, + UpstreamAddressPolicy, UpstreamRequest, +}; + +pub type RelayFuture<'a, T> = Pin + Send + 'a>>; + +/// Hard cap for the policy-level buffered response limit; streamed responses +/// use the service limit instead. +const POLICY_RESPONSE_LIMIT: usize = 16 * 1024 * 1024; +const MAX_AUDIT_PATH_BYTES: usize = 256; + +/// One brokered service as configured by the operator profile. +pub struct RelayService { + id: String, + provider: CredentialProvider, + policy: CredentialPolicy, + secret: SecretName, + methods: Vec, + path_prefixes: Vec, + max_request_bytes: usize, + max_response_bytes: u64, + max_duration: Duration, + idle_timeout: Duration, +} + +impl fmt::Debug for RelayService { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("RelayService") + .field("id", &self.id) + .field("provider", &self.provider) + .field("target", &self.policy.target_host()) + .finish_non_exhaustive() + } +} + +impl RelayService { + pub fn from_profile(profile: &CredentialServiceProfile) -> Result { + let invalid = |message: &str| { + CredentialBrokerError::InvalidConfiguration(format!( + "credential service `{}`: {message}", + profile.id + )) + }; + let secret = + SecretName::new(profile.secret.clone()).map_err(|error| invalid(&error.to_string()))?; + let methods = profile + .effective_methods() + .iter() + .map(|method| Method::from_bytes(method.as_bytes()).map_err(|_| invalid("bad method"))) + .collect::, _>>()?; + let max_request_bytes = usize::try_from(profile.max_request_bytes) + .map_err(|_| invalid("request limit is out of range"))?; + let injection = match profile.provider.injection() { + ProviderInjection::Bearer => CredentialInjection::Bearer, + ProviderInjection::Header(name) => CredentialInjection::Header { + name: HeaderName::from_static(name), + }, + }; + let policy = CredentialPolicy::new( + profile.provider.target_host(), + "/", + injection, + methods.iter().cloned(), + max_request_bytes, + usize::try_from(profile.max_response_bytes) + .unwrap_or(POLICY_RESPONSE_LIMIT) + .min(POLICY_RESPONSE_LIMIT), + RedirectPolicy::Deny, + secret.clone(), + )?; + Ok(Self { + id: profile.id.to_string(), + provider: profile.provider, + policy, + secret, + methods, + path_prefixes: profile.effective_path_prefixes(), + max_request_bytes, + max_response_bytes: profile.max_response_bytes, + max_duration: Duration::from_secs(profile.max_duration_seconds), + idle_timeout: Duration::from_secs(profile.idle_timeout_seconds), + }) + } + + #[must_use] + pub fn id(&self) -> &str { + &self.id + } + + #[must_use] + pub fn secret_name(&self) -> &SecretName { + &self.secret + } +} + +/// Decision for one relay request. Implementations consult the grant +/// authority with identity taken from trusted host state. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RelayAuthorization { + Allowed { grant: String, generation: u64 }, + Denied { reason: &'static str }, +} + +pub trait RelayAuthorizer: Send + Sync { + fn authorize<'a>( + &'a self, + service: &'a str, + method: &'a str, + path: &'a str, + ) -> RelayFuture<'a, RelayAuthorization>; +} + +/// Delivers host-to-guest relay events over the authenticated channel. +pub trait RelayOutbound: Send + Sync { + fn send(&self, event: Event) -> RelayFuture<'_, Result<(), CredentialBrokerError>>; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RelayStreamOutcome { + Complete, + Denied, + Failed, + Aborted, + /// Aborted after the request reached the upstream; it may have been + /// processed and its external effects are not reversed. + AbortedUncertain, +} + +impl RelayStreamOutcome { + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::Complete => "complete", + Self::Denied => "denied", + Self::Failed => "failed", + Self::Aborted => "aborted", + Self::AbortedUncertain => "aborted_uncertain", + } + } +} + +/// Redacted audit evidence. Paths never include the query string and no +/// header, body, or credential is ever recorded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RelayAuditEvent { + Decision { + stream: u64, + service: String, + method: String, + path: String, + allowed: bool, + reason: &'static str, + grant: Option, + generation: Option, + }, + Outcome { + stream: u64, + service: String, + method: String, + path: String, + outcome: RelayStreamOutcome, + reason: &'static str, + status: Option, + request_bytes: u64, + response_bytes: u64, + duration_ms: u64, + }, +} + +pub trait RelayAuditSink: Send + Sync { + fn record(&self, event: RelayAuditEvent); +} + +#[derive(Debug, Clone)] +pub struct RelayLimits { + pub max_streams: usize, + pub connect_timeout: Duration, + pub max_header_count: usize, + pub max_header_bytes: usize, + pub address_policy: UpstreamAddressPolicy, +} + +impl Default for RelayLimits { + fn default() -> Self { + Self { + max_streams: 8, + connect_timeout: Duration::from_secs(10), + max_header_count: 64, + max_header_bytes: 32 * 1024, + address_policy: UpstreamAddressPolicy::default(), + } + } +} + +/// A violation that makes the relay channel itself untrustworthy. The caller +/// must fail the session rather than continue. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("credential relay protocol violation: {0}")] +pub struct RelayProtocolError(pub &'static str); + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RelayCloseReport { + pub completed: usize, + pub aborted: usize, +} + +struct Receiving { + service: Arc, + request: CredentialRelayRequestV1, + body: Zeroizing>, + expected: usize, +} + +/// Why a running stream was cancelled. The first cause recorded wins. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum AbortCause { + /// The guest ended the stream; it already knows, so no `End` is sent. + Guest, + /// The stream's grant lapsed and its revocation grace elapsed. + GrantLapsed, + /// The session is closing. + Closing, +} + +struct Running { + service: String, + cancel: CancellationToken, + cause: Arc>, + credits: Arc, + sent: Arc, + granted: u64, +} + +enum StreamState { + Receiving(Receiving), + Running(Running), +} + +#[derive(Default)] +struct EndpointState { + streams: HashMap, + last_stream: u64, + outbound: Option>, +} + +struct Shared { + services: BTreeMap>, + authorizer: Arc, + secrets: Arc, + transport: Arc, + audit: Arc, + limits: RelayLimits, + state: Mutex, + closed: AtomicBool, + closing: CancellationToken, +} + +impl Shared { + fn lock(&self) -> std::sync::MutexGuard<'_, EndpointState> { + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn outbound(&self) -> Option> { + self.lock().outbound.clone() + } + + fn finish(&self, stream: u64) { + self.lock().streams.remove(&stream); + } +} + +pub struct RelayEndpoint { + shared: Arc, + tasks: Mutex>, +} + +impl fmt::Debug for RelayEndpoint { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("RelayEndpoint") + .field("services", &self.shared.services.keys().collect::>()) + .finish_non_exhaustive() + } +} + +impl RelayEndpoint { + pub fn new( + services: Vec, + authorizer: Arc, + secrets: Arc, + transport: Arc, + audit: Arc, + limits: RelayLimits, + ) -> Result { + if services.is_empty() || limits.max_streams == 0 { + return Err(CredentialBrokerError::InvalidConfiguration( + "credential relay requires at least one service and stream".to_owned(), + )); + } + let mut by_id = BTreeMap::new(); + for service in services { + let id = service.id.clone(); + if by_id.insert(id.clone(), Arc::new(service)).is_some() { + return Err(CredentialBrokerError::InvalidConfiguration(format!( + "credential service `{id}` is duplicated" + ))); + } + } + Ok(Self { + shared: Arc::new(Shared { + services: by_id, + authorizer, + secrets, + transport, + audit, + limits, + state: Mutex::new(EndpointState::default()), + closed: AtomicBool::new(false), + closing: CancellationToken::new(), + }), + tasks: Mutex::new(JoinSet::new()), + }) + } + + /// Connects the endpoint to the guest channel of a running workload. + pub fn attach(&self, outbound: Arc) { + self.shared.lock().outbound = Some(outbound); + } + + fn spawn(&self, task: impl Future + Send + 'static) { + self.tasks + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .spawn(task); + } + + fn reply_end(&self, stream: u64, outcome: CredentialRelayOutcomeV1, reason: &'static str) { + if let Some(outbound) = self.shared.outbound() { + self.spawn(async move { + let _ = outbound.send(end_event(stream, outcome, reason)).await; + }); + } + } + + /// Accepts one guest relay event without blocking. Per-request problems + /// end only that stream; malformed channel use returns an error. + pub fn handle(&self, event: Event) -> Result<(), RelayProtocolError> { + let stream = event.stream_id; + if !valid_credential_relay_stream(stream) { + return Err(RelayProtocolError( + "stream identifier is outside the relay range", + )); + } + match event.kind { + EventKind::CredentialRelayRequest => self.open(stream, &event.payload), + EventKind::CredentialRelayRequestBody => self.body(stream, event.payload), + EventKind::CredentialRelayEnd => { + let end: CredentialRelayEndV1 = decode(&event.payload)?; + end.validate() + .map_err(|_| RelayProtocolError("invalid stream end"))?; + self.abort_stream(stream); + Ok(()) + } + EventKind::CredentialRelayCredit => { + let credit: CredentialRelayCreditV1 = decode(&event.payload)?; + credit + .validate() + .map_err(|_| RelayProtocolError("invalid credit"))?; + self.credit(stream, credit.credits) + } + _ => Err(RelayProtocolError("event kind is not a guest relay event")), + } + } + + fn open(&self, stream: u64, payload: &[u8]) -> Result<(), RelayProtocolError> { + let request: CredentialRelayRequestV1 = decode(payload)?; + let mut state = self.shared.lock(); + if stream <= state.last_stream { + return Err(RelayProtocolError("stream identifiers must increase")); + } + state.last_stream = stream; + if request.validate().is_err() { + drop(state); + self.reply_end(stream, CredentialRelayOutcomeV1::Denied, "invalid_request"); + return Ok(()); + } + if self.shared.closed.load(Ordering::SeqCst) { + drop(state); + self.reply_end(stream, CredentialRelayOutcomeV1::Denied, "session_closing"); + return Ok(()); + } + if state.streams.len() >= self.shared.limits.max_streams { + drop(state); + self.reply_end(stream, CredentialRelayOutcomeV1::Denied, "too_many_streams"); + return Ok(()); + } + let Some(service) = self.shared.services.get(&request.service).cloned() else { + drop(state); + self.shared.audit.record(RelayAuditEvent::Decision { + stream, + service: request.service.clone(), + method: request.method.clone(), + path: audit_path(&request.path), + allowed: false, + reason: "service_not_granted", + grant: None, + generation: None, + }); + self.reply_end( + stream, + CredentialRelayOutcomeV1::Denied, + "service_not_granted", + ); + return Ok(()); + }; + let Ok(expected) = usize::try_from(request.body_bytes) else { + drop(state); + self.reply_end( + stream, + CredentialRelayOutcomeV1::Denied, + "request_too_large", + ); + return Ok(()); + }; + if expected > service.max_request_bytes { + drop(state); + self.reply_end( + stream, + CredentialRelayOutcomeV1::Denied, + "request_too_large", + ); + return Ok(()); + } + let receiving = Receiving { + service, + request, + body: Zeroizing::new(Vec::with_capacity(expected.min(64 * 1024))), + expected, + }; + if expected == 0 { + drop(state); + self.start(stream, receiving); + } else { + state + .streams + .insert(stream, StreamState::Receiving(receiving)); + } + Ok(()) + } + + fn body(&self, stream: u64, bytes: Vec) -> Result<(), RelayProtocolError> { + if bytes.is_empty() || bytes.len() > CREDENTIAL_RELAY_CHUNK_BYTES { + return Err(RelayProtocolError("request body chunk size is invalid")); + } + let mut state = self.shared.lock(); + if stream > state.last_stream { + return Err(RelayProtocolError("request body for an unopened stream")); + } + let Some(StreamState::Receiving(receiving)) = state.streams.get_mut(&stream) else { + return Ok(()); + }; + if receiving.body.len().saturating_add(bytes.len()) > receiving.expected { + state.streams.remove(&stream); + drop(state); + self.reply_end( + stream, + CredentialRelayOutcomeV1::Failed, + "request_length_mismatch", + ); + return Ok(()); + } + receiving.body.extend_from_slice(&bytes); + let mut bytes = Zeroizing::new(bytes); + bytes.clear(); + if receiving.body.len() == receiving.expected { + let Some(StreamState::Receiving(receiving)) = state.streams.remove(&stream) else { + unreachable!("stream state was just matched"); + }; + drop(state); + self.start(stream, receiving); + } + Ok(()) + } + + fn credit(&self, stream: u64, credits: u16) -> Result<(), RelayProtocolError> { + let mut state = self.shared.lock(); + if stream > state.last_stream { + return Err(RelayProtocolError("credit for an unopened stream")); + } + let Some(StreamState::Running(running)) = state.streams.get_mut(&stream) else { + return Ok(()); + }; + let granted = running.granted.saturating_add(u64::from(credits)); + if granted > running.sent.load(Ordering::SeqCst) { + return Err(RelayProtocolError("credit exceeds the stream window")); + } + running.granted = granted; + running.credits.add_permits(usize::from(credits)); + Ok(()) + } + + fn abort_stream(&self, stream: u64) { + if let Some(state) = self.shared.lock().streams.remove(&stream) + && let StreamState::Running(running) = state + { + running.abort(AbortCause::Guest); + } + } + + fn start(&self, stream: u64, receiving: Receiving) { + let cancel = CancellationToken::new(); + let cause = Arc::new(OnceLock::new()); + let credits = Arc::new(Semaphore::new(usize::from(CREDENTIAL_RELAY_WINDOW_CHUNKS))); + let sent = Arc::new(AtomicU64::new(0)); + self.shared.lock().streams.insert( + stream, + StreamState::Running(Running { + service: receiving.service.id.clone(), + cancel: cancel.clone(), + cause: Arc::clone(&cause), + credits: Arc::clone(&credits), + sent: Arc::clone(&sent), + granted: 0, + }), + ); + let shared = Arc::clone(&self.shared); + self.spawn(async move { + let exchange = Exchange { + shared: Arc::clone(&shared), + stream, + started: Instant::now(), + service: receiving.service, + request: receiving.request, + cancel, + cause, + credits, + sent, + }; + exchange.run(receiving.body).await; + shared.finish(stream); + }); + } + + /// Ends streams of `services` that were authorized before their grant + /// lapsed. Later requests are denied by the authorizer; streams already + /// running get `grace` to finish before they are cancelled, and the guest + /// is told the stream ended with `grant_lapsed`. + pub fn expire_in_flight(&self, services: &[&str], grace: Duration) { + let running = self + .shared + .lock() + .streams + .values() + .filter_map(|stream| match stream { + StreamState::Running(running) if services.contains(&running.service.as_str()) => { + Some((running.cancel.clone(), Arc::clone(&running.cause))) + } + _ => None, + }) + .collect::>(); + if running.is_empty() { + return; + } + let closing = self.shared.closing.clone(); + self.spawn(async move { + tokio::select! { + () = tokio::time::sleep(grace) => {} + () = closing.cancelled() => return, + } + for (cancel, cause) in running { + let _ = cause.set(AbortCause::GrantLapsed); + cancel.cancel(); + } + }); + } + + /// Stops accepting requests, lets in-flight streams finish within + /// `grace`, then aborts the rest. Aborted streams that already reached the + /// upstream are reported as uncertain. + pub async fn close(&self, grace: Duration) -> RelayCloseReport { + self.shared.closed.store(true, Ordering::SeqCst); + self.shared.closing.cancel(); + let mut tasks = std::mem::take( + &mut *self + .tasks + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner), + ); + let mut report = RelayCloseReport::default(); + let deadline = tokio::time::Instant::now() + grace; + loop { + match tokio::time::timeout_at(deadline, tasks.join_next()).await { + Ok(Some(_)) => report.completed += 1, + Ok(None) => break, + Err(_) => { + let running = { + let mut state = self.shared.lock(); + state.streams.drain().collect::>() + }; + for (_, stream) in running { + if let StreamState::Running(running) = stream { + running.abort(AbortCause::Closing); + } + } + while let Some(result) = tasks.join_next().await { + if result.is_ok() { + report.aborted += 1; + } + } + break; + } + } + } + self.shared.lock().outbound = None; + report + } +} + +impl Running { + fn abort(&self, cause: AbortCause) { + let _ = self.cause.set(cause); + self.cancel.cancel(); + } +} + +struct Exchange { + shared: Arc, + stream: u64, + started: Instant, + service: Arc, + request: CredentialRelayRequestV1, + cancel: CancellationToken, + cause: Arc>, + credits: Arc, + sent: Arc, +} + +struct Progress { + contacted: bool, + status: Option, + response_bytes: u64, +} + +enum Failure { + Denied(&'static str), + Failed(&'static str), + Aborted, +} + +impl Exchange { + fn path(&self) -> &str { + self.request + .path + .split_once('?') + .map_or(self.request.path.as_str(), |(path, _)| path) + } + + async fn run(self, body: Zeroizing>) { + let request_bytes = body.len() as u64; + let mut progress = Progress { + contacted: false, + status: None, + response_bytes: 0, + }; + let result = self.forward(body, &mut progress).await; + let (outcome, reason, end) = match result { + Ok(()) => ( + RelayStreamOutcome::Complete, + "complete", + Some((CredentialRelayOutcomeV1::Complete, "complete")), + ), + Err(Failure::Denied(reason)) => ( + RelayStreamOutcome::Denied, + reason, + Some((CredentialRelayOutcomeV1::Denied, reason)), + ), + Err(Failure::Failed(reason)) => ( + RelayStreamOutcome::Failed, + reason, + Some((CredentialRelayOutcomeV1::Failed, reason)), + ), + Err(Failure::Aborted) => { + let reason = match self.cause.get() { + Some(AbortCause::GrantLapsed) => "grant_lapsed", + _ => "aborted", + }; + ( + if progress.contacted { + RelayStreamOutcome::AbortedUncertain + } else { + RelayStreamOutcome::Aborted + }, + reason, + (self.cause.get() != Some(&AbortCause::Guest)) + .then_some((CredentialRelayOutcomeV1::Aborted, reason)), + ) + } + }; + if let Some((outcome, reason)) = end + && let Some(outbound) = self.shared.outbound() + { + let _ = outbound.send(end_event(self.stream, outcome, reason)).await; + } + self.shared.audit.record(RelayAuditEvent::Outcome { + stream: self.stream, + service: self.service.id.clone(), + method: self.request.method.clone(), + path: audit_path(self.path()), + outcome, + reason, + status: progress.status, + request_bytes, + response_bytes: progress.response_bytes, + duration_ms: u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + }); + } + + async fn forward( + &self, + body: Zeroizing>, + progress: &mut Progress, + ) -> Result<(), Failure> { + let deadline = tokio::time::Instant::from_std(self.started + self.service.max_duration); + let method = Method::from_bytes(self.request.method.as_bytes()) + .map_err(|_| Failure::Denied("method_not_granted"))?; + let local_denial = if !self.service.methods.contains(&method) { + Some("method_not_granted") + } else if sendbox_governance::validate_request_path(self.path()).is_err() { + Some("invalid_path") + } else if !sendbox_governance::path_permitted(&self.service.path_prefixes, self.path()) { + Some("path_not_granted") + } else { + None + }; + let authorization = match local_denial { + Some(reason) => RelayAuthorization::Denied { reason }, + None => tokio::select! { + () = self.cancel.cancelled() => return Err(Failure::Aborted), + authorization = self.shared.authorizer.authorize( + &self.service.id, + &self.request.method, + self.path(), + ) => authorization, + }, + }; + let (allowed, reason, grant, generation) = match &authorization { + RelayAuthorization::Allowed { grant, generation } => { + (true, "allowed", Some(grant.clone()), Some(*generation)) + } + RelayAuthorization::Denied { reason } => (false, *reason, None, None), + }; + self.shared.audit.record(RelayAuditEvent::Decision { + stream: self.stream, + service: self.service.id.clone(), + method: self.request.method.clone(), + path: audit_path(self.path()), + allowed, + reason, + grant, + generation, + }); + if !allowed { + return Err(Failure::Denied(reason)); + } + + let secrets = Arc::clone(&self.shared.secrets); + let name = self.service.secret.clone(); + let secret = tokio::select! { + () = self.cancel.cancelled() => return Err(Failure::Aborted), + secret = tokio::task::spawn_blocking(move || secrets.retrieve(&name)) => secret + .map_err(|_| Failure::Failed("credential_unavailable"))? + .map_err(|_| Failure::Failed("credential_unavailable"))?, + }; + let url = Url::parse(&format!( + "https://{}{}", + self.service.policy.target_host(), + self.request.path + )) + .map_err(|_| Failure::Denied("invalid_path"))?; + let headers = self + .request + .headers + .iter() + .filter(|header| self.service.provider.forwards_request_header(&header.name)) + .map(|header| { + HeaderName::from_bytes(header.name.as_bytes()) + .map(|name| (name, header.value.as_bytes().to_vec())) + .map_err(|_| Failure::Denied("invalid_request")) + }) + .collect::, _>>()?; + let transformed = self + .service + .policy + .transform( + BrokerRequest { + method, + url, + headers, + body: body.to_vec(), + }, + &secret, + ) + .map_err(|_| Failure::Denied("request_rejected"))?; + drop(secret); + drop(body); + let upstream = UpstreamRequest::from_transformed(transformed, usize::MAX); + let limits = StreamingLimits { + connect_timeout: self.shared.limits.connect_timeout, + idle_timeout: self.service.idle_timeout, + max_header_count: self.shared.limits.max_header_count, + max_header_bytes: self.shared.limits.max_header_bytes, + }; + progress.contacted = true; + let mut response = tokio::select! { + () = self.cancel.cancelled() => return Err(Failure::Aborted), + () = tokio::time::sleep_until(deadline) => return Err(Failure::Failed("max_duration")), + response = self.shared.transport.open( + &upstream, + &limits, + &self.shared.limits.address_policy, + &self.cancel, + ) => response.map_err(|error| match error { + CredentialBrokerError::Cancelled => Failure::Aborted, + CredentialBrokerError::Upstream(message) if message.contains("address class") => { + Failure::Failed("upstream_address_denied") + } + _ => Failure::Failed("upstream_unavailable"), + })?, + }; + drop(upstream); + progress.status = Some(response.status.as_u16()); + if response.status.is_redirection() { + return Err(Failure::Failed("redirect_denied")); + } + let head = CredentialRelayResponseHeadV1 { + schema_version: CREDENTIAL_RELAY_SCHEMA_VERSION, + status: response.status.as_u16(), + headers: response + .headers + .iter() + .filter(|(name, _)| forwards_response_header(name)) + .filter_map(|(name, value)| { + value.to_str().ok().map(|value| CredentialRelayHeaderV1 { + name: name.as_str().to_owned(), + value: value.to_owned(), + }) + }) + .collect(), + }; + head.validate() + .map_err(|_| Failure::Failed("upstream_headers_invalid"))?; + self.send(Event { + stream_id: self.stream, + kind: EventKind::CredentialRelayResponseHead, + payload: serde_json::to_vec(&head).map_err(|_| Failure::Failed("encode_failed"))?, + }) + .await?; + + loop { + let chunk = tokio::select! { + () = self.cancel.cancelled() => return Err(Failure::Aborted), + () = tokio::time::sleep_until(deadline) => return Err(Failure::Failed("max_duration")), + chunk = tokio::time::timeout(self.service.idle_timeout, response.body.next_chunk()) => { + chunk + .map_err(|_| Failure::Failed("idle_timeout"))? + .map_err(|_| Failure::Failed("upstream_read_failed"))? + } + }; + let Some(chunk) = chunk else { + return Ok(()); + }; + progress.response_bytes = progress.response_bytes.saturating_add(chunk.len() as u64); + if progress.response_bytes > self.service.max_response_bytes { + return Err(Failure::Failed("response_too_large")); + } + for piece in chunk.chunks(CREDENTIAL_RELAY_CHUNK_BYTES) { + let permit = tokio::select! { + () = self.cancel.cancelled() => return Err(Failure::Aborted), + () = tokio::time::sleep_until(deadline) => return Err(Failure::Failed("max_duration")), + permit = tokio::time::timeout(self.service.idle_timeout, self.credits.acquire()) => permit + .map_err(|_| Failure::Failed("credit_timeout"))? + .map_err(|_| Failure::Aborted)?, + }; + permit.forget(); + self.sent.fetch_add(1, Ordering::SeqCst); + self.send(Event { + stream_id: self.stream, + kind: EventKind::CredentialRelayResponseBody, + payload: piece.to_vec(), + }) + .await?; + } + } + } + + async fn send(&self, event: Event) -> Result<(), Failure> { + let outbound = self.shared.outbound().ok_or(Failure::Aborted)?; + tokio::select! { + () = self.cancel.cancelled() => Err(Failure::Aborted), + result = outbound.send(event) => result.map_err(|_| Failure::Aborted), + } + } +} + +fn forwards_response_header(name: &HeaderName) -> bool { + !matches!( + name.as_str(), + "set-cookie" | "set-cookie2" | "content-length" | "transfer-encoding" | "connection" + ) +} + +fn end_event(stream: u64, outcome: CredentialRelayOutcomeV1, reason: &'static str) -> Event { + Event { + stream_id: stream, + kind: EventKind::CredentialRelayEnd, + payload: serde_json::to_vec(&CredentialRelayEndV1::new(outcome, reason)) + .expect("relay end payloads always encode"), + } +} + +fn decode(payload: &[u8]) -> Result { + serde_json::from_slice(payload).map_err(|_| RelayProtocolError("malformed relay payload")) +} + +fn audit_path(path: &str) -> String { + let path = path.split_once('?').map_or(path, |(path, _)| path); + if path.len() <= MAX_AUDIT_PATH_BYTES { + return path.to_owned(); + } + let mut end = MAX_AUDIT_PATH_BYTES; + while !path.is_char_boundary(end) { + end -= 1; + } + path[..end].to_owned() +} + +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::sync::atomic::AtomicUsize; + + use async_trait::async_trait; + use http::StatusCode; + use sendbox_governance::GovernanceProfile; + use sendbox_protocol::relay::CREDENTIAL_RELAY_STREAM_BASE; + use sendbox_secrets::SecretValue; + use tokio::sync::mpsc; + + use super::*; + use crate::{ResponseBody, StreamingResponse}; + + const SECRET: &str = "sk-ant-live-0123456789abcdef"; + + fn service(path_prefixes: &str) -> RelayService { + let profile = GovernanceProfile::parse( + format!( + r#" +format: sendbox.governance-profile +version: 1 +id: acme +revision: 1 +not_before_unix: 0 +expires_at_unix: 1000 +ceiling: + runtimes: [apple] + commands: {{ default_action: deny }} + network: {{ default_action: deny }} +credential_services: + - id: anthropic + provider: anthropic + secret: SENDBOX_ANTHROPIC_API_KEY + methods: [POST] + path_prefixes: [{path_prefixes}] + max_request_bytes: 64 + max_response_bytes: 4194304 + idle_timeout_seconds: 5 +"# + ) + .as_bytes(), + ) + .expect("profile"); + RelayService::from_profile(&profile.credential_services[0]).expect("service") + } + + struct Authorizer { + decision: RelayAuthorization, + calls: AtomicUsize, + } + + impl RelayAuthorizer for Authorizer { + fn authorize<'a>( + &'a self, + _service: &'a str, + _method: &'a str, + _path: &'a str, + ) -> RelayFuture<'a, RelayAuthorization> { + self.calls.fetch_add(1, Ordering::SeqCst); + Box::pin(async move { self.decision.clone() }) + } + } + + struct Secrets; + + impl SecretResolver for Secrets { + fn retrieve(&self, _name: &SecretName) -> Result { + Ok(SecretValue::try_from(SECRET).expect("secret")) + } + } + + #[derive(Debug, Clone)] + struct Captured { + method: String, + url: String, + headers: Vec<(String, String)>, + body: Vec, + } + + struct Chunks(VecDeque>, bool); + + #[async_trait] + impl ResponseBody for Chunks { + async fn next_chunk(&mut self) -> Result>, CredentialBrokerError> { + match self.0.pop_front() { + Some(chunk) => Ok(Some(chunk)), + None if self.1 => std::future::pending().await, + None => Ok(None), + } + } + } + + struct Transport { + status: StatusCode, + chunks: Vec>, + stall: bool, + captured: Mutex>, + } + + #[async_trait] + impl StreamingTransport for Transport { + async fn open( + &self, + request: &UpstreamRequest, + _limits: &StreamingLimits, + _address_policy: &UpstreamAddressPolicy, + _cancellation: &CancellationToken, + ) -> Result { + self.captured.lock().unwrap().push(Captured { + method: request.method().to_string(), + url: request.url().to_owned(), + headers: request + .headers() + .iter() + .map(|(name, value)| { + ( + name.as_str().to_owned(), + String::from_utf8_lossy(value.expose()).into_owned(), + ) + }) + .collect(), + body: request.body().to_vec(), + }); + Ok(StreamingResponse { + status: self.status, + headers: vec![ + ( + HeaderName::from_static("content-type"), + http::HeaderValue::from_static("text/event-stream"), + ), + ( + HeaderName::from_static("set-cookie"), + http::HeaderValue::from_static("session=1"), + ), + ], + body: Box::new(Chunks(self.chunks.clone().into(), self.stall)), + }) + } + } + + struct Outbound(mpsc::UnboundedSender); + + impl RelayOutbound for Outbound { + fn send(&self, event: Event) -> RelayFuture<'_, Result<(), CredentialBrokerError>> { + let result = self + .0 + .send(event) + .map_err(|_| CredentialBrokerError::Cancelled); + Box::pin(async move { result }) + } + } + + #[derive(Default)] + struct Audit(Mutex>); + + impl RelayAuditSink for Audit { + fn record(&self, event: RelayAuditEvent) { + self.0.lock().unwrap().push(event); + } + } + + struct Harness { + endpoint: RelayEndpoint, + events: mpsc::UnboundedReceiver, + authorizer: Arc, + transport: Arc, + audit: Arc, + } + + fn harness(decision: RelayAuthorization, transport: Transport) -> Harness { + let authorizer = Arc::new(Authorizer { + decision, + calls: AtomicUsize::new(0), + }); + let transport = Arc::new(transport); + let audit = Arc::new(Audit::default()); + let endpoint = RelayEndpoint::new( + vec![service("/v1/messages")], + authorizer.clone(), + Arc::new(Secrets), + transport.clone(), + audit.clone(), + RelayLimits { + max_streams: 2, + ..RelayLimits::default() + }, + ) + .expect("endpoint"); + let (sender, events) = mpsc::unbounded_channel(); + endpoint.attach(Arc::new(Outbound(sender))); + Harness { + endpoint, + events, + authorizer, + transport, + audit, + } + } + + fn transport(chunks: Vec>) -> Transport { + Transport { + status: StatusCode::OK, + chunks, + stall: false, + captured: Mutex::new(Vec::new()), + } + } + + fn allowed() -> RelayAuthorization { + RelayAuthorization::Allowed { + grant: "00".repeat(16), + generation: 1, + } + } + + fn request_event(stream: u64, path: &str, body: &[u8]) -> Vec { + let request = CredentialRelayRequestV1 { + schema_version: CREDENTIAL_RELAY_SCHEMA_VERSION, + service: "anthropic".to_owned(), + method: "POST".to_owned(), + path: path.to_owned(), + headers: vec![ + CredentialRelayHeaderV1 { + name: "content-type".to_owned(), + value: "application/json".to_owned(), + }, + CredentialRelayHeaderV1 { + name: "x-api-key".to_owned(), + value: "agent-supplied".to_owned(), + }, + CredentialRelayHeaderV1 { + name: "authorization".to_owned(), + value: "Bearer agent-supplied".to_owned(), + }, + CredentialRelayHeaderV1 { + name: "anthropic-version".to_owned(), + value: "2023-06-01".to_owned(), + }, + ], + body_bytes: body.len() as u64, + }; + let mut events = vec![Event { + stream_id: stream, + kind: EventKind::CredentialRelayRequest, + payload: serde_json::to_vec(&request).unwrap(), + }]; + if !body.is_empty() { + events.push(Event { + stream_id: stream, + kind: EventKind::CredentialRelayRequestBody, + payload: body.to_vec(), + }); + } + events + } + + async fn next(events: &mut mpsc::UnboundedReceiver) -> Event { + tokio::time::timeout(Duration::from_secs(5), events.recv()) + .await + .expect("relay event") + .expect("open channel") + } + + fn end(event: &Event) -> CredentialRelayEndV1 { + assert_eq!(event.kind, EventKind::CredentialRelayEnd); + serde_json::from_slice(&event.payload).unwrap() + } + + fn assert_no_secret(harness: &Harness) { + let audit = format!("{:?}", harness.audit.0.lock().unwrap()); + assert!(!audit.contains(SECRET)); + assert!(!audit.contains("agent-supplied")); + } + + #[tokio::test] + async fn allowed_requests_inject_the_host_credential_and_stream_back() { + let stream = CREDENTIAL_RELAY_STREAM_BASE + 1; + let mut harness = harness(allowed(), transport(vec![b"event: one\n\n".to_vec()])); + for event in request_event(stream, "/v1/messages?beta=true", b"{\"x\":1}") { + harness.endpoint.handle(event).unwrap(); + } + let head = next(&mut harness.events).await; + assert_eq!(head.kind, EventKind::CredentialRelayResponseHead); + let head: CredentialRelayResponseHeadV1 = serde_json::from_slice(&head.payload).unwrap(); + assert_eq!(head.status, 200); + assert!( + head.headers + .iter() + .all(|header| header.name != "set-cookie") + ); + let body = next(&mut harness.events).await; + assert_eq!(body.payload, b"event: one\n\n"); + assert_eq!( + end(&next(&mut harness.events).await).outcome, + CredentialRelayOutcomeV1::Complete + ); + + let captured = harness.transport.captured.lock().unwrap()[0].clone(); + assert_eq!(captured.method, "POST"); + assert_eq!( + captured.url, + "https://api.anthropic.com/v1/messages?beta=true" + ); + assert_eq!(captured.body, b"{\"x\":1}"); + let header = |name: &str| { + captured + .headers + .iter() + .filter(|(header, _)| header == name) + .map(|(_, value)| value.clone()) + .collect::>() + }; + assert_eq!(header("x-api-key"), vec![SECRET.to_owned()]); + assert!(header("authorization").is_empty()); + assert_eq!(header("anthropic-version"), vec!["2023-06-01".to_owned()]); + + harness.endpoint.close(Duration::from_secs(1)).await; + let audit = harness.audit.0.lock().unwrap().clone(); + assert!(matches!( + &audit[0], + RelayAuditEvent::Decision { allowed: true, path, .. } if path == "/v1/messages" + )); + assert!(matches!( + &audit[1], + RelayAuditEvent::Outcome { + outcome: RelayStreamOutcome::Complete, + status: Some(200), + .. + } + )); + drop(audit); + assert_no_secret(&harness); + } + + #[tokio::test] + async fn denials_never_contact_the_upstream() { + let mut harness = harness( + RelayAuthorization::Denied { + reason: "stale_policy", + }, + transport(Vec::new()), + ); + let stream = CREDENTIAL_RELAY_STREAM_BASE; + for event in request_event(stream, "/v1/messages", b"{}") { + harness.endpoint.handle(event).unwrap(); + } + let ended = end(&next(&mut harness.events).await); + assert_eq!(ended.outcome, CredentialRelayOutcomeV1::Denied); + assert_eq!(ended.reason, "stale_policy"); + + for (offset, path) in ["/v1/files", "/v1/messages/../files"] + .into_iter() + .enumerate() + { + for event in request_event(stream + 1 + offset as u64, path, b"{}") { + harness.endpoint.handle(event).unwrap(); + } + let ended = end(&next(&mut harness.events).await); + assert_eq!(ended.outcome, CredentialRelayOutcomeV1::Denied); + } + assert_eq!(harness.authorizer.calls.load(Ordering::SeqCst), 1); + assert!(harness.transport.captured.lock().unwrap().is_empty()); + + let mut oversized = request_event(stream + 10, "/v1/messages", &[b'x'; 65]); + harness.endpoint.handle(oversized.remove(0)).unwrap(); + assert_eq!( + end(&next(&mut harness.events).await).reason, + "request_too_large" + ); + + let mut unknown = request_event(stream + 11, "/v1/messages", b""); + let mut request: CredentialRelayRequestV1 = + serde_json::from_slice(&unknown[0].payload).unwrap(); + request.service = "openai".to_owned(); + unknown[0].payload = serde_json::to_vec(&request).unwrap(); + harness.endpoint.handle(unknown.remove(0)).unwrap(); + assert_eq!( + end(&next(&mut harness.events).await).reason, + "service_not_granted" + ); + harness.endpoint.close(Duration::from_secs(1)).await; + assert_no_secret(&harness); + } + + #[tokio::test] + async fn response_chunks_require_guest_credit() { + let chunks = vec![vec![b'a'; CREDENTIAL_RELAY_CHUNK_BYTES]; 20]; + let mut harness = harness(allowed(), transport(chunks)); + let stream = CREDENTIAL_RELAY_STREAM_BASE; + for event in request_event(stream, "/v1/messages", b"{}") { + harness.endpoint.handle(event).unwrap(); + } + assert_eq!( + next(&mut harness.events).await.kind, + EventKind::CredentialRelayResponseHead + ); + for _ in 0..CREDENTIAL_RELAY_WINDOW_CHUNKS { + assert_eq!( + next(&mut harness.events).await.kind, + EventKind::CredentialRelayResponseBody + ); + } + assert!( + tokio::time::timeout(Duration::from_millis(100), harness.events.recv()) + .await + .is_err(), + "the host must wait for credit" + ); + let credit = |credits| Event { + stream_id: stream, + kind: EventKind::CredentialRelayCredit, + payload: serde_json::to_vec(&CredentialRelayCreditV1::new(credits).unwrap()).unwrap(), + }; + assert!(harness.endpoint.handle(credit(16)).is_ok()); + for _ in 0..4 { + assert_eq!( + next(&mut harness.events).await.kind, + EventKind::CredentialRelayResponseBody + ); + } + assert_eq!( + end(&next(&mut harness.events).await).outcome, + CredentialRelayOutcomeV1::Complete + ); + harness.endpoint.close(Duration::from_secs(1)).await; + } + + #[tokio::test] + async fn lapsed_grants_end_only_their_streams_and_guest_ends_are_not_echoed() { + let transport = Transport { + stall: true, + ..transport(Vec::new()) + }; + let mut harness = harness(allowed(), transport); + let stream = CREDENTIAL_RELAY_STREAM_BASE; + for event in request_event(stream, "/v1/messages", b"{}") { + harness.endpoint.handle(event).unwrap(); + } + assert_eq!( + next(&mut harness.events).await.kind, + EventKind::CredentialRelayResponseHead + ); + harness + .endpoint + .expire_in_flight(&["openai"], Duration::ZERO); + assert!( + tokio::time::timeout(Duration::from_millis(100), harness.events.recv()) + .await + .is_err(), + "another service's lapse must not end this stream" + ); + harness + .endpoint + .expire_in_flight(&["anthropic"], Duration::ZERO); + let ended = end(&next(&mut harness.events).await); + assert_eq!(ended.outcome, CredentialRelayOutcomeV1::Aborted); + assert_eq!(ended.reason, "grant_lapsed"); + + let guest_ended = stream + 1; + for event in request_event(guest_ended, "/v1/messages", b"{}") { + harness.endpoint.handle(event).unwrap(); + } + assert_eq!( + next(&mut harness.events).await.kind, + EventKind::CredentialRelayResponseHead + ); + harness + .endpoint + .handle(Event { + stream_id: guest_ended, + kind: EventKind::CredentialRelayEnd, + payload: serde_json::to_vec(&CredentialRelayEndV1::new( + CredentialRelayOutcomeV1::Aborted, + "client_disconnected", + )) + .unwrap(), + }) + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(100), harness.events.recv()) + .await + .is_err(), + "a guest-initiated end is not echoed" + ); + harness.endpoint.close(Duration::from_secs(1)).await; + let reasons = harness + .audit + .0 + .lock() + .unwrap() + .iter() + .filter_map(|event| match event { + RelayAuditEvent::Outcome { reason, .. } => Some(*reason), + RelayAuditEvent::Decision { .. } => None, + }) + .collect::>(); + assert_eq!(reasons, ["grant_lapsed", "aborted"]); + } + + #[tokio::test] + async fn credit_beyond_the_window_and_misordered_streams_are_violations() { + let transport = Transport { + stall: true, + ..transport(Vec::new()) + }; + let mut harness = harness(allowed(), transport); + let stream = CREDENTIAL_RELAY_STREAM_BASE + 5; + for event in request_event(stream, "/v1/messages", b"{}") { + harness.endpoint.handle(event).unwrap(); + } + assert_eq!( + next(&mut harness.events).await.kind, + EventKind::CredentialRelayResponseHead + ); + let credit = Event { + stream_id: stream, + kind: EventKind::CredentialRelayCredit, + payload: serde_json::to_vec(&CredentialRelayCreditV1::new(1).unwrap()).unwrap(), + }; + assert!(harness.endpoint.handle(credit).is_err()); + assert!( + harness + .endpoint + .handle(request_event(stream, "/v1/messages", b"").remove(0)) + .is_err() + ); + assert!( + harness + .endpoint + .handle(request_event(7, "/v1/messages", b"").remove(0)) + .is_err() + ); + assert!( + harness + .endpoint + .handle(Event { + stream_id: stream + 100, + kind: EventKind::CredentialRelayRequestBody, + payload: vec![1], + }) + .is_err() + ); + assert!( + harness + .endpoint + .handle(Event { + stream_id: stream, + kind: EventKind::CredentialRelayResponseBody, + payload: vec![1], + }) + .is_err() + ); + + let report = harness.endpoint.close(Duration::from_millis(50)).await; + assert_eq!(report.aborted, 1); + let audit = harness.audit.0.lock().unwrap().clone(); + assert!(audit.iter().any(|event| matches!( + event, + RelayAuditEvent::Outcome { + outcome: RelayStreamOutcome::AbortedUncertain, + .. + } + ))); + assert_eq!( + end(&next(&mut harness.events).await).outcome, + CredentialRelayOutcomeV1::Aborted + ); + } + + #[tokio::test] + async fn redirects_and_closed_sessions_are_refused() { + let mut harness = harness( + allowed(), + Transport { + status: StatusCode::TEMPORARY_REDIRECT, + ..transport(Vec::new()) + }, + ); + let stream = CREDENTIAL_RELAY_STREAM_BASE; + for event in request_event(stream, "/v1/messages", b"{}") { + harness.endpoint.handle(event).unwrap(); + } + assert_eq!( + end(&next(&mut harness.events).await).reason, + "redirect_denied" + ); + let report = harness.endpoint.close(Duration::from_secs(1)).await; + assert_eq!(report.aborted, 0); + let (sender, mut events) = mpsc::unbounded_channel(); + harness.endpoint.attach(Arc::new(Outbound(sender))); + harness + .endpoint + .handle(request_event(stream + 1, "/v1/messages", b"").remove(0)) + .unwrap(); + assert_eq!(end(&next(&mut events).await).reason, "session_closing"); + } +} diff --git a/crates/sendbox-credentials/src/upstream.rs b/crates/sendbox-credentials/src/upstream.rs index 7a86dc5..e8f1f7f 100644 --- a/crates/sendbox-credentials/src/upstream.rs +++ b/crates/sendbox-credentials/src/upstream.rs @@ -178,15 +178,16 @@ impl PinnedHttpsTransport { } } -#[async_trait] -impl UpstreamTransport for PinnedHttpsTransport { - async fn send( +impl PinnedHttpsTransport { + /// Resolves, classifies, and pins the upstream addresses, then builds a + /// certificate-verifying HTTPS/1.1 client bound to exactly those addresses. + async fn pinned_client( &self, request: &UpstreamRequest, - limits: &BrokerLimits, address_policy: &UpstreamAddressPolicy, + timeouts: ClientTimeouts, cancellation: &CancellationToken, - ) -> Result { + ) -> Result<(reqwest::Client, url::Url), CredentialBrokerError> { let url = url::Url::parse(request.url()).map_err(|_| { CredentialBrokerError::Upstream("transformed upstream URL is invalid".to_owned()) })?; @@ -207,27 +208,42 @@ impl UpstreamTransport for PinnedHttpsTransport { pinned.sort_unstable(); pinned.dedup(); - let client = reqwest::Client::builder() + let mut builder = reqwest::Client::builder() .https_only(true) .http1_only() .redirect(reqwest::redirect::Policy::none()) .no_proxy() .referer(false) - .connect_timeout(limits.upstream_connect_timeout) - .read_timeout(limits.upstream_read_timeout) - .timeout(limits.upstream_total_timeout) + .connect_timeout(timeouts.connect) + .read_timeout(timeouts.read) .pool_max_idle_per_host(0) .danger_accept_invalid_certs(false) .danger_accept_invalid_hostnames(false) .tls_sni(true) - .resolve_to_addrs(host, &pinned) - .build() - .map_err(|_| { - CredentialBrokerError::Upstream( - "could not initialize certificate-verifying HTTPS client".to_owned(), - ) - })?; + .resolve_to_addrs(host, &pinned); + if let Some(total) = timeouts.total { + builder = builder.timeout(total); + } + let client = builder.build().map_err(|_| { + CredentialBrokerError::Upstream( + "could not initialize certificate-verifying HTTPS client".to_owned(), + ) + })?; + Ok((client, url)) + } + async fn open_response( + &self, + request: &UpstreamRequest, + address_policy: &UpstreamAddressPolicy, + timeouts: ClientTimeouts, + max_header_count: usize, + max_header_bytes: usize, + cancellation: &CancellationToken, + ) -> Result { + let (client, url) = self + .pinned_client(request, address_policy, timeouts, cancellation) + .await?; let mut builder = client.request(request.method().clone(), url); for (name, value) in request.headers() { let mut header = HeaderValue::from_bytes(value.expose()).map_err(|_| { @@ -237,7 +253,7 @@ impl UpstreamTransport for PinnedHttpsTransport { builder = builder.header(name, header); } builder = builder.body(request.body().to_vec()); - let mut response = tokio::select! { + let response = tokio::select! { result = builder.send() => result.map_err(|error| { CredentialBrokerError::Upstream(format!( "HTTPS request failed ({})", @@ -246,23 +262,59 @@ impl UpstreamTransport for PinnedHttpsTransport { })?, () = cancellation.cancelled() => return Err(CredentialBrokerError::Cancelled), }; - - let headers = response + let header_bytes = response .headers() .iter() - .map(|(name, value)| (name.clone(), value.clone())) - .collect::>(); - let header_bytes = headers.iter().fold(0_usize, |total, (name, value)| { - total - .saturating_add(name.as_str().len()) - .saturating_add(value.as_bytes().len()) - .saturating_add(4) - }); - if headers.len() > limits.max_header_count || header_bytes > limits.max_header_bytes { + .fold(0_usize, |total, (name, value)| { + total + .saturating_add(name.as_str().len()) + .saturating_add(value.as_bytes().len()) + .saturating_add(4) + }); + if response.headers().len() > max_header_count || header_bytes > max_header_bytes { return Err(CredentialBrokerError::Upstream( "upstream response headers exceed the configured limit".to_owned(), )); } + Ok(response) + } +} + +#[derive(Debug, Clone, Copy)] +struct ClientTimeouts { + connect: std::time::Duration, + read: std::time::Duration, + total: Option, +} + +#[async_trait] +impl UpstreamTransport for PinnedHttpsTransport { + async fn send( + &self, + request: &UpstreamRequest, + limits: &BrokerLimits, + address_policy: &UpstreamAddressPolicy, + cancellation: &CancellationToken, + ) -> Result { + let mut response = self + .open_response( + request, + address_policy, + ClientTimeouts { + connect: limits.upstream_connect_timeout, + read: limits.upstream_read_timeout, + total: Some(limits.upstream_total_timeout), + }, + limits.max_header_count, + limits.max_header_bytes, + cancellation, + ) + .await?; + let headers = response + .headers() + .iter() + .map(|(name, value)| (name.clone(), value.clone())) + .collect::>(); if response .content_length() .is_some_and(|length| length > request.max_response_body_bytes as u64) @@ -296,6 +348,104 @@ impl UpstreamTransport for PinnedHttpsTransport { } } +/// Limits for one streamed upstream exchange. The caller enforces the total +/// duration and body size while it forwards chunks. +#[derive(Debug, Clone)] +pub struct StreamingLimits { + pub connect_timeout: std::time::Duration, + pub idle_timeout: std::time::Duration, + pub max_header_count: usize, + pub max_header_bytes: usize, +} + +/// A response body read incrementally, so long-lived event streams reach the +/// agent as they arrive instead of after completion. +#[async_trait] +pub trait ResponseBody: Send { + async fn next_chunk(&mut self) -> Result>, CredentialBrokerError>; +} + +pub struct StreamingResponse { + pub status: StatusCode, + pub headers: Vec<(HeaderName, HeaderValue)>, + pub body: Box, +} + +impl fmt::Debug for StreamingResponse { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("StreamingResponse") + .field("status", &self.status) + .field("headers", &"[REDACTED]") + .finish_non_exhaustive() + } +} + +#[async_trait] +pub trait StreamingTransport: Send + Sync { + async fn open( + &self, + request: &UpstreamRequest, + limits: &StreamingLimits, + address_policy: &UpstreamAddressPolicy, + cancellation: &CancellationToken, + ) -> Result; +} + +struct ReqwestBody(reqwest::Response); + +#[async_trait] +impl ResponseBody for ReqwestBody { + async fn next_chunk(&mut self) -> Result>, CredentialBrokerError> { + self.0 + .chunk() + .await + .map(|chunk| chunk.map(|bytes| bytes.to_vec())) + .map_err(|error| { + CredentialBrokerError::Upstream(format!( + "upstream response read failed ({})", + reqwest_error_kind(&error) + )) + }) + } +} + +#[async_trait] +impl StreamingTransport for PinnedHttpsTransport { + async fn open( + &self, + request: &UpstreamRequest, + limits: &StreamingLimits, + address_policy: &UpstreamAddressPolicy, + cancellation: &CancellationToken, + ) -> Result { + let response = self + .open_response( + request, + address_policy, + ClientTimeouts { + connect: limits.connect_timeout, + read: limits.idle_timeout, + total: None, + }, + limits.max_header_count, + limits.max_header_bytes, + cancellation, + ) + .await?; + let headers = response + .headers() + .iter() + .map(|(name, value)| (name.clone(), value.clone())) + .collect::>(); + Ok(StreamingResponse { + status: response.status(), + headers: strip_hop_by_hop(&headers), + body: Box::new(ReqwestBody(response)), + }) + } +} + fn reqwest_error_kind(error: &reqwest::Error) -> &'static str { if error.is_timeout() { "timeout" diff --git a/crates/sendbox-egress/src/linux/nft.rs b/crates/sendbox-egress/src/linux/nft.rs index a0be319..b00c68e 100644 --- a/crates/sendbox-egress/src/linux/nft.rs +++ b/crates/sendbox-egress/src/linux/nft.rs @@ -109,6 +109,9 @@ pub struct NftConfig { /// The loopback HTTP MCP gateway port, or `None` when no remote MCP server /// is configured. pub mcp_gateway_port: Option, + /// The loopback brokered-credential relay port served by the trusted guest + /// supervisor, or `None` when no credential service is brokered. + pub credential_relay_tcp_port: Option, /// Workload-facing registry proxy port and registry-only trusted SOCKS port. /// Both are configured together or both omitted. pub registry_proxy_tcp_port: Option, @@ -172,6 +175,7 @@ impl NftConfig { if let Some(port) = self.mcp_gateway_port { ports.push(port); } + ports.extend(self.credential_relay_tcp_port); if let Some(port) = self.registry_proxy_tcp_port { ports.push(port); } @@ -229,6 +233,9 @@ impl NftConfig { if let Some(mcp_port) = self.mcp_gateway_port { self.push_loopback_accept(&mut out, " iif lo", "tcp", mcp_port); } + if let Some(relay_port) = self.credential_relay_tcp_port { + self.push_loopback_accept(&mut out, " iif lo", "tcp", relay_port); + } if let Some(proxy_port) = self.registry_proxy_tcp_port { self.push_loopback_accept(&mut out, " iif lo", "tcp", proxy_port); } @@ -262,6 +269,9 @@ impl NftConfig { if let Some(mcp_port) = self.mcp_gateway_port { self.push_cgroup_loopback_accept(&mut out, &agent, "tcp", mcp_port); } + if let Some(relay_port) = self.credential_relay_tcp_port { + self.push_cgroup_loopback_accept(&mut out, &agent, "tcp", relay_port); + } if let Some(proxy_port) = self.registry_proxy_tcp_port { self.push_cgroup_loopback_accept(&mut out, &agent, "tcp", proxy_port); } @@ -509,6 +519,7 @@ mod tests { http_proxy_tcp_port: Some(15083), dns_broker_port: Some(15053), mcp_gateway_port: Some(15082), + credential_relay_tcp_port: None, registry_proxy_tcp_port: Some(14873), trusted_registry_tcp_port: Some(15081), metadata_v4_addresses: crate::address::METADATA_V4_ADDRESSES.to_vec(), @@ -566,6 +577,20 @@ mod tests { assert!(!text.contains("\"sendbox/inst01/agent\" accept")); } + #[test] + fn render_admits_the_credential_relay_only_when_configured() { + let relay = "\"sendbox/inst01/agent\" ip daddr 127.0.0.1 tcp dport 15084 accept"; + assert!(!config().render().contains(relay)); + let mut configured = config(); + configured.credential_relay_tcp_port = Some(15084); + let text = configured.render(); + assert!(text.contains(relay)); + assert!(text.contains("iif lo ip daddr 127.0.0.1 tcp dport 15084 accept")); + assert!(!text.contains("\"sendbox/inst01/registry\" ip daddr 127.0.0.1 tcp dport 15084")); + configured.credential_relay_tcp_port = Some(15082); + assert!(configured.validate().is_err()); + } + #[test] fn render_isolates_registry_proxy_and_trusted_socks_ports() { let text = config().render(); diff --git a/crates/sendbox-egress/src/linux/supervisor.rs b/crates/sendbox-egress/src/linux/supervisor.rs index 0b1381b..14107ee 100644 --- a/crates/sendbox-egress/src/linux/supervisor.rs +++ b/crates/sendbox-egress/src/linux/supervisor.rs @@ -45,6 +45,8 @@ pub struct SupervisorConfig { pub dns_port: Option, /// Loopback HTTP MCP gateway port. pub mcp_gateway_port: Option, + /// Loopback brokered-credential relay port. + pub credential_relay_port: Option, /// Optional workload-facing package proxy and registry-only trusted SOCKS. pub registry_proxy_port: Option, pub trusted_registry_port: Option, @@ -75,6 +77,7 @@ impl SupervisorConfig { http_proxy_port: None, dns_port: None, mcp_gateway_port: None, + credential_relay_port: None, registry_proxy_port: None, trusted_registry_port: None, metadata_v4: crate::address::METADATA_V4_ADDRESSES.to_vec(), @@ -103,6 +106,12 @@ impl SupervisorConfig { self } + #[must_use] + pub fn with_credential_relay_port(mut self, port: u16) -> Self { + self.credential_relay_port = Some(port); + self + } + #[must_use] pub fn with_registry_proxy(mut self, proxy_port: u16, trusted_port: u16) -> Self { self.registry_proxy_port = Some(proxy_port); @@ -139,6 +148,7 @@ impl SupervisorConfig { http_proxy_tcp_port: self.http_proxy_port, dns_broker_port: self.dns_port, mcp_gateway_port: self.mcp_gateway_port, + credential_relay_tcp_port: self.credential_relay_port, registry_proxy_tcp_port: self.registry_proxy_port, trusted_registry_tcp_port: self.trusted_registry_port, metadata_v4_addresses: self.metadata_v4.clone(), diff --git a/crates/sendbox-egress/src/runtime.rs b/crates/sendbox-egress/src/runtime.rs index e863d22..ef755f8 100644 --- a/crates/sendbox-egress/src/runtime.rs +++ b/crates/sendbox-egress/src/runtime.rs @@ -19,6 +19,7 @@ pub const DEFAULT_HTTP_PROXY_PORT: u16 = 15_083; pub const DEFAULT_DNS_PORT: u16 = 53; pub const DEFAULT_REGISTRY_PROXY_PORT: u16 = 14_873; pub const DEFAULT_TRUSTED_REGISTRY_PORT: u16 = 15_081; +pub const DEFAULT_CREDENTIAL_RELAY_PORT: u16 = 15_084; pub const DEFAULT_CGROUP_ROOT: &str = "/sys/fs/cgroup"; const INSTANCE_ID_HEX_BYTES: usize = 12; const TABLE_PREFIX: &str = "sbxeg_"; @@ -40,6 +41,10 @@ pub struct RuntimePolicyDocument { pub network_policy: NetworkPolicy, #[serde(default)] pub registry: Option, + /// Loopback port of the brokered-credential relay that the agent may + /// reach. Omitted when no credential service is brokered. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential_relay_port: Option, pub proxy_environment: BTreeMap, } @@ -121,10 +126,17 @@ impl RuntimePolicyDocument { deny_direct_ip: remote_mcp_active, network_policy, registry: None, + credential_relay_port: None, proxy_environment: proxy_environment(connect_port, DEFAULT_HTTP_PROXY_PORT, None), }) } + #[must_use] + pub fn with_credential_relay(mut self, port: u16) -> Self { + self.credential_relay_port = Some(port); + self + } + #[must_use] pub fn with_registry( mut self, @@ -199,6 +211,7 @@ impl RuntimePolicyDocument { let mut loopback_ports = vec![self.connect_port, self.http_proxy_port]; loopback_ports.extend(self.dns_port); loopback_ports.extend(self.mcp_gateway_port); + loopback_ports.extend(self.credential_relay_port); if let Some(registry) = &self.registry { loopback_ports.extend([registry.proxy_port, registry.trusted_upstream_port]); PolicyEngine::compile(®istry.upstream_network_policy)?; @@ -348,6 +361,31 @@ mod tests { first.validate().expect("valid policy"); } + #[test] + fn credential_relay_port_is_optional_and_must_be_distinct() { + let policy = + RuntimePolicyDocument::for_session(SessionId::from_bytes([7; 16]), network_policy()); + assert!( + !serde_json::to_string(&policy) + .expect("encode") + .contains("credential_relay_port") + ); + let relayed = policy + .clone() + .with_credential_relay(DEFAULT_CREDENTIAL_RELAY_PORT); + relayed.validate().expect("relay port"); + let decoded: RuntimePolicyDocument = + serde_json::from_str(&serde_json::to_string(&relayed).expect("encode")) + .expect("decode"); + assert_eq!(decoded, relayed); + assert!(matches!( + policy + .with_credential_relay(DEFAULT_CONNECT_PORT) + .validate(), + Err(RuntimePolicyError::InvalidLoopbackPorts) + )); + } + #[test] fn registry_policy_adds_only_local_npm_environment() { let original = network_policy(); diff --git a/crates/sendbox-exec/src/lib.rs b/crates/sendbox-exec/src/lib.rs index 813a957..c09896c 100644 --- a/crates/sendbox-exec/src/lib.rs +++ b/crates/sendbox-exec/src/lib.rs @@ -40,5 +40,6 @@ pub use error::{ }; pub use policy::{ CommandAdmission, CommandPolicyCompileError, CompiledCommandPolicy, MatchKind, MatchedRule, + rule_covers, }; pub use sendbox_core::SessionId; diff --git a/crates/sendbox-exec/src/policy.rs b/crates/sendbox-exec/src/policy.rs index a908512..03b565b 100644 --- a/crates/sendbox-exec/src/policy.rs +++ b/crates/sendbox-exec/src/policy.rs @@ -303,6 +303,39 @@ fn admission(disposition: AdmissionDisposition, rule: &CompiledRule) -> CommandA } } +/// Reports whether every argv that `candidate` admits is also admitted by +/// `ceiling`. +/// +/// The answer is conservative: a wildcard candidate is covered only by an +/// identical ceiling rule, while an exact candidate is covered when the ceiling +/// rule matches it with the runtime's own program-basename semantics. +pub fn rule_covers(ceiling: &str, candidate: &str) -> Result { + let ceiling = compile_rule("ceiling", 0, ceiling)?; + let candidate = compile_rule("candidate", 0, candidate)?; + match &candidate.exact { + Some(argv) => Ok(ceiling.matches(argv)), + None => Ok(ceiling.exact.is_none() + && ceiling.tokens.len() == candidate.tokens.len() + && ceiling + .tokens + .iter() + .zip(&candidate.tokens) + .all(|(left, right)| left.same_as(right))), + } +} + +impl TokenPattern { + fn same_as(&self, other: &Self) -> bool { + self.0.len() == other.0.len() + && self.0.iter().zip(&other.0).all(|pair| match pair { + (PatternAtom::Literal(left), PatternAtom::Literal(right)) => left == right, + (PatternAtom::AnyCharacter, PatternAtom::AnyCharacter) + | (PatternAtom::AnySequence, PatternAtom::AnySequence) => true, + _ => false, + }) + } +} + const fn convert_action(action: Action) -> AdmissionDisposition { match action { Action::Allow => AdmissionDisposition::Allow, @@ -404,6 +437,19 @@ mod tests { ); } + #[test] + fn rule_coverage_uses_runtime_matching_and_is_conservative_for_wildcards() { + assert!(rule_covers("git *", "git status").unwrap()); + assert!(rule_covers("git *", "/usr/bin/git status").unwrap()); + assert!(!rule_covers("git *", "git status --short").unwrap()); + assert!(!rule_covers("/usr/bin/git *", "git status").unwrap()); + assert!(rule_covers("git *", "git *").unwrap()); + assert!(!rule_covers("git *", "git s*").unwrap()); + assert!(!rule_covers("git s*", "git *").unwrap()); + assert!(!rule_covers(r"git \*", "git *").unwrap()); + assert!(rule_covers(r"tool literal\*", r"tool literal\*").unwrap()); + } + #[test] fn deny_rules_win_even_when_an_allow_rule_matches() { let policy = compile(Action::Deny, &["git *"], &["git push"]); diff --git a/crates/sendbox-governance/Cargo.toml b/crates/sendbox-governance/Cargo.toml new file mode 100644 index 0000000..eb87693 --- /dev/null +++ b/crates/sendbox-governance/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "sendbox-governance" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "Shared governance contract: identities, signed policy profiles, session bindings, and credential grants." + +[dependencies] +sendbox-core = { path = "../sendbox-core" } +serde.workspace = true +serde_json.workspace = true +serde_json_canonicalizer.workspace = true +serde_yaml_ng.workspace = true +sha2.workspace = true +thiserror.workspace = true + +[dev-dependencies] +proptest.workspace = true + +[lints] +workspace = true diff --git a/crates/sendbox-governance/src/authority.rs b/crates/sendbox-governance/src/authority.rs new file mode 100644 index 0000000..183c4e2 --- /dev/null +++ b/crates/sendbox-governance/src/authority.rs @@ -0,0 +1,644 @@ +//! Grant authority contract and the single-host implementation. + +use std::collections::BTreeMap; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::{ + CONTRACT_VERSION, GovernanceError, GrantId, + grant::{ + AllowedRequest, CredentialGrant, Decision, DenyReason, GrantRequest, RequestContext, + RevocationReason, path_permitted, validate_method, validate_path_prefix, + }, + profile::ProfileRef, +}; + +pub type AuthorityFuture<'a, T> = Pin + Send + 'a>>; + +pub trait Clock: Send + Sync { + fn now_unix(&self) -> u64; +} + +#[derive(Debug, Default, Clone, Copy)] +pub struct SystemClock; + +impl Clock for SystemClock { + fn now_unix(&self) -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()) + } +} + +/// The current, trusted revision of a profile as seen by the authority. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurrentProfile { + pub reference: ProfileRef, + pub minimum_revision: u64, + pub expires_at_unix: u64, +} + +/// Reports the authority's current view of a profile. Implementations must +/// re-verify the profile rather than trust cached workload-visible state, and +/// return an error when the authority cannot be consulted. +pub trait RevisionSource: Send + Sync { + fn current(&self, profile: &crate::ProfileId) -> Result; +} + +/// Issues, checks, renews, and revokes credential grants. +/// +/// `authorize` must be called for every brokered request and must deny when +/// the authority cannot establish that the grant is current. +pub trait GrantAuthority: Send + Sync { + fn issue<'a>( + &'a self, + request: GrantRequest, + ) -> AuthorityFuture<'a, Result>; + + fn authorize<'a>(&'a self, context: &'a RequestContext) -> AuthorityFuture<'a, Decision>; + + fn renew<'a>( + &'a self, + grant: &'a GrantId, + ) -> AuthorityFuture<'a, Result>; + + fn revoke<'a>( + &'a self, + grant: &'a GrantId, + reason: RevocationReason, + ) -> AuthorityFuture<'a, Result<(), GovernanceError>>; +} + +#[derive(Debug, Clone)] +pub struct LocalAuthorityLimits { + pub lease_seconds: u64, + pub max_grants: usize, +} + +impl Default for LocalAuthorityLimits { + fn default() -> Self { + Self { + lease_seconds: 300, + max_grants: 64, + } + } +} + +#[derive(Debug, Clone)] +struct GrantState { + grant: CredentialGrant, + revoked: Option, +} + +/// In-process authority for one host. It holds no credentials; it only +/// decides whether a request is covered by a current grant. +pub struct LocalGrantAuthority { + grants: Mutex>, + revisions: Arc, + clock: Arc, + limits: LocalAuthorityLimits, + random: Box Result<[u8; 16], GovernanceError> + Send + Sync>, +} + +impl LocalGrantAuthority { + #[must_use] + pub fn new( + revisions: Arc, + clock: Arc, + limits: LocalAuthorityLimits, + random: Box Result<[u8; 16], GovernanceError> + Send + Sync>, + ) -> Self { + Self { + grants: Mutex::new(BTreeMap::new()), + revisions, + clock, + limits, + random, + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap> { + self.grants + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn current_revision( + &self, + reference: &ProfileRef, + now: u64, + ) -> Result { + let current = self + .revisions + .current(&reference.id) + .map_err(|_| DenyReason::AuthorityUnavailable)?; + if current.reference != *reference + || reference.revision < current.minimum_revision + || now >= current.expires_at_unix + { + return Err(DenyReason::StalePolicy); + } + Ok(current) + } + + fn issue_sync(&self, request: GrantRequest) -> Result { + let binding_sha256 = request.binding.digest()?; + if request.binding.principal != request.principal + || request.binding.project != request.project + { + return Err(GovernanceError::InvalidGrant( + "grant identity does not match the session binding".to_owned(), + )); + } + if !request.binding.brokered_services.contains(&request.service) { + return Err(GovernanceError::InvalidGrant( + "service is not admitted by the session binding".to_owned(), + )); + } + if request.methods.is_empty() || request.path_prefixes.is_empty() { + return Err(GovernanceError::InvalidGrant( + "grants require at least one method and path prefix".to_owned(), + )); + } + for method in &request.methods { + validate_method(method)?; + } + for prefix in &request.path_prefixes { + validate_path_prefix(prefix)?; + } + let now = self.clock.now_unix(); + let current = self + .current_revision(&request.binding.profile, now) + .map_err(|reason| GovernanceError::Denied(reason.code()))?; + let max_expires_at_unix = now + .saturating_add(request.max_ttl_seconds) + .min(current.expires_at_unix); + if max_expires_at_unix <= now { + return Err(GovernanceError::InvalidGrant( + "grant would expire immediately".to_owned(), + )); + } + let grant = CredentialGrant { + contract_version: CONTRACT_VERSION, + grant_id: GrantId::from_bytes((self.random)()?), + principal: request.principal, + project: request.project, + session: request.session, + binding_sha256, + profile: request.binding.profile, + service: request.service, + methods: request.methods, + path_prefixes: request.path_prefixes, + issued_at_unix: now, + lease_expires_at_unix: now + .saturating_add(self.limits.lease_seconds) + .min(max_expires_at_unix), + max_expires_at_unix, + generation: 1, + }; + grant.validate()?; + let mut grants = self.lock(); + grants.retain(|_, state| state.revoked.is_none() && state.grant.max_expires_at_unix > now); + if grants.len() >= self.limits.max_grants { + return Err(GovernanceError::InvalidGrant( + "local grant capacity is exhausted".to_owned(), + )); + } + if grants.contains_key(&grant.grant_id) { + return Err(GovernanceError::InvalidGrant( + "grant identifier collision".to_owned(), + )); + } + grants.insert( + grant.grant_id.clone(), + GrantState { + grant: grant.clone(), + revoked: None, + }, + ); + Ok(grant) + } + + fn authorize_sync(&self, context: &RequestContext) -> Decision { + let now = self.clock.now_unix(); + let grant = { + let grants = self.lock(); + let Some(state) = grants.get(&context.grant_id) else { + return deny(DenyReason::UnknownGrant); + }; + if state.revoked.is_some() { + return deny(DenyReason::Revoked); + } + state.grant.clone() + }; + let checks = [ + (now >= grant.max_expires_at_unix, DenyReason::Expired), + (now >= grant.lease_expires_at_unix, DenyReason::LeaseExpired), + ( + context.principal != grant.principal, + DenyReason::PrincipalMismatch, + ), + ( + context.project != grant.project, + DenyReason::ProjectMismatch, + ), + ( + context.session != grant.session, + DenyReason::SessionMismatch, + ), + ( + context.binding_sha256 != grant.binding_sha256, + DenyReason::BindingMismatch, + ), + ( + context.service != grant.service, + DenyReason::ServiceNotGranted, + ), + ( + !grant.methods.contains(&context.method), + DenyReason::MethodNotGranted, + ), + ]; + if let Some((_, reason)) = checks.iter().find(|(failed, _)| *failed) { + return deny(*reason); + } + if crate::grant::validate_request_path(&context.path).is_err() { + return deny(DenyReason::InvalidPath); + } + if !path_permitted(&grant.path_prefixes, &context.path) { + return deny(DenyReason::PathNotGranted); + } + if let Err(reason) = self.current_revision(&grant.profile, now) { + return deny(reason); + } + Decision::Allow(AllowedRequest { + grant_id: grant.grant_id, + generation: grant.generation, + profile: grant.profile, + lease_expires_at_unix: grant.lease_expires_at_unix, + }) + } + + fn renew_sync(&self, grant_id: &GrantId) -> Result { + let now = self.clock.now_unix(); + let profile = { + let grants = self.lock(); + let state = grants + .get(grant_id) + .ok_or(GovernanceError::Denied(DenyReason::UnknownGrant.code()))?; + if state.revoked.is_some() { + return Err(GovernanceError::Denied(DenyReason::Revoked.code())); + } + if now >= state.grant.max_expires_at_unix { + return Err(GovernanceError::Denied(DenyReason::Expired.code())); + } + if now >= state.grant.lease_expires_at_unix { + return Err(GovernanceError::Denied(DenyReason::LeaseExpired.code())); + } + state.grant.profile.clone() + }; + self.current_revision(&profile, now) + .map_err(|reason| GovernanceError::Denied(reason.code()))?; + let mut grants = self.lock(); + let state = grants + .get_mut(grant_id) + .ok_or(GovernanceError::Denied(DenyReason::UnknownGrant.code()))?; + if state.revoked.is_some() { + return Err(GovernanceError::Denied(DenyReason::Revoked.code())); + } + state.grant.lease_expires_at_unix = now + .saturating_add(self.limits.lease_seconds) + .min(state.grant.max_expires_at_unix); + state.grant.generation = state.grant.generation.saturating_add(1); + Ok(state.grant.clone()) + } + + fn revoke_sync( + &self, + grant_id: &GrantId, + reason: RevocationReason, + ) -> Result<(), GovernanceError> { + let mut grants = self.lock(); + let state = grants + .get_mut(grant_id) + .ok_or(GovernanceError::Denied(DenyReason::UnknownGrant.code()))?; + if state.revoked.is_none() { + state.revoked = Some(reason); + state.grant.generation = state.grant.generation.saturating_add(1); + } + Ok(()) + } +} + +fn deny(reason: DenyReason) -> Decision { + Decision::Deny { reason } +} + +impl GrantAuthority for LocalGrantAuthority { + fn issue<'a>( + &'a self, + request: GrantRequest, + ) -> AuthorityFuture<'a, Result> { + Box::pin(async move { self.issue_sync(request) }) + } + + fn authorize<'a>(&'a self, context: &'a RequestContext) -> AuthorityFuture<'a, Decision> { + Box::pin(async move { self.authorize_sync(context) }) + } + + fn renew<'a>( + &'a self, + grant: &'a GrantId, + ) -> AuthorityFuture<'a, Result> { + Box::pin(async move { self.renew_sync(grant) }) + } + + fn revoke<'a>( + &'a self, + grant: &'a GrantId, + reason: RevocationReason, + ) -> AuthorityFuture<'a, Result<(), GovernanceError>> { + Box::pin(async move { self.revoke_sync(grant, reason) }) + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; + + use super::*; + use crate::{ + AuthorityRef, GovernanceBinding, PrincipalId, ProfileId, ProjectId, ServiceId, SessionRef, + digest::Sha256Digest, + }; + + struct TestClock(AtomicU64); + + impl Clock for TestClock { + fn now_unix(&self) -> u64 { + self.0.load(Ordering::SeqCst) + } + } + + struct TestRevisions { + current: Mutex>, + } + + impl RevisionSource for TestRevisions { + fn current(&self, _profile: &ProfileId) -> Result { + self.current + .lock() + .unwrap() + .clone() + .ok_or_else(|| GovernanceError::AuthorityUnavailable("offline".to_owned())) + } + } + + fn profile_ref(revision: u64) -> ProfileRef { + ProfileRef { + id: ProfileId::new("acme").unwrap(), + revision, + sha256: Sha256Digest::of(&revision.to_be_bytes()), + } + } + + fn binding() -> GovernanceBinding { + GovernanceBinding { + contract_version: CONTRACT_VERSION, + authority: AuthorityRef { + id: "local".to_owned(), + trust_sha256: Sha256Digest::of(b"trust"), + }, + profile: profile_ref(1), + principal: PrincipalId::new("local-user:501:alice").unwrap(), + project: ProjectId::new("github:octo/api").unwrap(), + effective_policy_sha256: Sha256Digest::of(b"policy"), + brokered_services: vec![ServiceId::new("anthropic").unwrap()], + } + } + + struct Fixture { + authority: LocalGrantAuthority, + clock: Arc, + revisions: Arc, + } + + fn fixture() -> Fixture { + let clock = Arc::new(TestClock(AtomicU64::new(1_000))); + let revisions = Arc::new(TestRevisions { + current: Mutex::new(Some(CurrentProfile { + reference: profile_ref(1), + minimum_revision: 1, + expires_at_unix: 100_000, + })), + }); + let counter = Arc::new(AtomicU8::new(0)); + let authority = LocalGrantAuthority::new( + revisions.clone(), + clock.clone(), + LocalAuthorityLimits { + lease_seconds: 60, + max_grants: 4, + }, + Box::new(move || Ok([counter.fetch_add(1, Ordering::SeqCst); 16])), + ); + Fixture { + authority, + clock, + revisions, + } + } + + fn request() -> GrantRequest { + let binding = binding(); + GrantRequest { + principal: binding.principal.clone(), + project: binding.project.clone(), + session: SessionRef::new("ab".repeat(16)).unwrap(), + service: ServiceId::new("anthropic").unwrap(), + methods: ["POST".to_owned()].into(), + path_prefixes: vec!["/v1/messages".to_owned()], + max_ttl_seconds: 600, + binding, + } + } + + fn context(grant: &CredentialGrant) -> RequestContext { + RequestContext { + grant_id: grant.grant_id.clone(), + principal: grant.principal.clone(), + project: grant.project.clone(), + session: grant.session.clone(), + binding_sha256: grant.binding_sha256, + service: grant.service.clone(), + method: "POST".to_owned(), + path: "/v1/messages".to_owned(), + } + } + + fn reason(decision: Decision) -> DenyReason { + match decision { + Decision::Deny { reason } => reason, + Decision::Allow(_) => panic!("unexpected allow"), + } + } + + #[test] + fn current_grant_authorizes_exact_binding_only() { + let fixture = fixture(); + let grant = fixture.authority.issue_sync(request()).unwrap(); + assert!( + fixture + .authority + .authorize_sync(&context(&grant)) + .is_allowed() + ); + + let mut wrong = context(&grant); + wrong.principal = PrincipalId::new("local-user:502:mallory").unwrap(); + assert_eq!( + reason(fixture.authority.authorize_sync(&wrong)), + DenyReason::PrincipalMismatch + ); + let mut wrong = context(&grant); + wrong.project = ProjectId::new("github:octo/other").unwrap(); + assert_eq!( + reason(fixture.authority.authorize_sync(&wrong)), + DenyReason::ProjectMismatch + ); + let mut wrong = context(&grant); + wrong.session = SessionRef::new("cd".repeat(16)).unwrap(); + assert_eq!( + reason(fixture.authority.authorize_sync(&wrong)), + DenyReason::SessionMismatch + ); + let mut wrong = context(&grant); + wrong.binding_sha256 = Sha256Digest::of(b"changed"); + assert_eq!( + reason(fixture.authority.authorize_sync(&wrong)), + DenyReason::BindingMismatch + ); + let mut wrong = context(&grant); + wrong.method = "DELETE".to_owned(); + assert_eq!( + reason(fixture.authority.authorize_sync(&wrong)), + DenyReason::MethodNotGranted + ); + let mut wrong = context(&grant); + wrong.path = "/v1/files".to_owned(); + assert_eq!( + reason(fixture.authority.authorize_sync(&wrong)), + DenyReason::PathNotGranted + ); + let mut wrong = context(&grant); + wrong.path = "/v1/messages/../files".to_owned(); + assert_eq!( + reason(fixture.authority.authorize_sync(&wrong)), + DenyReason::InvalidPath + ); + let mut wrong = context(&grant); + wrong.grant_id = GrantId::new("ff".repeat(16)).unwrap(); + assert_eq!( + reason(fixture.authority.authorize_sync(&wrong)), + DenyReason::UnknownGrant + ); + } + + #[test] + fn leases_expire_unless_renewed_and_never_exceed_the_ttl() { + let fixture = fixture(); + let grant = fixture.authority.issue_sync(request()).unwrap(); + fixture.clock.0.store(1_059, Ordering::SeqCst); + let renewed = fixture.authority.renew_sync(&grant.grant_id).unwrap(); + assert_eq!(renewed.generation, 2); + assert_eq!(renewed.lease_expires_at_unix, 1_119); + fixture.clock.0.store(1_119, Ordering::SeqCst); + assert_eq!( + reason(fixture.authority.authorize_sync(&context(&grant))), + DenyReason::LeaseExpired + ); + assert!(fixture.authority.renew_sync(&grant.grant_id).is_err()); + + let grant = fixture.authority.issue_sync(request()).unwrap(); + assert_eq!(grant.max_expires_at_unix, 1_119 + 600); + for now in (1_150..1_719).step_by(50) { + fixture.clock.0.store(now, Ordering::SeqCst); + fixture.authority.renew_sync(&grant.grant_id).unwrap(); + } + fixture.clock.0.store(1_719, Ordering::SeqCst); + assert_eq!( + reason(fixture.authority.authorize_sync(&context(&grant))), + DenyReason::Expired + ); + } + + #[test] + fn revocation_stale_policy_and_unavailable_authority_deny() { + let fixture = fixture(); + let grant = fixture.authority.issue_sync(request()).unwrap(); + *fixture.revisions.current.lock().unwrap() = Some(CurrentProfile { + reference: profile_ref(2), + minimum_revision: 1, + expires_at_unix: 100_000, + }); + assert_eq!( + reason(fixture.authority.authorize_sync(&context(&grant))), + DenyReason::StalePolicy + ); + assert!(fixture.authority.renew_sync(&grant.grant_id).is_err()); + + *fixture.revisions.current.lock().unwrap() = Some(CurrentProfile { + reference: profile_ref(1), + minimum_revision: 2, + expires_at_unix: 100_000, + }); + assert_eq!( + reason(fixture.authority.authorize_sync(&context(&grant))), + DenyReason::StalePolicy + ); + + *fixture.revisions.current.lock().unwrap() = None; + assert_eq!( + reason(fixture.authority.authorize_sync(&context(&grant))), + DenyReason::AuthorityUnavailable + ); + assert!(fixture.authority.issue_sync(request()).is_err()); + + *fixture.revisions.current.lock().unwrap() = Some(CurrentProfile { + reference: profile_ref(1), + minimum_revision: 1, + expires_at_unix: 100_000, + }); + assert!( + fixture + .authority + .authorize_sync(&context(&grant)) + .is_allowed() + ); + fixture + .authority + .revoke_sync(&grant.grant_id, RevocationReason::SessionCompleted) + .unwrap(); + assert_eq!( + reason(fixture.authority.authorize_sync(&context(&grant))), + DenyReason::Revoked + ); + } + + #[test] + fn issuance_requires_an_admitted_service_and_matching_identity() { + let fixture = fixture(); + let mut wrong_service = request(); + wrong_service.service = ServiceId::new("openai").unwrap(); + assert!(fixture.authority.issue_sync(wrong_service).is_err()); + let mut wrong_principal = request(); + wrong_principal.principal = PrincipalId::new("local-user:502:mallory").unwrap(); + assert!(fixture.authority.issue_sync(wrong_principal).is_err()); + for _ in 0..4 { + fixture.authority.issue_sync(request()).unwrap(); + } + assert!(fixture.authority.issue_sync(request()).is_err()); + } +} diff --git a/crates/sendbox-governance/src/binding.rs b/crates/sendbox-governance/src/binding.rs new file mode 100644 index 0000000..551266c --- /dev/null +++ b/crates/sendbox-governance/src/binding.rs @@ -0,0 +1,123 @@ +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; + +use crate::{ + CONTRACT_VERSION, GovernanceError, PrincipalId, ProjectId, ServiceId, + digest::{Sha256Digest, canonical_digest}, + profile::ProfileRef, +}; + +/// The policy authority a session was admitted under. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuthorityRef { + /// `local` for a root-owned operator configuration, otherwise the + /// governance service identifier. + pub id: String, + /// Digest of the trusted signer set and threshold that verified the profile. + pub trust_sha256: Sha256Digest, +} + +/// Binds one session to the principal, project, profile revision, and +/// effective policy it was admitted with. Embedded in the signed boundary plan +/// and repeated in every credential grant as its digest. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GovernanceBinding { + pub contract_version: u32, + pub authority: AuthorityRef, + pub profile: ProfileRef, + pub principal: PrincipalId, + pub project: ProjectId, + pub effective_policy_sha256: Sha256Digest, + pub brokered_services: Vec, +} + +impl GovernanceBinding { + pub fn validate(&self) -> Result<(), GovernanceError> { + if self.contract_version != CONTRACT_VERSION { + return Err(GovernanceError::UnsupportedContract(self.contract_version)); + } + if self.authority.id.is_empty() + || self.authority.id.len() > 128 + || !self + .authority + .id + .bytes() + .all(|byte| byte.is_ascii_graphic()) + { + return Err(GovernanceError::InvalidBinding( + "authority id must be 1-128 printable ASCII bytes".to_owned(), + )); + } + let unique = self.brokered_services.iter().collect::>(); + if unique.len() != self.brokered_services.len() + || !self + .brokered_services + .windows(2) + .all(|pair| pair[0] < pair[1]) + { + return Err(GovernanceError::InvalidBinding( + "brokered services must be sorted and unique".to_owned(), + )); + } + Ok(()) + } + + /// RFC 8785 canonical digest used to bind grants to this exact admission. + pub fn digest(&self) -> Result { + self.validate()?; + canonical_digest(self) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ProfileId; + + pub(crate) fn binding() -> GovernanceBinding { + GovernanceBinding { + contract_version: CONTRACT_VERSION, + authority: AuthorityRef { + id: "local".to_owned(), + trust_sha256: Sha256Digest::of(b"trust"), + }, + profile: ProfileRef { + id: ProfileId::new("acme").unwrap(), + revision: 1, + sha256: Sha256Digest::of(b"profile"), + }, + principal: PrincipalId::new("local-user:501:alice").unwrap(), + project: ProjectId::new("github:octo/api").unwrap(), + effective_policy_sha256: Sha256Digest::of(b"policy"), + brokered_services: vec![ + ServiceId::new("anthropic").unwrap(), + ServiceId::new("openai").unwrap(), + ], + } + } + + #[test] + fn digest_changes_with_any_bound_field() { + let original = binding(); + let digest = original.digest().unwrap(); + let mut changed = original.clone(); + changed.profile.revision = 2; + assert_ne!(changed.digest().unwrap(), digest); + let mut changed = original.clone(); + changed.project = ProjectId::new("github:octo/other").unwrap(); + assert_ne!(changed.digest().unwrap(), digest); + let mut changed = original; + changed.effective_policy_sha256 = Sha256Digest::of(b"other"); + assert_ne!(changed.digest().unwrap(), digest); + } + + #[test] + fn unsorted_services_are_rejected() { + let mut binding = binding(); + binding.brokered_services.reverse(); + assert!(binding.digest().is_err()); + } +} diff --git a/crates/sendbox-governance/src/digest.rs b/crates/sendbox-governance/src/digest.rs new file mode 100644 index 0000000..12f46d5 --- /dev/null +++ b/crates/sendbox-governance/src/digest.rs @@ -0,0 +1,102 @@ +use std::fmt; + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use sha2::{Digest, Sha256}; + +use crate::GovernanceError; + +/// A SHA-256 digest that serializes as 64 lowercase hexadecimal characters. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Sha256Digest([u8; 32]); + +impl Sha256Digest { + #[must_use] + pub const fn from_bytes(bytes: [u8; 32]) -> Self { + Self(bytes) + } + + #[must_use] + pub fn of(bytes: &[u8]) -> Self { + Self(Sha256::digest(bytes).into()) + } + + #[must_use] + pub const fn as_bytes(&self) -> &[u8; 32] { + &self.0 + } + + pub fn parse_hex(value: &str) -> Result { + let invalid = || GovernanceError::InvalidDigest(value.chars().take(16).collect()); + if value.len() != 64 { + return Err(invalid()); + } + let mut bytes = [0_u8; 32]; + for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() { + let text = std::str::from_utf8(pair).map_err(|_| invalid())?; + if text.bytes().any(|byte| byte.is_ascii_uppercase()) { + return Err(invalid()); + } + bytes[index] = u8::from_str_radix(text, 16).map_err(|_| invalid())?; + } + Ok(Self(bytes)) + } +} + +impl fmt::Display for Sha256Digest { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + for byte in self.0 { + write!(formatter, "{byte:02x}")?; + } + Ok(()) + } +} + +impl fmt::Debug for Sha256Digest { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "Sha256Digest({self})") + } +} + +impl Serialize for Sha256Digest { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.to_string()) + } +} + +impl<'de> Deserialize<'de> for Sha256Digest { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Self::parse_hex(&value).map_err(serde::de::Error::custom) + } +} + +/// Digest of the RFC 8785 canonical JSON form of `value`. +pub fn canonical_digest(value: &T) -> Result { + let bytes = serde_json_canonicalizer::to_vec(value) + .map_err(|error| GovernanceError::Encoding(error.to_string()))?; + Ok(Sha256Digest::of(&bytes)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hex_round_trip_is_lowercase_and_strict() { + let digest = Sha256Digest::of(b"sendbox"); + let text = digest.to_string(); + assert_eq!(Sha256Digest::parse_hex(&text).unwrap(), digest); + assert!(Sha256Digest::parse_hex(&text.to_ascii_uppercase()).is_err()); + assert!(Sha256Digest::parse_hex(&text[..62]).is_err()); + } + + #[test] + fn canonical_digest_ignores_key_order() { + let first: serde_json::Value = serde_json::from_str(r#"{"a":1,"b":[2,3]}"#).unwrap(); + let second: serde_json::Value = serde_json::from_str(r#"{"b":[2,3],"a":1}"#).unwrap(); + assert_eq!( + canonical_digest(&first).unwrap(), + canonical_digest(&second).unwrap() + ); + } +} diff --git a/crates/sendbox-governance/src/grant.rs b/crates/sendbox-governance/src/grant.rs new file mode 100644 index 0000000..1856a24 --- /dev/null +++ b/crates/sendbox-governance/src/grant.rs @@ -0,0 +1,287 @@ +use std::collections::BTreeSet; +use std::fmt; + +use serde::{Deserialize, Serialize}; + +use crate::{ + CONTRACT_VERSION, GovernanceError, GrantId, PrincipalId, ProjectId, ServiceId, SessionRef, + binding::GovernanceBinding, digest::Sha256Digest, profile::ProfileRef, +}; + +const MAX_PATH_BYTES: usize = 2048; +const MAX_PREFIX_BYTES: usize = 256; +const KNOWN_METHODS: &[&str] = &["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]; + +/// A request for one brokered credential service for one admitted session. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GrantRequest { + pub principal: PrincipalId, + pub project: ProjectId, + pub session: SessionRef, + pub binding: GovernanceBinding, + pub service: ServiceId, + pub methods: BTreeSet, + pub path_prefixes: Vec, + pub max_ttl_seconds: u64, +} + +/// An expiring, revocable authorization for one session to use one brokered +/// service. Grants carry no credential material. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialGrant { + pub contract_version: u32, + pub grant_id: GrantId, + pub principal: PrincipalId, + pub project: ProjectId, + pub session: SessionRef, + pub binding_sha256: Sha256Digest, + pub profile: ProfileRef, + pub service: ServiceId, + pub methods: BTreeSet, + pub path_prefixes: Vec, + pub issued_at_unix: u64, + pub lease_expires_at_unix: u64, + pub max_expires_at_unix: u64, + pub generation: u64, +} + +/// What the enforcement point presents for every upstream request. All fields +/// come from trusted host state; none are taken from the workload. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RequestContext { + pub grant_id: GrantId, + pub principal: PrincipalId, + pub project: ProjectId, + pub session: SessionRef, + pub binding_sha256: Sha256Digest, + pub service: ServiceId, + pub method: String, + pub path: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AllowedRequest { + pub grant_id: GrantId, + pub generation: u64, + pub profile: ProfileRef, + pub lease_expires_at_unix: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "decision", rename_all = "snake_case")] +pub enum Decision { + Allow(AllowedRequest), + Deny { reason: DenyReason }, +} + +impl Decision { + #[must_use] + pub const fn is_allowed(&self) -> bool { + matches!(self, Self::Allow(_)) + } +} + +/// Stable denial reasons recorded in audit evidence. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DenyReason { + UnknownGrant, + Revoked, + Expired, + LeaseExpired, + PrincipalMismatch, + ProjectMismatch, + SessionMismatch, + BindingMismatch, + StalePolicy, + ServiceNotGranted, + MethodNotGranted, + PathNotGranted, + InvalidPath, + AuthorityUnavailable, +} + +impl DenyReason { + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::UnknownGrant => "unknown_grant", + Self::Revoked => "revoked", + Self::Expired => "expired", + Self::LeaseExpired => "lease_expired", + Self::PrincipalMismatch => "principal_mismatch", + Self::ProjectMismatch => "project_mismatch", + Self::SessionMismatch => "session_mismatch", + Self::BindingMismatch => "binding_mismatch", + Self::StalePolicy => "stale_policy", + Self::ServiceNotGranted => "service_not_granted", + Self::MethodNotGranted => "method_not_granted", + Self::PathNotGranted => "path_not_granted", + Self::InvalidPath => "invalid_path", + Self::AuthorityUnavailable => "authority_unavailable", + } + } +} + +impl fmt::Display for DenyReason { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.code()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RevocationReason { + SessionCompleted, + SessionCancelled, + SessionFailed, + OperatorRevoked, + PolicyChanged, +} + +impl RevocationReason { + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::SessionCompleted => "session_completed", + Self::SessionCancelled => "session_cancelled", + Self::SessionFailed => "session_failed", + Self::OperatorRevoked => "operator_revoked", + Self::PolicyChanged => "policy_changed", + } + } +} + +impl CredentialGrant { + pub fn validate(&self) -> Result<(), GovernanceError> { + if self.contract_version != CONTRACT_VERSION { + return Err(GovernanceError::UnsupportedContract(self.contract_version)); + } + if self.methods.is_empty() || self.path_prefixes.is_empty() { + return Err(GovernanceError::InvalidGrant( + "grants require at least one method and path prefix".to_owned(), + )); + } + for method in &self.methods { + validate_method(method)?; + } + for prefix in &self.path_prefixes { + validate_path_prefix(prefix)?; + } + if self.lease_expires_at_unix > self.max_expires_at_unix + || self.issued_at_unix >= self.max_expires_at_unix + { + return Err(GovernanceError::InvalidGrant( + "grant expiry is inconsistent".to_owned(), + )); + } + Ok(()) + } +} + +pub fn validate_method(method: &str) -> Result<(), GovernanceError> { + if KNOWN_METHODS.contains(&method) { + Ok(()) + } else { + Err(GovernanceError::InvalidGrant(format!( + "method `{}` must be one of {}", + method.chars().take(16).collect::(), + KNOWN_METHODS.join(", ") + ))) + } +} + +/// A grant path prefix: absolute, segment-normalized, printable ASCII, without +/// query, fragment, percent-encoding, or a trailing slash. +pub fn validate_path_prefix(prefix: &str) -> Result<(), GovernanceError> { + let valid = prefix.len() <= MAX_PREFIX_BYTES + && prefix.starts_with('/') + && (prefix == "/" || !prefix.ends_with('/')) + && normalized_path(prefix); + if valid { + Ok(()) + } else { + Err(GovernanceError::InvalidGrant(format!( + "path prefix `{}` must be an absolute normalized path without query, encoding, or trailing slash", + prefix.chars().take(64).collect::() + ))) + } +} + +/// Validates an upstream request path (without query) presented for +/// authorization. Encoded separators and dot segments are rejected so that a +/// prefix check cannot be bypassed by upstream path normalization. +pub fn validate_request_path(path: &str) -> Result<(), DenyReason> { + if path.len() <= MAX_PATH_BYTES && path.starts_with('/') && normalized_path(path) { + Ok(()) + } else { + Err(DenyReason::InvalidPath) + } +} + +/// Segment-aware prefix match: `/v1/messages` matches `/v1/messages` and +/// `/v1/messages/count_tokens`, but not `/v1/messagesx`. +#[must_use] +pub fn path_permitted(prefixes: &[String], path: &str) -> bool { + validate_request_path(path).is_ok() + && prefixes.iter().any(|prefix| { + prefix == "/" + || path == prefix + || path + .strip_prefix(prefix.as_str()) + .is_some_and(|rest| rest.starts_with('/')) + }) +} + +fn normalized_path(path: &str) -> bool { + path.bytes() + .all(|byte| byte.is_ascii_graphic() && !matches!(byte, b'?' | b'#' | b'%' | b'\\')) + && path[1..].split('/').enumerate().all(|(index, segment)| { + segment != "." && segment != ".." && (index == 0 || !segment.is_empty()) + }) + && !path.contains("//") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn path_matching_is_segment_aware() { + let prefixes = vec!["/v1/messages".to_owned()]; + assert!(path_permitted(&prefixes, "/v1/messages")); + assert!(path_permitted(&prefixes, "/v1/messages/count_tokens")); + assert!(!path_permitted(&prefixes, "/v1/messagesx")); + assert!(!path_permitted(&prefixes, "/v1/models")); + assert!(!path_permitted(&prefixes, "/v1/messages/../admin")); + assert!(!path_permitted(&prefixes, "/v1/messages/%2e%2e/admin")); + assert!(!path_permitted(&prefixes, "/v1/messages//x")); + assert!(!path_permitted(&prefixes, "/v1/messages?x=1")); + assert!(path_permitted(&["/".to_owned()], "/anything")); + } + + #[test] + fn prefixes_and_methods_are_validated() { + assert!(validate_path_prefix("/v1/messages").is_ok()); + assert!(validate_path_prefix("/v1/messages/").is_err()); + assert!(validate_path_prefix("v1").is_err()); + assert!(validate_path_prefix("/v1/%2f").is_err()); + assert!(validate_path_prefix("/v1/./x").is_err()); + assert!(validate_method("POST").is_ok()); + assert!(validate_method("post").is_err()); + assert!(validate_method("CONNECT").is_err()); + } + + #[test] + fn decisions_serialize_with_stable_codes() { + let json = serde_json::to_string(&Decision::Deny { + reason: DenyReason::StalePolicy, + }) + .unwrap(); + assert_eq!(json, r#"{"decision":"deny","reason":"stale_policy"}"#); + } +} diff --git a/crates/sendbox-governance/src/identity.rs b/crates/sendbox-governance/src/identity.rs new file mode 100644 index 0000000..c3f64cf --- /dev/null +++ b/crates/sendbox-governance/src/identity.rs @@ -0,0 +1,260 @@ +//! Validated identifiers shared by the session runtime and a governance service. +//! +//! Every identifier is an opaque, bounded, printable-ASCII string with a fixed +//! grammar so that it can be compared byte-for-byte, logged without escaping, +//! and embedded in canonical JSON without normalization surprises. + +use std::fmt; + +use serde::{Deserialize, Deserializer, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::GovernanceError; + +const MAX_PRINCIPAL_BYTES: usize = 160; +const MAX_PROJECT_BYTES: usize = 160; +const MAX_PROFILE_ID_BYTES: usize = 64; +const MAX_SERVICE_ID_BYTES: usize = 32; +const GRANT_ID_BYTES: usize = 16; + +macro_rules! string_identifier { + ($name:ident, $validate:path, $what:literal) => { + #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] + #[serde(transparent)] + pub struct $name(String); + + impl $name { + pub fn new(value: impl Into) -> Result { + let value = value.into(); + if $validate(&value) { + Ok(Self(value)) + } else { + Err(GovernanceError::InvalidIdentifier { + kind: $what, + value: printable_prefix(&value), + }) + } + } + + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } + } + + impl fmt::Debug for $name { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_tuple(stringify!($name)) + .field(&self.0) + .finish() + } + } + + impl fmt::Display for $name { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } + } + + impl<'de> Deserialize<'de> for $name { + fn deserialize>(deserializer: D) -> Result { + let value = String::deserialize(deserializer)?; + Self::new(value).map_err(serde::de::Error::custom) + } + } + }; +} + +string_identifier!(PrincipalId, valid_principal, "principal"); +string_identifier!(ProjectId, valid_project, "project"); +string_identifier!(ProfileId, valid_profile_id, "profile"); +string_identifier!(ServiceId, valid_service_id, "service"); +string_identifier!(SessionRef, valid_session_ref, "session"); +string_identifier!(GrantId, valid_grant_id, "grant"); + +impl PrincipalId { + /// Identity of a local operating-system account. Increment 1 uses this for + /// every session; a shared governance service authenticates its own + /// principals and never accepts this kind from a workload. + #[must_use] + pub fn local_user(uid: u32) -> Self { + Self(format!("local-user:{uid}")) + } + + #[must_use] + pub fn kind(&self) -> &str { + self.0.split_once(':').map_or("", |(kind, _)| kind) + } +} + +impl ProjectId { + /// Project identity derived from a GitHub `owner/repository` pair. + pub fn github(owner: &str, repository: &str) -> Result { + Self::new(format!( + "github:{}/{}", + owner.to_ascii_lowercase(), + repository.to_ascii_lowercase() + )) + } + + /// Project identity for a workspace without a resolvable repository. + #[must_use] + pub fn from_canonical_path(path: &[u8]) -> Self { + let digest = Sha256::digest(path); + let mut encoded = String::from("path-sha256:"); + for byte in digest { + encoded.push_str(&format!("{byte:02x}")); + } + Self(encoded) + } +} + +impl SessionRef { + #[must_use] + pub fn from_session_id(session: sendbox_core::SessionId) -> Self { + Self(session.to_string()) + } +} + +impl GrantId { + #[must_use] + pub fn from_bytes(bytes: [u8; GRANT_ID_BYTES]) -> Self { + let mut encoded = String::with_capacity(GRANT_ID_BYTES * 2); + for byte in bytes { + encoded.push_str(&format!("{byte:02x}")); + } + Self(encoded) + } +} + +fn printable_prefix(value: &str) -> String { + value + .chars() + .take(48) + .map(|character| { + if character.is_ascii_graphic() { + character + } else { + '?' + } + }) + .collect() +} + +fn is_lower_hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +fn valid_principal(value: &str) -> bool { + let Some((kind, rest)) = value.split_once(':') else { + return false; + }; + value.len() <= MAX_PRINCIPAL_BYTES + && !kind.is_empty() + && kind.len() <= 32 + && kind + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte == b'-') + && !rest.is_empty() + && rest.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'@' | b'+' | b'-' | b':') + }) +} + +fn valid_project(value: &str) -> bool { + if value.len() > MAX_PROJECT_BYTES { + return false; + } + if let Some(digest) = value.strip_prefix("path-sha256:") { + return is_lower_hex(digest, 64); + } + let Some(repository) = value.strip_prefix("github:") else { + return false; + }; + let Some((owner, name)) = repository.split_once('/') else { + return false; + }; + let segment = |segment: &str| { + !segment.is_empty() + && segment.len() <= 100 + && !segment.starts_with('.') + && segment.bytes().all(|byte| { + byte.is_ascii_lowercase() + || byte.is_ascii_digit() + || matches!(byte, b'-' | b'_' | b'.') + }) + }; + segment(owner) && segment(name) +} + +fn valid_profile_id(value: &str) -> bool { + let bytes = value.as_bytes(); + !bytes.is_empty() + && bytes.len() <= MAX_PROFILE_ID_BYTES + && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit()) + && bytes.iter().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'.' | b'_' | b'-') + }) +} + +fn valid_service_id(value: &str) -> bool { + let bytes = value.as_bytes(); + !bytes.is_empty() + && bytes.len() <= MAX_SERVICE_ID_BYTES + && bytes[0].is_ascii_lowercase() + && bytes + .iter() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-') +} + +fn valid_session_ref(value: &str) -> bool { + is_lower_hex(value, 32) +} + +fn valid_grant_id(value: &str) -> bool { + is_lower_hex(value, GRANT_ID_BYTES * 2) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn identifiers_enforce_their_grammar() { + assert!(PrincipalId::new("local-user:501:alice").is_ok()); + assert!(PrincipalId::new("oidc:alice@example.com").is_ok()); + assert!(PrincipalId::new("alice").is_err()); + assert!(PrincipalId::new("Local:alice").is_err()); + assert!(PrincipalId::new("local-user:alice bob").is_err()); + + assert!(ProjectId::new("github:octo/api").is_ok()); + assert!(ProjectId::new("github:Octo/api").is_err()); + assert!(ProjectId::new("github:octo/../api").is_err()); + assert!(ProjectId::new("github:octo").is_err()); + assert_eq!( + ProjectId::github("Octo", "API").unwrap().as_str(), + "github:octo/api" + ); + assert!(ProjectId::from_canonical_path(b"/work/app").as_str().len() == 76); + + assert!(ServiceId::new("anthropic").is_ok()); + assert!(ServiceId::new("Anthropic").is_err()); + assert!(ServiceId::new("1openai").is_err()); + assert!(ProfileId::new("acme.default-v2").is_ok()); + assert!(ProfileId::new("").is_err()); + + assert!(GrantId::new("00".repeat(16)).is_ok()); + assert!(GrantId::new("0".repeat(31)).is_err()); + assert!(SessionRef::new("AB".repeat(16)).is_err()); + } + + #[test] + fn deserialization_rejects_invalid_identifiers() { + assert!(serde_json::from_str::("\"openai\"").is_ok()); + assert!(serde_json::from_str::("\"open ai\"").is_err()); + } +} diff --git a/crates/sendbox-governance/src/lib.rs b/crates/sendbox-governance/src/lib.rs new file mode 100644 index 0000000..6c8e548 --- /dev/null +++ b/crates/sendbox-governance/src/lib.rs @@ -0,0 +1,62 @@ +#![forbid(unsafe_code)] +//! Shared governance contract for SendBox. +//! +//! This crate is deliberately free of runtime, I/O, and transport code so a +//! session host and a separate governance service can share one definition of +//! identities, signed policy profiles, session bindings, and credential +//! grants. It never holds credential material. + +pub mod authority; +pub mod binding; +pub mod digest; +pub mod grant; +pub mod identity; +pub mod profile; + +use thiserror::Error; + +pub use authority::{ + AuthorityFuture, Clock, CurrentProfile, GrantAuthority, LocalAuthorityLimits, + LocalGrantAuthority, RevisionSource, SystemClock, +}; +pub use binding::{AuthorityRef, GovernanceBinding}; +pub use digest::{Sha256Digest, canonical_digest}; +pub use grant::{ + AllowedRequest, CredentialGrant, Decision, DenyReason, GrantRequest, RequestContext, + RevocationReason, path_permitted, validate_request_path, +}; +pub use identity::{GrantId, PrincipalId, ProfileId, ProjectId, ServiceId, SessionRef}; +pub use profile::{ + BROKERED_CREDENTIAL_PLACEHOLDER, Ceiling, CeilingAction, CredentialProvider, + CredentialServiceProfile, GovernanceProfile, PROFILE_FORMAT, PROFILE_VERSION, ProfileRef, + ProviderInjection, RuntimeKind, +}; + +/// Wire and digest version shared with external governance services. +pub const CONTRACT_VERSION: u32 = 1; + +#[derive(Debug, Error, Clone, PartialEq, Eq)] +pub enum GovernanceError { + #[error("invalid {kind} identifier `{value}`")] + InvalidIdentifier { kind: &'static str, value: String }, + #[error("invalid SHA-256 digest `{0}`")] + InvalidDigest(String), + #[error("invalid governance profile: {0}")] + InvalidProfile(String), + #[error("governance profile `{id}` revision {revision} is not yet valid")] + ProfileNotYetValid { id: String, revision: u64 }, + #[error("governance profile `{id}` revision {revision} has expired")] + ProfileExpired { id: String, revision: u64 }, + #[error("unsupported governance contract version {0}")] + UnsupportedContract(u32), + #[error("invalid governance binding: {0}")] + InvalidBinding(String), + #[error("invalid credential grant: {0}")] + InvalidGrant(String), + #[error("credential grant denied: {0}")] + Denied(&'static str), + #[error("governance authority unavailable: {0}")] + AuthorityUnavailable(String), + #[error("governance encoding: {0}")] + Encoding(String), +} diff --git a/crates/sendbox-governance/src/profile.rs b/crates/sendbox-governance/src/profile.rs new file mode 100644 index 0000000..cd83254 --- /dev/null +++ b/crates/sendbox-governance/src/profile.rs @@ -0,0 +1,1011 @@ +//! Operator-owned, versioned governance profiles. +//! +//! A profile is the maximum a governed session may be granted. It is parsed +//! from the exact bytes an operator signed; its digest is the SHA-256 of those +//! bytes, so any edit produces a different, separately signed revision. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use crate::{ + GovernanceError, ProfileId, ServiceId, + digest::Sha256Digest, + grant::{validate_method, validate_path_prefix}, +}; + +pub const PROFILE_FORMAT: &str = "sendbox.governance-profile"; +pub const PROFILE_VERSION: u32 = 1; +pub const MAX_PROFILE_BYTES: usize = 256 * 1024; +/// Upper bound for the validity window of one profile revision. +pub const MAX_PROFILE_VALIDITY_SECONDS: u64 = 400 * 24 * 60 * 60; +/// Placeholder credential value given to agents. It is not a secret: the host +/// broker discards it and injects the operator-managed provider credential. +pub const BROKERED_CREDENTIAL_PLACEHOLDER: &str = "sendbox-brokered-credential"; + +const MAX_LIST_ENTRIES: usize = 256; +const MAX_PATTERN_BYTES: usize = 4096; +const MAX_DOMAIN_BYTES: usize = 253; +const MAX_SECRET_NAME_BYTES: usize = 128; +const MAX_MCP_SERVER_ID_BYTES: usize = 64; +const MAX_CREDENTIAL_SERVICES: usize = 16; +const HARD_MAX_REQUEST_BYTES: u64 = 16 * 1024 * 1024; +const HARD_MAX_RESPONSE_BYTES: u64 = 256 * 1024 * 1024; +const HARD_MAX_STREAM_SECONDS: u64 = 60 * 60; +const HARD_MAX_IDLE_SECONDS: u64 = 10 * 60; +const MIN_LEASE_SECONDS: u64 = 30; +const MAX_LEASE_SECONDS: u64 = 60 * 60; +const MAX_GRANT_TTL_SECONDS: u64 = 7 * 24 * 60 * 60; +const MAX_REVOCATION_GRACE_SECONDS: u64 = 60; +const MAX_CONCURRENT_STREAMS: u32 = 64; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GovernanceProfile { + pub format: String, + pub version: u32, + pub id: ProfileId, + pub revision: u64, + pub not_before_unix: u64, + pub expires_at_unix: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + pub ceiling: Ceiling, + #[serde(default)] + pub denials: Denials, + #[serde(default)] + pub credential_services: Vec, + #[serde(default)] + pub grants: GrantLimits, +} + +/// Identity of one exact profile revision. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProfileRef { + pub id: ProfileId, + pub revision: u64, + pub sha256: Sha256Digest, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CeilingAction { + Allow, + Deny, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum RuntimeKind { + Apple, + Kata, + Hyperlight, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Ceiling { + pub runtimes: Vec, + /// Permitted OCI image digests (`sha256:`). Empty permits any image. + #[serde(default)] + pub images: Vec, + /// Permitted host workspace roots. Empty permits any workspace. + #[serde(default)] + pub workspace_roots: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resources: Option, + pub commands: CommandCeiling, + pub network: NetworkCeiling, + #[serde(default)] + pub mcp: McpCeiling, + #[serde(default)] + pub packages: PackageCeiling, + #[serde(default)] + pub secrets: SecretCeiling, + #[serde(default)] + pub github: GitHubCeiling, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ResourceCeiling { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_cpus: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_memory_mb: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_disk_mb: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CommandCeiling { + pub default_action: CeilingAction, + #[serde(default)] + pub allowlist: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TransportProtocol { + Tcp, + Udp, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PortCeiling { + pub protocol: TransportProtocol, + pub port: u16, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NetworkCeiling { + pub default_action: CeilingAction, + #[serde(default)] + pub allowed_domains: Vec, + #[serde(default)] + pub allowed_networks: Vec, + /// Empty permits any destination port. + #[serde(default)] + pub allowed_ports: Vec, + #[serde(default)] + pub allow_dns: bool, + /// Permits the implicit GitHub Meta CIDR delegation that an exact + /// `github.com` grant enables. + #[serde(default)] + pub github_meta: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_connections: Option, + #[serde(default)] + pub dns: DnsCeiling, +} + +/// Loosest DNS broker controls a session may use. Smaller numeric limits and +/// fewer record types are stricter; the budget window must match exactly. +/// Defaults equal the runtime's built-in DNS policy. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct DnsCeiling { + pub max_ttl_secs: u32, + pub max_qname_octets: u32, + pub max_labels: u32, + pub max_label_octets: u32, + pub allowed_record_types: Vec, + pub max_response_records: u32, + pub budget_window_secs: u32, + pub budget_max_queries: u32, + pub budget_max_query_octets: u64, + pub budget_max_unique_names: u32, + pub budget_max_dynamic_labels: u32, +} + +impl Default for DnsCeiling { + fn default() -> Self { + Self { + max_ttl_secs: 300, + max_qname_octets: 253, + max_labels: 40, + max_label_octets: 63, + allowed_record_types: vec!["A".to_owned(), "AAAA".to_owned()], + max_response_records: 32, + budget_window_secs: 60, + budget_max_queries: 600, + budget_max_query_octets: 32_768, + budget_max_unique_names: 256, + budget_max_dynamic_labels: 256, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct McpCeiling { + /// Sessions must keep the MCP/syscall boundary enabled. + #[serde(default = "default_true")] + pub require_boundaries: bool, + #[serde(default)] + pub servers: BTreeMap, +} + +impl Default for McpCeiling { + fn default() -> Self { + Self { + require_boundaries: true, + servers: BTreeMap::new(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum McpTransportCeiling { + Stdio, + StreamableHttp, + StreamableHttp2025, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct McpServerCeiling { + pub transport: McpTransportCeiling, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub command: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option, + #[serde(default)] + pub tools: ToolCeiling, + #[serde(default)] + pub allow_plaintext_local: bool, + #[serde(default)] + pub allow_private_networks: bool, + #[serde(default)] + pub allow_redirects: bool, + #[serde(default)] + pub redirect_allowlist: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bearer_secret: Option, + #[serde(default)] + pub stdio_secrets: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ToolCeiling { + pub default_action: CeilingAction, + #[serde(default)] + pub allowlist: Vec, +} + +impl Default for ToolCeiling { + fn default() -> Self { + Self { + default_action: CeilingAction::Deny, + allowlist: Vec::new(), + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct PackageCeiling { + pub allowed_registries: Vec, + pub allow_insecure_http: bool, + pub registry_credentials: Vec, + pub require_supply_chain: bool, + pub allow_finding_overrides: bool, + pub allow_exceptions: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct SecretCeiling { + /// Host secret names that may be delivered into the guest environment. + pub workload: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct GitHubCeiling { + pub forward_auth: bool, + pub forward_copilot_auth: bool, + pub allow_private_repository_access: bool, + pub ssh_key: bool, + pub require_branch_protection: bool, + pub safe_outputs: SafeOutputsCeiling, +} + +impl Default for GitHubCeiling { + fn default() -> Self { + Self { + forward_auth: false, + forward_copilot_auth: false, + allow_private_repository_access: false, + ssh_key: false, + require_branch_protection: true, + safe_outputs: SafeOutputsCeiling::default(), + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct SafeOutputsCeiling { + pub enabled: bool, + pub allow_apply: bool, + /// Permitted `owner/repository` targets. Empty permits any target. + pub repositories: Vec, +} + +/// Explicit denials appended to every governed session. They always narrow. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Denials { + pub commands: Vec, + pub domains: Vec, + pub networks: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CredentialProvider { + Anthropic, + Openai, +} + +/// How the broker attaches the provider credential to an upstream request. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProviderInjection { + Bearer, + Header(&'static str), +} + +impl CredentialProvider { + #[must_use] + pub const fn target_host(self) -> &'static str { + match self { + Self::Anthropic => "api.anthropic.com", + Self::Openai => "api.openai.com", + } + } + + #[must_use] + pub const fn injection(self) -> ProviderInjection { + match self { + Self::Anthropic => ProviderInjection::Header("x-api-key"), + Self::Openai => ProviderInjection::Bearer, + } + } + + #[must_use] + pub fn default_methods(self) -> Vec { + vec!["GET".to_owned(), "POST".to_owned()] + } + + #[must_use] + pub fn default_path_prefixes(self) -> Vec { + match self { + Self::Anthropic => vec!["/v1/messages".to_owned(), "/v1/models".to_owned()], + Self::Openai => vec![ + "/v1/responses".to_owned(), + "/v1/chat/completions".to_owned(), + "/v1/models".to_owned(), + ], + } + } + + /// Path appended to the relay route in the agent's base URL. OpenAI SDKs + /// expect the version segment in the base URL; Anthropic SDKs append it. + #[must_use] + pub const fn base_url_suffix(self) -> &'static str { + match self { + Self::Anthropic => "", + Self::Openai => "/v1", + } + } + + /// Provider-standard variables that compatible agents read for an explicit + /// API base URL and key. + #[must_use] + pub const fn base_url_environment(self) -> &'static str { + match self { + Self::Anthropic => "ANTHROPIC_BASE_URL", + Self::Openai => "OPENAI_BASE_URL", + } + } + + #[must_use] + pub const fn api_key_environment(self) -> &'static str { + match self { + Self::Anthropic => "ANTHROPIC_API_KEY", + Self::Openai => "OPENAI_API_KEY", + } + } + + /// Request headers the relay forwards from the agent. Every other header, + /// including any agent-supplied credential, is dropped. + #[must_use] + pub fn forwards_request_header(self, name: &str) -> bool { + const COMMON: &[&str] = &[ + "accept", + "accept-encoding", + "accept-language", + "content-type", + "user-agent", + "idempotency-key", + ]; + let name = name.to_ascii_lowercase(); + if COMMON.contains(&name.as_str()) || name.starts_with("x-stainless-") { + return true; + } + match self { + Self::Anthropic => matches!(name.as_str(), "anthropic-version" | "anthropic-beta"), + Self::Openai => matches!(name.as_str(), "openai-beta" | "originator" | "session_id"), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialServiceProfile { + pub id: ServiceId, + pub provider: CredentialProvider, + /// Host secret-store name holding the provider credential. + pub secret: String, + #[serde(default)] + pub methods: Vec, + #[serde(default)] + pub path_prefixes: Vec, + #[serde(default = "default_max_request_bytes")] + pub max_request_bytes: u64, + #[serde(default = "default_max_response_bytes")] + pub max_response_bytes: u64, + #[serde(default = "default_max_duration_seconds")] + pub max_duration_seconds: u64, + #[serde(default = "default_idle_timeout_seconds")] + pub idle_timeout_seconds: u64, + /// Adds the provider host to every governed session's blocked domains so + /// the workload cannot bypass the broker with its own credential. + #[serde(default = "default_true")] + pub deny_direct_egress: bool, +} + +impl CredentialServiceProfile { + #[must_use] + pub fn effective_methods(&self) -> BTreeSet { + if self.methods.is_empty() { + self.provider.default_methods().into_iter().collect() + } else { + self.methods.iter().cloned().collect() + } + } + + #[must_use] + pub fn effective_path_prefixes(&self) -> Vec { + if self.path_prefixes.is_empty() { + self.provider.default_path_prefixes() + } else { + self.path_prefixes.clone() + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct GrantLimits { + pub lease_seconds: u64, + pub max_ttl_seconds: u64, + pub revocation_grace_seconds: u64, + pub max_concurrent_streams: u32, +} + +impl Default for GrantLimits { + fn default() -> Self { + Self { + lease_seconds: 300, + max_ttl_seconds: 8 * 60 * 60, + revocation_grace_seconds: 5, + max_concurrent_streams: 8, + } + } +} + +const fn default_true() -> bool { + true +} + +const fn default_max_request_bytes() -> u64 { + 8 * 1024 * 1024 +} + +const fn default_max_response_bytes() -> u64 { + 64 * 1024 * 1024 +} + +const fn default_max_duration_seconds() -> u64 { + 15 * 60 +} + +const fn default_idle_timeout_seconds() -> u64 { + 120 +} + +impl GovernanceProfile { + /// Parses and structurally validates the exact signed profile bytes. + pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAX_PROFILE_BYTES { + return Err(GovernanceError::InvalidProfile(format!( + "profile exceeds {MAX_PROFILE_BYTES} bytes" + ))); + } + let text = std::str::from_utf8(bytes) + .map_err(|_| GovernanceError::InvalidProfile("profile is not UTF-8".to_owned()))?; + let profile: Self = serde_yaml_ng::from_str(text) + .map_err(|error| GovernanceError::InvalidProfile(error.to_string()))?; + profile.validate()?; + Ok(profile) + } + + #[must_use] + pub fn reference(&self, signed_bytes: &[u8]) -> ProfileRef { + ProfileRef { + id: self.id.clone(), + revision: self.revision, + sha256: Sha256Digest::of(signed_bytes), + } + } + + /// Rejects a profile outside its validity window. + pub fn check_validity(&self, now_unix: u64) -> Result<(), GovernanceError> { + if now_unix < self.not_before_unix { + return Err(GovernanceError::ProfileNotYetValid { + id: self.id.to_string(), + revision: self.revision, + }); + } + if now_unix >= self.expires_at_unix { + return Err(GovernanceError::ProfileExpired { + id: self.id.to_string(), + revision: self.revision, + }); + } + Ok(()) + } + + #[must_use] + pub fn credential_service(&self, id: &ServiceId) -> Option<&CredentialServiceProfile> { + self.credential_services + .iter() + .find(|service| &service.id == id) + } + + pub fn validate(&self) -> Result<(), GovernanceError> { + let mut problems = Vec::new(); + let mut require = |ok: bool, message: String| { + if !ok { + problems.push(message); + } + }; + require( + self.format == PROFILE_FORMAT, + format!("format must be `{PROFILE_FORMAT}`"), + ); + require( + self.version == PROFILE_VERSION, + format!("version must be {PROFILE_VERSION}"), + ); + require(self.revision >= 1, "revision must be at least 1".to_owned()); + require( + self.not_before_unix < self.expires_at_unix + && self.expires_at_unix - self.not_before_unix <= MAX_PROFILE_VALIDITY_SECONDS, + format!( + "validity window must be non-empty and at most {MAX_PROFILE_VALIDITY_SECONDS} seconds" + ), + ); + if let Some(description) = &self.description { + require( + description.len() <= 1024 && !description.chars().any(char::is_control), + "description must be at most 1024 bytes without control characters".to_owned(), + ); + } + self.ceiling.validate(&mut problems); + validate_patterns(&self.denials.commands, "denials.commands", &mut problems); + validate_domains(&self.denials.domains, "denials.domains", &mut problems); + validate_patterns(&self.denials.networks, "denials.networks", &mut problems); + self.validate_credential_services(&mut problems); + self.grants.validate(&mut problems); + if problems.is_empty() { + Ok(()) + } else { + Err(GovernanceError::InvalidProfile(problems.join("; "))) + } + } + + fn validate_credential_services(&self, problems: &mut Vec) { + if self.credential_services.len() > MAX_CREDENTIAL_SERVICES { + problems.push(format!( + "at most {MAX_CREDENTIAL_SERVICES} credential services are supported" + )); + } + let mut ids = BTreeSet::new(); + for service in &self.credential_services { + let path = format!("credential_services[{}]", service.id); + if !ids.insert(&service.id) { + problems.push(format!("{path}: duplicate service id")); + } + if !valid_secret_name(&service.secret) { + problems.push(format!( + "{path}.secret must be 1-{MAX_SECRET_NAME_BYTES} ASCII letters, digits, '_', '-' or '.'" + )); + } + if self + .ceiling + .secrets + .workload + .iter() + .any(|name| name.eq_ignore_ascii_case(&service.secret)) + { + problems.push(format!( + "{path}.secret must not also be a workload secret delivered to the guest" + )); + } + let methods = service.effective_methods(); + if methods.len() != service.methods.len() && !service.methods.is_empty() { + problems.push(format!("{path}.methods contains duplicates")); + } + for method in &methods { + if let Err(error) = validate_method(method) { + problems.push(format!("{path}.methods: {error}")); + } + } + let prefixes = service.effective_path_prefixes(); + if prefixes.len() > MAX_LIST_ENTRIES { + problems.push(format!("{path}.path_prefixes has too many entries")); + } + for prefix in &prefixes { + if let Err(error) = validate_path_prefix(prefix) { + problems.push(format!("{path}.path_prefixes: {error}")); + } + } + if !(1..=HARD_MAX_REQUEST_BYTES).contains(&service.max_request_bytes) { + problems.push(format!( + "{path}.max_request_bytes must be 1..={HARD_MAX_REQUEST_BYTES}" + )); + } + if !(1..=HARD_MAX_RESPONSE_BYTES).contains(&service.max_response_bytes) { + problems.push(format!( + "{path}.max_response_bytes must be 1..={HARD_MAX_RESPONSE_BYTES}" + )); + } + if !(1..=HARD_MAX_STREAM_SECONDS).contains(&service.max_duration_seconds) { + problems.push(format!( + "{path}.max_duration_seconds must be 1..={HARD_MAX_STREAM_SECONDS}" + )); + } + if !(1..=HARD_MAX_IDLE_SECONDS).contains(&service.idle_timeout_seconds) { + problems.push(format!( + "{path}.idle_timeout_seconds must be 1..={HARD_MAX_IDLE_SECONDS}" + )); + } + } + } +} + +impl Ceiling { + fn validate(&self, problems: &mut Vec) { + let runtimes = self.runtimes.iter().collect::>(); + if runtimes.is_empty() || runtimes.len() != self.runtimes.len() { + problems + .push("ceiling.runtimes must be a non-empty list without duplicates".to_owned()); + } + bounded(&self.images, "ceiling.images", problems); + for image in &self.images { + let valid = image.strip_prefix("sha256:").is_some_and(|hex| { + hex.len() == 64 + && hex + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + }); + if !valid { + problems.push(format!( + "ceiling.images entry `{image}` must be sha256:<64 lowercase hex>" + )); + } + } + bounded(&self.workspace_roots, "ceiling.workspace_roots", problems); + for root in &self.workspace_roots { + if !normalized_absolute_path(root) { + problems.push(format!( + "ceiling.workspace_roots entry `{root}` must be an absolute, normalized path below `/`" + )); + } + } + if let Some(resources) = &self.resources { + for (name, value) in [ + ("max_cpus", resources.max_cpus), + ("max_memory_mb", resources.max_memory_mb), + ("max_disk_mb", resources.max_disk_mb), + ] { + if value.is_some_and(|value| value <= 0) { + problems.push(format!("ceiling.resources.{name} must be positive")); + } + } + } + validate_patterns( + &self.commands.allowlist, + "ceiling.commands.allowlist", + problems, + ); + validate_domains( + &self.network.allowed_domains, + "ceiling.network.allowed_domains", + problems, + ); + validate_patterns( + &self.network.allowed_networks, + "ceiling.network.allowed_networks", + problems, + ); + bounded( + &self.network.allowed_ports, + "ceiling.network.allowed_ports", + problems, + ); + if self.network.allowed_ports.iter().any(|rule| rule.port == 0) { + problems.push("ceiling.network.allowed_ports cannot contain port 0".to_owned()); + } + if self.network.max_connections.is_some_and(|value| value <= 0) { + problems.push("ceiling.network.max_connections must be positive".to_owned()); + } + let dns = &self.network.dns; + if dns.allowed_record_types.is_empty() + || dns + .allowed_record_types + .iter() + .any(|kind| kind != "A" && kind != "AAAA") + { + problems.push( + "ceiling.network.dns.allowed_record_types must contain only A and AAAA".to_owned(), + ); + } + if dns.budget_window_secs == 0 { + problems.push("ceiling.network.dns.budget_window_secs must be positive".to_owned()); + } + if self.mcp.servers.len() > MAX_LIST_ENTRIES { + problems.push("ceiling.mcp.servers has too many entries".to_owned()); + } + for (id, server) in &self.mcp.servers { + let path = format!("ceiling.mcp.servers.{id}"); + if id.is_empty() + || id.len() > MAX_MCP_SERVER_ID_BYTES + || !id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) + { + problems.push(format!("{path}: invalid server id")); + } + match server.transport { + McpTransportCeiling::Stdio => { + if server.command.is_empty() || server.url.is_some() { + problems.push(format!( + "{path}: stdio servers require `command` and forbid `url`" + )); + } + } + McpTransportCeiling::StreamableHttp | McpTransportCeiling::StreamableHttp2025 => { + if server.url.is_none() || !server.command.is_empty() { + problems.push(format!( + "{path}: HTTP servers require `url` and forbid `command`" + )); + } + } + } + validate_patterns(&server.command, &format!("{path}.command"), problems); + validate_patterns( + &server.tools.allowlist, + &format!("{path}.tools.allowlist"), + problems, + ); + validate_patterns( + &server.redirect_allowlist, + &format!("{path}.redirect_allowlist"), + problems, + ); + for secret in server.bearer_secret.iter().chain(&server.stdio_secrets) { + if !valid_secret_name(secret) { + problems.push(format!("{path}: invalid secret name `{secret}`")); + } + } + } + validate_patterns( + &self.packages.allowed_registries, + "ceiling.packages.allowed_registries", + problems, + ); + for name in self + .packages + .registry_credentials + .iter() + .chain(&self.secrets.workload) + { + if !valid_secret_name(name) { + problems.push(format!("ceiling: invalid secret name `{name}`")); + } + } + bounded( + &self.packages.registry_credentials, + "ceiling.packages.registry_credentials", + problems, + ); + bounded(&self.secrets.workload, "ceiling.secrets.workload", problems); + validate_patterns( + &self.github.safe_outputs.repositories, + "ceiling.github.safe_outputs.repositories", + problems, + ); + if self.github.safe_outputs.allow_apply && !self.github.safe_outputs.enabled { + problems.push( + "ceiling.github.safe_outputs.allow_apply requires safe_outputs.enabled".to_owned(), + ); + } + } +} + +impl GrantLimits { + fn validate(&self, problems: &mut Vec) { + if !(MIN_LEASE_SECONDS..=MAX_LEASE_SECONDS).contains(&self.lease_seconds) { + problems.push(format!( + "grants.lease_seconds must be {MIN_LEASE_SECONDS}..={MAX_LEASE_SECONDS}" + )); + } + if self.max_ttl_seconds < self.lease_seconds || self.max_ttl_seconds > MAX_GRANT_TTL_SECONDS + { + problems.push(format!( + "grants.max_ttl_seconds must be between lease_seconds and {MAX_GRANT_TTL_SECONDS}" + )); + } + if self.revocation_grace_seconds > MAX_REVOCATION_GRACE_SECONDS { + problems.push(format!( + "grants.revocation_grace_seconds must be at most {MAX_REVOCATION_GRACE_SECONDS}" + )); + } + if !(1..=MAX_CONCURRENT_STREAMS).contains(&self.max_concurrent_streams) { + problems.push(format!( + "grants.max_concurrent_streams must be 1..={MAX_CONCURRENT_STREAMS}" + )); + } + } +} + +fn bounded(values: &[T], path: &str, problems: &mut Vec) { + if values.len() > MAX_LIST_ENTRIES { + problems.push(format!("{path} has more than {MAX_LIST_ENTRIES} entries")); + } +} + +fn validate_patterns(values: &[String], path: &str, problems: &mut Vec) { + bounded(values, path, problems); + let mut unique = BTreeSet::new(); + for value in values { + if value.trim().is_empty() + || value.len() > MAX_PATTERN_BYTES + || value.chars().any(char::is_control) + { + problems.push(format!( + "{path} entries must be non-empty, bounded, and free of control characters" + )); + } else if !unique.insert(value) { + problems.push(format!("{path} contains duplicate `{value}`")); + } + } +} + +fn validate_domains(values: &[String], path: &str, problems: &mut Vec) { + validate_patterns(values, path, problems); + for value in values { + if value.len() > MAX_DOMAIN_BYTES || value.bytes().any(|byte| byte.is_ascii_whitespace()) { + problems.push(format!("{path} entry `{value}` is not a domain pattern")); + } + } +} + +#[must_use] +pub fn valid_secret_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= MAX_SECRET_NAME_BYTES + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.')) +} + +fn normalized_absolute_path(value: &str) -> bool { + value.starts_with('/') + && value.len() > 1 + && !value.ends_with('/') + && !value.chars().any(char::is_control) + && value[1..] + .split('/') + .all(|segment| !segment.is_empty() && segment != "." && segment != "..") +} + +#[cfg(test)] +mod tests { + use super::*; + + pub(crate) const MINIMAL: &str = r#" +format: sendbox.governance-profile +version: 1 +id: acme-default +revision: 3 +not_before_unix: 1000 +expires_at_unix: 2000 +ceiling: + runtimes: [apple, kata] + commands: + default_action: deny + allowlist: ["/usr/bin/git *"] + network: + default_action: deny + allowed_domains: ["*.github.com"] +credential_services: + - id: anthropic + provider: anthropic + secret: SENDBOX_ANTHROPIC_API_KEY +"#; + + #[test] + fn minimal_profile_parses_with_conservative_defaults() { + let profile = GovernanceProfile::parse(MINIMAL.as_bytes()).expect("profile"); + assert!(profile.ceiling.mcp.require_boundaries); + assert!(profile.ceiling.github.require_branch_protection); + assert!(!profile.ceiling.github.forward_auth); + assert!(!profile.ceiling.network.github_meta); + let service = &profile.credential_services[0]; + assert!(service.deny_direct_egress); + assert_eq!( + service.effective_path_prefixes(), + vec!["/v1/messages", "/v1/models"] + ); + let reference = profile.reference(MINIMAL.as_bytes()); + assert_eq!(reference.revision, 3); + assert_eq!(reference.sha256, Sha256Digest::of(MINIMAL.as_bytes())); + } + + #[test] + fn validity_window_is_enforced() { + let profile = GovernanceProfile::parse(MINIMAL.as_bytes()).expect("profile"); + assert!(matches!( + profile.check_validity(999), + Err(GovernanceError::ProfileNotYetValid { .. }) + )); + assert!(profile.check_validity(1000).is_ok()); + assert!(matches!( + profile.check_validity(2000), + Err(GovernanceError::ProfileExpired { .. }) + )); + } + + #[test] + fn invalid_profiles_are_rejected_with_reasons() { + for (needle, replacement, reason) in [ + ("version: 1", "version: 2", "version"), + ("revision: 3", "revision: 0", "revision"), + ("runtimes: [apple, kata]", "runtimes: []", "runtimes"), + ( + "secret: SENDBOX_ANTHROPIC_API_KEY", + "secret: \"bad name\"", + "secret", + ), + ("expires_at_unix: 2000", "expires_at_unix: 1000", "validity"), + ] { + let text = MINIMAL.replace(needle, replacement); + let error = GovernanceProfile::parse(text.as_bytes()).expect_err(reason); + assert!(error.to_string().contains(reason), "{reason}: {error}"); + } + let unknown = format!("{MINIMAL}unexpected: true\n"); + assert!(GovernanceProfile::parse(unknown.as_bytes()).is_err()); + } + + #[test] + fn brokered_secret_cannot_also_be_a_workload_secret() { + let text = MINIMAL.replace( + " network:", + " secrets:\n workload: [SENDBOX_ANTHROPIC_API_KEY]\n network:", + ); + let error = GovernanceProfile::parse(text.as_bytes()).expect_err("overlap"); + assert!(error.to_string().contains("workload secret")); + } + + #[test] + fn provider_header_allowlist_drops_credentials() { + let provider = CredentialProvider::Anthropic; + assert!(provider.forwards_request_header("Anthropic-Version")); + assert!(provider.forwards_request_header("x-stainless-lang")); + assert!(!provider.forwards_request_header("x-api-key")); + assert!(!provider.forwards_request_header("authorization")); + assert!(!CredentialProvider::Openai.forwards_request_header("Authorization")); + assert!(!CredentialProvider::Openai.forwards_request_header("cookie")); + } +} diff --git a/crates/sendbox-host/Cargo.toml b/crates/sendbox-host/Cargo.toml index 1eb7de1..8093d0d 100644 --- a/crates/sendbox-host/Cargo.toml +++ b/crates/sendbox-host/Cargo.toml @@ -8,6 +8,7 @@ publish = false [dependencies] getrandom = "0.3.4" +ipnet.workspace = true reqwest.workspace = true rustix.workspace = true sendbox-agent = { path = "../sendbox-agent" } @@ -21,8 +22,10 @@ sendbox-credentials = { path = "../sendbox-credentials" } sendbox-egress = { path = "../sendbox-egress" } sendbox-exec = { path = "../sendbox-exec" } sendbox-git = { path = "../sendbox-git" } +sendbox-governance = { path = "../sendbox-governance" } sendbox-mcp = { path = "../sendbox-mcp" } sendbox-policy = { path = "../sendbox-policy" } +sendbox-protocol = { path = "../sendbox-protocol" } sendbox-registry = { path = "../sendbox-registry" } sendbox-runtime = { path = "../sendbox-runtime" } sendbox-runtime-apple = { path = "../sendbox-runtime-apple" } @@ -33,6 +36,7 @@ sendbox-security = { path = "../sendbox-security" } sendbox-session-security = { path = "../sendbox-session-security" } serde.workspace = true serde_json.workspace = true +serde_yaml_ng.workspace = true thiserror.workspace = true tempfile.workspace = true tokio.workspace = true diff --git a/crates/sendbox-host/src/governance/composition.rs b/crates/sendbox-host/src/governance/composition.rs new file mode 100644 index 0000000..f472670 --- /dev/null +++ b/crates/sendbox-host/src/governance/composition.rs @@ -0,0 +1,1100 @@ +//! Checks that a project configuration stays within a governance profile. +//! +//! The check compares the effective, fully expanded session capabilities +//! against the profile ceiling. It never merges allowlists: every capability a +//! session would receive, including implicit grants such as GitHub Meta CIDR +//! delegation, must be individually covered. Dimensions the profile cannot +//! express are rejected rather than ignored. + +use std::fmt; +use std::net::IpAddr; +use std::path::Path; + +use ipnet::IpNet; +use sendbox_config::{KataRuntimeConfiguration, SafeOutputsMode, SandboxConfiguration}; +use sendbox_egress::domain::{normalize_pattern, pattern_matches}; +use sendbox_governance::ServiceId; +use sendbox_governance::profile::{ + CeilingAction, CredentialServiceProfile, DnsCeiling, GovernanceProfile, McpTransportCeiling, + RuntimeKind, TransportProtocol, +}; +use sendbox_policy::{ + Action, DnsRecordType, McpServerPolicy, NetworkPolicy, PackageAction, PolicyConfiguration, + Protocol, ToolTransport, normalize_mcp_http_endpoint, +}; + +/// Session facts that are not part of the project configuration. +#[derive(Debug, Clone)] +pub struct SessionFacts<'a> { + pub runtime: RuntimeKind, + pub image: Option<&'a str>, + pub workspace_root: &'a Path, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ViolationKind { + /// The session requests more than the profile permits. + Widening, + /// The session uses a setting governance cannot reason about safely. + Unsupported, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Violation { + pub kind: ViolationKind, + pub path: String, + pub message: String, +} + +impl fmt::Display for Violation { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.kind { + ViolationKind::Widening => "exceeds profile", + ViolationKind::Unsupported => "unsupported in governed sessions", + }; + write!(formatter, "{} ({kind}): {}", self.path, self.message) + } +} + +/// Appends the profile's explicit denials. Denials only ever narrow: they add +/// deny rules and blocked destinations and never remove an existing entry. +pub fn apply_denials(profile: &GovernanceProfile, policy: &mut PolicyConfiguration) { + extend_unique(&mut policy.commands.denylist, &profile.denials.commands); + extend_unique( + &mut policy.network.blocked_domains, + &profile.denials.domains, + ); + extend_unique( + &mut policy.network.blocked_networks, + &profile.denials.networks, + ); + let provider_hosts = profile + .credential_services + .iter() + .filter(|service| service.deny_direct_egress) + .map(|service| service.provider.target_host().to_owned()) + .collect::>(); + extend_unique(&mut policy.network.blocked_domains, &provider_hosts); +} + +fn extend_unique(target: &mut Vec, additions: &[String]) { + for addition in additions { + if !target.iter().any(|existing| existing == addition) { + target.push(addition.clone()); + } + } +} + +/// Returns every way `configuration` exceeds `profile`, or nothing when the +/// session is admissible. +#[must_use] +pub fn check( + profile: &GovernanceProfile, + configuration: &SandboxConfiguration, + facts: &SessionFacts<'_>, +) -> Vec { + let mut checker = Checker::default(); + checker.runtime(profile, configuration, facts); + checker.commands(profile, &configuration.policy); + checker.network(profile, &configuration.policy.network); + checker.boundaries(profile, &configuration.policy); + checker.packages(profile, &configuration.policy); + checker.secrets(profile, configuration); + checker.github(profile, configuration); + checker.credential_services(profile, configuration, facts); + checker.violations +} + +/// The credential services a configuration selects, resolved against the +/// profile in sorted order. +pub fn selected_services<'a>( + profile: &'a GovernanceProfile, + configuration: &SandboxConfiguration, +) -> Result, String> { + let mut selected = configuration + .credential_services + .iter() + .map(|id| { + let id = ServiceId::new(id.clone()).map_err(|error| error.to_string())?; + profile + .credential_service(&id) + .ok_or_else(|| format!("credential service `{id}` is not offered by the profile")) + }) + .collect::, _>>()?; + selected.sort_by(|left, right| left.id.cmp(&right.id)); + Ok(selected) +} + +#[derive(Default)] +struct Checker { + violations: Vec, +} + +impl Checker { + fn widening(&mut self, path: impl Into, message: impl Into) { + self.violations.push(Violation { + kind: ViolationKind::Widening, + path: path.into(), + message: message.into(), + }); + } + + fn unsupported(&mut self, path: impl Into, message: impl Into) { + self.violations.push(Violation { + kind: ViolationKind::Unsupported, + path: path.into(), + message: message.into(), + }); + } + + fn runtime( + &mut self, + profile: &GovernanceProfile, + configuration: &SandboxConfiguration, + facts: &SessionFacts<'_>, + ) { + let ceiling = &profile.ceiling; + if facts.runtime == RuntimeKind::Hyperlight { + self.unsupported( + "runtime.provider", + "Hyperlight does not provide the persistent guest boundary that governed sessions require", + ); + } else if !ceiling.runtimes.contains(&facts.runtime) { + self.widening( + "runtime.provider", + format!("runtime {:?} is not permitted", facts.runtime), + ); + } + if let Some(runtime) = &configuration.runtime + && runtime.kata != KataRuntimeConfiguration::default() + { + self.unsupported( + "runtime.kata", + "project files cannot select Kata executables, handlers, or configuration in governed sessions", + ); + } + if !ceiling.images.is_empty() { + let digest = facts + .image + .and_then(|image| image.rsplit_once('@')) + .map(|(_, digest)| digest); + if !digest.is_some_and(|digest| ceiling.images.iter().any(|image| image == digest)) { + self.widening("--image", "image digest is not in the permitted image set"); + } + } + if !ceiling.workspace_roots.is_empty() + && !ceiling + .workspace_roots + .iter() + .any(|root| facts.workspace_root.starts_with(root)) + { + self.widening( + "workspace_path", + format!( + "workspace {} is outside the permitted workspace roots", + facts.workspace_root.display() + ), + ); + } + if let Some(resources) = &ceiling.resources { + for (path, value, maximum) in [ + ( + "resources.cpus", + configuration.resources.cpus, + resources.max_cpus, + ), + ( + "resources.memory_mb", + configuration.resources.memory_mb, + resources.max_memory_mb, + ), + ( + "resources.disk_size_mb", + configuration.resources.disk_size_mb, + resources.max_disk_mb, + ), + ] { + if let Some(maximum) = maximum + && value > maximum + { + self.widening(path, format!("{value} exceeds the maximum {maximum}")); + } + } + } + } + + fn commands(&mut self, profile: &GovernanceProfile, policy: &PolicyConfiguration) { + let ceiling = &profile.ceiling.commands; + if ceiling.default_action == CeilingAction::Allow { + return; + } + if policy.commands.default_action == Action::Allow { + self.widening( + "policy.commands.default_action", + "allow-by-default command execution is not permitted", + ); + return; + } + for rule in &policy.commands.allowlist { + let mut covered = false; + for ceiling_rule in &ceiling.allowlist { + match sendbox_exec::rule_covers(ceiling_rule, rule) { + Ok(true) => { + covered = true; + break; + } + Ok(false) => {} + Err(error) => { + self.unsupported( + "ceiling.commands.allowlist", + format!("rule `{ceiling_rule}` cannot be compiled: {error}"), + ); + return; + } + } + } + if !covered { + self.widening( + "policy.commands.allowlist", + format!("`{rule}` is not covered by a permitted command rule"), + ); + } + } + } + + fn network(&mut self, profile: &GovernanceProfile, network: &NetworkPolicy) { + let ceiling = &profile.ceiling.network; + let (blocked, allowed, ceiling_domains) = match ( + normalize_all(&network.blocked_domains), + normalize_all(&network.allowed_domains), + normalize_all(&ceiling.allowed_domains), + ) { + (Ok(blocked), Ok(allowed), Ok(ceiling)) => (blocked, allowed, ceiling), + (Err(message), _, _) | (_, Err(message), _) | (_, _, Err(message)) => { + self.unsupported("policy.network", message); + return; + } + }; + + if ceiling.default_action == CeilingAction::Deny { + if network.default_action == Action::Allow { + self.widening( + "policy.network.default_action", + "allow-by-default network egress is not permitted", + ); + } else { + for pattern in &allowed { + if !pattern_covered(&blocked, pattern) + && !pattern_covered(&ceiling_domains, pattern) + { + self.widening( + "policy.network.allowed_domains", + format!("`{pattern}` is not covered by a permitted domain"), + ); + } + } + } + } + + let meta_delegated = allowed.iter().any(|name| name == "github.com") + && !blocked + .iter() + .any(|pattern| pattern_matches(pattern, "github.com")); + if meta_delegated && !ceiling.github_meta { + self.widening( + "policy.network.allowed_domains", + "an exact `github.com` grant implicitly delegates GitHub Meta CIDRs, which the profile does not permit", + ); + } + + match ( + parse_networks(&network.allowed_networks), + parse_networks(&ceiling.allowed_networks), + ) { + (Ok(networks), Ok(ceiling_networks)) => { + for net in networks { + if !ceiling_networks + .iter() + .any(|ceiling| ceiling.contains(&net)) + { + self.widening( + "policy.network.allowed_networks", + format!("`{net}` is not contained in a permitted network"), + ); + } + } + } + (Err(message), _) | (_, Err(message)) => { + self.unsupported("policy.network.allowed_networks", message); + } + } + + if !ceiling.allowed_ports.is_empty() { + if network.allowed_ports.is_empty() { + self.widening( + "policy.network.allowed_ports", + "an empty port list permits every port; list permitted ports explicitly", + ); + } + for rule in &network.allowed_ports { + let protocol = match rule.protocol { + Protocol::Tcp => TransportProtocol::Tcp, + Protocol::Udp => TransportProtocol::Udp, + }; + if !ceiling + .allowed_ports + .iter() + .any(|permitted| permitted.protocol == protocol && permitted.port == rule.port) + { + self.widening( + "policy.network.allowed_ports", + format!("{protocol:?}/{} is not permitted", rule.port), + ); + } + } + } + if network.allow_dns && !ceiling.allow_dns { + self.widening( + "policy.network.allow_dns", + "DNS resolution is not permitted", + ); + } + if let Some(maximum) = ceiling.max_connections { + match network.max_connections { + Some(value) if value <= maximum => {} + _ => self.widening( + "policy.network.max_connections", + format!("must be set to at most {maximum}"), + ), + } + } + self.dns(&ceiling.dns, network); + } + + fn dns(&mut self, ceiling: &DnsCeiling, network: &NetworkPolicy) { + let dns = &network.dns; + let limits: [(&str, u64, u64); 9] = [ + ( + "max_ttl_secs", + dns.max_ttl_secs.into(), + ceiling.max_ttl_secs.into(), + ), + ( + "max_qname_octets", + dns.max_qname_octets.into(), + ceiling.max_qname_octets.into(), + ), + ( + "max_labels", + dns.max_labels.into(), + ceiling.max_labels.into(), + ), + ( + "max_label_octets", + dns.max_label_octets.into(), + ceiling.max_label_octets.into(), + ), + ( + "max_response_records", + dns.max_response_records.into(), + ceiling.max_response_records.into(), + ), + ( + "budget.max_queries", + dns.budget.max_queries.into(), + ceiling.budget_max_queries.into(), + ), + ( + "budget.max_query_octets", + dns.budget.max_query_octets, + ceiling.budget_max_query_octets, + ), + ( + "budget.max_unique_names", + dns.budget.max_unique_names.into(), + ceiling.budget_max_unique_names.into(), + ), + ( + "budget.max_dynamic_labels", + dns.budget.max_dynamic_labels.into(), + ceiling.budget_max_dynamic_labels.into(), + ), + ]; + for (field, value, maximum) in limits { + if value > maximum { + self.widening( + format!("policy.network.dns.{field}"), + format!("{value} exceeds the maximum {maximum}"), + ); + } + } + if dns.budget.window_secs != ceiling.budget_window_secs { + self.widening( + "policy.network.dns.budget.window_secs", + format!("must equal {}", ceiling.budget_window_secs), + ); + } + for record in &dns.allowed_record_types { + let name = match record { + DnsRecordType::A => "A", + DnsRecordType::Aaaa => "AAAA", + }; + if !ceiling.allowed_record_types.iter().any(|kind| kind == name) { + self.widening( + "policy.network.dns.allowed_record_types", + format!("{name} queries are not permitted"), + ); + } + } + } + + fn boundaries(&mut self, profile: &GovernanceProfile, policy: &PolicyConfiguration) { + let ceiling = &profile.ceiling.mcp; + let boundaries = &policy.boundaries; + if !boundaries.enabled && ceiling.require_boundaries { + self.widening( + "policy.boundaries.enabled", + "the MCP and syscall boundary must stay enabled", + ); + } + let tools = &boundaries.tool_calls; + if tools.uses_legacy_fields() { + self.unsupported( + "policy.boundaries.tool_calls", + "legacy flat MCP rules are not supported; declare hierarchical `servers` instead", + ); + } + for (id, server) in &tools.servers { + let path = format!("policy.boundaries.tool_calls.servers.{id}"); + let Some(permitted) = ceiling.servers.get(id) else { + self.widening(path, "MCP server is not permitted"); + continue; + }; + let transport = match server.transport() { + ToolTransport::Stdio => McpTransportCeiling::Stdio, + ToolTransport::StreamableHttp => McpTransportCeiling::StreamableHttp, + ToolTransport::StreamableHttp2025 => McpTransportCeiling::StreamableHttp2025, + }; + if transport != permitted.transport { + self.widening(&path, "transport differs from the permitted server"); + continue; + } + match server { + McpServerPolicy::Stdio { + command, + authorization, + .. + } => { + if *command != permitted.command { + self.widening( + format!("{path}.command"), + "command differs from the permitted server", + ); + } + for secret in authorization + .iter() + .flat_map(|authorization| authorization.secret_names()) + { + if !permitted.stdio_secrets.contains(secret) { + self.widening( + format!("{path}.authorization"), + format!("secret `{secret}` is not permitted for this server"), + ); + } + } + } + McpServerPolicy::StreamableHttp { url, http, .. } + | McpServerPolicy::StreamableHttp2025 { url, http, .. } => { + let same_url = permitted.url.as_deref().is_some_and(|permitted| { + matches!( + ( + normalize_mcp_http_endpoint(url), + normalize_mcp_http_endpoint(permitted), + ), + (Ok(left), Ok(right)) if left == right + ) + }); + if !same_url { + self.widening( + format!("{path}.url"), + "endpoint differs from the permitted server", + ); + } + for (field, requested, allowed) in [ + ( + "allow_plaintext_local", + http.allow_plaintext_local, + permitted.allow_plaintext_local, + ), + ( + "allow_private_networks", + http.allow_private_networks, + permitted.allow_private_networks, + ), + ( + "allow_redirects", + http.allow_redirects, + permitted.allow_redirects, + ), + ] { + if requested && !allowed { + self.widening(format!("{path}.http.{field}"), "is not permitted"); + } + } + for redirect in &http.redirect_allowlist { + if !permitted.redirect_allowlist.contains(redirect) { + self.widening( + format!("{path}.http.redirect_allowlist"), + format!("`{redirect}` is not permitted"), + ); + } + } + if let Some(authorization) = &http.authorization + && permitted.bearer_secret.as_deref() + != Some(authorization.bearer_secret.as_str()) + { + self.widening( + format!("{path}.http.authorization"), + "bearer credential is not permitted for this server", + ); + } + } + } + let tool_rules = server.tools(); + if permitted.tools.default_action == CeilingAction::Deny { + if tool_rules.default_action == Action::Allow { + self.widening( + format!("{path}.tools.default_action"), + "allow-by-default tools are not permitted", + ); + } + for tool in &tool_rules.allowlist { + if !permitted.tools.allowlist.contains(tool) { + self.widening( + format!("{path}.tools.allowlist"), + format!("tool `{tool}` is not permitted"), + ); + } + } + } + } + } + + fn packages(&mut self, profile: &GovernanceProfile, policy: &PolicyConfiguration) { + let ceiling = &profile.ceiling.packages; + let packages = &policy.packages; + if !packages.enabled { + if ceiling.require_supply_chain { + self.widening( + "policy.packages.enabled", + "package supply-chain inspection is required", + ); + } + return; + } + for (index, registry) in packages.registries.iter().enumerate() { + let path = format!("policy.packages.registries[{index}]"); + if !ceiling.allowed_registries.contains(®istry.url) { + self.widening( + &path, + format!("registry `{}` is not permitted", registry.url), + ); + } + if registry.allow_insecure_http && !ceiling.allow_insecure_http { + self.widening( + format!("{path}.allow_insecure_http"), + "plaintext registries are not permitted", + ); + } + if let Some(secret) = ®istry.credential_secret + && !ceiling.registry_credentials.contains(secret) + { + self.widening( + format!("{path}.credential_secret"), + format!("registry credential `{secret}` is not permitted"), + ); + } + } + let overrides = packages.default_finding_action == PackageAction::Allow + || packages + .finding_actions + .iter() + .any(|rule| rule.action == PackageAction::Allow); + if overrides && !ceiling.allow_finding_overrides { + self.widening( + "policy.packages.finding_actions", + "allowing packages with findings is not permitted", + ); + } + if !packages.exceptions.is_empty() && !ceiling.allow_exceptions { + self.widening( + "policy.packages.exceptions", + "package exceptions are not permitted", + ); + } + } + + fn secrets(&mut self, profile: &GovernanceProfile, configuration: &SandboxConfiguration) { + for secret in &configuration.secrets { + if profile + .credential_services + .iter() + .any(|service| service.secret.eq_ignore_ascii_case(secret)) + { + self.unsupported( + "secrets", + format!("`{secret}` is a brokered credential and can never enter the guest"), + ); + } else if !profile.ceiling.secrets.workload.contains(secret) { + self.widening( + "secrets", + format!("`{secret}` may not be delivered to the guest"), + ); + } + } + } + + fn github(&mut self, profile: &GovernanceProfile, configuration: &SandboxConfiguration) { + let ceiling = &profile.ceiling.github; + let github = &configuration.github; + for (path, requested, allowed) in [ + ( + "github.forward_auth", + github.forward_auth, + ceiling.forward_auth, + ), + ( + "github.forward_copilot_auth", + github.forward_copilot_auth, + ceiling.forward_copilot_auth, + ), + ( + "github.allow_private_repository_access", + github.allow_private_repository_access, + ceiling.allow_private_repository_access, + ), + ( + "github.ssh_key_path", + github.ssh_key_path.is_some(), + ceiling.ssh_key, + ), + ] { + if requested && !allowed { + self.widening(path, "is not permitted"); + } + } + if !github.branch_protection.enabled && ceiling.require_branch_protection { + self.widening( + "github.branch_protection.enabled", + "branch protection must stay enabled", + ); + } + let safe_outputs = &github.safe_outputs; + if safe_outputs.enabled { + if !ceiling.safe_outputs.enabled { + self.widening( + "github.safe_outputs.enabled", + "Safe Outputs is not permitted", + ); + } + if safe_outputs.mode == SafeOutputsMode::Apply && !ceiling.safe_outputs.allow_apply { + self.widening( + "github.safe_outputs.mode", + "apply mode is not permitted; use staged", + ); + } + if !ceiling.safe_outputs.repositories.is_empty() { + for repository in &safe_outputs.allowed_repositories { + if !ceiling + .safe_outputs + .repositories + .iter() + .any(|permitted| permitted.eq_ignore_ascii_case(repository)) + { + self.widening( + "github.safe_outputs.allowed_repositories", + format!("`{repository}` is not a permitted target"), + ); + } + } + } + } + } + + fn credential_services( + &mut self, + profile: &GovernanceProfile, + configuration: &SandboxConfiguration, + facts: &SessionFacts<'_>, + ) { + let services = match selected_services(profile, configuration) { + Ok(services) => services, + Err(message) => { + self.widening("credential_services", message); + return; + } + }; + for service in services { + for variable in [ + service.provider.base_url_environment(), + service.provider.api_key_environment(), + ] { + if configuration + .secrets + .iter() + .any(|secret| secret == variable) + { + self.unsupported( + "secrets", + format!( + "`{variable}` is configured by brokered service `{}` and cannot also be a workload secret", + service.id + ), + ); + } + } + } + if !configuration.credential_services.is_empty() && facts.runtime == RuntimeKind::Hyperlight + { + self.unsupported( + "credential_services", + "brokered credentials require a persistent Apple or Kata session", + ); + } + } +} + +fn normalize_all(patterns: &[String]) -> Result, String> { + patterns + .iter() + .map(|pattern| normalize_pattern(pattern).map_err(|error| format!("`{pattern}`: {error}"))) + .collect() +} + +/// Whether every name `pattern` can match is matched by some `covering` pattern. +fn pattern_covered(covering: &[String], pattern: &str) -> bool { + match pattern.strip_prefix("*.") { + None => covering + .iter() + .any(|candidate| pattern_matches(candidate, pattern)), + Some(suffix) => covering.iter().any(|candidate| { + candidate == pattern + || (candidate.starts_with("*.") && pattern_matches(candidate, suffix)) + }), + } +} + +fn parse_networks(values: &[String]) -> Result, String> { + values + .iter() + .map(|value| { + value + .parse::() + .or_else(|_| value.parse::().map(IpNet::from)) + .map(|net| net.trunc()) + .map_err(|_| format!("`{value}` is not an IP address or CIDR")) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use sendbox_config::{PolicyPreset, RuntimeProvider}; + use sendbox_policy::{DnsPolicy, PortRule}; + + use super::*; + + const PROFILE: &str = r#" +format: sendbox.governance-profile +version: 1 +id: acme +revision: 1 +not_before_unix: 0 +expires_at_unix: 30000000 +ceiling: + runtimes: [apple, kata] + workspace_roots: [/work] + resources: { max_cpus: 4 } + commands: + default_action: deny + allowlist: ["git *", "/usr/local/bin/claude"] + network: + default_action: deny + allowed_domains: ["*.github.com", "registry.npmjs.org", "api.example.com"] + allowed_networks: ["10.0.0.0/8"] + allow_dns: true + github: + forward_copilot_auth: true + secrets: + workload: [NPM_TOKEN] +denials: + domains: [pastebin.com] + commands: ["git push"] +credential_services: + - id: anthropic + provider: anthropic + secret: SENDBOX_ANTHROPIC_API_KEY +"#; + + fn profile() -> GovernanceProfile { + GovernanceProfile::parse(PROFILE.as_bytes()).expect("profile") + } + + fn configuration() -> SandboxConfiguration { + let mut configuration = SandboxConfiguration::for_project( + PathBuf::from("/work/app"), + PolicyPreset::Strict, + RuntimeProvider::Apple, + ); + configuration.github.forward_auth = false; + configuration.policy.network.allowed_domains = vec!["*.github.com".to_owned()]; + configuration.policy.commands.allowlist = vec!["git status".to_owned()]; + configuration + } + + fn facts() -> SessionFacts<'static> { + SessionFacts { + runtime: RuntimeKind::Apple, + image: Some("ghcr.io/acme/agent@sha256:00"), + workspace_root: Path::new("/work/app"), + } + } + + fn paths(violations: &[Violation]) -> Vec<&str> { + violations + .iter() + .map(|violation| violation.path.as_str()) + .collect() + } + + #[test] + fn narrowed_configuration_is_admitted() { + let violations = check(&profile(), &configuration(), &facts()); + assert!(violations.is_empty(), "{violations:?}"); + } + + #[test] + fn denials_only_narrow_and_block_brokered_provider_hosts() { + let profile = profile(); + let mut policy = configuration().policy; + let before = policy.clone(); + apply_denials(&profile, &mut policy); + apply_denials(&profile, &mut policy); + assert!( + before + .network + .blocked_domains + .iter() + .all(|domain| policy.network.blocked_domains.contains(domain)) + ); + assert!( + policy + .network + .blocked_domains + .contains(&"api.anthropic.com".to_owned()) + ); + assert!( + policy + .network + .blocked_domains + .contains(&"pastebin.com".to_owned()) + ); + assert_eq!( + policy + .commands + .denylist + .iter() + .filter(|rule| *rule == "git push") + .count(), + 1 + ); + assert_eq!( + policy.network.allowed_domains, + before.network.allowed_domains + ); + } + + #[test] + fn implicit_github_meta_delegation_is_a_widening() { + let mut configuration = configuration(); + configuration + .policy + .network + .allowed_domains + .push("github.com".to_owned()); + let violations = check(&profile(), &configuration, &facts()); + assert!( + violations + .iter() + .any(|violation| violation.message.contains("GitHub Meta")), + "{violations:?}" + ); + configuration + .policy + .network + .blocked_domains + .push("github.com".to_owned()); + let violations = check(&profile(), &configuration, &facts()); + assert!( + !violations + .iter() + .any(|violation| violation.message.contains("GitHub Meta")) + ); + } + + #[test] + fn default_allow_presets_and_uncovered_rules_are_rejected() { + let mut configuration = SandboxConfiguration::for_project( + PathBuf::from("/work/app"), + PolicyPreset::Permissive, + RuntimeProvider::Apple, + ); + configuration.github.forward_auth = false; + let violations = check(&profile(), &configuration, &facts()); + let found = paths(&violations); + assert!(found.contains(&"policy.commands.default_action")); + assert!(found.contains(&"policy.network.default_action")); + assert!(found.contains(&"policy.boundaries.tool_calls")); + + let mut configuration = self::configuration(); + configuration.policy.commands.allowlist = vec!["curl *".to_owned()]; + configuration.policy.network.allowed_domains = + vec!["*.example.com".to_owned(), "evil.com".to_owned()]; + configuration.policy.network.allowed_networks = vec!["192.168.0.0/16".to_owned()]; + configuration.policy.network.allowed_ports = vec![PortRule { + protocol: Protocol::Tcp, + port: 22, + }]; + let violations = check(&profile(), &configuration, &facts()); + assert_eq!( + violations + .iter() + .filter(|violation| violation.path == "policy.network.allowed_domains") + .count(), + 2, + "{violations:?}" + ); + let found = paths(&violations); + assert!(found.contains(&"policy.commands.allowlist")); + assert!(found.contains(&"policy.network.allowed_networks")); + } + + #[test] + fn wildcard_domains_need_a_wildcard_ceiling() { + let ceiling = vec!["*.github.com".to_owned(), "api.example.com".to_owned()]; + assert!(pattern_covered(&ceiling, "api.github.com")); + assert!(pattern_covered(&ceiling, "*.api.github.com")); + assert!(pattern_covered(&ceiling, "*.github.com")); + assert!(!pattern_covered(&ceiling, "github.com")); + assert!(!pattern_covered(&ceiling, "*.example.com")); + assert!(pattern_covered(&ceiling, "api.example.com")); + } + + #[test] + fn github_secrets_runtime_and_workspace_dimensions_are_checked() { + let mut configuration = configuration(); + configuration.github.forward_auth = true; + configuration.github.ssh_key_path = Some(PathBuf::from("/home/me/.ssh/id")); + configuration.github.branch_protection.enabled = false; + configuration.secrets = vec![ + "NPM_TOKEN".to_owned(), + "OTHER".to_owned(), + "SENDBOX_ANTHROPIC_API_KEY".to_owned(), + ]; + configuration.resources.cpus = 8; + configuration + .runtime + .as_mut() + .expect("runtime") + .kata + .executable = "/tmp/nerdctl".to_owned(); + configuration.credential_services = vec!["openai".to_owned()]; + let facts = SessionFacts { + runtime: RuntimeKind::Apple, + image: None, + workspace_root: Path::new("/elsewhere"), + }; + let violations = check(&profile(), &configuration, &facts); + let found = paths(&violations); + for expected in [ + "github.forward_auth", + "github.ssh_key_path", + "github.branch_protection.enabled", + "resources.cpus", + "runtime.kata", + "workspace_path", + "credential_services", + ] { + assert!(found.contains(&expected), "{expected}: {violations:?}"); + } + assert_eq!( + violations + .iter() + .filter(|violation| violation.path == "secrets") + .count(), + 2 + ); + assert!(violations.iter().any(|violation| { + violation.kind == ViolationKind::Unsupported + && violation.message.contains("brokered credential") + })); + + let hyperlight = SessionFacts { + runtime: RuntimeKind::Hyperlight, + ..self::facts() + }; + assert!( + check(&profile(), &self::configuration(), &hyperlight) + .iter() + .any(|violation| violation.kind == ViolationKind::Unsupported) + ); + } + + #[test] + fn dns_defaults_match_the_runtime_policy_and_limits_are_checked() { + let defaults = DnsPolicy::default(); + let ceiling = DnsCeiling::default(); + assert_eq!( + ( + ceiling.max_ttl_secs, + ceiling.max_qname_octets, + ceiling.max_labels, + ceiling.max_label_octets, + ceiling.max_response_records, + ), + ( + defaults.max_ttl_secs, + defaults.max_qname_octets, + defaults.max_labels, + defaults.max_label_octets, + defaults.max_response_records, + ) + ); + assert_eq!( + ( + ceiling.budget_window_secs, + ceiling.budget_max_queries, + ceiling.budget_max_query_octets, + ceiling.budget_max_unique_names, + ceiling.budget_max_dynamic_labels, + ), + ( + defaults.budget.window_secs, + defaults.budget.max_queries, + defaults.budget.max_query_octets, + defaults.budget.max_unique_names, + defaults.budget.max_dynamic_labels, + ) + ); + + let mut configuration = configuration(); + configuration.policy.network.dns.max_ttl_secs = 3600; + configuration.policy.network.dns.budget.window_secs = 1; + let violations = check(&profile(), &configuration, &facts()); + let found = paths(&violations); + assert!(found.contains(&"policy.network.dns.max_ttl_secs")); + assert!(found.contains(&"policy.network.dns.budget.window_secs")); + } +} diff --git a/crates/sendbox-host/src/governance/mod.rs b/crates/sendbox-host/src/governance/mod.rs new file mode 100644 index 0000000..1ed35f8 --- /dev/null +++ b/crates/sendbox-host/src/governance/mod.rs @@ -0,0 +1,715 @@ +//! Governed sessions: operator-signed profile admission, effective-policy +//! binding, and brokered credential grants. + +pub mod composition; +pub mod operator; +pub(crate) mod relay; + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use sendbox_agent::EnvironmentIntent; +use sendbox_bootstrap::CredentialRelayBootstrap; +use sendbox_config::{RuntimeProvider as ConfiguredRuntime, SandboxConfiguration}; +use sendbox_core::SessionId; +use sendbox_egress::runtime::DEFAULT_CREDENTIAL_RELAY_PORT; +use sendbox_governance::profile::{CredentialServiceProfile, RuntimeKind}; +use sendbox_governance::{ + CONTRACT_VERSION, GovernanceBinding, PrincipalId, ProjectId, ServiceId, SessionRef, + Sha256Digest, +}; +use sendbox_security::audit::{AuditCategory, AuditResult}; +use sendbox_session_security::AuditRecorder; +use serde::Serialize; + +pub use composition::{SessionFacts, Violation, ViolationKind}; +pub use operator::{ + GovernanceMode, GovernanceSource, MANAGED_CONFIGURATION_PATH, OperatorConfiguration, + SIGNATURES_FORMAT, VerifiedProfile, encode_signatures, verify_profile, +}; + +use crate::HostError; + +/// Governance state for one admitted run. +pub(crate) struct GovernedSession { + pub(crate) mode: GovernanceMode, + pub(crate) source: GovernanceSource, + pub(crate) verified: VerifiedProfile, + pub(crate) principal: PrincipalId, +} + +impl GovernedSession { + /// Discovers, loads, and verifies governance, then applies profile + /// denials to `configuration`. Returns `None` for standalone sessions. + pub(crate) fn prepare( + configuration: &mut SandboxConfiguration, + managed_path: &Path, + opt_in: Option<&Path>, + bundle: BundleSelection<'_>, + state_root: &Path, + now_unix: u64, + ) -> Result, HostError> { + let uid = crate::current_uid(); + let Some(source) = GovernanceSource::discover(managed_path, opt_in, uid)? else { + if !configuration.credential_services.is_empty() { + return Err(HostError::Governance( + "credential_services require a governed session; select a governance configuration" + .to_owned(), + )); + } + return Ok(None); + }; + let operator = source.load()?; + operator.verify_bundle( + bundle.trust_root, + source.ownership, + bundle.trust_root_id, + bundle.minimum_release_sequence, + )?; + let verified = verify_profile(&source, &operator, now_unix)?; + crate::ensure_private_directory(state_root)?; + operator::RevisionHighWater::open(state_root)? + .check(&verified.authority, &verified.reference)?; + composition::apply_denials(&verified.profile, &mut configuration.policy); + Ok(Some(Self { + mode: source.mode, + source, + verified, + principal: PrincipalId::local_user(uid), + })) + } + + /// Rejects the session unless its effective configuration stays within + /// the profile. + pub(crate) fn admit( + &self, + configuration: &SandboxConfiguration, + facts: &SessionFacts<'_>, + ) -> Result<(), HostError> { + let violations = composition::check(&self.verified.profile, configuration, facts); + if violations.is_empty() { + Ok(()) + } else { + Err(HostError::GovernanceRejected { + profile: format!( + "{} revision {}", + self.verified.reference.id, self.verified.reference.revision + ), + violations, + }) + } + } + + pub(crate) fn binding( + &self, + project: ProjectId, + effective_policy_sha256: &str, + configuration: &SandboxConfiguration, + ) -> Result { + let mut brokered_services = + composition::selected_services(&self.verified.profile, configuration) + .map_err(HostError::Governance)? + .into_iter() + .map(|service| service.id.clone()) + .collect::>(); + brokered_services.sort(); + let binding = GovernanceBinding { + contract_version: CONTRACT_VERSION, + authority: self.verified.authority.clone(), + profile: self.verified.reference.clone(), + principal: self.principal.clone(), + project, + effective_policy_sha256: Sha256Digest::parse_hex(effective_policy_sha256) + .map_err(operator::governance_error)?, + brokered_services, + }; + binding.validate().map_err(operator::governance_error)?; + Ok(binding) + } + + pub(crate) fn record_admission(&self, state_root: &Path) -> Result<(), HostError> { + operator::RevisionHighWater::open(state_root)? + .record(&self.verified.authority, &self.verified.reference) + } + + /// Profile definitions of the services this session brokers, sorted by id. + pub(crate) fn brokered_services( + &self, + configuration: &SandboxConfiguration, + ) -> Result, HostError> { + composition::selected_services(&self.verified.profile, configuration) + .map(|services| services.into_iter().cloned().collect()) + .map_err(HostError::Governance) + } + + /// Guest relay listener configuration. It names services and limits only. + pub(crate) fn relay_bootstrap( + &self, + services: &[CredentialServiceProfile], + ) -> Option { + (!services.is_empty()).then(|| CredentialRelayBootstrap { + port: DEFAULT_CREDENTIAL_RELAY_PORT, + services: services + .iter() + .map(|service| service.id.to_string()) + .collect(), + max_streams: self.verified.profile.grants.max_concurrent_streams, + max_request_bytes: services + .iter() + .map(|service| service.max_request_bytes) + .max() + .unwrap_or(1), + }) + } +} + +/// Provider-standard endpoint variables for compatible agents. The key is a +/// fixed placeholder: the host broker discards it and injects the real one. +pub(crate) fn relay_environment( + services: &[CredentialServiceProfile], + port: u16, +) -> Vec { + services + .iter() + .flat_map(|service| { + [ + EnvironmentIntent { + name: service.provider.base_url_environment().to_owned(), + value: format!( + "http://127.0.0.1:{port}/{}{}", + service.id, + service.provider.base_url_suffix() + ), + sensitive: false, + }, + EnvironmentIntent { + name: service.provider.api_key_environment().to_owned(), + value: sendbox_governance::BROKERED_CREDENTIAL_PLACEHOLDER.to_owned(), + sensitive: false, + }, + ] + }) + .collect() +} + +/// An admitted governed run: the verified profile plus the exact binding +/// signed into the boundary plan. +pub(crate) struct GovernedRun { + pub(crate) session: GovernedSession, + pub(crate) binding: GovernanceBinding, + pub(crate) binding_sha256: Sha256Digest, + pub(crate) session_ref: SessionRef, + brokered: Option<(Vec, relay::BrokeredSecrets)>, +} + +impl GovernedRun { + pub(crate) fn new( + session: GovernedSession, + binding: GovernanceBinding, + session_id: SessionId, + ) -> Result { + let binding_sha256 = binding.digest().map_err(operator::governance_error)?; + Ok(Self { + session, + binding, + binding_sha256, + session_ref: SessionRef::from_session_id(session_id), + brokered: None, + }) + } + + pub(crate) fn attach_brokered( + &mut self, + services: Vec, + secrets: relay::BrokeredSecrets, + ) { + self.brokered = Some((services, secrets)); + } + + /// Starts the host credential relay for a brokered session. + pub(crate) async fn start_relay( + &mut self, + audit: &AuditRecorder, + ) -> Result>, HostError> { + let Some((services, secrets)) = self.brokered.take() else { + return Ok(None); + }; + relay::HostCredentialRelay::start(self, &services, secrets, audit.clone()) + .await + .map(|relay| Some(std::sync::Arc::new(relay))) + } + + /// Identity metadata shared by every governance audit record. It never + /// contains credential material. + pub(crate) fn audit_metadata(&self) -> BTreeMap { + BTreeMap::from([ + ("principal".to_owned(), self.binding.principal.to_string()), + ("project".to_owned(), self.binding.project.to_string()), + ("session".to_owned(), self.session_ref.to_string()), + ("authority".to_owned(), self.binding.authority.id.clone()), + ("profile".to_owned(), self.binding.profile.id.to_string()), + ( + "profile_revision".to_owned(), + self.binding.profile.revision.to_string(), + ), + ( + "profile_sha256".to_owned(), + self.binding.profile.sha256.to_string(), + ), + ( + "effective_policy_sha256".to_owned(), + self.binding.effective_policy_sha256.to_string(), + ), + ("binding_sha256".to_owned(), self.binding_sha256.to_string()), + ]) + } + + pub(crate) fn record_admission(&self, audit: &AuditRecorder) -> Result<(), HostError> { + let mut metadata = self.audit_metadata(); + metadata.insert( + "mode".to_owned(), + match self.session.mode { + GovernanceMode::Managed => "managed", + GovernanceMode::OptIn => "opt_in", + } + .to_owned(), + ); + metadata.insert( + "trust_sha256".to_owned(), + self.binding.authority.trust_sha256.to_string(), + ); + metadata.insert( + "valid_signers".to_owned(), + self.session + .verified + .signers + .iter() + .cloned() + .collect::>() + .join(","), + ); + metadata.insert( + "brokered_services".to_owned(), + self.binding + .brokered_services + .iter() + .map(ToString::to_string) + .collect::>() + .join(","), + ); + record_audit( + audit, + AuditCategory::Policy, + "governance.admission.accepted", + &self.session_ref.to_string(), + AuditResult::Allowed, + metadata, + ) + } +} + +pub(crate) fn record_audit( + audit: &AuditRecorder, + category: AuditCategory, + action: &str, + subject: &str, + result: AuditResult, + metadata: BTreeMap, +) -> Result<(), HostError> { + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|error| HostError::Governance(format!("read audit time: {error}")))? + .as_nanos() + .try_into() + .map_err(|_| HostError::Governance("audit time is out of range".to_owned()))?; + audit + .record(timestamp, category, action, subject, result, metadata) + .map(|_| ()) + .map_err(HostError::SessionSecurity) +} + +/// CLI-selected guest bundle trust that the operator may pin. +#[derive(Debug, Clone, Copy)] +pub(crate) struct BundleSelection<'a> { + pub trust_root: &'a Path, + pub trust_root_id: &'a str, + pub minimum_release_sequence: u64, +} + +/// Project identity used for bindings and grants. +pub(crate) fn project_id( + repository: Option<&sendbox_git::RepositoryIdentity>, + workspace_root: &Path, +) -> Result { + use std::os::unix::ffi::OsStrExt; + match repository { + Some(repository) if repository.host() == "github.com" => { + ProjectId::github(repository.owner(), repository.name()) + .map_err(operator::governance_error) + } + _ => Ok(ProjectId::from_canonical_path( + workspace_root.as_os_str().as_bytes(), + )), + } +} + +/// Maps the runtime a session resolved to the profile vocabulary. +pub(crate) const fn runtime_kind(runtime: sendbox_boundary::ResolvedRuntime) -> RuntimeKind { + match runtime { + sendbox_boundary::ResolvedRuntime::Apple => RuntimeKind::Apple, + sendbox_boundary::ResolvedRuntime::Kata => RuntimeKind::Kata, + sendbox_boundary::ResolvedRuntime::Hyperlight => RuntimeKind::Hyperlight, + } +} + +/// The active, verified governance configuration for this host. +#[derive(Debug, Clone)] +pub struct ActiveGovernance { + pub source: GovernanceSource, + pub operator: OperatorConfiguration, + pub verified: VerifiedProfile, +} + +/// Loads and verifies the active governance profile, if governance applies. +pub fn verify_active( + managed_path: &Path, + opt_in: Option<&Path>, +) -> Result, HostError> { + let Some(source) = GovernanceSource::discover(managed_path, opt_in, crate::current_uid())? + else { + return Ok(None); + }; + let operator = source.load()?; + let verified = verify_profile(&source, &operator, crate::unix_time()?)?; + Ok(Some(ActiveGovernance { + source, + operator, + verified, + })) +} + +/// Inputs for `sendbox governance check`. +#[derive(Debug, Clone)] +pub struct GovernanceCheckRequest { + pub configuration: SandboxConfiguration, + pub managed_path: PathBuf, + pub governance_config: Option, + pub runtime: Option, + pub image: Option, +} + +/// Explains how a configuration composes with the active governance profile. +#[derive(Debug, Clone, Serialize)] +pub struct GovernanceCheckReport { + pub mode: Option, + pub authority: Option, + pub profile: Option, + pub profile_revision: Option, + pub profile_sha256: Option, + pub admitted: bool, + pub violations: Vec, + pub applied_denials: AppliedDenials, + pub brokered_services: Vec, +} + +#[derive(Debug, Clone, Default, Serialize)] +pub struct AppliedDenials { + pub commands: Vec, + pub domains: Vec, + pub networks: Vec, +} + +/// Evaluates a configuration against the active governance profile without +/// starting a session. +pub fn check(request: GovernanceCheckRequest) -> Result { + let mut configuration = request.configuration; + configuration + .validate() + .map_err(|error| HostError::Invalid(error.to_string()))?; + let Some(ActiveGovernance { + source, verified, .. + }) = verify_active(&request.managed_path, request.governance_config.as_deref())? + else { + return Ok(GovernanceCheckReport { + mode: None, + authority: None, + profile: None, + profile_revision: None, + profile_sha256: None, + admitted: configuration.credential_services.is_empty(), + violations: if configuration.credential_services.is_empty() { + Vec::new() + } else { + vec!["credential_services require a governed session".to_owned()] + }, + applied_denials: AppliedDenials::default(), + brokered_services: Vec::new(), + }); + }; + let before = configuration.policy.clone(); + composition::apply_denials(&verified.profile, &mut configuration.policy); + let added = |after: &[String], before: &[String]| { + after + .iter() + .filter(|entry| !before.contains(entry)) + .cloned() + .collect::>() + }; + let applied_denials = AppliedDenials { + commands: added( + &configuration.policy.commands.denylist, + &before.commands.denylist, + ), + domains: added( + &configuration.policy.network.blocked_domains, + &before.network.blocked_domains, + ), + networks: added( + &configuration.policy.network.blocked_networks, + &before.network.blocked_networks, + ), + }; + let runtime = request.runtime.unwrap_or_else(|| { + match configuration + .runtime + .as_ref() + .map_or(ConfiguredRuntime::Auto, |runtime| runtime.provider) + { + ConfiguredRuntime::Kata => RuntimeKind::Kata, + ConfiguredRuntime::Hyperlight => RuntimeKind::Hyperlight, + ConfiguredRuntime::Apple | ConfiguredRuntime::Auto => { + if cfg!(target_os = "macos") { + RuntimeKind::Apple + } else { + RuntimeKind::Kata + } + } + } + }); + let workspace_root = configuration.workspace_root().to_path_buf(); + let violations = composition::check( + &verified.profile, + &configuration, + &SessionFacts { + runtime, + image: request.image.as_deref(), + workspace_root: &workspace_root, + }, + ); + Ok(GovernanceCheckReport { + mode: Some(source.mode), + authority: Some(verified.authority.id.clone()), + profile: Some(verified.reference.id.to_string()), + profile_revision: Some(verified.reference.revision), + profile_sha256: Some(verified.reference.sha256.to_string()), + admitted: violations.is_empty(), + violations: violations.iter().map(ToString::to_string).collect(), + applied_denials, + brokered_services: configuration.credential_services.clone(), + }) +} + +#[cfg(test)] +pub(crate) mod tests { + use sendbox_config::{PolicyPreset, RuntimeProvider}; + use sendbox_governance::profile::GovernanceProfile; + + use super::operator::tests::{Fixture, fixture, private_directory, protected_test_tree}; + use super::*; + + pub(crate) fn now_unix() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("time") + .as_secs() + } + + /// A profile valid now, brokering both supported providers. + pub(crate) fn brokered_profile() -> String { + let now = now_unix(); + format!( + r#"format: sendbox.governance-profile +version: 1 +id: acme +revision: 4 +not_before_unix: {} +expires_at_unix: {} +ceiling: + runtimes: [apple, kata] + commands: + default_action: deny + allowlist: ["git *"] + network: + default_action: deny + allowed_domains: ["*.github.com"] + allow_dns: true +credential_services: + - id: openai + provider: openai + secret: SENDBOX_OPENAI_API_KEY + - id: anthropic + provider: anthropic + secret: SENDBOX_ANTHROPIC_API_KEY +"#, + now - 60, + now + 86_400 + ) + } + + pub(crate) fn configuration(services: &[&str]) -> SandboxConfiguration { + let mut configuration = SandboxConfiguration::for_project( + PathBuf::from("/work/app"), + PolicyPreset::Strict, + RuntimeProvider::Apple, + ); + configuration.github.forward_auth = false; + configuration.github.forward_copilot_auth = false; + configuration.policy.network.allowed_domains = vec!["*.github.com".to_owned()]; + configuration.policy.commands.allowlist = vec!["git status".to_owned()]; + configuration.credential_services = services.iter().map(|&s| s.to_owned()).collect(); + configuration + } + + fn bundle() -> BundleSelection<'static> { + BundleSelection { + trust_root: Path::new("/nonexistent/trust.json"), + trust_root_id: "test", + minimum_release_sequence: 0, + } + } + + pub(crate) fn prepare( + fixture: &Fixture, + configuration: &mut SandboxConfiguration, + ) -> GovernedSession { + GovernedSession::prepare( + configuration, + &fixture.directory.path().join("absent-managed.yaml"), + Some(&fixture.source.path), + bundle(), + &fixture.directory.path().join("state"), + now_unix(), + ) + .expect("prepare") + .expect("governed") + } + + pub(crate) fn admitted_run( + fixture: &Fixture, + configuration: &mut SandboxConfiguration, + ) -> GovernedRun { + let session = prepare(fixture, configuration); + let facts = SessionFacts { + runtime: RuntimeKind::Apple, + image: None, + workspace_root: Path::new("/work/app"), + }; + session.admit(configuration, &facts).expect("admit"); + let binding = session + .binding( + ProjectId::github("acme", "app").expect("project"), + &"ab".repeat(32), + configuration, + ) + .expect("binding"); + GovernedRun::new(session, binding, SessionId::from_bytes([7; 16])).expect("run") + } + + #[test] + fn standalone_sessions_cannot_request_brokered_credentials() { + let directory = private_directory(); + let managed = directory.path().join("absent.yaml"); + let state = directory.path().join("state"); + let mut standalone = configuration(&[]); + assert!( + GovernedSession::prepare(&mut standalone, &managed, None, bundle(), &state, 0) + .expect("standalone") + .is_none() + ); + let mut brokered = configuration(&["anthropic"]); + let error = GovernedSession::prepare(&mut brokered, &managed, None, bundle(), &state, 0) + .err() + .expect("brokered services without governance are rejected"); + assert!( + matches!(error, HostError::Governance(message) if message.contains("credential_services")) + ); + } + + #[test] + fn relay_environment_points_agents_at_the_loopback_relay() { + let profile = GovernanceProfile::parse(brokered_profile().as_bytes()).expect("profile"); + let environment = relay_environment(&profile.credential_services, 15_084) + .into_iter() + .map(|intent| { + assert!(!intent.sensitive); + (intent.name, intent.value) + }) + .collect::>(); + assert_eq!( + environment, + BTreeMap::from([ + ( + "ANTHROPIC_BASE_URL".to_owned(), + "http://127.0.0.1:15084/anthropic".to_owned() + ), + ( + "ANTHROPIC_API_KEY".to_owned(), + sendbox_governance::BROKERED_CREDENTIAL_PLACEHOLDER.to_owned() + ), + ( + "OPENAI_BASE_URL".to_owned(), + "http://127.0.0.1:15084/openai/v1".to_owned() + ), + ( + "OPENAI_API_KEY".to_owned(), + sendbox_governance::BROKERED_CREDENTIAL_PLACEHOLDER.to_owned() + ), + ]) + ); + } + + #[test] + fn governed_session_binds_admission_and_brokered_services() { + if !protected_test_tree() { + return; + } + let fixture = fixture(&brokered_profile(), 1); + let mut configuration = configuration(&["openai", "anthropic"]); + let run = admitted_run(&fixture, &mut configuration); + for host in ["api.anthropic.com", "api.openai.com"] { + assert!( + configuration + .policy + .network + .blocked_domains + .contains(&host.to_owned()), + "{host} must be denied to the workload" + ); + } + let ids = + |services: &[ServiceId]| services.iter().map(ToString::to_string).collect::>(); + assert_eq!(ids(&run.binding.brokered_services), ["anthropic", "openai"]); + assert_eq!(run.binding_sha256, run.binding.digest().expect("digest")); + + let services = run + .session + .brokered_services(&configuration) + .expect("services"); + let relay = run.session.relay_bootstrap(&services).expect("relay"); + assert_eq!(relay.port, DEFAULT_CREDENTIAL_RELAY_PORT); + assert_eq!(relay.services, ["anthropic", "openai"]); + assert!(run.session.relay_bootstrap(&[]).is_none()); + + let audit = AuditRecorder::new(SessionId::from_bytes([7; 16])).expect("audit"); + run.record_admission(&audit).expect("record"); + let records = audit.records().expect("records"); + let admission = &records.last().expect("admission record").event; + assert_eq!(admission.action, "governance.admission.accepted"); + assert_eq!(admission.metadata["mode"], "opt_in"); + assert_eq!(admission.metadata["brokered_services"], "anthropic,openai"); + assert_eq!( + admission.metadata["binding_sha256"], + run.binding_sha256.to_string() + ); + } +} diff --git a/crates/sendbox-host/src/governance/operator.rs b/crates/sendbox-host/src/governance/operator.rs new file mode 100644 index 0000000..507cc33 --- /dev/null +++ b/crates/sendbox-host/src/governance/operator.rs @@ -0,0 +1,814 @@ +//! Operator governance configuration, signed profile verification, and +//! rollback protection. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use sendbox_governance::{ + AuthorityRef, Clock, CurrentProfile, GovernanceError, GovernanceProfile, ProfileId, ProfileRef, + RevisionSource, Sha256Digest, canonical_digest, profile::MAX_PROFILE_BYTES, +}; +use sendbox_security::fs::{TrustedOwnership, read_trusted_file}; +use sendbox_security::provenance::{ + DetachedSignature, Identity, SubjectKind, TrustPolicy, TrustStore, +}; +use serde::{Deserialize, Serialize}; + +use crate::HostError; + +#[cfg(target_os = "macos")] +pub const MANAGED_CONFIGURATION_PATH: &str = "/Library/Application Support/SendBox/governance.yaml"; +#[cfg(not(target_os = "macos"))] +pub const MANAGED_CONFIGURATION_PATH: &str = "/etc/sendbox/governance.yaml"; + +pub const OPERATOR_FORMAT: &str = "sendbox.governance-operator"; +pub const SIGNATURES_FORMAT: &str = "sendbox.governance-signatures"; +const FORMAT_VERSION: u32 = 1; +const MAX_OPERATOR_BYTES: u64 = 256 * 1024; +const MAX_SIGNATURE_BYTES: u64 = 256 * 1024; +const MAX_TRUST_ROOT_BYTES: u64 = 64 * 1024; +const MAX_SIGNERS: usize = 32; +const MAX_REVISION_CACHE_SECONDS: u64 = 300; +const SIGNATURE_SUFFIX: &str = ".sig.json"; + +/// How governance was selected for this host. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum GovernanceMode { + /// A root-owned operator configuration exists; governance is mandatory. + Managed, + /// The user selected a configuration explicitly on an unmanaged host. + OptIn, +} + +/// Where the operator configuration comes from and who may own it. +#[derive(Debug, Clone)] +pub struct GovernanceSource { + pub mode: GovernanceMode, + pub path: PathBuf, + pub ownership: TrustedOwnership, +} + +impl GovernanceSource { + /// Selects the governance authority. A managed configuration always wins + /// and cannot be replaced by a caller-supplied path. + pub fn discover( + managed_path: &Path, + opt_in: Option<&Path>, + uid: u32, + ) -> Result, HostError> { + match std::fs::symlink_metadata(managed_path) { + Ok(_) => { + if opt_in.is_some_and(|path| path != managed_path) { + return Err(HostError::Governance(format!( + "this host is managed by {}; --governance-config cannot select a different policy authority", + managed_path.display() + ))); + } + Ok(Some(Self { + mode: GovernanceMode::Managed, + path: managed_path.to_path_buf(), + ownership: TrustedOwnership::Root, + })) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + Ok(opt_in.map(|path| Self { + mode: GovernanceMode::OptIn, + path: path.to_path_buf(), + ownership: TrustedOwnership::RootOrUser(uid), + })) + } + Err(source) => Err(HostError::Governance(format!( + "cannot determine whether {} requires governance: {source}", + managed_path.display() + ))), + } + } + + pub fn load(&self) -> Result { + let bytes = read_trusted_file(&self.path, self.ownership, MAX_OPERATOR_BYTES) + .map_err(|error| HostError::Governance(format!("operator configuration: {error}")))?; + OperatorConfiguration::parse(&bytes) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperatorConfiguration { + pub format: String, + pub version: u32, + #[serde(default = "local_authority")] + pub authority: String, + pub profile: ProfileId, + pub profile_path: PathBuf, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub signatures_path: Option, + pub minimum_revision: u64, + pub trust: OperatorTrust, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bundle: Option, + #[serde(default = "default_revision_cache_seconds")] + pub revision_cache_seconds: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperatorTrust { + pub threshold: usize, + pub signers: Vec, +} + +/// Pins the guest bundle trust root that `sendbox run` may use. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct BundlePin { + pub trust_root_sha256: Vec, + pub trust_root_ids: Vec, + pub minimum_release_sequence: u64, +} + +fn local_authority() -> String { + "local".to_owned() +} + +const fn default_revision_cache_seconds() -> u64 { + 30 +} + +#[derive(Serialize)] +struct TrustDigestInput<'a> { + threshold: usize, + signers: BTreeSet<&'a str>, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SignatureBundle { + format: String, + version: u32, + signatures: Vec, +} + +impl OperatorConfiguration { + pub fn parse(bytes: &[u8]) -> Result { + let text = std::str::from_utf8(bytes) + .map_err(|_| HostError::Governance("operator configuration is not UTF-8".to_owned()))?; + let configuration: Self = serde_yaml_ng::from_str(text) + .map_err(|error| HostError::Governance(format!("operator configuration: {error}")))?; + configuration.validate()?; + Ok(configuration) + } + + fn validate(&self) -> Result<(), HostError> { + let invalid = |message: &str| { + Err(HostError::Governance(format!( + "operator configuration: {message}" + ))) + }; + if self.format != OPERATOR_FORMAT || self.version != FORMAT_VERSION { + return invalid(&format!( + "format must be `{OPERATOR_FORMAT}` version {FORMAT_VERSION}" + )); + } + if self.authority.is_empty() + || self.authority.len() > 128 + || !self.authority.bytes().all(|byte| byte.is_ascii_graphic()) + { + return invalid("authority must be 1-128 printable ASCII bytes"); + } + if !self.profile_path.is_absolute() + || self + .signatures_path + .as_ref() + .is_some_and(|path| !path.is_absolute()) + { + return invalid("profile and signature paths must be absolute"); + } + if self.minimum_revision == 0 { + return invalid("minimum_revision must be at least 1"); + } + let fingerprints = self + .trust + .signers + .iter() + .map(|signer| signer.fingerprint.as_str()) + .collect::>(); + if self.trust.signers.is_empty() + || self.trust.signers.len() > MAX_SIGNERS + || fingerprints.len() != self.trust.signers.len() + { + return invalid(&format!( + "trust.signers must list 1-{MAX_SIGNERS} distinct identities" + )); + } + if self.trust.threshold == 0 || self.trust.threshold > self.trust.signers.len() { + return invalid("trust.threshold must be between 1 and the number of signers"); + } + if !(1..=MAX_REVISION_CACHE_SECONDS).contains(&self.revision_cache_seconds) { + return invalid(&format!( + "revision_cache_seconds must be 1..={MAX_REVISION_CACHE_SECONDS}" + )); + } + if let Some(bundle) = &self.bundle + && (bundle.trust_root_sha256.is_empty() || bundle.trust_root_ids.is_empty()) + { + return invalid("bundle pins require at least one trust root digest and id"); + } + self.trust_store()?; + Ok(()) + } + + #[must_use] + pub fn signatures_path(&self) -> PathBuf { + self.signatures_path.clone().unwrap_or_else(|| { + let mut path = self.profile_path.clone().into_os_string(); + path.push(SIGNATURE_SUFFIX); + PathBuf::from(path) + }) + } + + fn trust_store(&self) -> Result { + let mut store = TrustStore::new(TrustPolicy { + allow_unsigned: false, + threshold: self.trust.threshold, + required_signers: BTreeSet::new(), + }); + for signer in &self.trust.signers { + store.add_identity(signer.clone()).map_err(|error| { + HostError::Governance(format!("operator trust signer: {error}")) + })?; + } + Ok(store) + } + + pub fn authority(&self) -> Result { + let trust_sha256 = canonical_digest(&TrustDigestInput { + threshold: self.trust.threshold, + signers: self + .trust + .signers + .iter() + .map(|signer| signer.fingerprint.as_str()) + .collect(), + }) + .map_err(governance_error)?; + Ok(AuthorityRef { + id: self.authority.clone(), + trust_sha256, + }) + } + + /// Rejects a guest bundle trust root the operator has not pinned. + /// + /// The pinned file must meet the same ownership rule as the governance + /// configuration. In managed mode that means root-owned with protected + /// ancestors, so the caller cannot replace it after this check and before + /// the bundle is verified and launched from the same path. + pub fn verify_bundle( + &self, + trust_root: &Path, + ownership: TrustedOwnership, + trust_root_id: &str, + minimum_release_sequence: u64, + ) -> Result<(), HostError> { + let Some(pin) = &self.bundle else { + return Ok(()); + }; + let canonical = std::fs::canonicalize(trust_root).map_err(|source| HostError::Io { + context: "resolve bundle trust root", + path: trust_root.to_path_buf(), + source, + })?; + let bytes = read_trusted_file(&canonical, ownership, MAX_TRUST_ROOT_BYTES) + .map_err(|error| HostError::Governance(format!("bundle trust root: {error}")))?; + if !pin.trust_root_sha256.contains(&Sha256Digest::of(&bytes)) { + return Err(HostError::Governance( + "the guest bundle trust root is not pinned by the operator".to_owned(), + )); + } + if !pin.trust_root_ids.iter().any(|id| id == trust_root_id) { + return Err(HostError::Governance(format!( + "bundle trust root id `{trust_root_id}` is not pinned by the operator" + ))); + } + if minimum_release_sequence < pin.minimum_release_sequence { + return Err(HostError::Governance(format!( + "--minimum-release-sequence must be at least {}", + pin.minimum_release_sequence + ))); + } + Ok(()) + } +} + +/// A profile whose exact bytes were verified against the operator trust. +#[derive(Debug, Clone)] +pub struct VerifiedProfile { + pub profile: GovernanceProfile, + pub reference: ProfileRef, + pub authority: AuthorityRef, + pub minimum_revision: u64, + pub signers: BTreeSet, +} + +pub fn verify_profile( + source: &GovernanceSource, + operator: &OperatorConfiguration, + now_unix: u64, +) -> Result { + let bytes = read_trusted_file( + &operator.profile_path, + source.ownership, + MAX_PROFILE_BYTES as u64, + ) + .map_err(|error| HostError::Governance(format!("governance profile: {error}")))?; + let signatures = read_signatures(&operator.signatures_path(), source.ownership)?; + let verified = operator + .trust_store()? + .verify(&bytes, SubjectKind::Configuration, &signatures, now_unix) + .map_err(|error| { + HostError::Governance(format!( + "governance profile signature verification failed: {error}" + )) + })?; + let profile = GovernanceProfile::parse(&bytes).map_err(governance_error)?; + if profile.id != operator.profile { + return Err(HostError::Governance(format!( + "profile `{}` is not the required profile `{}`", + profile.id, operator.profile + ))); + } + if profile.revision < operator.minimum_revision { + return Err(HostError::Governance(format!( + "profile `{}` revision {} is older than the operator minimum {}", + profile.id, profile.revision, operator.minimum_revision + ))); + } + profile.check_validity(now_unix).map_err(governance_error)?; + Ok(VerifiedProfile { + reference: profile.reference(&bytes), + profile, + authority: operator.authority()?, + minimum_revision: operator.minimum_revision, + signers: verified.valid_signers, + }) +} + +fn read_signatures( + path: &Path, + ownership: TrustedOwnership, +) -> Result, HostError> { + let bytes = read_trusted_file(path, ownership, MAX_SIGNATURE_BYTES) + .map_err(|error| HostError::Governance(format!("governance signatures: {error}")))?; + let bundle: SignatureBundle = serde_json::from_slice(&bytes) + .map_err(|error| HostError::Governance(format!("governance signatures: {error}")))?; + if bundle.format != SIGNATURES_FORMAT || bundle.version != FORMAT_VERSION { + return Err(HostError::Governance(format!( + "governance signatures must use format `{SIGNATURES_FORMAT}` version {FORMAT_VERSION}" + ))); + } + bundle + .signatures + .into_iter() + .map(|value| { + let signature: DetachedSignature = serde_json::from_value(value) + .map_err(|error| HostError::Governance(format!("governance signature: {error}")))?; + let canonical = signature + .encode() + .map_err(|error| HostError::Governance(format!("governance signature: {error}")))?; + DetachedSignature::decode(&canonical) + .map_err(|error| HostError::Governance(format!("governance signature: {error}"))) + }) + .collect() +} + +/// Encodes signatures in the bundle format `verify_profile` reads. +pub fn encode_signatures(signatures: &[DetachedSignature]) -> Result, HostError> { + #[derive(Serialize)] + struct Output<'a> { + format: &'static str, + version: u32, + signatures: &'a [DetachedSignature], + } + let mut bytes = serde_json::to_vec_pretty(&Output { + format: SIGNATURES_FORMAT, + version: FORMAT_VERSION, + signatures, + }) + .map_err(|error| HostError::Governance(format!("encode signatures: {error}")))?; + bytes.push(b'\n'); + Ok(bytes) +} + +/// Highest admitted revision per authority and profile. Rejects a profile +/// rollback that is still inside its validity window. The operator minimum +/// revision is authoritative; this record adds per-host protection. +pub struct RevisionHighWater { + path: PathBuf, +} + +impl RevisionHighWater { + pub fn open(state_root: &Path) -> Result { + let directory = state_root.join("governance"); + crate::ensure_private_directory(&directory)?; + Ok(Self { + path: directory.join("revision-high-water.json"), + }) + } + + fn key(authority: &AuthorityRef, profile: &ProfileRef) -> String { + format!("{}/{}/{}", authority.id, authority.trust_sha256, profile.id) + } + + fn read(&self) -> Result, HostError> { + match std::fs::read(&self.path) { + Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| { + HostError::Governance(format!( + "revision record {} is corrupt: {error}", + self.path.display() + )) + }), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()), + Err(source) => Err(HostError::Io { + context: "read governance revision record", + path: self.path.clone(), + source, + }), + } + } + + pub fn check(&self, authority: &AuthorityRef, profile: &ProfileRef) -> Result<(), HostError> { + let recorded = self + .read()? + .get(&Self::key(authority, profile)) + .copied() + .unwrap_or(0); + if profile.revision < recorded { + return Err(HostError::Governance(format!( + "profile `{}` revision {} is older than revision {recorded} already admitted on this host", + profile.id, profile.revision + ))); + } + Ok(()) + } + + pub fn record(&self, authority: &AuthorityRef, profile: &ProfileRef) -> Result<(), HostError> { + let mut records = self.read()?; + let entry = records.entry(Self::key(authority, profile)).or_insert(0); + if profile.revision > *entry { + *entry = profile.revision; + let bytes = serde_json::to_vec_pretty(&records).map_err(|error| { + HostError::Governance(format!("encode revision record: {error}")) + })?; + crate::atomic_write(&self.path, &bytes, 0o600)?; + } + Ok(()) + } +} + +/// Re-verifies the operator configuration and profile for the local grant +/// authority, so revocation by revision or removal takes effect within the +/// configured cache interval. +pub struct OperatorRevisionSource { + source: GovernanceSource, + clock: Arc, + cache: Mutex>, +} + +impl OperatorRevisionSource { + #[must_use] + pub fn new(source: GovernanceSource, clock: Arc) -> Self { + Self { + source, + clock, + cache: Mutex::new(None), + } + } + + fn reload(&self) -> Result<(CurrentProfile, Duration), HostError> { + let operator = self.source.load()?; + let verified = verify_profile(&self.source, &operator, self.clock.now_unix())?; + Ok(( + CurrentProfile { + reference: verified.reference, + minimum_revision: verified.minimum_revision, + expires_at_unix: verified.profile.expires_at_unix, + }, + Duration::from_secs(operator.revision_cache_seconds), + )) + } +} + +impl RevisionSource for OperatorRevisionSource { + fn current(&self, _profile: &ProfileId) -> Result { + let mut cache = self + .cache + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some((valid_until, current)) = cache.as_ref() + && Instant::now() < *valid_until + { + return Ok(current.clone()); + } + *cache = None; + let (current, ttl) = self + .reload() + .map_err(|error| GovernanceError::AuthorityUnavailable(error.to_string()))?; + *cache = Some((Instant::now() + ttl, current.clone())); + Ok(current) + } +} + +pub(crate) fn governance_error(error: GovernanceError) -> HostError { + HostError::Governance(error.to_string()) +} + +#[cfg(test)] +pub(crate) mod tests { + use std::os::unix::fs::PermissionsExt; + + use sendbox_security::provenance::{SignedSubject, SigningKeyMaterial}; + + use super::*; + + pub(crate) const PROFILE: &str = r#"format: sendbox.governance-profile +version: 1 +id: acme +revision: 4 +not_before_unix: 0 +expires_at_unix: 30000000 +ceiling: + runtimes: [apple, kata] + commands: + default_action: deny + allowlist: ["git *"] + network: + default_action: deny + allowed_domains: ["*.github.com"] +credential_services: + - id: anthropic + provider: anthropic + secret: SENDBOX_ANTHROPIC_API_KEY +"#; + + pub(crate) struct Fixture { + pub directory: tempfile::TempDir, + pub key: SigningKeyMaterial, + pub source: GovernanceSource, + } + + pub(crate) fn private_directory() -> tempfile::TempDir { + let directory = tempfile::Builder::new() + .prefix(".governance-test-") + .tempdir_in(env!("CARGO_MANIFEST_DIR")) + .expect("temporary directory"); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)) + .expect("private mode"); + directory + } + + pub(crate) fn write_private(path: &Path, bytes: &[u8]) { + std::fs::write(path, bytes).expect("write"); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).expect("mode"); + } + + pub(crate) fn sign(key: &SigningKeyMaterial, bytes: &[u8]) -> Vec { + let signature = DetachedSignature::sign( + SignedSubject::from_bytes(SubjectKind::Configuration, None, bytes), + key, + 1, + None, + BTreeMap::new(), + ) + .expect("sign"); + encode_signatures(&[signature]).expect("encode") + } + + pub(crate) fn test_operator( + identity: Identity, + profile_path: PathBuf, + minimum_revision: u64, + ) -> OperatorConfiguration { + OperatorConfiguration { + format: OPERATOR_FORMAT.to_owned(), + version: FORMAT_VERSION, + authority: "local".to_owned(), + profile: ProfileId::new("acme").unwrap(), + profile_path, + signatures_path: None, + minimum_revision, + trust: OperatorTrust { + threshold: 1, + signers: vec![identity], + }, + bundle: None, + revision_cache_seconds: 1, + } + } + + pub(crate) fn fixture(profile: &str, minimum_revision: u64) -> Fixture { + let directory = private_directory(); + let key = SigningKeyMaterial::generate().expect("key"); + let identity = key.identity("Operator", None, 0, None); + let profile_path = directory.path().join("acme.yaml"); + write_private(&profile_path, profile.as_bytes()); + write_private( + &directory.path().join("acme.yaml.sig.json"), + &sign(&key, profile.as_bytes()), + ); + let operator = test_operator( + identity, + std::fs::canonicalize(directory.path()) + .unwrap() + .join("acme.yaml"), + minimum_revision, + ); + let path = std::fs::canonicalize(directory.path()) + .unwrap() + .join("governance.yaml"); + write_private( + &path, + serde_yaml_ng::to_string(&operator).unwrap().as_bytes(), + ); + let source = GovernanceSource { + mode: GovernanceMode::OptIn, + path, + ownership: TrustedOwnership::RootOrUser(crate::current_uid()), + }; + Fixture { + directory, + key, + source, + } + } + + pub(crate) fn protected_test_tree() -> bool { + use std::os::unix::fs::MetadataExt; + let uid = crate::current_uid(); + Path::new(env!("CARGO_MANIFEST_DIR")) + .ancestors() + .all(|ancestor| { + std::fs::symlink_metadata(ancestor).is_ok_and(|metadata| { + (metadata.uid() == 0 || metadata.uid() == uid) && metadata.mode() & 0o022 == 0 + }) + }) + } + + #[test] + fn managed_configuration_cannot_be_replaced_by_the_caller() { + let directory = private_directory(); + let managed = directory.path().join("managed.yaml"); + assert!( + GovernanceSource::discover(&managed, None, 501) + .unwrap() + .is_none() + ); + let opt_in = directory.path().join("mine.yaml"); + let selected = GovernanceSource::discover(&managed, Some(&opt_in), 501) + .unwrap() + .unwrap(); + assert_eq!(selected.mode, GovernanceMode::OptIn); + assert_eq!(selected.ownership, TrustedOwnership::RootOrUser(501)); + + write_private(&managed, b"x"); + let managed_source = GovernanceSource::discover(&managed, None, 501) + .unwrap() + .unwrap(); + assert_eq!(managed_source.mode, GovernanceMode::Managed); + assert_eq!(managed_source.ownership, TrustedOwnership::Root); + assert!(GovernanceSource::discover(&managed, Some(&opt_in), 501).is_err()); + if crate::current_uid() != 0 { + assert!(managed_source.load().is_err()); + } + } + + #[test] + fn signed_profiles_verify_and_tampering_or_rollback_is_rejected() { + if !protected_test_tree() { + return; + } + let fixture = fixture(PROFILE, 1); + let operator = fixture.source.load().expect("operator"); + let verified = verify_profile(&fixture.source, &operator, 100).expect("verified"); + assert_eq!(verified.reference.revision, 4); + assert_eq!(verified.signers.len(), 1); + + assert!(verify_profile(&fixture.source, &operator, 30_000_000).is_err()); + + let mut stale = operator.clone(); + stale.minimum_revision = 5; + assert!(verify_profile(&fixture.source, &stale, 100).is_err()); + + let tampered = PROFILE.replace("*.github.com", "*.example.com"); + write_private(&operator.profile_path, tampered.as_bytes()); + let error = verify_profile(&fixture.source, &operator, 100).expect_err("tampered"); + assert!(error.to_string().contains("signature"), "{error}"); + + let other = SigningKeyMaterial::generate().unwrap(); + write_private( + &operator.signatures_path(), + &sign(&other, tampered.as_bytes()), + ); + assert!(verify_profile(&fixture.source, &operator, 100).is_err()); + + write_private( + &operator.signatures_path(), + &sign(&fixture.key, tampered.as_bytes()), + ); + assert!(verify_profile(&fixture.source, &operator, 100).is_ok()); + drop(fixture.directory); + } + + #[test] + fn high_water_mark_rejects_admitted_revision_rollback() { + let directory = private_directory(); + let state = directory.path().join("state"); + let records = RevisionHighWater::open(&state).unwrap(); + let authority = AuthorityRef { + id: "local".to_owned(), + trust_sha256: Sha256Digest::of(b"trust"), + }; + let reference = |revision| ProfileRef { + id: ProfileId::new("acme").unwrap(), + revision, + sha256: Sha256Digest::of(b"profile"), + }; + records.check(&authority, &reference(3)).unwrap(); + records.record(&authority, &reference(3)).unwrap(); + records.check(&authority, &reference(3)).unwrap(); + records.check(&authority, &reference(4)).unwrap(); + assert!(records.check(&authority, &reference(2)).is_err()); + } + + #[test] + fn revision_source_reports_unavailable_authority() { + if !protected_test_tree() { + return; + } + let fixture = fixture(PROFILE, 1); + struct FixedClock; + impl Clock for FixedClock { + fn now_unix(&self) -> u64 { + 100 + } + } + let source = OperatorRevisionSource::new(fixture.source.clone(), Arc::new(FixedClock)); + let current = source + .current(&ProfileId::new("acme").unwrap()) + .expect("current"); + assert_eq!(current.reference.revision, 4); + std::fs::remove_file(&fixture.source.path).unwrap(); + *source.cache.lock().unwrap() = None; + assert!(matches!( + source.current(&ProfileId::new("acme").unwrap()), + Err(GovernanceError::AuthorityUnavailable(_)) + )); + } + + #[test] + fn bundle_pins_are_enforced() { + let directory = private_directory(); + let root = directory.path().join("root.pub"); + write_private(&root, b"public key"); + let key = SigningKeyMaterial::generate().unwrap(); + let mut operator = OperatorConfiguration::parse( + serde_yaml_ng::to_string(&test_operator( + key.identity("Operator", None, 0, None), + PathBuf::from("/governance/acme.yaml"), + 1, + )) + .unwrap() + .as_bytes(), + ) + .unwrap(); + assert_eq!( + operator.signatures_path(), + PathBuf::from("/governance/acme.yaml.sig.json") + ); + let user = TrustedOwnership::RootOrUser(crate::current_uid()); + operator.verify_bundle(&root, user, "any", 0).unwrap(); + operator.bundle = Some(BundlePin { + trust_root_sha256: vec![Sha256Digest::of(b"public key")], + trust_root_ids: vec!["release".to_owned()], + minimum_release_sequence: 5, + }); + if crate::current_uid() != 0 { + assert!( + operator + .verify_bundle(&root, TrustedOwnership::Root, "release", 5) + .is_err(), + "managed mode requires a root-owned trust root" + ); + } + if !protected_test_tree() { + return; + } + operator.verify_bundle(&root, user, "release", 5).unwrap(); + assert!(operator.verify_bundle(&root, user, "other", 5).is_err()); + assert!(operator.verify_bundle(&root, user, "release", 4).is_err()); + write_private(&root, b"different"); + assert!(operator.verify_bundle(&root, user, "release", 5).is_err()); + } +} diff --git a/crates/sendbox-host/src/governance/relay.rs b/crates/sendbox-host/src/governance/relay.rs new file mode 100644 index 0000000..ac7ff78 --- /dev/null +++ b/crates/sendbox-host/src/governance/relay.rs @@ -0,0 +1,669 @@ +//! Host wiring for brokered credential services: grants from the local +//! authority, per-request authorization, host-held secrets, and audit. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use sendbox_agent::{AgentError, BoxFuture, CredentialRelayHandler, CredentialRelayOutbound}; +use sendbox_credentials::relay::{ + RelayAuditEvent, RelayAuditSink, RelayAuthorization, RelayAuthorizer, RelayEndpoint, + RelayFuture, RelayLimits, RelayOutbound, RelayService, +}; +use sendbox_credentials::{CredentialBrokerError, PinnedHttpsTransport, SecretResolver}; +use sendbox_governance::profile::CredentialServiceProfile; +use sendbox_governance::{ + CredentialGrant, Decision, GrantAuthority, GrantId, GrantRequest, LocalAuthorityLimits, + LocalGrantAuthority, RequestContext, RevocationReason, ServiceId, SystemClock, +}; +use sendbox_protocol::Event; +use sendbox_secrets::{SecretName, SecretStore, SecretValue}; +use sendbox_security::audit::{AuditCategory, AuditResult}; +use sendbox_session_security::AuditRecorder; +use tokio::task::JoinHandle; + +use super::{GovernedRun, operator::OperatorRevisionSource, record_audit}; +use crate::HostError; + +/// Provider credentials resolved from the host secret store before the +/// session starts. They are held only in this process. +pub(crate) struct BrokeredSecrets { + values: BTreeMap, +} + +impl std::fmt::Debug for BrokeredSecrets { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("BrokeredSecrets") + .field("names", &self.values.keys().collect::>()) + .finish() + } +} + +impl BrokeredSecrets { + pub(crate) fn resolve( + services: &[CredentialServiceProfile], + store: &dyn SecretStore, + masker: &sendbox_secrets::CredentialMasker, + ) -> Result { + let mut values = BTreeMap::new(); + for service in services { + if values.contains_key(&service.secret) { + continue; + } + let name = SecretName::new(service.secret.clone())?; + let secret = store.retrieve(&name).map_err(|error| { + HostError::Governance(format!( + "brokered credential `{}` for service `{}` is unavailable in the host secret store: {error}", + service.secret, service.id + )) + })?; + masker.register(secret.value.expose_secret())?; + values.insert(service.secret.clone(), secret.value); + } + Ok(Self { values }) + } +} + +impl SecretResolver for BrokeredSecrets { + fn retrieve(&self, name: &SecretName) -> Result { + let value = self.values.get(name.as_str()).ok_or_else(|| { + CredentialBrokerError::InvalidConfiguration( + "brokered credential was not resolved for this session".to_owned(), + ) + })?; + SecretValue::new(value.expose_secret().to_vec()).map_err(CredentialBrokerError::from) + } +} + +/// Authorizes relay requests against the session's grants. Identity comes +/// from the admitted binding, never from the workload request. +struct GrantAuthorizer { + authority: Arc, + grants: BTreeMap, + context: RequestContext, +} + +impl RelayAuthorizer for GrantAuthorizer { + fn authorize<'a>( + &'a self, + service: &'a str, + method: &'a str, + path: &'a str, + ) -> RelayFuture<'a, RelayAuthorization> { + Box::pin(async move { + let (Some(grant), Ok(service)) = + (self.grants.get(service), ServiceId::new(service.to_owned())) + else { + return RelayAuthorization::Denied { + reason: "service_not_granted", + }; + }; + let context = RequestContext { + grant_id: grant.clone(), + service, + method: method.to_owned(), + path: path.to_owned(), + ..self.context.clone() + }; + match self.authority.authorize(&context).await { + Decision::Allow(allowed) => RelayAuthorization::Allowed { + grant: allowed.grant_id.to_string(), + generation: allowed.generation, + }, + Decision::Deny { reason } => RelayAuthorization::Denied { + reason: reason.code(), + }, + } + }) + } +} + +/// Writes relay evidence into the signed session audit chain. +struct RelayAudit { + audit: AuditRecorder, + metadata: BTreeMap, + failed: Arc, +} + +impl RelayAuditSink for RelayAudit { + fn record(&self, event: RelayAuditEvent) { + let mut metadata = self.metadata.clone(); + let (action, result, subject) = match event { + RelayAuditEvent::Decision { + stream, + service, + method, + path, + allowed, + reason, + grant, + generation, + } => { + metadata.extend([ + ("stream".to_owned(), stream.to_string()), + ("service".to_owned(), service.clone()), + ("method".to_owned(), method), + ("target_path".to_owned(), path), + ("reason".to_owned(), reason.to_owned()), + ]); + if let Some(grant) = grant { + metadata.insert("grant".to_owned(), grant); + } + if let Some(generation) = generation { + metadata.insert("grant_generation".to_owned(), generation.to_string()); + } + if allowed { + ("credential.request.allowed", AuditResult::Allowed, service) + } else { + ("credential.request.denied", AuditResult::Denied, service) + } + } + RelayAuditEvent::Outcome { + stream, + service, + method, + path, + outcome, + reason, + status, + request_bytes, + response_bytes, + duration_ms, + } => { + metadata.extend([ + ("stream".to_owned(), stream.to_string()), + ("service".to_owned(), service.clone()), + ("method".to_owned(), method), + ("target_path".to_owned(), path), + ("outcome".to_owned(), outcome.code().to_owned()), + ("reason".to_owned(), reason.to_owned()), + ("request_bytes".to_owned(), request_bytes.to_string()), + ("response_bytes".to_owned(), response_bytes.to_string()), + ("duration_ms".to_owned(), duration_ms.to_string()), + ]); + if let Some(status) = status { + metadata.insert("upstream_status".to_owned(), status.to_string()); + } + let result = match outcome { + sendbox_credentials::relay::RelayStreamOutcome::Complete => { + AuditResult::Success + } + sendbox_credentials::relay::RelayStreamOutcome::Denied => AuditResult::Denied, + _ => AuditResult::Error, + }; + ("credential.request.outcome", result, service) + } + }; + if let Err(error) = record_audit( + &self.audit, + AuditCategory::Secret, + action, + &subject, + result, + metadata, + ) { + self.failed.store(true, Ordering::SeqCst); + eprintln!("sendbox: recording credential relay audit failed: {error}"); + } + } +} + +struct OutboundAdapter(Arc); + +impl RelayOutbound for OutboundAdapter { + fn send(&self, event: Event) -> RelayFuture<'_, Result<(), CredentialBrokerError>> { + Box::pin(async move { + self.0 + .send(event) + .await + .map_err(|error| CredentialBrokerError::Upstream(error.to_string())) + }) + } +} + +/// The host credential relay for one governed session. +pub(crate) struct HostCredentialRelay { + endpoint: Arc, + authority: Arc, + grants: Vec, + audit: AuditRecorder, + metadata: BTreeMap, + audit_failed: Arc, + renewal: Mutex>>, + lease: Duration, + revocation_grace: Duration, + finished: AtomicBool, +} + +impl HostCredentialRelay { + pub(crate) async fn start( + run: &GovernedRun, + services: &[CredentialServiceProfile], + secrets: BrokeredSecrets, + audit: AuditRecorder, + ) -> Result { + let limits = &run.session.verified.profile.grants; + let authority: Arc = Arc::new(LocalGrantAuthority::new( + Arc::new(OperatorRevisionSource::new( + run.session.source.clone(), + Arc::new(SystemClock), + )), + Arc::new(SystemClock), + LocalAuthorityLimits { + lease_seconds: limits.lease_seconds, + max_grants: services.len(), + }, + Box::new(|| { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes).map_err(|error| { + sendbox_governance::GovernanceError::AuthorityUnavailable(error.to_string()) + })?; + Ok(bytes) + }), + )); + let metadata = run.audit_metadata(); + let mut grants = Vec::with_capacity(services.len()); + let mut grant_ids = BTreeMap::new(); + for service in services { + let grant = authority + .issue(GrantRequest { + principal: run.binding.principal.clone(), + project: run.binding.project.clone(), + session: run.session_ref.clone(), + binding: run.binding.clone(), + service: service.id.clone(), + methods: service.effective_methods(), + path_prefixes: service.effective_path_prefixes(), + max_ttl_seconds: limits.max_ttl_seconds, + }) + .await + .map_err(|error| { + HostError::Governance(format!( + "issue credential grant for `{}`: {error}", + service.id + )) + })?; + let mut grant_metadata = metadata.clone(); + grant_metadata.extend([ + ("service".to_owned(), service.id.to_string()), + ("grant".to_owned(), grant.grant_id.to_string()), + ("grant_generation".to_owned(), grant.generation.to_string()), + ( + "lease_expires_at_unix".to_owned(), + grant.lease_expires_at_unix.to_string(), + ), + ( + "max_expires_at_unix".to_owned(), + grant.max_expires_at_unix.to_string(), + ), + ( + "methods".to_owned(), + grant.methods.iter().cloned().collect::>().join(","), + ), + ("path_prefixes".to_owned(), grant.path_prefixes.join(",")), + ]); + record_audit( + &audit, + AuditCategory::Secret, + "credential.grant.issued", + service.id.as_str(), + AuditResult::Allowed, + grant_metadata, + )?; + grant_ids.insert(service.id.to_string(), grant.grant_id.clone()); + grants.push(grant); + } + let relay_services = services + .iter() + .map(RelayService::from_profile) + .collect::, _>>()?; + let audit_failed = Arc::new(AtomicBool::new(false)); + let endpoint = RelayEndpoint::new( + relay_services, + Arc::new(GrantAuthorizer { + authority: Arc::clone(&authority), + grants: grant_ids, + context: RequestContext { + grant_id: grants + .first() + .map(|grant| grant.grant_id.clone()) + .ok_or_else(|| { + HostError::Governance("no brokered service was granted".to_owned()) + })?, + principal: run.binding.principal.clone(), + project: run.binding.project.clone(), + session: run.session_ref.clone(), + binding_sha256: run.binding_sha256, + service: grants[0].service.clone(), + method: String::new(), + path: String::new(), + }, + }), + Arc::new(secrets), + Arc::new(PinnedHttpsTransport::default()), + Arc::new(RelayAudit { + audit: audit.clone(), + metadata: metadata.clone(), + failed: Arc::clone(&audit_failed), + }), + RelayLimits { + max_streams: usize::try_from(limits.max_concurrent_streams).unwrap_or(1), + ..RelayLimits::default() + }, + )?; + Ok(Self { + endpoint: Arc::new(endpoint), + authority, + grants, + audit, + metadata, + audit_failed, + renewal: Mutex::new(None), + lease: Duration::from_secs(limits.lease_seconds), + revocation_grace: Duration::from_secs(limits.revocation_grace_seconds), + finished: AtomicBool::new(false), + }) + } + + fn start_renewal(&self) { + let authority = Arc::clone(&self.authority); + let endpoint = Arc::clone(&self.endpoint); + let audit = self.audit.clone(); + let metadata = self.metadata.clone(); + let grants = self + .grants + .iter() + .map(|grant| (grant.grant_id.clone(), grant.service.to_string())) + .collect::>(); + let interval = (self.lease / 3).max(Duration::from_secs(10)); + let grace = self.revocation_grace; + let audit_failed = Arc::clone(&self.audit_failed); + let task = tokio::spawn(async move { + let mut live = grants; + while !live.is_empty() { + tokio::time::sleep(interval).await; + let mut lapsed = Vec::new(); + let mut remaining = Vec::with_capacity(live.len()); + for (grant, service) in live { + match authority.renew(&grant).await { + Ok(_) => remaining.push((grant, service)), + Err(error) => { + let mut metadata = metadata.clone(); + metadata.extend([ + ("service".to_owned(), service.clone()), + ("grant".to_owned(), grant.to_string()), + ("reason".to_owned(), error.to_string()), + ( + "in_flight_grace_seconds".to_owned(), + grace.as_secs().to_string(), + ), + ]); + if let Err(error) = record_audit( + &audit, + AuditCategory::Secret, + "credential.grant.lapsed", + &service, + AuditResult::Denied, + metadata, + ) { + audit_failed.store(true, Ordering::SeqCst); + eprintln!( + "sendbox: recording credential grant lapse failed: {error}" + ); + } + lapsed.push(service); + } + } + } + if !lapsed.is_empty() { + let services = lapsed.iter().map(String::as_str).collect::>(); + endpoint.expire_in_flight(&services, grace); + } + live = remaining; + } + }); + *self + .renewal + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(task); + } + + fn stop_renewal(&self) { + if let Some(task) = self + .renewal + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + { + task.abort(); + } + } + + /// Ends the session's grants after the workload finished and reports + /// whether audit evidence could not be recorded. + pub(crate) async fn finish(&self, reason: RevocationReason) -> Result<(), HostError> { + if self.finished.swap(true, Ordering::SeqCst) { + return Ok(()); + } + self.stop_renewal(); + self.endpoint.close(Duration::ZERO).await; + let mut failures = Vec::new(); + for grant in &self.grants { + let mut metadata = self.metadata.clone(); + metadata.extend([ + ("service".to_owned(), grant.service.to_string()), + ("grant".to_owned(), grant.grant_id.to_string()), + ("reason".to_owned(), reason.code().to_owned()), + ]); + let revoked = self.authority.revoke(&grant.grant_id, reason).await; + if let Err(error) = &revoked { + failures.push(format!("revoke grant {}: {error}", grant.grant_id)); + } + if let Err(error) = record_audit( + &self.audit, + AuditCategory::Secret, + "credential.grant.revoked", + grant.service.as_str(), + if revoked.is_ok() { + AuditResult::Success + } else { + AuditResult::Error + }, + metadata, + ) { + failures.push(error.to_string()); + } + } + if self.audit_failed.load(Ordering::SeqCst) { + failures.push("credential relay audit evidence could not be recorded".to_owned()); + } + if failures.is_empty() { + Ok(()) + } else { + Err(HostError::Governance(failures.join("; "))) + } + } +} + +impl CredentialRelayHandler for HostCredentialRelay { + fn attach(&self, outbound: Arc) { + self.endpoint.attach(Arc::new(OutboundAdapter(outbound))); + self.start_renewal(); + } + + fn handle(&self, event: Event) -> Result<(), AgentError> { + self.endpoint + .handle(event) + .map_err(|error| AgentError::Guest(error.to_string())) + } + + fn close(&self, grace: Duration) -> BoxFuture<'_, ()> { + Box::pin(async move { + self.stop_renewal(); + self.endpoint.close(grace).await; + }) + } +} + +#[cfg(test)] +mod tests { + use sendbox_core::SessionId; + use sendbox_secrets::{ + CredentialMasker, RecordVersion, Secret, SecretMetadata, SecretStoreError, + }; + + use super::super::operator::tests::{fixture, protected_test_tree}; + use super::super::tests::{admitted_run, brokered_profile, configuration}; + use super::*; + + struct FakeStore(BTreeMap<&'static str, &'static str>); + + impl FakeStore { + fn unsupported() -> Result { + Err(SecretStoreError::AccessDenied) + } + } + + impl SecretStore for FakeStore { + fn store( + &self, + _: &SecretName, + _: SecretValue, + ) -> Result { + Self::unsupported() + } + fn update( + &self, + _: &SecretName, + _: SecretValue, + ) -> Result { + Self::unsupported() + } + fn retrieve(&self, name: &SecretName) -> Result { + let value = self + .0 + .get(name.as_str()) + .ok_or_else(|| SecretStoreError::NotFound(name.clone()))?; + Ok(Secret { + metadata: SecretMetadata { + name: name.clone(), + created_at_unix_ms: 0, + updated_at_unix_ms: 0, + version: RecordVersion::V1, + }, + value: SecretValue::try_from(*value)?, + }) + } + fn delete(&self, _: &SecretName) -> Result<(), SecretStoreError> { + Self::unsupported() + } + fn list(&self) -> Result, SecretStoreError> { + Self::unsupported() + } + fn exists(&self, name: &SecretName) -> Result { + Ok(self.0.contains_key(name.as_str())) + } + fn migrate(&self, _: &SecretName) -> Result { + Self::unsupported() + } + } + + const ANTHROPIC_KEY: &str = "sk-ant-test-0123456789"; + const OPENAI_KEY: &str = "sk-openai-test-0123456789"; + + fn store() -> FakeStore { + FakeStore(BTreeMap::from([ + ("SENDBOX_ANTHROPIC_API_KEY", ANTHROPIC_KEY), + ("SENDBOX_OPENAI_API_KEY", OPENAI_KEY), + ])) + } + + fn services() -> Vec { + sendbox_governance::profile::GovernanceProfile::parse(brokered_profile().as_bytes()) + .expect("profile") + .credential_services + } + + #[test] + fn brokered_secrets_are_masked_and_missing_secrets_fail_closed() { + let masker = CredentialMasker::default(); + let secrets = BrokeredSecrets::resolve(&services(), &store(), &masker).expect("resolve"); + assert!(!format!("{secrets:?}").contains(ANTHROPIC_KEY)); + let masked = masker + .mask_complete(format!("leak {OPENAI_KEY}").as_bytes()) + .expect("mask"); + assert!(!String::from_utf8_lossy(&masked).contains(OPENAI_KEY)); + let resolved = SecretResolver::retrieve( + &secrets, + &SecretName::new("SENDBOX_ANTHROPIC_API_KEY".to_owned()).expect("name"), + ) + .expect("resolved"); + assert_eq!(resolved.expose_secret(), ANTHROPIC_KEY.as_bytes()); + assert!( + SecretResolver::retrieve( + &secrets, + &SecretName::new("SENDBOX_OTHER".to_owned()).expect("name") + ) + .is_err() + ); + + let partial = FakeStore(BTreeMap::from([("SENDBOX_OPENAI_API_KEY", OPENAI_KEY)])); + let error = + BrokeredSecrets::resolve(&services(), &partial, &masker).expect_err("missing secret"); + assert!(error.to_string().contains("SENDBOX_ANTHROPIC_API_KEY")); + } + + #[tokio::test] + async fn relay_issues_and_revokes_audited_grants_without_secret_material() { + if !protected_test_tree() { + return; + } + let fixture = fixture(&brokered_profile(), 1); + let mut configuration = configuration(&["anthropic", "openai"]); + let run = admitted_run(&fixture, &mut configuration); + let services = run + .session + .brokered_services(&configuration) + .expect("services"); + let secrets = BrokeredSecrets::resolve(&services, &store(), &CredentialMasker::default()) + .expect("secrets"); + let audit = AuditRecorder::new(SessionId::from_bytes([7; 16])).expect("audit"); + let relay = HostCredentialRelay::start(&run, &services, secrets, audit.clone()) + .await + .expect("relay"); + relay + .finish(RevocationReason::SessionCompleted) + .await + .expect("finish"); + relay + .finish(RevocationReason::SessionFailed) + .await + .expect("finish is idempotent"); + + let records = audit.records().expect("records"); + let actions = records + .iter() + .map(|record| (record.event.action.as_str(), record.event.result)) + .collect::>(); + assert_eq!( + actions, + [ + ("credential.grant.issued", AuditResult::Allowed), + ("credential.grant.issued", AuditResult::Allowed), + ("credential.grant.revoked", AuditResult::Success), + ("credential.grant.revoked", AuditResult::Success), + ] + ); + for record in &records { + assert_eq!( + record.event.metadata["binding_sha256"], + run.binding_sha256.to_string() + ); + let serialized = serde_json::to_string(&record.event).expect("json"); + assert!(!serialized.contains(ANTHROPIC_KEY) && !serialized.contains(OPENAI_KEY)); + } + assert_eq!(records[2].event.metadata["reason"], "session_completed"); + } +} diff --git a/crates/sendbox-host/src/lib.rs b/crates/sendbox-host/src/lib.rs index 48fb738..13b3901 100644 --- a/crates/sendbox-host/src/lib.rs +++ b/crates/sendbox-host/src/lib.rs @@ -1,6 +1,7 @@ #![forbid(unsafe_code)] mod github_meta; +pub mod governance; mod masking; mod safe_outputs; mod security; @@ -123,6 +124,11 @@ pub struct HostRunRequest { pub readiness_timeout: Duration, /// Requests a pseudoterminal for the workload with this initial geometry. pub terminal: Option, + /// Root-owned operator governance configuration. When it exists, every + /// session is governed and `governance_config` cannot override it. + pub managed_governance_path: PathBuf, + /// Opt-in governance configuration for an unmanaged host. + pub governance_config: Option, } #[derive(Debug)] @@ -363,6 +369,24 @@ pub enum HostError { Bundle(String), #[error("GitHub Meta: {0}")] GitHubMeta(#[from] sendbox_egress::github_meta::GitHubMetaError), + #[error("governance: {0}")] + Governance(String), + #[error( + "governance profile {profile} does not permit this session:\n{}", + render_violations(.violations) + )] + GovernanceRejected { + profile: String, + violations: Vec, + }, +} + +fn render_violations(violations: &[governance::Violation]) -> String { + violations + .iter() + .map(|violation| format!(" - {violation}")) + .collect::>() + .join("\n") } impl HostError { @@ -398,6 +422,7 @@ pub struct PreparedHostRun { safe_outputs: Option, signed_plan_path: PathBuf, terminal_source: Option>, + governance: Option, } struct RuntimeInputs { @@ -407,6 +432,7 @@ struct RuntimeInputs { output: Arc, signals: Arc, terminal_source: Option>, + governance: Option, } struct EffectiveCredentialSet { @@ -474,6 +500,7 @@ impl PreparedHostRun { safe_outputs, signed_plan_path: _, terminal_source, + governance, } = self; let masker = secrets.masker.clone(); let masked_output = Arc::new(masking::MaskingOutputSink::new(masker.clone(), output)); @@ -484,6 +511,7 @@ impl PreparedHostRun { output: masked_output.clone(), signals, terminal_source, + governance, }; let runtime_masker = masker.clone(); let result = security::execute( @@ -517,6 +545,24 @@ pub async fn prepare(mut request: HostRunRequest) -> Result Result Result policy.with_credential_relay(relay.port), + None => policy, + }); let github_meta = github_meta::session_seed(egress_policy.as_ref(), &state_root).await?; let git_guard_policy = make_git_guard_policy( selected_runtime, @@ -597,8 +665,14 @@ pub async fn prepare(mut request: HostRunRequest) -> Result Result Result Result Result Result Result { @@ -878,6 +983,7 @@ pub async fn prepare(mut request: HostRunRequest) -> Result sendbox_governance::RevocationReason::SessionCompleted, + Err(failure) + if matches!(failure.primary, sendbox_agent::AgentError::Cancelled) => + { + sendbox_governance::RevocationReason::SessionCancelled + } + Err(_) => sendbox_governance::RevocationReason::SessionFailed, + }; + let finished = relay.finish(reason).await; + if let (Ok(_), Err(error)) = (&agent, finished) { + return Err(error); + } + } + let agent = agent.map_err(HostError::AgentRun)?; drop(orchestrator); drop(secrets); match (safe_outputs.as_ref(), agent.safe_outputs.as_ref()) { @@ -986,6 +1114,7 @@ fn build_runtime( github_meta: Option<&GitHubMetaSeed>, gateway_credentials: &[GatewayCredential], registry_proxy: Option<&PreparedRegistryProxy>, + credential_relay: Option<&sendbox_bootstrap::CredentialRelayBootstrap>, ) -> Result { let manifest_path = bundle_root.join("manifest.json"); let mut artifacts = vec![ @@ -1028,6 +1157,7 @@ fn build_runtime( configuration.gateway_credentials = gateway_credentials.to_vec(); configuration.registry_proxy = registry_proxy.map(|prepared| prepared.bootstrap.clone()); + configuration.credential_relay = credential_relay.cloned(); configuration.workload_uid = workload_uid; configuration.workload_gid = workload_gid; configuration.launch.resources.cpus = @@ -1096,6 +1226,7 @@ fn build_runtime( github_meta: github_meta.cloned(), gateway_credentials: gateway_credentials.to_vec(), registry_proxy: registry_proxy.map(|prepared| prepared.bootstrap.clone()), + credential_relay: credential_relay.cloned(), workload_uid, workload_gid, }; diff --git a/crates/sendbox-host/src/security.rs b/crates/sendbox-host/src/security.rs index 350a942..25efcc3 100644 --- a/crates/sendbox-host/src/security.rs +++ b/crates/sendbox-host/src/security.rs @@ -1275,6 +1275,8 @@ impl HostError { Self::Io { .. } => "io", Self::Bundle(_) => "bundle", Self::GitHubMeta(_) => "github_meta", + Self::Governance(_) => "governance", + Self::GovernanceRejected { .. } => "governance_rejected", } } } @@ -1526,6 +1528,7 @@ mod tests { memory_bytes: 512 * 1024 * 1024, }, features: BTreeMap::new(), + governance: None, }; let signed = SignedBoundaryPlan::sign(plan, &key, now_unix).expect("sign plan"); let verified = signed diff --git a/crates/sendbox-protocol/src/codec.rs b/crates/sendbox-protocol/src/codec.rs index 38da787..1512986 100644 --- a/crates/sendbox-protocol/src/codec.rs +++ b/crates/sendbox-protocol/src/codec.rs @@ -353,6 +353,12 @@ fn decode_event_kind(decoder: &mut Decoder<'_>) -> Result Ok(EventKind::StandardInputEof), 8 => Ok(EventKind::TerminalResize), 9 => Ok(EventKind::TerminalInputCredit), + 10 => Ok(EventKind::CredentialRelayRequest), + 11 => Ok(EventKind::CredentialRelayRequestBody), + 12 => Ok(EventKind::CredentialRelayResponseHead), + 13 => Ok(EventKind::CredentialRelayResponseBody), + 14 => Ok(EventKind::CredentialRelayEnd), + 15 => Ok(EventKind::CredentialRelayCredit), value => Err(ProtocolError::MalformedEncoding(format!( "unsupported event kind {value}" ))), @@ -534,6 +540,12 @@ mod tests { (EventKind::StandardInputEof, 7), (EventKind::TerminalResize, 8), (EventKind::TerminalInputCredit, 9), + (EventKind::CredentialRelayRequest, 10), + (EventKind::CredentialRelayRequestBody, 11), + (EventKind::CredentialRelayResponseHead, 12), + (EventKind::CredentialRelayResponseBody, 13), + (EventKind::CredentialRelayEnd, 14), + (EventKind::CredentialRelayCredit, 15), ] { let encoded = [value]; let mut decoder = Decoder::new(&encoded); @@ -543,8 +555,8 @@ mod tests { #[test] fn unknown_event_kinds_are_still_rejected() { - let mut decoder = Decoder::new(&[10]); - let error = decode_event_kind(&mut decoder).expect_err("kind 10 is unassigned"); + let mut decoder = Decoder::new(&[16]); + let error = decode_event_kind(&mut decoder).expect_err("kind 16 is unassigned"); assert!(matches!(error, ProtocolError::MalformedEncoding(_))); } diff --git a/crates/sendbox-protocol/src/lib.rs b/crates/sendbox-protocol/src/lib.rs index b5ee493..343710b 100644 --- a/crates/sendbox-protocol/src/lib.rs +++ b/crates/sendbox-protocol/src/lib.rs @@ -7,6 +7,7 @@ mod frame; mod handshake; mod limits; mod operations; +pub mod relay; mod types; pub use codec::{decode_message, encode_message}; diff --git a/crates/sendbox-protocol/src/relay.rs b/crates/sendbox-protocol/src/relay.rs new file mode 100644 index 0000000..b52a35e --- /dev/null +++ b/crates/sendbox-protocol/src/relay.rs @@ -0,0 +1,322 @@ +//! Wire payloads for the brokered credential relay. +//! +//! A relay stream carries one HTTP request from the guest to the host broker +//! and one streamed response back. Stream identifiers are chosen by the guest, +//! start at [`CREDENTIAL_RELAY_STREAM_BASE`] so they never collide with request +//! identifiers, and increase strictly. Response body chunks are flow +//! controlled: the host may only send a chunk for which the guest granted +//! credit, and the guest grants at most [`CREDENTIAL_RELAY_WINDOW_CHUNKS`] +//! outstanding chunks per stream. + +use serde::{Deserialize, Serialize}; + +pub const CREDENTIAL_RELAY_SCHEMA_VERSION: u32 = 1; +pub const CREDENTIAL_RELAY_STREAM_BASE: u64 = 1 << 32; +pub const CREDENTIAL_RELAY_CHUNK_BYTES: usize = 32 * 1024; +pub const CREDENTIAL_RELAY_WINDOW_CHUNKS: u16 = 16; +pub const MAX_CREDENTIAL_RELAY_HEADERS: usize = 64; +pub const MAX_CREDENTIAL_RELAY_HEADER_BYTES: usize = 16 * 1024; +pub const MAX_CREDENTIAL_RELAY_PATH_BYTES: usize = 4096; +const MAX_REASON_BYTES: usize = 64; +const MAX_SERVICE_BYTES: usize = 32; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CredentialRelayError { + #[error("unsupported credential relay schema version")] + UnsupportedSchema, + #[error("credential relay service identifier is invalid")] + InvalidService, + #[error("credential relay method is invalid")] + InvalidMethod, + #[error("credential relay path must be an origin-form path")] + InvalidPath, + #[error("credential relay headers exceed the configured limits or are malformed")] + InvalidHeaders, + #[error("credential relay status code is invalid")] + InvalidStatus, + #[error("credential relay credit must be within the stream window")] + InvalidCredit, + #[error("credential relay reason is invalid")] + InvalidReason, +} + +/// One HTTP header carried across the relay. Values are bytes-safe strings +/// that already passed HTTP header validation at the sender. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialRelayHeaderV1 { + pub name: String, + pub value: String, +} + +impl std::fmt::Debug for CredentialRelayHeaderV1 { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("CredentialRelayHeaderV1") + .field("name", &self.name) + .field("value", &format_args!("<{} bytes>", self.value.len())) + .finish() + } +} + +/// Guest to host: opens a relay stream for one request. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialRelayRequestV1 { + pub schema_version: u32, + pub service: String, + pub method: String, + /// Upstream origin-form target: absolute path plus optional query. + pub path: String, + pub headers: Vec, + pub body_bytes: u64, +} + +/// Host to guest: the upstream response status and forwarded headers. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialRelayResponseHeadV1 { + pub schema_version: u32, + pub status: u16, + pub headers: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CredentialRelayOutcomeV1 { + /// The upstream response completed. + Complete, + /// Authorization denied the request before any upstream contact. + Denied, + /// The request failed. If a response head was already sent the upstream + /// may have processed the request. + Failed, + /// The stream was aborted by the peer or by session teardown. + Aborted, +} + +/// Either direction: terminates a relay stream. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialRelayEndV1 { + pub schema_version: u32, + pub outcome: CredentialRelayOutcomeV1, + /// Stable machine-readable reason code; never contains request data. + pub reason: String, +} + +/// Guest to host: permits more response body chunks for one stream. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CredentialRelayCreditV1 { + pub schema_version: u32, + pub credits: u16, +} + +#[must_use] +pub const fn valid_credential_relay_stream(stream_id: u64) -> bool { + stream_id >= CREDENTIAL_RELAY_STREAM_BASE +} + +fn validate_schema(version: u32) -> Result<(), CredentialRelayError> { + if version == CREDENTIAL_RELAY_SCHEMA_VERSION { + Ok(()) + } else { + Err(CredentialRelayError::UnsupportedSchema) + } +} + +fn validate_headers(headers: &[CredentialRelayHeaderV1]) -> Result<(), CredentialRelayError> { + let bytes = headers.iter().fold(0_usize, |total, header| { + total + .saturating_add(header.name.len()) + .saturating_add(header.value.len()) + .saturating_add(4) + }); + let malformed = headers.iter().any(|header| { + header.name.is_empty() + || !header + .name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte)) + || header + .value + .bytes() + .any(|byte| byte == b'\r' || byte == b'\n' || byte == 0) + }); + if headers.len() > MAX_CREDENTIAL_RELAY_HEADERS + || bytes > MAX_CREDENTIAL_RELAY_HEADER_BYTES + || malformed + { + Err(CredentialRelayError::InvalidHeaders) + } else { + Ok(()) + } +} + +impl CredentialRelayRequestV1 { + pub fn validate(&self) -> Result<(), CredentialRelayError> { + validate_schema(self.schema_version)?; + let service = self.service.as_bytes(); + if service.is_empty() + || service.len() > MAX_SERVICE_BYTES + || !service[0].is_ascii_lowercase() + || !service + .iter() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-') + { + return Err(CredentialRelayError::InvalidService); + } + if self.method.is_empty() + || self.method.len() > 16 + || !self.method.bytes().all(|byte| byte.is_ascii_uppercase()) + { + return Err(CredentialRelayError::InvalidMethod); + } + if !self.path.starts_with('/') + || self.path.starts_with("//") + || self.path.len() > MAX_CREDENTIAL_RELAY_PATH_BYTES + || !self + .path + .bytes() + .all(|byte| byte.is_ascii_graphic() && byte != b'#') + { + return Err(CredentialRelayError::InvalidPath); + } + validate_headers(&self.headers) + } +} + +impl CredentialRelayResponseHeadV1 { + pub fn validate(&self) -> Result<(), CredentialRelayError> { + validate_schema(self.schema_version)?; + if !(100..=599).contains(&self.status) { + return Err(CredentialRelayError::InvalidStatus); + } + validate_headers(&self.headers) + } +} + +impl CredentialRelayEndV1 { + pub fn new(outcome: CredentialRelayOutcomeV1, reason: &str) -> Self { + Self { + schema_version: CREDENTIAL_RELAY_SCHEMA_VERSION, + outcome, + reason: reason.to_owned(), + } + } + + pub fn validate(&self) -> Result<(), CredentialRelayError> { + validate_schema(self.schema_version)?; + if self.reason.is_empty() + || self.reason.len() > MAX_REASON_BYTES + || !self + .reason + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_') + { + return Err(CredentialRelayError::InvalidReason); + } + Ok(()) + } +} + +impl CredentialRelayCreditV1 { + pub fn new(credits: u16) -> Result { + let credit = Self { + schema_version: CREDENTIAL_RELAY_SCHEMA_VERSION, + credits, + }; + credit.validate()?; + Ok(credit) + } + + pub fn validate(self) -> Result<(), CredentialRelayError> { + validate_schema(self.schema_version)?; + if self.credits == 0 || self.credits > CREDENTIAL_RELAY_WINDOW_CHUNKS { + return Err(CredentialRelayError::InvalidCredit); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request() -> CredentialRelayRequestV1 { + CredentialRelayRequestV1 { + schema_version: CREDENTIAL_RELAY_SCHEMA_VERSION, + service: "anthropic".to_owned(), + method: "POST".to_owned(), + path: "/v1/messages?beta=true".to_owned(), + headers: vec![CredentialRelayHeaderV1 { + name: "content-type".to_owned(), + value: "application/json".to_owned(), + }], + body_bytes: 12, + } + } + + #[test] + fn relay_requests_are_bounded_and_origin_form() { + assert!(request().validate().is_ok()); + for mutate in [ + (|request: &mut CredentialRelayRequestV1| request.schema_version = 2) + as fn(&mut CredentialRelayRequestV1), + |request| request.service = "Anthropic".to_owned(), + |request| request.method = "post".to_owned(), + |request| request.path = "https://evil.example/v1".to_owned(), + |request| request.path = "//evil.example/v1".to_owned(), + |request| request.path = "/v1/messages#x".to_owned(), + |request| request.headers[0].value = "a\r\nx-api-key: leak".to_owned(), + |request| request.headers[0].name = "bad header".to_owned(), + |request| { + request.headers = (0..=MAX_CREDENTIAL_RELAY_HEADERS) + .map(|index| CredentialRelayHeaderV1 { + name: format!("x-{index}"), + value: String::new(), + }) + .collect(); + }, + ] { + let mut candidate = request(); + mutate(&mut candidate); + assert!(candidate.validate().is_err(), "{candidate:?}"); + } + } + + #[test] + fn credit_end_and_head_payloads_are_validated() { + assert!(CredentialRelayCreditV1::new(CREDENTIAL_RELAY_WINDOW_CHUNKS).is_ok()); + assert!(CredentialRelayCreditV1::new(0).is_err()); + assert!(CredentialRelayCreditV1::new(CREDENTIAL_RELAY_WINDOW_CHUNKS + 1).is_err()); + assert!( + CredentialRelayEndV1::new(CredentialRelayOutcomeV1::Denied, "stale_policy") + .validate() + .is_ok() + ); + assert!( + CredentialRelayEndV1::new(CredentialRelayOutcomeV1::Failed, "Bearer abc") + .validate() + .is_err() + ); + let head = CredentialRelayResponseHeadV1 { + schema_version: CREDENTIAL_RELAY_SCHEMA_VERSION, + status: 99, + headers: Vec::new(), + }; + assert!(head.validate().is_err()); + assert!(!valid_credential_relay_stream(7)); + assert!(valid_credential_relay_stream(CREDENTIAL_RELAY_STREAM_BASE)); + } + + #[test] + fn header_debug_redacts_values() { + let header = CredentialRelayHeaderV1 { + name: "authorization".to_owned(), + value: "Bearer secret".to_owned(), + }; + assert!(!format!("{header:?}").contains("secret")); + } +} diff --git a/crates/sendbox-protocol/src/types.rs b/crates/sendbox-protocol/src/types.rs index e73e4d5..c02347f 100644 --- a/crates/sendbox-protocol/src/types.rs +++ b/crates/sendbox-protocol/src/types.rs @@ -218,6 +218,20 @@ pub enum EventKind { TerminalResize = 8, /// Carries an encoded `TerminalInputCreditV1` after a V2 interactive launch. TerminalInputCredit = 9, + /// Guest to host: an encoded `CredentialRelayRequestV1` opening one + /// brokered credential stream. + CredentialRelayRequest = 10, + /// Guest to host: request body bytes for an open relay stream. + CredentialRelayRequestBody = 11, + /// Host to guest: an encoded `CredentialRelayResponseHeadV1`. + CredentialRelayResponseHead = 12, + /// Host to guest: response body bytes for a relay stream. + CredentialRelayResponseBody = 13, + /// Either direction: an encoded `CredentialRelayEndV1` closing a stream. + CredentialRelayEnd = 14, + /// Guest to host: an encoded `CredentialRelayCreditV1` permitting more + /// response body chunks. + CredentialRelayCredit = 15, } impl EventKind { @@ -233,6 +247,20 @@ impl EventKind { Self::StandardInput | Self::StandardInputEof | Self::TerminalResize ) } + + /// Reports whether the kind belongs to the brokered credential relay. + #[must_use] + pub const fn is_credential_relay(self) -> bool { + matches!( + self, + Self::CredentialRelayRequest + | Self::CredentialRelayRequestBody + | Self::CredentialRelayResponseHead + | Self::CredentialRelayResponseBody + | Self::CredentialRelayEnd + | Self::CredentialRelayCredit + ) + } } #[derive(Clone, PartialEq, Eq)] diff --git a/crates/sendbox-runtime-apple/src/provider.rs b/crates/sendbox-runtime-apple/src/provider.rs index bea2010..7b0f282 100644 --- a/crates/sendbox-runtime-apple/src/provider.rs +++ b/crates/sendbox-runtime-apple/src/provider.rs @@ -9,8 +9,9 @@ use std::{ }; use sendbox_bootstrap::{ - BootstrapDocumentConfiguration, ExecutionBrokerConfiguration, GatewayCredential, - REQUIRED_RUNTIME_CONTROLS, RegistryProxyConfiguration, encode_bootstrap_document, + BootstrapDocumentConfiguration, CredentialRelayBootstrap, ExecutionBrokerConfiguration, + GatewayCredential, REQUIRED_RUNTIME_CONTROLS, RegistryProxyConfiguration, + encode_bootstrap_document, }; use sendbox_bundle::{Architecture, VerifyOptions, verify_bundle}; use sendbox_egress::github_meta::GitHubMetaSeed; @@ -70,6 +71,7 @@ pub struct AppleRuntimeConfiguration { pub github_meta: Option, pub gateway_credentials: Vec, pub registry_proxy: Option, + pub credential_relay: Option, pub workload_uid: u32, pub workload_gid: u32, pub launch: AppleLaunchConfiguration, @@ -112,6 +114,7 @@ impl AppleRuntimeConfiguration { github_meta: None, gateway_credentials: Vec::new(), registry_proxy: None, + credential_relay: None, workload_uid: 65_534, workload_gid: 65_534, launch: AppleLaunchConfiguration::default(), @@ -625,6 +628,7 @@ impl AppleRuntime { github_meta: self.configuration.github_meta.clone(), gateway_credentials: self.configuration.gateway_credentials.clone(), registry_proxy: self.configuration.registry_proxy.clone(), + credential_relay: self.configuration.credential_relay.clone(), }, channel.bootstrap_material.as_bytes(), ) diff --git a/crates/sendbox-runtime-kata/src/lib.rs b/crates/sendbox-runtime-kata/src/lib.rs index 8b010dd..4d06e35 100644 --- a/crates/sendbox-runtime-kata/src/lib.rs +++ b/crates/sendbox-runtime-kata/src/lib.rs @@ -12,9 +12,9 @@ use std::task::{Context, Poll}; use std::time::Duration; use sendbox_bootstrap::{ - BootstrapDocumentConfiguration, ExecutionBrokerConfiguration, GatewayCredential, - REQUIRED_RUNTIME_CONTROLS, RegistryProxyConfiguration, encode_bootstrap_document, - encode_injection_envelope, + BootstrapDocumentConfiguration, CredentialRelayBootstrap, ExecutionBrokerConfiguration, + GatewayCredential, REQUIRED_RUNTIME_CONTROLS, RegistryProxyConfiguration, + encode_bootstrap_document, encode_injection_envelope, }; use sendbox_bundle::{Architecture, VerifyOptions, verify_bundle}; use sendbox_egress::github_meta::GitHubMetaSeed; @@ -70,6 +70,7 @@ pub struct KataProviderConfiguration { pub github_meta: Option, pub gateway_credentials: Vec, pub registry_proxy: Option, + pub credential_relay: Option, pub workload_uid: u32, pub workload_gid: u32, } @@ -1039,6 +1040,7 @@ fn bootstrap_payload( github_meta: configuration.github_meta.clone(), gateway_credentials: configuration.gateway_credentials.clone(), registry_proxy: configuration.registry_proxy.clone(), + credential_relay: configuration.credential_relay.clone(), }, secret, ) @@ -1402,6 +1404,7 @@ mod tests { github_meta: None, gateway_credentials: Vec::new(), registry_proxy: None, + credential_relay: None, workload_uid: 65_534, workload_gid: 65_534, } diff --git a/crates/sendbox-security/src/fs.rs b/crates/sendbox-security/src/fs.rs index 56acb66..842c2b4 100644 --- a/crates/sendbox-security/src/fs.rs +++ b/crates/sendbox-security/src/fs.rs @@ -708,6 +708,119 @@ mod platform { #[cfg(unix)] pub use platform::SecureRoot; +/// Who may own a trusted configuration file and every directory above it. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TrustedOwnership { + /// The file and every ancestor are root-owned. Use for operator-managed + /// configuration that an unprivileged user must not be able to change. + Root, + /// The file and every ancestor are owned by root or the given user. Use for + /// configuration a user opts into for their own sessions. + RootOrUser(u32), +} + +impl TrustedOwnership { + const fn permits(self, owner: u32) -> bool { + match self { + Self::Root => owner == 0, + Self::RootOrUser(user) => owner == 0 || owner == user, + } + } +} + +/// Reads a bounded regular file whose path cannot be changed by anyone other +/// than the permitted owners. +/// +/// The file must be a single-link regular file. The file and every ancestor +/// of its canonical location must be owned according to `ownership` and must +/// not be writable by group or other users. The file is opened without +/// following symlinks and its identity is rechecked after opening. +#[cfg(unix)] +pub fn read_trusted_file( + path: &Path, + ownership: TrustedOwnership, + max_bytes: u64, +) -> SecurityResult> { + use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; + + let invalid = |detail: String| SecurityError::Policy(format!("{}: {detail}", path.display())); + if !path.is_absolute() { + return Err(invalid( + "trusted configuration paths must be absolute".to_owned(), + )); + } + let name = path + .file_name() + .ok_or_else(|| invalid("path has no file name".to_owned()))?; + let parent = path + .parent() + .ok_or_else(|| invalid("path has no parent directory".to_owned()))?; + let parent = std::fs::canonicalize(parent) + .map_err(|source| io_error("canonicalize trusted directory", parent, source))?; + for ancestor in parent.ancestors() { + let metadata = std::fs::symlink_metadata(ancestor) + .map_err(|source| io_error("inspect trusted directory", ancestor, source))?; + if !metadata.is_dir() || !ownership.permits(metadata.uid()) || metadata.mode() & 0o022 != 0 + { + return Err(invalid(format!( + "directory {} must be a non-symlink directory owned by a permitted owner and not writable by group or other users", + ancestor.display() + ))); + } + } + let canonical = parent.join(name); + let expected = std::fs::symlink_metadata(&canonical) + .map_err(|source| io_error("inspect trusted file", &canonical, source))?; + let validate = |metadata: &std::fs::Metadata| { + metadata.file_type().is_file() + && metadata.nlink() == 1 + && ownership.permits(metadata.uid()) + && metadata.mode() & 0o022 == 0 + }; + if !validate(&expected) { + return Err(invalid( + "file must be a single-link regular file owned by a permitted owner and not writable by group or other users".to_owned(), + )); + } + if expected.size() > max_bytes { + return Err(SecurityError::SizeLimit { + path: canonical, + limit: max_bytes, + }); + } + let file = std::fs::OpenOptions::new() + .read(true) + .custom_flags(rustix::fs::OFlags::NOFOLLOW.bits() as i32) + .open(&canonical) + .map_err(|source| io_error("open trusted file", &canonical, source))?; + let opened = file + .metadata() + .map_err(|source| io_error("inspect opened trusted file", &canonical, source))?; + if opened.dev() != expected.dev() || opened.ino() != expected.ino() || !validate(&opened) { + return Err(invalid("file changed while it was being opened".to_owned())); + } + let mut bytes = Vec::new(); + file.take(max_bytes.saturating_add(1)) + .read_to_end(&mut bytes) + .map_err(|source| io_error("read trusted file", &canonical, source))?; + if bytes.len() as u64 > max_bytes { + return Err(SecurityError::SizeLimit { + path: canonical, + limit: max_bytes, + }); + } + Ok(bytes) +} + +#[cfg(not(unix))] +pub fn read_trusted_file( + _path: &Path, + _ownership: TrustedOwnership, + _max_bytes: u64, +) -> SecurityResult> { + Err(SecurityError::UnsupportedPlatform) +} + #[cfg(not(unix))] pub struct SecureRoot; @@ -717,3 +830,67 @@ impl SecureRoot { Err(SecurityError::UnsupportedPlatform) } } + +#[cfg(all(test, unix))] +mod trusted_file_tests { + use std::os::unix::fs::{PermissionsExt, symlink}; + + use super::*; + + fn private_directory() -> tempfile::TempDir { + let directory = tempfile::Builder::new() + .prefix(".trusted-file-test-") + .tempdir_in(env!("CARGO_MANIFEST_DIR")) + .expect("temporary directory"); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)) + .expect("private mode"); + directory + } + + fn write(path: &Path, mode: u32) { + std::fs::write(path, b"trusted").expect("write"); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).expect("mode"); + } + + #[test] + fn trusted_files_require_permitted_owners_and_protected_paths() { + let directory = private_directory(); + let uid = rustix::process::getuid().as_raw(); + let file = directory.path().join("governance.yaml"); + write(&file, 0o644); + if ancestors_are_protected(directory.path(), uid) { + assert_eq!( + read_trusted_file(&file, TrustedOwnership::RootOrUser(uid), 64).expect("read"), + b"trusted" + ); + assert!(matches!( + read_trusted_file(&file, TrustedOwnership::RootOrUser(uid), 3), + Err(SecurityError::SizeLimit { .. }) + )); + } + if uid != 0 { + assert!(read_trusted_file(&file, TrustedOwnership::Root, 64).is_err()); + } + + let writable = directory.path().join("writable.yaml"); + write(&writable, 0o664); + assert!(read_trusted_file(&writable, TrustedOwnership::RootOrUser(uid), 64).is_err()); + + let link = directory.path().join("link.yaml"); + symlink(&file, &link).expect("symlink"); + assert!(read_trusted_file(&link, TrustedOwnership::RootOrUser(uid), 64).is_err()); + assert!(read_trusted_file(Path::new("relative.yaml"), TrustedOwnership::Root, 64).is_err()); + } + + fn ancestors_are_protected(path: &Path, uid: u32) -> bool { + use std::os::unix::fs::MetadataExt; + std::fs::canonicalize(path) + .expect("canonical") + .ancestors() + .all(|ancestor| { + std::fs::symlink_metadata(ancestor).is_ok_and(|metadata| { + (metadata.uid() == 0 || metadata.uid() == uid) && metadata.mode() & 0o022 == 0 + }) + }) + } +} diff --git a/docs/README.md b/docs/README.md index 2736352..efd22e3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -29,6 +29,7 @@ to a first run. Use this index for setup, operation, and implementation details. ## Security - [Security model](security-model.md) +- [Governed sessions and brokered credentials](architecture/governed-sessions.md) - [Egress enforcement trust boundary](security/egress-enforcement-trust-boundary.md) - [Secrets migration](migration/secrets.md) - [Security-record migration](migration/security-records.md) @@ -52,6 +53,7 @@ to a first run. Use this index for setup, operation, and implementation details. - [MCP broker](architecture/mcp-broker.md) - [Package registry proxy](architecture/package-registry-proxy.md) - [Secrets and credential broker](architecture/secrets-and-credential-broker.md) +- [Governed sessions](architecture/governed-sessions.md) - [Git branch guard](architecture/git-branch-guard.md) - [Safe Outputs](architecture/safe-outputs.md) - [Security records](architecture/security-records.md) diff --git a/docs/architecture/authenticated-guest-protocol.md b/docs/architecture/authenticated-guest-protocol.md index 03836c4..7857511 100644 --- a/docs/architecture/authenticated-guest-protocol.md +++ b/docs/architecture/authenticated-guest-protocol.md @@ -128,6 +128,20 @@ operation. The host atomically persists the validated JSON with mode `0600`, records its digest in signed session provenance, and includes a compact `network_report: {path, sha256}` reference in `run --json`. +[Governed sessions](governed-sessions.md) with brokered credential services +append event kinds 10 to 15 for the credential relay (schema version 1): +`CredentialRelayRequest`, `CredentialRelayRequestBody`, and +`CredentialRelayCredit` travel guest to host, `CredentialRelayResponseHead` and +`CredentialRelayResponseBody` travel host to guest, and `CredentialRelayEnd` +closes a stream in either direction. The guest chooses strictly increasing +stream identifiers starting at `1 << 32`, so they never collide with request +IDs. Response bodies use 32 KiB chunks, and the host never has more than 16 +uncredited chunks outstanding per stream. Relay events carry no credential +material. There is no new capability discriminant: a brokered plan requires the +guest's authenticated readiness to report a healthy `credential_relay` +service, and the host rejects relay events in a session without a brokered +relay. + ## Terminal post-processing ordering The launch request remains request ID `1`. If package analysis is configured, @@ -219,6 +233,9 @@ state and terminally poisons the connection. - V2 terminal input is additionally bounded to 64 authenticated chunks of at most 4 KiB each. Credits travel guest-to-host without blocking the guest socket reader, and end of file remains outside the credit budget. +- Credential relay responses are bounded to 16 outstanding 32 KiB chunks per + stream and to the profile's concurrent stream limit, so a slow agent cannot + stall terminal or control traffic. Dropping a receive future is resumable because already-read bytes remain in the bounded reader buffer. Dropping a send future can leave a partial frame on the diff --git a/docs/architecture/egress-enforcement.md b/docs/architecture/egress-enforcement.md index 5bbc218..c3b9436 100644 --- a/docs/architecture/egress-enforcement.md +++ b/docs/architecture/egress-enforcement.md @@ -250,6 +250,9 @@ Workloads receive exact upper- and lower-case `ALL_PROXY`/`NO_PROXY` and The HTTP listener on port 15083 and SOCKS listener on 15080 share the same authorization cache, DNS guard, semaphore, and marked dialer. Both ports are signed and pairwise distinct from DNS, MCP, and package ports. +A brokered [governed session](governed-sessions.md) adds the signed credential +relay port 15084, also pairwise distinct, which nftables admits only from the +agent cgroup to loopback. The authenticated stdio MCP broker receives the same fixed proxy environment, so local servers remain descendants of execution leaves and cannot bypass enforcement. The remote MCP gateway remains in the broker cgroup and uses diff --git a/docs/architecture/governed-sessions.md b/docs/architecture/governed-sessions.md new file mode 100644 index 0000000..6b4b6b0 --- /dev/null +++ b/docs/architecture/governed-sessions.md @@ -0,0 +1,332 @@ +# Governed sessions + +Status: **increment 1, single host**. Governed sessions add operator-signed +policy profiles and host-side credential mediation on top of the existing VM +isolation, signed boundary plan, and session audit. Standalone sessions are +unchanged unless governance is selected or required by the host. + +Increment 1 is not multi-user governance. Authenticated shared management, +project-scoped roles, central audit, and approved exceptions are tracked for +the separate `sendbox-fleet` service, which shares the +[`sendbox-governance`](../../crates/sendbox-governance) contract crate. + +```mermaid +flowchart LR + subgraph Guest VM + A[Agent
ANTHROPIC_BASE_URL / OPENAI_BASE_URL] -->|loopback, admitted for the agent cgroup| R[Credential relay
trusted supervisor] + end + R -->|relay events on the authenticated control channel| H[Host relay endpoint] + H --> G{Grant authority
binding, expiry, revocation, revision} + G -->|allowed| B[Broker
verified TLS, DNS pinning,
address classes, limits] + B -->|provider key injected on the host| U[(api.anthropic.com
api.openai.com)] + O[Operator config + signed profile] --> P[Admission: verify, compose, bind] --> BP[Signed boundary plan
+ governance binding] +``` + +## Selecting governance + +| Mode | How it is selected | Who may own the files | +|---|---|---| +| Managed | `/Library/Application Support/SendBox/governance.yaml` (macOS) or `/etc/sendbox/governance.yaml` (Linux) exists | root, with every ancestor root-owned and not group/world writable | +| Opt-in | `sendbox run --governance-config PATH` on a host without a managed file | root or the current user, not group/world writable | +| Standalone | neither | not applicable | + +A managed configuration always wins. When it exists, every `sendbox run` is +governed and `--governance-config` is rejected if it names any other file. +There is no environment variable or project setting that disables governance +or selects another authority. If the managed path exists but cannot be read or +verified, the session fails closed. + +Opt-in mode is self-governance: it lets a user apply a signed profile to their +own sessions, but the user can stop selecting it. Use managed mode when the +operator and the session user are different parties. + +A standalone project that lists `credential_services` is rejected, because +brokered credentials only exist under a grant authority. + +## Operator configuration + +```yaml +format: sendbox.governance-operator +version: 1 +authority: local +profile: acme-default +profile_path: /Library/Application Support/SendBox/profiles/acme-default.yaml +# signatures_path defaults to profile_path + ".sig.json" +minimum_revision: 3 +trust: + threshold: 1 + signers: + - version: 1 + fingerprint: "" + name: Acme security + email: null + public_key_base64: "" + valid_from_unix: 1790000000 + expires_at_unix: null + revoked_at_unix: null +bundle: # optional: pin the guest bundle trust root + trust_root_sha256: [""] + trust_root_ids: [external-release-root] + minimum_release_sequence: 7 +revision_cache_seconds: 30 +``` + +- `trust` builds a provenance trust store with `allow_unsigned: false`. At + least `threshold` distinct, unexpired, unrevoked signers must sign the + profile's exact bytes. +- `minimum_revision` is the operator's rollback floor. Raising it makes every + older revision, and every grant bound to one, stale. +- `bundle` pins the `--trust-root`, `--trust-root-id`, and minimum + `--minimum-release-sequence` a governed run may use, so a caller cannot + substitute their own guest supervisor. In managed mode the pinned trust root + file must be root-owned with protected ancestors, so it cannot be swapped + between the pin check and bundle verification. +- `revision_cache_seconds` bounds how long the grant authority reuses a + verified profile before re-reading and re-verifying it. + +The host also keeps a per-user high-water mark of admitted revisions under the +runtime state directory and rejects a lower revision. That record is +user-writable; the operator `minimum_revision` is the authoritative floor. + +## Profiles + +Profiles are YAML documents signed byte for byte. Their digest is the SHA-256 +of those bytes, so any edit is a new revision that must be signed again. + +```yaml +format: sendbox.governance-profile +version: 1 +id: acme-default +revision: 4 +not_before_unix: 1790000000 +expires_at_unix: 1810000000 # at most 400 days after not_before_unix +ceiling: + runtimes: [apple, kata] + images: ["sha256:<64 hex>"] # optional; empty permits any image + workspace_roots: [/Users] # optional; empty permits any workspace + resources: { max_cpus: 8, max_memory_mb: 16384 } + commands: + default_action: deny + allowlist: ["/usr/local/bin/claude *", "git *", "cat *"] + network: + default_action: deny + allowed_domains: ["*.github.com", "registry.npmjs.org"] + allowed_networks: [] + allowed_ports: [] # empty permits any port + allow_dns: true + github_meta: false # implicit GitHub Meta CIDR delegation + mcp: + require_boundaries: true + servers: {} + packages: + allowed_registries: ["https://registry.npmjs.org/"] + require_supply_chain: false + secrets: + workload: [NPM_TOKEN] # names that may enter the guest + github: + forward_auth: false + forward_copilot_auth: false + allow_private_repository_access: false + ssh_key: false + require_branch_protection: true + safe_outputs: { enabled: true, allow_apply: false, repositories: [] } +denials: + commands: ["git push --force *"] + domains: [pastebin.com] + networks: ["169.254.0.0/16"] +credential_services: + - id: anthropic + provider: anthropic + secret: SENDBOX_ANTHROPIC_API_KEY + methods: [POST, GET] # default: GET, POST + path_prefixes: [/v1/messages, /v1/models] + max_request_bytes: 8388608 + max_response_bytes: 67108864 + max_duration_seconds: 900 + idle_timeout_seconds: 120 + deny_direct_egress: true + - id: openai + provider: openai + secret: SENDBOX_OPENAI_API_KEY +grants: + lease_seconds: 300 + max_ttl_seconds: 28800 + revocation_grace_seconds: 5 + max_concurrent_streams: 8 +``` + +Omitted ceiling sections take their most restrictive value. Unknown fields are +rejected. + +### Signing workflow + +```bash +sendbox governance keygen --output ~/acme-governance.key # prints the public identity +sendbox governance sign acme-default.yaml --key ~/acme-governance.key +sendbox governance sign acme-default.yaml --key second.key --append # threshold signing +sudo install -m 0644 -o root acme-default.yaml acme-default.yaml.sig.json \ + "/Library/Application Support/SendBox/profiles/" +sendbox governance verify +sendbox governance check --config .sendbox.yaml +``` + +`check` loads the active profile, applies its denials, and lists every +violation without starting a session. Keep signing keys off the managed host. + +## Admission and composition + +Admission runs before any side effect such as resolving GitHub credentials, +creating session state, or starting a runtime: + +1. Discover the authority, load the operator configuration, check bundle pins. +2. Verify profile signatures, profile id, validity window, minimum revision, + and the local high-water mark. +3. Append profile denials and every `deny_direct_egress` provider host to the + session policy. Denials only add deny rules and blocked destinations. +4. Compare the effective configuration with the ceiling. Every violation is + reported; nothing is silently narrowed. +5. Sign a governance binding into the boundary plan. + +Composition is a subset check over expanded capabilities, never a merge: + +| Dimension | Rule | +|---|---| +| Runtime | Must be listed. Hyperlight is always rejected because it has no persistent guest boundary. Project-selected Kata executables, handlers, or configuration are rejected. | +| Image, workspace, resources | Image digest in `images`, workspace under a `workspace_roots` entry, resources at most the maximums, when configured. | +| Commands | `allow` default requires an `allow` ceiling. Each exact rule must be matched by a ceiling rule with the runtime's own argv and basename semantics; a wildcard rule must equal a ceiling rule. | +| Domains | `allow` default requires an `allow` ceiling. Exact names need a covering pattern; `*.x` needs `*.x` or a broader `*.y`. Entries already blocked are ignored. | +| GitHub Meta | An unblocked exact `github.com` grant implicitly delegates GitHub Meta CIDRs and requires `github_meta: true`. | +| Networks and ports | Each CIDR must be contained in a ceiling CIDR. A port ceiling requires an explicit, covered port list. | +| DNS | Numeric limits at most the ceiling (defaults equal the runtime defaults), record types a subset, and the budget window equal. | +| MCP | The boundary must stay enabled when required. Legacy flat tool rules are unsupported. Each server must match a ceiling server's transport, command or URL, tools, HTTP flags, redirects, and secrets. | +| Packages | Registries, plaintext HTTP, credentials, finding overrides, and exceptions need explicit ceiling permission; inspection can be required. | +| Secrets | Workload secrets must be listed; a brokered credential or a provider endpoint variable can never be a workload secret. | +| GitHub | Token forwarding, Copilot forwarding, private access, SSH keys, disabled branch protection, and Safe Outputs apply mode or targets each need ceiling permission. | +| Credential services | Must be offered by the profile. | + +Observability settings are not capabilities and are not compared. + +## Binding + +`BoundaryPlan.governance` records the authority (id and trust digest), the +exact profile (id, revision, SHA-256), the principal, the project, the +effective policy SHA-256, and the brokered service ids. It is omitted from +standalone plans, whose canonical bytes are unchanged. The effective policy +digest must equal the plan's `policy_sha256`, which secret envelopes already +authenticate. Increment 1 uses `local-user:` as the principal and +`github:/` (or a workspace path digest) as the project. + +## Brokered credentials + +A project requests services by profile id: + +```yaml +credential_services: [anthropic] +``` + +The host resolves each provider credential from the host secret store before +the session starts (`sendbox secrets add SENDBOX_ANTHROPIC_API_KEY`) and keeps +it in the host process. It is never part of the boundary plan, bootstrap, +secret envelopes, guest environment, or audit. The guest receives only: + +| Provider | Base URL variable | Key variable | +|---|---|---| +| `anthropic` | `ANTHROPIC_BASE_URL=http://127.0.0.1:15084/` | `ANTHROPIC_API_KEY=sendbox-brokered-credential` | +| `openai` | `OPENAI_BASE_URL=http://127.0.0.1:15084//v1` | `OPENAI_API_KEY=sendbox-brokered-credential` | + +The key value is a fixed placeholder that the broker discards. Policies +describe services, not agents: any agent or SDK that honors these variables +works, including Claude Code and Codex. + +### Compatibility contract + +- The client must support an explicit base URL and append the upstream path. +- Request bodies need `Content-Length`; chunked uploads are rejected. +- Clients that hardcode their service origin or require HTTPS proxy tunneling + are unsupported. SendBox never falls back to delivering the raw credential, + intercepting TLS, or executing on the host. + +### Relay + +The trusted guest supervisor listens on `127.0.0.1:15084`; when egress is +enforced, nftables admits that port only for the agent cgroup. A request to +`//` becomes one relay stream on the authenticated control +channel. The guest drops `authorization`, `x-api-key`, `cookie`, and forwarding +headers, and the host additionally forwards only the provider's header +allowlist. + +The host checks method and path locally, asks the grant authority, injects the +credential (`x-api-key` for Anthropic, `Authorization: Bearer` for OpenAI), +and sends the request with the existing broker transport: verified HTTPS on +port 443, DNS resolved and classified per request, addresses pinned, no +system proxy, and redirects denied. Responses stream back as they arrive, +including server-sent events. The guest grants one credit per chunk written +to the agent and the host never exceeds 16 outstanding 32 KiB chunks, so a +slow agent cannot stall terminal or control traffic. Limits per service bound +request size, response size, total duration, and idle time; a stream whose +upstream or guest credit stays idle longer than `idle_timeout_seconds` fails. +When the agent disconnects or the guest stops reading a stream, the guest +tells the host so it closes the upstream connection. + +## Grants and revocation + +At session start the local grant authority issues one grant per brokered +service, bound to the principal, project, session, binding digest, profile +revision, methods, path prefixes, a renewable lease, and a hard maximum +lifetime. Every request is checked for: + +- an existing, unrevoked grant with an unexpired lease and lifetime; +- the exact principal, project, session, and binding digest from trusted host + state (workload-supplied identity is never consulted); +- the granted service, method, and segment-aware path prefix (encoded + separators and dot segments are rejected); +- a profile revision that is still the operator's current, verified revision + and not below the minimum. + +An unreadable or unverifiable profile denies with `authority_unavailable`. The +host renews leases at a third of the lease length. When a grant's renewal +fails, new requests for that service are denied and its in-flight streams get +`revocation_grace_seconds` to finish before they are cancelled and the agent +sees the stream end with `grant_lapsed`. Streams of other services are not +affected. Streams are authorized once at start and are +otherwise bounded by `max_duration_seconds`. + +When the workload ends, is cancelled, or fails, the relay stops accepting +requests, aborts in-flight streams, and revokes every grant. A stream that was +already sent upstream is recorded as `aborted_uncertain`: SendBox does not +claim that revocation reverses completed external effects. + +## Audit + +Records join the existing signed session audit chain: + +| Action | Recorded when | +|---|---| +| `governance.admission.accepted` | the session starts under a profile | +| `credential.grant.issued`, `.lapsed`, `.revoked` | grant lifecycle | +| `credential.request.allowed`, `.denied` | each authorization decision | +| `credential.request.outcome` | each stream ends, with status, byte counts, duration, and outcome | + +Each record carries principal, project, session, authority, profile id, +revision and digest, effective policy digest, and binding digest. Request +records add the service, method, path without query, and reason. Credentials, +headers, query strings, and request or response bodies are never recorded. A +failure to record relay evidence fails the run. + +## Trust boundaries and residual risks + +- The local user who owns the host secret store can still read their own + provider key on the host. The guarantee is that the agent and guest never + receive it. +- Opt-in governance is chosen by the user and is not an enforcement boundary + against that user. +- The local revision high-water mark is user-writable; rely on + `minimum_revision` for rollback protection. +- Long-running streams are not re-authorized mid-stream. +- With `deny_direct_egress: false` and permissive network policy, a workload + that has its own provider key could still call the provider directly. Keep + the default to block the provider host for the workload. + +Non-goals for increment 1: Kubernetes or fleet scheduling, universal TLS +interception, formal policy verification, model API translation, and +replacing isolation providers. diff --git a/docs/architecture/secrets-and-credential-broker.md b/docs/architecture/secrets-and-credential-broker.md index 919268b..9773f48 100644 --- a/docs/architecture/secrets-and-credential-broker.md +++ b/docs/architecture/secrets-and-credential-broker.md @@ -155,6 +155,19 @@ credentials into CONNECT tunnels. Clients that hardcode their service origin or only support HTTPS proxy tunneling are incompatible until they gain an explicit base-URL setting. +### Governed provider relay + +[Governed sessions](governed-sessions.md) connect this broker to compatible +agents for Anthropic and OpenAI without placing the credential in the guest. +The guest supervisor listens on loopback port 15084 and forwards each request +over the authenticated control channel. The host relay +(`sendbox_credentials::relay::RelayEndpoint`) authorizes it against a leased +grant, injects the host-held key, and reuses the pinned transport above with +redirects denied. Unlike the per-connection listener, the relay streams +response bodies, including server-sent events, under guest credit and per +service size, duration, and idle limits. Agents receive only the provider base +URL variable and a fixed placeholder key. + ## Guarded GitHub repository authentication `GitHubMetadataClient` separates repository metadata from the production `gh` @@ -205,6 +218,8 @@ features because it does not provide persistent secret delivery. ## Remaining qualification -- Connect generic explicit-base-URL credential rules to compatible agents. +- Connect generic explicit-base-URL credential rules to compatible agents + outside governed sessions. Governed sessions already broker Anthropic and + OpenAI through the relay. - Run the ignored Keychain ACL qualification whenever the production signing identity or Keychain service identity changes. diff --git a/docs/architecture/session-security-lifecycle.md b/docs/architecture/session-security-lifecycle.md index b762d02..2433ff4 100644 --- a/docs/architecture/session-security-lifecycle.md +++ b/docs/architecture/session-security-lifecycle.md @@ -95,3 +95,9 @@ snapshots, restores eligible mutations on failure, and quarantines changed excluded cache/dependency entries. Runtime cleanup still runs when security finalization fails, and all primary, rollback, audit, publication, and cleanup failures remain visible. + +[Governed sessions](governed-sessions.md#audit) append governance admission +and credential grant and request records to the same signed audit chain. Each +record names the profile revision and the binding digest signed into the +boundary plan, and never includes credential material. A failure to record +relay evidence fails the run. diff --git a/docs/cli-agents.md b/docs/cli-agents.md index fc93b02..eee4e86 100644 --- a/docs/cli-agents.md +++ b/docs/cli-agents.md @@ -84,6 +84,11 @@ github: ``` For Codex use `OPENAI_API_KEY`; for another provider use its documented variable. + +In a [governed session](architecture/governed-sessions.md#brokered-credentials), +list `credential_services: [anthropic]` (or `openai`) instead of the provider +key in `secrets`. The key stays on the host, and Claude Code or Codex receive +only a loopback `ANTHROPIC_BASE_URL` or `OPENAI_BASE_URL` and a placeholder key. The host's home, global agent configuration, browser, keychain files, and runtime sockets are not mounted. Each session gets an owner-only guest home at `/run/sendbox-workload/` and isolated XDG directories. Login state diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 745b9d2..121754d 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -14,6 +14,7 @@ SUBCOMMANDS: mcp Parse and summarize native or legacy MCP observations package Show package verdict status or a complete security report boundary Inspect the structured native boundary plan + governance Sign, verify, and check operator governance profiles completions Install or print shell completions help Show help for any subcommand ``` @@ -41,6 +42,7 @@ entry program and initial inference endpoints; `open-code` is an alias for | `--trust-root PATH` | Release public key used to verify the bundle | | `--json` | Emit machine-readable events instead of raw output | | `--interactive` | Run the workload on a pseudoterminal; conflicts with `--json` | +| `--governance-config PATH` | Opt-in governance configuration; rejected when a managed configuration names a different file | See [interactive sessions](interactive-sessions.md) for terminal-specific requirements and [configuration](configuration.md) for the YAML reference. @@ -60,6 +62,21 @@ guest evidence whose digest is recorded in session provenance, not a separately GitHub-signed feed or a complete refresh log. See [network grants](configuration.md#network-grants). +## Governance + +`sendbox governance` manages operator-signed profiles for +[governed sessions](architecture/governed-sessions.md): + +| Subcommand | Purpose | +|---|---| +| `keygen --output PATH` | Create an Ed25519 signing key (mode `0600`, never overwritten) and print its public identity | +| `sign PROFILE --key PATH [--append]` | Sign the profile's exact bytes into `PROFILE.sig.json`; `--append` adds a threshold signature | +| `verify [--governance-config PATH]` | Verify the active operator configuration, profile, and signatures | +| `check --config PATH [--governance-config PATH] [--runtime apple\|kata] [--image IMAGE@sha256:DIGEST]` | List every violation of the active profile without starting a session | + +Each subcommand accepts `--json`. A governance failure or a rejected +configuration exits with code `6`. + ## Examples ```bash @@ -102,4 +119,7 @@ sendbox mcp report /var/log/sendbox/mcp-trace.log # Inspect the structured boundary declaration without generating scripts sendbox boundary inspect --config .sendbox.yaml --json + +# Check a project against the active governance profile +sendbox governance check --config .sendbox.yaml --runtime apple ``` diff --git a/docs/configuration.md b/docs/configuration.md index 1ac3f51..2a4a3b1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -356,6 +356,7 @@ guest syscall tracing. | `policy.boundaries.tool_calls.servers.*.http.allowed_auth_methods` | list | Admitted HTTP auth methods: `none`, `bearer` | | `policy.boundaries.syscalls.additional_denylist` | list | Extra syscall names blocked by seccomp | | `secrets` | list | Secret names injected at runtime | +| `credential_services` | list | Brokered credential service ids from the active [governance profile](architecture/governed-sessions.md#brokered-credentials); rejected outside governed sessions | | `devcontainer.auto_generate` | bool | Generate a devcontainer spec | | `github.forward_auth` | bool | Forward guarded GitHub credentials for the selected repository | | `github.forward_copilot_auth` | bool | Forward Copilot authentication independently as `COPILOT_GITHUB_TOKEN` | diff --git a/docs/security-model.md b/docs/security-model.md index 18852d2..999120c 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -59,6 +59,13 @@ token is retrieved only after complete pagination succeeds. Apple and Kata runs deliver approved credentials through authenticated, policy-bound secret envelopes. +[Governed sessions](architecture/governed-sessions.md) go further for model +provider keys: an operator-signed profile bounds what a project may request, +the admission is bound into the signed boundary plan, and Anthropic or OpenAI +requests are relayed to the host over the authenticated control channel. The +host checks a leased, revocable grant and injects the key, so the provider +credential never enters the guest. + ### Production package mediation The Rust [`sendbox-registry`](package-supply-chain.md) component is a trusted diff --git a/docs/security/egress-enforcement-trust-boundary.md b/docs/security/egress-enforcement-trust-boundary.md index fdb0a7f..b65450b 100644 --- a/docs/security/egress-enforcement-trust-boundary.md +++ b/docs/security/egress-enforcement-trust-boundary.md @@ -36,8 +36,11 @@ nftables default-drop denies every other cgroup/destination combination ## What the kernel layer enforces - The agent cgroup can originate traffic **only** to the exact loopback broker - ports (CONNECT always; DNS only when `allow_dns = true`) and the configured - npm proxy port. + ports (CONNECT always; DNS only when `allow_dns = true`), the configured + npm proxy port, and, in a governed session with brokered credentials, the + credential relay port (15084). The relay is served by the trusted guest + supervisor and forwards to the host over the authenticated control channel, + not through the broker cgroup. - The registry cgroup can originate traffic **only** to the exact registry-only SOCKS port. It cannot reach public broker ports or external destinations. diff --git a/fuzz/bpf/Cargo.lock b/fuzz/bpf/Cargo.lock index 7f7ba73..4a7f2fa 100644 --- a/fuzz/bpf/Cargo.lock +++ b/fuzz/bpf/Cargo.lock @@ -1525,6 +1525,7 @@ dependencies = [ "clap", "ed25519-dalek", "getrandom 0.3.4", + "http", "libc", "rustix", "sendbox-bootstrap", diff --git a/fuzz/credentials/Cargo.lock b/fuzz/credentials/Cargo.lock index 2ca562f..69180ee 100644 --- a/fuzz/credentials/Cargo.lock +++ b/fuzz/credentials/Cargo.lock @@ -54,7 +54,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -65,7 +65,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -162,7 +162,7 @@ dependencies = [ "maybe-owned", "rustix", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -416,7 +416,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1183,7 +1183,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1304,7 +1304,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1373,7 +1373,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1406,6 +1406,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "ryu-js" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" + [[package]] name = "same-file" version = "1.0.6" @@ -1483,6 +1489,8 @@ dependencies = [ "reqwest", "sendbox-config", "sendbox-egress", + "sendbox-governance", + "sendbox-protocol", "sendbox-runtime", "sendbox-secrets", "serde", @@ -1544,6 +1552,19 @@ dependencies = [ "url", ] +[[package]] +name = "sendbox-governance" +version = "0.2.7" +dependencies = [ + "sendbox-core", + "serde", + "serde_json", + "serde_json_canonicalizer", + "sha2", + "thiserror", + "yaml_serde", +] + [[package]] name = "sendbox-policy" version = "0.2.7" @@ -1651,6 +1672,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_json_canonicalizer" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe52319a927259afbfa5180c5157cd8167edfd3e8c254f9558c7fef44c5649f2" +dependencies = [ + "ryu-js", + "serde", + "serde_json", +] + [[package]] name = "sha2" version = "0.11.0" @@ -1713,7 +1745,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -2148,7 +2180,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/guest/sendbox-guest/Cargo.toml b/guest/sendbox-guest/Cargo.toml index 2f00bd4..1d20ac0 100644 --- a/guest/sendbox-guest/Cargo.toml +++ b/guest/sendbox-guest/Cargo.toml @@ -11,10 +11,12 @@ publish = false default = ["execution-broker"] execution-broker = [ "dep:sendbox-bpf", + "dep:sendbox-credentials", "dep:sendbox-egress", "dep:sendbox-exec", "dep:sendbox-policy", "dep:sendbox-registry", + "dep:sendbox-runtime", ] [dependencies] @@ -22,12 +24,14 @@ async-trait.workspace = true clap.workspace = true ed25519-dalek.workspace = true getrandom = "0.3.4" +http.workspace = true libc.workspace = true rustix = { workspace = true, features = ["mount"] } sendbox-bpf = { path = "../../crates/sendbox-bpf", optional = true } sendbox-config = { path = "../../crates/sendbox-config" } sendbox-bootstrap = { path = "../../crates/sendbox-bootstrap" } sendbox-core = { path = "../../crates/sendbox-core" } +sendbox-credentials = { path = "../../crates/sendbox-credentials", optional = true } sendbox-egress = { path = "../../crates/sendbox-egress", optional = true } sendbox-exec = { path = "../../crates/sendbox-exec", optional = true } sendbox-git = { path = "../../crates/sendbox-git" } @@ -35,6 +39,7 @@ sendbox-mcp = { path = "../../crates/sendbox-mcp" } sendbox-policy = { path = "../../crates/sendbox-policy", optional = true } sendbox-protocol = { path = "../../crates/sendbox-protocol" } sendbox-registry = { path = "../../crates/sendbox-registry", optional = true } +sendbox-runtime = { path = "../../crates/sendbox-runtime", optional = true } sendbox-secrets = { path = "../../crates/sendbox-secrets" } serde.workspace = true serde_json.workspace = true diff --git a/guest/sendbox-guest/src/bootstrap.rs b/guest/sendbox-guest/src/bootstrap.rs index a71481b..8f78bec 100644 --- a/guest/sendbox-guest/src/bootstrap.rs +++ b/guest/sendbox-guest/src/bootstrap.rs @@ -201,6 +201,7 @@ mod tests { github_meta: None, gateway_credentials: Vec::new(), registry_proxy: None, + credential_relay: None, }, &secret, ) diff --git a/guest/sendbox-guest/src/credential_relay.rs b/guest/sendbox-guest/src/credential_relay.rs new file mode 100644 index 0000000..3768916 --- /dev/null +++ b/guest/sendbox-guest/src/credential_relay.rs @@ -0,0 +1,658 @@ +//! Guest side of the brokered credential relay. +//! +//! The trusted supervisor listens on a loopback port that the agent cgroup is +//! admitted to. Each HTTP request to `//` becomes one +//! relay stream over the authenticated control channel. The host broker adds +//! the provider credential; nothing in this module ever sees it. Responses are +//! written to the agent with chunked framing as they arrive, and every body +//! chunk written returns one credit to the host. + +use std::collections::{BTreeSet, HashMap}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use sendbox_bootstrap::CredentialRelayBootstrap; +use sendbox_credentials::BrokerLimits; +use sendbox_credentials::http1::{ParsedRequest, read_request, strip_hop_by_hop}; +use sendbox_protocol::relay::{ + CREDENTIAL_RELAY_CHUNK_BYTES, CREDENTIAL_RELAY_SCHEMA_VERSION, CREDENTIAL_RELAY_STREAM_BASE, + CREDENTIAL_RELAY_WINDOW_CHUNKS, CredentialRelayCreditV1, CredentialRelayEndV1, + CredentialRelayHeaderV1, CredentialRelayOutcomeV1, CredentialRelayRequestV1, + CredentialRelayResponseHeadV1, +}; +use sendbox_protocol::{Event, EventKind}; +use tokio::io::{AsyncWrite, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::{Semaphore, mpsc}; + +use crate::GuestError; + +const OUTBOUND_DEPTH: usize = 64; +const STREAM_DEPTH: usize = CREDENTIAL_RELAY_WINDOW_CHUNKS as usize + 4; +const REQUEST_READ_TIMEOUT: Duration = Duration::from_secs(30); +const END_SEND_TIMEOUT: Duration = Duration::from_secs(5); +/// Credentials a workload might attach itself. They are dropped here and the +/// host additionally forwards only a provider allowlist. +const DROPPED_REQUEST_HEADERS: &[&str] = &[ + "authorization", + "proxy-authorization", + "x-api-key", + "cookie", + "forwarded", + "x-forwarded-for", +]; + +pub(crate) struct CredentialRelay { + port: u16, + services: BTreeSet, + max_request_bytes: usize, + outbound: mpsc::Sender, + outbound_receiver: tokio::sync::Mutex>, + streams: Mutex>>, + next_stream: AtomicU64, + connections: Arc, +} + +impl CredentialRelay { + /// Binds the loopback listener before readiness so a failed bind fails the + /// session instead of silently leaving agents without a credential path. + pub(crate) async fn bind( + configuration: &CredentialRelayBootstrap, + ) -> Result<(Arc, TcpListener), GuestError> { + configuration + .validate() + .map_err(|error| GuestError::Bootstrap(error.to_string()))?; + let listener = TcpListener::bind(("127.0.0.1", configuration.port)) + .await + .map_err(|error| GuestError::io("binding credential relay listener", error))?; + let max_request_bytes = usize::try_from(configuration.max_request_bytes).map_err(|_| { + GuestError::Bootstrap("credential relay request limit is out of range".to_owned()) + })?; + let streams = usize::try_from(configuration.max_streams).map_err(|_| { + GuestError::Bootstrap("credential relay stream limit is out of range".to_owned()) + })?; + let (outbound, outbound_receiver) = mpsc::channel(OUTBOUND_DEPTH); + Ok(( + Arc::new(Self { + port: configuration.port, + services: configuration.services.iter().cloned().collect(), + max_request_bytes, + outbound, + outbound_receiver: tokio::sync::Mutex::new(outbound_receiver), + streams: Mutex::new(HashMap::new()), + next_stream: AtomicU64::new(CREDENTIAL_RELAY_STREAM_BASE), + connections: Arc::new(Semaphore::new(streams)), + }), + listener, + )) + } + + pub(crate) fn serve(self: &Arc, listener: TcpListener) -> tokio::task::JoinHandle<()> { + let relay = Arc::clone(self); + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { + tokio::time::sleep(Duration::from_millis(50)).await; + continue; + }; + let relay = Arc::clone(&relay); + tokio::spawn(async move { relay.connection(stream).await }); + } + }) + } + + /// Next guest-to-host relay event for the execution loop to forward. + pub(crate) async fn next_outbound(&self) -> Option { + self.outbound_receiver.lock().await.recv().await + } + + /// Routes one host-to-guest relay event to its connection. Events for a + /// finished stream are discarded; a host that exceeds the credit window + /// ends that stream. + pub(crate) fn deliver(&self, event: Event) -> Result<(), String> { + if !matches!( + event.kind, + EventKind::CredentialRelayResponseHead + | EventKind::CredentialRelayResponseBody + | EventKind::CredentialRelayEnd + ) { + return Err("host sent a guest-only credential relay event".to_owned()); + } + let stream_id = event.stream_id; + let ended = event.kind == EventKind::CredentialRelayEnd; + let mut streams = self + .streams + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(sender) = streams.get(&stream_id) else { + return Ok(()); + }; + if sender.try_send(event).is_err() || ended { + streams.remove(&stream_id); + } + Ok(()) + } + + /// Ends every open stream, for example when the workload terminated. + pub(crate) fn abort_all(&self) { + self.streams + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clear(); + } + + async fn connection(self: Arc, mut stream: TcpStream) { + let Ok(_permit) = Arc::clone(&self.connections).try_acquire_owned() else { + let _ = write_error(&mut stream, 503, "too_many_streams").await; + return; + }; + let limits = BrokerLimits { + request_read_timeout: REQUEST_READ_TIMEOUT, + ..BrokerLimits::default() + }; + let cancellation = sendbox_runtime::CancellationToken::new(); + let parsed = + match read_request(&mut stream, &limits, self.max_request_bytes, &cancellation).await { + Ok(parsed) => parsed, + Err(_) => { + let _ = write_error(&mut stream, 400, "invalid_request").await; + return; + } + }; + let request = match self.relay_request(&parsed) { + Ok(request) => request, + Err((status, reason)) => { + let _ = write_error(&mut stream, status, reason).await; + return; + } + }; + let stream_id = self.next_stream.fetch_add(1, Ordering::SeqCst); + let (sender, mut frames) = mpsc::channel(STREAM_DEPTH); + self.streams + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(stream_id, sender); + let opened = self + .send_request(stream_id, &request, &parsed.body) + .await + .is_ok(); + if opened { + let reason = match self.respond(stream_id, &mut stream, &mut frames).await { + Delivery::Complete | Delivery::HostEnded => None, + Delivery::ClientGone => Some("client_disconnected"), + Delivery::Abandoned => Some("relay_abandoned"), + }; + if let Some(reason) = reason { + // The host keeps the stream and its upstream connection open + // until it learns the guest stopped reading. + let _ = tokio::time::timeout( + END_SEND_TIMEOUT, + self.outbound.send(end_event( + stream_id, + CredentialRelayOutcomeV1::Aborted, + reason, + )), + ) + .await; + } + } else { + let _ = write_error(&mut stream, 502, "relay_unavailable").await; + } + self.streams + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .remove(&stream_id); + } + + fn relay_request( + &self, + parsed: &ParsedRequest, + ) -> Result { + let host = parsed + .headers + .iter() + .find(|(name, _)| name == http::header::HOST) + .and_then(|(_, value)| value.to_str().ok()) + .ok_or((400, "invalid_host"))?; + let loopback = [ + format!("127.0.0.1:{}", self.port), + format!("localhost:{}", self.port), + ]; + if !loopback + .iter() + .any(|expected| host.eq_ignore_ascii_case(expected)) + { + return Err((400, "invalid_host")); + } + let target = parsed + .target + .strip_prefix('/') + .ok_or((400, "invalid_request"))?; + let split = target.find(['/', '?']).unwrap_or(target.len()); + let (service, remainder) = target.split_at(split); + if !self.services.contains(service) { + return Err((404, "service_not_configured")); + } + let path = if remainder.starts_with('/') { + remainder.to_owned() + } else { + format!("/{remainder}") + }; + let headers = strip_hop_by_hop(&parsed.headers) + .into_iter() + .filter(|(name, _)| !DROPPED_REQUEST_HEADERS.contains(&name.as_str())) + .filter_map(|(name, value)| { + value.to_str().ok().map(|value| CredentialRelayHeaderV1 { + name: name.as_str().to_owned(), + value: value.to_owned(), + }) + }) + .collect(); + let request = CredentialRelayRequestV1 { + schema_version: CREDENTIAL_RELAY_SCHEMA_VERSION, + service: service.to_owned(), + method: parsed.method.as_str().to_owned(), + path, + headers, + body_bytes: parsed.body.len() as u64, + }; + request.validate().map_err(|_| (400, "invalid_request"))?; + Ok(request) + } + + async fn send_request( + &self, + stream_id: u64, + request: &CredentialRelayRequestV1, + body: &[u8], + ) -> Result<(), ()> { + let payload = serde_json::to_vec(request).map_err(|_| ())?; + self.outbound + .send(Event { + stream_id, + kind: EventKind::CredentialRelayRequest, + payload, + }) + .await + .map_err(|_| ())?; + for chunk in body.chunks(CREDENTIAL_RELAY_CHUNK_BYTES) { + self.outbound + .send(Event { + stream_id, + kind: EventKind::CredentialRelayRequestBody, + payload: chunk.to_vec(), + }) + .await + .map_err(|_| ())?; + } + Ok(()) + } + + async fn respond( + &self, + stream_id: u64, + client: &mut (impl AsyncWrite + Unpin), + frames: &mut mpsc::Receiver, + ) -> Delivery { + let mut head_sent = false; + while let Some(event) = frames.recv().await { + match event.kind { + EventKind::CredentialRelayResponseHead if !head_sent => { + let Ok(head) = + serde_json::from_slice::(&event.payload) + else { + return Delivery::Abandoned; + }; + if head.validate().is_err() { + let _ = write_error(client, 502, "invalid_upstream_response").await; + return Delivery::Abandoned; + } + if write_head(client, &head).await.is_err() { + return Delivery::ClientGone; + } + head_sent = true; + } + EventKind::CredentialRelayResponseBody if head_sent => { + if write_chunk(client, &event.payload).await.is_err() { + return Delivery::ClientGone; + } + let credit = CredentialRelayCreditV1::new(1) + .ok() + .and_then(|credit| serde_json::to_vec(&credit).ok()); + if let Some(payload) = credit { + let _ = self + .outbound + .send(Event { + stream_id, + kind: EventKind::CredentialRelayCredit, + payload, + }) + .await; + } + } + EventKind::CredentialRelayEnd => { + let end = serde_json::from_slice::(&event.payload) + .ok() + .filter(|end| end.validate().is_ok()); + return match (end, head_sent) { + (Some(end), true) if end.outcome == CredentialRelayOutcomeV1::Complete => { + if client.write_all(b"0\r\n\r\n").await.is_err() { + return Delivery::ClientGone; + } + let _ = client.shutdown().await; + Delivery::Complete + } + (_, true) => Delivery::HostEnded, + (Some(end), false) => { + let status = match end.outcome { + CredentialRelayOutcomeV1::Denied => 403, + _ => 502, + }; + let _ = write_error(client, status, &end.reason).await; + Delivery::HostEnded + } + (None, false) => { + let _ = write_error(client, 502, "invalid_relay_end").await; + Delivery::HostEnded + } + }; + } + _ => return Delivery::Abandoned, + } + } + if !head_sent { + let _ = write_error(client, 502, "relay_closed").await; + } + Delivery::Abandoned + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Delivery { + /// The host completed the stream. + Complete, + /// The host ended the stream with a failure. + HostEnded, + /// The agent closed its connection before the stream ended. + ClientGone, + /// The guest stopped reading a stream the host may still be serving. + Abandoned, +} + +fn end_event(stream_id: u64, outcome: CredentialRelayOutcomeV1, reason: &str) -> Event { + Event { + stream_id, + kind: EventKind::CredentialRelayEnd, + payload: serde_json::to_vec(&CredentialRelayEndV1::new(outcome, reason)) + .unwrap_or_default(), + } +} + +async fn write_head( + client: &mut (impl AsyncWrite + Unpin), + head: &CredentialRelayResponseHeadV1, +) -> std::io::Result<()> { + let status = http::StatusCode::from_u16(head.status) + .map_err(|_| std::io::Error::other("invalid status"))?; + let mut bytes = format!( + "HTTP/1.1 {} {}\r\n", + status.as_u16(), + status.canonical_reason().unwrap_or("Upstream Response") + ) + .into_bytes(); + for header in &head.headers { + bytes.extend_from_slice(header.name.as_bytes()); + bytes.extend_from_slice(b": "); + bytes.extend_from_slice(header.value.as_bytes()); + bytes.extend_from_slice(b"\r\n"); + } + bytes.extend_from_slice(b"transfer-encoding: chunked\r\nconnection: close\r\n\r\n"); + client.write_all(&bytes).await?; + client.flush().await +} + +async fn write_chunk(client: &mut (impl AsyncWrite + Unpin), bytes: &[u8]) -> std::io::Result<()> { + if bytes.is_empty() { + return Ok(()); + } + client + .write_all(format!("{:x}\r\n", bytes.len()).as_bytes()) + .await?; + client.write_all(bytes).await?; + client.write_all(b"\r\n").await?; + client.flush().await +} + +async fn write_error( + client: &mut (impl AsyncWrite + Unpin), + status: u16, + reason: &str, +) -> std::io::Result<()> { + let status = http::StatusCode::from_u16(status).unwrap_or(http::StatusCode::BAD_GATEWAY); + let body = serde_json::json!({ + "type": "error", + "error": { + "type": "sendbox_credential_relay", + "message": format!("SendBox credential broker: {reason}"), + "reason": reason, + } + }) + .to_string(); + let response = format!( + "HTTP/1.1 {} {}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + status.as_u16(), + status.canonical_reason().unwrap_or("Error"), + body.len() + ); + client.write_all(response.as_bytes()).await?; + client.shutdown().await +} + +#[cfg(test)] +mod tests { + use tokio::io::AsyncReadExt; + + use super::*; + + async fn relay() -> (Arc, u16, tokio::task::JoinHandle<()>) { + let port = std::net::TcpListener::bind("127.0.0.1:0") + .expect("probe") + .local_addr() + .expect("address") + .port(); + let (relay, listener) = CredentialRelay::bind(&CredentialRelayBootstrap { + port, + services: vec!["anthropic".to_owned()], + max_streams: 4, + max_request_bytes: 1024, + }) + .await + .expect("bind"); + let task = relay.serve(listener); + (relay, port, task) + } + + async fn next(relay: &CredentialRelay) -> Event { + tokio::time::timeout(Duration::from_secs(5), relay.next_outbound()) + .await + .expect("outbound event") + .expect("open channel") + } + + async fn send(port: u16, request: &str) -> TcpStream { + let mut client = TcpStream::connect(("127.0.0.1", port)) + .await + .expect("connect"); + client + .write_all(request.replace("{port}", &port.to_string()).as_bytes()) + .await + .expect("request"); + client + } + + async fn response(mut client: TcpStream) -> String { + let mut bytes = Vec::new(); + tokio::time::timeout(Duration::from_secs(5), client.read_to_end(&mut bytes)) + .await + .expect("response") + .expect("read"); + String::from_utf8(bytes).expect("utf8") + } + + fn host_event(stream_id: u64, kind: EventKind, payload: Vec) -> Event { + Event { + stream_id, + kind, + payload, + } + } + + #[tokio::test] + async fn requests_become_relay_streams_without_agent_credentials() { + let (relay, port, task) = relay().await; + let client = send( + port, + "POST /anthropic/v1/messages?beta=true HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\ncontent-type: application/json\r\nx-api-key: agent-key\r\nauthorization: Bearer agent\r\ncontent-length: 2\r\n\r\n{}", + ) + .await; + let opened = next(&relay).await; + assert_eq!(opened.kind, EventKind::CredentialRelayRequest); + assert!(opened.stream_id >= CREDENTIAL_RELAY_STREAM_BASE); + let request: CredentialRelayRequestV1 = serde_json::from_slice(&opened.payload).unwrap(); + assert_eq!(request.service, "anthropic"); + assert_eq!(request.path, "/v1/messages?beta=true"); + assert_eq!(request.body_bytes, 2); + assert!( + request + .headers + .iter() + .all(|header| !matches!(header.name.as_str(), "x-api-key" | "authorization")) + ); + let body = next(&relay).await; + assert_eq!(body.kind, EventKind::CredentialRelayRequestBody); + assert_eq!(body.payload, b"{}"); + + let stream = opened.stream_id; + let head = CredentialRelayResponseHeadV1 { + schema_version: CREDENTIAL_RELAY_SCHEMA_VERSION, + status: 200, + headers: vec![CredentialRelayHeaderV1 { + name: "content-type".to_owned(), + value: "text/event-stream".to_owned(), + }], + }; + relay + .deliver(host_event( + stream, + EventKind::CredentialRelayResponseHead, + serde_json::to_vec(&head).unwrap(), + )) + .unwrap(); + relay + .deliver(host_event( + stream, + EventKind::CredentialRelayResponseBody, + b"data: hi\n\n".to_vec(), + )) + .unwrap(); + let credit = next(&relay).await; + assert_eq!(credit.kind, EventKind::CredentialRelayCredit); + relay + .deliver(end_event( + stream, + CredentialRelayOutcomeV1::Complete, + "complete", + )) + .unwrap(); + let text = response(client).await; + assert!(text.starts_with("HTTP/1.1 200 OK\r\n"), "{text}"); + assert!(text.contains("content-type: text/event-stream\r\n")); + assert!(text.contains("transfer-encoding: chunked\r\n")); + assert!(text.ends_with("a\r\ndata: hi\n\n\r\n0\r\n\r\n"), "{text:?}"); + task.abort(); + } + + #[tokio::test] + async fn denials_unknown_services_and_foreign_hosts_fail_locally() { + let (relay, port, task) = relay().await; + let client = send( + port, + "GET /anthropic/v1/models HTTP/1.1\r\nHost: localhost:{port}\r\n\r\n", + ) + .await; + let opened = next(&relay).await; + relay + .deliver(end_event( + opened.stream_id, + CredentialRelayOutcomeV1::Denied, + "stale_policy", + )) + .unwrap(); + let text = response(client).await; + assert!(text.starts_with("HTTP/1.1 403 Forbidden\r\n"), "{text}"); + assert!(text.contains("\"reason\":\"stale_policy\"")); + + let text = response( + send( + port, + "GET /openai/v1/models HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\r\n", + ) + .await, + ) + .await; + assert!(text.starts_with("HTTP/1.1 404"), "{text}"); + let text = response( + send( + port, + "GET /anthropic/v1/models HTTP/1.1\r\nHost: evil.example\r\n\r\n", + ) + .await, + ) + .await; + assert!(text.starts_with("HTTP/1.1 400"), "{text}"); + assert!( + tokio::time::timeout(Duration::from_millis(100), relay.next_outbound()) + .await + .is_err(), + "rejected requests must not reach the host" + ); + + let client = send( + port, + "GET /anthropic/v1/models HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\r\n", + ) + .await; + let opened = next(&relay).await; + relay.abort_all(); + assert!(response(client).await.starts_with("HTTP/1.1 502")); + let abandoned = next(&relay).await; + assert_eq!(abandoned.stream_id, opened.stream_id); + assert_eq!(abandoned.kind, EventKind::CredentialRelayEnd); + let abandoned: CredentialRelayEndV1 = serde_json::from_slice(&abandoned.payload).unwrap(); + assert_eq!( + (abandoned.outcome, abandoned.reason.as_str()), + (CredentialRelayOutcomeV1::Aborted, "relay_abandoned"), + "the host must learn that the guest stopped reading" + ); + assert!( + relay + .deliver(end_event( + opened.stream_id, + CredentialRelayOutcomeV1::Complete, + "complete" + )) + .is_ok() + ); + assert!( + relay + .deliver(host_event( + opened.stream_id, + EventKind::CredentialRelayRequest, + Vec::new() + )) + .is_err() + ); + task.abort(); + } +} diff --git a/guest/sendbox-guest/src/egress.rs b/guest/sendbox-guest/src/egress.rs index 101fa6c..ed41145 100644 --- a/guest/sendbox-guest/src/egress.rs +++ b/guest/sendbox-guest/src/egress.rs @@ -483,6 +483,9 @@ pub async fn run_supervisor(config_path: PathBuf) -> Result<(), GuestError> { if let Some(port) = config.policy.mcp_gateway_port { supervisor_config = supervisor_config.with_mcp_gateway_port(port); } + if let Some(port) = config.policy.credential_relay_port { + supervisor_config = supervisor_config.with_credential_relay_port(port); + } if let Some(registry) = &config.policy.registry { supervisor_config = supervisor_config .with_registry_proxy(registry.proxy_port, registry.trusted_upstream_port); diff --git a/guest/sendbox-guest/src/lib.rs b/guest/sendbox-guest/src/lib.rs index 2cb700a..e20ba08 100644 --- a/guest/sendbox-guest/src/lib.rs +++ b/guest/sendbox-guest/src/lib.rs @@ -7,6 +7,8 @@ pub mod bootstrap; #[cfg(feature = "execution-broker")] pub mod broker; #[cfg(feature = "execution-broker")] +pub(crate) mod credential_relay; +#[cfg(feature = "execution-broker")] pub mod egress; pub mod error; pub mod git_guard; diff --git a/guest/sendbox-guest/src/protocol.rs b/guest/sendbox-guest/src/protocol.rs index 16be69d..6938ceb 100644 --- a/guest/sendbox-guest/src/protocol.rs +++ b/guest/sendbox-guest/src/protocol.rs @@ -24,6 +24,7 @@ use tokio::net::UnixStream; use crate::GuestError; use crate::broker::BrokerClientConfiguration; +use crate::credential_relay::CredentialRelay; use crate::runtime::{ReadinessSnapshot, RuntimeSession}; use crate::safe_outputs::SafeOutputsHandle; use crate::secure_fs::{ @@ -88,6 +89,7 @@ pub(crate) struct ProtocolServices { secret_decryptor: GuestSecretDecryptor, safe_outputs: Option, syscall_tracing: bool, + credential_relay: Option>, } #[derive(Debug, Clone)] @@ -150,6 +152,7 @@ impl ProtocolServices { secret_decryptor, safe_outputs: None, syscall_tracing: false, + credential_relay: None, } } @@ -178,6 +181,19 @@ impl ProtocolServices { self.safe_outputs = safe_outputs; self } + + #[must_use] + pub(crate) fn with_credential_relay(mut self, relay: Option>) -> Self { + self.credential_relay = relay; + self + } +} + +async fn next_relay_outbound(relay: Option<&Arc>) -> Option { + match relay { + Some(relay) => relay.next_outbound().await, + None => std::future::pending().await, + } } pub(crate) async fn serve_authenticated( @@ -318,6 +334,12 @@ where })) .await?; } + // Host relay frames already queued when the workload ended belong + // to streams that were aborted with it. + Message::Event(event) + if terminal_response_sent + && services.credential_relay.is_some() + && event.kind.is_credential_relay() => {} other => { writer .send(&Message::ProtocolError(ProtocolErrorMessage { @@ -863,6 +885,9 @@ where drop(eof_sender); drop(resize_sender); writer_task.abort(); + if let Some(relay) = &services.credential_relay { + relay.abort_all(); + } result } @@ -971,8 +996,28 @@ where } } + relay_event = next_relay_outbound(services.credential_relay.as_ref()) => { + if let Some(event) = relay_event { + host_writer.send(&Message::Event(event)).await?; + } + } host_message = host_reader.receive() => { match host_message? { + Message::Event(event) if event.kind.is_credential_relay() => { + let delivered = match services.credential_relay.as_ref() { + Some(relay) => relay.deliver(event), + None => Err("credential relay is not configured".to_owned()), + }; + if let Err(detail) = delivered { + host_writer.send(&Message::ProtocolError(ProtocolErrorMessage { + code: ProtocolErrorCode::InvalidState, + detail, + })).await?; + return Err(GuestError::Protocol( + "invalid credential relay event during execution".to_owned(), + )); + } + } Message::Cancellation(cancellation) if cancellation.request_id == request.request_id => { let _ = control_sender.send( sendbox_exec::service::ClientFrame::Cancel { diff --git a/guest/sendbox-guest/src/supervisor.rs b/guest/sendbox-guest/src/supervisor.rs index e86aa1e..b6628e1 100644 --- a/guest/sendbox-guest/src/supervisor.rs +++ b/guest/sendbox-guest/src/supervisor.rs @@ -295,6 +295,38 @@ pub async fn run( .map_err(|error| GuestError::io("setting private guest root mode", error)) } + let credential_relay = match bootstrap.credential_relay.as_ref() { + Some(configuration) => { + match crate::credential_relay::CredentialRelay::bind(configuration).await { + Ok((relay, listener)) => { + let task = relay.serve(listener); + audit.lock().expect("audit mutex").record( + "credential_relay_started", + bootstrap.session_id.to_string(), + configuration.services.join(","), + ); + Some((relay, task)) + } + Err(error) => { + fail_and_cleanup(&state, &audit, &runtime, &mut services).await?; + return Err(error); + } + } + } + None => None, + }; + if credential_relay.is_some() { + service_health.push(ServiceHealth { + id: ServiceId::CredentialRelay, + mandatory: true, + healthy: true, + restart_count: 0, + stdout_bytes: 0, + stderr_bytes: 0, + output_truncated: false, + }); + } + let (safe_outputs, mut safe_outputs_task) = if let Some((policy, workload_uid, workload_gid)) = safe_outputs_configuration { @@ -401,7 +433,10 @@ pub async fn run( .with_package_report(package_report) .with_network_reports(network_reports) .with_syscall_tracing(tracing_requested) - .with_safe_outputs(safe_outputs.clone()), + .with_safe_outputs(safe_outputs.clone()) + .with_credential_relay( + credential_relay.as_ref().map(|(relay, _)| Arc::clone(relay)), + ), ) => protocol, failure = services.wait_for_mandatory_failure() => Err(failure), failure = wait_for_safe_outputs_failure(safe_outputs.as_ref()), if safe_outputs.is_some() => Err(failure), @@ -411,6 +446,10 @@ pub async fn run( Err(error) => Err(error), }; + if let Some((relay, task)) = &credential_relay { + relay.abort_all(); + task.abort(); + } if let Some(handle) = &safe_outputs { handle.shutdown().await; }