From 5b7583bc8794a8cd0c918a93acb10e60ecef2a55 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 00:06:06 +0100 Subject: [PATCH 1/5] Share one host GitHub Meta cache across sessions Every sandbox gateway fetched https://api.github.com/meta anonymously before readiness, so each session cost one or two requests against GitHub's 60-per-hour-per-IP limit and busy hosts started failing with 403. The host now keeps one file-locked, ETag-revalidated cache in the private runtime state root (at most about one request per hour per machine), backs off after failures until the published rate-limit reset, and reuses the last validated document while it has at least 15 minutes of its 24-hour lifetime left. The validated response travels to the guest as a seed in bootstrap schema v5; gateways revalidate and install it without any network I/O, and the guest refresh task is removed because executions are capped at 300 seconds. The seed digest is bound into the signed network_github_meta admission, and rate limits surface as a typed error with the reset time. --- Cargo.lock | 1 + README.md | 5 +- Tests/qualification/inventory.v1.json | 4 +- crates/sendbox-bootstrap/src/lib.rs | 92 ++- crates/sendbox-cli/src/main.rs | 1 + crates/sendbox-egress/Cargo.toml | 1 + crates/sendbox-egress/src/gateway.rs | 57 +- crates/sendbox-egress/src/github_meta.rs | 617 +++++++----------- .../sendbox-egress/src/github_meta_client.rs | 322 +++++---- crates/sendbox-egress/src/policy.rs | 68 +- crates/sendbox-egress/src/runtime.rs | 16 + .../tests/github_meta_integration.rs | 226 +++---- crates/sendbox-host/src/github_meta.rs | 429 ++++++++++++ crates/sendbox-host/src/lib.rs | 206 +++++- crates/sendbox-host/src/security.rs | 1 + crates/sendbox-runtime-apple/src/provider.rs | 4 + crates/sendbox-runtime-kata/src/lib.rs | 4 + docs/architecture/egress-enforcement.md | 87 ++- docs/configuration.md | 57 +- guest/sendbox-guest/src/bootstrap.rs | 1 + guest/sendbox-guest/src/egress.rs | 66 +- guest/sendbox-guest/src/supervisor.rs | 1 + 22 files changed, 1438 insertions(+), 828 deletions(-) create mode 100644 crates/sendbox-host/src/github_meta.rs diff --git a/Cargo.lock b/Cargo.lock index 414db9d..0d0ee48 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2627,6 +2627,7 @@ name = "sendbox-egress" version = "0.2.6" dependencies = [ "async-trait", + "base64", "bytes", "cap-std", "clap", diff --git a/README.md b/README.md index 6a4a1f2..712c1a4 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,9 @@ controls must be ready before the agent starts. An unavailable provider or unsupported capability is an error, **not a fallback to running on the host**. Network grants support explicit subdomain wildcards. On Apple and Kata, an exact -`github.com` grant also includes periodically refreshed official GitHub Meta -domains and IPv4/IPv6 CIDRs, including shared-cloud ranges. See +`github.com` grant also includes official GitHub Meta domains and IPv4/IPv6 +CIDRs, including shared-cloud ranges. The host caches them for all sessions and +revalidates at most hourly, keeping within GitHub's anonymous rate limit. See [network scope, outages, and provenance](docs/configuration.md#network-grants). ## Supported coding agents diff --git a/Tests/qualification/inventory.v1.json b/Tests/qualification/inventory.v1.json index 0bcfdd5..f70cf8e 100644 --- a/Tests/qualification/inventory.v1.json +++ b/Tests/qualification/inventory.v1.json @@ -48,9 +48,9 @@ {"id":"module.rust-bootstrap","category":"source_module","name":"Rust authenticated guest bootstrap contract","disposition":"preserve","rationale":"Retain one typed, bounded, versioned bootstrap schema shared by host providers and the guest, with exact secret length, fresh nonce and broker authentication, hardening declarations, and fail-closed decoding.","evidence":["crates/sendbox-bootstrap/src/lib.rs#typed guest bootstrap schema encoding and decoding"],"target_crate":"sendbox-bootstrap","target_phase":7,"conformance":{"status":"implemented","fixture_ids":["runtime.contracts","known-defects.negative"],"compatibility_note":"Apple injects the inner document directly; Kata retains a provider-specific outer envelope for trust-root delivery."}}, {"id":"module.rust-boundary","category":"source_module","name":"Rust signed runtime boundary plans","disposition":"redesign","rationale":"Resolve runtime selection and immutable execution declarations into a bounded canonical plan signed by the local host identity before provider dispatch.","evidence":["crates/sendbox-boundary/src/lib.rs#BoundaryPlan SignedBoundaryPlan and fail-closed runtime selection","crates/sendbox-host/src/lib.rs#prepare verifies the plan before provider construction","crates/sendbox-bootstrap/src/lib.rs#boundary_plan_digest binding","crates/sendbox-protocol/src/handshake.rs#authenticated boundary digest negotiation","crates/sendbox-host/src/lib.rs#boundary drift and feature binding tests"],"target_crate":"sendbox-boundary","target_phase":10,"conformance":{"status":"implemented","fixture_ids":["runtime.contracts","known-defects.negative","persisted.formats"],"compatibility_note":"The signed plan contains only bounded hashes and declarations; its digest is bound through create, bootstrap, control-channel provisioning, and authenticated guest handshake."}}, {"id":"module.rust-bundle","category":"source_module","name":"Rust signed guest artifact bundles","disposition":"preserve","rationale":"Retain deterministic artifact staging, canonical guest-compatible manifests, external-key Ed25519 signing, inventory and SPDX SBOM generation, and pre-launch verification.","evidence":["crates/sendbox-bundle/src/lib.rs#staging signing inventory SBOM and verification","crates/sendbox-bundle/src/main.rs#sendbox-bundle CLI"],"target_crate":"sendbox-bundle","target_phase":7,"conformance":{"status":"implemented","fixture_ids":["persisted.formats","runtime.contracts","known-defects.negative"],"compatibility_note":"Runtime trust-root provisioning and adapter wiring remain intentionally separate."}}, - {"id":"module.rust-egress","category":"source_module","name":"Rust production egress enforcement","disposition":"preserve","rationale":"Retain fail-closed policy compilation, authenticated runtime identity, DNS and CONNECT/SOCKS5/HTTP brokers, validated expiring GitHub Meta delegation, bounded remote-MCP origin reservations, exfiltration budgets, authorization and rebinding defenses, and Linux cgroup-v2/SO_MARK/nftables enforcement.","evidence":["crates/sendbox-egress/src/address.rs#address classification","crates/sendbox-egress/src/audit.rs#audit events","crates/sendbox-egress/src/authorization.rs#authorization and rebinding defense","crates/sendbox-egress/src/bin/harness.rs#live qualification harness","crates/sendbox-egress/src/connect_broker.rs#CONNECT broker","crates/sendbox-egress/src/connect_proto.rs#CONNECT protocol","crates/sendbox-egress/src/dialer.rs#authorized dialer","crates/sendbox-egress/src/dns_broker.rs#DNS broker","crates/sendbox-egress/src/dns_budget.rs#exfiltration budget","crates/sendbox-egress/src/domain.rs#domain normalization","crates/sendbox-egress/src/fixture_resolver.rs#fixture resolver","crates/sendbox-egress/src/forwarding_resolver.rs#forwarding resolver","crates/sendbox-egress/src/gateway.rs#egress gateway","crates/sendbox-egress/src/github_meta.rs#validated atomic expiring Meta snapshots and refresh lifecycle","crates/sendbox-egress/src/github_meta_client.rs#fixed anonymous HTTPS exact-IP transport","crates/sendbox-egress/src/http_proxy.rs#bounded HTTP CONNECT and forward proxy framing","crates/sendbox-egress/src/lib.rs#public exports","crates/sendbox-egress/src/linux/cgroup.rs#descriptor-safe cgroup identity","crates/sendbox-egress/src/linux/mark.rs#SO_MARK identity","crates/sendbox-egress/src/linux/mod.rs#Linux enforcement exports","crates/sendbox-egress/src/linux/nft.rs#atomic nftables ownership","crates/sendbox-egress/src/linux/preflight.rs#enforcement preflight","crates/sendbox-egress/src/linux/supervisor.rs#Linux enforcement supervisor","crates/sendbox-egress/src/origin.rs#OriginReservations","crates/sendbox-egress/src/policy.rs#network policy compilation","crates/sendbox-egress/src/resolver.rs#resolver contract","crates/sendbox-egress/src/runtime.rs#EgressRuntimePolicy and execution cgroup identity","crates/sendbox-egress/src/socks5.rs#SOCKS5 broker"],"target_crate":"sendbox-egress","target_phase":7,"conformance":{"status":"implemented","fixture_ids":["policy.decisions","runtime.contracts","known-defects.negative"],"compatibility_note":null}}, + {"id":"module.rust-egress","category":"source_module","name":"Rust production egress enforcement","disposition":"preserve","rationale":"Retain fail-closed policy compilation, authenticated runtime identity, DNS and CONNECT/SOCKS5/HTTP brokers, validated expiring GitHub Meta delegation, bounded remote-MCP origin reservations, exfiltration budgets, authorization and rebinding defenses, and Linux cgroup-v2/SO_MARK/nftables enforcement.","evidence":["crates/sendbox-egress/src/address.rs#address classification","crates/sendbox-egress/src/audit.rs#audit events","crates/sendbox-egress/src/authorization.rs#authorization and rebinding defense","crates/sendbox-egress/src/bin/harness.rs#live qualification harness","crates/sendbox-egress/src/connect_broker.rs#CONNECT broker","crates/sendbox-egress/src/connect_proto.rs#CONNECT protocol","crates/sendbox-egress/src/dialer.rs#authorized dialer","crates/sendbox-egress/src/dns_broker.rs#DNS broker","crates/sendbox-egress/src/dns_budget.rs#exfiltration budget","crates/sendbox-egress/src/domain.rs#domain normalization","crates/sendbox-egress/src/fixture_resolver.rs#fixture resolver","crates/sendbox-egress/src/forwarding_resolver.rs#forwarding resolver","crates/sendbox-egress/src/gateway.rs#egress gateway","crates/sendbox-egress/src/github_meta.rs#validated atomic expiring Meta snapshots installed from host seeds","crates/sendbox-egress/src/github_meta_client.rs#host-side fixed anonymous HTTPS exact-IP transport with rate-limit detection","crates/sendbox-egress/src/http_proxy.rs#bounded HTTP CONNECT and forward proxy framing","crates/sendbox-egress/src/lib.rs#public exports","crates/sendbox-egress/src/linux/cgroup.rs#descriptor-safe cgroup identity","crates/sendbox-egress/src/linux/mark.rs#SO_MARK identity","crates/sendbox-egress/src/linux/mod.rs#Linux enforcement exports","crates/sendbox-egress/src/linux/nft.rs#atomic nftables ownership","crates/sendbox-egress/src/linux/preflight.rs#enforcement preflight","crates/sendbox-egress/src/linux/supervisor.rs#Linux enforcement supervisor","crates/sendbox-egress/src/origin.rs#OriginReservations","crates/sendbox-egress/src/policy.rs#network policy compilation","crates/sendbox-egress/src/resolver.rs#resolver contract","crates/sendbox-egress/src/runtime.rs#EgressRuntimePolicy and execution cgroup identity","crates/sendbox-egress/src/socks5.rs#SOCKS5 broker"],"target_crate":"sendbox-egress","target_phase":7,"conformance":{"status":"implemented","fixture_ids":["policy.decisions","runtime.contracts","known-defects.negative"],"compatibility_note":null}}, {"id":"module.rust-registry","category":"source_module","name":"Rust package registry proxy","disposition":"redesign","rationale":"Provide fail-closed package resolution, trusted upstream access, integrity and provenance verification, archive inspection, deterministic policy evaluation, content-addressed caching, and bounded security reports behind ecosystem-neutral adapter contracts.","evidence":["crates/sendbox-registry/src/adapter.rs#registry adapter contracts","crates/sendbox-registry/src/cache.rs#content-addressed package cache","crates/sendbox-registry/src/client.rs#SOCKS-routed upstream client","crates/sendbox-registry/src/engine.rs#deterministic package policy evaluation","crates/sendbox-registry/src/lib.rs#public exports","crates/sendbox-registry/src/model.rs#ecosystem-neutral registry models","crates/sendbox-registry/src/npm.rs#npm metadata integrity and signature verification","crates/sendbox-registry/src/provenance.rs#offline npm Sigstore provenance verification","crates/sendbox-registry/src/report.rs#bounded package security reports","crates/sendbox-registry/src/scanner.rs#non-executing archive inspection","crates/sendbox-registry/src/service.rs#loopback registry proxy service"],"target_crate":"sendbox-registry","target_phase":10,"conformance":{"status":"implemented","fixture_ids":["policy.decisions","runtime.contracts","known-defects.negative"],"compatibility_note":"npm is the first production adapter; PyPI, Cargo, Go modules, Maven, and OCI reuse capability-oriented contracts without inheriting npm-specific metadata or archive assumptions."}}, - {"id":"module.rust-host","category":"source_module","name":"Rust authenticated host runtime composition","disposition":"preserve","rationale":"Retain verified boundary-plan preparation, capability-aware provider dispatch, authenticated security-service composition, session lifecycle enforcement, cleanup aggregation, package-report persistence, and post-runtime Safe Outputs processing.","evidence":["crates/sendbox-host/src/lib.rs#prepare PreparedHostRun and provider-neutral runtime composition","crates/sendbox-host/src/security.rs#host session security lifecycle and package report persistence","crates/sendbox-host/src/safe_outputs.rs#host-only verification ledger GitHub writer and isolated pull-request transport"],"target_crate":"sendbox-host","target_phase":10,"conformance":{"status":"implemented","fixture_ids":["runtime.contracts","policy.decisions","persisted.formats","known-defects.negative"],"compatibility_note":null}}, + {"id":"module.rust-host","category":"source_module","name":"Rust authenticated host runtime composition","disposition":"preserve","rationale":"Retain verified boundary-plan preparation, capability-aware provider dispatch, authenticated security-service composition, session lifecycle enforcement, cleanup aggregation, package-report persistence, shared GitHub Meta seeding, and post-runtime Safe Outputs processing.","evidence":["crates/sendbox-host/src/lib.rs#prepare PreparedHostRun and provider-neutral runtime composition","crates/sendbox-host/src/security.rs#host session security lifecycle and package report persistence","crates/sendbox-host/src/safe_outputs.rs#host-only verification ledger GitHub writer and isolated pull-request transport","crates/sendbox-host/src/github_meta.rs#machine-wide file-locked GitHub Meta cache seeding guest gateways"],"target_crate":"sendbox-host","target_phase":10,"conformance":{"status":"implemented","fixture_ids":["runtime.contracts","policy.decisions","persisted.formats","known-defects.negative"],"compatibility_note":null}}, {"id":"module.rust-security","category":"source_module","name":"Rust security records foundation","disposition":"preserve","rationale":"Retain descriptor-relative persistence, canonical records, Merkle audit integrity, Ed25519 provenance and trust policies, versioned snapshots, and legacy Swift readers.","evidence":["crates/sendbox-security/src/audit.rs#audit records and Merkle tree","crates/sendbox-security/src/canonical.rs#canonical JSON","crates/sendbox-security/src/error.rs#SecurityError","crates/sendbox-security/src/fs.rs#descriptor-relative persistence","crates/sendbox-security/src/legacy.rs#legacy Swift readers","crates/sendbox-security/src/lib.rs#public exports","crates/sendbox-security/src/provenance.rs#Ed25519 provenance and trust policy","crates/sendbox-security/src/snapshot.rs#versioned snapshots"],"target_crate":"sendbox-security","target_phase":9,"conformance":{"status":"implemented","fixture_ids":["persisted.formats"],"compatibility_note":null}}, {"id":"module.rust-secrets","category":"source_module","name":"Rust secrets and credential foundation","disposition":"preserve","rationale":"Retain typed credential scope, authenticated envelopes, versioned records, and platform-specific secure storage foundations.","evidence":["crates/sendbox-secrets/src/credential.rs#credential scope","crates/sendbox-secrets/src/envelope.rs#authenticated envelope","crates/sendbox-secrets/src/error.rs#SecretsError","crates/sendbox-secrets/src/lib.rs#public exports","crates/sendbox-secrets/src/linux.rs#Linux secure store","crates/sendbox-secrets/src/macos.rs#macOS secure store","crates/sendbox-secrets/src/record.rs#versioned secret record","crates/sendbox-secrets/src/types.rs#secret types"],"target_crate":"sendbox-secrets","target_phase":9,"conformance":{"status":"implemented","fixture_ids":["policy.decisions","persisted.formats"],"compatibility_note":null}}, {"id":"module.rust-credentials","category":"source_module","name":"Rust production credential broker and guarded GitHub auth","disposition":"preserve","rationale":"Retain explicit loopback credential endpoints, strict bounded HTTP/1.1 parsing, pinned certificate-verifying HTTPS forwarding, repository-scope authorization, exact-shape gh metadata execution, cancellation, redaction, and session-bound configuration.","evidence":["crates/sendbox-credentials/src/broker.rs#CredentialBroker","crates/sendbox-credentials/src/config.rs#BrokerConfiguration","crates/sendbox-credentials/src/error.rs#CredentialBrokerError","crates/sendbox-credentials/src/github.rs#GitHubMetadataClient","crates/sendbox-credentials/src/http1.rs#ParsedRequest","crates/sendbox-credentials/src/lib.rs#public exports","crates/sendbox-credentials/src/session.rs#SessionCredentialConfiguration","crates/sendbox-credentials/src/upstream.rs#PinnedHttpsTransport"],"target_crate":"sendbox-credentials","target_phase":9,"conformance":{"status":"implemented","fixture_ids":["policy.decisions","runtime.contracts","known-defects.negative"],"compatibility_note":"The broker requires agents to use explicit per-rule HTTP base URLs; transparent TLS interception and CONNECT credential injection are intentionally unsupported."}}, diff --git a/crates/sendbox-bootstrap/src/lib.rs b/crates/sendbox-bootstrap/src/lib.rs index 65f4def..f898f5e 100644 --- a/crates/sendbox-bootstrap/src/lib.rs +++ b/crates/sendbox-bootstrap/src/lib.rs @@ -5,6 +5,7 @@ use std::fmt; use std::path::{Component, Path, PathBuf}; use sendbox_core::{BoundaryPlanDigest, SessionId}; +use sendbox_egress::github_meta::{GitHubMetaSeed, MAX_META_BYTES, MAX_SEED_BYTES}; use sendbox_egress::runtime::{ DEFAULT_CGROUP_ROOT, RuntimePolicyDocument as EgressRuntimePolicyDocument, }; @@ -18,8 +19,9 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer}; use thiserror::Error; use zeroize::{Zeroize, Zeroizing}; -pub const BOOTSTRAP_SCHEMA_VERSION: u32 = 4; -pub const MAX_BOOTSTRAP_BYTES: usize = 2 * 1024 * 1024; +pub const BOOTSTRAP_SCHEMA_VERSION: u32 = 5; +/// Session configuration budget plus room for one host-validated Meta seed. +pub const MAX_BOOTSTRAP_BYTES: usize = 2 * 1024 * 1024 + MAX_SEED_BYTES; const MAX_GATEWAY_CREDENTIALS: usize = 64; const MAX_GATEWAY_CREDENTIAL_BYTES: usize = 64 * 1024; pub const MAX_REGISTRY_CREDENTIALS: usize = 16; @@ -320,6 +322,7 @@ pub struct BootstrapDocumentConfiguration { pub services: Vec, pub execution_broker: Option, pub egress_policy: Option, + pub github_meta: Option, pub gateway_credentials: Vec, pub registry_proxy: Option, } @@ -338,6 +341,7 @@ pub struct BootstrapDocument { pub services: Vec, pub execution_broker: Option, pub egress_policy: Option, + pub github_meta: Option, pub gateway_credentials: Vec, pub registry_proxy: Option, } @@ -377,6 +381,8 @@ struct BootstrapWire { #[serde(default)] egress_policy: Option, #[serde(default)] + github_meta: Option, + #[serde(default)] gateway_credentials: Vec, #[serde(default)] registry_proxy: Option, @@ -481,6 +487,7 @@ pub fn encode_bootstrap_document( services: configuration.services, execution_broker, egress_policy: configuration.egress_policy, + github_meta: configuration.github_meta, gateway_credentials: configuration.gateway_credentials, registry_proxy: configuration.registry_proxy, }; @@ -539,6 +546,10 @@ fn validate_configuration( .as_ref() .map(|broker| &broker.cgroup_parent), )?; + validate_github_meta( + configuration.egress_policy.as_ref(), + configuration.github_meta.as_ref(), + )?; validate_gateway_credentials( &configuration.gateway_credentials, configuration @@ -611,6 +622,7 @@ fn validate_wire(wire: BootstrapWire) -> Result Result Result<(), B Ok(()) } +/// The guest never fetches Meta itself, so a `github.com` delegation needs +/// exactly one host seed; gateways perform the complete document validation. +fn validate_github_meta( + egress: Option<&EgressRuntimePolicyDocument>, + seed: Option<&GitHubMetaSeed>, +) -> Result<(), BootstrapError> { + let delegated = egress + .map(EgressRuntimePolicyDocument::github_meta_enabled) + .transpose() + .map_err(|error| BootstrapError::Invalid(error.to_string()))? + .unwrap_or(false); + if delegated != seed.is_some() { + return Err(BootstrapError::Invalid( + "a GitHub Meta seed must accompany exactly a github.com delegation".to_owned(), + )); + } + if seed.is_some_and(|seed| seed.body.len() > MAX_META_BYTES) { + return Err(BootstrapError::Invalid( + "GitHub Meta seed exceeds its byte limit".to_owned(), + )); + } + Ok(()) +} + fn validate_egress( session_id: SessionId, policy: Option<&EgressRuntimePolicyDocument>, @@ -1076,6 +1113,7 @@ mod tests { syscall_tracing: false, }), egress_policy: None, + github_meta: None, gateway_credentials: Vec::new(), registry_proxy: None, } @@ -1289,6 +1327,56 @@ mod tests { assert!(encode_bootstrap_document(config, &[5; 32]).is_err()); } + #[test] + fn github_delegation_carries_exactly_one_seed_through_the_bootstrap() { + let github = sendbox_policy::NetworkPolicy { + default_action: Action::Deny, + allowed_domains: vec!["github.com".to_owned()], + blocked_domains: Vec::new(), + allow_dns: true, + max_connections: None, + allowed_networks: Vec::new(), + blocked_networks: Vec::new(), + allowed_ports: Vec::new(), + dns: sendbox_policy::DnsPolicy::default(), + }; + let seed = GitHubMetaSeed { + body: br#"{"web":["203.0.113.0/24"]}"#.to_vec(), + etag: Some("\"fixture\"".to_owned()), + validated_unix_seconds: 1_800_000_000, + last_attempt_unix_seconds: 1_800_000_000, + last_error: None, + }; + let configured = |network: sendbox_policy::NetworkPolicy, seed: Option| { + let mut config = configuration(); + let policy = EgressRuntimePolicyDocument::for_session(config.session_id, network); + config + .execution_broker + .as_mut() + .expect("execution broker") + .cgroup_parent = policy.execution_cgroup_parent(Path::new(DEFAULT_CGROUP_ROOT)); + config.egress_policy = Some(policy); + config.github_meta = seed; + config + }; + let encoded = + encode_bootstrap_document(configured(github.clone(), Some(seed.clone())), &[5; 32]) + .expect("encode seeded bootstrap"); + let decoded = decode_bootstrap_document(&encoded).expect("decode seeded bootstrap"); + assert_eq!(decoded.github_meta, Some(seed.clone())); + + assert!(encode_bootstrap_document(configured(github.clone(), None), &[5; 32]).is_err()); + let mut exact_host = github.clone(); + exact_host.allowed_domains = vec!["api.github.com".to_owned()]; + assert!( + encode_bootstrap_document(configured(exact_host, Some(seed.clone())), &[5; 32]) + .is_err() + ); + let mut oversized = seed; + oversized.body = vec![b' '; MAX_META_BYTES + 1]; + assert!(encode_bootstrap_document(configured(github, Some(oversized)), &[5; 32]).is_err()); + } + #[test] fn remote_mcp_bootstrap_requires_authenticated_egress() { let mut config = configuration(); diff --git a/crates/sendbox-cli/src/main.rs b/crates/sendbox-cli/src/main.rs index 44aabbe..aafa1fc 100644 --- a/crates/sendbox-cli/src/main.rs +++ b/crates/sendbox-cli/src/main.rs @@ -1321,6 +1321,7 @@ fn host_error_exit_code(error: &HostError) -> u8 { INVALID_CONFIGURATION_EXIT } HostError::OutputFinalization { runtime, .. } => host_error_exit_code(runtime), + error if error.is_github_meta_policy_denial() => INVALID_CONFIGURATION_EXIT, HostError::Invalid(_) | HostError::Boundary(_) | HostError::Credentials(_) diff --git a/crates/sendbox-egress/Cargo.toml b/crates/sendbox-egress/Cargo.toml index 9633f47..d8424d6 100644 --- a/crates/sendbox-egress/Cargo.toml +++ b/crates/sendbox-egress/Cargo.toml @@ -19,6 +19,7 @@ path = "src/bin/harness.rs" sendbox-core = { path = "../sendbox-core" } sendbox-policy = { path = "../sendbox-policy" } async-trait.workspace = true +base64.workspace = true bytes.workspace = true clap.workspace = true hickory-proto.workspace = true diff --git a/crates/sendbox-egress/src/gateway.rs b/crates/sendbox-egress/src/gateway.rs index d6e9450..4893fa7 100644 --- a/crates/sendbox-egress/src/gateway.rs +++ b/crates/sendbox-egress/src/gateway.rs @@ -24,8 +24,7 @@ use crate::connect_broker::{ use crate::dialer::Dialer; use crate::dns_broker::{DnsBroker, DnsBrokerConfig}; use crate::dns_budget::DnsGuard; -use crate::github_meta::{self, GitHubMetaClient}; -use crate::github_meta_client::OfficialGitHubMetaClient; +use crate::github_meta::{GitHubMetaError, GitHubMetaSeed}; use crate::origin::OriginReservations; use crate::policy::PolicyEngine; use crate::resolver::UpstreamResolver; @@ -160,7 +159,7 @@ pub struct Gateway { authorizations: Arc, guard: Arc, config: GatewayConfig, - metadata_client: Option>, + github_meta_seed: Option, metadata_prepared: AtomicBool, } @@ -203,43 +202,35 @@ impl Gateway { authorizations: Arc::new(AuthorizationCache::with_capacity(capacity)), guard, config, - metadata_client: None, + github_meta_seed: None, metadata_prepared: AtomicBool::new(false), } } + /// Supplies the host-validated Meta response a `github.com` grant needs. #[must_use] - pub fn with_github_meta_client(mut self, client: Arc) -> Self { - self.metadata_client = Some(client); + pub fn with_github_meta_seed(mut self, seed: GitHubMetaSeed) -> Self { + self.github_meta_seed = Some(seed); self } - fn metadata_client(&self) -> Arc { - self.metadata_client.clone().unwrap_or_else(|| { - Arc::new(OfficialGitHubMetaClient::new( - Arc::clone(&self.resolver), - Arc::clone(&self.dialer), - )) - }) - } - /// Production calls this after cgroup/mark enforcement is armed and before - /// publishing service readiness. A missing initial snapshot is an error. - pub async fn prepare_github_meta(&self, cancel: &CancellationToken) -> io::Result<()> { + /// publishing service readiness. It performs no network I/O; a missing or + /// invalid seed is an error rather than an exact-host fallback. + pub fn prepare_github_meta(&self) -> io::Result<()> { let Some(metadata) = self.engine.github_meta() else { return Ok(()); }; if self.metadata_prepared.load(Ordering::Acquire) && metadata.view().1.is_some() { return Ok(()); } - let client = self.metadata_client(); - tokio::select! { - biased; - () = cancel.cancelled() => return Err(io::Error::new(io::ErrorKind::Interrupted, "GitHub Meta bootstrap cancelled")), - result = metadata.refresh_once(client.as_ref(), &self.engine, self.audit.as_ref()) => { - result.map_err(io::Error::other)?; - } - } + let seed = self + .github_meta_seed + .as_ref() + .ok_or_else(|| io::Error::other(GitHubMetaError::MissingSeed))?; + metadata + .install_seed(seed, self.audit.as_ref()) + .map_err(io::Error::other)?; self.metadata_prepared.store(true, Ordering::Release); Ok(()) } @@ -257,13 +248,7 @@ impl Gateway { listeners: GatewayListeners, cancel: CancellationToken, ) -> io::Result<()> { - if let Err(error) = self.prepare_github_meta(&cancel).await { - return if cancel.is_cancelled() { - Ok(()) - } else { - Err(error) - }; - } + self.prepare_github_meta()?; let _guard = GatewayRunGuard { engine: &self.engine, authorizations: &self.authorizations, @@ -284,14 +269,6 @@ impl Gateway { ); let mut tasks = tokio::task::JoinSet::new(); - if self.engine.github_meta().is_some() { - tasks.spawn(github_meta::run_refresh( - Arc::clone(&self.engine), - self.metadata_client(), - Arc::clone(&self.audit), - cancel.clone(), - )); - } tasks.spawn(Arc::clone(&connect_broker).run(listeners.connect, cancel.clone())); if let Some(http_proxy) = listeners.http_proxy { tasks.spawn(connect_broker.run_with_frontend( diff --git a/crates/sendbox-egress/src/github_meta.rs b/crates/sendbox-egress/src/github_meta.rs index 9d2b90e..01f8535 100644 --- a/crates/sendbox-egress/src/github_meta.rs +++ b/crates/sendbox-egress/src/github_meta.rs @@ -1,4 +1,9 @@ //! Validated, expiring destination grants from GitHub's official Meta API. +//! +//! The host owns the only network fetch (see [`crate::github_meta_client`]) +//! and shares one cached response across sessions. Gateways install that +//! host-supplied [`GitHubMetaSeed`] after re-validating it and never contact +//! GitHub themselves. use std::collections::BTreeSet; use std::net::IpAddr; @@ -6,23 +11,26 @@ use std::sync::{Arc, RwLock}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use ipnet::IpNet; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use serde_json::Value; use sha2::{Digest, Sha256}; use thiserror::Error; use tokio::time::Instant; -use tokio_util::sync::CancellationToken; use crate::audit::{AuditEvent, AuditSink}; use crate::domain; -use crate::policy::PolicyEngine; pub const GITHUB_META_URL: &str = "https://api.github.com/meta"; pub const GITHUB_META_API_VERSION: &str = "2022-11-28"; pub const MAX_META_BYTES: usize = 2 * 1024 * 1024; +/// Upper bound for one serialized seed: the base64 body plus small metadata. +pub const MAX_SEED_BYTES: usize = 3 * 1024 * 1024; +/// How long the host reuses a validated response before revalidating it. pub const META_REFRESH_INTERVAL: Duration = Duration::from_secs(60 * 60); pub const META_MAX_STALENESS: Duration = Duration::from_secs(24 * 60 * 60); pub const META_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); +/// Tolerated host/guest clock disagreement for a seed's validation time. +pub const META_MAX_CLOCK_SKEW: Duration = Duration::from_secs(5 * 60); const MAX_NETWORK_ENTRIES: usize = 16_384; const MAX_DOMAIN_ENTRIES: usize = 4096; @@ -54,13 +62,13 @@ const DOMAIN_FIELDS: &[&str] = &[ "actions", ]; -#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)] #[serde(tag = "kind", content = "detail", rename_all = "snake_case")] pub enum GitHubMetaError { #[error("GitHub Meta response exceeds its byte or entry limit")] LimitExceeded, #[error("invalid GitHub Meta document: {0}")] - InvalidDocument(&'static str), + InvalidDocument(String), #[error("GitHub Meta contains an invalid or unrestricted IP/CIDR")] InvalidNetwork, #[error("GitHub Meta contains an invalid domain pattern")] @@ -71,6 +79,11 @@ pub enum GitHubMetaError { Clock, #[error("GitHub Meta HTTP request failed with status {0}")] HttpStatus(u16), + #[error( + "GitHub Meta request hit GitHub's anonymous API rate limit (60 requests per hour per IP address){}", + rate_limit_reset(.reset_unix_seconds) + )] + RateLimited { reset_unix_seconds: Option }, #[error("GitHub Meta refresh timed out")] Timeout, #[error("GitHub Meta refresh is denied by network policy")] @@ -78,15 +91,23 @@ pub enum GitHubMetaError { #[error("GitHub Meta DNS resolution failed")] Resolution, #[error("GitHub Meta transport failed during {0}")] - Transport(&'static str), + Transport(String), #[error("GitHub Meta TLS roots are unavailable or invalid")] TlsRoots, #[error("GitHub Meta response has invalid headers or framing")] InvalidResponse, #[error("GitHub Meta provenance publication failed")] Publication, - #[error("GitHub Meta refresh is already in progress")] - RefreshInProgress, + #[error("GitHub Meta delegation requires a host-validated seed")] + MissingSeed, + #[error("GitHub Meta seed is expired or validated in the future")] + ExpiredSeed, +} + +fn rate_limit_reset(reset_unix_seconds: &Option) -> String { + reset_unix_seconds.map_or_else(String::new, |reset| { + format!("; it resets at Unix time {reset}") + }) } #[derive(Debug, Clone)] @@ -102,16 +123,16 @@ impl GitHubMetaScope { return Err(GitHubMetaError::LimitExceeded); } let document: Value = serde_json::from_slice(bytes) - .map_err(|_| GitHubMetaError::InvalidDocument("expected JSON"))?; + .map_err(|_| GitHubMetaError::InvalidDocument("expected JSON".to_owned()))?; let object = document .as_object() - .ok_or(GitHubMetaError::InvalidDocument("expected an object"))?; + .ok_or_else(|| GitHubMetaError::InvalidDocument("expected an object".to_owned()))?; if !object .get("verifiable_password_authentication") .is_some_and(Value::is_boolean) { return Err(GitHubMetaError::InvalidDocument( - "missing authentication metadata", + "missing authentication metadata".to_owned(), )); } let mut networks = BTreeSet::new(); @@ -141,7 +162,7 @@ impl GitHubMetaScope { | "commit_signing_keys" ) { return Err(GitHubMetaError::InvalidDocument( - "unrecognized top-level field", + "unrecognized top-level field".to_owned(), )); } } @@ -152,14 +173,14 @@ impl GitHubMetaScope { .is_none_or(|values| values.is_empty()) { return Err(GitHubMetaError::InvalidDocument( - "missing core network field", + "missing core network field".to_owned(), )); } } let published_domains = object .get("domains") .and_then(Value::as_object) - .ok_or(GitHubMetaError::InvalidDocument("missing domains object"))?; + .ok_or_else(|| GitHubMetaError::InvalidDocument("missing domains object".to_owned()))?; let mut domains = BTreeSet::new(); let mut domain_count = 0; let mut add_domains = |value: &Value| -> Result<(), GitHubMetaError> { @@ -183,12 +204,12 @@ impl GitHubMetaScope { } else { if !matches!(field.as_str(), "actions_inbound" | "artifact_attestations") { return Err(GitHubMetaError::InvalidDocument( - "unrecognized domain field", + "unrecognized domain field".to_owned(), )); } - let nested = value.as_object().ok_or(GitHubMetaError::InvalidDocument( - "expected a nested domain object", - ))?; + let nested = value.as_object().ok_or_else(|| { + GitHubMetaError::InvalidDocument("expected a nested domain object".to_owned()) + })?; for (key, value) in nested { match (field.as_str(), key.as_str()) { ("actions_inbound", "full_domains" | "wildcard_domains") @@ -196,7 +217,7 @@ impl GitHubMetaScope { ("artifact_attestations", "trust_domain") if value.is_string() => {} _ => { return Err(GitHubMetaError::InvalidDocument( - "unrecognized domain field", + "unrecognized domain field".to_owned(), )); } } @@ -204,32 +225,31 @@ impl GitHubMetaScope { } } if networks.is_empty() || domains.is_empty() { - return Err(GitHubMetaError::InvalidDocument("empty destination scope")); + return Err(GitHubMetaError::InvalidDocument( + "empty destination scope".to_owned(), + )); } Ok(Self { domains: domains.into_iter().collect(), networks: networks.into_iter().collect(), - sha256: Sha256::digest(bytes) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(), + sha256: hex_sha256(bytes), }) } } fn strings(value: &Value) -> Result, GitHubMetaError> { - let values = value.as_array().ok_or(GitHubMetaError::InvalidDocument( - "expected a destination array", - ))?; + let values = value.as_array().ok_or_else(|| { + GitHubMetaError::InvalidDocument("expected a destination array".to_owned()) + })?; if values.len() > MAX_NETWORK_ENTRIES { return Err(GitHubMetaError::LimitExceeded); } values .iter() .map(|value| { - value.as_str().ok_or(GitHubMetaError::InvalidDocument( - "destination entries must be strings", - )) + value.as_str().ok_or_else(|| { + GitHubMetaError::InvalidDocument("destination entries must be strings".to_owned()) + }) }) .collect() } @@ -239,16 +259,84 @@ pub enum GitHubMetaResponse { NotModified, } -/// Trusted control-plane transport. Production always uses the fixed official -/// HTTPS client; injection lets embedders and tests keep the same owner and -/// refresh semantics without doing network I/O in policy compilation. -#[async_trait::async_trait] -pub trait GitHubMetaClient: Send + Sync { - async fn fetch( - &self, - policy: &PolicyEngine, - etag: Option<&str>, - ) -> Result; +/// One whole official Meta response validated by the host's shared cache. +/// The guest re-validates every field before any grant becomes effective. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GitHubMetaSeed { + #[serde(with = "base64_body")] + pub body: Vec, + pub etag: Option, + /// Last successful fetch or conditional revalidation, in host Unix time. + pub validated_unix_seconds: u64, + pub last_attempt_unix_seconds: u64, + /// Set when the host's latest revalidation failed and this is last-good. + pub last_error: Option, +} + +impl GitHubMetaSeed { + /// Checks the validator, freshness bound and complete document. + pub fn validate(&self, now_unix_seconds: u64) -> Result { + if self.etag.as_deref().is_some_and(|etag| !valid_etag(etag)) { + return Err(GitHubMetaError::InvalidResponse); + } + self.remaining_validity(now_unix_seconds)?; + GitHubMetaScope::parse(&self.body) + } + + /// Time left before the 24-hour staleness bound, measured from the host's + /// validation time. Future validation times are tolerated within skew. + pub fn remaining_validity(&self, now_unix_seconds: u64) -> Result { + if self.validated_unix_seconds + > now_unix_seconds.saturating_add(META_MAX_CLOCK_SKEW.as_secs()) + { + return Err(GitHubMetaError::ExpiredSeed); + } + META_MAX_STALENESS + .checked_sub(Duration::from_secs( + now_unix_seconds.saturating_sub(self.validated_unix_seconds), + )) + .filter(|remaining| !remaining.is_zero()) + .ok_or(GitHubMetaError::ExpiredSeed) + } + + #[must_use] + pub fn sha256_hex(&self) -> String { + hex_sha256(&self.body) + } +} + +mod base64_body { + use base64::Engine as _; + use base64::engine::general_purpose::STANDARD; + use serde::de::Error as _; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize(body: &[u8], serializer: S) -> Result { + serializer.serialize_str(&STANDARD.encode(body)) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + let encoded = String::deserialize(deserializer)?; + if encoded.len() > super::MAX_SEED_BYTES { + return Err(D::Error::custom("GitHub Meta seed body exceeds its limit")); + } + STANDARD.decode(encoded).map_err(D::Error::custom) + } +} + +fn hex_sha256(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +pub fn unix_now() -> Result { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|time| time.as_secs()) + .map_err(|_| GitHubMetaError::Clock) } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] @@ -291,7 +379,8 @@ pub struct GitHubMetaStatus { #[derive(Clone)] struct Snapshot { scope: Arc, - validated_at: Instant, + // Absolute deadline: a freshly booted guest cannot backdate an Instant. + expires_at: Instant, validated_unix_seconds: u64, etag: Option, } @@ -307,7 +396,6 @@ struct State { #[derive(Default)] pub struct GitHubMeta { state: RwLock, - refresh: tokio::sync::Mutex<()>, } impl GitHubMeta { @@ -318,43 +406,29 @@ impl GitHubMeta { state.last_error = None; } - pub async fn refresh_once( + /// Validates a host-supplied seed and atomically publishes its status + /// before it can authorize anything. An invalid seed leaves any previous + /// snapshot untouched until its own expiry. + pub fn install_seed( &self, - client: &dyn GitHubMetaClient, - policy: &PolicyEngine, + seed: &GitHubMetaSeed, audit: &dyn AuditSink, ) -> Result<(), GitHubMetaError> { - let _refresh = self - .refresh - .try_lock() - .map_err(|_| GitHubMetaError::RefreshInProgress)?; - let etag = self - .state - .read() - .expect("GitHub Meta state poisoned") - .snapshot - .as_ref() - .and_then(|snapshot| snapshot.etag.clone()); - let response = - tokio::time::timeout(META_REQUEST_TIMEOUT, client.fetch(policy, etag.as_deref())) - .await - .map_err(|_| GitHubMetaError::Timeout) - .and_then(|response| response) - .and_then(|response| self.prepare_response(response)); - if let Err(error) = &response { + let candidate = self.prepare_seed(seed); + if let Err(error) = &candidate { let mut state = self.state.write().expect("GitHub Meta state poisoned"); - match SystemTime::now().duration_since(UNIX_EPOCH) { - Ok(time) => { - state.last_attempt_unix_seconds = Some(time.as_secs()); + match unix_now() { + Ok(now) => { + state.last_attempt_unix_seconds = Some(now); state.last_error = Some(error.clone()); } - Err(_) => { + Err(clock) => { state.last_attempt_unix_seconds = None; - state.last_error = Some(GitHubMetaError::Clock); + state.last_error = Some(clock); } } } - let status = match &response { + let status = match &candidate { Ok(candidate) => Self::describe(candidate), Err(_) => self.status(), }; @@ -370,7 +444,7 @@ impl GitHubMeta { }); return Err(GitHubMetaError::Publication); } - let candidate = response?; + let candidate = candidate?; *self.state.write().expect("GitHub Meta state poisoned") = candidate; Ok(()) } @@ -384,7 +458,7 @@ impl GitHubMeta { let active = state .snapshot .as_ref() - .is_some_and(|snapshot| snapshot.validated_at.elapsed() < META_MAX_STALENESS); + .is_some_and(|snapshot| Instant::now() < snapshot.expires_at); let health = match (&state.snapshot, active, state.last_error.is_some()) { (None, _, false) => GitHubMetaState::Pending, (None, _, true) => GitHubMetaState::Unavailable, @@ -419,66 +493,34 @@ impl GitHubMeta { pub(crate) fn view(&self) -> (u64, Option>) { let state = self.state.read().expect("GitHub Meta state poisoned"); match &state.snapshot { - Some(snapshot) if snapshot.validated_at.elapsed() < META_MAX_STALENESS => { + Some(snapshot) if Instant::now() < snapshot.expires_at => { (state.revision, Some(Arc::clone(&snapshot.scope))) } _ => (0, None), } } - #[cfg(test)] - pub(crate) fn install_response( - &self, - response: GitHubMetaResponse, - ) -> Result<(), GitHubMetaError> { - let candidate = self.prepare_response(response)?; - *self.state.write().expect("GitHub Meta state poisoned") = candidate; - Ok(()) - } - - fn prepare_response(&self, response: GitHubMetaResponse) -> Result { - let parsed = match response { - GitHubMetaResponse::Modified { body, etag } => { - if etag.as_ref().is_some_and(|etag| !valid_etag(etag)) { - return Err(GitHubMetaError::InvalidResponse); - } - Some((Arc::new(GitHubMetaScope::parse(&body)?), etag)) - } - GitHubMetaResponse::NotModified => None, - }; - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|_| GitHubMetaError::Clock)? - .as_secs(); + fn prepare_seed(&self, seed: &GitHubMetaSeed) -> Result { + let now = unix_now()?; + let scope = Arc::new(seed.validate(now)?); + let remaining = seed.remaining_validity(now)?; let mut state = self .state .read() .expect("GitHub Meta state poisoned") .clone(); - let revision = state + state.revision = state .revision .checked_add(1) .ok_or(GitHubMetaError::LimitExceeded)?; - let (scope, etag) = match parsed { - Some(parsed) => parsed, - None => { - let previous = state - .snapshot - .as_ref() - .filter(|snapshot| snapshot.etag.is_some()) - .ok_or(GitHubMetaError::UnexpectedNotModified)?; - (Arc::clone(&previous.scope), previous.etag.clone()) - } - }; state.snapshot = Some(Snapshot { scope, - validated_at: Instant::now(), - validated_unix_seconds: now, - etag, + expires_at: Instant::now() + remaining, + validated_unix_seconds: seed.validated_unix_seconds, + etag: seed.etag.clone(), }); - state.revision = revision; - state.last_attempt_unix_seconds = Some(now); - state.last_error = None; + state.last_attempt_unix_seconds = Some(seed.last_attempt_unix_seconds); + state.last_error = seed.last_error.clone(); Ok(state) } } @@ -496,45 +538,10 @@ pub(crate) fn valid_etag(etag: &str) -> bool { }) } -/// Owned by the gateway alongside its brokers, with no detached task or disk -/// cache. Expiry is also checked on every policy view, not just on this timer. -pub(crate) async fn run_refresh( - engine: Arc, - client: Arc, - audit: Arc, - cancel: CancellationToken, -) -> std::io::Result<()> { - let metadata = engine - .github_meta() - .expect("refresh requires a GitHub grant"); - let mut timer = tokio::time::interval_at( - Instant::now() + META_REFRESH_INTERVAL, - META_REFRESH_INTERVAL, - ); - timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); - loop { - tokio::select! { - biased; - () = cancel.cancelled() => return Ok(()), - _ = timer.tick() => { - tokio::select! { - biased; - () = cancel.cancelled() => return Ok(()), - result = metadata.refresh_once(client.as_ref(), &engine, audit.as_ref()) => { - if result == Err(GitHubMetaError::Publication) { - return Err(std::io::Error::other(GitHubMetaError::Publication)); - } - } - } - } - } - } -} - #[cfg(test)] mod tests { use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; + use crate::policy::PolicyEngine; fn fixture() -> Vec { serde_json::to_vec(&serde_json::json!({ @@ -589,21 +596,6 @@ mod tests { assert!(GitHubMetaScope::parse(&serde_json::to_vec(&document).unwrap()).is_err()); } - #[test] - fn rejects_invalid_conditional_validator_without_installing_a_scope() { - let metadata = GitHubMeta::default(); - for etag in ["", "unquoted", "\"embedded\"quote\"", "\"line\r\nbreak\""] { - assert_eq!( - metadata.install_response(GitHubMetaResponse::Modified { - body: fixture(), - etag: Some(etag.to_owned()), - }), - Err(GitHubMetaError::InvalidResponse) - ); - assert!(!metadata.status().grants_active); - } - } - #[test] fn rejects_malformed_unbounded_and_incomplete_destination_scopes() { for (path, value) in [ @@ -645,136 +637,112 @@ mod tests { )); } - fn engine() -> Arc { - Arc::new( - PolicyEngine::compile( - &serde_json::from_value(serde_json::json!({ - "default_action": "deny", "allowed_domains": ["github.com"], - "blocked_domains": [], "allow_dns": true - })) - .unwrap(), - ) - .unwrap(), - ) + fn seed(validated_unix_seconds: u64) -> GitHubMetaSeed { + GitHubMetaSeed { + body: fixture(), + etag: Some("\"fixture\"".to_owned()), + validated_unix_seconds, + last_attempt_unix_seconds: validated_unix_seconds, + last_error: None, + } } - #[tokio::test(start_paused = true)] - async fn conditional_revalidation_renews_only_a_previously_valid_snapshot() { - let engine = engine(); - let metadata = engine.github_meta().unwrap(); - assert_eq!( - metadata.install_response(GitHubMetaResponse::NotModified), - Err(GitHubMetaError::UnexpectedNotModified) - ); - metadata - .install_response(GitHubMetaResponse::Modified { - body: fixture(), - etag: Some("\"fixture\"".to_owned()), - }) - .unwrap(); - let previous = metadata.status(); - tokio::time::advance(META_MAX_STALENESS / 2).await; - metadata - .install_response(GitHubMetaResponse::NotModified) - .unwrap(); - tokio::time::advance(META_MAX_STALENESS / 2).await; - assert!(metadata.status().grants_active); - assert_eq!(metadata.status().published_scope, previous.published_scope); - assert_ne!(metadata.status().revision, previous.revision); + fn engine() -> PolicyEngine { + PolicyEngine::compile( + &serde_json::from_value(serde_json::json!({ + "default_action": "deny", "allowed_domains": ["github.com"], + "blocked_domains": [], "allow_dns": true + })) + .unwrap(), + ) + .unwrap() } - struct BlockingClient { - calls: AtomicUsize, - dropped: Arc, + #[test] + fn seed_body_round_trips_exactly_through_its_wire_encoding() { + let mut original = seed(unix_now().unwrap()); + original.body.extend_from_slice(b" \n"); + let encoded = serde_json::to_vec(&original).unwrap(); + let decoded: GitHubMetaSeed = serde_json::from_slice(&encoded).unwrap(); + assert_eq!(decoded, original); + assert_eq!(decoded.sha256_hex(), original.sha256_hex()); } - #[async_trait::async_trait] - impl GitHubMetaClient for BlockingClient { - async fn fetch( - &self, - _policy: &PolicyEngine, - _etag: Option<&str>, - ) -> Result { - if self.calls.fetch_add(1, Ordering::SeqCst) == 0 { - return Ok(GitHubMetaResponse::Modified { - body: fixture(), - etag: Some("\"fixture\"".to_owned()), - }); - } - struct DropProbe(Arc); - impl Drop for DropProbe { - fn drop(&mut self) { - self.0.fetch_add(1, Ordering::SeqCst); - } - } - let _probe = DropProbe(Arc::clone(&self.dropped)); - std::future::pending().await + #[test] + fn rejects_invalid_validators_stale_and_future_seeds_without_installing_a_scope() { + let now = unix_now().unwrap(); + let mut invalid = Vec::new(); + for etag in ["", "unquoted", "\"embedded\"quote\"", "\"line\r\nbreak\""] { + let mut candidate = seed(now); + candidate.etag = Some(etag.to_owned()); + invalid.push((candidate, GitHubMetaError::InvalidResponse)); + } + invalid.push(( + seed(now - META_MAX_STALENESS.as_secs()), + GitHubMetaError::ExpiredSeed, + )); + invalid.push(( + seed(now + META_MAX_CLOCK_SKEW.as_secs() + 60), + GitHubMetaError::ExpiredSeed, + )); + for (candidate, expected) in invalid { + let metadata = GitHubMeta::default(); + let audit = crate::audit::CollectingAuditSink::new(); + assert_eq!(metadata.install_seed(&candidate, &audit), Err(expected)); + assert!(!metadata.status().grants_active); + assert_eq!(metadata.status().state, GitHubMetaState::Unavailable); + assert_eq!(audit.len(), 1); } } #[tokio::test(start_paused = true)] - async fn periodic_refresh_is_hourly_bounded_and_cancelled_without_orphans() { + async fn seed_expires_from_host_validation_time_not_guest_install_time() { let engine = engine(); - let client = Arc::new(BlockingClient { - calls: AtomicUsize::new(0), - dropped: Arc::new(AtomicUsize::new(0)), - }); - let audit = Arc::new(crate::audit::CollectingAuditSink::new()); - engine - .github_meta() - .unwrap() - .refresh_once(client.as_ref(), &engine, audit.as_ref()) - .await + let metadata = engine.github_meta().unwrap(); + let validated = + unix_now().unwrap() - (META_MAX_STALENESS - META_REFRESH_INTERVAL).as_secs(); + metadata + .install_seed(&seed(validated), &crate::audit::NullAuditSink) .unwrap(); - let cancel = CancellationToken::new(); - let task = tokio::spawn(run_refresh( - Arc::clone(&engine), - Arc::clone(&client) as Arc<_>, - audit, - cancel.clone(), - )); - tokio::task::yield_now().await; - tokio::time::advance(META_REFRESH_INTERVAL - Duration::from_secs(1)).await; - assert_eq!(client.calls.load(Ordering::SeqCst), 1); - tokio::time::advance(Duration::from_secs(1)).await; - tokio::task::yield_now().await; - assert_eq!(client.calls.load(Ordering::SeqCst), 2); - cancel.cancel(); - task.await.unwrap().unwrap(); - assert_eq!(client.dropped.load(Ordering::SeqCst), 1); - tokio::time::advance(META_REFRESH_INTERVAL).await; - assert_eq!(client.calls.load(Ordering::SeqCst), 2); + let installed = engine.snapshot(); + assert_eq!(metadata.status().state, GitHubMetaState::Fresh); + assert_eq!( + metadata.status().expires_unix_seconds, + Some(validated + META_MAX_STALENESS.as_secs()) + ); + assert!(engine.evaluate_domain_name("assets.github.test").unwrap()); + tokio::time::advance(META_REFRESH_INTERVAL - Duration::from_secs(5)).await; + assert!(installed.is_current()); + tokio::time::advance(Duration::from_secs(5)).await; + assert_eq!(metadata.status().state, GitHubMetaState::Expired); + assert!(!installed.is_current()); + assert!(!engine.evaluate_domain_name("assets.github.test").unwrap()); + assert!(engine.evaluate_domain_name("github.com").unwrap()); } - #[tokio::test(start_paused = true)] - async fn hung_refresh_reports_timeout_without_extending_its_lease() { + #[test] + fn last_good_seed_reports_the_hosts_failed_revalidation() { let engine = engine(); - let client = BlockingClient { - calls: AtomicUsize::new(0), - dropped: Arc::new(AtomicUsize::new(0)), - }; - let audit = crate::audit::CollectingAuditSink::new(); + let now = unix_now().unwrap(); + let mut candidate = seed(now - 7200); + candidate.last_attempt_unix_seconds = now; + candidate.last_error = Some(GitHubMetaError::RateLimited { + reset_unix_seconds: Some(now + 600), + }); let metadata = engine.github_meta().unwrap(); metadata - .refresh_once(&client, &engine, &audit) - .await + .install_seed(&candidate, &crate::audit::NullAuditSink) .unwrap(); - let before = metadata.status(); - assert_eq!( - metadata.refresh_once(&client, &engine, &audit).await, - Err(GitHubMetaError::Timeout) - ); - assert_eq!( - metadata.status().last_success_unix_seconds, - before.last_success_unix_seconds - ); - assert_eq!(metadata.status().revision, before.revision); - assert_eq!(metadata.status().state, GitHubMetaState::Degraded); - assert_eq!(client.dropped.load(Ordering::SeqCst), 1); + let status = metadata.status(); + assert_eq!(status.state, GitHubMetaState::Degraded); + assert!(status.grants_active); + assert_eq!(status.last_attempt_unix_seconds, Some(now)); + assert_eq!(status.last_error, candidate.last_error); + assert!(engine.evaluate_domain_name("assets.github.test").unwrap()); } - #[tokio::test] - async fn failed_provenance_publication_revokes_the_derived_scope() { + #[test] + fn failed_provenance_publication_revokes_the_derived_scope() { struct BrokenAudit; impl AuditSink for BrokenAudit { fn record(&self, _event: AuditEvent) {} @@ -783,21 +751,17 @@ mod tests { } } let engine = engine(); - let client = BlockingClient { - calls: AtomicUsize::new(0), - dropped: Arc::new(AtomicUsize::new(0)), - }; let metadata = engine.github_meta().unwrap(); assert_eq!( - metadata.refresh_once(&client, &engine, &BrokenAudit).await, + metadata.install_seed(&seed(unix_now().unwrap()), &BrokenAudit), Err(GitHubMetaError::Publication) ); assert!(!metadata.status().grants_active); assert!(!engine.evaluate_domain_name("assets.github.test").unwrap()); } - #[tokio::test] - async fn scope_is_published_before_it_can_authorize_a_connection() { + #[test] + fn scope_is_published_before_it_can_authorize_a_connection() { struct PublicationCheck<'a>(&'a PolicyEngine); impl AuditSink for PublicationCheck<'_> { fn record(&self, _event: AuditEvent) {} @@ -808,98 +772,11 @@ mod tests { } } let engine = engine(); - let client = BlockingClient { - calls: AtomicUsize::new(0), - dropped: Arc::new(AtomicUsize::new(0)), - }; engine .github_meta() .unwrap() - .refresh_once(&client, &engine, &PublicationCheck(&engine)) - .await + .install_seed(&seed(unix_now().unwrap()), &PublicationCheck(&engine)) .unwrap(); assert!(engine.evaluate_domain_name("assets.github.test").unwrap()); } - - #[tokio::test(start_paused = true)] - async fn concurrent_refreshes_cannot_overwrite_a_newer_snapshot() { - let engine = engine(); - let client = Arc::new(BlockingClient { - calls: AtomicUsize::new(1), - dropped: Arc::new(AtomicUsize::new(0)), - }); - let task_engine = Arc::clone(&engine); - let task_client = Arc::clone(&client); - let task = tokio::spawn(async move { - task_engine - .github_meta() - .unwrap() - .refresh_once( - task_client.as_ref(), - &task_engine, - &crate::audit::NullAuditSink, - ) - .await - }); - tokio::task::yield_now().await; - assert_eq!( - engine - .github_meta() - .unwrap() - .refresh_once(client.as_ref(), &engine, &crate::audit::NullAuditSink,) - .await, - Err(GitHubMetaError::RefreshInProgress) - ); - assert_eq!(client.calls.load(Ordering::SeqCst), 2); - task.abort(); - assert!(task.await.unwrap_err().is_cancelled()); - assert_eq!(client.dropped.load(Ordering::SeqCst), 1); - } - - #[tokio::test(start_paused = true)] - async fn failed_refresh_retains_last_good_only_until_its_monotonic_expiry() { - struct FailingClient; - #[async_trait::async_trait] - impl GitHubMetaClient for FailingClient { - async fn fetch( - &self, - _policy: &crate::policy::PolicyEngine, - _etag: Option<&str>, - ) -> Result { - Err(GitHubMetaError::HttpStatus(503)) - } - } - let raw = serde_json::from_value(serde_json::json!({ - "default_action": "deny", - "allowed_domains": ["github.com"], - "blocked_domains": [], - "allow_dns": true - })) - .unwrap(); - let engine = crate::policy::PolicyEngine::compile(&raw).unwrap(); - let metadata = engine.github_meta().unwrap(); - metadata - .install_response(GitHubMetaResponse::Modified { - body: fixture(), - etag: Some("\"fixture\"".to_owned()), - }) - .unwrap(); - let previous = engine.snapshot(); - let audit = crate::audit::CollectingAuditSink::new(); - assert!( - metadata - .refresh_once(&FailingClient, &engine, &audit) - .await - .is_err() - ); - assert_eq!(metadata.status().state, GitHubMetaState::Degraded); - assert!(previous.is_current()); - tokio::time::advance(META_MAX_STALENESS).await; - assert_eq!(metadata.status().state, GitHubMetaState::Expired); - assert!(!metadata.status().grants_active); - assert!(!previous.is_current()); - assert!(!engine.evaluate_domain_name("api.github.test").unwrap()); - assert!(engine.evaluate_domain_name("github.com").unwrap()); - assert_eq!(audit.len(), 1); - } } diff --git a/crates/sendbox-egress/src/github_meta_client.rs b/crates/sendbox-egress/src/github_meta_client.rs index 9552ff2..78a7e36 100644 --- a/crates/sendbox-egress/src/github_meta_client.rs +++ b/crates/sendbox-egress/src/github_meta_client.rs @@ -1,14 +1,15 @@ -//! Fixed-origin HTTPS transport using the gateway's marked, exact-IP dialer. -//! No environment proxy, OS re-resolution, redirects, or credentials. +//! Host-side fixed-origin HTTPS transport for the official Meta document. +//! System DNS, direct exact-IP dials and verified TLS; no environment proxy, +//! redirects, or credentials. Guests never call this: they install the +//! host's validated response. -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::time::Duration; use bytes::Bytes; -use hickory_proto::rr::Name; -use http::header::{CONTENT_ENCODING, CONTENT_LENGTH, ETAG, IF_NONE_MATCH}; -use http::{Request, StatusCode}; +use http::header::{CONTENT_ENCODING, CONTENT_LENGTH, ETAG, IF_NONE_MATCH, RETRY_AFTER}; +use http::{HeaderMap, Request, StatusCode}; use http_body_util::{BodyExt, Empty, Limited}; use hyper::client::conn::http1; use hyper_util::rt::TokioIo; @@ -18,113 +19,74 @@ use tokio_rustls::TlsConnector; use tokio_util::task::AbortOnDropHandle; use crate::address::{canonicalize, classify}; -use crate::dialer::Dialer; -use crate::dns_budget::DnsGuard; +use crate::dialer::{Dialer, DirectDialer}; use crate::github_meta::{ - GITHUB_META_API_VERSION, GitHubMetaClient, GitHubMetaError, GitHubMetaResponse, MAX_META_BYTES, + GITHUB_META_API_VERSION, GitHubMetaError, GitHubMetaResponse, MAX_META_BYTES, META_REQUEST_TIMEOUT, }; -use crate::policy::PolicyEngine; -use crate::resolver::UpstreamResolver; -use sendbox_policy::DnsRecordType; -const META_HOST: &str = "api.github.com"; +pub const META_HOST: &str = "api.github.com"; const CONNECT_TIMEOUT: Duration = Duration::from_secs(3); +// GitHub publishes resets at most an hour ahead; ignore implausible values. +const MAX_RATE_LIMIT_WAIT_SECS: u64 = 60 * 60; -pub struct OfficialGitHubMetaClient { - resolver: Arc, - dialer: Arc, +/// Fetches the official Meta document once, conditionally when `etag` is set. +/// Restricted resolutions (private, link-local, metadata) are refused. +pub async fn fetch_official_github_meta( + etag: Option<&str>, +) -> Result { + tokio::time::timeout(META_REQUEST_TIMEOUT, async { + let tls = tls_config()?; + let addresses = resolve_meta_host().await?; + fetch_via(&addresses, &DirectDialer, tls, etag).await + }) + .await + .map_err(|_| GitHubMetaError::Timeout)? } -impl OfficialGitHubMetaClient { - #[must_use] - pub fn new(resolver: Arc, dialer: Arc) -> Self { - Self { resolver, dialer } - } - - async fn fetch_inner( - &self, - policy: &PolicyEngine, - etag: Option<&str>, - tls: Arc, - ) -> Result { - if !policy.github_meta_name_permitted(META_HOST) { +async fn resolve_meta_host() -> Result, GitHubMetaError> { + let mut addresses = Vec::new(); + for address in tokio::net::lookup_host((META_HOST, 443)) + .await + .map_err(|_| GitHubMetaError::Resolution)? + { + let ip = canonicalize(address.ip()); + if classify(ip).is_restricted() { return Err(GitHubMetaError::PolicyDenied); } - let name = Name::from_ascii("api.github.com.").expect("fixed Meta hostname"); - let resolved = self - .resolver - .resolve(&name) - .await - .map_err(|_| GitHubMetaError::Resolution)?; - let guard = DnsGuard::from_policy(policy.dns_policy()); - for name in resolved.names_to_validate() { - let name = crate::domain::normalize_domain(&name.to_ascii()) - .map_err(|_| GitHubMetaError::Resolution)?; - if !policy.github_meta_name_permitted(&name) || guard.check_structure(&name).is_err() { - return Err(GitHubMetaError::PolicyDenied); - } - } - let mut addresses = Vec::new(); - for address in resolved.addresses { - let ip = canonicalize(address.ip); - if classify(ip).is_restricted() || !policy.address_permitted(ip).allowed { - return Err(GitHubMetaError::PolicyDenied); - } - let qtype = if ip.is_ipv4() { - DnsRecordType::A - } else { - DnsRecordType::Aaaa - }; - if guard.record_type_allowed(qtype) { - addresses.push(ip); - } - } - addresses.sort(); - addresses.dedup(); - addresses.truncate(guard.max_response_records()); - if addresses.is_empty() { - return Err(GitHubMetaError::Resolution); - } - let mut last_error = GitHubMetaError::Transport("connect"); - for ip in addresses { - let stream = match self - .dialer - .dial(SocketAddr::new(ip, 443), CONNECT_TIMEOUT) - .await - { - Ok(stream) => stream, - Err(_) => { - last_error = GitHubMetaError::Transport("connect"); - continue; - } - }; - let tls = TlsConnector::from(Arc::clone(&tls)) - .connect( - ServerName::try_from(META_HOST).expect("fixed TLS name"), - stream, - ) - .await - .map_err(|_| GitHubMetaError::Transport("TLS verification"))?; - return fetch_http(tls, etag).await; - } - Err(last_error) + addresses.push(ip); } + addresses.sort(); + addresses.dedup(); + if addresses.is_empty() { + return Err(GitHubMetaError::Resolution); + } + Ok(addresses) } -#[async_trait::async_trait] -impl GitHubMetaClient for OfficialGitHubMetaClient { - async fn fetch( - &self, - policy: &PolicyEngine, - etag: Option<&str>, - ) -> Result { - tokio::time::timeout(META_REQUEST_TIMEOUT, async { - self.fetch_inner(policy, etag, tls_config()?).await - }) - .await - .map_err(|_| GitHubMetaError::Timeout)? +async fn fetch_via( + addresses: &[IpAddr], + dialer: &dyn Dialer, + tls: Arc, + etag: Option<&str>, +) -> Result { + for ip in addresses { + let Ok(stream) = dialer + .dial(SocketAddr::new(*ip, 443), CONNECT_TIMEOUT) + .await + else { + continue; + }; + let tls = TlsConnector::from(Arc::clone(&tls)) + .connect( + ServerName::try_from(META_HOST).expect("fixed TLS name"), + stream, + ) + .await + .map_err(|_| GitHubMetaError::Transport("TLS verification".to_owned()))?; + return fetch_http(tls, etag).await; } + Err(GitHubMetaError::Transport("connect".to_owned())) } fn tls_config() -> Result, GitHubMetaError> { @@ -169,12 +131,12 @@ where .map_err(|_| GitHubMetaError::InvalidResponse)?; let (mut sender, connection) = http1::handshake(TokioIo::new(stream)) .await - .map_err(|_| GitHubMetaError::Transport("HTTP handshake"))?; + .map_err(|_| GitHubMetaError::Transport("HTTP handshake".to_owned()))?; let _driver = AbortOnDropHandle::new(tokio::spawn(connection)); let response = sender .send_request(request) .await - .map_err(|_| GitHubMetaError::Transport("HTTP response"))?; + .map_err(|_| GitHubMetaError::Transport("HTTP response".to_owned()))?; if response.status() == StatusCode::NOT_MODIFIED { return if etag.is_some() { Ok(GitHubMetaResponse::NotModified) @@ -183,7 +145,7 @@ where }; } if response.status() != StatusCode::OK { - return Err(GitHubMetaError::HttpStatus(response.status().as_u16())); + return Err(status_error(response.status(), response.headers())); } if response .headers() @@ -225,11 +187,35 @@ where Ok(GitHubMetaResponse::Modified { body, etag }) } +/// GitHub signals primary limits with `x-ratelimit-remaining: 0` and secondary +/// limits with `retry-after`, on either 403 or 429. +fn status_error(status: StatusCode, headers: &HeaderMap) -> GitHubMetaError { + let header = |name: &str| { + headers + .get(name) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.trim().parse::().ok()) + }; + let exhausted = header("x-ratelimit-remaining") == Some(0); + let retry_after = header(RETRY_AFTER.as_str()); + if !(status == StatusCode::TOO_MANY_REQUESTS + || (status == StatusCode::FORBIDDEN && (exhausted || retry_after.is_some()))) + { + return GitHubMetaError::HttpStatus(status.as_u16()); + } + let now = crate::github_meta::unix_now().ok(); + let reset_unix_seconds = retry_after + .and_then(|seconds| now.map(|now| now.saturating_add(seconds))) + .or_else(|| header("x-ratelimit-reset").filter(|_| exhausted)) + .filter(|reset| { + now.is_none_or(|now| *reset <= now.saturating_add(MAX_RATE_LIMIT_WAIT_SECS)) + }); + GitHubMetaError::RateLimited { reset_unix_seconds } +} + #[cfg(test)] mod tests { use super::*; - use crate::fixture_resolver::StaticResolver; - use crate::resolver::{ResolvedAddress, ResolvedChain}; use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; @@ -238,26 +224,8 @@ mod tests { #[tokio::test] #[ignore = "explicit anonymous HTTPS qualification against the official Meta API"] async fn live_official_meta_contract() { - let addresses = tokio::net::lookup_host((META_HOST, 443)) - .await - .unwrap() - .map(|address| ResolvedAddress { - ip: address.ip(), - ttl_secs: 60, - }) - .collect(); - let resolver = Arc::new(StaticResolver::new()); - resolver.set( - Name::from_ascii("api.github.com.").unwrap(), - ResolvedChain { - cname_chain: Vec::new(), - final_name: Name::from_ascii("api.github.com.").unwrap(), - addresses, - }, - ); - let client = OfficialGitHubMetaClient::new(resolver, Arc::new(crate::dialer::DirectDialer)); let GitHubMetaResponse::Modified { body, etag } = - client.fetch(&policy(false), None).await.unwrap() + fetch_official_github_meta(None).await.unwrap() else { panic!("an unconditional request must return a complete document") }; @@ -329,6 +297,53 @@ mod tests { assert!(matches!(cached, Ok(GitHubMetaResponse::NotModified))); } + #[tokio::test] + async fn primary_and_secondary_rate_limits_carry_their_reset_time() { + let now = crate::github_meta::unix_now().unwrap(); + let reset = now + 900; + let (primary, _) = exchange( + format!( + "HTTP/1.1 403 Forbidden\r\nX-RateLimit-Remaining: 0\r\nX-RateLimit-Reset: {reset}\r\nContent-Length: 0\r\n\r\n" + ) + .as_bytes(), + None, + ) + .await; + assert_eq!( + primary.err(), + Some(GitHubMetaError::RateLimited { + reset_unix_seconds: Some(reset) + }) + ); + let (secondary, _) = exchange( + b"HTTP/1.1 429 Too Many Requests\r\nRetry-After: 60\r\nContent-Length: 0\r\n\r\n", + None, + ) + .await; + assert!(matches!( + secondary, + Err(GitHubMetaError::RateLimited { reset_unix_seconds: Some(reset) }) + if (now + 60..=now + 61).contains(&reset) + )); + let (implausible, _) = exchange( + b"HTTP/1.1 403 Forbidden\r\nX-RateLimit-Remaining: 0\r\nX-RateLimit-Reset: 99999999999\r\nContent-Length: 0\r\n\r\n", + None, + ) + .await; + assert_eq!( + implausible.err(), + Some(GitHubMetaError::RateLimited { + reset_unix_seconds: None + }) + ); + let (forbidden, _) = exchange( + b"HTTP/1.1 403 Forbidden\r\nX-RateLimit-Remaining: 12\r\nContent-Length: 0\r\n\r\n", + None, + ) + .await; + assert_eq!(forbidden.err(), Some(GitHubMetaError::HttpStatus(403))); + } + #[tokio::test] async fn oversized_and_encoded_responses_are_rejected() { for headers in [ @@ -354,21 +369,8 @@ mod tests { } } - fn policy(blocked: bool) -> PolicyEngine { - PolicyEngine::compile( - &serde_json::from_value(serde_json::json!({ - "default_action": "deny", - "allowed_domains": ["github.com"], - "blocked_domains": if blocked { vec!["api.github.com"] } else { Vec::new() }, - "allow_dns": true - })) - .unwrap(), - ) - .unwrap() - } - #[tokio::test] - async fn official_client_pins_dns_and_verifies_the_fixed_tls_identity() { + async fn exact_ip_dial_verifies_the_fixed_tls_identity() { for certificate_name in ["api.github.com", "lookalike.test"] { let rcgen::CertifiedKey { cert, signing_key } = rcgen::generate_simple_self_signed(vec![certificate_name.to_owned()]).unwrap(); @@ -390,7 +392,7 @@ mod tests { .with_root_certificates(roots) .with_no_client_auth(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let dialer = Arc::new(LocalDialer(listener.local_addr().unwrap())); + let dialer = LocalDialer(listener.local_addr().unwrap()); let server = tokio::spawn(async move { let (stream, _) = listener.accept().await.unwrap(); let accepted = TlsAcceptor::from(Arc::new(server)).accept(stream).await; @@ -410,45 +412,15 @@ mod tests { .unwrap(); stream.shutdown().await.unwrap(); }); - let resolver = Arc::new(StaticResolver::new()); - resolver.set( - Name::from_ascii("api.github.com.").unwrap(), - ResolvedChain { - cname_chain: Vec::new(), - final_name: Name::from_ascii("api.github.com.").unwrap(), - addresses: vec![ResolvedAddress { - ip: "203.0.113.10".parse().unwrap(), - ttl_secs: 300, - }], - }, - ); - let client = OfficialGitHubMetaClient::new(resolver, dialer); - let result = client - .fetch_inner(&policy(false), None, Arc::new(client_tls)) - .await; + let result = fetch_via( + &["203.0.113.10".parse().unwrap()], + &dialer, + Arc::new(client_tls), + None, + ) + .await; assert_eq!(result.is_ok(), certificate_name == META_HOST); server.await.unwrap(); } } - - #[tokio::test] - async fn explicit_api_deny_prevents_the_control_plane_request() { - let client = OfficialGitHubMetaClient::new( - Arc::new(StaticResolver::new()), - Arc::new(crate::dialer::DirectDialer), - ); - let roots = RootCertStore::empty(); - let config = - ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) - .with_safe_default_protocol_versions() - .unwrap() - .with_root_certificates(roots) - .with_no_client_auth(); - assert!(matches!( - client - .fetch_inner(&policy(true), None, Arc::new(config)) - .await, - Err(GitHubMetaError::PolicyDenied) - )); - } } diff --git a/crates/sendbox-egress/src/policy.rs b/crates/sendbox-egress/src/policy.rs index 352d84c..df302d5 100644 --- a/crates/sendbox-egress/src/policy.rs +++ b/crates/sendbox-egress/src/policy.rs @@ -263,13 +263,16 @@ impl PolicyEngine { self.github_meta.as_ref() } - pub(crate) fn github_meta_name_permitted(&self, name: &str) -> bool { + /// Whether a delegating policy still admits the fixed Meta source. An + /// explicit `api.github.com` deny, disabled DNS, or a TCP/443 exclusion + /// keeps the session from starting instead of narrowing silently. + #[must_use] + pub fn github_meta_source_permitted(&self) -> bool { self.github_meta.is_some() && self.allow_dns - && !self - .blocked_domains - .iter() - .any(|pattern| domain::pattern_matches(pattern, name)) + && !self.blocked_domains.iter().any(|pattern| { + domain::pattern_matches(pattern, crate::github_meta_client::META_HOST) + }) && (self.allowed_ports.is_empty() || self .allowed_ports @@ -576,6 +579,33 @@ mod tests { assert!(PolicyEngine::compile(&raw).unwrap().github_meta().is_none()); } + #[test] + fn meta_source_denials_block_delegation_instead_of_narrowing_it() { + let mut raw = policy(Action::Deny); + raw.allowed_domains = vec!["github.com".to_owned()]; + assert!( + PolicyEngine::compile(&raw) + .unwrap() + .github_meta_source_permitted() + ); + let mut blocked = raw.clone(); + blocked.blocked_domains = vec!["api.github.com".to_owned()]; + let mut no_dns = raw.clone(); + no_dns.allow_dns = false; + let mut no_https = raw; + no_https.allowed_ports = vec![sendbox_policy::PortRule { + protocol: Protocol::Tcp, + port: 22, + }]; + for denied in [blocked, no_dns, no_https] { + assert!( + !PolicyEngine::compile(&denied) + .unwrap() + .github_meta_source_permitted() + ); + } + } + #[test] fn explicit_github_grant_adds_published_destinations_without_overriding_denies() { let mut raw = policy(Action::Deny); @@ -587,17 +617,23 @@ mod tests { engine .github_meta() .unwrap() - .install_response(crate::github_meta::GitHubMetaResponse::Modified { - body: serde_json::to_vec(&serde_json::json!({ - "verifiable_password_authentication": false, - "web": ["203.0.113.0/24"], - "api": ["2001:db8:1234::/48"], - "git": ["10.0.0.0/8"], - "domains": {"website": ["*.github.test"]} - })) - .unwrap(), - etag: Some("\"fixture-v1\"".to_owned()), - }) + .install_seed( + &crate::github_meta::GitHubMetaSeed { + body: serde_json::to_vec(&serde_json::json!({ + "verifiable_password_authentication": false, + "web": ["203.0.113.0/24"], + "api": ["2001:db8:1234::/48"], + "git": ["10.0.0.0/8"], + "domains": {"website": ["*.github.test"]} + })) + .unwrap(), + etag: Some("\"fixture-v1\"".to_owned()), + validated_unix_seconds: crate::github_meta::unix_now().unwrap(), + last_attempt_unix_seconds: crate::github_meta::unix_now().unwrap(), + last_error: None, + }, + &crate::audit::NullAuditSink, + ) .unwrap(); assert!(engine.evaluate_domain_name("api.github.test").unwrap()); assert!(!engine.evaluate_domain_name("denied.github.test").unwrap()); diff --git a/crates/sendbox-egress/src/runtime.rs b/crates/sendbox-egress/src/runtime.rs index 1d29c91..e863d22 100644 --- a/crates/sendbox-egress/src/runtime.rs +++ b/crates/sendbox-egress/src/runtime.rs @@ -236,6 +236,22 @@ impl RuntimePolicyDocument { Ok(false) } + /// Whether every role that delegates to GitHub Meta still admits its fixed + /// source host. The host refuses to seed a session when this is `false`. + pub fn github_meta_source_permitted(&self) -> Result { + for network in std::iter::once(&self.network_policy).chain( + self.registry + .as_ref() + .map(|registry| ®istry.upstream_network_policy), + ) { + let engine = PolicyEngine::compile(network)?; + if engine.github_meta().is_some() && !engine.github_meta_source_permitted() { + return Ok(false); + } + } + Ok(true) + } + #[must_use] pub fn execution_cgroup_parent(&self, cgroup_root: &Path) -> PathBuf { cgroup_root diff --git a/crates/sendbox-egress/tests/github_meta_integration.rs b/crates/sendbox-egress/tests/github_meta_integration.rs index 76fca4e..f402ac6 100644 --- a/crates/sendbox-egress/tests/github_meta_integration.rs +++ b/crates/sendbox-egress/tests/github_meta_integration.rs @@ -1,4 +1,3 @@ -use std::collections::VecDeque; use std::io; use std::net::{IpAddr, SocketAddr}; use std::sync::{Arc, Mutex}; @@ -14,9 +13,7 @@ use sendbox_egress::connect_proto::{ use sendbox_egress::dialer::{Dialer, DirectDialer}; use sendbox_egress::fixture_resolver::StaticResolver; use sendbox_egress::gateway::{Gateway, GatewayConfig, GatewayListeners}; -use sendbox_egress::github_meta::{ - GitHubMetaClient, GitHubMetaError, GitHubMetaResponse, GitHubMetaState, -}; +use sendbox_egress::github_meta::{GitHubMetaError, GitHubMetaSeed, GitHubMetaState, unix_now}; use sendbox_egress::policy::PolicyEngine; use sendbox_egress::resolver::{ResolvedAddress, ResolvedChain}; use sendbox_policy::NetworkPolicy; @@ -24,36 +21,6 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream, UdpSocket}; use tokio_util::sync::CancellationToken; -struct FixtureClient { - responses: Mutex>>, - requests: Mutex>>, -} - -impl FixtureClient { - fn new(responses: Vec>) -> Self { - Self { - responses: Mutex::new(responses.into()), - requests: Mutex::new(Vec::new()), - } - } -} - -#[async_trait::async_trait] -impl GitHubMetaClient for FixtureClient { - async fn fetch( - &self, - _policy: &PolicyEngine, - etag: Option<&str>, - ) -> Result { - self.requests.lock().unwrap().push(etag.map(str::to_owned)); - self.responses - .lock() - .unwrap() - .pop_front() - .expect("unexpected metadata request") - } -} - fn policy() -> NetworkPolicy { serde_json::from_value(serde_json::json!({ "default_action": "deny", @@ -64,21 +31,27 @@ fn policy() -> NetworkPolicy { .unwrap() } -fn metadata( - domains: &[&str], - v4: &str, - v6: &str, - etag: &str, -) -> Result { - Ok(GitHubMetaResponse::Modified { - body: serde_json::to_vec(&serde_json::json!({ +fn seed(body: Vec, etag: &str) -> GitHubMetaSeed { + let now = unix_now().unwrap(); + GitHubMetaSeed { + body, + etag: Some(etag.to_owned()), + validated_unix_seconds: now, + last_attempt_unix_seconds: now, + last_error: None, + } +} + +fn metadata(domains: &[&str], v4: &str, v6: &str, etag: &str) -> GitHubMetaSeed { + seed( + serde_json::to_vec(&serde_json::json!({ "verifiable_password_authentication": false, "web": [v4], "api": [v6], "git": [v4], "domains": {"website": domains} })) .unwrap(), - etag: Some(etag.to_owned()), - }) + etag, + ) } struct FixtureDialer { @@ -96,7 +69,6 @@ impl Dialer for FixtureDialer { struct Harness { engine: Arc, - client: Arc, resolver: Arc, audit: Arc, dialer: Arc, @@ -112,7 +84,7 @@ impl Harness { async fn start( raw: NetworkPolicy, frontend: ConnectFrontend, - responses: Vec>, + seed: Option, ) -> Self { let cancel = CancellationToken::new(); let echo_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -146,8 +118,7 @@ impl Harness { let engine = Arc::new(PolicyEngine::compile(&raw).unwrap()); let resolver = Arc::new(StaticResolver::new()); let audit = Arc::new(CollectingAuditSink::new()); - let client = Arc::new(FixtureClient::new(responses)); - let gateway = Gateway::new( + let mut gateway = Gateway::new( Arc::clone(&engine), Arc::clone(&resolver), Arc::clone(&dialer) as Arc<_>, @@ -159,9 +130,11 @@ impl Harness { }, ..GatewayConfig::default() }, - ) - .with_github_meta_client(Arc::clone(&client) as Arc<_>); - gateway.prepare_github_meta(&cancel).await.unwrap(); + ); + if let Some(seed) = seed { + gateway = gateway.with_github_meta_seed(seed); + } + gateway.prepare_github_meta().unwrap(); let listeners = GatewayListeners::bind_with_http_proxy( Some("127.0.0.1:0".parse().unwrap()), "127.0.0.1:0".parse().unwrap(), @@ -176,7 +149,6 @@ impl Harness { let gateway = tokio::spawn(async move { gateway.serve(listeners, gateway_cancel).await }); Self { engine, - client, resolver, audit, dialer, @@ -347,7 +319,22 @@ impl Harness { } #[tokio::test] -async fn failed_bootstrap_is_an_error_not_a_ready_exact_host_fallback() { +async fn missing_or_invalid_seed_is_an_error_not_a_ready_exact_host_fallback() { + let listeners = || GatewayListeners::bind(None, "127.0.0.1:0".parse().unwrap()); + let engine = Arc::new(PolicyEngine::compile(&policy()).unwrap()); + let unseeded = Gateway::new( + Arc::clone(&engine), + Arc::new(StaticResolver::new()), + Arc::new(DirectDialer), + Arc::new(CollectingAuditSink::new()), + GatewayConfig::default(), + ); + let error = unseeded + .serve(listeners().await.unwrap(), CancellationToken::new()) + .await + .unwrap_err(); + assert_eq!(error.to_string(), GitHubMetaError::MissingSeed.to_string()); + let engine = Arc::new(PolicyEngine::compile(&policy()).unwrap()); let audit = Arc::new(CollectingAuditSink::new()); let gateway = Gateway::new( @@ -357,15 +344,10 @@ async fn failed_bootstrap_is_an_error_not_a_ready_exact_host_fallback() { Arc::clone(&audit) as Arc<_>, GatewayConfig::default(), ) - .with_github_meta_client(Arc::new(FixtureClient::new(vec![Err( - GitHubMetaError::HttpStatus(503), - )]))); - let listeners = GatewayListeners::bind(None, "127.0.0.1:0".parse().unwrap()) - .await - .unwrap(); + .with_github_meta_seed(seed(b"{malformed".to_vec(), "\"bad\"")); assert!( gateway - .serve(listeners, CancellationToken::new()) + .serve(listeners().await.unwrap(), CancellationToken::new()) .await .is_err() ); @@ -375,7 +357,8 @@ async fn failed_bootstrap_is_an_error_not_a_ready_exact_host_fallback() { ); assert!( matches!(&audit.events()[0], AuditEvent::GitHubMeta { status } - if !status.grants_active && status.last_error == Some(GitHubMetaError::HttpStatus(503))) + if !status.grants_active + && matches!(status.last_error, Some(GitHubMetaError::InvalidDocument(_)))) ); } @@ -392,12 +375,12 @@ async fn metadata_scope_is_enforced_across_dns_native_socks_http_and_ip_families let h = Harness::start( raw, frontend, - vec![metadata( + Some(metadata( &["*.github.test", "edge.cdn.test"], "203.0.113.0/24", "2001:db8:1234::/48", "\"v1\"", - )], + )), ) .await; h.resolve("download.github.test", "203.0.113.1", Some("edge.cdn.test")); @@ -461,7 +444,6 @@ async fn metadata_scope_is_enforced_across_dns_native_socks_http_and_ip_families .iter() .any(|address| address.ip().is_ipv6()) ); - assert_eq!(h.client.requests.lock().unwrap().as_slice(), [None]); h.stop().await; } } @@ -472,7 +454,7 @@ async fn wildcard_grants_keep_apex_exact_host_and_label_boundaries_on_every_fron let mut raw = policy(); raw.allowed_domains = vec!["*.tools.test".to_owned(), "exact.test".to_owned()]; raw.blocked_domains = vec!["blocked.tools.test".to_owned()]; - let h = Harness::start(raw, frontend, Vec::new()).await; + let h = Harness::start(raw, frontend, None).await; for host in [ "a.tools.test", "nested.a.tools.test", @@ -499,35 +481,21 @@ async fn wildcard_grants_keep_apex_exact_host_and_label_boundaries_on_every_fron h.tunnel(frontend, host, 443, allowed).await; h.tunnel(ConnectFrontend::Http, host, 443, allowed).await; } - assert!(h.client.requests.lock().unwrap().is_empty()); h.stop().await; } } #[tokio::test] -async fn refresh_retires_removed_domains_networks_and_cached_cname_authorizations() { +async fn newer_seed_retires_removed_domains_networks_and_cached_cname_authorizations() { let h = Harness::start( policy(), ConnectFrontend::Socks5, - vec![ - metadata( - &["*.github.test", "edge.cdn.test"], - "203.0.113.0/24", - "2001:db8:1234::/48", - "\"v1\"", - ), - metadata( - &["*.github.test", "new.test"], - "198.51.100.0/24", - "2001:db8:5678::/48", - "\"v2\"", - ), - Ok(GitHubMetaResponse::Modified { - body: b"{malformed".to_vec(), - etag: Some("\"bad\"".to_owned()), - }), - Ok(GitHubMetaResponse::NotModified), - ], + Some(metadata( + &["*.github.test", "edge.cdn.test"], + "203.0.113.0/24", + "2001:db8:1234::/48", + "\"v1\"", + )), ) .await; h.resolve("download.github.test", "203.0.113.1", Some("edge.cdn.test")); @@ -543,10 +511,15 @@ async fn refresh_retires_removed_domains_networks_and_cached_cname_authorization .await; h.tunnel(ConnectFrontend::Http, "new.test", 443, false) .await; - let metadata = h.engine.github_meta().unwrap(); - metadata - .refresh_once(h.client.as_ref(), &h.engine, h.audit.as_ref()) - .await + let metadata_state = h.engine.github_meta().unwrap(); + let newer = metadata( + &["*.github.test", "new.test"], + "198.51.100.0/24", + "2001:db8:5678::/48", + "\"v2\"", + ); + metadata_state + .install_seed(&newer, h.audit.as_ref()) .unwrap(); h.tunnel(ConnectFrontend::Socks5, "download.github.test", 443, false) .await; @@ -555,54 +528,32 @@ async fn refresh_retires_removed_domains_networks_and_cached_cname_authorization .await; h.tunnel(ConnectFrontend::Http, "198.51.100.1", 443, true) .await; - h.tunnel(ConnectFrontend::Socks5, "2001:db8:1234::1", 443, false) + h.tunnel(ConnectFrontend::Socks5, "2001:db8:5678::1", 443, true) .await; - h.tunnel(ConnectFrontend::Http, "2001:db8:5678::1", 443, true) + h.tunnel(ConnectFrontend::Socks5, "2001:db8:1234::1", 443, false) .await; - let previous = metadata.status(); + let previous = metadata_state.status(); assert!( - metadata - .refresh_once(h.client.as_ref(), &h.engine, h.audit.as_ref()) - .await + metadata_state + .install_seed(&seed(b"{malformed".to_vec(), "\"bad\""), h.audit.as_ref()) .is_err() ); - assert_eq!(metadata.status().state, GitHubMetaState::Degraded); - assert_eq!(metadata.status().published_scope, previous.published_scope); - h.tunnel(ConnectFrontend::Http, "new.test", 443, true).await; - metadata - .refresh_once(h.client.as_ref(), &h.engine, h.audit.as_ref()) - .await - .unwrap(); - assert_eq!(metadata.status().state, GitHubMetaState::Fresh); + assert_eq!(metadata_state.status().state, GitHubMetaState::Degraded); assert_eq!( - h.client.requests.lock().unwrap().as_slice(), - [ - None, - Some("\"v1\"".to_owned()), - Some("\"v2\"".to_owned()), - Some("\"v2\"".to_owned()), - ] + metadata_state.status().published_scope, + previous.published_scope ); + h.tunnel(ConnectFrontend::Http, "new.test", 443, true).await; + metadata_state + .install_seed(&newer, h.audit.as_ref()) + .unwrap(); + assert_eq!(metadata_state.status().state, GitHubMetaState::Fresh); h.stop().await; } #[tokio::test] -async fn restarting_the_gateway_fetches_fresh_metadata_and_cannot_reuse_dns_pins() { +async fn restarting_the_gateway_reinstalls_its_seed_and_cannot_reuse_dns_pins() { let engine = Arc::new(PolicyEngine::compile(&policy()).unwrap()); - let client = Arc::new(FixtureClient::new(vec![ - metadata( - &["old.test"], - "203.0.113.0/24", - "2001:db8:1234::/48", - "\"old\"", - ), - metadata( - &["new.test"], - "198.51.100.0/24", - "2001:db8:5678::/48", - "\"new\"", - ), - ])); let gateway = Gateway::new( Arc::clone(&engine), Arc::new(StaticResolver::new()), @@ -610,19 +561,24 @@ async fn restarting_the_gateway_fetches_fresh_metadata_and_cannot_reuse_dns_pins Arc::new(CollectingAuditSink::new()), GatewayConfig::default(), ) - .with_github_meta_client(Arc::clone(&client) as Arc<_>); + .with_github_meta_seed(metadata( + &["fixture.test"], + "203.0.113.0/24", + "2001:db8:1234::/48", + "\"fixture\"", + )); let cache = gateway.authorizations(); let mut previous_revision = 0; - for name in ["old.test", "new.test"] { + for _ in 0..2 { let cancel = CancellationToken::new(); - gateway.prepare_github_meta(&cancel).await.unwrap(); - assert!(engine.evaluate_domain_name(name).unwrap()); + gateway.prepare_github_meta().unwrap(); + assert!(engine.evaluate_domain_name("fixture.test").unwrap()); let revision = engine.snapshot().revision(); assert_ne!(revision, previous_revision); previous_revision = revision; assert!(cache.is_empty()); cache.authorize_for_revision( - name, + "fixture.test", "203.0.113.1".parse().unwrap(), Duration::from_secs(300), revision, @@ -638,21 +594,19 @@ async fn restarting_the_gateway_fetches_fresh_metadata_and_cannot_reuse_dns_pins assert!(cache.is_empty()); assert!(!engine.github_meta().unwrap().status().grants_active); } - - assert_eq!(client.requests.lock().unwrap().as_slice(), [None, None]); } #[tokio::test] -async fn aborting_the_gateway_future_cancels_its_owned_refresh_and_scope() { +async fn aborting_the_gateway_future_revokes_its_scope() { let h = Harness::start( policy(), ConnectFrontend::Socks5, - vec![metadata( + Some(metadata( &["fixture.test"], "203.0.113.0/24", "2001:db8:1234::/48", "\"fixture\"", - )], + )), ) .await; tokio::task::yield_now().await; diff --git a/crates/sendbox-host/src/github_meta.rs b/crates/sendbox-host/src/github_meta.rs new file mode 100644 index 0000000..9340cdc --- /dev/null +++ b/crates/sendbox-host/src/github_meta.rs @@ -0,0 +1,429 @@ +//! Machine-wide cache for the official GitHub Meta document. +//! +//! Every `github.com`-delegating session needs one validated Meta response. +//! Fetching it per session and per gateway exhausted GitHub's anonymous limit +//! of 60 requests per hour per IP address. Sessions sharing a runtime state +//! root now reuse one file-locked cache: at most one conditional request per +//! refresh interval, failure backoff, and bounded last-good reuse. + +use std::future::Future; +use std::path::Path; +use std::time::Duration; + +use sendbox_egress::github_meta::{ + GitHubMetaError, GitHubMetaResponse, GitHubMetaScope, GitHubMetaSeed, MAX_SEED_BYTES, + META_MAX_CLOCK_SKEW, META_REFRESH_INTERVAL, META_REQUEST_TIMEOUT, unix_now, +}; +use sendbox_egress::github_meta_client::fetch_official_github_meta; +use sendbox_egress::runtime::RuntimePolicyDocument; +use sendbox_security::fs::{ExclusiveLock, PRIVATE_FILE_MODE, SecureRoot}; +use serde::{Deserialize, Serialize}; + +use crate::HostError; + +const CACHE_FILE: &str = "github-meta.json"; +const LOCK_FILE: &str = "github-meta.lock"; +const CACHE_SCHEMA_VERSION: u32 = 1; +const MAX_CACHE_BYTES: u64 = MAX_SEED_BYTES as u64 + 4096; +const FAILURE_BACKOFF_SECS: u64 = 60; +const MAX_RATE_LIMIT_BACKOFF_SECS: u64 = 60 * 60; +/// A reused last-good seed must outlive guest boot plus one bounded execution. +const MIN_FALLBACK_VALIDITY: Duration = Duration::from_secs(15 * 60); +const LOCK_WAIT: Duration = Duration::from_secs(3 * META_REQUEST_TIMEOUT.as_secs()); +const LOCK_POLL: Duration = Duration::from_millis(100); + +/// `document` is always stored as freshly validated; the file-level attempt +/// and error describe the latest refresh and are overlaid onto issued seeds. +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct CacheFile { + schema_version: u32, + document: Option, + last_attempt_unix_seconds: u64, + last_error: Option, +} + +impl CacheFile { + fn seed(&self) -> Option { + self.document.clone().map(|mut seed| { + seed.last_attempt_unix_seconds = self.last_attempt_unix_seconds; + seed.last_error.clone_from(&self.last_error); + seed + }) + } + + fn fresh(&self, now: u64) -> bool { + self.document.as_ref().is_some_and(|document| { + document.validated_unix_seconds <= now.saturating_add(META_MAX_CLOCK_SKEW.as_secs()) + && now.saturating_sub(document.validated_unix_seconds) + < META_REFRESH_INTERVAL.as_secs() + }) + } + + fn retry_at(&self) -> Option { + let backoff = self + .last_attempt_unix_seconds + .saturating_add(FAILURE_BACKOFF_SECS); + match self.last_error.as_ref()? { + GitHubMetaError::RateLimited { + reset_unix_seconds: Some(reset), + } => Some( + (*reset).clamp( + backoff, + self.last_attempt_unix_seconds + .saturating_add(MAX_RATE_LIMIT_BACKOFF_SECS), + ), + ), + _ => Some(backoff), + } + } +} + +/// Returns the seed a session's gateways need, or `None` when its egress +/// policy does not delegate to GitHub Meta. +pub(crate) async fn session_seed( + egress: Option<&RuntimePolicyDocument>, + state_root: &Path, +) -> Result, HostError> { + let Some(policy) = egress else { + return Ok(None); + }; + let invalid = + |error: sendbox_egress::policy::PolicyError| HostError::Invalid(error.to_string()); + if !policy.github_meta_enabled().map_err(invalid)? { + return Ok(None); + } + if !policy.github_meta_source_permitted().map_err(invalid)? { + return Err(GitHubMetaError::PolicyDenied.into()); + } + obtain_seed(state_root, |etag| async move { + fetch_official_github_meta(etag.as_deref()).await + }) + .await + .map(Some) +} + +async fn obtain_seed(state_root: &Path, fetch: F) -> Result +where + F: FnOnce(Option) -> Fut, + Fut: Future>, +{ + let root = SecureRoot::open(state_root)?; + let _lock = lock(&root).await?; + let now = unix_now()?; + let mut cache = read_cache(&root, now).unwrap_or(CacheFile { + schema_version: CACHE_SCHEMA_VERSION, + document: None, + last_attempt_unix_seconds: 0, + last_error: None, + }); + if cache.fresh(now) { + return Ok(cache.seed().expect("a fresh cache has a document")); + } + if let Some(error) = &cache.last_error + && cache.retry_at().is_some_and(|retry_at| now < retry_at) + { + return fallback(&cache, now, error.clone()); + } + let etag = cache + .document + .as_ref() + .and_then(|document| document.etag.clone()); + let outcome = fetch(etag) + .await + .and_then(|response| accept(response, cache.document.as_ref(), now)); + cache.last_attempt_unix_seconds = now; + match outcome { + Ok(document) => { + cache.document = Some(document); + cache.last_error = None; + persist(&root, &cache); + Ok(cache.seed().expect("a refreshed cache has a document")) + } + Err(error) => { + cache.last_error = Some(error.clone()); + persist(&root, &cache); + fallback(&cache, now, error) + } + } +} + +async fn lock(root: &SecureRoot) -> Result { + let deadline = tokio::time::Instant::now() + LOCK_WAIT; + loop { + if let Some(lock) = root.try_lock_exclusive(LOCK_FILE)? { + return Ok(lock); + } + if tokio::time::Instant::now() >= deadline { + return Err(HostError::Invalid(format!( + "another SendBox process held the GitHub Meta cache lock for {}s", + LOCK_WAIT.as_secs() + ))); + } + tokio::time::sleep(LOCK_POLL).await; + } +} + +fn accept( + response: GitHubMetaResponse, + previous: Option<&GitHubMetaSeed>, + now: u64, +) -> Result { + let document = match response { + GitHubMetaResponse::Modified { body, etag } => GitHubMetaSeed { + body, + etag, + validated_unix_seconds: now, + last_attempt_unix_seconds: now, + last_error: None, + }, + GitHubMetaResponse::NotModified => GitHubMetaSeed { + validated_unix_seconds: now, + last_attempt_unix_seconds: now, + last_error: None, + ..previous + .cloned() + .ok_or(GitHubMetaError::UnexpectedNotModified)? + }, + }; + document.validate(now)?; + Ok(document) +} + +fn fallback( + cache: &CacheFile, + now: u64, + error: GitHubMetaError, +) -> Result { + let Some(seed) = cache.seed().filter(|seed| { + seed.remaining_validity(now) + .is_ok_and(|remaining| remaining >= MIN_FALLBACK_VALIDITY) + }) else { + return Err(error.into()); + }; + eprintln!( + "sendbox: GitHub Meta refresh failed ({error}); reusing the shared copy validated {} minutes ago", + now.saturating_sub(seed.validated_unix_seconds) / 60 + ); + Ok(seed) +} + +fn read_cache(root: &SecureRoot, now: u64) -> Option { + let bytes = match root.read_bounded(CACHE_FILE, MAX_CACHE_BYTES) { + Ok(bytes) => bytes, + Err(sendbox_security::SecurityError::Io { source, .. }) + if source.kind() == std::io::ErrorKind::NotFound => + { + return None; + } + Err(error) => { + eprintln!("sendbox: ignoring unreadable GitHub Meta cache: {error}"); + return None; + } + }; + let mut cache = match serde_json::from_slice::(&bytes) { + Ok(cache) if cache.schema_version == CACHE_SCHEMA_VERSION => cache, + Ok(_) | Err(_) => { + eprintln!("sendbox: ignoring an invalid GitHub Meta cache"); + return None; + } + }; + // A tampered or truncated document must never become a grant; keep only + // whole documents, even when they are too old to reuse. + if cache.document.as_ref().is_some_and(|document| { + GitHubMetaScope::parse(&document.body).is_err() + || document.validated_unix_seconds > now.saturating_add(META_MAX_CLOCK_SKEW.as_secs()) + }) { + eprintln!("sendbox: discarding an invalid cached GitHub Meta document"); + cache.document = None; + } + Some(cache) +} + +fn persist(root: &SecureRoot, cache: &CacheFile) { + let result = serde_json::to_vec(cache) + .map_err(|error| error.to_string()) + .and_then(|bytes| { + root.write_atomic(CACHE_FILE, &bytes, MAX_CACHE_BYTES, PRIVATE_FILE_MODE) + .map_err(|error| error.to_string()) + }); + if let Err(error) = result { + eprintln!("sendbox: updating the shared GitHub Meta cache failed: {error}"); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + + fn document(website: &str) -> Vec { + serde_json::to_vec(&serde_json::json!({ + "verifiable_password_authentication": false, + "web": ["203.0.113.0/24"], "api": ["2001:db8::/32"], "git": ["203.0.113.1"], + "domains": {"website": [website]} + })) + .unwrap() + } + + fn modified(website: &str, etag: &str) -> Result { + Ok(GitHubMetaResponse::Modified { + body: document(website), + etag: Some(etag.to_owned()), + }) + } + + async fn never(_: Option) -> Result { + panic!("the shared cache must not contact GitHub here") + } + + fn age_cache(root: &Path, validated_ago: u64) { + let path = root.join(CACHE_FILE); + let mut cache: CacheFile = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + let validated = unix_now().unwrap() - validated_ago; + let document = cache.document.as_mut().unwrap(); + document.validated_unix_seconds = validated; + document.last_attempt_unix_seconds = validated; + cache.last_attempt_unix_seconds = validated; + std::fs::write(&path, serde_json::to_vec(&cache).unwrap()).unwrap(); + } + + #[tokio::test] + async fn sessions_share_one_fetch_per_refresh_interval_and_revalidate_by_etag() { + let root = tempfile::tempdir().unwrap(); + let first = obtain_seed(root.path(), |etag| async move { + assert_eq!(etag, None); + modified("one.github.test", "\"v1\"") + }) + .await + .unwrap(); + for _ in 0..3 { + assert_eq!(obtain_seed(root.path(), never).await.unwrap(), first); + } + assert_eq!( + std::fs::metadata(root.path().join(CACHE_FILE)) + .map( + |metadata| std::os::unix::fs::PermissionsExt::mode(&metadata.permissions()) + & 0o777 + ) + .unwrap(), + 0o600 + ); + + age_cache(root.path(), META_REFRESH_INTERVAL.as_secs()); + let revalidated = obtain_seed(root.path(), |etag| async move { + assert_eq!(etag.as_deref(), Some("\"v1\"")); + Ok(GitHubMetaResponse::NotModified) + }) + .await + .unwrap(); + assert_eq!(revalidated.body, first.body); + assert!(revalidated.validated_unix_seconds >= first.validated_unix_seconds); + assert!(revalidated.last_error.is_none()); + } + + #[tokio::test] + async fn rate_limited_refresh_reuses_last_good_and_backs_off_until_reset() { + let root = tempfile::tempdir().unwrap(); + obtain_seed(root.path(), |_| async { + modified("one.github.test", "\"v1\"") + }) + .await + .unwrap(); + age_cache(root.path(), 2 * META_REFRESH_INTERVAL.as_secs()); + let reset = unix_now().unwrap() + 600; + let limited = GitHubMetaError::RateLimited { + reset_unix_seconds: Some(reset), + }; + let calls = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&calls); + let error = limited.clone(); + let degraded = obtain_seed(root.path(), move |_| async move { + counter.fetch_add(1, Ordering::SeqCst); + Err(error) + }) + .await + .unwrap(); + assert_eq!(degraded.last_error, Some(limited)); + assert!(GitHubMetaScope::parse(°raded.body).is_ok()); + assert_eq!(obtain_seed(root.path(), never).await.unwrap(), degraded); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn without_a_usable_last_good_the_failure_is_surfaced_and_backed_off() { + let root = tempfile::tempdir().unwrap(); + let limited = GitHubMetaError::RateLimited { + reset_unix_seconds: None, + }; + let error = limited.clone(); + let failure = obtain_seed(root.path(), move |_| async move { Err(error) }) + .await + .unwrap_err(); + assert!(matches!(&failure, HostError::GitHubMeta(error) if *error == limited)); + assert!(matches!( + obtain_seed(root.path(), never).await, + Err(HostError::GitHubMeta(error)) if error == limited + )); + + let root = tempfile::tempdir().unwrap(); + obtain_seed(root.path(), |_| async { + modified("one.github.test", "\"v1\"") + }) + .await + .unwrap(); + let nearly_expired = + sendbox_egress::github_meta::META_MAX_STALENESS - MIN_FALLBACK_VALIDITY / 2; + age_cache(root.path(), nearly_expired.as_secs()); + assert!(matches!( + obtain_seed(root.path(), |_| async { + Err(GitHubMetaError::HttpStatus(503)) + }) + .await, + Err(HostError::GitHubMeta(GitHubMetaError::HttpStatus(503))) + )); + } + + #[tokio::test] + async fn invalid_or_tampered_documents_never_become_seeds() { + let root = tempfile::tempdir().unwrap(); + let malformed = obtain_seed(root.path(), |_| async { + Ok(GitHubMetaResponse::Modified { + body: b"{malformed".to_vec(), + etag: None, + }) + }) + .await; + assert!(matches!( + malformed, + Err(HostError::GitHubMeta(GitHubMetaError::InvalidDocument(_))) + )); + assert!(matches!( + obtain_seed(root.path(), |_| async { + Ok(GitHubMetaResponse::NotModified) + }) + .await, + Err(HostError::GitHubMeta(GitHubMetaError::InvalidDocument(_))) + )); + + let root = tempfile::tempdir().unwrap(); + obtain_seed(root.path(), |_| async { + modified("one.github.test", "\"v1\"") + }) + .await + .unwrap(); + let path = root.path().join(CACHE_FILE); + let mut cache: CacheFile = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + cache.document.as_mut().unwrap().body = b"{\"tampered\":true}".to_vec(); + std::fs::write(&path, serde_json::to_vec(&cache).unwrap()).unwrap(); + let refetched = obtain_seed(root.path(), |etag| async move { + assert_eq!(etag, None); + modified("two.github.test", "\"v2\"") + }) + .await + .unwrap(); + assert_eq!(refetched.body, document("two.github.test")); + } +} diff --git a/crates/sendbox-host/src/lib.rs b/crates/sendbox-host/src/lib.rs index ec3fe35..48fb738 100644 --- a/crates/sendbox-host/src/lib.rs +++ b/crates/sendbox-host/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod github_meta; mod masking; mod safe_outputs; mod security; @@ -39,6 +40,7 @@ use sendbox_credentials::{ CredentialBrokerError, GhMetadataClient, GhProcessConfiguration, GitHubSessionCredentials, RepositoryIdentity as CredentialRepositoryIdentity, authorize_github, }; +use sendbox_egress::github_meta::GitHubMetaSeed; use sendbox_egress::runtime::{ DEFAULT_REGISTRY_PROXY_PORT, DEFAULT_TRUSTED_REGISTRY_PORT, RuntimePolicyDocument as EgressRuntimePolicyDocument, requires_enforcement, @@ -359,9 +361,20 @@ pub enum HostError { }, #[error("bundle verification: {0}")] Bundle(String), + #[error("GitHub Meta: {0}")] + GitHubMeta(#[from] sendbox_egress::github_meta::GitHubMetaError), } impl HostError { + /// A configured deny of the fixed Meta source, as opposed to a fetch failure. + #[must_use] + pub fn is_github_meta_policy_denial(&self) -> bool { + matches!( + self, + Self::GitHubMeta(sendbox_egress::github_meta::GitHubMetaError::PolicyDenied) + ) + } + #[must_use] pub fn is_cancelled(&self) -> bool { match self { @@ -566,6 +579,7 @@ pub async fn prepare(mut request: HostRunRequest) -> Result Result Result Result, mcp_policy: Option<&RuntimePolicyDocument>, egress_policy: Option<&EgressRuntimePolicyDocument>, + github_meta: Option<&GitHubMetaSeed>, gateway_credentials: &[GatewayCredential], registry_proxy: Option<&PreparedRegistryProxy>, ) -> Result { @@ -1006,6 +1024,7 @@ fn build_runtime( configuration.mcp_policy = mcp_policy.cloned(); configuration.syscall_tracing = request.configuration.syscall_tracing_enabled(); configuration.egress_policy = egress_policy.cloned(); + configuration.github_meta = github_meta.cloned(); configuration.gateway_credentials = gateway_credentials.to_vec(); configuration.registry_proxy = registry_proxy.map(|prepared| prepared.bootstrap.clone()); @@ -1074,6 +1093,7 @@ fn build_runtime( mcp_policy: mcp_policy.cloned(), syscall_tracing: request.configuration.syscall_tracing_enabled(), egress_policy: egress_policy.cloned(), + github_meta: github_meta.cloned(), gateway_credentials: gateway_credentials.to_vec(), registry_proxy: registry_proxy.map(|prepared| prepared.bootstrap.clone()), workload_uid, @@ -1935,6 +1955,7 @@ fn boundary_features( git_guard_policy: Option<&GuardPolicyDocument>, mcp_policy: Option<&RuntimePolicyDocument>, egress_policy: Option<&EgressRuntimePolicyDocument>, + github_meta: Option<&GitHubMetaSeed>, credentials: &EffectiveCredentialSet, ) -> Result, HostError> { let mut features = BTreeMap::new(); @@ -2031,19 +2052,28 @@ fn boundary_features( mechanism: mechanism.clone(), }, ); - if policy + let delegated = policy .github_meta_enabled() - .map_err(|error| HostError::Invalid(error.to_string()))? - { - features.insert( - "network_github_meta".to_owned(), - FeatureAdmission { - decision: FeatureDecision::Enforced, - mechanism: format!( - "official_https_meta_v1+authenticated_network_report_v1:{mechanism}" - ), - }, - ); + .map_err(|error| HostError::Invalid(error.to_string()))?; + match (delegated, github_meta) { + (true, Some(seed)) => { + features.insert( + "network_github_meta".to_owned(), + FeatureAdmission { + decision: FeatureDecision::Enforced, + mechanism: format!( + "host_seeded_official_https_meta_v2:sha256={}+authenticated_network_report_v1:{mechanism}", + seed.sha256_hex() + ), + }, + ); + } + (false, None) => {} + _ => { + return Err(HostError::Invalid( + "a GitHub Meta seed must accompany exactly a github.com delegation".to_owned(), + )); + } } if policy.dns_port.is_some() { features.insert( @@ -2252,6 +2282,7 @@ struct SecurityComposition<'a> { git_guard_policy: Option<&'a GuardPolicyDocument>, mcp_policy: Option<&'a RuntimePolicyDocument>, egress_policy: Option<&'a EgressRuntimePolicyDocument>, + github_meta: Option<&'a GitHubMetaSeed>, credentials: &'a EffectiveCredentialSet, features: &'a BTreeMap, } @@ -2268,6 +2299,7 @@ fn validate_security_composition(composition: SecurityComposition<'_>) -> Result git_guard_policy, mcp_policy, egress_policy, + github_meta, credentials, features, } = composition; @@ -2357,6 +2389,7 @@ fn validate_security_composition(composition: SecurityComposition<'_>) -> Result git_guard_policy, mcp_policy, egress_policy, + github_meta, credentials, )?; if &expected_features != features { @@ -3129,7 +3162,8 @@ mod tests { copilot_auth: false, git_ssh_auth: false, }; - let features = boundary_features(&configuration, None, None, None, &credentials).unwrap(); + let features = + boundary_features(&configuration, None, None, None, None, &credentials).unwrap(); assert_eq!( features["syscall_tracing"].decision, FeatureDecision::Enforced @@ -3295,8 +3329,15 @@ mod tests { copilot_auth: false, git_ssh_auth: false, }; - let features = boundary_features(&configuration, None, Some(&policy), None, &credentials) - .expect("MCP features"); + let features = boundary_features( + &configuration, + None, + Some(&policy), + None, + None, + &credentials, + ) + .expect("MCP features"); assert!(features.contains_key("mcp_stdio_broker")); assert!(features.contains_key("mcp_stdio_observation")); validate_security_composition(SecurityComposition { @@ -3310,6 +3351,7 @@ mod tests { git_guard_policy: None, mcp_policy: Some(&policy), egress_policy: None, + github_meta: None, credentials: &credentials, features: &features, }) @@ -3319,9 +3361,15 @@ mod tests { drifted .fixed_environment .insert("PATH".to_owned(), "/tmp/bin".to_owned()); - let drifted_features = - boundary_features(&configuration, None, Some(&drifted), None, &credentials) - .expect("drifted features"); + let drifted_features = boundary_features( + &configuration, + None, + Some(&drifted), + None, + None, + &credentials, + ) + .expect("drifted features"); assert!( validate_security_composition(SecurityComposition { selected_runtime: ResolvedRuntime::Kata, @@ -3334,6 +3382,7 @@ mod tests { git_guard_policy: None, mcp_policy: Some(&drifted), egress_policy: None, + github_meta: None, credentials: &credentials, features: &drifted_features, }) @@ -3392,8 +3441,15 @@ mod tests { copilot_auth: false, git_ssh_auth: false, }; - let features = boundary_features(&configuration, None, Some(&policy), None, &credentials) - .expect("features"); + let features = boundary_features( + &configuration, + None, + Some(&policy), + None, + None, + &credentials, + ) + .expect("features"); assert!(features.contains_key("github_safe_outputs")); } @@ -3544,6 +3600,62 @@ mod tests { )); } + #[test] + fn github_delegation_binds_the_host_seed_digest_into_the_signed_plan() { + let temp = TempDir::new().expect("temp dir"); + let mut configuration = supported_configuration(temp.path().to_path_buf()); + configuration.policy.network.default_action = Action::Deny; + configuration.policy.network.allowed_domains = vec!["github.com".to_owned()]; + let egress = make_egress_policy(ResolvedRuntime::Kata, &configuration, test_session()) + .expect("egress policy") + .expect("restrictive network"); + let credentials = EffectiveCredentialSet { + values: BTreeMap::new(), + github_https_auth: false, + copilot_auth: false, + git_ssh_auth: false, + }; + assert!( + boundary_features( + &configuration, + None, + None, + Some(&egress), + None, + &credentials + ) + .is_err() + ); + let seed = GitHubMetaSeed { + body: b"{\"fixture\":1}".to_vec(), + etag: None, + validated_unix_seconds: 1_800_000_000, + last_attempt_unix_seconds: 1_800_000_000, + last_error: None, + }; + let mechanism = |seed: &GitHubMetaSeed| { + boundary_features( + &configuration, + None, + None, + Some(&egress), + Some(seed), + &credentials, + ) + .expect("seeded features") + .remove("network_github_meta") + .expect("Meta admission") + .mechanism + }; + assert!(mechanism(&seed).starts_with(&format!( + "host_seeded_official_https_meta_v2:sha256={}+", + seed.sha256_hex() + ))); + let mut other = seed.clone(); + other.body = b"{\"fixture\":2}".to_vec(); + assert_ne!(mechanism(&other), mechanism(&seed)); + } + #[test] fn authenticated_egress_binds_runtime_mcp_features_and_drift() { let temp = TempDir::new().expect("temp dir"); @@ -3564,9 +3676,15 @@ mod tests { git_ssh_auth: false, }; - let egress_only = - boundary_features(&configuration, None, None, Some(&egress), &credentials) - .expect("egress features"); + let egress_only = boundary_features( + &configuration, + None, + None, + Some(&egress), + None, + &credentials, + ) + .expect("egress features"); assert!(egress_only.contains_key("network_egress_enforcement")); assert!(egress_only.contains_key("network_dns_broker")); @@ -3601,6 +3719,7 @@ mod tests { None, Some(&mcp), Some(&egress), + None, &credentials, ) .expect("composed features"); @@ -3625,6 +3744,7 @@ mod tests { git_guard_policy: None, mcp_policy: Some(&mcp), egress_policy: Some(&egress), + github_meta: None, credentials: &credentials, features: &features, }) @@ -3637,6 +3757,7 @@ mod tests { None, Some(&mcp), Some(&drifted), + None, &credentials, ) .expect("drifted features"); @@ -3652,6 +3773,7 @@ mod tests { git_guard_policy: None, mcp_policy: Some(&mcp), egress_policy: Some(&drifted), + github_meta: None, credentials: &credentials, features: &drifted_features, }) @@ -3715,10 +3837,24 @@ mod tests { copilot_auth: false, git_ssh_auth: false, }; - let first = boundary_features(&configuration, Some(&policy), None, None, &credentials) - .expect("features"); - let second = boundary_features(&configuration, Some(&policy), None, None, &credentials) - .expect("features"); + let first = boundary_features( + &configuration, + Some(&policy), + None, + None, + None, + &credentials, + ) + .expect("features"); + let second = boundary_features( + &configuration, + Some(&policy), + None, + None, + None, + &credentials, + ) + .expect("features"); assert_eq!(first, second); let admission = first .get("git_branch_protection") @@ -3850,9 +3986,15 @@ mod tests { &credentials, ) .expect("policy"); - let mut features = - boundary_features(&configuration, policy.as_ref(), None, None, &credentials) - .expect("features"); + let mut features = boundary_features( + &configuration, + policy.as_ref(), + None, + None, + None, + &credentials, + ) + .expect("features"); validate_security_composition(SecurityComposition { selected_runtime: ResolvedRuntime::Kata, configuration: &configuration, @@ -3864,6 +4006,7 @@ mod tests { git_guard_policy: policy.as_ref(), mcp_policy: None, egress_policy: None, + github_meta: None, credentials: &credentials, features: &features, }) @@ -3882,6 +4025,7 @@ mod tests { git_guard_policy: policy.as_ref(), mcp_policy: None, egress_policy: None, + github_meta: None, credentials: &credentials, features: &features, }) @@ -3900,12 +4044,14 @@ mod tests { git_guard_policy: policy.as_ref(), mcp_policy: None, egress_policy: None, + github_meta: None, credentials: &credentials, features: &boundary_features( &configuration, policy.as_ref(), None, None, + None, &credentials, ) .expect("features"), diff --git a/crates/sendbox-host/src/security.rs b/crates/sendbox-host/src/security.rs index ed8bd30..350a942 100644 --- a/crates/sendbox-host/src/security.rs +++ b/crates/sendbox-host/src/security.rs @@ -1274,6 +1274,7 @@ impl HostError { Self::SafeOutputs(_) => "safe_outputs", Self::Io { .. } => "io", Self::Bundle(_) => "bundle", + Self::GitHubMeta(_) => "github_meta", } } } diff --git a/crates/sendbox-runtime-apple/src/provider.rs b/crates/sendbox-runtime-apple/src/provider.rs index 147879e..bea2010 100644 --- a/crates/sendbox-runtime-apple/src/provider.rs +++ b/crates/sendbox-runtime-apple/src/provider.rs @@ -13,6 +13,7 @@ use sendbox_bootstrap::{ REQUIRED_RUNTIME_CONTROLS, RegistryProxyConfiguration, encode_bootstrap_document, }; use sendbox_bundle::{Architecture, VerifyOptions, verify_bundle}; +use sendbox_egress::github_meta::GitHubMetaSeed; use sendbox_egress::runtime::{ DEFAULT_CGROUP_ROOT, RuntimePolicyDocument as EgressRuntimePolicyDocument, }; @@ -66,6 +67,7 @@ pub struct AppleRuntimeConfiguration { pub mcp_policy: Option, pub syscall_tracing: bool, pub egress_policy: Option, + pub github_meta: Option, pub gateway_credentials: Vec, pub registry_proxy: Option, pub workload_uid: u32, @@ -107,6 +109,7 @@ impl AppleRuntimeConfiguration { mcp_policy: None, syscall_tracing: false, egress_policy: None, + github_meta: None, gateway_credentials: Vec::new(), registry_proxy: None, workload_uid: 65_534, @@ -619,6 +622,7 @@ impl AppleRuntime { syscall_tracing: self.configuration.syscall_tracing, }), egress_policy: self.configuration.egress_policy.clone(), + github_meta: self.configuration.github_meta.clone(), gateway_credentials: self.configuration.gateway_credentials.clone(), registry_proxy: self.configuration.registry_proxy.clone(), }, diff --git a/crates/sendbox-runtime-kata/src/lib.rs b/crates/sendbox-runtime-kata/src/lib.rs index e2fa13e..554c2e8 100644 --- a/crates/sendbox-runtime-kata/src/lib.rs +++ b/crates/sendbox-runtime-kata/src/lib.rs @@ -16,6 +16,7 @@ use sendbox_bootstrap::{ REQUIRED_RUNTIME_CONTROLS, RegistryProxyConfiguration, encode_bootstrap_document, }; use sendbox_bundle::{Architecture, VerifyOptions, verify_bundle}; +use sendbox_egress::github_meta::GitHubMetaSeed; use sendbox_egress::runtime::{ DEFAULT_CGROUP_ROOT, RuntimePolicyDocument as EgressRuntimePolicyDocument, }; @@ -66,6 +67,7 @@ pub struct KataProviderConfiguration { pub mcp_policy: Option, pub syscall_tracing: bool, pub egress_policy: Option, + pub github_meta: Option, pub gateway_credentials: Vec, pub registry_proxy: Option, pub workload_uid: u32, @@ -1040,6 +1042,7 @@ fn bootstrap_payload( syscall_tracing: configuration.syscall_tracing, }), egress_policy: configuration.egress_policy.clone(), + github_meta: configuration.github_meta.clone(), gateway_credentials: configuration.gateway_credentials.clone(), registry_proxy: configuration.registry_proxy.clone(), }, @@ -1405,6 +1408,7 @@ mod tests { mcp_policy: None, syscall_tracing: false, egress_policy: None, + github_meta: None, gateway_credentials: Vec::new(), registry_proxy: None, workload_uid: 65_534, diff --git a/docs/architecture/egress-enforcement.md b/docs/architecture/egress-enforcement.md index 9d944e0..5bbc218 100644 --- a/docs/architecture/egress-enforcement.md +++ b/docs/architecture/egress-enforcement.md @@ -47,8 +47,8 @@ permits, and do so with a mechanism that: | `dns_broker` | Loopback DNS broker: decodes/validates/authorizes, applies budgets, emits audit events. | | `connect_broker` | Loopback CONNECT broker: selectable front end, pins the validated address, re-checks the port-aware decision, dials via a `Dialer`, proxies bytes. | | `gateway` | Colocates both brokers so they share one `AuthorizationCache`, engine, guard, and audit sink. | -| `github_meta` | Validates whole official Meta documents; owns single-flight, expiring immutable snapshots, conditional refresh and provenance. | -| `github_meta_client` | Anonymous fixed-origin HTTPS using the shared resolver and exact-IP marked dialer, verified TLS, bounded bodies and no redirects or environment proxy. | +| `github_meta` | Validates whole official Meta documents and host-supplied seeds; owns expiring immutable snapshots and provenance. | +| `github_meta_client` | Host-side anonymous fixed-origin HTTPS: system DNS, exact-IP direct dials, verified TLS, bounded bodies, rate-limit detection, and no redirects or environment proxy. | | `audit` | Typed, deterministic, serializable audit events and sinks. | | `dialer` | The `Dialer` abstraction and `SO_MARK`-aware socket helpers. | | `runtime` | Session-derived authenticated runtime policy, stable instance/table/mark identity, execution-cgroup parent, and exact proxy environment. | @@ -265,11 +265,43 @@ shutdown failures are aggregated rather than abandoning later cleanup. ### GitHub Meta delegation and refresh An effective exact `github.com` grant delegates to the fixed official Meta API. -Compilation stays offline and immutable for configured rules. The gateway must -successfully prepare a validated snapshot **after** its marked identity is -armed and **before** readiness. Its owned refresh task checks hourly with a -ten-second request deadline and conditional ETags. It is cancelled and drained -alongside the brokers, not detached or shared with unrelated sessions. +Compilation stays offline and immutable for configured rules. + +**The host owns the only fetch.** Each gateway used to fetch Meta before +readiness, so every session cost one or two anonymous requests against +GitHub's limit of 60 per hour per IP address. Many short sessions exhausted it +and then failed with HTTP 403. Now `sendbox-host` keeps one machine-wide cache +in the private runtime state root (`~/.sendbox/run/github-meta.json`, mode +`0600`, guarded by an exclusive `flock` on `github-meta.lock`): + +- A response validated less than an hour ago is reused without a request, so + concurrent and back-to-back sessions share it. +- An older response is revalidated with its ETag: a `304` renews it, a `200` + replaces it after full validation, and the cache costs at most one request + per hour per machine. +- A failed refresh is recorded with its time and typed error. Retries wait 60 + seconds, or until the published reset for a rate limit (403/429 with + `x-ratelimit-remaining: 0` or `retry-after`), capped at one hour. +- During a failure the previous document is reused only while at least 15 + minutes remain before its 24-hour expiry, so it outlives guest boot plus one + bounded execution. Otherwise the session fails with the typed error, + including the rate-limit reset time. +- Every cached document is reparsed with the strict validator on read. A + corrupt or tampered cache is discarded, never granted. + +The host also refuses delegation when a role denies the fixed source: an +explicit `api.github.com` deny, disabled DNS, or a TCP/443 exclusion. Role +address and network controls govern guest traffic, not this host request. + +The validated body, ETag, validation time, and latest attempt and error form a +`GitHubMetaSeed`. Its SHA-256 is bound into the signed `network_github_meta` +admission (`host_seeded_official_https_meta_v2:sha256=...`). The seed travels in +bootstrap schema v5, whose limit grows from 2 MiB to 5 MiB to fit a maximum +document. The guest supervisor writes it once to a root-owned `0400` file beside +the egress configuration. Each gateway reads it, revalidates the full document, +and installs it **after** its marked identity is armed and **before** +readiness. Guests never contact GitHub, and no refresh task runs in the guest: +an execution is capped at 300 seconds, far below the hourly interval. The parser explicitly reviews the documented CIDR fields plus the live `shared_ingress` field, the arrays under `domains`, the full/wildcard inbound @@ -280,24 +312,26 @@ entries and 4,096 domain entries before deduplication; default routes are rejected. The source is API version `2022-11-28`, not a caller-supplied URL. Each request evaluates one immutable scope view. DNS pins carry its revision; -every successful refresh/revalidation changes that revision, and an expiry -produces a scope-less view. New CONNECTs therefore cannot reuse authorizations -for removed CNAMEs. In-flight resolutions and dials recheck their revision. -Explicit domain/network denies, restricted-address checks, ports, DNS controls, -MCP reservations and trusted-registry separation remain authoritative. -Published networks only add public direct-IP reachability; they never unlock a +every installed seed changes that revision, and an expiry produces a +scope-less view. New CONNECTs therefore cannot reuse authorizations for removed +CNAMEs. In-flight resolutions and dials recheck their revision. Explicit +domain/network denies, restricted-address checks, ports, DNS controls, MCP +reservations and trusted-registry separation remain authoritative. Published +networks only add public direct-IP reachability; they never unlock a restricted address class or authorize an unlisted hostname. -An invalid initial response is fatal. A later failed refresh retains the -last-good scope only until 24 hours after successful validation, checked with a -monotonic clock on every new view. The status distinguishes pending, fresh, -degraded, unavailable and expired. The previous digest/scope remains diagnostic -after expiry, but has no granting power. No persistent authorization/feed cache -is loaded at restart. Existing tunnels retain their original 300-second bound; -refresh is not retroactive application-layer revocation. - -Before activating a candidate, production atomically publishes its full status -to a root-owned `0600` file under the existing private session directory. +A missing or invalid seed is fatal to the gateway. Expiry is 24 hours after the +host's last successful fetch or conditional revalidation. The gateway converts +the remaining time into a monotonic deadline at install time, because a freshly +booted guest cannot backdate an `Instant`, and checks it on every new view. +Seeds validated more than five minutes in the guest's future are rejected. The +status distinguishes pending, fresh, degraded (the host reused last-good after +a failed revalidation), unavailable and expired. The previous digest/scope +remains diagnostic after expiry, but has no granting power. Existing tunnels +retain their original 300-second bound. + +Before activating a seed, production atomically publishes its full status to a +root-owned `0600` file under the existing private session directory. Publication failure revokes derived scope and is fatal to the gateway. `AuditSink::record_github_meta` is fallible; the normal typed JSON event is also emitted. Unlike ordinary captured stderr counts, these files feed the bounded @@ -307,9 +341,10 @@ its URL, API version, digest, ETag, revision, timestamps and failure state. It is a latest-attempt snapshot, not an append-only audit history. The boundary-plan format remains v3. Its `network_github_meta` feature binds -the schema-v5 egress document digest and requires authenticated report -collection. Matching updated host/guest artifacts are necessary; release -v0.2.3 consumers do not acquire these semantics merely by changing settings. +the seed digest and the schema-v5 egress document digest, and requires +authenticated report collection. Matching updated host/guest artifacts are +necessary: older guests reject the new bootstrap field, and newer guests +reject a delegation without a seed. ## Atomic apply / update / rollback and fail-closed teardown diff --git a/docs/configuration.md b/docs/configuration.md index 4720fe2..1ac3f51 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -179,9 +179,13 @@ Add the apex separately when needed. Ordinary exact hosts remain exact; they do not implicitly grant subdomains. All CNAME hops must also be admitted. **`github.com` is an explicit delegation to the official GitHub Meta feed**, not -an apex-only grant. SendBox fetches the fixed anonymous HTTPS endpoint - before gateway readiness, then checks it hourly -using ETags. Only an effective exact apex grant triggers this behavior: +an apex-only grant. The host fetches the fixed anonymous HTTPS endpoint + into one cache shared by every session on the +machine (`~/.sendbox/run/github-meta.json`). It reuses that response for up to +an hour, then revalidates it with its ETag, so SendBox makes at most about one +request per hour per machine. Each session's gateways receive the validated +response before readiness and never contact GitHub themselves. Only an +effective exact apex grant triggers this behavior: `api.github.com`, `*.github.com`, and permissive defaults alone do not. The reviewed network fields and domain/endpoint fields, including their published wildcard patterns, become additional grants. SSH keys, commit keys, @@ -199,24 +203,26 @@ Explicit deny rules, private/link-local/metadata address protections, DNS budgets, reserved MCP origins, package-proxy isolation, and UDP/QUIC denial still apply. Published CIDRs never count as explicit private-address grants. -Initial HTTPS/TLS/DNS, policy-denial, rate-limit, or validation failure blocks -readiness rather than silently reverting to apex-only behavior. Later failures -are reported as `degraded` and preserve the previous validated snapshot for at -most 24 hours since its last successful fetch or conditional revalidation. -After that monotonic deadline, derived grants expire independently of the -refresh task; configured exact hosts and explicit networks are unchanged. -Blocking the Meta API, disabling DNS, excluding TCP/443, or omitting guest CA -certificates can therefore prevent a `github.com`-enabled session from starting. -Each request has a ten-second deadline, no redirects, environment proxy, or -credentials. Separate workload/registry gateways each own their refresh; many -short sessions can encounter GitHub's unauthenticated rate limit. - -Refresh affects **new connections in the current guest**, not just future -launches. Removed grants and CNAME permissions cannot survive through old DNS -pins. Already-open tunnels are not forcibly revoked and retain their existing -maximum 300-second lifetime. Cancellation stops the fetch/timer with the -gateway; a restart fetches again and never restores an authorization or -metadata cache from disk. +GitHub allows 60 anonymous API requests per hour per IP address, shared with +every other unauthenticated client behind that address. When a refresh fails, +including a 403/429 rate limit, the host records the error and waits 60 seconds +or until GitHub's published reset before retrying. Meanwhile it keeps using the +previous validated response while at least 15 minutes remain of its 24-hour +lifetime, and the session's network report shows `degraded` with the error. +Without such a response, the session fails before launch with the typed error +and the reset time. It never silently reverts to apex-only behavior. +Derived grants expire 24 hours after the host's last successful fetch or +conditional revalidation; configured exact hosts and explicit networks are +unchanged. An explicit `api.github.com` deny, disabled DNS, or a TCP/443 +exclusion makes a `github.com`-enabled session fail with an invalid +configuration error. Each request has a ten-second deadline, no redirects, +environment proxy, or credentials. The cached copy is revalidated with the +strict parser on every read, and a corrupt cache is discarded. + +A guest receives one validated response at boot and does not refresh it; guest +executions are capped at 300 seconds. Already-open tunnels retain their +existing maximum 300-second lifetime. A restart installs the same host-supplied +response again and cannot reuse earlier DNS pins. With `sendbox run --json`, the final `network_report: {path, sha256}` references a private host-side `network-egress-report.json`, following the package-report @@ -233,10 +239,11 @@ normal terminal response, not guaranteed after forced cancellation. pretend to resolve this live scope. This requires a matching updated host and signed guest bundle. The boundary -plan remains version 3, with a signed `network_github_meta` admission; the -internal egress runtime document is version 5 and `network.report` is -independently versioned at 1. Older guest bundles are rejected, not silently -accepted with narrower behavior. Hyperlight has no authenticated production +plan remains version 3, with a signed `network_github_meta` admission that +binds the response's SHA-256; the internal egress runtime document is version +5, the guest bootstrap is version 5, and `network.report` is independently +versioned at 1. Older guest bundles are rejected, not silently accepted with +narrower behavior. Hyperlight has no authenticated production Meta-refresh gateway. No release or consumer activation is implied by a source build. diff --git a/guest/sendbox-guest/src/bootstrap.rs b/guest/sendbox-guest/src/bootstrap.rs index df21da3..a71481b 100644 --- a/guest/sendbox-guest/src/bootstrap.rs +++ b/guest/sendbox-guest/src/bootstrap.rs @@ -198,6 +198,7 @@ mod tests { services: Vec::new(), execution_broker: None, egress_policy: None, + github_meta: None, gateway_credentials: Vec::new(), registry_proxy: None, }, diff --git a/guest/sendbox-guest/src/egress.rs b/guest/sendbox-guest/src/egress.rs index 74bc50e..101fa6c 100644 --- a/guest/sendbox-guest/src/egress.rs +++ b/guest/sendbox-guest/src/egress.rs @@ -23,6 +23,7 @@ use sendbox_bootstrap::{GatewayCredential, RegistryProxyConfiguration}; use sendbox_core::SessionId; #[cfg(any(target_os = "linux", test))] use sendbox_egress::address::{AddressClass, classify}; +use sendbox_egress::github_meta::GitHubMetaSeed; use sendbox_egress::runtime::RuntimePolicyDocument; use sendbox_mcp::runtime::RuntimePolicyDocument as McpRuntimePolicyDocument; use serde::{Deserialize, Serialize}; @@ -68,6 +69,8 @@ impl sendbox_egress::audit::AuditSink for MetadataFileAuditSink { } } +const GITHUB_META_SEED_FILE: &str = "egress-github-meta-seed.json"; + fn metadata_status_path(session_dir: &Path, registry: bool) -> PathBuf { session_dir.join(if registry { "egress-registry-meta.json" @@ -118,6 +121,7 @@ struct SupervisorProcessConfiguration { mcp_policy: Option, gateway_credentials: Vec, registry: Option, + github_meta_seed: Option, readiness_socket: PathBuf, workload_control_socket: PathBuf, trusted_control_socket: Option, @@ -132,6 +136,7 @@ struct GatewayProcessConfiguration { role: GatewayRole, mcp_policy: Option, gateway_credentials: Vec, + github_meta_seed: Option, upstream: SocketAddr, control_socket: PathBuf, control_token: String, @@ -189,10 +194,19 @@ pub fn prepare( mcp_policy: Option, gateway_credentials: Vec, registry: Option, + github_meta: Option, ) -> Result { policy .validate() .map_err(|error| GuestError::Runtime(format!("invalid egress policy: {error}")))?; + let delegated = policy + .github_meta_enabled() + .map_err(|error| GuestError::Runtime(format!("invalid egress policy: {error}")))?; + if delegated != github_meta.is_some() { + return Err(GuestError::Runtime( + "a GitHub Meta seed must accompany exactly a github.com delegation".to_owned(), + )); + } let mcp_policy = mcp_policy.filter(|policy| policy.tool_policy.has_remote_servers()); validate_mcp_gateway_configuration(&policy, mcp_policy.as_ref(), &gateway_credentials)?; let readiness_socket = session_dir.join("egress-ready.sock"); @@ -204,6 +218,14 @@ pub fn prepare( .as_ref() .map(|_| session_dir.join("registry-proxy-control.sock")); let config_path = session_dir.join("egress-supervisor.json"); + // Both gateway processes read this one host-validated response; it is too + // large for their bounded configuration files. + let github_meta_seed = github_meta + .map(|seed| { + let path = session_dir.join(GITHUB_META_SEED_FILE); + write_root_config(&path, &seed).map(|()| path) + }) + .transpose()?; write_root_config( &config_path, &SupervisorProcessConfiguration { @@ -212,6 +234,7 @@ pub fn prepare( mcp_policy, gateway_credentials, registry, + github_meta_seed, readiness_socket: readiness_socket.clone(), workload_control_socket, trusted_control_socket, @@ -280,7 +303,17 @@ pub async fn run_supervisor(config_path: PathBuf) -> Result<(), GuestError> { &config.workload_control_socket, config.trusted_control_socket.as_deref(), config.registry_control_socket.as_deref(), + config.github_meta_seed.as_deref(), )?; + let delegated = config + .policy + .github_meta_enabled() + .map_err(|error| GuestError::Runtime(format!("invalid egress policy: {error}")))?; + if delegated != config.github_meta_seed.is_some() { + return Err(GuestError::Runtime( + "a GitHub Meta seed must accompany exactly a github.com delegation".to_owned(), + )); + } if config.registry.is_some() != config.policy.registry.is_some() || config.registry.is_some() != config.trusted_control_socket.is_some() || config.registry.is_some() != config.registry_control_socket.is_some() @@ -316,6 +349,7 @@ pub async fn run_supervisor(config_path: PathBuf) -> Result<(), GuestError> { role: GatewayRole::Workload, mcp_policy: config.mcp_policy.clone(), gateway_credentials: config.gateway_credentials.clone(), + github_meta_seed: config.github_meta_seed.clone(), upstream: resolver.upstream, control_socket: config.workload_control_socket.clone(), control_token: workload_token.clone(), @@ -342,6 +376,7 @@ pub async fn run_supervisor(config_path: PathBuf) -> Result<(), GuestError> { role: GatewayRole::Registry, mcp_policy: None, gateway_credentials: Vec::new(), + github_meta_seed: config.github_meta_seed.clone(), upstream: resolver.upstream, control_socket: trusted_control_socket.clone(), control_token: trusted_token.clone(), @@ -917,7 +952,11 @@ pub async fn run_gateway(config_path: PathBuf) -> Result<(), GuestError> { OriginReservations::new(reserved_origins) .map_err(|error| GuestError::Runtime(format!("reserve MCP origins: {error}")))?, ); - let gateway = Gateway::new( + let github_meta_seed = match &config.github_meta_seed { + Some(path) if engine.github_meta().is_some() => Some(read_github_meta_seed(path)?), + _ => None, + }; + let mut gateway = Gateway::new( engine, resolver, Arc::new(MarkDialer::new(config.policy.broker_mark)), @@ -938,6 +977,9 @@ pub async fn run_gateway(config_path: PathBuf) -> Result<(), GuestError> { ..GatewayConfig::default() }, ); + if let Some(seed) = github_meta_seed { + gateway = gateway.with_github_meta_seed(seed); + } let http_gateway = match (config.mcp_policy, mcp_listener) { (Some(policy), Some(listener)) => { struct ReservationAdapter { @@ -1008,11 +1050,10 @@ pub async fn run_gateway(config_path: PathBuf) -> Result<(), GuestError> { )); } }; - let cancellation = CancellationToken::new(); gateway - .prepare_github_meta(&cancellation) - .await + .prepare_github_meta() .map_err(|error| GuestError::io("preparing GitHub Meta egress scope", error))?; + let cancellation = CancellationToken::new(); let gateway_cancellation = cancellation.clone(); let mut gateway_task = tokio::spawn(async move { gateway.serve(listeners, gateway_cancellation).await }); @@ -1652,6 +1693,18 @@ fn read_root_config Deserialize<'de>>(path: &Path) -> Result Result { + validate_root_file(path, 0o400)?; + let bytes = read_bounded( + path, + sendbox_egress::github_meta::MAX_SEED_BYTES, + "reading GitHub Meta seed", + )?; + serde_json::from_slice(&bytes) + .map_err(|error| GuestError::Runtime(format!("decode GitHub Meta seed: {error}"))) +} + #[cfg(target_os = "linux")] fn validate_root_file(path: &Path, mode: u32) -> Result<(), GuestError> { validate_owned_file(path, mode, 0, 0) @@ -1688,6 +1741,7 @@ fn validate_runtime_paths( workload_control: &Path, trusted_control: Option<&Path>, registry_control: Option<&Path>, + github_meta_seed: Option<&Path>, ) -> Result<(), GuestError> { let parent = config_path .parent() @@ -1709,6 +1763,10 @@ fn validate_runtime_paths( != Some("registry-proxy-control.sock") }) || trusted_control.is_some() != registry_control.is_some() + || github_meta_seed.is_some_and(|path| { + path.parent() != Some(parent) + || path.file_name().and_then(|name| name.to_str()) != Some(GITHUB_META_SEED_FILE) + }) { return Err(GuestError::Runtime( "egress runtime paths must be fixed files beneath the authenticated session directory" diff --git a/guest/sendbox-guest/src/supervisor.rs b/guest/sendbox-guest/src/supervisor.rs index ace3f1b..e86aa1e 100644 --- a/guest/sendbox-guest/src/supervisor.rs +++ b/guest/sendbox-guest/src/supervisor.rs @@ -183,6 +183,7 @@ pub async fn run( .and_then(|broker| broker.mcp_policy.clone()), std::mem::take(&mut bootstrap.gateway_credentials), registry_proxy, + bootstrap.github_meta.take(), )?; if bootstrap.required_services.contains(&ServiceId::Audit) && !service.dependencies.contains(&ServiceId::Audit) From 9dcd5536bea6cc2fca8db943592df46ecb94cd35 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 00:08:54 +0100 Subject: [PATCH 2/5] Fix CI: bump quinn-udp and authenticate Python preload quinn-udp 0.5.15 is affected by RUSTSEC-2026-0538; 0.5.16 is the patched release. The pinned Python preload called the GitHub release-asset API anonymously and hit the shared runner-IP rate limit (HTTP 403); pass the workflow token when available. --- .github/workflows/ci.yaml | 2 ++ Cargo.lock | 24 ++++++++++++------------ docs/contributing.md | 3 ++- scripts/setup-ci-python.sh | 7 +++++++ 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 4ee8e10..899662e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -38,6 +38,8 @@ jobs: - name: Preload pinned Python if: matrix.task == 'checks' + env: + GITHUB_TOKEN: ${{ github.token }} run: ./scripts/setup-ci-python.sh "$PYTHON_VERSION" - name: Set up stable Python diff --git a/Cargo.lock b/Cargo.lock index 0d0ee48..bcf5b00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -60,7 +60,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -71,7 +71,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -311,7 +311,7 @@ dependencies = [ "maybe-owned", "rustix", "rustix-linux-procfs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "winx", ] @@ -862,7 +862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2026,16 +2026,16 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2290,7 +2290,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2359,7 +2359,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3404,7 +3404,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3507,7 +3507,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4032,7 +4032,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/docs/contributing.md b/docs/contributing.md index 3a7683a..019add2 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -53,7 +53,8 @@ belong to the tap that owns formula updates, not this source repository. CI preloads the exact Python release asset through GitHub's release-asset API using `scripts/setup-ci-python.sh`, with SHA-256 verification and bounded retries before the normal `setup-python` action selects -it. The helper supports macOS arm64 and Ubuntu x64, including matching packages +it. The workflow passes its `GITHUB_TOKEN` so the request is not subject to the +anonymous 60-requests-per-hour limit shared by runner IP addresses. The helper supports macOS arm64 and Ubuntu x64, including matching packages for Ubuntu 22.04, 24.04, and 26.04. Update the workflow version, helper version, asset IDs, and checksums together when updating Python. diff --git a/scripts/setup-ci-python.sh b/scripts/setup-ci-python.sh index 4f00a8b..7b13c20 100755 --- a/scripts/setup-ci-python.sh +++ b/scripts/setup-ci-python.sh @@ -54,8 +54,15 @@ else directory="$(mktemp -d "$RUNNER_TEMP/python-api.XXXXXX")" trap 'rm -rf "$directory"' EXIT archive="$directory/python.tar.gz" + # Anonymous API calls share 60 requests/hour per runner IP; authenticate + # when the workflow token is available. curl drops it on the CDN redirect. + authorization=() + if [[ -n "${GITHUB_TOKEN:-}" ]]; then + authorization=(--header "Authorization: Bearer $GITHUB_TOKEN") + fi curl -fsSL --retry 5 --retry-max-time 600 --connect-timeout 10 --max-time 600 \ --header 'Accept: application/octet-stream' \ + ${authorization[@]+"${authorization[@]}"} \ "https://api.github.com/repos/actions/python-versions/releases/assets/$ASSET_ID" \ --output "$archive" printf '%s %s\n' "$SHA256" "$archive" | "${CHECKSUM_COMMAND[@]}" From 6289d374235afc282265fdcb948fa3e4354ee408 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 00:16:57 +0100 Subject: [PATCH 3/5] Fit seeded bootstraps through Kata injection Kata's inject-bootstrap read at most 128 KiB of stdin and framed the bootstrap as a JSON number array (about 4x expansion), so any Kata session carrying a GitHub Meta seed would fail to decode its envelope. Move the envelope into sendbox-bootstrap as base64 with a bound derived from MAX_BOOTSTRAP_BYTES, shared by the host encoder and guest decoder, and test a maximum-size seed through the Kata payload. --- Cargo.lock | 1 + crates/sendbox-bootstrap/Cargo.toml | 1 + crates/sendbox-bootstrap/src/lib.rs | 86 ++++++++++++++++++++++++++ crates/sendbox-runtime-kata/src/lib.rs | 58 ++++++++++------- guest/sendbox-guest/src/main.rs | 34 +++------- 5 files changed, 130 insertions(+), 50 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bcf5b00..371b66f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2498,6 +2498,7 @@ dependencies = [ name = "sendbox-bootstrap" version = "0.2.6" dependencies = [ + "base64", "getrandom 0.4.3", "sendbox-core", "sendbox-egress", diff --git a/crates/sendbox-bootstrap/Cargo.toml b/crates/sendbox-bootstrap/Cargo.toml index ff5443e..2d24d5e 100644 --- a/crates/sendbox-bootstrap/Cargo.toml +++ b/crates/sendbox-bootstrap/Cargo.toml @@ -7,6 +7,7 @@ license.workspace = true repository.workspace = true [dependencies] +base64.workspace = true getrandom.workspace = true sendbox-core = { path = "../sendbox-core" } sendbox-egress = { path = "../sendbox-egress" } diff --git a/crates/sendbox-bootstrap/src/lib.rs b/crates/sendbox-bootstrap/src/lib.rs index f898f5e..b3d734e 100644 --- a/crates/sendbox-bootstrap/src/lib.rs +++ b/crates/sendbox-bootstrap/src/lib.rs @@ -22,6 +22,9 @@ use zeroize::{Zeroize, Zeroizing}; pub const BOOTSTRAP_SCHEMA_VERSION: u32 = 5; /// Session configuration budget plus room for one host-validated Meta seed. pub const MAX_BOOTSTRAP_BYTES: usize = 2 * 1024 * 1024 + MAX_SEED_BYTES; +/// Base64 bootstrap plus a 32-byte trust root and fixed JSON framing. +pub const MAX_INJECTION_ENVELOPE_BYTES: usize = MAX_BOOTSTRAP_BYTES.div_ceil(3) * 4 + 1024; +const TRUST_ROOT_BYTES: usize = 32; const MAX_GATEWAY_CREDENTIALS: usize = 64; const MAX_GATEWAY_CREDENTIAL_BYTES: usize = 64 * 1024; pub const MAX_REGISTRY_CREDENTIALS: usize = 16; @@ -500,6 +503,74 @@ pub fn encode_bootstrap_document( Ok(Zeroizing::new(encoded)) } +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct InjectionEnvelope { + bootstrap: String, + trust_root: String, +} + +impl Drop for InjectionEnvelope { + fn drop(&mut self) { + self.bootstrap.zeroize(); + self.trust_root.zeroize(); + } +} + +/// Frames a bootstrap and its trust root for runtimes that inject both through +/// one stdin stream, such as Kata's `inject-bootstrap`. +pub fn encode_injection_envelope( + bootstrap: &[u8], + trust_root: &[u8], +) -> Result>, BootstrapError> { + use base64::Engine as _; + if bootstrap.len() > MAX_BOOTSTRAP_BYTES || trust_root.len() != TRUST_ROOT_BYTES { + return Err(BootstrapError::Invalid( + "injection envelope inputs exceed their bounds".to_owned(), + )); + } + let encoded = serde_json::to_vec(&InjectionEnvelope { + bootstrap: base64::engine::general_purpose::STANDARD.encode(bootstrap), + trust_root: base64::engine::general_purpose::STANDARD.encode(trust_root), + }) + .map_err(BootstrapError::Encode)?; + Ok(Zeroizing::new(encoded)) +} + +pub struct InjectedBootstrap { + pub bootstrap: Zeroizing>, + pub trust_root: Zeroizing>, +} + +/// Reverses [`encode_injection_envelope`] within its bounds. +pub fn decode_injection_envelope(bytes: &[u8]) -> Result { + use base64::Engine as _; + if bytes.len() > MAX_INJECTION_ENVELOPE_BYTES { + return Err(BootstrapError::Invalid(format!( + "injection envelope exceeds {MAX_INJECTION_ENVELOPE_BYTES} bytes" + ))); + } + let envelope: InjectionEnvelope = + serde_json::from_slice(bytes).map_err(BootstrapError::Decode)?; + let decode = |value: &str| { + base64::engine::general_purpose::STANDARD + .decode(value) + .map(Zeroizing::new) + .map_err(|_| BootstrapError::Invalid("injection envelope is not base64".to_owned())) + }; + let bootstrap = decode(&envelope.bootstrap)?; + let trust_root = decode(&envelope.trust_root)?; + if bootstrap.len() > MAX_BOOTSTRAP_BYTES || trust_root.len() != TRUST_ROOT_BYTES { + return Err(BootstrapError::Invalid( + "injected bootstrap or trust root has an invalid size".to_owned(), + )); + } + Ok(InjectedBootstrap { + bootstrap, + trust_root, + }) +} + pub fn decode_bootstrap_document(bytes: &[u8]) -> Result { if bytes.len() > MAX_BOOTSTRAP_BYTES { return Err(BootstrapError::Invalid(format!( @@ -1377,6 +1448,21 @@ mod tests { assert!(encode_bootstrap_document(configured(github, Some(oversized)), &[5; 32]).is_err()); } + #[test] + fn injection_envelope_round_trips_within_its_bound() { + let bootstrap = vec![0xa5; MAX_BOOTSTRAP_BYTES]; + let encoded = encode_injection_envelope(&bootstrap, &[7; 32]).expect("encode envelope"); + assert!(encoded.len() <= MAX_INJECTION_ENVELOPE_BYTES); + let decoded = decode_injection_envelope(&encoded).expect("decode envelope"); + assert_eq!(decoded.bootstrap.as_slice(), bootstrap.as_slice()); + assert_eq!(decoded.trust_root.as_slice(), [7; 32]); + + assert!(encode_injection_envelope(&bootstrap, &[7; 31]).is_err()); + assert!(encode_injection_envelope(&vec![0; MAX_BOOTSTRAP_BYTES + 1], &[7; 32]).is_err()); + assert!(decode_injection_envelope(&vec![b' '; MAX_INJECTION_ENVELOPE_BYTES + 1]).is_err()); + assert!(decode_injection_envelope(br#"{"bootstrap":"AA==","trust_root":"AA=="}"#).is_err()); + } + #[test] fn remote_mcp_bootstrap_requires_authenticated_egress() { let mut config = configuration(); diff --git a/crates/sendbox-runtime-kata/src/lib.rs b/crates/sendbox-runtime-kata/src/lib.rs index 554c2e8..8b010dd 100644 --- a/crates/sendbox-runtime-kata/src/lib.rs +++ b/crates/sendbox-runtime-kata/src/lib.rs @@ -14,6 +14,7 @@ use std::time::Duration; use sendbox_bootstrap::{ BootstrapDocumentConfiguration, ExecutionBrokerConfiguration, GatewayCredential, REQUIRED_RUNTIME_CONTROLS, RegistryProxyConfiguration, encode_bootstrap_document, + encode_injection_envelope, }; use sendbox_bundle::{Architecture, VerifyOptions, verify_bundle}; use sendbox_egress::github_meta::GitHubMetaSeed; @@ -33,7 +34,6 @@ use sendbox_runtime::{ RuntimeHealth, RuntimeId, RuntimeProvider, RuntimeSignal, RuntimeStatus, SearchPathResolver, StartRequest, StopRequest, }; -use serde::Serialize; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadBuf}; use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command}; use tokio::task::JoinHandle; @@ -991,19 +991,13 @@ impl OutputSubscription for OwnedProcessSubscription { } } -#[derive(Serialize)] -struct BootstrapEnvelope<'a> { - bootstrap: &'a [u8], - trust_root: &'a [u8], -} - fn bootstrap_payload( configuration: &KataProviderConfiguration, channel: &ControlChannelRequest, create: &sendbox_runtime::CreateRequest, secret: &[u8], trust_root: &[u8], -) -> Result, RuntimeError> { +) -> Result>, RuntimeError> { let workspace = create .mounts .iter() @@ -1049,11 +1043,8 @@ fn bootstrap_payload( secret, ) .map_err(|error| RuntimeError::Provider(format!("encode bootstrap: {error}")))?; - serde_json::to_vec(&BootstrapEnvelope { - bootstrap: bootstrap.as_ref(), - trust_root, - }) - .map_err(|error| RuntimeError::Provider(format!("encode bootstrap injection: {error}"))) + encode_injection_envelope(&bootstrap, trust_root) + .map_err(|error| RuntimeError::Provider(format!("encode bootstrap injection: {error}"))) } fn strict_host_preflight( @@ -1370,7 +1361,7 @@ fn spawn_stderr_capture(stderr: ChildStderr) -> JoinHandle> { mod tests { use std::os::unix::fs::PermissionsExt; - use sendbox_bootstrap::decode_bootstrap_document; + use sendbox_bootstrap::{decode_bootstrap_document, decode_injection_envelope}; use sendbox_core::{BoundaryPlanDigest, SessionId}; use sendbox_policy::Action; use sendbox_runtime::{ @@ -1457,12 +1448,6 @@ mod tests { assert!(KataRuntimeProvider::new(config).is_err()); } - #[derive(serde::Deserialize)] - struct DecodedBootstrapEnvelope { - bootstrap: Vec, - trust_root: Vec, - } - #[test] fn kata_wraps_the_shared_guest_bootstrap_document() { let temporary = tempdir().expect("temporary"); @@ -1505,11 +1490,10 @@ mod tests { let payload = bootstrap_payload(&configuration, &channel, &create, &[9; 32], &[7; 32]) .expect("Kata bootstrap envelope"); - let envelope: DecodedBootstrapEnvelope = - serde_json::from_slice(&payload).expect("bootstrap envelope JSON"); - assert_eq!(envelope.trust_root, vec![7; 32]); + let injected = decode_injection_envelope(&payload).expect("bootstrap envelope"); + assert_eq!(injected.trust_root.as_slice(), [7; 32]); let decoded = - decode_bootstrap_document(&envelope.bootstrap).expect("shared guest bootstrap schema"); + decode_bootstrap_document(&injected.bootstrap).expect("shared guest bootstrap schema"); assert_eq!(decoded.session_id, channel.session_id); assert_eq!(decoded.boundary_plan_digest, channel.boundary_plan_digest); assert_eq!( @@ -1524,6 +1508,32 @@ mod tests { broker.cgroup_parent, egress.execution_cgroup_parent(Path::new(DEFAULT_CGROUP_ROOT)) ); + + // A maximum-size GitHub Meta seed must still fit the guest's stdin bound. + let mut github = egress.network_policy.clone(); + github.allowed_domains = vec!["github.com".to_owned()]; + configuration.egress_policy = Some(EgressRuntimePolicyDocument::for_session( + create.session_id, + github, + )); + let seed = sendbox_egress::github_meta::GitHubMetaSeed { + body: vec![b'x'; sendbox_egress::github_meta::MAX_META_BYTES], + etag: Some("\"fixture\"".to_owned()), + validated_unix_seconds: 1_800_000_000, + last_attempt_unix_seconds: 1_800_000_000, + last_error: None, + }; + configuration.github_meta = Some(seed.clone()); + let payload = bootstrap_payload(&configuration, &channel, &create, &[9; 32], &[7; 32]) + .expect("seeded Kata bootstrap envelope"); + assert!(payload.len() <= sendbox_bootstrap::MAX_INJECTION_ENVELOPE_BYTES); + let injected = decode_injection_envelope(&payload).expect("seeded envelope"); + assert_eq!( + decode_bootstrap_document(&injected.bootstrap) + .expect("seeded bootstrap") + .github_meta, + Some(seed) + ); } #[tokio::test] diff --git a/guest/sendbox-guest/src/main.rs b/guest/sendbox-guest/src/main.rs index 008741f..bed268b 100644 --- a/guest/sendbox-guest/src/main.rs +++ b/guest/sendbox-guest/src/main.rs @@ -315,16 +315,9 @@ async fn execute(cli: Cli) -> Result<(), GuestError> { Commands::InjectBootstrap(args) => inject_bootstrap(args).await, }; - #[derive(serde::Deserialize)] - #[serde(deny_unknown_fields)] - struct InjectionEnvelope { - bootstrap: Vec, - trust_root: Vec, - } - async fn inject_bootstrap(args: InjectBootstrapArgs) -> Result<(), GuestError> { + use sendbox_bootstrap::{MAX_INJECTION_ENVELOPE_BYTES, decode_injection_envelope}; use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; - use zeroize::Zeroize; if args.bootstrap_target.parent() != args.trust_root_target.parent() || !args.bootstrap_target.is_absolute() @@ -346,28 +339,17 @@ async fn execute(cli: Cli) -> Result<(), GuestError> { sendbox_guest::platform::prepare_native_exec_cgroup(Path::new("/sys/fs/cgroup"))?; std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)) .map_err(|error| GuestError::io("setting bootstrap injection directory mode", error))?; - let mut encoded = Vec::new(); + let mut encoded = zeroize::Zeroizing::new(Vec::new()); tokio::io::stdin() - .take(128 * 1024) + .take(u64::try_from(MAX_INJECTION_ENVELOPE_BYTES + 1).expect("envelope bound fits u64")) .read_to_end(&mut encoded) .await .map_err(|error| GuestError::io("reading injected bootstrap", error))?; - let mut envelope: InjectionEnvelope = - serde_json::from_slice(&encoded).map_err(|error| { - GuestError::Bootstrap(format!("decode injection envelope: {error}")) - })?; - encoded.zeroize(); - if envelope.trust_root.len() != 32 { - envelope.bootstrap.zeroize(); - envelope.trust_root.zeroize(); - return Err(GuestError::Bootstrap( - "injected trust root must contain exactly 32 bytes".to_owned(), - )); - } - write_injected(&args.bootstrap_target, &envelope.bootstrap, 0o400)?; - write_injected(&args.trust_root_target, &envelope.trust_root, 0o444)?; - envelope.bootstrap.zeroize(); - envelope.trust_root.zeroize(); + let injected = decode_injection_envelope(&encoded).map_err(|error| { + GuestError::Bootstrap(format!("decode injection envelope: {error}")) + })?; + write_injected(&args.bootstrap_target, &injected.bootstrap, 0o400)?; + write_injected(&args.trust_root_target, &injected.trust_root, 0o444)?; Ok(()) } From 61e08554cd6d1a4578ab957e3f1d3b8240fd41f3 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 00:23:10 +0100 Subject: [PATCH 4/5] Authenticate pinned libseccomp downloads in CI image builds The guest bundle and supervisor Dockerfiles fetch the libseccomp release asset through GitHub's API anonymously, which now returns 403 on shared runner addresses. Accept an optional github_token BuildKit secret and pass the workflow token from every CI and release invocation. The secret never enters a layer, so reproducible outputs are unchanged. --- .github/workflows/guest-artifacts.yaml | 13 +++++++++++++ .github/workflows/guest-supervisor.yaml | 6 ++++++ .github/workflows/release.yaml | 2 ++ docs/architecture/guest-artifact-bundles.md | 5 ++++- docs/architecture/guest-supervisor.md | 3 ++- guest/sendbox-guest/Dockerfile | 9 ++++++++- packaging/guest/Dockerfile | 9 ++++++++- 7 files changed, 43 insertions(+), 4 deletions(-) diff --git a/.github/workflows/guest-artifacts.yaml b/.github/workflows/guest-artifacts.yaml index 661b83a..b1e6e54 100644 --- a/.github/workflows/guest-artifacts.yaml +++ b/.github/workflows/guest-artifacts.yaml @@ -66,6 +66,7 @@ jobs: - name: Cache pinned quality build dependencies uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: + secrets: github_token=${{ github.token }} context: . file: packaging/guest/Dockerfile platforms: linux/amd64 @@ -76,8 +77,11 @@ jobs: outputs: type=cacheonly - name: Run fresh quality checks + env: + GITHUB_TOKEN: ${{ github.token }} run: | docker buildx build \ + --secret "id=github_token,env=GITHUB_TOKEN" \ --no-cache-filter quality \ --platform linux/amd64 \ --build-arg CARGO_BUILD_JOBS=2 \ @@ -114,8 +118,11 @@ jobs: chmod 0400 "$RUNNER_TEMP/guest-artifact-ci.key" - name: Build independent bundle without cache + env: + GITHUB_TOKEN: ${{ github.token }} run: | docker buildx build \ + --secret "id=github_token,env=GITHUB_TOKEN" \ --no-cache \ --platform "linux/${{ matrix.architecture }}" \ --build-arg CARGO_BUILD_JOBS=2 \ @@ -127,8 +134,11 @@ jobs: - name: Export OCI layout from the same build if: matrix.attempt == 'first' + env: + GITHUB_TOKEN: ${{ github.token }} run: | docker buildx build \ + --secret "id=github_token,env=GITHUB_TOKEN" \ --platform "linux/${{ matrix.architecture }}" \ --build-arg CARGO_BUILD_JOBS=2 \ --target image \ @@ -272,8 +282,11 @@ jobs: clang libelf-dev libzstd-dev make pkg-config zlib1g-dev - name: Export architecture-specific BPF object + env: + GITHUB_TOKEN: ${{ github.token }} run: | docker build \ + --secret "id=github_token,env=GITHUB_TOKEN" \ --no-cache \ --platform "linux/${{ matrix.platform }}" \ --target bpf-artifact \ diff --git a/.github/workflows/guest-supervisor.yaml b/.github/workflows/guest-supervisor.yaml index 0263704..121002b 100644 --- a/.github/workflows/guest-supervisor.yaml +++ b/.github/workflows/guest-supervisor.yaml @@ -41,8 +41,11 @@ jobs: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - name: Run pinned quality environment + env: + GITHUB_TOKEN: ${{ github.token }} run: | docker build \ + --secret "id=github_token,env=GITHUB_TOKEN" \ --no-cache \ --build-arg CARGO_BUILD_JOBS=2 \ --file guest/sendbox-guest/Dockerfile \ @@ -69,9 +72,12 @@ jobs: driver-opts: image=moby/buildkit:buildx-stable-1@sha256:2f5adac4ecd194d9f8c10b7b5d7bceb5186853db1b26e5abd3a657af0b7e26ec - name: Build twice without cache + env: + GITHUB_TOKEN: ${{ github.token }} run: | for attempt in first second; do docker buildx build \ + --secret "id=github_token,env=GITHUB_TOKEN" \ --no-cache \ --platform "linux/${{ matrix.architecture }}" \ --build-arg CARGO_BUILD_JOBS=2 \ diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 789a496..dcc5658 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -140,6 +140,7 @@ jobs: - name: Build signed reproducible guest bundle shell: bash env: + GITHUB_TOKEN: ${{ github.token }} VERSION: ${{ github.ref_name }} run: | set -euo pipefail @@ -162,6 +163,7 @@ jobs: fi docker buildx build \ + --secret "id=github_token,env=GITHUB_TOKEN" \ --no-cache \ --platform "linux/${{ matrix.platform }}" \ --target artifact \ diff --git a/docs/architecture/guest-artifact-bundles.md b/docs/architecture/guest-artifact-bundles.md index c1edb2b..086064e 100644 --- a/docs/architecture/guest-artifact-bundles.md +++ b/docs/architecture/guest-artifact-bundles.md @@ -119,7 +119,10 @@ Build inputs: Supervisor and production bundle builds download the pinned libseccomp source through GitHub's release-asset API using its immutable asset ID. Requests use bounded connection, transfer, and retry timeouts. The pinned version and SHA-256 -verification remain mandatory; exhausted retries fail the build. +verification remain mandatory; exhausted retries fail the build. An optional +BuildKit secret `github_token` authenticates the request so shared CI runner +addresses do not hit GitHub's anonymous limit of 60 requests per hour; CI passes +`--secret id=github_token,env=GITHUB_TOKEN`. It never reaches an image layer. The production bundle, standalone supervisor, and BPF spike Dockerfiles use the same `musl-dev`, `zlib`, `zlib-dev`, and `zlib-static` revisions, available for both diff --git a/docs/architecture/guest-supervisor.md b/docs/architecture/guest-supervisor.md index d1a7236..60bc253 100644 --- a/docs/architecture/guest-supervisor.md +++ b/docs/architecture/guest-supervisor.md @@ -209,7 +209,8 @@ dependency. The pinned libseccomp source is downloaded through GitHub's release-asset API using its immutable asset ID, with bounded retries and network timeouts. -SHA-256 verification remains mandatory before extraction. +SHA-256 verification remains mandatory before extraction. The optional +`github_token` BuildKit secret authenticates the request in CI. Guest Supervisor CI passes `--build-arg CARGO_BUILD_JOBS=2` to the quality build and both clean builds on each native architecture, matching production bundle diff --git a/guest/sendbox-guest/Dockerfile b/guest/sendbox-guest/Dockerfile index 8026a86..a205e00 100644 --- a/guest/sendbox-guest/Dockerfile +++ b/guest/sendbox-guest/Dockerfile @@ -36,8 +36,15 @@ RUN case "$TARGETARCH" in \ && printf '%s\n' "$target" >/opt/target-triple FROM toolchain AS libseccomp -RUN curl -fsSL --retry 5 --retry-max-time 120 --connect-timeout 10 --max-time 60 \ +# Anonymous API calls share 60 requests/hour per IP; CI passes its token so +# shared runner addresses do not exhaust it. curl drops it on the CDN redirect. +RUN --mount=type=secret,id=github_token,required=false \ + if [ -s /run/secrets/github_token ]; then \ + set -- --header "Authorization: Bearer $(cat /run/secrets/github_token)"; \ + fi \ + && curl -fsSL --retry 5 --retry-max-time 120 --connect-timeout 10 --max-time 60 \ --header 'Accept: application/octet-stream' \ + "$@" \ https://api.github.com/repos/seccomp/libseccomp/releases/assets/222948192 \ -o /tmp/libseccomp.tar.gz \ && echo "83b6085232d1588c379dc9b9cae47bb37407cf262e6e74993c61ba72d2a784dc /tmp/libseccomp.tar.gz" \ diff --git a/packaging/guest/Dockerfile b/packaging/guest/Dockerfile index aa699f4..b8ce1bc 100644 --- a/packaging/guest/Dockerfile +++ b/packaging/guest/Dockerfile @@ -68,8 +68,15 @@ RUN case "$TARGETARCH" in \ && rm -f /tmp/vmlinux.btf.tar.xz /tmp/5.8.0-63-generic.btf FROM toolchain AS libseccomp -RUN curl -fsSL --retry 5 --retry-max-time 120 --connect-timeout 10 --max-time 60 \ +# Anonymous API calls share 60 requests/hour per IP; CI passes its token so +# shared runner addresses do not exhaust it. curl drops it on the CDN redirect. +RUN --mount=type=secret,id=github_token,required=false \ + if [ -s /run/secrets/github_token ]; then \ + set -- --header "Authorization: Bearer $(cat /run/secrets/github_token)"; \ + fi \ + && curl -fsSL --retry 5 --retry-max-time 120 --connect-timeout 10 --max-time 60 \ --header 'Accept: application/octet-stream' \ + "$@" \ https://api.github.com/repos/seccomp/libseccomp/releases/assets/222948192 \ -o /tmp/libseccomp.tar.gz \ && echo "83b6085232d1588c379dc9b9cae47bb37407cf262e6e74993c61ba72d2a784dc /tmp/libseccomp.tar.gz" \ From da663ae77ee551a55c51f18f1c058502752068cc Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 00:30:28 +0100 Subject: [PATCH 5/5] Refresh fuzz lockfiles for base64 and quinn-udp 0.5.16 Fuzz workspaces lock sendbox-egress and sendbox-bootstrap separately, so make fuzz-check --locked needs the new base64 edge. Also apply the RUSTSEC-2026-0538 quinn-udp fix in the two fuzz locks that carry it. --- fuzz/bpf/Cargo.lock | 2 ++ fuzz/credentials/Cargo.lock | 23 ++++++++++++----------- fuzz/mcp/Cargo.lock | 1 + fuzz/registry/Cargo.lock | 16 ++++++++-------- 4 files changed, 23 insertions(+), 19 deletions(-) diff --git a/fuzz/bpf/Cargo.lock b/fuzz/bpf/Cargo.lock index 34212e9..6e54cd1 100644 --- a/fuzz/bpf/Cargo.lock +++ b/fuzz/bpf/Cargo.lock @@ -1403,6 +1403,7 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" name = "sendbox-bootstrap" version = "0.2.6" dependencies = [ + "base64", "getrandom 0.4.3", "sendbox-core", "sendbox-egress", @@ -1478,6 +1479,7 @@ name = "sendbox-egress" version = "0.2.6" dependencies = [ "async-trait", + "base64", "bytes", "cap-std", "clap", diff --git a/fuzz/credentials/Cargo.lock b/fuzz/credentials/Cargo.lock index 4cd4109..959135b 100644 --- a/fuzz/credentials/Cargo.lock +++ b/fuzz/credentials/Cargo.lock @@ -54,7 +54,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -65,7 +65,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -162,7 +162,7 @@ dependencies = [ "maybe-owned", "rustix", "rustix-linux-procfs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "winx", ] @@ -416,7 +416,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1174,16 +1174,16 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1304,7 +1304,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1373,7 +1373,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1506,6 +1506,7 @@ name = "sendbox-egress" version = "0.2.6" dependencies = [ "async-trait", + "base64", "bytes", "cap-std", "clap", @@ -1712,7 +1713,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -2147,7 +2148,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/fuzz/mcp/Cargo.lock b/fuzz/mcp/Cargo.lock index 346cf96..a8052d5 100644 --- a/fuzz/mcp/Cargo.lock +++ b/fuzz/mcp/Cargo.lock @@ -1214,6 +1214,7 @@ name = "sendbox-egress" version = "0.2.6" dependencies = [ "async-trait", + "base64", "bytes", "cap-std", "clap", diff --git a/fuzz/registry/Cargo.lock b/fuzz/registry/Cargo.lock index e638df9..9d61694 100644 --- a/fuzz/registry/Cargo.lock +++ b/fuzz/registry/Cargo.lock @@ -591,7 +591,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1488,16 +1488,16 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", "once_cell", "socket2", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1675,7 +1675,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1732,7 +1732,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2398,7 +2398,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2833,7 +2833,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]]