From c6f4d5d28afb56f6334efdee79bdd3a6c5a752e7 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Tue, 1 Dec 2026 12:15:32 -0800 Subject: [PATCH 1/6] fix(storage,crypto,oci): zeroize keys, add AAD, guard OCI SSRF, clean local tmp files, unify GCP auth --- Cargo.lock | 5 + Tiltfile | 2 + crates/engram-cloud-gcp/Cargo.toml | 6 + crates/engram-cloud-gcp/src/auth.rs | 310 ++++++++++++++++++ crates/engram-cloud-gcp/src/gke.rs | 173 +++++----- crates/engram-cloud-gcp/src/lib.rs | 5 +- .../tests/enable_reuse_live_pg.rs | 4 +- crates/engram-crypto/Cargo.toml | 1 + crates/engram-crypto/src/lib.rs | 124 ++++--- crates/engram-crypto/src/providers.rs | 47 ++- crates/engram-kms-aws/src/lib.rs | 61 +++- crates/engram-oci/src/docker_image.rs | 22 +- crates/engram-oci/src/lib.rs | 201 ++++++++++-- crates/engram-oci/tests/docker_blob_resume.rs | 16 +- .../engram-oci/tests/per_chunk_roundtrip.rs | 2 +- .../tests/materialize.rs | 2 +- .../tests/materialize_boot.rs | 2 +- crates/engram-secrets-aws/src/ca.rs | 4 +- crates/engram-secrets-aws/src/lib.rs | 53 ++- crates/engram-secrets-gcp/Cargo.toml | 3 +- crates/engram-secrets-gcp/src/lib.rs | 191 ++++------- crates/engram-storage-local/src/lib.rs | 102 +++++- 22 files changed, 967 insertions(+), 369 deletions(-) create mode 100644 crates/engram-cloud-gcp/src/auth.rs diff --git a/Cargo.lock b/Cargo.lock index d1fd274ce..a5c74db3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2392,7 +2392,10 @@ dependencies = [ "reqwest", "serde", "serde_json", + "tokio", "tracing", + "uuid", + "wiremock", "workspace-hack", ] @@ -2540,6 +2543,7 @@ dependencies = [ "tokio", "tracing", "workspace-hack", + "zeroize", ] [[package]] @@ -3285,6 +3289,7 @@ version = "0.1.0" dependencies = [ "async-trait", "base64 0.23.1", + "engram-cloud-gcp", "engram-core", "engram-egress-proxy", "engram-tls", diff --git a/Tiltfile b/Tiltfile index 6c5b2485d..df77f8e7f 100644 --- a/Tiltfile +++ b/Tiltfile @@ -408,6 +408,7 @@ if not bin_dir: otel_endpoint = env_or('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://localhost:4317') coord_env = { + 'ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK': '1', 'DATABASE_URL': 'postgres://engram:engram@localhost:5435/engram', 'ENGRAM_BIND_ADDR': '127.0.0.1:8090', # ADR 0051: the app-gRPC surface is how the orchestrator (and the @@ -562,6 +563,7 @@ if two_hosts and fc_colima_profile: def host_agent_resource(name, grpc_port, metrics_port, work_dir, egress_proxy_port, egress_dns_port, guest_gateway_port, thin_pool): env = { + 'ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK': '1', # `kernel_key` is only non-None for vz/firecracker, both of # which force `dev_split`, so this always lands on the # host-agent (there's no coord-side mode=all + real-virt path diff --git a/crates/engram-cloud-gcp/Cargo.toml b/crates/engram-cloud-gcp/Cargo.toml index 13c9b3e06..1b3d5cc51 100644 --- a/crates/engram-cloud-gcp/Cargo.toml +++ b/crates/engram-cloud-gcp/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [dependencies] engram-tls.workspace = true +tokio = { workspace = true, features = ["sync", "time"] } +uuid.workspace = true engram-core.workspace = true async-trait.workspace = true reqwest.workspace = true @@ -18,3 +20,7 @@ serde.workspace = true serde_json.workspace = true tracing.workspace = true workspace-hack = { version = "0.1", path = "../../workspace-hack" } + +[dev-dependencies] +tokio = { workspace = true, features = ["macros", "rt"] } +wiremock = "0.6" diff --git a/crates/engram-cloud-gcp/src/auth.rs b/crates/engram-cloud-gcp/src/auth.rs new file mode 100644 index 000000000..1d96a5b46 --- /dev/null +++ b/crates/engram-cloud-gcp/src/auth.rs @@ -0,0 +1,310 @@ +//! Cached metadata credentials and bounded HTTP retries for GCP APIs. + +use async_trait::async_trait; +use engram_core::SecretError; +use serde::Deserialize; +use std::time::{Duration, Instant}; + +/// Default metadata-server token endpoint. Overridable for tests. +const DEFAULT_METADATA_TOKEN_URL: &str = + "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"; + +/// Supplies bearer tokens for GCP APIs. Tests can inject a static value. +#[async_trait] +pub trait TokenSource: Send + Sync { + async fn token(&self) -> Result; + + /// Discard a rejected token without evicting a newer concurrent refresh. + async fn invalidate(&self, _rejected: &str) {} +} + +/// Returns a fixed token. Test fixture. +#[derive(Clone, Debug)] +pub struct StaticTokenSource(pub String); + +#[async_trait] +impl TokenSource for StaticTokenSource { + async fn token(&self) -> Result { + Ok(self.0.clone()) + } +} + +/// Fetches tokens from the GCE/GKE instance metadata server. Caches +/// the token in memory until 60 s before expiry. The metadata server +/// itself caches across the same lifetime, but skipping the round-trip +/// keeps session-create latency tight when several secrets resolve in +/// a row. +pub struct MetadataTokenSource { + http: reqwest::Client, + endpoint: String, + cache: tokio::sync::Mutex>, +} + +struct CachedToken { + bearer: String, + not_after: Instant, +} + +#[derive(Deserialize)] +struct MetadataTokenResponse { + access_token: String, + /// Seconds until expiry, per RFC 6749. Metadata server returns ~3600. + expires_in: u64, +} + +impl MetadataTokenSource { + pub fn new() -> Result { + let http = engram_tls::client_builder() + .timeout(Duration::from_secs(5)) + .build() + .map_err(|e| SecretError::Backend(Box::new(e)))?; + Ok(Self { + http, + endpoint: DEFAULT_METADATA_TOKEN_URL.into(), + cache: tokio::sync::Mutex::new(None), + }) + } + + /// Override the metadata endpoint. For tests pointing at a mock + /// server. + pub fn with_endpoint(mut self, endpoint: impl Into) -> Self { + self.endpoint = endpoint.into(); + self + } +} + +#[async_trait] +impl TokenSource for MetadataTokenSource { + async fn token(&self) -> Result { + // Hold the lock through refresh so concurrent callers share one fetch. + let mut cache = self.cache.lock().await; + if let Some(tok) = cache.as_ref() { + if tok.not_after > Instant::now() { + return Ok(tok.bearer.clone()); + } + } + + let resp = send_with_retry( + || { + self.http + .get(&self.endpoint) + .header("Metadata-Flavor", "Google") + }, + None, + ) + .await?; + let status = resp.status(); + if status.is_client_error() { + return Err(SecretError::Unauthorized(format!( + "metadata-server returned {status} fetching access token" + ))); + } + if !status.is_success() { + return Err(SecretError::Backend( + format!("metadata-server returned {status} fetching access token").into(), + )); + } + let body: MetadataTokenResponse = resp + .json() + .await + .map_err(|e| SecretError::Protocol(format!("metadata-server token JSON: {e}")))?; + + // Refresh 60 s before actual expiry so we don't trip into an + // expired token mid-request. + let lifetime = Duration::from_secs(body.expires_in.saturating_sub(60)); + let cached = CachedToken { + bearer: body.access_token.clone(), + not_after: Instant::now() + .checked_add(lifetime) + .ok_or_else(|| SecretError::Protocol("metadata token lifetime overflow".into()))?, + }; + *cache = Some(cached); + Ok(body.access_token) + } + + async fn invalidate(&self, rejected: &str) { + let mut cache = self.cache.lock().await; + if cache.as_ref().is_some_and(|token| token.bearer == rejected) { + *cache = None; + } + } +} + +/// Send a replayable request with at most three attempts and one token refresh. +/// The deadline includes token acquisition, requests, and backoff. +pub async fn send_with_retry( + request: impl Fn() -> reqwest::RequestBuilder, + tokens: Option<&dyn TokenSource>, +) -> Result { + tokio::time::timeout(Duration::from_secs(10), async { + let mut refreshed = false; + for attempt in 0..3 { + let bearer = match tokens { + Some(source) => Some(source.token().await?), + None => None, + }; + let mut req = request(); + if let Some(token) = &bearer { + req = req.bearer_auth(token); + } + let result = req.send().await; + let retry = match &result { + Ok(resp) if resp.status() == reqwest::StatusCode::UNAUTHORIZED => { + if let (Some(source), Some(token)) = (tokens, &bearer) { + source.invalidate(token).await; + let retry = !refreshed; + refreshed = true; + retry + } else { + false + } + } + Ok(resp) => { + resp.status().is_server_error() + || resp.status() == reqwest::StatusCode::TOO_MANY_REQUESTS + } + Err(err) => { + err.is_timeout() || err.is_connect() || err.is_body() || err.is_request() + } + }; + if !retry || attempt == 2 { + return result.map_err(|e| SecretError::Backend(Box::new(e))); + } + drop(result); + tokio::time::sleep(Duration::from_millis(100 << attempt)).await; + } + unreachable!("bounded retry loop returns on the last attempt") + }) + .await + .map_err(|_| SecretError::Backend("GCP request exceeded the 10s deadline".into()))? +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }; + use wiremock::matchers::{header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + #[tokio::test] + async fn concurrent_refresh_is_single_flight_and_invalidation_is_conditional() { + let server = MockServer::start().await; + let calls = Arc::new(AtomicUsize::new(0)); + let count = calls.clone(); + Mock::given(path("/token")) + .and(header("Metadata-Flavor", "Google")) + .respond_with(move |_: &wiremock::Request| { + let n = count.fetch_add(1, Ordering::SeqCst); + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({ + "access_token": format!("token-{n}"), "expires_in": 3600 + })) + .set_delay(Duration::from_millis(20)) + }) + .expect(2) + .mount(&server) + .await; + let source = Arc::new( + MetadataTokenSource::new() + .unwrap() + .with_endpoint(format!("{}/token", server.uri())), + ); + let mut tasks = Vec::new(); + for _ in 0..12 { + let source = source.clone(); + tasks.push(tokio::spawn(async move { source.token().await.unwrap() })); + } + for task in tasks { + assert_eq!(task.await.unwrap(), "token-0"); + } + assert_eq!(calls.load(Ordering::SeqCst), 1); + source.invalidate("token-0").await; + assert_eq!(source.token().await.unwrap(), "token-1"); + source.invalidate("token-0").await; + assert_eq!(source.token().await.unwrap(), "token-1"); + } + + #[tokio::test] + async fn unauthorized_refreshes_once_then_returns_failure() { + let server = MockServer::start().await; + Mock::given(path("/token")) + .respond_with( + ResponseTemplate::new(200).set_body_json( + serde_json::json!({"access_token": "rejected", "expires_in": 3600}), + ), + ) + .expect(2) + .mount(&server) + .await; + Mock::given(path("/api")) + .respond_with(ResponseTemplate::new(401)) + .expect(2) + .mount(&server) + .await; + let source = MetadataTokenSource::new() + .unwrap() + .with_endpoint(format!("{}/token", server.uri())); + let http = engram_tls::client(); + let resp = send_with_retry(|| http.get(format!("{}/api", server.uri())), Some(&source)) + .await + .unwrap(); + assert_eq!(resp.status(), 401); + } + + #[tokio::test] + async fn retries_transient_responses_but_not_permanent_failures() { + for code in [429, 500, 503, 403] { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(code)) + .expect(if code == 403 { 1 } else { 3 }) + .mount(&server) + .await; + let http = engram_tls::client(); + assert_eq!( + send_with_retry(|| http.get(server.uri()), None) + .await + .unwrap() + .status(), + code + ); + } + } + + #[tokio::test] + async fn invalid_request_is_not_retried() { + let attempts = AtomicUsize::new(0); + let http = engram_tls::client(); + let result = send_with_retry( + || { + attempts.fetch_add(1, Ordering::SeqCst); + http.get("not a URL") + }, + None, + ) + .await; + assert!(result.is_err()); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn short_lived_tokens_are_not_cached_past_expiry() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"access_token": "short", "expires_in": 0})), + ) + .expect(2) + .mount(&server) + .await; + let source = MetadataTokenSource::new() + .unwrap() + .with_endpoint(server.uri()); + source.token().await.unwrap(); + source.token().await.unwrap(); + } +} diff --git a/crates/engram-cloud-gcp/src/gke.rs b/crates/engram-cloud-gcp/src/gke.rs index e963958a4..43ffa550f 100644 --- a/crates/engram-cloud-gcp/src/gke.rs +++ b/crates/engram-cloud-gcp/src/gke.rs @@ -1,19 +1,9 @@ -//! ADR 0044 K4: GKE node-pool actuator — the `NodePoolScaler` impl for GCP. -//! -//! **UNVALIDATED ON REAL INFRA.** No nested-virt GKE pool exists to exercise -//! the full loop yet (it arrives with the K5 cutover), and the policy driving -//! it is uncalibrated (no production load). The `setSize` call + the -//! Workload-Identity token fetch are structurally correct and mirror this -//! crate's metadata-server pattern, but treat this as observe-with-caution -//! until a real pool exercises it. -//! -//! Auth: GKE Workload Identity → the GCE metadata server issues an OAuth token -//! for the pod's bound service account. project / cluster / location are read -//! from the same metadata server, so the only per-fleet config is the -//! node-pool name. +//! GKE node-pool scaling through the Container and Compute APIs. +use std::sync::Arc; use std::time::Duration; +use crate::auth::{send_with_retry, MetadataTokenSource, TokenSource}; use async_trait::async_trait; use engram_core::traits::cloud::NodePoolScaler; use engram_core::BackendError; @@ -30,11 +20,7 @@ pub struct GkeNodePoolScaler { project: String, location: String, cluster: String, -} - -#[derive(Deserialize)] -struct TokenResp { - access_token: String, + tokens: Arc, } /// The slice of a GKE `nodePools.get` response we read: the managed @@ -95,21 +81,18 @@ impl GkeNodePoolScaler { project, location, cluster, + tokens: Arc::new( + MetadataTokenSource::new().map_err(|e| BackendError::Sdk(Box::new(e)))?, + ), }) } - async fn node_pool(&self, node_pool: &str, token: &str) -> Result { + async fn node_pool(&self, node_pool: &str) -> Result { let np_url = format!( "{CONTAINER_API}/projects/{}/locations/{}/clusters/{}/nodePools/{}", self.project, self.location, self.cluster, node_pool ); - let resp = self - .http - .get(&np_url) - .bearer_auth(token) - .send() - .await - .map_err(|e| BackendError::Sdk(Box::new(e)))?; + let resp = self.send(|| self.http.get(&np_url)).await?; if !resp.status().is_success() { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); @@ -134,37 +117,26 @@ impl GkeNodePoolScaler { Ok(np) } - async fn token(&self) -> Result { - let resp = self - .http - .get(format!( - "{METADATA_BASE}/instance/service-accounts/default/token" - )) - .header("Metadata-Flavor", "Google") - .send() - .await - .map_err(|e| BackendError::Sdk(Box::new(e)))?; - if !resp.status().is_success() { - return Err(BackendError::Protocol(format!( - "gke token endpoint returned {}", - resp.status() - ))); - } - Ok(resp - .json::() + async fn send( + &self, + request: impl Fn() -> reqwest::RequestBuilder, + ) -> Result { + send_with_retry(request, Some(self.tokens.as_ref())) .await - .map_err(|e| BackendError::Sdk(Box::new(e)))? - .access_token) + .map_err(|e| BackendError::Sdk(Box::new(e))) } } async fn fetch_meta(http: &reqwest::Client, path: &str) -> Result { - let resp = http - .get(format!("{METADATA_BASE}/{path}")) - .header("Metadata-Flavor", "Google") - .send() - .await - .map_err(|e| BackendError::Sdk(Box::new(e)))?; + let resp = send_with_retry( + || { + http.get(format!("{METADATA_BASE}/{path}")) + .header("Metadata-Flavor", "Google") + }, + None, + ) + .await + .map_err(|e| BackendError::Sdk(Box::new(e)))?; if !resp.status().is_success() { return Err(BackendError::Protocol(format!( "gke metadata {path} returned {}", @@ -180,23 +152,20 @@ async fn fetch_meta(http: &reqwest::Client, path: &str) -> Result Result { - let token = self.token().await?; - let pool = self.node_pool(node_pool, &token).await?; + let pool = self.node_pool(node_pool).await?; let mut total = 0u32; for url in pool.instance_group_urls { let (zone, igm) = parse_igm_url(&url).ok_or_else(|| { BackendError::Protocol(format!("invalid instance group URL: {url}")) })?; let resp = self - .http - .get(format!( - "{COMPUTE_API}/projects/{}/zones/{zone}/instanceGroupManagers/{igm}", - self.project - )) - .bearer_auth(&token) - .send() - .await - .map_err(|e| BackendError::Sdk(Box::new(e)))?; + .send(|| { + self.http.get(format!( + "{COMPUTE_API}/projects/{}/zones/{zone}/instanceGroupManagers/{igm}", + self.project + )) + }) + .await?; if !resp.status().is_success() { return Err(BackendError::Protocol(format!( "compute instanceGroupManagers.get returned {}", @@ -215,19 +184,17 @@ impl NodePoolScaler for GkeNodePoolScaler { } async fn set_size(&self, node_pool: &str, desired: u32) -> Result<(), BackendError> { - let token = self.token().await?; let url = format!( "{CONTAINER_API}/projects/{}/locations/{}/clusters/{}/nodePools/{}:setSize", self.project, self.location, self.cluster, node_pool ); let resp = self - .http - .post(&url) - .bearer_auth(token) - .json(&serde_json::json!({ "nodeCount": desired })) - .send() - .await - .map_err(|e| BackendError::Sdk(Box::new(e)))?; + .send(|| { + self.http + .post(&url) + .json(&serde_json::json!({ "nodeCount": desired })) + }) + .await?; if !resp.status().is_success() { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); @@ -252,8 +219,7 @@ impl NodePoolScaler for GkeNodePoolScaler { /// no-op success (idempotent). No LRO polling — same posture as /// `set_size`; the next reconcile re-observes the fleet. async fn remove_node(&self, node_pool: &str, node_name: &str) -> Result<(), BackendError> { - let token = self.token().await?; - let np = self.node_pool(node_pool, &token).await?; + let np = self.node_pool(node_pool).await?; // 2. Find the MIG that owns this node (by hash-prefix match). let owner = np @@ -277,17 +243,19 @@ impl NodePoolScaler for GkeNodePoolScaler { "{COMPUTE_API}/projects/{}/zones/{zone}/instanceGroupManagers/{igm}/deleteInstances", self.project ); + // Compute deduplicates retries with the same nonzero request ID. + let request_id = uuid::Uuid::new_v4().to_string(); let resp = self - .http - .post(&url) - .bearer_auth(&token) - .json(&serde_json::json!({ - "instances": [format!("zones/{zone}/instances/{node_name}")], - "skipInstancesOnValidationError": true, - })) - .send() - .await - .map_err(|e| BackendError::Sdk(Box::new(e)))?; + .send(|| { + self.http + .post(&url) + .query(&[("requestId", &request_id)]) + .json(&serde_json::json!({ + "instances": [format!("zones/{zone}/instances/{node_name}")], + "skipInstancesOnValidationError": true, + })) + }) + .await?; if !resp.status().is_success() { let status = resp.status(); let body = resp.text().await.unwrap_or_default(); @@ -310,6 +278,45 @@ impl NodePoolScaler for GkeNodePoolScaler { mod tests { use super::*; + #[tokio::test] + async fn scaler_retries_with_auth_and_preserves_request_body() { + use wiremock::matchers::{body_json, header, method}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let server = MockServer::start().await; + let calls = std::sync::atomic::AtomicUsize::new(0); + Mock::given(method("POST")) + .and(header("authorization", "Bearer token")) + .and(body_json(serde_json::json!({"nodeCount": 2}))) + .respond_with(move |_: &wiremock::Request| { + ResponseTemplate::new( + if calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 { + 503 + } else { + 200 + }, + ) + }) + .expect(2) + .mount(&server) + .await; + let scaler = GkeNodePoolScaler { + http: engram_tls::client(), + project: "project".into(), + location: "zone".into(), + cluster: "cluster".into(), + tokens: Arc::new(crate::auth::StaticTokenSource("token".into())), + }; + assert!(scaler + .send(|| scaler + .http + .post(server.uri()) + .json(&serde_json::json!({"nodeCount": 2}))) + .await + .unwrap() + .status() + .is_success()); + } + #[test] fn parse_igm_url_extracts_zone_and_name() { let url = "https://www.googleapis.com/compute/v1/projects/p/zones/us-west2-a/\ diff --git a/crates/engram-cloud-gcp/src/lib.rs b/crates/engram-cloud-gcp/src/lib.rs index d02347ed0..0bff636a0 100644 --- a/crates/engram-cloud-gcp/src/lib.rs +++ b/crates/engram-cloud-gcp/src/lib.rs @@ -1,5 +1,4 @@ -//! GCP cloud integrations. Today this is only the GKE node-pool -//! scaler (`gke`); the per-host `CloudBackend` metadata reader that -//! used to live here was unused and was removed. +//! GCP cloud API clients and metadata authentication. +pub mod auth; pub mod gke; diff --git a/crates/engram-coordinator/tests/enable_reuse_live_pg.rs b/crates/engram-coordinator/tests/enable_reuse_live_pg.rs index 62fff1eda..96022f990 100644 --- a/crates/engram-coordinator/tests/enable_reuse_live_pg.rs +++ b/crates/engram-coordinator/tests/enable_reuse_live_pg.rs @@ -285,7 +285,7 @@ impl HostClient for FakeCaptureHost { // ADR 0093: no packer seam — the streaming pack runs for real // (pure Rust, no mke2fs needed in the test env). let materializer = Materializer::new( - OciClient::new(Arc::new(AnonymousResolver)), + OciClient::new(Arc::new(AnonymousResolver)).with_insecure_loopback(true), InitInjection { vsock_port: 1024, transport: Transport::Vsock, @@ -515,7 +515,7 @@ async fn second_tag_with_identical_content_reuses_base_snapshot() { kek: Arc::new(engram_crypto::EnvVarKeyProvider::from_bytes( [0xab; 32], "test:v1", )), - oci: Arc::new(OciClient::new(Arc::new(AnonymousResolver))), + oci: Arc::new(OciClient::new(Arc::new(AnonymousResolver)).with_insecure_loopback(true)), auth_resolver: Arc::new(AnonymousResolver), blob: blob.clone(), chunk_store: chunk_store.clone(), diff --git a/crates/engram-crypto/Cargo.toml b/crates/engram-crypto/Cargo.toml index 3a72b78a7..7880bc2d4 100644 --- a/crates/engram-crypto/Cargo.toml +++ b/crates/engram-crypto/Cargo.toml @@ -15,6 +15,7 @@ serde = { workspace = true, optional = true } tracing.workspace = true aes-gcm = "0.11" rand = "0.10" +zeroize = "1.9" base64.workspace = true workspace-hack = { version = "0.1", path = "../../workspace-hack" } diff --git a/crates/engram-crypto/src/lib.rs b/crates/engram-crypto/src/lib.rs index d86c6c50e..a02edd2f1 100644 --- a/crates/engram-crypto/src/lib.rs +++ b/crates/engram-crypto/src/lib.rs @@ -28,11 +28,12 @@ //! Postgres schema stores them as four columns rather than one packed //! BYTEA so they're individually queryable / auditable. -use aes_gcm::aead::{Aead, KeyInit}; +use aes_gcm::aead::{Aead, KeyInit, Payload}; use aes_gcm::{Aes256Gcm, Key}; use async_trait::async_trait; use rand::rngs::SysRng; use rand::TryRng; +use zeroize::Zeroizing; pub mod providers; @@ -42,8 +43,7 @@ pub use providers::{EnvVarKeyProvider, GcpKmsProvider}; /// /// Implementations are responsible for the master key's lifecycle: /// `EnvVarKeyProvider` reads from process env (key never persists past -/// the process); `GcpKmsProvider` calls KMS so the master key never -/// leaves the KMS at all. +/// the process). KMS providers keep the master key in the KMS. #[async_trait] pub trait MasterKeyProvider: Send + Sync { /// Wrap a 32-byte DEK. The returned bytes are opaque — the @@ -51,10 +51,8 @@ pub trait MasterKeyProvider: Send + Sync { async fn wrap(&self, dek: &[u8]) -> Result, CryptoError>; /// Unwrap a previously-wrapped DEK. Errors if the wrapped value - /// was produced by a different KEK or a different provider, or if - /// `key_id()` no longer matches what produced it (the caller can - /// detect rotation by comparing the row's `key_id` against this - /// method). + /// was produced by an incompatible KEK or provider. The caller checks + /// the stored `key_id` to detect rotation. async fn unwrap(&self, wrapped: &[u8]) -> Result, CryptoError>; /// Stable identifier for the active KEK. Stored alongside each @@ -91,32 +89,42 @@ impl<'a> CredCipher<'a> { /// AES-256-GCM, wrap the DEK with the KEK, and tag the result /// with the active KEK's `key_id`. pub async fn seal(&self, plaintext: &[u8]) -> Result { - // SysRng is `Send` (unit struct around the OS RNG). We avoid - // `rand::rng()` here because it returns a `!Send` handle, - // which would poison the future with `!Send` and break axum - // handlers that hold a `CredCipher` across an await point. - // - // rand 0.10 makes the OS RNG explicitly fallible: SysRng - // implements only `TryRng`, where 0.9's `OsRng` implemented - // the infallible `RngCore` and panicked internally on a failed - // syscall. Propagate instead — a DEK or nonce must never come - // from a degraded source, and both callers already handle - // `CryptoError`. + self.seal_payload(plaintext, &[]).await + } + + /// Seal with authenticated key identity and caller context. Use only after + /// all readers support `open_with_aad`; legacy `open` cannot read this format. + pub async fn seal_with_aad( + &self, + plaintext: &[u8], + aad: &[u8], + ) -> Result { + self.seal_payload(plaintext, &envelope_aad(self.kek.key_id(), aad)) + .await + } + + async fn seal_payload(&self, plaintext: &[u8], aad: &[u8]) -> Result { let mut rng = SysRng; - let mut dek = [0u8; 32]; - rng.try_fill_bytes(&mut dek) + let mut dek = Zeroizing::new([0u8; 32]); + rng.try_fill_bytes(&mut *dek) .map_err(|e| CryptoError::Provider(format!("OS RNG failed for DEK: {e}")))?; let mut nonce = [0u8; 12]; rng.try_fill_bytes(&mut nonce) .map_err(|e| CryptoError::Provider(format!("OS RNG failed for nonce: {e}")))?; - let cipher = Aes256Gcm::new((&dek).into()); + let cipher = Aes256Gcm::new((&*dek).into()); let ciphertext = cipher - .encrypt((&nonce).into(), plaintext) + .encrypt( + (&nonce).into(), + Payload { + msg: plaintext, + aad, + }, + ) .map_err(|_| CryptoError::Aead("encrypt"))?; - let wrapped_dek = self.kek.wrap(&dek).await?; + let wrapped_dek = self.kek.wrap(&*dek).await?; Ok(SealedCred { wrapped_dek, @@ -130,19 +138,45 @@ impl<'a> CredCipher<'a> { /// can't be unwrapped (wrong KEK, corrupted bytes) or the GCM tag /// doesn't authenticate (tampered ciphertext / nonce). pub async fn open(&self, sealed: &SealedCred) -> Result, CryptoError> { - let dek = self.kek.unwrap(&sealed.wrapped_dek).await?; - // A DEK that is not exactly 32 bytes means the wrong KEK or a wrap - // format mismatch. `TryFrom` is the length check — it is the same - // condition the explicit comparison used to test. + self.open_payload(sealed, &[]).await + } + + /// Open an AAD-bound envelope. There is no fallback to legacy empty AAD. + pub async fn open_with_aad( + &self, + sealed: &SealedCred, + aad: &[u8], + ) -> Result, CryptoError> { + self.open_payload(sealed, &envelope_aad(&sealed.key_id, aad)) + .await + } + + async fn open_payload(&self, sealed: &SealedCred, aad: &[u8]) -> Result, CryptoError> { + let dek = Zeroizing::new(self.kek.unwrap(&sealed.wrapped_dek).await?); let key = <&Key>::try_from(&dek[..]).map_err(|_| CryptoError::DekLength(dek.len()))?; let cipher = Aes256Gcm::new(key); cipher - .decrypt((&sealed.nonce).into(), sealed.ciphertext.as_slice()) + .decrypt( + (&sealed.nonce).into(), + Payload { + msg: &sealed.ciphertext, + aad, + }, + ) .map_err(|_| CryptoError::Aead("decrypt")) } } +// Length-prefix the key identity so adjacent fields cannot alias. +fn envelope_aad(key_id: &str, context: &[u8]) -> Vec { + let mut aad = b"engram-credential-aad-v1".to_vec(); + aad.extend_from_slice(&(key_id.len() as u64).to_be_bytes()); + aad.extend_from_slice(key_id.as_bytes()); + aad.extend_from_slice(context); + aad +} + #[derive(Debug)] pub enum CryptoError { /// AES-GCM seal/open failed (auth tag mismatch, etc.). @@ -169,6 +203,24 @@ impl std::error::Error for CryptoError {} mod tests { use super::*; + #[tokio::test] + async fn aad_binds_context_and_key_identity_without_legacy_fallback() { + let kek = EnvVarKeyProvider::from_bytes([7; 32], "key:v1"); + let cipher = CredCipher::new(&kek); + let mut sealed = cipher.seal_with_aad(b"secret", b"row:1").await.unwrap(); + assert_eq!( + cipher.open_with_aad(&sealed, b"row:1").await.unwrap(), + b"secret" + ); + assert!(cipher.open_with_aad(&sealed, b"row:2").await.is_err()); + assert!(cipher.open(&sealed).await.is_err()); + sealed.key_id = "key:v2".into(); + assert!(cipher.open_with_aad(&sealed, b"row:1").await.is_err()); + let legacy = cipher.seal(b"legacy").await.unwrap(); + assert_eq!(cipher.open(&legacy).await.unwrap(), b"legacy"); + assert!(cipher.open_with_aad(&legacy, b"").await.is_err()); + } + /// Decode a compile-time hex literal into a byte vector. fn unhex(s: &str) -> Vec { assert!( @@ -181,20 +233,8 @@ mod tests { .collect() } - /// A `SealedCred` produced by aes-gcm **0.10.3** — the version this - /// repo shipped before the 0.11 bump — must still open. - /// - /// Every other test in this module seals and opens with the same code, - /// so all of them would keep passing if an upgrade silently changed the - /// envelope's wire format. Rows already sealed in Postgres would then be - /// permanently unreadable, and nothing would say so. This test is the - /// only thing standing between that failure and a green build. - /// - /// The bytes below were generated by running the 0.10.3 encrypt path - /// against fixed inputs (KEK `00..1f`, DEK `42*32`, wrap nonce `11*12`, - /// DEK nonce `22*12`). Treat a failure here the way you would treat a - /// content-addressing digest failure: it is a data-migration problem, - /// never a new expected value to paste in. + /// Fixed ciphertext from aes-gcm 0.10.3 pins the persisted envelope format. + /// KEK is 00..1f, DEK is 42*32, and wrap/data nonces are 11*12 and 22*12. #[tokio::test] async fn opens_an_envelope_sealed_by_aes_gcm_0_10_3() { let kek = EnvVarKeyProvider::from_bytes( diff --git a/crates/engram-crypto/src/providers.rs b/crates/engram-crypto/src/providers.rs index e4a7487bc..c9d3126cb 100644 --- a/crates/engram-crypto/src/providers.rs +++ b/crates/engram-crypto/src/providers.rs @@ -4,20 +4,17 @@ //! env var (base64-encoded). Used for dev (`just bootstrap` writes //! the key into `.env`) and for prod deployments that source secrets //! from k8s Secrets / Doppler / Vault into env. -//! - [`GcpKmsProvider`]: stub for prod KMS-backed wrap/unwrap. Wired -//! when needed; placeholder today, mirroring `engram-secrets-gcp`. +//! - [`GcpKmsProvider`]: unsupported KMS configuration; operations return errors. use async_trait::async_trait; use base64::Engine; +use zeroize::Zeroizing; use crate::{CryptoError, MasterKeyProvider}; /// 32-byte AES-256 key sourced from a process env var (base64). /// -/// The wrap format is the simplest envelope: AES-256-GCM encrypt the -/// DEK with a deterministic nonce derived from the DEK plaintext is -/// **not** safe — instead we use a random 12-byte nonce per wrap and -/// prepend it to the wrapped output. So `wrapped_dek` is laid out as: +/// Each wrap uses a random 12-byte nonce, stored before the ciphertext: /// /// ```text /// [0..12] nonce_for_dek @@ -28,7 +25,7 @@ use crate::{CryptoError, MasterKeyProvider}; /// returns the plaintext DEK. Tag validation guarantees that wrapped /// values from a different KEK fail to unwrap. pub struct EnvVarKeyProvider { - key_bytes: [u8; 32], + key_bytes: Zeroizing<[u8; 32]>, key_id: String, } @@ -37,18 +34,22 @@ impl EnvVarKeyProvider { /// holds). Padding-tolerant. Errors if the decoded length is not /// 32 bytes. pub fn from_base64(b64: &str, key_id: impl Into) -> Result { - let bytes = base64::engine::general_purpose::STANDARD - .decode(b64.trim()) - .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(b64.trim())) + // Decode into owned zeroizing storage, including partial decode failures. + let mut bytes = Zeroizing::new(vec![0u8; b64.trim().len()]); + let len = base64::engine::general_purpose::STANDARD + .decode_slice(b64.trim(), &mut bytes[..]) + .or_else(|_| { + base64::engine::general_purpose::STANDARD_NO_PAD + .decode_slice(b64.trim(), &mut bytes[..]) + }) .map_err(|e| CryptoError::Provider(format!("base64 decode: {e}")))?; - if bytes.len() != 32 { + if len != 32 { return Err(CryptoError::Provider(format!( - "KEK must be 32 bytes after base64 decode, got {}", - bytes.len() + "KEK must be 32 bytes after base64 decode, got {len}" ))); } - let mut key_bytes = [0u8; 32]; - key_bytes.copy_from_slice(&bytes); + let mut key_bytes = Zeroizing::new([0u8; 32]); + key_bytes.copy_from_slice(&bytes[..len]); Ok(Self { key_bytes, key_id: key_id.into(), @@ -59,12 +60,12 @@ impl EnvVarKeyProvider { /// provider. Fails closed if the var is missing, empty, or not /// 32 bytes. pub fn from_env(var_name: &str) -> Result { - let raw = std::env::var(var_name).map_err(|_| { + let raw = Zeroizing::new(std::env::var(var_name).map_err(|_| { CryptoError::Provider(format!( "required env var `{var_name}` is unset; \ generate a 32-byte key (base64) and export it before starting the coordinator" )) - })?; + })?); let key_id = format!("env:{var_name}:v1"); Self::from_base64(&raw, key_id) } @@ -72,14 +73,14 @@ impl EnvVarKeyProvider { /// For tests only. Skip the env-var dance. pub fn from_bytes(key_bytes: [u8; 32], key_id: impl Into) -> Self { Self { - key_bytes, + key_bytes: Zeroizing::new(key_bytes), key_id: key_id.into(), } } fn cipher(&self) -> aes_gcm::Aes256Gcm { use aes_gcm::KeyInit; - aes_gcm::Aes256Gcm::new((&self.key_bytes).into()) + aes_gcm::Aes256Gcm::new((&*self.key_bytes).into()) } } @@ -90,9 +91,6 @@ impl MasterKeyProvider for EnvVarKeyProvider { use rand::rngs::SysRng; use rand::TryRng; - // rand 0.10: the OS RNG is fallible (`TryRng`), where 0.9's - // `OsRng` panicked internally instead. Propagate — a wrap nonce - // must never come from a degraded source. let mut nonce = [0u8; 12]; SysRng .try_fill_bytes(&mut nonce) @@ -134,10 +132,7 @@ impl MasterKeyProvider for EnvVarKeyProvider { } } -/// Stub for GCP KMS-backed wrap/unwrap. The real implementation calls -/// `projects.locations.keyRings.cryptoKeys.encrypt` and `.decrypt` -/// against a customer-managed key. Wired when needed; today returns -/// errors, mirroring the `engram-secrets-gcp` stub pattern. +/// Unsupported GCP KMS configuration. Wrap and unwrap return errors. pub struct GcpKmsProvider { key_id: String, } diff --git a/crates/engram-kms-aws/src/lib.rs b/crates/engram-kms-aws/src/lib.rs index e06a93294..2524eb23e 100644 --- a/crates/engram-kms-aws/src/lib.rs +++ b/crates/engram-kms-aws/src/lib.rs @@ -22,10 +22,8 @@ //! dependency of musl guest binaries and every sealing consumer, and //! must not pull an AWS SDK. //! -//! Auth: the SDK default chain via `engram-aws` — IRSA on EKS. No -//! SDK-internal retries (engram-aws posture); a failed wrap/unwrap -//! surfaces to the caller, whose operation (registry-cred seal, cred -//! open) is the right retry unit. +//! Auth uses the SDK default chain. Transient failures receive at most two +//! retries with exponential backoff, within the operation's 10 s deadline. use async_trait::async_trait; use aws_sdk_kms::primitives::Blob; @@ -33,12 +31,7 @@ use aws_sdk_kms::Client; use engram_crypto::{CryptoError, MasterKeyProvider}; -/// Per-call deadline. The shared `engram-aws` transport bounds only -/// the CONNECT (5 s) and disables SDK retries; a KMS response that -/// stalls after the handshake would otherwise hang the caller — -/// wrap/unwrap sit on the registry-cred seal/open and session-secret -/// paths, which must fail fast, not wedge. Mirrors the 10 s bound -/// engram-secrets-aws applies to GetSecretValue. +/// Total deadline for the operation, including SDK retries and backoff. const OPERATION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); /// Bound one KMS call with [`OPERATION_TIMEOUT`], mapping a stall to @@ -99,7 +92,15 @@ impl AwsKmsProvider { fn from_config(cfg: &engram_aws::SdkConfig, key: String) -> Self { let key_id = format!("aws-kms:{key}"); Self { - client: Client::new(cfg), + client: Client::from_conf( + aws_sdk_kms::config::Builder::from(cfg) + .retry_config( + aws_sdk_kms::config::retry::RetryConfig::standard() + .with_max_attempts(3) + .with_initial_backoff(std::time::Duration::from_millis(100)), + ) + .build(), + ), key, key_id, } @@ -157,6 +158,44 @@ mod tests { use wiremock::matchers::{body_string_contains, header}; use wiremock::{Mock, MockServer, ResponseTemplate}; + #[tokio::test(flavor = "current_thread")] + async fn transient_kms_errors_exhaust_three_attempts() { + for (code, kind) in [(500, "KMSInternalException"), (429, "ThrottlingException")] { + let server = MockServer::start().await; + Mock::given(header("x-amz-target", "TrentService.Encrypt")) + .respond_with( + ResponseTemplate::new(code).set_body_json(serde_json::json!({"__type": kind})), + ) + .expect(3) + .mount(&server) + .await; + assert!(provider(&server).await.wrap(&[7; 32]).await.is_err()); + } + } + + #[tokio::test(flavor = "current_thread")] + async fn decrypt_recovers_after_transient_failure() { + let server = MockServer::start().await; + let calls = std::sync::atomic::AtomicUsize::new(0); + Mock::given(header("x-amz-target", "TrentService.Decrypt")) + .respond_with(move |_: &wiremock::Request| { + if calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 { + ResponseTemplate::new(503) + } else { + ResponseTemplate::new(200).set_body_json( + serde_json::json!({"Plaintext": BASE64_STANDARD.encode([7; 32])}), + ) + } + }) + .expect(2) + .mount(&server) + .await; + assert_eq!( + provider(&server).await.unwrap(b"wrapped").await.unwrap(), + [7; 32] + ); + } + const KEY_ARN: &str = "arn:aws:kms:us-east-1:123456789012:key/00000000-0000-0000-0000-000000000000"; diff --git a/crates/engram-oci/src/docker_image.rs b/crates/engram-oci/src/docker_image.rs index 0e84bb3ce..a69db9169 100644 --- a/crates/engram-oci/src/docker_image.rs +++ b/crates/engram-oci/src/docker_image.rs @@ -81,7 +81,7 @@ impl OciClient { let reference: oci_client::Reference = uri .parse() .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; let auth = self.auth_for(&reference).await?; let (manifest, digest) = client @@ -164,7 +164,7 @@ impl OciClient { let reference: oci_client::Reference = uri .parse() .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; pull_layer_to_vec(client, &reference, &blob.to_descriptor()).await } @@ -172,17 +172,9 @@ impl OciClient { /// bounded memory regardless of layer size, whole-file digest-verified /// before returning. /// - /// **Transient-resilient (the `dev-brain` incident).** A ~60 GiB - /// image's fat layers are long single-stream downloads; through GKE - /// Cloud NAT they hit idle/receive resets mid-body (reqwest: - /// `error decoding response body`). Rather than fail the layer — and - /// with it the whole image pull, which the enable scanner scrubs and - /// restarts from zero — this **keeps the bytes already written and - /// resumes** with `Range: bytes=-` (a 206 appends; a registry - /// that ignores `Range` and 200s restarts the layer from zero so we - /// never double a prefix), up to [`BlobRetryConfig::max_attempts`] - /// with exponential backoff (429 backs off harder). One re-auth on - /// 401 (GHCR bearer tokens live ~5 min) doesn't consume an attempt. + /// A partial transfer resumes with `Range` from the last written byte. + /// A server that ignores `Range` restarts the download from byte zero. + /// Retries use bounded exponential backoff; one 401 refresh is separate. /// /// A blob of at least [`RangedPullConfig::min_blob_bytes`] first /// downloads as concurrent `Range` requests. When that fails for any @@ -221,7 +213,7 @@ impl OciClient { ), } } - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; self.stream_blob_resumable(client, &reference, &desc, &blob.digest, dest) .await } @@ -316,7 +308,7 @@ impl OciClient { use tokio::io::AsyncSeekExt as _; let cfg = self.blob_retry(); - let client = self.client_for(reference); + let client = self.client_for(reference).await?; let mut file = tokio::fs::OpenOptions::new() .write(true) .open(path) diff --git a/crates/engram-oci/src/lib.rs b/crates/engram-oci/src/lib.rs index 8b80c1c36..4aed44f15 100644 --- a/crates/engram-oci/src/lib.rs +++ b/crates/engram-oci/src/lib.rs @@ -16,9 +16,12 @@ //! //! ## HTTP fallback for local registries //! -//! Standard OCI clients reject plaintext HTTP for security. We allow -//! it only when the registry host is `localhost`, `127.0.0.1`, or -//! `::1` — same heuristic Docker uses for `--insecure-registry`. +//! HTTPS and public registry addresses are the defaults. Local development +//! must set `ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK=1` for loopback HTTP. +//! Private HTTPS registries require `ENGRAM_OCI_ALLOW_PRIVATE_REGISTRIES=1`. +//! Address checks cover the initial registry and the HEAD token endpoint; +//! oci-client owns its redirects and token requests, so network egress policy +//! must also restrict those destinations and DNS rebinding. use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -93,6 +96,8 @@ pub struct OciClient { /// tests dial the backoff down via [`OciClient::with_blob_retry`]. blob_retry: BlobRetryConfig, ranged_pull: RangedPullConfig, + allow_insecure_loopback: bool, + allow_private_registries: bool, } /// Transient-retry policy for streaming ONE (potentially multi-GB) blob @@ -189,11 +194,19 @@ impl OciClient { Self { inner, inner_http, - http: engram_tls::client(), + http: engram_tls::client_builder() + .redirect(reqwest::redirect::Policy::none()) + .build() + .expect("OCI HTTP client"), head_tokens: Arc::new(Mutex::new(HashMap::new())), auth, blob_retry: BlobRetryConfig::default(), ranged_pull: RangedPullConfig::default(), + allow_insecure_loopback: std::env::var("ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK").as_deref() + == Ok("1"), + allow_private_registries: std::env::var("ENGRAM_OCI_ALLOW_PRIVATE_REGISTRIES") + .as_deref() + == Ok("1"), } } @@ -218,15 +231,83 @@ impl OciClient { self } - /// The cached client whose protocol matches `reference`'s registry - /// host: `Http` for loopback, `Https` otherwise. Plaintext is the - /// wrong default everywhere except dev. - fn client_for(&self, reference: &Reference) -> &Client { - if is_loopback_host(reference.registry()) { + /// Permit plaintext HTTP to loopback registries for local development. + pub fn with_insecure_loopback(mut self, allow: bool) -> Self { + self.allow_insecure_loopback = allow; + self + } + + /// Permit private registry addresses. HTTPS remains required off loopback. + pub fn with_private_registries(mut self, allow: bool) -> Self { + self.allow_private_registries = allow; + self + } + + fn uses_http(&self, registry: &str) -> bool { + self.allow_insecure_loopback && is_loopback_host(registry) + } + + async fn validate_registry(&self, registry: &str) -> Result<(), OciError> { + let url = reqwest::Url::parse(&format!("https://{registry}")) + .map_err(|e| OciError::InvalidUri(format!("invalid registry: {e}")))?; + self.validate_destination(&url).await + } + + async fn validate_destination(&self, url: &reqwest::Url) -> Result<(), OciError> { + let host = url + .host_str() + .ok_or_else(|| OciError::InvalidUri("registry has no host".into()))?; + let host = host.trim_start_matches('[').trim_end_matches(']'); + let loopback = is_loopback_host(host); + if url.scheme() != "https" + && !(url.scheme() == "http" && self.allow_insecure_loopback && loopback) + { + return Err(OciError::InvalidUri("registry requires HTTPS".into())); + } + if self.allow_private_registries || (self.allow_insecure_loopback && loopback) { + return Ok(()); + } + let rejected = + || OciError::InvalidUri("private registry address requires explicit opt-in".into()); + if loopback { + return Err(rejected()); + } + if let Ok(ip) = host.parse::() { + return if forbidden_ip(ip) { + Err(rejected()) + } else { + Ok(()) + }; + } + let addresses = tokio::time::timeout( + Duration::from_secs(5), + tokio::net::lookup_host((host, url.port_or_known_default().unwrap_or(443))), + ) + .await + .map_err(|_| OciError::InvalidUri("registry DNS lookup timed out".into()))? + .map_err(OciError::Io)?; + let mut found = false; + for address in addresses { + found = true; + if forbidden_ip(address.ip()) { + return Err(rejected()); + } + } + if !found { + return Err(OciError::InvalidUri( + "registry DNS returned no addresses".into(), + )); + } + Ok(()) + } + + async fn client_for(&self, reference: &Reference) -> Result<&Client, OciError> { + self.validate_registry(reference.registry()).await?; + Ok(if self.uses_http(reference.registry()) { &self.inner_http } else { &self.inner - } + }) } async fn auth_for(&self, reference: &Reference) -> Result { @@ -274,7 +355,7 @@ impl OciClient { let reference: Reference = uri .parse() .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; let auth = self.auth_for(&reference).await?; let mut layers = Vec::new(); @@ -328,7 +409,7 @@ impl OciClient { let reference: Reference = uri .parse() .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; let auth = self.auth_for(&reference).await?; // Manifest only — layer descriptors, no bodies. Also primes @@ -403,7 +484,7 @@ impl OciClient { let reference: Reference = uri .parse() .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; let auth = self.auth_for(&reference).await?; let tar_gz = tar_gz_dir(pack_dir).await?; @@ -428,7 +509,7 @@ impl OciClient { let reference: Reference = uri .parse() .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; let auth = self.auth_for(&reference).await?; let accepted = vec![ENGRAM_HARNESS_TAR_MEDIA_TYPE, OCI_IMAGE_MEDIA_TYPE]; @@ -466,7 +547,7 @@ impl OciClient { let reference: Reference = uri .parse() .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; let auth = self.auth_for(&reference).await?; client .auth(&reference, &auth, RegistryOperation::Push) @@ -491,7 +572,8 @@ impl OciClient { .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; let registry = reference.registry().to_string(); let repo = reference.repository().to_string(); - let scheme = if is_loopback_host(®istry) { + self.validate_registry(®istry).await?; + let scheme = if self.uses_http(®istry) { "http" } else { "https" @@ -553,7 +635,10 @@ impl OciClient { "unparseable WWW-Authenticate challenge from {registry}: {challenge}" )) })?; - let mut req = self.http.get(¶ms.realm); + let realm = reqwest::Url::parse(¶ms.realm) + .map_err(|e| OciError::InvalidUri(format!("invalid token endpoint: {e}")))?; + self.validate_destination(&realm).await?; + let mut req = self.http.get(realm); let mut query: Vec<(&str, &str)> = Vec::new(); if let Some(service) = ¶ms.service { query.push(("service", service)); @@ -608,7 +693,7 @@ impl OciClient { let reference: Reference = uri .parse() .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; self.push_blob_reauth(client, &reference, bytes.into(), digest) .await } @@ -666,7 +751,7 @@ impl OciClient { let reference: Reference = uri .parse() .map_err(|e: oci_client::ParseError| OciError::InvalidUri(format!("{uri}: {e}")))?; - let client = self.client_for(&reference); + let client = self.client_for(&reference).await?; // Push the small layers + config as blobs, collecting // descriptors as we go. @@ -933,7 +1018,45 @@ fn is_loopback_host(host: &str) -> bool { // bare IPv6 address with no port (e.g. "::1") host }; - matches!(stripped, "localhost" | "127.0.0.1" | "::1") + stripped + .trim_end_matches('.') + .eq_ignore_ascii_case("localhost") + || stripped + .parse::() + .is_ok_and(|ip| match ip { + std::net::IpAddr::V4(ip) => ip.is_loopback(), + std::net::IpAddr::V6(ip) => { + ip.is_loopback() || ip.to_ipv4_mapped().is_some_and(|ip| ip.is_loopback()) + } + }) +} + +fn forbidden_ip(ip: std::net::IpAddr) -> bool { + match ip { + std::net::IpAddr::V4(ip) => { + let [a, b, _, _] = ip.octets(); + ip.is_loopback() + || ip.is_private() + || ip.is_link_local() + || ip.is_unspecified() + || ip.is_multicast() + || ip.is_broadcast() + || a == 0 + || a >= 240 + || (a == 100 && (64..=127).contains(&b)) + } + std::net::IpAddr::V6(ip) => ip.to_ipv4_mapped().map_or_else( + || { + let first = ip.segments()[0]; + ip.is_loopback() + || ip.is_unspecified() + || ip.is_multicast() + || first & 0xfe00 == 0xfc00 + || first & 0xffc0 == 0xfe80 + }, + |v4| forbidden_ip(v4.into()), + ), + } } async fn read_file_bytes(path: &Path) -> Result, OciError> { @@ -1037,6 +1160,44 @@ pub fn sha256_digest(bytes: &[u8]) -> Digest256 { mod tests { use super::*; + #[tokio::test] + async fn registry_policy_rejects_private_addresses_and_gates_http() { + let safe = OciClient::new(Arc::new(AnonymousResolver)) + .with_private_registries(false) + .with_insecure_loopback(false); + for host in [ + "localhost", + "127.1.2.3", + "10.1.2.3", + "172.16.0.1", + "192.168.1.1", + "169.254.169.254", + "100.64.0.1", + "0.0.0.0", + "224.0.0.1", + "[::1]", + "[::]", + "[fe80::1]", + "[fc00::1]", + "[ff02::1]", + "[::ffff:127.0.0.1]", + "2130706433", + ] { + assert!(safe.validate_registry(host).await.is_err(), "{host}"); + assert!(!safe.uses_http(host)); + } + for host in ["8.8.8.8", "[2606:4700:4700::1111]"] { + safe.validate_registry(host).await.unwrap(); + } + let local = safe.clone().with_insecure_loopback(true); + local.validate_registry("localhost:5000").await.unwrap(); + assert!(local.uses_http("localhost:5000")); + assert!(local.validate_registry("169.254.169.254").await.is_err()); + let private = safe.with_private_registries(true); + private.validate_registry("10.0.0.1").await.unwrap(); + assert!(!private.uses_http("localhost")); + } + #[test] fn loopback_host_recognized() { assert!(is_loopback_host("localhost")); diff --git a/crates/engram-oci/tests/docker_blob_resume.rs b/crates/engram-oci/tests/docker_blob_resume.rs index 0c4735230..33793b711 100644 --- a/crates/engram-oci/tests/docker_blob_resume.rs +++ b/crates/engram-oci/tests/docker_blob_resume.rs @@ -1,5 +1,5 @@ //! Transient-resume tests for the standard-docker layer pull -//! (`pull_docker_blob_to_file`) — the `dev-brain` incident. +//! (`pull_docker_blob_to_file`). //! //! A fat layer's long single-stream GB download through GKE Cloud NAT //! gets reset mid-body (reqwest: `error decoding response body`). The @@ -10,7 +10,7 @@ //! 401 once — the `per_chunk_roundtrip.rs` / `materialize.rs` pattern. //! //! Each property is proved with the least data: a 2 KB synthetic blob, -//! a millisecond backoff, no network, no Docker. +//! a millisecond backoff, and a loopback registry. use std::net::SocketAddr; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -225,11 +225,13 @@ async fn spawn(mode: Mode, blob: Bytes) -> (SocketAddr, Registry, oneshot::Sende /// A client whose blob-retry backoff is milliseconds, so the exhaustion /// path doesn't sleep for real seconds. fn fast_client() -> OciClient { - OciClient::new(Arc::new(AnonymousResolver)).with_blob_retry(BlobRetryConfig { - max_attempts: 5, - base_backoff: Duration::from_millis(1), - rate_limit_backoff: Duration::from_millis(1), - }) + OciClient::new(Arc::new(AnonymousResolver)) + .with_insecure_loopback(true) + .with_blob_retry(BlobRetryConfig { + max_attempts: 5, + base_backoff: Duration::from_millis(1), + rate_limit_backoff: Duration::from_millis(1), + }) } fn blob_ref(blob: &Bytes) -> DockerBlobRef { diff --git a/crates/engram-oci/tests/per_chunk_roundtrip.rs b/crates/engram-oci/tests/per_chunk_roundtrip.rs index f88b39f0f..75fca9b02 100644 --- a/crates/engram-oci/tests/per_chunk_roundtrip.rs +++ b/crates/engram-oci/tests/per_chunk_roundtrip.rs @@ -206,7 +206,7 @@ async fn spawn_registry() -> (SocketAddr, Registry, oneshot::Sender<()>) { async fn per_chunk_artifact_push_pull_roundtrip() { let (addr, reg, _shutdown) = spawn_registry().await; let uri = format!("127.0.0.1:{}/roundtrip:warm-1", addr.port()); - let client = OciClient::new(Arc::new(AnonymousResolver)); + let client = OciClient::new(Arc::new(AnonymousResolver)).with_insecure_loopback(true); // Three "chunks" with distinct content. let chunks: Vec<&[u8]> = vec![b"chunk-alpha", b"chunk-beta-longer", b"chunk-gamma"]; diff --git a/crates/engram-rootfs-materializer/tests/materialize.rs b/crates/engram-rootfs-materializer/tests/materialize.rs index 4167b4d56..b7cb37fe4 100644 --- a/crates/engram-rootfs-materializer/tests/materialize.rs +++ b/crates/engram-rootfs-materializer/tests/materialize.rs @@ -253,7 +253,7 @@ async fn publish_fixture(layer_media_types: Option<[&str; 2]>) -> Fixture { } fn oci_client() -> OciClient { - OciClient::new(Arc::new(AnonymousResolver)) + OciClient::new(Arc::new(AnonymousResolver)).with_insecure_loopback(true) } // --------------------------------------------------------------- diff --git a/crates/engram-sandbox-firecracker/tests/materialize_boot.rs b/crates/engram-sandbox-firecracker/tests/materialize_boot.rs index b4e2cc268..26110a5f5 100644 --- a/crates/engram-sandbox-firecracker/tests/materialize_boot.rs +++ b/crates/engram-sandbox-firecracker/tests/materialize_boot.rs @@ -340,7 +340,7 @@ async fn materialize_and_boot() { )); let scratch = tempfile::tempdir().expect("scratch"); let materializer = Materializer::new( - OciClient::new(Arc::new(AnonymousResolver)), + OciClient::new(Arc::new(AnonymousResolver)).with_insecure_loopback(true), InitInjection { vsock_port: ENGRAM_AGENTD_PORT, transport: Transport::Vsock, diff --git a/crates/engram-secrets-aws/src/ca.rs b/crates/engram-secrets-aws/src/ca.rs index c88d53b1b..3a29852d1 100644 --- a/crates/engram-secrets-aws/src/ca.rs +++ b/crates/engram-secrets-aws/src/ca.rs @@ -43,7 +43,7 @@ impl AwsSecretsManagerCaSource { )); } Ok(Self { - client: aws_sdk_secretsmanager::Client::new(&cfg), + client: crate::retrying_client(&cfg), cert_ref: parse_ref(cert_secret.as_ref()), key_ref: parse_ref(key_secret.as_ref()), }) @@ -61,7 +61,7 @@ impl AwsSecretsManagerCaSource { }) .await; Self { - client: aws_sdk_secretsmanager::Client::new(&cfg), + client: crate::retrying_client(&cfg), cert_ref: parse_ref(cert_secret.as_ref()), key_ref: parse_ref(key_secret.as_ref()), } diff --git a/crates/engram-secrets-aws/src/lib.rs b/crates/engram-secrets-aws/src/lib.rs index 5cd666adb..5b6fca9f4 100644 --- a/crates/engram-secrets-aws/src/lib.rs +++ b/crates/engram-secrets-aws/src/lib.rs @@ -92,7 +92,7 @@ impl AwsSecretsManager { )); } Ok(Self { - client: Client::new(&cfg), + client: retrying_client(&cfg), }) } @@ -104,7 +104,7 @@ impl AwsSecretsManager { }) .await; Self { - client: Client::new(&cfg), + client: retrying_client(&cfg), } } @@ -139,14 +139,20 @@ impl AwsSecretsManager { } } -/// Per-call deadline. The shared `engram-aws` transport bounds only -/// the CONNECT (5 s) and disables SDK retries — correct for the -/// GB-scale blob path, but a secret read that stalls after the -/// handshake (an LB draining mid-response, a partial partition) -/// would otherwise hang forever, wedging session-create and -/// host-agent boot instead of failing them. 10 s matches the GCP -/// twin's reqwest operation timeout -/// (`engram-secrets-gcp`'s client builder). +/// Secrets and CA reads share the same bounded SDK retry policy. +pub(crate) fn retrying_client(cfg: &engram_aws::SdkConfig) -> Client { + Client::from_conf( + aws_sdk_secretsmanager::config::Builder::from(cfg) + .retry_config( + aws_sdk_secretsmanager::config::retry::RetryConfig::standard() + .with_max_attempts(3) + .with_initial_backoff(std::time::Duration::from_millis(100)), + ) + .build(), + ) +} + +/// Total deadline for the operation, including SDK retries and backoff. const OPERATION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); /// Low-level `GetSecretValue`: map service errors to typed @@ -243,6 +249,33 @@ mod tests { use wiremock::matchers::{body_string_contains, header}; use wiremock::{Mock, MockServer, ResponseTemplate}; + #[tokio::test(flavor = "current_thread")] + async fn transient_secret_errors_exhaust_three_attempts() { + std::env::set_var("AWS_ACCESS_KEY_ID", "test"); + std::env::set_var("AWS_SECRET_ACCESS_KEY", "test"); + for (code, kind) in [(500, "InternalServiceError"), (429, "ThrottlingException")] { + let server = wiremock::MockServer::start().await; + wiremock::Mock::given(wiremock::matchers::method("POST")) + .respond_with( + wiremock::ResponseTemplate::new(code) + .set_body_json(serde_json::json!({"__type": kind})), + ) + .expect(3) + .mount(&server) + .await; + let manager = AwsSecretsManager::with_endpoint(server.uri()).await; + assert!(get_secret_string( + &manager.client, + &SecretRef { + secret_id: "test-secret".into(), + version_stage: None + } + ) + .await + .is_err()); + } + } + fn ctx() -> SecretContext<'static> { SecretContext { repo: "cortex/api", diff --git a/crates/engram-secrets-gcp/Cargo.toml b/crates/engram-secrets-gcp/Cargo.toml index 57e451030..20e5a1fcc 100644 --- a/crates/engram-secrets-gcp/Cargo.toml +++ b/crates/engram-secrets-gcp/Cargo.toml @@ -4,13 +4,14 @@ version.workspace = true edition.workspace = true license.workspace = true repository.workspace = true -description = "GCP Secret Manager SecretStore implementation. Production target stub." +description = "GCP Secret Manager SecretStore implementation." [lints] workspace = true [dependencies] engram-tls.workspace = true +engram-cloud-gcp.workspace = true engram-core.workspace = true engram-egress-proxy.workspace = true async-trait.workspace = true diff --git a/crates/engram-secrets-gcp/src/lib.rs b/crates/engram-secrets-gcp/src/lib.rs index 9be4c068b..bf4037b35 100644 --- a/crates/engram-secrets-gcp/src/lib.rs +++ b/crates/engram-secrets-gcp/src/lib.rs @@ -28,8 +28,8 @@ pub mod ca; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; +use std::sync::Arc; +use std::time::Duration; use async_trait::async_trait; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; @@ -43,126 +43,8 @@ use serde::Deserialize; /// [`GcpSecretManager::with_base_url`]. pub(crate) const DEFAULT_SECRETMANAGER_BASE: &str = "https://secretmanager.googleapis.com"; -/// Default metadata-server token endpoint. Overridable for tests. -const DEFAULT_METADATA_TOKEN_URL: &str = - "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"; - -// --------------------------------------------------------------------- -// TokenSource -// --------------------------------------------------------------------- - -/// Fetches an OAuth bearer token suitable for calling -/// `secretmanager.googleapis.com`. Trait so tests can inject a -/// static value without hitting the metadata server. -#[async_trait] -pub trait TokenSource: Send + Sync { - async fn token(&self) -> Result; -} - -/// Returns a fixed token. Test fixture. -#[derive(Clone, Debug)] -pub struct StaticTokenSource(pub String); - -#[async_trait] -impl TokenSource for StaticTokenSource { - async fn token(&self) -> Result { - Ok(self.0.clone()) - } -} - -/// Fetches tokens from the GCE/GKE instance metadata server. Caches -/// the token in memory until 60 s before expiry. The metadata server -/// itself caches across the same lifetime, but skipping the round-trip -/// keeps session-create latency tight when several secrets resolve in -/// a row. -pub struct MetadataTokenSource { - http: reqwest::Client, - endpoint: String, - cache: Mutex>, -} - -#[derive(Clone)] -struct CachedToken { - bearer: String, - not_after: Instant, -} - -#[derive(Deserialize)] -struct MetadataTokenResponse { - access_token: String, - /// Seconds until expiry, per RFC 6749. Metadata server returns ~3600. - expires_in: u64, -} - -impl MetadataTokenSource { - pub fn new() -> Result { - let http = engram_tls::client_builder() - .timeout(Duration::from_secs(5)) - .build() - .map_err(|e| SecretError::Backend(Box::new(e)))?; - Ok(Self { - http, - endpoint: DEFAULT_METADATA_TOKEN_URL.into(), - cache: Mutex::new(None), - }) - } - - /// Override the metadata endpoint. For tests pointing at a mock - /// server. - pub fn with_endpoint(mut self, endpoint: impl Into) -> Self { - self.endpoint = endpoint.into(); - self - } -} - -#[async_trait] -impl TokenSource for MetadataTokenSource { - async fn token(&self) -> Result { - if let Some(tok) = self - .cache - .lock() - .expect("token cache mutex poisoned") - .as_ref() - { - if tok.not_after > Instant::now() { - return Ok(tok.bearer.clone()); - } - } - - let resp = self - .http - .get(&self.endpoint) - .header("Metadata-Flavor", "Google") - .send() - .await - .map_err(|e| SecretError::Backend(Box::new(e)))?; - let status = resp.status(); - if status.is_client_error() { - return Err(SecretError::Unauthorized(format!( - "metadata-server returned {status} fetching access token" - ))); - } - if !status.is_success() { - return Err(SecretError::Backend( - format!("metadata-server returned {status} fetching access token").into(), - )); - } - let body: MetadataTokenResponse = resp - .json() - .await - .map_err(|e| SecretError::Protocol(format!("metadata-server token JSON: {e}")))?; - - // Refresh 60 s before actual expiry so we don't trip into an - // expired token mid-request. - let lifetime = Duration::from_secs(body.expires_in.saturating_sub(60).max(30)); - let cached = CachedToken { - bearer: body.access_token.clone(), - not_after: Instant::now() + lifetime, - }; - *self.cache.lock().expect("token cache mutex poisoned") = Some(cached); - Ok(body.access_token) - } -} +use engram_cloud_gcp::auth::send_with_retry; +pub use engram_cloud_gcp::auth::{MetadataTokenSource, StaticTokenSource, TokenSource}; // --------------------------------------------------------------------- // GcpSecretManager @@ -286,22 +168,15 @@ pub(crate) async fn access_payload( path: &str, ) -> Result>, SecretError> { let url = format!("{base_url}/v1/{path}:access"); - let bearer = token_source.token().await?; - - let resp = http - .get(&url) - .bearer_auth(&bearer) - .send() - .await - .map_err(|e| SecretError::Backend(Box::new(e)))?; + let resp = send_with_retry(|| http.get(&url), Some(token_source.as_ref())).await?; let status = resp.status(); if status == reqwest::StatusCode::NOT_FOUND { return Ok(None); } - if status == reqwest::StatusCode::FORBIDDEN { + if status == reqwest::StatusCode::FORBIDDEN || status == reqwest::StatusCode::UNAUTHORIZED { return Err(SecretError::Unauthorized(format!( - "Secret Manager denied access to `{path}` (status 403); \ + "Secret Manager denied access to `{path}` (status {status}); \ check Workload Identity binding for `roles/secretmanager.secretAccessor`" ))); } @@ -358,6 +233,58 @@ mod tests { use wiremock::matchers::{header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; + #[tokio::test] + async fn get_refreshes_rejected_metadata_token_and_recovers_from_503() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let server = MockServer::start().await; + let token_count = AtomicUsize::new(0); + Mock::given(path("/token")) + .respond_with(move |_: &wiremock::Request| { + let token = if token_count.fetch_add(1, Ordering::SeqCst) == 0 { + "old" + } else { + "new" + }; + ResponseTemplate::new(200) + .set_body_json(serde_json::json!({"access_token": token, "expires_in": 3600})) + }) + .expect(2) + .mount(&server) + .await; + Mock::given(header("authorization", "Bearer old")) + .respond_with(ResponseTemplate::new(401)) + .expect(1) + .mount(&server) + .await; + let attempts = AtomicUsize::new(0); + Mock::given(header("authorization", "Bearer new")) + .respond_with(move |_: &wiremock::Request| { + if attempts.fetch_add(1, Ordering::SeqCst) == 0 { + ResponseTemplate::new(503) + } else { + ResponseTemplate::new(200).set_body_json( + serde_json::json!({"payload": {"data": BASE64_STANDARD.encode("secret")}}), + ) + } + }) + .expect(2) + .mount(&server) + .await; + let manager = manager(&server).with_token_source(Arc::new( + MetadataTokenSource::new() + .unwrap() + .with_endpoint(format!("{}/token", server.uri())), + )); + assert_eq!( + manager + .get(&ctx(), "KEY", &schema(None)) + .await + .unwrap() + .as_deref(), + Some("secret") + ); + } + fn ctx() -> SecretContext<'static> { SecretContext { repo: "cortex/api", diff --git a/crates/engram-storage-local/src/lib.rs b/crates/engram-storage-local/src/lib.rs index d26b03794..5c317f8fa 100644 --- a/crates/engram-storage-local/src/lib.rs +++ b/crates/engram-storage-local/src/lib.rs @@ -84,18 +84,28 @@ impl BlobStorage for LocalBlobStorage { .map(|d| d.as_nanos()) .unwrap_or(0) )); - let mut file = fs::File::create(&tmp).await?; - let mut total: u64 = 0; - while let Some(chunk) = body.next().await { - let bytes = chunk?; - file.write_all(&bytes).await?; - total += bytes.len() as u64; + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp) + .await?; + let result = async { + let mut total = 0u64; + while let Some(chunk) = body.next().await { + let bytes = chunk?; + file.write_all(&bytes).await?; + total += bytes.len() as u64; + } + file.flush().await?; + drop(file); + fs::rename(&tmp, &dst).await?; + Ok::<_, BlobError>(total) + } + .await; + if result.is_err() { + let _ = fs::remove_file(&tmp).await; } - file.flush().await?; - // Drop the file handle before rename so windows-y filesystems - // don't choke; a no-op on POSIX but defensible. - drop(file); - fs::rename(&tmp, &dst).await?; + let total = result?; tracing::debug!(key = %key, bytes = total, "local blob put"); Ok(total) } @@ -192,7 +202,9 @@ impl BlobStorage for LocalBlobStorage { }; let mut out = Vec::new(); if metadata.is_file() { - out.push(prefix.to_string()); + if !is_upload_temp(&start) { + out.push(prefix.to_string()); + } return Ok(out); } let mut stack: Vec = vec![start]; @@ -200,6 +212,9 @@ impl BlobStorage for LocalBlobStorage { let mut rd = fs::read_dir(&dir).await?; while let Some(entry) = rd.next_entry().await? { let path = entry.path(); + if is_upload_temp(&path) { + continue; + } let ft = entry.file_type().await?; if ft.is_dir() { stack.push(path); @@ -227,6 +242,27 @@ impl BlobStorage for LocalBlobStorage { } } +// Upload staging files are not blob keys, including files left by a crash. +fn is_upload_temp(path: &Path) -> bool { + let Some(name) = path.file_name() else { + return false; + }; + let name = name.to_string_lossy(); + if name.starts_with(".tmp.") { + return true; + } + let Some((_, suffix)) = name.rsplit_once(".tmp.") else { + return false; + }; + let Some((pid, nanos)) = suffix.split_once('.') else { + return false; + }; + !pid.is_empty() + && !nanos.is_empty() + && pid.bytes().all(|c| c.is_ascii_digit()) + && nanos.bytes().all(|c| c.is_ascii_digit()) +} + #[cfg(test)] mod tests { use super::*; @@ -242,6 +278,48 @@ mod tests { // key validation and the lexicographic-ordering guarantee this // backend adds on top of the contract. + #[tokio::test] + async fn failed_upload_removes_staging_file() { + let dir = tempdir().unwrap(); + let store = LocalBlobStorage::new(dir.path()); + let body = ByteStream::new(futures::stream::iter([ + Ok(Bytes::from_static(b"partial")), + Err(BlobError::Io(std::io::Error::other("stream failed"))), + ])); + assert!(store.put_streaming("blob", body).await.is_err()); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); + } + + #[tokio::test] + async fn list_ignores_crash_staging_files() { + let dir = tempdir().unwrap(); + let store = LocalBlobStorage::new(dir.path()); + std::fs::write(dir.path().join("blob.tmp.1.2"), b"partial").unwrap(); + std::fs::write(dir.path().join(".tmp.orphan"), b"partial").unwrap(); + store + .put("blob", Bytes::from_static(b"complete")) + .await + .unwrap(); + assert_eq!(store.list_prefix("").await.unwrap(), ["blob"]); + assert!(store.list_prefix("blob.tmp.1.2").await.unwrap().is_empty()); + } + + #[tokio::test] + async fn failed_rename_removes_staging_file() { + let dir = tempdir().unwrap(); + let store = LocalBlobStorage::new(dir.path()); + std::fs::create_dir(dir.path().join("blob")).unwrap(); + assert!(store + .put("blob", Bytes::from_static(b"data")) + .await + .is_err()); + let names: Vec<_> = std::fs::read_dir(dir.path()) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(names, ["blob"]); + } + #[tokio::test] async fn conformance_round_trip() { let dir = tempdir().unwrap(); From a7cae16323e9c13b6f1267a11621805a24a576ca Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:06:15 -0800 Subject: [PATCH 2/6] fix(crypto): drop the unused aad envelope api and zeroize the aes key schedule `seal_with_aad` and `open_with_aad` had no caller. A sealed row does not record whether it was sealed with AAD, so a reader cannot select the right open without a schema change, and an open that falls back to empty AAD gives no binding. The API stays out until a change adds the format marker and the callers together. Turn on the aes-gcm `zeroize` feature so the expanded AES and GHASH keys are cleared on drop, as the raw DEK and KEK already are. The persisted envelope format does not change; the aes-gcm 0.10.3 vector still opens. Restore the two facts the earlier cleanup dropped: why `SysRng` is used (a `!Send` RNG makes the seal future `!Send`), and that a failure of the fixed-vector test is a data problem, not a value to update. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 ++ crates/engram-crypto/Cargo.toml | 2 +- crates/engram-crypto/src/lib.rs | 81 ++++----------------------------- 3 files changed, 15 insertions(+), 72 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a5c74db3a..361e8879a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -36,6 +36,7 @@ dependencies = [ "cipher", "cpubits", "cpufeatures 0.3.0", + "zeroize", ] [[package]] @@ -50,6 +51,7 @@ dependencies = [ "ctr", "ctutils", "ghash", + "zeroize", ] [[package]] @@ -4035,6 +4037,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" dependencies = [ "polyval", + "zeroize", ] [[package]] @@ -6373,6 +6376,7 @@ dependencies = [ "cpubits", "cpufeatures 0.3.0", "universal-hash", + "zeroize", ] [[package]] diff --git a/crates/engram-crypto/Cargo.toml b/crates/engram-crypto/Cargo.toml index 7880bc2d4..60f8bd549 100644 --- a/crates/engram-crypto/Cargo.toml +++ b/crates/engram-crypto/Cargo.toml @@ -13,7 +13,7 @@ workspace = true async-trait.workspace = true serde = { workspace = true, optional = true } tracing.workspace = true -aes-gcm = "0.11" +aes-gcm = { version = "0.11", features = ["zeroize"] } rand = "0.10" zeroize = "1.9" base64.workspace = true diff --git a/crates/engram-crypto/src/lib.rs b/crates/engram-crypto/src/lib.rs index a02edd2f1..2206229f1 100644 --- a/crates/engram-crypto/src/lib.rs +++ b/crates/engram-crypto/src/lib.rs @@ -28,7 +28,7 @@ //! Postgres schema stores them as four columns rather than one packed //! BYTEA so they're individually queryable / auditable. -use aes_gcm::aead::{Aead, KeyInit, Payload}; +use aes_gcm::aead::{Aead, KeyInit}; use aes_gcm::{Aes256Gcm, Key}; use async_trait::async_trait; use rand::rngs::SysRng; @@ -89,21 +89,10 @@ impl<'a> CredCipher<'a> { /// AES-256-GCM, wrap the DEK with the KEK, and tag the result /// with the active KEK's `key_id`. pub async fn seal(&self, plaintext: &[u8]) -> Result { - self.seal_payload(plaintext, &[]).await - } - - /// Seal with authenticated key identity and caller context. Use only after - /// all readers support `open_with_aad`; legacy `open` cannot read this format. - pub async fn seal_with_aad( - &self, - plaintext: &[u8], - aad: &[u8], - ) -> Result { - self.seal_payload(plaintext, &envelope_aad(self.kek.key_id(), aad)) - .await - } - - async fn seal_payload(&self, plaintext: &[u8], aad: &[u8]) -> Result { + // `SysRng` is `Send`; `rand::rng()` is not, and a `!Send` handle held + // here would make the future `!Send` for callers that await across it. + // The OS RNG is fallible: a DEK or nonce never comes from a degraded + // source, so its error propagates. let mut rng = SysRng; let mut dek = Zeroizing::new([0u8; 32]); @@ -115,13 +104,7 @@ impl<'a> CredCipher<'a> { let cipher = Aes256Gcm::new((&*dek).into()); let ciphertext = cipher - .encrypt( - (&nonce).into(), - Payload { - msg: plaintext, - aad, - }, - ) + .encrypt((&nonce).into(), plaintext) .map_err(|_| CryptoError::Aead("encrypt"))?; let wrapped_dek = self.kek.wrap(&*dek).await?; @@ -138,45 +121,17 @@ impl<'a> CredCipher<'a> { /// can't be unwrapped (wrong KEK, corrupted bytes) or the GCM tag /// doesn't authenticate (tampered ciphertext / nonce). pub async fn open(&self, sealed: &SealedCred) -> Result, CryptoError> { - self.open_payload(sealed, &[]).await - } - - /// Open an AAD-bound envelope. There is no fallback to legacy empty AAD. - pub async fn open_with_aad( - &self, - sealed: &SealedCred, - aad: &[u8], - ) -> Result, CryptoError> { - self.open_payload(sealed, &envelope_aad(&sealed.key_id, aad)) - .await - } - - async fn open_payload(&self, sealed: &SealedCred, aad: &[u8]) -> Result, CryptoError> { let dek = Zeroizing::new(self.kek.unwrap(&sealed.wrapped_dek).await?); + // A DEK that is not 32 bytes means the wrong KEK or a wrap format mismatch. let key = <&Key>::try_from(&dek[..]).map_err(|_| CryptoError::DekLength(dek.len()))?; let cipher = Aes256Gcm::new(key); cipher - .decrypt( - (&sealed.nonce).into(), - Payload { - msg: &sealed.ciphertext, - aad, - }, - ) + .decrypt((&sealed.nonce).into(), sealed.ciphertext.as_slice()) .map_err(|_| CryptoError::Aead("decrypt")) } } -// Length-prefix the key identity so adjacent fields cannot alias. -fn envelope_aad(key_id: &str, context: &[u8]) -> Vec { - let mut aad = b"engram-credential-aad-v1".to_vec(); - aad.extend_from_slice(&(key_id.len() as u64).to_be_bytes()); - aad.extend_from_slice(key_id.as_bytes()); - aad.extend_from_slice(context); - aad -} - #[derive(Debug)] pub enum CryptoError { /// AES-GCM seal/open failed (auth tag mismatch, etc.). @@ -203,24 +158,6 @@ impl std::error::Error for CryptoError {} mod tests { use super::*; - #[tokio::test] - async fn aad_binds_context_and_key_identity_without_legacy_fallback() { - let kek = EnvVarKeyProvider::from_bytes([7; 32], "key:v1"); - let cipher = CredCipher::new(&kek); - let mut sealed = cipher.seal_with_aad(b"secret", b"row:1").await.unwrap(); - assert_eq!( - cipher.open_with_aad(&sealed, b"row:1").await.unwrap(), - b"secret" - ); - assert!(cipher.open_with_aad(&sealed, b"row:2").await.is_err()); - assert!(cipher.open(&sealed).await.is_err()); - sealed.key_id = "key:v2".into(); - assert!(cipher.open_with_aad(&sealed, b"row:1").await.is_err()); - let legacy = cipher.seal(b"legacy").await.unwrap(); - assert_eq!(cipher.open(&legacy).await.unwrap(), b"legacy"); - assert!(cipher.open_with_aad(&legacy, b"").await.is_err()); - } - /// Decode a compile-time hex literal into a byte vector. fn unhex(s: &str) -> Vec { assert!( @@ -235,6 +172,8 @@ mod tests { /// Fixed ciphertext from aes-gcm 0.10.3 pins the persisted envelope format. /// KEK is 00..1f, DEK is 42*32, and wrap/data nonces are 11*12 and 22*12. + /// A failure here means rows already sealed in Postgres no longer open: + /// fix the code, never the expected bytes. #[tokio::test] async fn opens_an_envelope_sealed_by_aes_gcm_0_10_3() { let kek = EnvVarKeyProvider::from_bytes( From 08125fe195e44fa9dfcddc729182d67c1da663ad Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:08:44 -0800 Subject: [PATCH 3/6] fix(oci): check a registry address once per client and keep safe head redirects The address check ran a DNS lookup before every pull part, so a ranged layer pull did one lookup per part on the resume path. A registry that passes the check is now kept in a per-client set. A policy change (`with_insecure_loopback`, `with_private_registries`) clears the set, so a clone with a stricter policy does not reuse a looser result. The HEAD probe client refused all redirects. A registry with a redirecting storage driver answers a blob HEAD with a redirect, so a bake against it failed. Redirects now follow to HTTPS hosts that are not loopback names or private address literals, or to any HTTPS host when private registries are allowed. Co-Authored-By: Claude Opus 5.5 --- crates/engram-oci/src/lib.rs | 75 ++++++++++++++++++++++++++++++------ 1 file changed, 63 insertions(+), 12 deletions(-) diff --git a/crates/engram-oci/src/lib.rs b/crates/engram-oci/src/lib.rs index 4aed44f15..192c2b420 100644 --- a/crates/engram-oci/src/lib.rs +++ b/crates/engram-oci/src/lib.rs @@ -14,16 +14,17 @@ //! its encrypted Postgres registry-credential store; tests / the host //! agent's anonymous-only path use [`AnonymousResolver`]. //! -//! ## HTTP fallback for local registries +//! ## Registry address policy //! //! HTTPS and public registry addresses are the defaults. Local development //! must set `ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK=1` for loopback HTTP. //! Private HTTPS registries require `ENGRAM_OCI_ALLOW_PRIVATE_REGISTRIES=1`. -//! Address checks cover the initial registry and the HEAD token endpoint; -//! oci-client owns its redirects and token requests, so network egress policy -//! must also restrict those destinations and DNS rebinding. +//! A registry's addresses are checked once per client, and the HEAD token +//! endpoint on each mint. oci-client owns its redirects, token requests, and +//! DNS, so network egress policy must also restrict those destinations and +//! DNS rebinding. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; @@ -98,6 +99,9 @@ pub struct OciClient { ranged_pull: RangedPullConfig, allow_insecure_loopback: bool, allow_private_registries: bool, + /// Registries that passed [`Self::validate_registry`] under this + /// client's policy, so each pull part does not repeat a DNS lookup. + validated_registries: Arc>>, } /// Transient-retry policy for streaming ONE (potentially multi-GB) blob @@ -194,10 +198,7 @@ impl OciClient { Self { inner, inner_http, - http: engram_tls::client_builder() - .redirect(reqwest::redirect::Policy::none()) - .build() - .expect("OCI HTTP client"), + http: head_client(false), head_tokens: Arc::new(Mutex::new(HashMap::new())), auth, blob_retry: BlobRetryConfig::default(), @@ -207,7 +208,17 @@ impl OciClient { allow_private_registries: std::env::var("ENGRAM_OCI_ALLOW_PRIVATE_REGISTRIES") .as_deref() == Ok("1"), + validated_registries: Arc::default(), } + .with_policy_reset() + } + + /// Rebuild the policy-dependent state after a policy change. A clone + /// with a different policy must not share the validation cache. + fn with_policy_reset(mut self) -> Self { + self.http = head_client(self.allow_private_registries); + self.validated_registries = Arc::default(); + self } /// Override the per-blob transient-retry policy (default: 5 attempts, @@ -234,13 +245,13 @@ impl OciClient { /// Permit plaintext HTTP to loopback registries for local development. pub fn with_insecure_loopback(mut self, allow: bool) -> Self { self.allow_insecure_loopback = allow; - self + self.with_policy_reset() } /// Permit private registry addresses. HTTPS remains required off loopback. pub fn with_private_registries(mut self, allow: bool) -> Self { self.allow_private_registries = allow; - self + self.with_policy_reset() } fn uses_http(&self, registry: &str) -> bool { @@ -248,9 +259,16 @@ impl OciClient { } async fn validate_registry(&self, registry: &str) -> Result<(), OciError> { + if self.validated_registries.lock().contains(registry) { + return Ok(()); + } let url = reqwest::Url::parse(&format!("https://{registry}")) .map_err(|e| OciError::InvalidUri(format!("invalid registry: {e}")))?; - self.validate_destination(&url).await + self.validate_destination(&url).await?; + self.validated_registries + .lock() + .insert(registry.to_string()); + Ok(()) } async fn validate_destination(&self, url: &reqwest::Url) -> Result<(), OciError> { @@ -1031,6 +1049,37 @@ fn is_loopback_host(host: &str) -> bool { }) } +/// The client for blob HEAD probes. A registry may redirect a HEAD to its +/// storage backend; a redirect to plaintext, loopback, or a private address +/// literal stops unless private registries are allowed. +fn head_client(allow_private: bool) -> reqwest::Client { + let policy = reqwest::redirect::Policy::custom(move |attempt| { + if attempt.previous().len() >= 10 { + return attempt.error("too many redirects"); + } + let url = attempt.url(); + let host = url + .host_str() + .unwrap_or_default() + .trim_start_matches('[') + .trim_end_matches(']'); + let host_allowed = !host.is_empty() + && !is_loopback_host(host) + && host + .parse::() + .map_or(true, |ip| !forbidden_ip(ip)); + if url.scheme() == "https" && (allow_private || host_allowed) { + attempt.follow() + } else { + attempt.stop() + } + }); + engram_tls::client_builder() + .redirect(policy) + .build() + .expect("OCI HTTP client") +} + fn forbidden_ip(ip: std::net::IpAddr) -> bool { match ip { std::net::IpAddr::V4(ip) => { @@ -1196,6 +1245,8 @@ mod tests { let private = safe.with_private_registries(true); private.validate_registry("10.0.0.1").await.unwrap(); assert!(!private.uses_http("localhost")); + let strict = private.with_private_registries(false); + assert!(strict.validate_registry("10.0.0.1").await.is_err()); } #[test] From 02c5b976401ddd995753be5d5142054bd2139d2c Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:08:45 -0800 Subject: [PATCH 4/6] docs(oci): document the private-registry opt-in and group the dev loopback opt-in `ENGRAM_OCI_ALLOW_PRIVATE_REGISTRIES` is a new setting that a deployment with an in-cluster registry or a private registry endpoint must set, so the configuration reference lists it for the coordinator and the host agents. The compose file comment now names the loopback opt-in. The Tiltfile entries move next to the other local-service settings, away from the first line of `coord_env`, which another open change also edits. Co-Authored-By: Claude Opus 5.5 --- Tiltfile | 6 ++++-- deploy/docker-compose.dev.yml | 4 ++-- site/src/content/docs/docs/reference/configuration.md | 2 ++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Tiltfile b/Tiltfile index df77f8e7f..8f179a405 100644 --- a/Tiltfile +++ b/Tiltfile @@ -408,7 +408,6 @@ if not bin_dir: otel_endpoint = env_or('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://localhost:4317') coord_env = { - 'ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK': '1', 'DATABASE_URL': 'postgres://engram:engram@localhost:5435/engram', 'ENGRAM_BIND_ADDR': '127.0.0.1:8090', # ADR 0051: the app-gRPC surface is how the orchestrator (and the @@ -437,6 +436,8 @@ coord_env = { 'ENGRAM_BLOB_BACKEND': 'gcs' if dev_split else env_or('ENGRAM_BLOB_BACKEND', 'local'), 'ENGRAM_GCS_BUCKET': env_or('ENGRAM_GCS_BUCKET', 'engram-snapshots-test'), 'STORAGE_EMULATOR_HOST': env_or('STORAGE_EMULATOR_HOST', 'http://localhost:4443'), + # The docker-compose registry serves plaintext HTTP on localhost:5001. + 'ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK': '1', 'OTEL_EXPORTER_OTLP_ENDPOINT': otel_endpoint, 'RUST_LOG': 'info,engram=debug', } @@ -563,7 +564,6 @@ if two_hosts and fc_colima_profile: def host_agent_resource(name, grpc_port, metrics_port, work_dir, egress_proxy_port, egress_dns_port, guest_gateway_port, thin_pool): env = { - 'ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK': '1', # `kernel_key` is only non-None for vz/firecracker, both of # which force `dev_split`, so this always lands on the # host-agent (there's no coord-side mode=all + real-virt path @@ -624,6 +624,8 @@ def host_agent_resource(name, grpc_port, metrics_port, work_dir, egress_proxy_po 'ENGRAM_EGRESS_DNS_PORT': egress_dns_port, 'ENGRAM_GUEST_GATEWAY_PORT': guest_gateway_port, 'ENGRAM_HOST_METRICS_ADDR': '0.0.0.0:' + metrics_port, + # The docker-compose registry serves plaintext HTTP on localhost:5001. + 'ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK': '1', # ADR 0019: same OTLP target as the coord, so the host-side # restore/boot spans land in the same Jaeger trace. 'OTEL_EXPORTER_OTLP_ENDPOINT': otel_endpoint, diff --git a/deploy/docker-compose.dev.yml b/deploy/docker-compose.dev.yml index 7e7d71f26..993e78ada 100644 --- a/deploy/docker-compose.dev.yml +++ b/deploy/docker-compose.dev.yml @@ -51,8 +51,8 @@ services: retries: 10 # Local OCI registry for dev. Anonymous pull/push over plaintext HTTP. - # Engram's OCI client allows HTTP only when the registry host is a - # loopback address, so this is safe-by-construction for dev only. + # Engram's OCI client allows HTTP only to a loopback registry host, and + # only when ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK=1 (the Tiltfile sets it). # `engram image build --push localhost:5001/cortex/api` lands here; # `engram session create --image localhost:5001/cortex/api:warm-X` # pulls from here on the host-agent side. diff --git a/site/src/content/docs/docs/reference/configuration.md b/site/src/content/docs/docs/reference/configuration.md index 118cdd98d..cf03747bb 100644 --- a/site/src/content/docs/docs/reference/configuration.md +++ b/site/src/content/docs/docs/reference/configuration.md @@ -24,6 +24,7 @@ where, for anyone reading a manifest or running a component outside the charts. | `ENGRAM_SECRETS_BACKEND` | `gcp`, `aws`, or `env` for development. | | `ENGRAM_GCP_PROJECT_ID` | With `gcp`: the Secret Manager project. | | `ENGRAM_CHUNK_GC_INTERVAL_SECS`, `ENGRAM_CHUNK_GC_RETAIN_SECS` | How often chunk garbage collection runs, and how long an unreferenced chunk is kept before deletion. | +| `ENGRAM_OCI_ALLOW_PRIVATE_REGISTRIES` | Set to `1` to pull from or push to a registry whose name resolves to a private, loopback, or link-local address, such as an in-cluster registry or a cloud registry behind a private endpoint. Unset, those registries are refused. Set the same value on the coordinator and the host agents. | | `ENGRAM_PLACEMENT_POOL_FLOOR_BYTES` | Free space a node's session-disk pool must keep for the scheduler to place a new session on it; default 16 GiB. A node deletes the checkpoint volumes of evicted sessions it kept for a fast resume when its free space falls under twice this value, so set it on the host agents too. | Cloud credentials are ambient: Workload Identity on GKE, IRSA on EKS, bound to the @@ -44,6 +45,7 @@ coordinator's ServiceAccount. There are no key files. | `ENGRAM_EGRESS_PROXY_PORT`, `ENGRAM_EGRESS_DNS_PORT`, `ENGRAM_GUEST_GATEWAY_PORT` | The proxy's listeners. Mandatory and non-zero; guest traffic is redirected to them. | | `ENGRAM_EGRESS_CA_SOURCE` | Where the proxy's certificate authority comes from. See below. | | `ENGRAM_WARM_STALL_SECS` | The stall budget for warm hooks during capture; default 120. | +| `ENGRAM_OCI_ALLOW_PRIVATE_REGISTRIES` | Must match the coordinator's. | ## The master key From 464ea6986c242bf31a71381b5e62d3ab1abecd35 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:09:24 -0800 Subject: [PATCH 5/6] fix(storage-local): list keys that start with .tmp. `list_prefix` hid every name that started with `.tmp.`, but no staging file has that shape: `put_streaming` names its staging file `.tmp..`. The rule hid valid keys such as `.tmp.key`. Only the real staging shape is now filtered. Co-Authored-By: Claude Opus 5.5 --- crates/engram-storage-local/src/lib.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/engram-storage-local/src/lib.rs b/crates/engram-storage-local/src/lib.rs index 5c317f8fa..4d767ba62 100644 --- a/crates/engram-storage-local/src/lib.rs +++ b/crates/engram-storage-local/src/lib.rs @@ -242,15 +242,13 @@ impl BlobStorage for LocalBlobStorage { } } -// Upload staging files are not blob keys, including files left by a crash. +/// Matches the `.tmp..` staging name of `put_streaming`, +/// including files that a crash left behind. fn is_upload_temp(path: &Path) -> bool { let Some(name) = path.file_name() else { return false; }; let name = name.to_string_lossy(); - if name.starts_with(".tmp.") { - return true; - } let Some((_, suffix)) = name.rsplit_once(".tmp.") else { return false; }; @@ -295,12 +293,17 @@ mod tests { let dir = tempdir().unwrap(); let store = LocalBlobStorage::new(dir.path()); std::fs::write(dir.path().join("blob.tmp.1.2"), b"partial").unwrap(); - std::fs::write(dir.path().join(".tmp.orphan"), b"partial").unwrap(); store .put("blob", Bytes::from_static(b"complete")) .await .unwrap(); - assert_eq!(store.list_prefix("").await.unwrap(), ["blob"]); + store + .put(".tmp.key", Bytes::from_static(b"key")) + .await + .unwrap(); + let mut listed = store.list_prefix("").await.unwrap(); + listed.sort(); + assert_eq!(listed, [".tmp.key", "blob"]); assert!(store.list_prefix("blob.tmp.1.2").await.unwrap().is_empty()); } From 0a051b2b9b371e167271d9e27c74d02755d1ef19 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 12:41:52 -0800 Subject: [PATCH 6/6] docs(changelog): add the private image registry upgrade note Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91e1ba4ff..d16e4d7d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,15 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu (RFC 1918, CGNAT), link-local, metadata or other reserved address. A Git server, package registry or other service that resolves only to such an address in your network is no longer reachable from sessions, and no setting turns this off. ([#1849]) +- **The coordinator and hosts refuse private image registries.** A registry whose name + resolves to a loopback, private (RFC 1918, CGNAT), link-local or metadata address is now + refused, so image enables and pulls from it fail. This includes a registry in the cluster + and a registry behind a private endpoint (an ECR VPC endpoint with private DNS, or + Artifact Registry through Private Service Connect). Public registries, such as `ghcr.io` + and `pkg.dev`, are not affected. To keep a private registry, set + `ENGRAM_OCI_ALLOW_PRIVATE_REGISTRIES=1` on the coordinator and the host agents (the + charts' `extraEnv`) before you upgrade. Plain HTTP to a loopback registry also needs + `ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK=1`; use it for local development only. ([#1852]) - **The GitHub `metadata:read` power covers less.** It gave every `GET` under `/repos///`. It now gives the repository itself and the metadata endpoints (events, forks, license, stargazers, subscribers, stats, rules, rulesets, topics, @@ -450,3 +459,4 @@ The first tagged release. See the [#1825]: https://github.com/cortexapps/engrams/pull/1825 [#1826]: https://github.com/cortexapps/engrams/pull/1826 [#1849]: https://github.com/cortexapps/engrams/pull/1849 +[#1852]: https://github.com/cortexapps/engrams/pull/1852