diff --git a/ROADMAP.md b/ROADMAP.md index 7b27959..cc2234e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -288,7 +288,8 @@ Features planned after core platform and agent support is solid. - [ ] OPA/Rego policy language support for complex rules - [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`) +- [x] Shared multi-user governance service with project-scoped roles, approved expiring exceptions, and central audit ([`sendbox-fleet`](https://github.com/mbianchidev/sendbox-fleet), [shared governance service](docs/architecture/governed-sessions.md#shared-governance-service)) +- [ ] Policy inheritance (org → team → project) - [ ] Policy testing framework - [ ] Community policy library diff --git a/Tests/qualification/inventory.v1.json b/Tests/qualification/inventory.v1.json index 1b62295..85e9ecc 100644 --- a/Tests/qualification/inventory.v1.json +++ b/Tests/qualification/inventory.v1.json @@ -55,9 +55,9 @@ {"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","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.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 LocalGrantAuthority and evaluate_request","crates/sendbox-governance/src/exception.rs#ExceptionPolicy ExceptionScope and PolicyException","crates/sendbox-governance/src/api.rs#shared governance service wire types","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-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-host/src/governance/fleet.rs#FleetClient and FleetGrantAuthority","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/crates/sendbox-agent/tests/agent.rs b/crates/sendbox-agent/tests/agent.rs index 9ec9aef..4634afd 100644 --- a/crates/sendbox-agent/tests/agent.rs +++ b/crates/sendbox-agent/tests/agent.rs @@ -1829,6 +1829,7 @@ fn brokered_plan(resources: &TempResource, capabilities: &RuntimeCapabilities) - project: ProjectId::new("github:octo/api").unwrap(), effective_policy_sha256: Sha256Digest::parse_hex(&boundary.policy_sha256).unwrap(), brokered_services: vec![ServiceId::new("anthropic").unwrap()], + exceptions: Vec::new(), }); let signing_key = SigningKeyMaterial::generate().unwrap(); let fingerprint = signing_key diff --git a/crates/sendbox-boundary/src/lib.rs b/crates/sendbox-boundary/src/lib.rs index 626ac02..1820936 100644 --- a/crates/sendbox-boundary/src/lib.rs +++ b/crates/sendbox-boundary/src/lib.rs @@ -1124,6 +1124,7 @@ mod tests { effective_policy_sha256: Sha256Digest::parse_hex(&governed.policy_sha256) .expect("policy digest"), brokered_services: Vec::new(), + exceptions: Vec::new(), }); governed.validate(now).expect("governed plan"); assert_ne!( diff --git a/crates/sendbox-governance/src/api.rs b/crates/sendbox-governance/src/api.rs new file mode 100644 index 0000000..ae5094d --- /dev/null +++ b/crates/sendbox-governance/src/api.rs @@ -0,0 +1,97 @@ +//! HTTP wire types of a shared governance service (`/v1`) that a SendBox host +//! and the service must agree on. Grant, request, and decision bodies reuse +//! the contract types directly. + +use serde::{Deserialize, Serialize}; + +use crate::{ + GovernanceBinding, PrincipalId, RevocationReason, SessionRef, digest::Sha256Digest, + exception::PolicyException, +}; + +/// Media type of error responses (RFC 9457). +pub const PROBLEM_CONTENT_TYPE: &str = "application/problem+json"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CallerKind { + /// A person. + User, + /// A machine identity, such as a managed runner. + Worker, +} + +/// `GET /v1/whoami`: the identity the service authenticated. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CallerIdentity { + pub principal: PrincipalId, + pub kind: CallerKind, + pub operator: bool, +} + +/// `POST /v1/sessions:admit` body. The binding principal must be the +/// authenticated caller; it is a claim, never a source of identity. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SessionAdmissionRequest { + pub session: SessionRef, + pub binding: GovernanceBinding, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SessionAdmission { + pub session: SessionRef, + pub binding_sha256: Sha256Digest, + pub admitted_at_unix: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SessionOutcome { + Completed, + Cancelled, + Failed, +} + +impl SessionOutcome { + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::Completed => "completed", + Self::Cancelled => "cancelled", + Self::Failed => "failed", + } + } + + #[must_use] + pub const fn revocation_reason(self) -> RevocationReason { + match self { + Self::Completed => RevocationReason::SessionCompleted, + Self::Cancelled => RevocationReason::SessionCancelled, + Self::Failed => RevocationReason::SessionFailed, + } + } +} + +/// `POST /v1/sessions/{session}:end` body. Ending a session revokes its grants. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SessionEnd { + pub outcome: SessionOutcome, +} + +/// `POST /v1/grants/{grant}:revoke` body. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RevokeGrantRequest { + pub reason: RevocationReason, +} + +/// `GET /v1/exceptions` response. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExceptionList { + pub exceptions: Vec, +} diff --git a/crates/sendbox-governance/src/authority.rs b/crates/sendbox-governance/src/authority.rs index 183c4e2..0787caf 100644 --- a/crates/sendbox-governance/src/authority.rs +++ b/crates/sendbox-governance/src/authority.rs @@ -134,12 +134,7 @@ impl LocalGrantAuthority { .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); - } + check_current(reference, ¤t, now)?; Ok(current) } @@ -223,62 +218,15 @@ impl LocalGrantAuthority { fn authorize_sync(&self, context: &RequestContext) -> Decision { let now = self.clock.now_unix(); - let grant = { + let (grant, revoked) = { 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() + (state.grant.clone(), state.revoked.is_some()) }; - 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, - }) + let current = self.revisions.current(&grant.profile.id).ok(); + evaluate_request(&grant, revoked, context, now, current.as_ref()) } fn renew_sync(&self, grant_id: &GrantId) -> Result { @@ -336,6 +284,93 @@ fn deny(reason: DenyReason) -> Decision { Decision::Deny { reason } } +/// Rejects a profile reference that is not the authority's current, unexpired +/// revision at or above the minimum. +pub fn check_current( + reference: &ProfileRef, + current: &CurrentProfile, + now_unix: u64, +) -> Result<(), DenyReason> { + if current.reference != *reference + || reference.revision < current.minimum_revision + || now_unix >= current.expires_at_unix + { + return Err(DenyReason::StalePolicy); + } + Ok(()) +} + +/// Decides one brokered request against a stored grant. Every authority uses +/// this so local and shared authorities deny for the same reasons. `current` +/// is `None` when the authority cannot establish the current profile. +#[must_use] +pub fn evaluate_request( + grant: &CredentialGrant, + revoked: bool, + context: &RequestContext, + now_unix: u64, + current: Option<&CurrentProfile>, +) -> Decision { + if context.grant_id != grant.grant_id { + return deny(DenyReason::UnknownGrant); + } + if revoked { + return deny(DenyReason::Revoked); + } + let checks = [ + (now_unix >= grant.max_expires_at_unix, DenyReason::Expired), + ( + now_unix >= 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); + } + let Some(current) = current else { + return deny(DenyReason::AuthorityUnavailable); + }; + if let Err(reason) = check_current(&grant.profile, current, now_unix) { + return deny(reason); + } + Decision::Allow(AllowedRequest { + grant_id: grant.grant_id.clone(), + generation: grant.generation, + profile: grant.profile.clone(), + lease_expires_at_unix: grant.lease_expires_at_unix, + }) +} + impl GrantAuthority for LocalGrantAuthority { fn issue<'a>( &'a self, @@ -416,6 +451,7 @@ mod tests { project: ProjectId::new("github:octo/api").unwrap(), effective_policy_sha256: Sha256Digest::of(b"policy"), brokered_services: vec![ServiceId::new("anthropic").unwrap()], + exceptions: Vec::new(), } } diff --git a/crates/sendbox-governance/src/binding.rs b/crates/sendbox-governance/src/binding.rs index 551266c..9b3fd8f 100644 --- a/crates/sendbox-governance/src/binding.rs +++ b/crates/sendbox-governance/src/binding.rs @@ -3,8 +3,9 @@ use std::collections::BTreeSet; use serde::{Deserialize, Serialize}; use crate::{ - CONTRACT_VERSION, GovernanceError, PrincipalId, ProjectId, ServiceId, + CONTRACT_VERSION, ExceptionId, GovernanceError, PrincipalId, ProjectId, ServiceId, digest::{Sha256Digest, canonical_digest}, + exception::MAX_SESSION_EXCEPTIONS, profile::ProfileRef, }; @@ -32,6 +33,10 @@ pub struct GovernanceBinding { pub project: ProjectId, pub effective_policy_sha256: Sha256Digest, pub brokered_services: Vec, + /// Approved exceptions whose denials this session lifted, sorted. Omitted + /// from the canonical form when empty. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub exceptions: Vec, } impl GovernanceBinding { @@ -62,6 +67,13 @@ impl GovernanceBinding { "brokered services must be sorted and unique".to_owned(), )); } + if self.exceptions.len() > MAX_SESSION_EXCEPTIONS + || !self.exceptions.windows(2).all(|pair| pair[0] < pair[1]) + { + return Err(GovernanceError::InvalidBinding(format!( + "exceptions must be sorted, unique, and at most {MAX_SESSION_EXCEPTIONS}" + ))); + } Ok(()) } @@ -96,6 +108,7 @@ mod tests { ServiceId::new("anthropic").unwrap(), ServiceId::new("openai").unwrap(), ], + exceptions: Vec::new(), } } @@ -114,6 +127,21 @@ mod tests { assert_ne!(changed.digest().unwrap(), digest); } + #[test] + fn exceptions_are_bound_only_when_present() { + let original = binding(); + let canonical = serde_json_canonicalizer::to_string(&original).unwrap(); + assert!(!canonical.contains("exceptions")); + let mut excepted = original.clone(); + excepted.exceptions = vec![ + ExceptionId::from_bytes([1; 16]), + ExceptionId::from_bytes([2; 16]), + ]; + assert_ne!(excepted.digest().unwrap(), original.digest().unwrap()); + excepted.exceptions.reverse(); + assert!(excepted.digest().is_err()); + } + #[test] fn unsorted_services_are_rejected() { let mut binding = binding(); diff --git a/crates/sendbox-governance/src/exception.rs b/crates/sendbox-governance/src/exception.rs new file mode 100644 index 0000000..13628a8 --- /dev/null +++ b/crates/sendbox-governance/src/exception.rs @@ -0,0 +1,337 @@ +//! Bounded, expiring policy exceptions. +//! +//! An operator-signed profile lists which of its own denials a project may +//! lift ([`ExceptionPolicy`]). A governance service records requests and +//! approvals for those entries ([`PolicyException`]); a host lifts a denial +//! only for an approved, unexpired exception bound to the exact profile +//! revision it runs under. Lifting a denial never adds a capability: the +//! session must still fit the profile ceiling. + +use serde::{Deserialize, Serialize}; + +use crate::{ + ExceptionId, GovernanceError, PrincipalId, ProjectId, + profile::{Denials, ProfileRef}, +}; + +/// Longest lifetime of one exception, from request to expiry. +pub const MAX_EXCEPTION_TTL_SECONDS: u64 = 7 * 24 * 60 * 60; +pub const MAX_EXCEPTION_REASON_CHARS: usize = 1000; +/// Most exceptions one session binding may carry. +pub const MAX_SESSION_EXCEPTIONS: usize = 32; +const MAX_SCOPE_VALUE_BYTES: usize = 1024; +const DEFAULT_EXCEPTION_TTL_SECONDS: u64 = 24 * 60 * 60; + +/// The profile denial list an exception lifts an entry from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ExceptionKind { + Command, + Domain, + Network, +} + +impl ExceptionKind { + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::Command => "command", + Self::Domain => "domain", + Self::Network => "network", + } + } +} + +/// Exactly one profile denial entry. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExceptionScope { + pub kind: ExceptionKind, + pub value: String, +} + +impl ExceptionScope { + pub fn validate(&self) -> Result<(), GovernanceError> { + if valid_scope_value(&self.value) { + Ok(()) + } else { + Err(GovernanceError::InvalidException(format!( + "scope value must be 1-{MAX_SCOPE_VALUE_BYTES} printable ASCII bytes without leading or trailing spaces" + ))) + } + } +} + +impl std::fmt::Display for ExceptionScope { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(formatter, "{}:{}", self.kind.code(), self.value) + } +} + +/// The operator's opt-in, signed into the profile: the denial entries that an +/// approved exception may lift, and the longest an exception may last. An +/// empty policy permits no exceptions. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ExceptionPolicy { + pub max_ttl_seconds: u64, + pub commands: Vec, + pub domains: Vec, + pub networks: Vec, +} + +impl Default for ExceptionPolicy { + fn default() -> Self { + Self { + max_ttl_seconds: DEFAULT_EXCEPTION_TTL_SECONDS, + commands: Vec::new(), + domains: Vec::new(), + networks: Vec::new(), + } + } +} + +impl ExceptionPolicy { + #[must_use] + pub fn permits(&self, scope: &ExceptionScope) -> bool { + self.entries(scope.kind).contains(&scope.value) + } + + fn entries(&self, kind: ExceptionKind) -> &[String] { + match kind { + ExceptionKind::Command => &self.commands, + ExceptionKind::Domain => &self.domains, + ExceptionKind::Network => &self.networks, + } + } + + pub(crate) fn validate(&self, denials: &Denials, problems: &mut Vec) { + if !(1..=MAX_EXCEPTION_TTL_SECONDS).contains(&self.max_ttl_seconds) { + problems.push(format!( + "exceptions.max_ttl_seconds must be 1..={MAX_EXCEPTION_TTL_SECONDS}" + )); + } + for (kind, denied) in [ + (ExceptionKind::Command, &denials.commands), + (ExceptionKind::Domain, &denials.domains), + (ExceptionKind::Network, &denials.networks), + ] { + let entries = self.entries(kind); + let mut seen = std::collections::BTreeSet::new(); + for entry in entries { + let path = format!("exceptions.{}s", kind.code()); + if !seen.insert(entry) { + problems.push(format!("{path} contains duplicate `{entry}`")); + } else if !valid_scope_value(entry) { + problems.push(format!( + "{path} entries must be 1-{MAX_SCOPE_VALUE_BYTES} printable ASCII bytes" + )); + } else if !denied.contains(entry) { + problems.push(format!( + "{path} entry `{entry}` must also be listed in denials.{}s", + kind.code() + )); + } + } + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ExceptionStatus { + Pending, + Approved, + Rejected, +} + +/// An exception as recorded by a governance service. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PolicyException { + pub id: ExceptionId, + pub project: ProjectId, + /// `None` covers every principal with a role in the project. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub principal: Option, + /// The exact profile revision the exception was reviewed against. + pub profile: ProfileRef, + pub scope: ExceptionScope, + pub reason: String, + pub status: ExceptionStatus, + pub requested_by: PrincipalId, + pub requested_at_unix: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub decided_by: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub decided_at_unix: Option, + pub expires_at_unix: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub revoked_by: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub revoked_at_unix: Option, +} + +impl PolicyException { + /// Whether this exception currently lifts its denial for one session. + #[must_use] + pub fn applies_to( + &self, + project: &ProjectId, + principal: &PrincipalId, + profile: &ProfileRef, + now_unix: u64, + ) -> bool { + self.status == ExceptionStatus::Approved + && self.revoked_at_unix.is_none() + && now_unix < self.expires_at_unix + && &self.project == project + && self + .principal + .as_ref() + .is_none_or(|bound| bound == principal) + && &self.profile == profile + } +} + +/// Validates a free-text exception reason. +pub fn validate_reason(reason: &str) -> Result<(), GovernanceError> { + if reason.trim().is_empty() + || reason.chars().count() > MAX_EXCEPTION_REASON_CHARS + || reason.chars().any(char::is_control) + { + return Err(GovernanceError::InvalidException(format!( + "reason must be 1 to {MAX_EXCEPTION_REASON_CHARS} characters without control characters" + ))); + } + Ok(()) +} + +fn valid_scope_value(value: &str) -> bool { + !value.is_empty() + && value.len() <= MAX_SCOPE_VALUE_BYTES + && value.trim() == value + && value + .bytes() + .all(|byte| byte == b' ' || byte.is_ascii_graphic()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ProfileId, digest::Sha256Digest}; + + fn denials() -> Denials { + Denials { + commands: vec!["git push --force *".to_owned()], + domains: vec!["gist.github.com".to_owned()], + networks: vec!["169.254.0.0/16".to_owned()], + } + } + + #[test] + fn policy_entries_must_be_profile_denials() { + let mut problems = Vec::new(); + ExceptionPolicy { + commands: vec!["git push --force *".to_owned()], + domains: vec!["gist.github.com".to_owned(), "example.com".to_owned()], + ..ExceptionPolicy::default() + } + .validate(&denials(), &mut problems); + assert_eq!(problems.len(), 1, "{problems:?}"); + assert!(problems[0].contains("example.com")); + + let mut problems = Vec::new(); + ExceptionPolicy { + max_ttl_seconds: MAX_EXCEPTION_TTL_SECONDS + 1, + ..ExceptionPolicy::default() + } + .validate(&denials(), &mut problems); + assert!(problems[0].contains("max_ttl_seconds")); + } + + #[test] + fn scopes_match_exact_entries_of_their_kind() { + let policy = ExceptionPolicy { + domains: vec!["gist.github.com".to_owned()], + ..ExceptionPolicy::default() + }; + let scope = |kind, value: &str| ExceptionScope { + kind, + value: value.to_owned(), + }; + assert!(policy.permits(&scope(ExceptionKind::Domain, "gist.github.com"))); + assert!(!policy.permits(&scope(ExceptionKind::Command, "gist.github.com"))); + assert!(!policy.permits(&scope(ExceptionKind::Domain, "*.github.com"))); + assert!( + scope(ExceptionKind::Command, "git push --force *") + .validate() + .is_ok() + ); + assert!(scope(ExceptionKind::Command, " git").validate().is_err()); + assert!(scope(ExceptionKind::Domain, "a\nb").validate().is_err()); + } + + #[test] + fn only_approved_current_matching_exceptions_apply() { + let profile = ProfileRef { + id: ProfileId::new("acme").unwrap(), + revision: 2, + sha256: Sha256Digest::of(b"profile"), + }; + let project = ProjectId::new("github:octo/api").unwrap(); + let alice = PrincipalId::new("oidc:alice@example.com").unwrap(); + let bob = PrincipalId::new("oidc:bob@example.com").unwrap(); + let exception = PolicyException { + id: ExceptionId::from_bytes([1; 16]), + project: project.clone(), + principal: Some(alice.clone()), + profile: profile.clone(), + scope: ExceptionScope { + kind: ExceptionKind::Domain, + value: "gist.github.com".to_owned(), + }, + reason: "release".to_owned(), + status: ExceptionStatus::Approved, + requested_by: alice.clone(), + requested_at_unix: 100, + decided_by: Some(bob.clone()), + decided_at_unix: Some(110), + expires_at_unix: 200, + revoked_by: None, + revoked_at_unix: None, + }; + assert!(exception.applies_to(&project, &alice, &profile, 150)); + assert!(!exception.applies_to(&project, &bob, &profile, 150)); + assert!(!exception.applies_to(&project, &alice, &profile, 200)); + let mut newer = profile.clone(); + newer.revision = 3; + assert!(!exception.applies_to(&project, &alice, &newer, 150)); + let revoked = PolicyException { + revoked_by: Some(bob.clone()), + revoked_at_unix: Some(120), + ..exception.clone() + }; + assert!(!revoked.applies_to(&project, &alice, &profile, 150)); + let pending = PolicyException { + status: ExceptionStatus::Pending, + decided_by: None, + decided_at_unix: None, + ..exception.clone() + }; + assert!(!pending.applies_to(&project, &alice, &profile, 150)); + let project_wide = PolicyException { + principal: None, + ..exception + }; + assert!(project_wide.applies_to(&project, &bob, &profile, 150)); + } + + #[test] + fn reasons_are_bounded_text() { + assert!(validate_reason("Mirror outage during release").is_ok()); + assert!(validate_reason(" ").is_err()); + assert!(validate_reason("line\nbreak").is_err()); + assert!(validate_reason(&"x".repeat(MAX_EXCEPTION_REASON_CHARS + 1)).is_err()); + } +} diff --git a/crates/sendbox-governance/src/identity.rs b/crates/sendbox-governance/src/identity.rs index c3f64cf..2617b6c 100644 --- a/crates/sendbox-governance/src/identity.rs +++ b/crates/sendbox-governance/src/identity.rs @@ -72,6 +72,7 @@ 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"); +string_identifier!(ExceptionId, valid_grant_id, "exception"); impl PrincipalId { /// Identity of a local operating-system account. Increment 1 uses this for @@ -101,12 +102,7 @@ impl ProjectId { /// 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) + Self(format!("path-sha256:{}", lower_hex(&Sha256::digest(path)))) } } @@ -120,12 +116,23 @@ impl SessionRef { 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) + Self(lower_hex(&bytes)) + } +} + +impl ExceptionId { + #[must_use] + pub fn from_bytes(bytes: [u8; GRANT_ID_BYTES]) -> Self { + Self(lower_hex(&bytes)) + } +} + +fn lower_hex(bytes: &[u8]) -> String { + let mut encoded = String::with_capacity(bytes.len() * 2); + for byte in bytes { + encoded.push_str(&format!("{byte:02x}")); } + encoded } fn printable_prefix(value: &str) -> String { @@ -248,6 +255,11 @@ mod tests { assert!(ProfileId::new("").is_err()); assert!(GrantId::new("00".repeat(16)).is_ok()); + assert_eq!( + ExceptionId::from_bytes([0xab; 16]).as_str(), + "ab".repeat(16) + ); + assert!(ExceptionId::new("AB".repeat(16)).is_err()); assert!(GrantId::new("0".repeat(31)).is_err()); assert!(SessionRef::new("AB".repeat(16)).is_err()); } diff --git a/crates/sendbox-governance/src/lib.rs b/crates/sendbox-governance/src/lib.rs index 6c8e548..c5f0a36 100644 --- a/crates/sendbox-governance/src/lib.rs +++ b/crates/sendbox-governance/src/lib.rs @@ -6,9 +6,11 @@ //! identities, signed policy profiles, session bindings, and credential //! grants. It never holds credential material. +pub mod api; pub mod authority; pub mod binding; pub mod digest; +pub mod exception; pub mod grant; pub mod identity; pub mod profile; @@ -17,15 +19,21 @@ use thiserror::Error; pub use authority::{ AuthorityFuture, Clock, CurrentProfile, GrantAuthority, LocalAuthorityLimits, - LocalGrantAuthority, RevisionSource, SystemClock, + LocalGrantAuthority, RevisionSource, SystemClock, check_current, evaluate_request, }; pub use binding::{AuthorityRef, GovernanceBinding}; pub use digest::{Sha256Digest, canonical_digest}; +pub use exception::{ + ExceptionKind, ExceptionPolicy, ExceptionScope, ExceptionStatus, MAX_EXCEPTION_TTL_SECONDS, + PolicyException, +}; 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 identity::{ + ExceptionId, GrantId, PrincipalId, ProfileId, ProjectId, ServiceId, SessionRef, +}; pub use profile::{ BROKERED_CREDENTIAL_PLACEHOLDER, Ceiling, CeilingAction, CredentialProvider, CredentialServiceProfile, GovernanceProfile, PROFILE_FORMAT, PROFILE_VERSION, ProfileRef, @@ -33,7 +41,8 @@ pub use profile::{ }; /// Wire and digest version shared with external governance services. -pub const CONTRACT_VERSION: u32 = 1; +/// Version 2 added policy exceptions to the session binding. +pub const CONTRACT_VERSION: u32 = 2; #[derive(Debug, Error, Clone, PartialEq, Eq)] pub enum GovernanceError { @@ -53,6 +62,8 @@ pub enum GovernanceError { InvalidBinding(String), #[error("invalid credential grant: {0}")] InvalidGrant(String), + #[error("invalid policy exception: {0}")] + InvalidException(String), #[error("credential grant denied: {0}")] Denied(&'static str), #[error("governance authority unavailable: {0}")] diff --git a/crates/sendbox-governance/src/profile.rs b/crates/sendbox-governance/src/profile.rs index cd83254..6fc0865 100644 --- a/crates/sendbox-governance/src/profile.rs +++ b/crates/sendbox-governance/src/profile.rs @@ -11,6 +11,7 @@ use serde::{Deserialize, Serialize}; use crate::{ GovernanceError, ProfileId, ServiceId, digest::Sha256Digest, + exception::{ExceptionPolicy, ExceptionScope}, grant::{validate_method, validate_path_prefix}, }; @@ -57,6 +58,10 @@ pub struct GovernanceProfile { pub credential_services: Vec, #[serde(default)] pub grants: GrantLimits, + /// Denials that an approved, expiring exception may lift. Empty by default, + /// so exceptions require the operator's explicit opt-in. + #[serde(default)] + pub exceptions: ExceptionPolicy, } /// Identity of one exact profile revision. @@ -554,6 +559,12 @@ impl GovernanceProfile { Ok(()) } + /// Whether an exception for `scope` may be requested under this revision. + #[must_use] + pub fn permits_exception(&self, scope: &ExceptionScope) -> bool { + scope.validate().is_ok() && self.exceptions.permits(scope) + } + #[must_use] pub fn credential_service(&self, id: &ServiceId) -> Option<&CredentialServiceProfile> { self.credential_services @@ -596,6 +607,7 @@ impl GovernanceProfile { validate_patterns(&self.denials.networks, "denials.networks", &mut problems); self.validate_credential_services(&mut problems); self.grants.validate(&mut problems); + self.exceptions.validate(&self.denials, &mut problems); if problems.is_empty() { Ok(()) } else { @@ -988,6 +1000,28 @@ credential_services: assert!(GovernanceProfile::parse(unknown.as_bytes()).is_err()); } + #[test] + fn exceptions_require_an_explicit_opt_in_for_listed_denials() { + use crate::exception::ExceptionKind; + let scope = ExceptionScope { + kind: ExceptionKind::Domain, + value: "gist.github.com".to_owned(), + }; + let profile = GovernanceProfile::parse(MINIMAL.as_bytes()).expect("profile"); + assert!(!profile.permits_exception(&scope)); + + let opted_in = format!( + "{MINIMAL}denials:\n domains: [gist.github.com]\nexceptions:\n max_ttl_seconds: 3600\n domains: [gist.github.com]\n" + ); + let profile = GovernanceProfile::parse(opted_in.as_bytes()).expect("profile"); + assert!(profile.permits_exception(&scope)); + assert_eq!(profile.exceptions.max_ttl_seconds, 3600); + + let undeclared = format!("{MINIMAL}exceptions:\n domains: [gist.github.com]\n"); + let error = GovernanceProfile::parse(undeclared.as_bytes()).expect_err("not a denial"); + assert!(error.to_string().contains("denials.domains")); + } + #[test] fn brokered_secret_cannot_also_be_a_workload_secret() { let text = MINIMAL.replace( diff --git a/crates/sendbox-host/src/governance/composition.rs b/crates/sendbox-host/src/governance/composition.rs index f472670..d9e2255 100644 --- a/crates/sendbox-host/src/governance/composition.rs +++ b/crates/sendbox-host/src/governance/composition.rs @@ -13,11 +13,11 @@ 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_governance::{ExceptionKind, ExceptionScope, ServiceId}; use sendbox_policy::{ Action, DnsRecordType, McpServerPolicy, NetworkPolicy, PackageAction, PolicyConfiguration, Protocol, ToolTransport, normalize_mcp_http_endpoint, @@ -58,15 +58,36 @@ impl fmt::Display for Violation { /// 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); +/// +/// Denials named by `lifted` (approved exceptions the profile permits) are +/// skipped. Provider hosts blocked for brokered services are never lifted. +pub fn apply_denials( + profile: &GovernanceProfile, + lifted: &[ExceptionScope], + policy: &mut PolicyConfiguration, +) { + let kept = |kind: ExceptionKind, entries: &[String]| { + entries + .iter() + .filter(|entry| { + !lifted.iter().any(|scope| { + scope.kind == kind && &scope.value == *entry && profile.permits_exception(scope) + }) + }) + .cloned() + .collect::>() + }; + extend_unique( + &mut policy.commands.denylist, + &kept(ExceptionKind::Command, &profile.denials.commands), + ); extend_unique( &mut policy.network.blocked_domains, - &profile.denials.domains, + &kept(ExceptionKind::Domain, &profile.denials.domains), ); extend_unique( &mut policy.network.blocked_networks, - &profile.denials.networks, + &kept(ExceptionKind::Network, &profile.denials.networks), ); let provider_hosts = profile .credential_services @@ -869,6 +890,39 @@ credential_services: .collect() } + #[test] + fn only_permitted_exceptions_lift_profile_denials() { + let text = + format!("{PROFILE}exceptions:\n max_ttl_seconds: 3600\n commands: [\"git push\"]\n"); + let profile = GovernanceProfile::parse(text.as_bytes()).expect("profile"); + let scope = |kind, value: &str| ExceptionScope { + kind, + value: value.to_owned(), + }; + let mut policy = configuration().policy; + apply_denials( + &profile, + &[ + scope(ExceptionKind::Command, "git push"), + scope(ExceptionKind::Domain, "pastebin.com"), + scope(ExceptionKind::Domain, "api.anthropic.com"), + ], + &mut policy, + ); + assert!(!policy.commands.denylist.contains(&"git push".to_owned())); + for blocked in ["pastebin.com", "api.anthropic.com"] { + assert!( + policy.network.blocked_domains.contains(&blocked.to_owned()), + "{blocked} is not liftable" + ); + } + + let mut configuration = configuration(); + configuration.policy.commands.allowlist = vec!["git push".to_owned()]; + configuration.policy.commands.denylist = policy.commands.denylist; + assert!(check(&profile, &configuration, &facts()).is_empty()); + } + #[test] fn narrowed_configuration_is_admitted() { let violations = check(&profile(), &configuration(), &facts()); @@ -880,8 +934,8 @@ credential_services: let profile = profile(); let mut policy = configuration().policy; let before = policy.clone(); - apply_denials(&profile, &mut policy); - apply_denials(&profile, &mut policy); + apply_denials(&profile, &[], &mut policy); + apply_denials(&profile, &[], &mut policy); assert!( before .network diff --git a/crates/sendbox-host/src/governance/fleet.rs b/crates/sendbox-host/src/governance/fleet.rs new file mode 100644 index 0000000..f0ea429 --- /dev/null +++ b/crates/sendbox-host/src/governance/fleet.rs @@ -0,0 +1,794 @@ +//! Client for a shared governance service (`sendbox-fleet`). +//! +//! The service authenticates the caller with a bearer token from the host +//! secret store, enforces project roles and exceptions at admission, and acts +//! as the grant authority. Every failure is explicit: an unreachable or +//! refusing service denies admission and brokered requests, and never falls +//! back to the local authority or to credential delivery. + +use std::time::Duration; + +use reqwest::{Method, StatusCode, Url, header}; +use sendbox_governance::api::{ + CallerIdentity, ExceptionList, RevokeGrantRequest, SessionAdmission, SessionAdmissionRequest, + SessionEnd, SessionOutcome, +}; +use sendbox_governance::{ + AuthorityFuture, CredentialGrant, Decision, DenyReason, GovernanceBinding, GovernanceError, + GrantAuthority, GrantId, GrantRequest, PolicyException, ProjectId, RequestContext, + RevocationReason, SessionRef, +}; +use sendbox_secrets::SecretValue; +use serde::Serialize; +use serde::de::DeserializeOwned; +use zeroize::Zeroizing; + +use super::operator::FleetSettings; +use crate::HostError; + +const MAX_DETAIL_CHARS: usize = 300; + +/// Why a fleet call failed. `detail` never contains the bearer token. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct FleetError { + pub(crate) status: Option, + pub(crate) detail: String, +} + +impl std::fmt::Display for FleetError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.status { + Some(status) => write!(formatter, "HTTP {status}: {}", self.detail), + None => formatter.write_str(&self.detail), + } + } +} + +impl From for HostError { + fn from(error: FleetError) -> Self { + Self::Governance(format!("governance service: {error}")) + } +} + +impl From for GovernanceError { + fn from(error: FleetError) -> Self { + Self::AuthorityUnavailable(error.to_string()) + } +} + +pub(crate) struct FleetClient { + client: reqwest::Client, + base: Url, + token: Zeroizing, +} + +impl std::fmt::Debug for FleetClient { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("FleetClient") + .field("base", &self.base.as_str()) + .finish_non_exhaustive() + } +} + +impl FleetClient { + pub(crate) fn new(settings: &FleetSettings, token: &SecretValue) -> Result { + let base = settings.base_url()?; + let token = Zeroizing::new( + std::str::from_utf8(token.expose_secret()) + .map_err(|_| { + HostError::Governance(format!( + "fleet token `{}` is not UTF-8", + settings.token_secret + )) + })? + .trim() + .to_owned(), + ); + let valid_token = !token.is_empty() + && token + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"-._~+/=".contains(&byte)); + if !valid_token { + return Err(HostError::Governance(format!( + "fleet token `{}` is not a bearer token", + settings.token_secret + ))); + } + let client = reqwest::Client::builder() + .https_only(base.scheme() == "https") + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(settings.timeout_seconds)) + .build() + .map_err(|error| HostError::Governance(format!("build fleet client: {error}")))?; + Ok(Self { + client, + base, + token, + }) + } + + fn url(&self, path: &str) -> Url { + let mut url = self.base.clone(); + let prefix = self.base.path().trim_end_matches('/'); + url.set_path(&format!("{prefix}{path}")); + url + } + + async fn call( + &self, + method: Method, + path: &str, + query: &[(&str, &str)], + body: Option<&(dyn erased::Body + Sync)>, + ) -> Result, FleetError> { + let mut url = self.url(path); + if !query.is_empty() { + url.query_pairs_mut().extend_pairs(query); + } + let mut bearer = header::HeaderValue::from_str(&format!("Bearer {}", *self.token)) + .map_err(|_| FleetError { + status: None, + detail: "fleet token cannot be sent as a header".to_owned(), + })?; + bearer.set_sensitive(true); + let mut request = self + .client + .request(method, url) + .header(header::AUTHORIZATION, bearer) + .header(header::ACCEPT, "application/json"); + if let Some(body) = body { + request = request + .header(header::CONTENT_TYPE, "application/json") + .body(body.to_json().map_err(|error| FleetError { + status: None, + detail: format!("encode request: {error}"), + })?); + } + let response = request.send().await.map_err(|error| FleetError { + status: None, + detail: format!( + "request failed: {}", + error + .without_url() + .to_string() + .replace(self.token.as_str(), "***") + ), + })?; + let status = response.status(); + let bytes = response.bytes().await.map_err(|error| FleetError { + status: Some(status.as_u16()), + detail: format!("read response: {}", error.without_url()), + })?; + if !status.is_success() { + return Err(FleetError { + status: Some(status.as_u16()), + detail: problem_detail(status, &bytes), + }); + } + if status == StatusCode::NO_CONTENT || bytes.is_empty() { + return Ok(None); + } + serde_json::from_slice(&bytes) + .map(Some) + .map_err(|error| FleetError { + status: Some(status.as_u16()), + detail: format!("unexpected response body: {error}"), + }) + } + + async fn call_required( + &self, + method: Method, + path: &str, + query: &[(&str, &str)], + body: Option<&(dyn erased::Body + Sync)>, + ) -> Result { + self.call(method, path, query, body) + .await? + .ok_or_else(|| FleetError { + status: None, + detail: "the service returned an empty response".to_owned(), + }) + } + + pub(crate) async fn whoami(&self) -> Result { + self.call_required(Method::GET, "/v1/whoami", &[], None) + .await + } + + /// Approved exceptions currently active for `project`. + pub(crate) async fn active_exceptions( + &self, + project: &ProjectId, + ) -> Result, FleetError> { + let list: ExceptionList = self + .call_required( + Method::GET, + "/v1/exceptions", + &[("project", project.as_str()), ("state", "active")], + None, + ) + .await?; + Ok(list.exceptions) + } + + pub(crate) async fn admit( + &self, + session: &SessionRef, + binding: &GovernanceBinding, + ) -> Result { + let admission: SessionAdmission = self + .call_required( + Method::POST, + "/v1/sessions:admit", + &[], + Some(&SessionAdmissionRequest { + session: session.clone(), + binding: binding.clone(), + }), + ) + .await?; + let expected = binding.digest().map_err(|error| FleetError { + status: None, + detail: error.to_string(), + })?; + if &admission.session != session || admission.binding_sha256 != expected { + return Err(FleetError { + status: None, + detail: "the service admitted a different session or binding".to_owned(), + }); + } + Ok(admission) + } + + pub(crate) async fn end( + &self, + session: &SessionRef, + outcome: SessionOutcome, + ) -> Result<(), FleetError> { + self.call::( + Method::POST, + &format!("/v1/sessions/{session}:end"), + &[], + Some(&SessionEnd { outcome }), + ) + .await + .map(drop) + } +} + +/// The shared service as the session's grant authority. +pub(crate) struct FleetGrantAuthority { + client: std::sync::Arc, +} + +impl FleetGrantAuthority { + pub(crate) const fn new(client: std::sync::Arc) -> Self { + Self { client } + } +} + +impl GrantAuthority for FleetGrantAuthority { + fn issue<'a>( + &'a self, + request: GrantRequest, + ) -> AuthorityFuture<'a, Result> { + Box::pin(async move { + let grant: CredentialGrant = self + .client + .call_required(Method::POST, "/v1/grants", &[], Some(&request)) + .await?; + grant.validate()?; + let matches = grant.principal == request.principal + && grant.project == request.project + && grant.session == request.session + && grant.service == request.service + && grant.binding_sha256 == request.binding.digest()? + && grant.profile == request.binding.profile + && grant.methods.is_subset(&request.methods) + && grant + .path_prefixes + .iter() + .all(|prefix| request.path_prefixes.contains(prefix)); + if matches { + Ok(grant) + } else { + Err(GovernanceError::InvalidGrant( + "the service issued a grant outside the request".to_owned(), + )) + } + }) + } + + fn authorize<'a>(&'a self, context: &'a RequestContext) -> AuthorityFuture<'a, Decision> { + Box::pin(async move { + match self + .client + .call_required::(Method::POST, "/v1/authorize", &[], Some(context)) + .await + { + Ok(Decision::Allow(allowed)) if allowed.grant_id != context.grant_id => { + Decision::Deny { + reason: DenyReason::AuthorityUnavailable, + } + } + Ok(decision) => decision, + Err(_) => Decision::Deny { + reason: DenyReason::AuthorityUnavailable, + }, + } + }) + } + + fn renew<'a>( + &'a self, + grant: &'a GrantId, + ) -> AuthorityFuture<'a, Result> { + Box::pin(async move { + let renewed: CredentialGrant = self + .client + .call_required( + Method::POST, + &format!("/v1/grants/{grant}:renew"), + &[], + None, + ) + .await?; + renewed.validate()?; + if &renewed.grant_id == grant { + Ok(renewed) + } else { + Err(GovernanceError::InvalidGrant( + "the service renewed a different grant".to_owned(), + )) + } + }) + } + + fn revoke<'a>( + &'a self, + grant: &'a GrantId, + reason: RevocationReason, + ) -> AuthorityFuture<'a, Result<(), GovernanceError>> { + Box::pin(async move { + self.client + .call::( + Method::POST, + &format!("/v1/grants/{grant}:revoke"), + &[], + Some(&RevokeGrantRequest { reason }), + ) + .await?; + Ok(()) + }) + } +} + +/// Extracts a bounded, printable `detail` from an RFC 9457 problem body. +fn problem_detail(status: StatusCode, bytes: &[u8]) -> String { + let detail = serde_json::from_slice::(bytes) + .ok() + .and_then(|value| value.get("detail")?.as_str().map(str::to_owned)) + .unwrap_or_else(|| { + status + .canonical_reason() + .unwrap_or("request refused") + .to_owned() + }); + detail + .chars() + .filter(|character| !character.is_control()) + .take(MAX_DETAIL_CHARS) + .collect() +} + +/// Object-safe JSON bodies so one request path serves every payload type. +mod erased { + pub(super) trait Body { + fn to_json(&self) -> Result, serde_json::Error>; + } + + impl Body for T { + fn to_json(&self) -> Result, serde_json::Error> { + serde_json::to_vec(self) + } + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + use std::net::SocketAddr; + use std::sync::{Arc, Mutex}; + + use sendbox_governance::api::{CallerKind, SessionOutcome}; + use sendbox_governance::{ + ExceptionId, ExceptionKind, ExceptionScope, ExceptionStatus, PrincipalId, ProfileRef, + ServiceId, Sha256Digest, + }; + use sendbox_secrets::SecretStore; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + use super::super::operator::tests::{Fixture, fixture, protected_test_tree, write_private}; + use super::super::operator::{DEFAULT_FLEET_TOKEN_SECRET, FleetSettings}; + use super::super::tests::{ + FakeStore, brokered_profile, configuration, no_secret_store, prepare, run_for, + }; + use super::*; + + const TOKEN: &str = "sbf_synthetic-test-token"; + const ALICE: &str = "oidc:alice@example.com"; + + #[derive(Debug, Clone)] + struct Recorded { + method: String, + target: String, + authorization: Option, + body: Vec, + } + + type Handler = dyn Fn(&Recorded) -> (u16, String) + Send + Sync; + + /// A loopback HTTP/1.1 stand-in for the governance service. + async fn serve(handler: Arc) -> (SocketAddr, Arc>>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let address = listener.local_addr().expect("address"); + let recorded = Arc::new(Mutex::new(Vec::new())); + let log = Arc::clone(&recorded); + tokio::spawn(async move { + while let Ok((mut stream, _)) = listener.accept().await { + let handler = Arc::clone(&handler); + let log = Arc::clone(&log); + tokio::spawn(async move { + let mut buffer = Vec::new(); + let mut chunk = [0_u8; 4096]; + let header_end = loop { + let read = stream.read(&mut chunk).await.unwrap_or(0); + if read == 0 { + return; + } + buffer.extend_from_slice(&chunk[..read]); + if let Some(position) = + buffer.windows(4).position(|window| window == b"\r\n\r\n") + { + break position + 4; + } + }; + let head = String::from_utf8_lossy(&buffer[..header_end]).to_string(); + let mut lines = head.split("\r\n"); + let mut request_line = lines.next().unwrap_or_default().split(' '); + let method = request_line.next().unwrap_or_default().to_owned(); + let target = request_line.next().unwrap_or_default().to_owned(); + let headers = lines + .filter_map(|line| line.split_once(':')) + .map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_owned())) + .collect::>(); + let length = headers + .get("content-length") + .and_then(|value| value.parse::().ok()) + .unwrap_or(0); + let mut body = buffer[header_end..].to_vec(); + while body.len() < length { + let read = stream.read(&mut chunk).await.unwrap_or(0); + if read == 0 { + break; + } + body.extend_from_slice(&chunk[..read]); + } + let request = Recorded { + method, + target, + authorization: headers.get("authorization").cloned(), + body, + }; + let (status, payload) = handler(&request); + log.lock().unwrap().push(request); + let content_type = if status >= 400 { + "application/problem+json" + } else { + "application/json" + }; + let location = if status == 307 { + "Location: http://127.0.0.1:9/elsewhere\r\n" + } else { + "" + }; + let response = format!( + "HTTP/1.1 {status} X\r\nContent-Type: {content_type}\r\n{location}Content-Length: {}\r\nConnection: close\r\n\r\n{payload}", + payload.len() + ); + let _ = stream.write_all(response.as_bytes()).await; + }); + } + }); + (address, recorded) + } + + fn fleet_profile() -> String { + format!( + "{}denials:\n domains: [gist.github.com, pastebin.com]\nexceptions:\n max_ttl_seconds: 3600\n domains: [gist.github.com]\n", + brokered_profile() + ) + } + + fn use_fleet(fixture: &Fixture, address: SocketAddr) { + let mut operator = fixture.source.load().expect("operator"); + operator.authority = "fleet.example.com".to_owned(); + operator.fleet = Some(FleetSettings { + url: format!("http://{address}"), + token_secret: DEFAULT_FLEET_TOKEN_SECRET.to_owned(), + timeout_seconds: 5, + }); + write_private( + &fixture.source.path, + serde_yaml_ng::to_string(&operator).unwrap().as_bytes(), + ); + } + + fn token_store() -> Result, HostError> { + Ok(Arc::new(FakeStore(BTreeMap::from([( + DEFAULT_FLEET_TOKEN_SECRET, + TOKEN, + )])))) + } + + fn exception( + byte: u8, + principal: Option<&str>, + profile: &ProfileRef, + value: &str, + expires_at_unix: u64, + ) -> PolicyException { + PolicyException { + id: ExceptionId::from_bytes([byte; 16]), + project: ProjectId::github("acme", "app").unwrap(), + principal: principal.map(|principal| PrincipalId::new(principal).unwrap()), + profile: profile.clone(), + scope: ExceptionScope { + kind: ExceptionKind::Domain, + value: value.to_owned(), + }, + reason: "synthetic".to_owned(), + status: ExceptionStatus::Approved, + requested_by: PrincipalId::new(ALICE).unwrap(), + requested_at_unix: 1, + decided_by: Some(PrincipalId::new("oidc:bob@example.com").unwrap()), + decided_at_unix: Some(2), + expires_at_unix, + revoked_by: None, + revoked_at_unix: None, + } + } + + fn json(value: &impl Serialize) -> String { + serde_json::to_string(value).unwrap() + } + + #[tokio::test] + async fn fleet_mode_authenticates_the_caller_and_lifts_only_applicable_exceptions() { + if !protected_test_tree() { + return; + } + let profile_text = fleet_profile(); + let profile = + sendbox_governance::profile::GovernanceProfile::parse(profile_text.as_bytes()) + .unwrap() + .reference(profile_text.as_bytes()); + let mut stale = profile.clone(); + stale.revision -= 1; + let later = super::super::tests::now_unix() + 3_000; + let exceptions = vec![ + exception(1, Some(ALICE), &profile, "gist.github.com", later - 100), + exception(2, None, &profile, "gist.github.com", later), + exception( + 3, + Some("oidc:bob@example.com"), + &profile, + "pastebin.com", + later, + ), + exception(4, None, &profile, "pastebin.com", later), + exception(5, None, &stale, "gist.github.com", later + 100), + ]; + let handler: Arc = Arc::new(move |request: &Recorded| { + match (request.method.as_str(), request.target.as_str()) { + ("GET", "/v1/whoami") => ( + 200, + json(&CallerIdentity { + principal: PrincipalId::new(ALICE).unwrap(), + kind: CallerKind::User, + operator: false, + }), + ), + ("GET", "/v1/exceptions?project=github%3Aacme%2Fapp&state=active") => ( + 200, + json(&ExceptionList { + exceptions: exceptions.clone(), + }), + ), + ("POST", "/v1/sessions:admit") => { + let admission: SessionAdmissionRequest = + serde_json::from_slice(&request.body).unwrap(); + ( + 200, + json(&SessionAdmission { + binding_sha256: admission.binding.digest().unwrap(), + session: admission.session, + admitted_at_unix: 10, + }), + ) + } + ("POST", target) if target.ends_with(":end") => (204, String::new()), + _ => (404, r#"{"detail":"no route"}"#.to_owned()), + } + }); + let (address, recorded) = serve(handler).await; + let fixture = fixture(&profile_text, 1); + use_fleet(&fixture, address); + let mut configuration = configuration(&["anthropic"]); + configuration + .policy + .network + .allowed_domains + .push("gist.github.com".to_owned()); + + let session = prepare(&fixture, &mut configuration, &token_store) + .await + .expect("prepare"); + assert_eq!(session.principal.as_str(), ALICE); + let ids = session + .exceptions + .iter() + .map(|exception| exception.id.clone()) + .collect::>(); + assert_eq!(ids, [ExceptionId::from_bytes([2; 16])]); + let blocked = &configuration.policy.network.blocked_domains; + assert!(!blocked.contains(&"gist.github.com".to_owned())); + assert!(blocked.contains(&"pastebin.com".to_owned())); + assert!(blocked.contains(&"api.anthropic.com".to_owned())); + assert_eq!( + session.exception_deadline().map(|e| e.expires_at_unix), + Some(later) + ); + + let run = run_for(session, &configuration); + assert_eq!(run.binding.principal.as_str(), ALICE); + assert_eq!(run.binding.exceptions, ids); + assert_eq!(run.binding.authority.id, "fleet.example.com"); + run.admit_remote().await.expect("admitted"); + run.end_remote(SessionOutcome::Completed) + .await + .expect("ended"); + + let requests = recorded.lock().unwrap().clone(); + assert_eq!(requests.len(), 4); + assert!( + requests + .iter() + .all(|request| request.authorization.as_deref() == Some(&format!("Bearer {TOKEN}"))) + ); + let admitted: SessionAdmissionRequest = + serde_json::from_slice(&requests[2].body).expect("admission body"); + assert_eq!(admitted.binding, run.binding); + assert_eq!(admitted.session, run.session_ref); + assert_eq!( + requests[3].body, br#"{"outcome":"completed"}"#, + "{}", + requests[3].target + ); + } + + #[tokio::test] + async fn fleet_failures_deny_explicitly_without_fallback() { + if !protected_test_tree() { + return; + } + let handler: Arc = Arc::new(|request: &Recorded| { + match (request.method.as_str(), request.target.as_str()) { + ("GET", "/v1/whoami") => ( + 401, + r#"{"detail":"bearer token was not accepted"}"#.to_owned(), + ), + ("POST", "/v1/authorize") => (307, String::new()), + ("POST", "/v1/sessions:admit") => ( + 200, + json(&SessionAdmission { + session: SessionRef::new("ab".repeat(16)).unwrap(), + binding_sha256: Sha256Digest::of(b"other"), + admitted_at_unix: 1, + }), + ), + _ => (503, r#"{"detail":"unavailable"}"#.to_owned()), + } + }); + let (address, _) = serve(handler).await; + let fixture = fixture(&fleet_profile(), 1); + use_fleet(&fixture, address); + + let error = prepare(&fixture, &mut configuration(&[]), &no_secret_store) + .await + .err() + .expect("no secret store"); + assert!(error.to_string().contains("no secret store"), "{error}"); + let empty = || -> Result, HostError> { + Ok(Arc::new(FakeStore(BTreeMap::new()))) + }; + let error = prepare(&fixture, &mut configuration(&[]), &empty) + .await + .err() + .expect("missing token"); + assert!(error.to_string().contains("sendbox secrets add"), "{error}"); + let error = prepare(&fixture, &mut configuration(&[]), &token_store) + .await + .err() + .expect("rejected token"); + assert!(error.to_string().contains("HTTP 401"), "{error}"); + assert!(!error.to_string().contains(TOKEN)); + let mut leaking = configuration(&[]); + leaking.secrets.push(DEFAULT_FLEET_TOKEN_SECRET.to_owned()); + let error = prepare(&fixture, &mut leaking, &token_store) + .await + .err() + .expect("token as workload secret"); + assert!(error.to_string().contains("workload secret"), "{error}"); + + let settings = FleetSettings { + url: format!("http://{address}"), + token_secret: DEFAULT_FLEET_TOKEN_SECRET.to_owned(), + timeout_seconds: 5, + }; + let client = Arc::new( + FleetClient::new(&settings, &SecretValue::try_from(TOKEN).unwrap()).expect("client"), + ); + assert!(FleetClient::new(&settings, &SecretValue::try_from("bad token").unwrap()).is_err()); + let authority = FleetGrantAuthority::new(Arc::clone(&client)); + let context = RequestContext { + grant_id: GrantId::from_bytes([9; 16]), + principal: PrincipalId::new(ALICE).unwrap(), + project: ProjectId::github("acme", "app").unwrap(), + session: SessionRef::new("ab".repeat(16)).unwrap(), + binding_sha256: Sha256Digest::of(b"binding"), + service: ServiceId::new("anthropic").unwrap(), + method: "POST".to_owned(), + path: "/v1/messages".to_owned(), + }; + assert_eq!( + authority.authorize(&context).await, + Decision::Deny { + reason: DenyReason::AuthorityUnavailable + }, + "a redirect is never followed" + ); + assert!(matches!( + authority.renew(&context.grant_id).await, + Err(GovernanceError::AuthorityUnavailable(message)) if message.contains("HTTP 503") + )); + + let binding = GovernanceBinding { + contract_version: sendbox_governance::CONTRACT_VERSION, + authority: sendbox_governance::AuthorityRef { + id: "fleet.example.com".to_owned(), + trust_sha256: Sha256Digest::of(b"trust"), + }, + profile: ProfileRef { + id: sendbox_governance::ProfileId::new("acme").unwrap(), + revision: 4, + sha256: Sha256Digest::of(b"profile"), + }, + principal: PrincipalId::new(ALICE).unwrap(), + project: ProjectId::github("acme", "app").unwrap(), + effective_policy_sha256: Sha256Digest::of(b"policy"), + brokered_services: Vec::new(), + exceptions: Vec::new(), + }; + let error = client + .admit(&SessionRef::new("ab".repeat(16)).unwrap(), &binding) + .await + .expect_err("mismatched admission"); + assert!(error.detail.contains("different session or binding")); + } +} diff --git a/crates/sendbox-host/src/governance/mod.rs b/crates/sendbox-host/src/governance/mod.rs index 1ed35f8..53f4842 100644 --- a/crates/sendbox-host/src/governance/mod.rs +++ b/crates/sendbox-host/src/governance/mod.rs @@ -2,30 +2,36 @@ //! binding, and brokered credential grants. pub mod composition; +pub(crate) mod fleet; pub mod operator; pub(crate) mod relay; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; +use std::sync::Arc; 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::api::SessionOutcome; +use sendbox_governance::exception::MAX_SESSION_EXCEPTIONS; use sendbox_governance::profile::{CredentialServiceProfile, RuntimeKind}; use sendbox_governance::{ - CONTRACT_VERSION, GovernanceBinding, PrincipalId, ProjectId, ServiceId, SessionRef, - Sha256Digest, + CONTRACT_VERSION, ExceptionScope, GovernanceBinding, PolicyException, PrincipalId, ProjectId, + ServiceId, SessionRef, Sha256Digest, }; +use sendbox_secrets::{SecretName, SecretStore}; 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, + DEFAULT_FLEET_TOKEN_SECRET, FleetSettings, GovernanceMode, GovernanceSource, + MANAGED_CONFIGURATION_PATH, OperatorConfiguration, SIGNATURES_FORMAT, VerifiedProfile, + encode_signatures, verify_profile, }; use crate::HostError; @@ -36,13 +42,23 @@ pub(crate) struct GovernedSession { pub(crate) source: GovernanceSource, pub(crate) verified: VerifiedProfile, pub(crate) principal: PrincipalId, + operator: OperatorConfiguration, + project: Option, + /// Approved exceptions whose denials this session lifts, sorted by id. + pub(crate) exceptions: Vec, + pub(crate) fleet: Option>, } +/// Opens the host secret store that holds the caller's fleet token. +pub(crate) type SecretStoreOpener<'a> = + &'a (dyn Fn() -> Result, HostError> + Sync); + impl GovernedSession { - /// Discovers, loads, and verifies governance, then applies profile - /// denials to `configuration`. Returns `None` for standalone sessions. + /// Discovers, loads, and verifies governance. Returns `None` for + /// standalone sessions. Profile denials are applied later by + /// [`Self::apply`], once the project is known. pub(crate) fn prepare( - configuration: &mut SandboxConfiguration, + configuration: &SandboxConfiguration, managed_path: &Path, opt_in: Option<&Path>, bundle: BundleSelection<'_>, @@ -70,15 +86,84 @@ impl GovernedSession { 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), + operator, + project: None, + exceptions: Vec::new(), + fleet: None, })) } + /// Binds the project and applies the profile denials to `configuration`. + /// + /// With a shared governance service, the service first authenticates the + /// caller (who becomes the session principal) and reports the project's + /// active exceptions. Only approved exceptions bound to this exact profile + /// revision, for this principal or the whole project, and permitted by the + /// profile, lift a denial. The ceiling check still applies afterwards. + pub(crate) async fn apply( + &mut self, + configuration: &mut SandboxConfiguration, + project: ProjectId, + open_secrets: SecretStoreOpener<'_>, + now_unix: u64, + ) -> Result<(), HostError> { + if let Some(settings) = &self.operator.fleet { + if configuration + .secrets + .iter() + .any(|name| name.eq_ignore_ascii_case(&settings.token_secret)) + { + return Err(HostError::Governance(format!( + "the fleet token `{}` can never be a workload secret", + settings.token_secret + ))); + } + let token = open_secrets()? + .retrieve(&SecretName::new(settings.token_secret.clone())?) + .map_err(|error| { + HostError::Governance(format!( + "fleet token `{0}` is unavailable in the host secret store ({error}); add it with `sendbox secrets add {0}`", + settings.token_secret + )) + })?; + let client = Arc::new(fleet::FleetClient::new(settings, &token.value)?); + let caller = client.whoami().await?; + let active = client.active_exceptions(&project).await?; + self.exceptions = select_exceptions( + active, + &project, + &caller.principal, + &self.verified, + now_unix, + )?; + self.principal = caller.principal; + self.fleet = Some(client); + } + let lifted = self + .exceptions + .iter() + .map(|exception| exception.scope.clone()) + .collect::>(); + composition::apply_denials(&self.verified.profile, &lifted, &mut configuration.policy); + self.project = Some(project); + configuration + .validate() + .map_err(|error| HostError::Invalid(error.to_string())) + } + + /// The earliest expiry among lifted exceptions. The session must stop + /// then, because its egress and command rules are fixed at start. + pub(crate) fn exception_deadline(&self) -> Option<&PolicyException> { + self.exceptions + .iter() + .min_by_key(|exception| exception.expires_at_unix) + } + /// Rejects the session unless its effective configuration stays within /// the profile. pub(crate) fn admit( @@ -102,10 +187,12 @@ impl GovernedSession { pub(crate) fn binding( &self, - project: ProjectId, effective_policy_sha256: &str, configuration: &SandboxConfiguration, ) -> Result { + let project = self.project.clone().ok_or_else(|| { + HostError::Governance("governance denials were not applied".to_owned()) + })?; let mut brokered_services = composition::selected_services(&self.verified.profile, configuration) .map_err(HostError::Governance)? @@ -122,6 +209,11 @@ impl GovernedSession { effective_policy_sha256: Sha256Digest::parse_hex(effective_policy_sha256) .map_err(operator::governance_error)?, brokered_services, + exceptions: self + .exceptions + .iter() + .map(|exception| exception.id.clone()) + .collect(), }; binding.validate().map_err(operator::governance_error)?; Ok(binding) @@ -192,6 +284,40 @@ pub(crate) fn relay_environment( .collect() } +/// Picks the exceptions a session lifts: for each permitted scope, the +/// applicable exception that lasts longest. Sorted by id for the binding. +fn select_exceptions( + active: Vec, + project: &ProjectId, + principal: &PrincipalId, + verified: &VerifiedProfile, + now_unix: u64, +) -> Result, HostError> { + let mut by_scope = BTreeMap::::new(); + for exception in active { + if !exception.applies_to(project, principal, &verified.reference, now_unix) + || !verified.profile.permits_exception(&exception.scope) + { + continue; + } + let replace = by_scope.get(&exception.scope).is_none_or(|kept| { + (exception.expires_at_unix, std::cmp::Reverse(&exception.id)) + > (kept.expires_at_unix, std::cmp::Reverse(&kept.id)) + }); + if replace { + by_scope.insert(exception.scope.clone(), exception); + } + } + if by_scope.len() > MAX_SESSION_EXCEPTIONS { + return Err(HostError::Governance(format!( + "more than {MAX_SESSION_EXCEPTIONS} policy exceptions apply to this session" + ))); + } + let mut selected = by_scope.into_values().collect::>(); + selected.sort_by(|left, right| left.id.cmp(&right.id)); + Ok(selected) +} + /// An admitted governed run: the verified profile plus the exact binding /// signed into the boundary plan. pub(crate) struct GovernedRun { @@ -218,6 +344,35 @@ impl GovernedRun { }) } + /// Registers the session with the shared governance service, which + /// checks the caller's project role, the profile revision, and every + /// bound exception. A local authority has nothing to register. + pub(crate) async fn admit_remote(&self) -> Result<(), HostError> { + if let Some(client) = &self.session.fleet { + client.admit(&self.session_ref, &self.binding).await?; + } + Ok(()) + } + + /// Tells the shared governance service that the session ended, which + /// revokes any grant it still holds. + pub(crate) async fn end_remote(&self, outcome: SessionOutcome) -> Result<(), HostError> { + if let Some(client) = &self.session.fleet { + client.end(&self.session_ref, outcome).await?; + } + Ok(()) + } + + pub(crate) fn authority( + &self, + local: impl FnOnce() -> Arc, + ) -> Arc { + match &self.session.fleet { + Some(client) => Arc::new(fleet::FleetGrantAuthority::new(Arc::clone(client))), + None => local(), + } + } + pub(crate) fn attach_brokered( &mut self, services: Vec, @@ -264,6 +419,31 @@ impl GovernedRun { ]) } + /// Records a session stopped because a lifted exception expired. + pub(crate) fn record_exception_expiry( + &self, + audit: &AuditRecorder, + exception: &PolicyException, + ) -> Result<(), HostError> { + let mut metadata = self.audit_metadata(); + metadata.extend([ + ("exception".to_owned(), exception.id.to_string()), + ("scope".to_owned(), exception.scope.to_string()), + ( + "expires_at_unix".to_owned(), + exception.expires_at_unix.to_string(), + ), + ]); + record_audit( + audit, + AuditCategory::Policy, + "governance.exception.expired", + &self.session_ref.to_string(), + AuditResult::Denied, + metadata, + ) + } + pub(crate) fn record_admission(&self, audit: &AuditRecorder) -> Result<(), HostError> { let mut metadata = self.audit_metadata(); metadata.insert( @@ -297,6 +477,32 @@ impl GovernedRun { .collect::>() .join(","), ); + if let Some(settings) = &self.session.operator.fleet { + metadata.insert("authority_url".to_owned(), settings.url.clone()); + } + if !self.session.exceptions.is_empty() { + metadata.insert( + "exceptions".to_owned(), + self.binding + .exceptions + .iter() + .map(ToString::to_string) + .collect::>() + .join(","), + ); + } + for exception in &self.session.exceptions { + let key = |field: &str| format!("exception.{}.{field}", exception.id); + metadata.insert(key("scope"), exception.scope.to_string()); + metadata.insert(key("requested_by"), exception.requested_by.to_string()); + if let Some(approver) = &exception.decided_by { + metadata.insert(key("approved_by"), approver.to_string()); + } + metadata.insert( + key("expires_at_unix"), + exception.expires_at_unix.to_string(), + ); + } record_audit( audit, AuditCategory::Policy, @@ -447,7 +653,7 @@ pub fn check(request: GovernanceCheckRequest) -> Result Result); + + 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() + } + } + + pub(crate) fn no_secret_store() -> Result, HostError> { + Err(HostError::Invalid( + "no secret store in this test".to_owned(), + )) + } + + pub(crate) async fn prepare( fixture: &Fixture, configuration: &mut SandboxConfiguration, - ) -> GovernedSession { - GovernedSession::prepare( + open_secrets: SecretStoreOpener<'_>, + ) -> Result { + let mut session = 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") + )? + .expect("governed"); + session + .apply( + configuration, + ProjectId::github("acme", "app").expect("project"), + open_secrets, + now_unix(), + ) + .await?; + Ok(session) } - pub(crate) fn admitted_run( + pub(crate) async fn admitted_run( fixture: &Fixture, configuration: &mut SandboxConfiguration, ) -> GovernedRun { - let session = prepare(fixture, configuration); + let session = prepare(fixture, configuration, &no_secret_store) + .await + .expect("prepare"); + run_for(session, configuration) + } + + pub(crate) fn run_for( + session: GovernedSession, + configuration: &SandboxConfiguration, + ) -> GovernedRun { let facts = SessionFacts { runtime: RuntimeKind::Apple, image: None, @@ -606,11 +889,7 @@ credential_services: }; session.admit(configuration, &facts).expect("admit"); let binding = session - .binding( - ProjectId::github("acme", "app").expect("project"), - &"ab".repeat(32), - configuration, - ) + .binding(&"ab".repeat(32), configuration) .expect("binding"); GovernedRun::new(session, binding, SessionId::from_bytes([7; 16])).expect("run") } @@ -620,14 +899,14 @@ credential_services: let directory = private_directory(); let managed = directory.path().join("absent.yaml"); let state = directory.path().join("state"); - let mut standalone = configuration(&[]); + let standalone = configuration(&[]); assert!( - GovernedSession::prepare(&mut standalone, &managed, None, bundle(), &state, 0) + GovernedSession::prepare(&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) + let brokered = configuration(&["anthropic"]); + let error = GovernedSession::prepare(&brokered, &managed, None, bundle(), &state, 0) .err() .expect("brokered services without governance are rejected"); assert!( @@ -668,14 +947,14 @@ credential_services: ); } - #[test] - fn governed_session_binds_admission_and_brokered_services() { + #[tokio::test] + async 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); + let run = admitted_run(&fixture, &mut configuration).await; for host in ["api.anthropic.com", "api.openai.com"] { assert!( configuration diff --git a/crates/sendbox-host/src/governance/operator.rs b/crates/sendbox-host/src/governance/operator.rs index 507cc33..d87c0f1 100644 --- a/crates/sendbox-host/src/governance/operator.rs +++ b/crates/sendbox-host/src/governance/operator.rs @@ -32,6 +32,9 @@ 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"; +const MAX_FLEET_TIMEOUT_SECONDS: u64 = 60; +/// Default host secret-store name holding the caller's fleet bearer token. +pub const DEFAULT_FLEET_TOKEN_SECRET: &str = "SENDBOX_FLEET_TOKEN"; /// How governance was selected for this host. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] @@ -111,6 +114,63 @@ pub struct OperatorConfiguration { pub bundle: Option, #[serde(default = "default_revision_cache_seconds")] pub revision_cache_seconds: u64, + /// Shared governance service. When set, it authenticates the caller, + /// enforces project roles and exceptions, and replaces the local grant + /// authority. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fleet: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct FleetSettings { + /// `https://` base URL of the service. Plain `http://` is accepted only + /// for a loopback host. + pub url: String, + /// Host secret-store name holding the caller's bearer token. + #[serde(default = "default_fleet_token_secret")] + pub token_secret: String, + #[serde(default = "default_fleet_timeout_seconds")] + pub timeout_seconds: u64, +} + +impl FleetSettings { + pub fn base_url(&self) -> Result { + let invalid = |message: &str| { + HostError::Governance(format!("operator configuration: fleet.url {message}")) + }; + let url = reqwest::Url::parse(&self.url).map_err(|error| invalid(&error.to_string()))?; + let loopback = match url.host() { + Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), + Some(url::Host::Ipv4(address)) => address.is_loopback(), + Some(url::Host::Ipv6(address)) => address.is_loopback(), + None => false, + }; + if !(url.scheme() == "https" || (url.scheme() == "http" && loopback)) { + return Err(invalid("must use https (http only for a loopback host)")); + } + if !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + { + return Err(invalid( + "must not contain credentials, a query, or a fragment", + )); + } + if url.path() != "/" && url.path().ends_with('/') { + return Err(invalid("must not end with `/` after a path")); + } + Ok(url) + } +} + +fn default_fleet_token_secret() -> String { + DEFAULT_FLEET_TOKEN_SECRET.to_owned() +} + +const fn default_fleet_timeout_seconds() -> u64 { + 10 } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -216,6 +276,20 @@ impl OperatorConfiguration { { return invalid("bundle pins require at least one trust root digest and id"); } + if let Some(fleet) = &self.fleet { + fleet.base_url()?; + if self.authority == "local" { + return invalid("a fleet authority needs its own `authority` id, not `local`"); + } + if !sendbox_governance::profile::valid_secret_name(&fleet.token_secret) { + return invalid("fleet.token_secret must be a valid secret name"); + } + if !(1..=MAX_FLEET_TIMEOUT_SECONDS).contains(&fleet.timeout_seconds) { + return invalid(&format!( + "fleet.timeout_seconds must be 1..={MAX_FLEET_TIMEOUT_SECONDS}" + )); + } + } self.trust_store()?; Ok(()) } @@ -605,6 +679,7 @@ credential_services: }, bundle: None, revision_cache_seconds: 1, + fleet: None, } } @@ -767,6 +842,40 @@ credential_services: )); } + #[test] + fn fleet_settings_require_a_dedicated_authority_and_a_safe_url() { + let key = SigningKeyMaterial::generate().unwrap(); + let mut operator = test_operator( + key.identity("Operator", None, 0, None), + PathBuf::from("/governance/acme.yaml"), + 1, + ); + let parse = |operator: &OperatorConfiguration| { + OperatorConfiguration::parse(serde_yaml_ng::to_string(operator).unwrap().as_bytes()) + }; + operator.fleet = Some(FleetSettings { + url: "https://fleet.example.com".to_owned(), + token_secret: DEFAULT_FLEET_TOKEN_SECRET.to_owned(), + timeout_seconds: 10, + }); + assert!(parse(&operator).is_err(), "local authority id with a fleet"); + operator.authority = "fleet.example.com".to_owned(); + assert!(parse(&operator).is_ok()); + for (url, accepted) in [ + ("https://fleet.example.com/governance", true), + ("http://127.0.0.1:8080", true), + ("http://localhost:8080", true), + ("http://fleet.example.com", false), + ("https://user:pass@fleet.example.com", false), + ("https://fleet.example.com/?x=1", false), + ("https://fleet.example.com/governance/", false), + ("ftp://fleet.example.com", false), + ] { + operator.fleet.as_mut().unwrap().url = url.to_owned(); + assert_eq!(parse(&operator).is_ok(), accepted, "{url}"); + } + } + #[test] fn bundle_pins_are_enforced() { let directory = private_directory(); diff --git a/crates/sendbox-host/src/governance/relay.rs b/crates/sendbox-host/src/governance/relay.rs index ac7ff78..9fd4446 100644 --- a/crates/sendbox-host/src/governance/relay.rs +++ b/crates/sendbox-host/src/governance/relay.rs @@ -245,24 +245,26 @@ impl HostCredentialRelay { 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(), + let authority = run.authority(|| { + Arc::new(LocalGrantAuthority::new( + Arc::new(OperatorRevisionSource::new( + run.session.source.clone(), + Arc::new(SystemClock), + )), 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) - }), - )); + 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(); @@ -510,66 +512,12 @@ impl CredentialRelayHandler for HostCredentialRelay { #[cfg(test)] mod tests { use sendbox_core::SessionId; - use sendbox_secrets::{ - CredentialMasker, RecordVersion, Secret, SecretMetadata, SecretStoreError, - }; + use sendbox_secrets::CredentialMasker; use super::super::operator::tests::{fixture, protected_test_tree}; - use super::super::tests::{admitted_run, brokered_profile, configuration}; + use super::super::tests::{FakeStore, 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"; @@ -622,7 +570,7 @@ mod tests { } let fixture = fixture(&brokered_profile(), 1); let mut configuration = configuration(&["anthropic", "openai"]); - let run = admitted_run(&fixture, &mut configuration); + let run = admitted_run(&fixture, &mut configuration).await; let services = run .session .brokered_services(&configuration) diff --git a/crates/sendbox-host/src/lib.rs b/crates/sendbox-host/src/lib.rs index 13b3901..91a008d 100644 --- a/crates/sendbox-host/src/lib.rs +++ b/crates/sendbox-host/src/lib.rs @@ -545,8 +545,8 @@ pub async fn prepare(mut request: HostRunRequest) -> Result Result Result Result repository, + None => discover_selected_repository(&request.configuration, &project_source)?, + }; let credentials = prepare_effective_credentials(&request.configuration, selected_repository.as_ref()).await?; credentials.apply_to(&mut request.configuration); @@ -723,8 +736,7 @@ pub async fn prepare(mut request: HostRunRequest) -> Result Result Result tokio::task::JoinHandle { + tokio::spawn(async move { + let remaining = expires_at_unix.saturating_sub(unix_time().unwrap_or(u64::MAX)); + tokio::select! { + () = outer.cancelled() => { + run.cancel(); + false + } + () = tokio::time::sleep(Duration::from_secs(remaining)) => { + eprintln!("sendbox: a policy exception for this session expired; stopping the session"); + run.cancel(); + true + } + } + }) +} + async fn execute_runtime( inputs: RuntimeInputs, audit: AuditRecorder, @@ -1031,20 +1069,49 @@ async fn execute_runtime( orchestrator = orchestrator.with_credential_relay(relay.clone()); } let session_id = plan.session_id(); - let agent = orchestrator.run(&plan, cancellation).await; - if let Some(relay) = &credential_relay { - let reason = match &agent { - Ok(_) => sendbox_governance::RevocationReason::SessionCompleted, + let deadline = governance + .as_ref() + .and_then(|run| run.session.exception_deadline().cloned()); + let (agent, expired) = match deadline { + Some(exception) => { + let run_cancellation = CancellationToken::new(); + let watcher = watch_exception_deadline( + cancellation.clone(), + run_cancellation.clone(), + exception.expires_at_unix, + ); + let agent = orchestrator.run(&plan, &run_cancellation).await; + watcher.abort(); + let expired = watcher.await.unwrap_or(false); + (agent, expired.then_some(exception)) + } + None => (orchestrator.run(&plan, cancellation).await, None), + }; + if let Some(run) = &governance { + let outcome = match &agent { + Ok(_) => sendbox_governance::api::SessionOutcome::Completed, Err(failure) if matches!(failure.primary, sendbox_agent::AgentError::Cancelled) => { - sendbox_governance::RevocationReason::SessionCancelled + sendbox_governance::api::SessionOutcome::Cancelled } - Err(_) => sendbox_governance::RevocationReason::SessionFailed, + Err(_) => sendbox_governance::api::SessionOutcome::Failed, }; - let finished = relay.finish(reason).await; - if let (Ok(_), Err(error)) = (&agent, finished) { - return Err(error); + let mut finished = Ok(()); + if let Some(relay) = &credential_relay { + finished = relay.finish(outcome.revocation_reason()).await; + } + let ended = run.end_remote(outcome).await; + if let Some(exception) = &expired { + run.record_exception_expiry(&audit, exception)?; + return Err(HostError::Governance(format!( + "policy exception {} ({}) expired at {}; the session was stopped", + exception.id, exception.scope, exception.expires_at_unix + ))); + } + if agent.is_ok() { + finished?; + ended?; } } let agent = agent.map_err(HostError::AgentRun)?; diff --git a/docs/architecture/governed-sessions.md b/docs/architecture/governed-sessions.md index 6b4b6b0..1bf4081 100644 --- a/docs/architecture/governed-sessions.md +++ b/docs/architecture/governed-sessions.md @@ -1,14 +1,22 @@ # 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. +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. +Two authorities are supported: + +- **Local** (single host): the host verifies the profile and runs the grant + authority in process. The principal is the local OS account. +- **Shared** ([`sendbox-fleet`](https://github.com/mbianchidev/sendbox-fleet)): + an authenticated, multi-user service enforces project-scoped roles, approves + bounded, expiring exceptions, admits sessions, issues and checks grants, and + keeps a central, hash-chained audit log. See + [shared governance service](#shared-governance-service). + +Both share the [`sendbox-governance`](../../crates/sendbox-governance) +contract crate (contract version 2). ```mermaid flowchart LR @@ -69,6 +77,10 @@ bundle: # optional: pin the guest bundle trust root trust_root_ids: [external-release-root] minimum_release_sequence: 7 revision_cache_seconds: 30 +fleet: # optional: use a shared governance service + url: https://fleet.acme.example + token_secret: SENDBOX_FLEET_TOKEN # host secret holding the caller's token + timeout_seconds: 10 ``` - `trust` builds a provenance trust store with `allow_unsigned: false`. At @@ -83,6 +95,11 @@ revision_cache_seconds: 30 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. +- `fleet` selects the [shared governance service](#shared-governance-service) + as the authority. `authority` must then equal the service's + `FLEET_AUTHORITY_ID` and cannot be `local`. `url` must use `https://`; + plain `http://` is accepted only for a loopback host. `timeout_seconds` is + 1 to 60. 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 @@ -153,10 +170,16 @@ grants: max_ttl_seconds: 28800 revocation_grace_seconds: 5 max_concurrent_streams: 8 +exceptions: # optional: denials an approved exception may lift + max_ttl_seconds: 86400 # at most 7 days + commands: [] + domains: [pastebin.com] # each entry must also be listed in denials + networks: [] ``` Omitted ceiling sections take their most restrictive value. Unknown fields are -rejected. +rejected. An omitted `exceptions` section permits no exceptions; see +[exceptions](#exceptions). ### Signing workflow @@ -210,11 +233,13 @@ Observability settings are not capabilities and are not compared. `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. +effective policy SHA-256, the brokered service ids, and the ids of any +exceptions the session lifted (omitted when there are none). 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. A local authority uses `local-user:` as the +principal; a shared service uses the principal it authenticated. The project +is `github:/` (or a workspace path digest). ## Brokered credentials @@ -270,7 +295,7 @@ tells the host so it closes the upstream connection. ## Grants and revocation -At session start the local grant authority issues one grant per brokered +At session start the 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: @@ -306,13 +331,82 @@ Records join the existing signed session audit chain: | `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 | +| `governance.exception.expired` | a lifted exception expired and the session was stopped | Each record carries principal, project, session, authority, profile id, -revision and digest, effective policy digest, and binding digest. Request +revision and digest, effective policy digest, and binding digest. The +admission record also lists each lifted exception with its scope, requester, +approver, and expiry, and the service URL when a shared service is used. 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. +## Shared governance service + +With `fleet` in the operator configuration, the host uses +[`sendbox-fleet`](https://github.com/mbianchidev/sendbox-fleet) as its +authority. The profile is still read from `profile_path` and verified against +the operator's `trust` signers on the host; the service separately verifies the +same signed bytes when an operator publishes them, and only admits sessions +bound to its current revision. + +```mermaid +sequenceDiagram + participant H as SendBox host (caller's token) + participant F as sendbox-fleet + H->>F: GET /v1/whoami + F-->>H: principal (becomes the session principal) + H->>F: GET /v1/exceptions?project=…&state=active + Note over H: lift only approved exceptions for this principal,
project, and exact profile revision; check the ceiling + H->>F: POST /v1/sessions:admit (session, binding) + Note over F: caller = binding principal, role ≥ member,
current revision, every exception still valid + H->>F: POST /v1/grants · /v1/authorize · :renew + H->>F: POST /v1/sessions/{id}:end (revokes remaining grants) +``` + +- **Authentication.** The caller stores their bearer token in the host + secret store (`sendbox secrets add SENDBOX_FLEET_TOKEN`, or the name in + `token_secret`). It is sent only to the configured URL, redirects are never + followed, system proxies are ignored, and it can never be a workload secret. +- **Identity.** The authenticated principal, not the local account, is the + session principal. The service refuses a binding whose principal is not the + caller, so a host cannot claim another identity. +- **Roles.** Admission needs the `member` role or higher in the project. + Roles, exceptions, and audit are managed through the service; see its + [architecture](https://github.com/mbianchidev/sendbox-fleet/blob/main/docs/architecture.md). +- **Grants.** The service is the grant authority. Every brokered request is + authorized by the service; any non-200 answer, timeout, or unreachable + service denies with `authority_unavailable`. Nothing falls back to the + local authority or to credential delivery. +- **End.** After the workload ends, the host revokes its grants and ends the + session on the service, which revokes any grant still live. + +### Exceptions + +An exception lifts exactly one profile denial for a project, or for one +principal in it, until it expires (at most 7 days). Only denials the operator +listed under the profile's `exceptions` section can be lifted, so the +operator's signed opt-in bounds every exception. Lifting a denial never adds a +capability: the session must still fit the ceiling, and provider hosts blocked +for brokered services are never lifted. + +A project member requests an exception against the current profile revision; +a different principal with the `owner` or `admin` role approves it. The host +lifts a denial only for an approved, unrevoked, unexpired exception bound to +the exact revision it runs under, binds its id into the signed boundary plan, +and the service re-checks it at admission. A new revision or a raised minimum +revision makes the approval stale, so it can no longer admit sessions. + +Egress and command rules are fixed when the VM starts, so the host stops the +session when the earliest lifted exception expires +(`governance.exception.expired`, exit code `6`). Like any failed run, the +workspace is rolled back to its starting snapshot, so request an expiry that +covers the work. Grants are capped at that +expiry, and once an exception is revoked the service denies the session's +brokered requests and lease renewals with `stale_policy`. Revocation does not +reach into the VM's egress rules: a revoked exception's lifted denial stays +lifted until the session ends or the exception's original expiry stops it. + ## Trust boundaries and residual risks - The local user who owns the host secret store can still read their own @@ -327,6 +421,14 @@ failure to record relay evidence fails the run. 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. +- A shared service that is compromised can authorize misuse but never sees + provider keys; the host broker keeps them. A compromised host is limited to + sessions and grants issued to the principals whose tokens it holds. +- The fleet token is a bearer credential for its principal. Keep token + lifetimes short; revoke tokens and disable principals in the service. +- `sendbox governance check` evaluates the local profile only and does not + consult the service for exceptions. + +Non-goals: Kubernetes or fleet scheduling, universal TLS interception, formal +policy verification, model API translation, and replacing isolation +providers. diff --git a/docs/architecture/session-security-lifecycle.md b/docs/architecture/session-security-lifecycle.md index 2433ff4..248f6b7 100644 --- a/docs/architecture/session-security-lifecycle.md +++ b/docs/architecture/session-security-lifecycle.md @@ -100,4 +100,6 @@ failures remain visible. 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. +relay evidence fails the run. A session that lifted a policy exception is +stopped when the exception expires, which follows the normal cancellation and +rollback path. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 121754d..a14bdf8 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -75,7 +75,10 @@ See [network grants](configuration.md#network-grants). | `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`. +configuration exits with code `6`. `check` evaluates the local profile only; +with a [shared governance service](architecture/governed-sessions.md#shared-governance-service), +store your service token with `sendbox secrets add SENDBOX_FLEET_TOKEN` before +`sendbox run`. ## Examples