From e812fe85ac85ecd5ae1accef1a36c05074b06fd5 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Tue, 1 Dec 2026 12:38:27 -0800 Subject: [PATCH 01/17] feat(coordinator,orchestrator): promote admin pause/resume to app-gRPC and unify HandoffMarker --- Cargo.lock | 1 + crates/engram-coordinator/src/api/admin.rs | 44 ++--- .../engram-coordinator/src/api/host_http.rs | 40 +---- crates/engram-coordinator/src/api/mod.rs | 20 +-- .../src/grpc_app/session.rs | 30 ++++ crates/engram-coordinator/tests/grpc_app.rs | 153 ++++++++++++++++++ crates/engram-host-core/Cargo.toml | 1 + crates/engram-host-core/src/shutdown.rs | 21 +-- .../proto/engram/app/v1/session.proto | 19 +++ crates/engram-protocol/src/app.rs | 19 +++ crates/engram-protocol/src/handoff.rs | 35 ++++ crates/engram-protocol/src/lib.rs | 2 + .../src/__tests__/admin-routes.test.ts | 113 +++++++++++++ orchestrator/src/authz/policy-map.ts | 2 + orchestrator/src/config.ts | 6 - .../src/gen/engram/app/v1/session_pb.ts | 100 +++++++++++- orchestrator/src/routes/admin.ts | 116 +++++-------- .../v1/session-SessionService_connectquery.ts | 14 ++ web/src/gen/engram/app/v1/session_pb.ts | 100 +++++++++++- 19 files changed, 661 insertions(+), 175 deletions(-) create mode 100644 crates/engram-protocol/src/handoff.rs create mode 100644 orchestrator/src/__tests__/admin-routes.test.ts diff --git a/Cargo.lock b/Cargo.lock index b1a2286a4..4802661c2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2908,6 +2908,7 @@ dependencies = [ "engram-chunk-store", "engram-core", "engram-fill", + "engram-protocol", "engram-storage-local", "libc", "serde", diff --git a/crates/engram-coordinator/src/api/admin.rs b/crates/engram-coordinator/src/api/admin.rs index 8cad7ffc5..1aeb10fdd 100644 --- a/crates/engram-coordinator/src/api/admin.rs +++ b/crates/engram-coordinator/src/api/admin.rs @@ -63,15 +63,10 @@ pub(crate) async fn evict_idle_core( Ok(EvictIdleResponse { session_id, status }) } -// --------------------------------------------------------------------- -// ADR 0045 Phase F — pause / resume a microVM in place (the freeze/flush -// test surface). Thin admin passthroughs to the FC pause/resume -// primitive: freeze or unfreeze the running guest WITHOUT snapshotting, -// destroying, or changing session state. The session stays `Active`; a -// paused guest simply stops executing until resumed. Distinct from -// teleport/evac (which relocate) and from idle-eviction (which -// snapshots + suspends to `Idle`). -// --------------------------------------------------------------------- +// Pause and resume freeze or unfreeze the guest in place. Session state does not change. +// Keep the HTTP adapters until all orchestrators use app-gRPC. Remove them in the +// contract follow-up after the rollback window. Deploy coordinators first; roll +// back orchestrators before coordinators. #[derive(Serialize)] pub struct PauseResumeResponse { @@ -79,13 +74,18 @@ pub struct PauseResumeResponse { pub note: &'static str, } -/// `POST /api/admin/sessions/:id/pause` — freeze the session's running -/// microVM in place. 409 if the session has no live sandbox (idle / not -/// yet started). +/// HTTP compatibility adapter for in-place pause. pub async fn pause_session( State(state): State, Path(session_id): Path, ) -> Result, ApiError> { + pause_session_core(&state, session_id).await.map(Json) +} + +pub(crate) async fn pause_session_core( + state: &SharedState, + session_id: SessionId, +) -> Result { let sandbox_id = state.resolve_sandbox(session_id).await.ok_or_else(|| { ApiError::Conflict( "session has no live sandbox to pause — it is idle or not yet started".into(), @@ -99,20 +99,24 @@ pub async fn pause_session( .await .map_err(|e| ApiError::Internal(format!("pause sandbox: {e}")))?; tracing::info!(%session_id, %sandbox_id, "admin: froze microVM in place"); - Ok(Json(PauseResumeResponse { + Ok(PauseResumeResponse { session_id, note: "paused", - })) + }) } -/// `POST /api/admin/sessions/:id/resume` — unfreeze a `pause`d microVM in -/// place. Note: this is the *in-place* unfreeze, NOT `/sessions/:id/resume` -/// (which rehydrates an `Idle` session from a snapshot). 409 if the -/// session has no live sandbox. +/// HTTP compatibility adapter for in-place resume. pub async fn resume_session( State(state): State, Path(session_id): Path, ) -> Result, ApiError> { + resume_session_core(&state, session_id).await.map(Json) +} + +pub(crate) async fn resume_session_core( + state: &SharedState, + session_id: SessionId, +) -> Result { let sandbox_id = state.resolve_sandbox(session_id).await.ok_or_else(|| { ApiError::Conflict( "session has no live sandbox to resume in place — it is idle or not yet started".into(), @@ -126,10 +130,10 @@ pub async fn resume_session( .await .map_err(|e| ApiError::Internal(format!("resume sandbox: {e}")))?; tracing::info!(%session_id, %sandbox_id, "admin: unfroze microVM in place"); - Ok(Json(PauseResumeResponse { + Ok(PauseResumeResponse { session_id, note: "resumed", - })) + }) } // --------------------------------------------------------------------- diff --git a/crates/engram-coordinator/src/api/host_http.rs b/crates/engram-coordinator/src/api/host_http.rs index 4dd1aaf42..6f6345918 100644 --- a/crates/engram-coordinator/src/api/host_http.rs +++ b/crates/engram-coordinator/src/api/host_http.rs @@ -33,6 +33,7 @@ use engram_core::types::BindingDisposition; use engram_core::{HostId, SandboxId, SessionId, SessionState}; use engram_harness_proto::HarnessEvent; use engram_protocol::heartbeat::{EnabledImageRef, HostCapacityReport, ManifestDigest}; +use engram_protocol::HandoffMarker; use serde::{Deserialize, Serialize}; use tracing::Instrument as _; @@ -72,23 +73,6 @@ pub struct RegisterRequest { pub handoff_marker: Option, } -/// ADR 0116 A-D2: the durable note a shutting-down host-agent leaves -/// beside its binding records for the successor generation. Mirrored in -/// `engram-host-core::shutdown` (the writer); duplicated shape rather -/// than a shared dep because the coordinator only OBSERVES it. -#[derive(Debug, Clone, Deserialize, Serialize)] -pub struct HandoffMarker { - /// Predecessor's wall clock at declaration (unix ms). Same-node - /// clock, so adoption latency derived from it is honest to within - /// node clock error — fine for a histogram, never a decision input. - pub declared_at_unix_ms: i64, - /// The TTL the predecessor asked its belt POST for. - pub ttl_secs: u64, - /// Sandboxes resident at declaration (diagnostics only). - #[serde(default)] - pub resident_sandboxes: u32, -} - #[derive(Serialize)] pub struct RegisterResponse { pub server_time: DateTime, @@ -1954,28 +1938,6 @@ mod tests { assert!(!ingest_span(session_id, &idle, None).is_none()); } - /// ADR 0116 A-D2 wire pin: the coordinator's `HandoffMarker` mirror - /// must decode exactly what `engram_host_core::shutdown::HandoffMarker` - /// serializes — the shapes are deliberately duplicated (the coord only - /// OBSERVES the marker), so this JSON literal is the interop contract. - /// A field rename on either side fails here, not in a mixed fleet. - #[test] - fn handoff_marker_wire_shape_is_pinned() { - let from_host = r#"{ - "declared_at_unix_ms": 1765432100000, - "ttl_secs": 600, - "resident_sandboxes": 4 - }"#; - let m: HandoffMarker = serde_json::from_str(from_host).expect("decode host marker"); - assert_eq!(m.declared_at_unix_ms, 1_765_432_100_000); - assert_eq!(m.ttl_secs, 600); - assert_eq!(m.resident_sandboxes, 4); - // Legacy host (no resident count field) decodes with the default. - let minimal = r#"{"declared_at_unix_ms": 1, "ttl_secs": 2}"#; - let m: HandoffMarker = serde_json::from_str(minimal).expect("decode minimal"); - assert_eq!(m.resident_sandboxes, 0); - } - use engram_core::types::session::SessionMode; use engram_core::types::Session; use engram_core::types::SessionState; diff --git a/crates/engram-coordinator/src/api/mod.rs b/crates/engram-coordinator/src/api/mod.rs index 8005af779..e9d705464 100644 --- a/crates/engram-coordinator/src/api/mod.rs +++ b/crates/engram-coordinator/src/api/mod.rs @@ -41,27 +41,17 @@ pub(crate) mod storage; pub(crate) mod upload; pub fn router(state: SharedState) -> Router { - // ADR 0051: the web-facing (protected / session-scoped / member / admin / - // auth-flow) human routers are GONE. The orchestrator owns all web traffic - // and calls the coordinator exclusively over the app-gRPC surface - // (`grpc_app/*`), which delegates to the transport-agnostic `*_core` fns. - // Only the internal (host → coord) ingestion, the in-guest forge seam, the - // admin pause/resume control plane, and health probes remain on HTTP. - // - // Production note: ENGRAM_AUTH_TOKENS must include the orchestrator's - // bearer so its REST proxy calls to /admin/sessions/:id/pause and - // /admin/sessions/:id/resume (the only remaining REST control verbs, - // pending their gRPC promotion) are authenticated. The orchestrator sends - // CONTROL_PLANE_BEARER on those requests; ensure both tokens agree at - // deploy time. + // The orchestrator uses app-gRPC. HTTP serves host ingestion, in-guest + // forge requests, health probes, and the pause/resume compatibility routes. + // Keep the old orchestrator bearer in ENGRAM_AUTH_TOKENS through the + // rollback window. Remove the two admin routes in the contract follow-up. let auth_state = auth::AuthState::new(state.cfg.auth_tokens.clone()); // ADR 0031 internal control-plane: host → coord ingestion. Machine // traffic authenticated by the deployment bearer (`require_bearer`). // pause/resume live here (not a human surface) behind the same bearer. let internal = Router::new() - // ADR 0045 Phase F: freeze / unfreeze a microVM in place. - // In prod: ENGRAM_AUTH_TOKENS must include the orchestrator's bearer. + // Compatibility for older orchestrators: in-place freeze / unfreeze. .route("/admin/sessions/{id}/pause", post(admin::pause_session)) .route("/admin/sessions/{id}/resume", post(admin::resume_session)) .route("/hosts/register", post(host_http::register)) diff --git a/crates/engram-coordinator/src/grpc_app/session.rs b/crates/engram-coordinator/src/grpc_app/session.rs index e99b1f91c..846581baf 100644 --- a/crates/engram-coordinator/src/grpc_app/session.rs +++ b/crates/engram-coordinator/src/grpc_app/session.rs @@ -680,6 +680,36 @@ impl app::session_service_server::SessionService for AppSessionService { })) } + async fn pause_session( + &self, + req: Request, + ) -> Result, Status> { + self.auth.check(&req)?; + let id = parse_session_id(&req.get_ref().session_id)?; + let result = crate::api::admin::pause_session_core(&self.state, id) + .await + .map_err(into_status)?; + Ok(Response::new(app::PauseSessionResponse { + session_id: result.session_id.to_string(), + note: result.note.to_string(), + })) + } + + async fn resume_session( + &self, + req: Request, + ) -> Result, Status> { + self.auth.check(&req)?; + let id = parse_session_id(&req.get_ref().session_id)?; + let result = crate::api::admin::resume_session_core(&self.state, id) + .await + .map_err(into_status)?; + Ok(Response::new(app::ResumeSessionResponse { + session_id: result.session_id.to_string(), + note: result.note.to_string(), + })) + } + async fn evict_local( &self, req: Request, diff --git a/crates/engram-coordinator/tests/grpc_app.rs b/crates/engram-coordinator/tests/grpc_app.rs index 8906fef63..5fa4ac19e 100644 --- a/crates/engram-coordinator/tests/grpc_app.rs +++ b/crates/engram-coordinator/tests/grpc_app.rs @@ -1340,3 +1340,156 @@ async fn session_stream_events_replays_past_one_page() { server.abort(); } + +#[tokio::test] +async fn admin_pause_resume_preserves_state_and_error_mapping() { + let (state, meta) = test_state(vec![TEST_TOKEN.into()]); + let service = grpc_app::AppSessionService { + state: state.clone(), + auth: Arc::new(grpc_app::auth::BearerAuth::new(vec![TEST_TOKEN.into()])), + }; + let sid = meta + .create_session(SessionSpec { + image: "test-image".into(), + mode: Default::default(), + }) + .await + .unwrap(); + + async fn invoke( + service: &grpc_app::AppSessionService, + pause: bool, + id: &str, + token: Option<&str>, + ) -> Result<(String, String), tonic::Status> { + let mut metadata = tonic::metadata::MetadataMap::new(); + if let Some(token) = token { + metadata.insert("authorization", format!("Bearer {token}").parse().unwrap()); + } + if pause { + let mut req = tonic::Request::new(app::PauseSessionRequest { + session_id: id.into(), + }); + *req.metadata_mut() = metadata; + let result = service.pause_session(req).await?.into_inner(); + Ok((result.session_id, result.note)) + } else { + let mut req = tonic::Request::new(app::ResumeSessionRequest { + session_id: id.into(), + }); + *req.metadata_mut() = metadata; + let result = service.resume_session(req).await?.into_inner(); + Ok((result.session_id, result.note)) + } + } + + for pause in [true, false] { + for token in [None, Some("wrong")] { + assert_eq!( + invoke(&service, pause, "invalid", token) + .await + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + } + assert_eq!( + invoke(&service, pause, "bad/id?query", Some(TEST_TOKEN)) + .await + .unwrap_err() + .code(), + tonic::Code::InvalidArgument + ); + for id in [sid, SessionId::new()] { + let error = invoke(&service, pause, &id.to_string(), Some(TEST_TOKEN)) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert_eq!( + error.metadata().get("engram-error-slug").unwrap(), + "conflict" + ); + } + } + + use engram_core::types::sandbox::{CpuLimit, DiskLimit, MemoryLimit, SandboxSpec}; + let sandbox = state + .services + .host + .create(SandboxSpec { + image: "test-image".into(), + rootfs_source: None, + image_uri: None, + rootfs_manifest: None, + cpu: CpuLimit { vcpus: 1 }, + memory: MemoryLimit { max_mib: 256 }, + disk: DiskLimit { max_gib: 1 }, + ttl: None, + env: HashMap::new(), + workdir: None, + network: Default::default(), + aux_ro_drives: Vec::new(), + swap_mib: None, + swap_source: None, + swap_manifest: None, + }) + .await + .unwrap(); + meta.rebind_session(sid, engram_core::HostId::new(), sandbox) + .await + .unwrap(); + for target in [SessionState::Created, SessionState::Active] { + meta.transition_session(sid, target, BindingDisposition::Retain) + .await + .unwrap(); + } + let before = meta.get_session(sid).await.unwrap(); + for (pause, note) in [(true, "paused"), (false, "resumed")] { + let response = invoke(&service, pause, &sid.to_string(), Some(TEST_TOKEN)) + .await + .unwrap(); + assert_eq!(response, (sid.to_string(), note.into())); + use tower::ServiceExt as _; + let operation = if pause { "pause" } else { "resume" }; + let http = engram_coordinator::api::router(state.clone()) + .oneshot( + axum::http::Request::builder() + .method("POST") + .uri(format!("/api/v1/admin/sessions/{sid}/{operation}")) + .body(axum::body::Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(http.status(), axum::http::StatusCode::OK); + let body = axum::body::to_bytes(http.into_body(), 4096).await.unwrap(); + assert_eq!( + serde_json::from_slice::(&body).unwrap(), + serde_json::json!({"session_id": sid.to_string(), "note": note}) + ); + let after = meta.get_session(sid).await.unwrap(); + assert_eq!(after.status, before.status); + assert_eq!(after.sandbox_id, before.sandbox_id); + assert_eq!(after.last_active_at, before.last_active_at); + assert_eq!(after.park_rung, before.park_rung); + } + + // A stale binding reaches the host and retains the HTTP core's Internal error. + meta.rebind_session( + sid, + engram_core::HostId::new(), + engram_core::SandboxId::new(), + ) + .await + .unwrap(); + for pause in [true, false] { + let error = invoke(&service, pause, &sid.to_string(), Some(TEST_TOKEN)) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::Internal); + assert_eq!( + error.metadata().get("engram-error-slug").unwrap(), + "internal" + ); + } +} diff --git a/crates/engram-host-core/Cargo.toml b/crates/engram-host-core/Cargo.toml index 1d123ed72..e96f6f23d 100644 --- a/crates/engram-host-core/Cargo.toml +++ b/crates/engram-host-core/Cargo.toml @@ -27,6 +27,7 @@ chrono.workspace = true engram-chunk-store.workspace = true engram-fill.workspace = true engram-core.workspace = true +engram-protocol.workspace = true libc = "0.2" serde.workspace = true tokio.workspace = true diff --git a/crates/engram-host-core/src/shutdown.rs b/crates/engram-host-core/src/shutdown.rs index 850f04556..39e1bc57f 100644 --- a/crates/engram-host-core/src/shutdown.rs +++ b/crates/engram-host-core/src/shutdown.rs @@ -24,26 +24,7 @@ pub fn capture_drain_budget(env_value: Option) -> Duration { Duration::from_secs_f64(secs) } -/// ADR 0116 A-D2: the durable note a shutting-down host-agent leaves in -/// its bindings directory for the successor generation — proof this was -/// a PLANNED exit with a declared lease deadline. The successor adopts -/// it (read + delete) and reports it on register; the coordinator uses -/// it for observability only (register renews the lease regardless). -/// Written FIRST in the SIGTERM ladder, before the heartbeat task is -/// aborted, so the belt POST and the durable note both precede any -/// silence the coordinator could observe. -#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -pub struct HandoffMarker { - /// Predecessor wall clock at declaration (unix ms). Same-node clock; - /// adoption latency derived from it is a histogram input, never a - /// decision. - pub declared_at_unix_ms: i64, - /// TTL the predecessor requested for its handoff window. - pub ttl_secs: u64, - /// Sandboxes resident at declaration (diagnostics). - #[serde(default)] - pub resident_sandboxes: u32, -} +pub use engram_protocol::HandoffMarker; /// File name of the handoff marker inside the bindings directory. pub const HANDOFF_MARKER_FILE: &str = "handoff.json"; diff --git a/crates/engram-protocol/proto/engram/app/v1/session.proto b/crates/engram-protocol/proto/engram/app/v1/session.proto index 7b964e6ef..4ba85143c 100644 --- a/crates/engram-protocol/proto/engram/app/v1/session.proto +++ b/crates/engram-protocol/proto/engram/app/v1/session.proto @@ -55,6 +55,10 @@ service SessionService { // (ADR 0066), exactly as EnsureBrowser does for VNC. rpc EnsureIde(EnsureIdeRequest) returns (EnsureIdeResponse); rpc Resume(ResumeRequest) returns (ResumeResponse); + // Admin-only: freeze the guest in place without changing session state. + rpc PauseSession(PauseSessionRequest) returns (PauseSessionResponse); + // Admin-only: unfreeze in place. Use Resume to rehydrate an idle session. + rpc ResumeSession(ResumeSessionRequest) returns (ResumeSessionResponse); rpc EvictLocal(EvictLocalRequest) returns (EvictLocalResponse); // ADR 0051: the explicit admin trigger for the idle-eviction primitive // (was POST /api/admin/sessions/:id/evict-idle). Fires the SAME pipeline @@ -741,3 +745,18 @@ message PortOpen { // Clean teardown sentinel (see ProxyPortClose in host_service.proto). message PortClose {} + +message PauseSessionRequest { + string session_id = 1; +} +message PauseSessionResponse { + string session_id = 1; + string note = 2; +} +message ResumeSessionRequest { + string session_id = 1; +} +message ResumeSessionResponse { + string session_id = 1; + string note = 2; +} diff --git a/crates/engram-protocol/src/app.rs b/crates/engram-protocol/src/app.rs index 836cb4f36..928647442 100644 --- a/crates/engram-protocol/src/app.rs +++ b/crates/engram-protocol/src/app.rs @@ -26,3 +26,22 @@ tonic::include_proto!("engram.app.v1"); /// only — exposes no data. pub const FILE_DESCRIPTOR_SET: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/engram_app_descriptor.bin")); + +#[cfg(test)] +mod tests { + use super::{ + PauseSessionRequest, PauseSessionResponse, ResumeSessionRequest, ResumeSessionResponse, + }; + use proptest::prelude::*; + use prost::Message; + + proptest! { + #[test] + fn pause_resume_decode_never_panics(bytes in proptest::collection::vec(any::(), 0..4096)) { + let _ = PauseSessionRequest::decode(bytes.as_slice()); + let _ = PauseSessionResponse::decode(bytes.as_slice()); + let _ = ResumeSessionRequest::decode(bytes.as_slice()); + let _ = ResumeSessionResponse::decode(bytes.as_slice()); + } + } +} diff --git a/crates/engram-protocol/src/handoff.rs b/crates/engram-protocol/src/handoff.rs new file mode 100644 index 000000000..bb6ac5178 --- /dev/null +++ b/crates/engram-protocol/src/handoff.rs @@ -0,0 +1,35 @@ +//! Durable host handoff marker, also sent to the coordinator on registration. + +/// A planned exit declaration adopted by the next host-agent process. +/// The coordinator uses it for observability; registration renews the lease. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct HandoffMarker { + /// Predecessor wall clock at declaration (unix ms). Same-node clock; + /// adoption latency derived from it is a histogram input, never a + /// decision. + pub declared_at_unix_ms: i64, + /// TTL the predecessor requested for its handoff window. + pub ttl_secs: u64, + /// Sandboxes resident at declaration (diagnostics). + #[serde(default)] + pub resident_sandboxes: u32, +} + +#[cfg(test)] +mod tests { + use super::HandoffMarker; + + #[test] + fn wire_and_disk_shape_stays_compatible() { + let json = r#"{"declared_at_unix_ms":1765432100000,"ttl_secs":600,"resident_sandboxes":4}"#; + let marker: HandoffMarker = serde_json::from_str(json).unwrap(); + assert_eq!(marker.declared_at_unix_ms, 1_765_432_100_000); + assert_eq!(marker.ttl_secs, 600); + assert_eq!(marker.resident_sandboxes, 4); + assert_eq!(serde_json::to_string(&marker).unwrap(), json); + let legacy: HandoffMarker = + serde_json::from_str(r#"{"declared_at_unix_ms":1,"ttl_secs":2,"future_field":true}"#) + .unwrap(); + assert_eq!(legacy.resident_sandboxes, 0); + } +} diff --git a/crates/engram-protocol/src/lib.rs b/crates/engram-protocol/src/lib.rs index d9141da09..d093e34af 100644 --- a/crates/engram-protocol/src/lib.rs +++ b/crates/engram-protocol/src/lib.rs @@ -18,8 +18,10 @@ pub mod app; pub mod grpc; pub mod grpc_client; pub mod grpc_pool; +mod handoff; pub mod heartbeat; pub mod wire; +pub use handoff::HandoffMarker; pub use heartbeat::*; pub use wire::{WireExecRequest, REATTACH_GENERATION, WIRE_VERSION}; diff --git a/orchestrator/src/__tests__/admin-routes.test.ts b/orchestrator/src/__tests__/admin-routes.test.ts new file mode 100644 index 000000000..30ca77f65 --- /dev/null +++ b/orchestrator/src/__tests__/admin-routes.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, test } from "bun:test"; +import { Code, ConnectError, createClient, createRouterTransport } from "@connectrpc/connect"; +import { makeAdminRoute } from "../routes/admin.ts"; +import { registerPassthrough } from "../rpc/passthrough.ts"; +import { SURFACE } from "../rpc/surface.ts"; +import { SessionService } from "../gen/engram/app/v1/session_pb.ts"; + +for (const operation of ["pause", "resume"] as const) { + describe(`admin ${operation}`, () => { + function fixture(role: string | null, failure?: ConnectError) { + const calls: Array<{ method: string; sessionId: string }> = []; + const app = makeAdminRoute({ + getSession: async () => role === null ? null : { user: { id: "u1", role } }, + sessions: { + pauseSession: async ({ sessionId }) => { + calls.push({ method: "pause", sessionId }); + if (failure) throw failure; + return { sessionId, note: "paused" }; + }, + resumeSession: async ({ sessionId }) => { + calls.push({ method: "resume", sessionId }); + if (failure) throw failure; + return { sessionId, note: "resumed" }; + }, + }, + }); + return { + calls, + request: (id = "s1") => app.request(`/api/v1/admin/sessions/${id}/${operation}`, { + method: "POST", + }), + }; + } + + for (const [role, status] of [[null, 401], ["user", 403]] as const) { + test(`rejects ${role ?? "anonymous"} before calling upstream`, async () => { + const f = fixture(role); + expect((await f.request()).status).toBe(status); + expect(f.calls).toEqual([]); + }); + } + + test("uses the in-place RPC and preserves the browser JSON shape", async () => { + const f = fixture("admin"); + const response = await f.request(); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + session_id: "s1", + note: operation === "pause" ? "paused" : "resumed", + }); + expect(f.calls).toEqual([{ method: operation, sessionId: "s1" }]); + }); + + test("passes encoded input as data", async () => { + const f = fixture("admin", new ConnectError("invalid session_id", Code.InvalidArgument)); + expect((await f.request("bad%2Fid%3Fquery")).status).toBe(400); + expect(f.calls).toEqual([{ method: operation, sessionId: "bad/id?query" }]); + }); + + for (const [code, status, slug] of [ + [Code.InvalidArgument, 400, "bad_request"], + [Code.FailedPrecondition, 409, "conflict"], + [Code.Internal, 500, "internal"], + [Code.Unavailable, 503, "unavailable"], + [Code.Unimplemented, 501, "unsupported"], + ] as const) { + test(`maps ${Code[code]} to HTTP ${status}`, async () => { + const f = fixture("admin", new ConnectError("failure", code)); + const response = await f.request(); + expect(response.status).toBe(status); + expect(await response.json()).toEqual({ error: slug, message: "failure" }); + expect(f.calls).toHaveLength(1); + }); + } + }); +} + +for (const method of ["pauseSession", "resumeSession"] as const) { + for (const role of [null, "user", "admin"] as const) { + test(`direct ${method} RPC gate for ${role ?? "anonymous"}`, async () => { + const calls: string[] = []; + const upstream = createRouterTransport((router) => { + router.service(SessionService, { + pauseSession: ({ sessionId }) => { + calls.push("pauseSession"); + return { sessionId, note: "paused" }; + }, + resumeSession: ({ sessionId }) => { + calls.push("resumeSession"); + return { sessionId, note: "resumed" }; + }, + }); + }); + const transport = createRouterTransport((router) => { + registerPassthrough(router, SURFACE, upstream, + async () => role === null ? null : { user: { id: "u1", role } }, + async () => "u1"); + }); + const client = createClient(SessionService, transport); + if (role === "admin") { + const result = await client[method]({ sessionId: "s1" }); + expect(result.sessionId).toBe("s1"); + expect(result.note).toBe(method === "pauseSession" ? "paused" : "resumed"); + expect(calls).toEqual([method]); + } else { + await expect(client[method]({ sessionId: "s1" })).rejects.toMatchObject({ + code: role === null ? Code.Unauthenticated : Code.PermissionDenied, + }); + expect(calls).toEqual([]); + } + }); + } +} diff --git a/orchestrator/src/authz/policy-map.ts b/orchestrator/src/authz/policy-map.ts index 858345208..460ef0b34 100644 --- a/orchestrator/src/authz/policy-map.ts +++ b/orchestrator/src/authz/policy-map.ts @@ -139,6 +139,8 @@ export const POLICY: Record = { sessionIdField: "sessionId", }, // Admin-only SessionService methods + "SessionService.PauseSession": { action: "manage", subject: "all" }, + "SessionService.ResumeSession": { action: "manage", subject: "all" }, "SessionService.Snapshot": { action: "manage", subject: "all" }, "SessionService.EvictLocal": { action: "manage", subject: "all" }, "SessionService.EvictIdle": { action: "manage", subject: "all" }, // explicit idle-evict trigger (ADR 0051) diff --git a/orchestrator/src/config.ts b/orchestrator/src/config.ts index b9d549870..91044e262 100644 --- a/orchestrator/src/config.ts +++ b/orchestrator/src/config.ts @@ -30,10 +30,6 @@ export interface Config { databaseUrl: string; /** CONTROL_PLANE_GRPC_URL — default http://127.0.0.1:50061 */ controlPlaneGrpcUrl: string; - /** CONTROL_PLANE_HTTP_URL — coordinator REST base URL. Used by admin REST - * proxy routes (pause/resume session) that have no gRPC equivalent yet. - * Default: http://127.0.0.1:8090 (coordinator HTTP port in dev). */ - controlPlaneHttpUrl: string; /** CONTROL_PLANE_BEARER — required: the coordinator app-gRPC bearer token */ controlPlaneBearer: string; /** @@ -395,7 +391,6 @@ export function loadConfig(env: Record = process.env const connectionBrokerBearer = optional("CONNECTION_BROKER_BEARER", controlPlaneBearer); const githubAppLogin = optional("GITHUB_APP_LOGIN", ""); const controlPlaneGrpcUrl = optional("CONTROL_PLANE_GRPC_URL", "http://127.0.0.1:50061"); - const controlPlaneHttpUrl = optional("CONTROL_PLANE_HTTP_URL", "http://127.0.0.1:8090"); const databaseUrl = require("ORCHESTRATOR_DATABASE_URL"); const trustedOriginsRaw = optional("TRUSTED_ORIGINS", "http://localhost:5173"); const trustedOrigins = trustedOriginsRaw @@ -597,7 +592,6 @@ export function loadConfig(env: Record = process.env baseUrl, databaseUrl, controlPlaneGrpcUrl, - controlPlaneHttpUrl, controlPlaneBearer, connectionBrokerBearer, deploymentId, diff --git a/orchestrator/src/gen/engram/app/v1/session_pb.ts b/orchestrator/src/gen/engram/app/v1/session_pb.ts index b5b3a07b1..850f826d0 100644 --- a/orchestrator/src/gen/engram/app/v1/session_pb.ts +++ b/orchestrator/src/gen/engram/app/v1/session_pb.ts @@ -12,7 +12,7 @@ import type { Message } from "@bufbuild/protobuf"; * Describes the file engram/app/v1/session.proto. */ export const file_engram_app_v1_session: GenFile = /*@__PURE__*/ - fileDesc("ChtlbmdyYW0vYXBwL3YxL3Nlc3Npb24ucHJvdG8SDWVuZ3JhbS5hcHAudjEiFQoTTGlzdFNlc3Npb25zUmVxdWVzdCJIChRMaXN0U2Vzc2lvbnNSZXNwb25zZRIwCghzZXNzaW9ucxgBIAMoCzIeLmVuZ3JhbS5hcHAudjEuU2Vzc2lvbkxpc3RJdGVtIrQBCg9TZXNzaW9uTGlzdEl0ZW0SJwoHc2Vzc2lvbhgBIAEoCzIWLmVuZ3JhbS5hcHAudjEuU2Vzc2lvb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wcC52MS5SZWxheVBvcnRSZXNwb25zZSgBMAFiBnByb3RvMw", [file_engram_app_v1_oauth]); /** * @generated from message engram.app.v1.ListSessionsRequest @@ -2256,6 +2256,84 @@ export type PortClose = Message<"engram.app.v1.PortClose"> & { export const PortCloseSchema: GenMessage = /*@__PURE__*/ messageDesc(file_engram_app_v1_session, 72); +/** + * @generated from message engram.app.v1.PauseSessionRequest + */ +export type PauseSessionRequest = Message<"engram.app.v1.PauseSessionRequest"> & { + /** + * @generated from field: string session_id = 1; + */ + sessionId: string; +}; + +/** + * Describes the message engram.app.v1.PauseSessionRequest. + * Use `create(PauseSessionRequestSchema)` to create a new message. + */ +export const PauseSessionRequestSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_engram_app_v1_session, 73); + +/** + * @generated from message engram.app.v1.PauseSessionResponse + */ +export type PauseSessionResponse = Message<"engram.app.v1.PauseSessionResponse"> & { + /** + * @generated from field: string session_id = 1; + */ + sessionId: string; + + /** + * @generated from field: string note = 2; + */ + note: string; +}; + +/** + * Describes the message engram.app.v1.PauseSessionResponse. + * Use `create(PauseSessionResponseSchema)` to create a new message. + */ +export const PauseSessionResponseSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_engram_app_v1_session, 74); + +/** + * @generated from message engram.app.v1.ResumeSessionRequest + */ +export type ResumeSessionRequest = Message<"engram.app.v1.ResumeSessionRequest"> & { + /** + * @generated from field: string session_id = 1; + */ + sessionId: string; +}; + +/** + * Describes the message engram.app.v1.ResumeSessionRequest. + * Use `create(ResumeSessionRequestSchema)` to create a new message. + */ +export const ResumeSessionRequestSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_engram_app_v1_session, 75); + +/** + * @generated from message engram.app.v1.ResumeSessionResponse + */ +export type ResumeSessionResponse = Message<"engram.app.v1.ResumeSessionResponse"> & { + /** + * @generated from field: string session_id = 1; + */ + sessionId: string; + + /** + * @generated from field: string note = 2; + */ + note: string; +}; + +/** + * Describes the message engram.app.v1.ResumeSessionResponse. + * Use `create(ResumeSessionResponseSchema)` to create a new message. + */ +export const ResumeSessionResponseSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_engram_app_v1_session, 76); + /** * The orchestrator-facing app contract (ADR 0051 §2.3, rev 2026-06-10). * The caller is a single trusted service (bearer-authed); there is no @@ -2467,6 +2545,26 @@ export const SessionService: GenService<{ input: typeof ResumeRequestSchema; output: typeof ResumeResponseSchema; }, + /** + * Admin-only: freeze the guest in place without changing session state. + * + * @generated from rpc engram.app.v1.SessionService.PauseSession + */ + pauseSession: { + methodKind: "unary"; + input: typeof PauseSessionRequestSchema; + output: typeof PauseSessionResponseSchema; + }, + /** + * Admin-only: unfreeze in place. Use Resume to rehydrate an idle session. + * + * @generated from rpc engram.app.v1.SessionService.ResumeSession + */ + resumeSession: { + methodKind: "unary"; + input: typeof ResumeSessionRequestSchema; + output: typeof ResumeSessionResponseSchema; + }, /** * @generated from rpc engram.app.v1.SessionService.EvictLocal */ diff --git a/orchestrator/src/routes/admin.ts b/orchestrator/src/routes/admin.ts index 33cea20d6..964ed93bf 100644 --- a/orchestrator/src/routes/admin.ts +++ b/orchestrator/src/routes/admin.ts @@ -1,54 +1,30 @@ -/** - * Admin REST proxy routes — thin forwarding of admin-only session operations - * that have no gRPC equivalent in the current proto. - * - * ADR 0051 Task 28: When the Vite proxy flips all /api browser traffic to - * the orchestrator, these coordinator-only admin REST routes would 404. This - * module adds orchestrator-side stubs that: - * 1. Authenticate via the browser session cookie (better-auth). - * 2. Assert admin role (CASL 'manage all'). - * 3. Forward the request to the coordinator REST API with the service - * bearer token (CONTROL_PLANE_BEARER). - * - * Routes: - * POST /api/v1/admin/sessions/:id/pause → coordinator pause (VM freeze) - * POST /api/v1/admin/sessions/:id/resume → coordinator resume (VM unfreeze) - * - * These are kept as REST proxies rather than gRPC calls because PauseSession / - * ResumeSession (in-place VM freeze/unfreeze — distinct from the - * SessionService.Resume idle-rehydrate) have no proto methods yet. When they - * are promoted to gRPC in a future task, delete these routes and migrate the - * hooks to connect-query. - * - * Note: teleportSession uses FleetService.TeleportSession (gRPC, already - * passing through the CASL gate) — no proxy route needed for it. - * - * Production auth note (ADR 0051 Task 32): The forwarded bearer is - * CONTROL_PLANE_BEARER. In production, ENGRAM_AUTH_TOKENS on the coordinator - * must include this bearer so the coordinator's REST chain accepts the - * orchestrator's forwarded requests for /pause and /resume. Ensure both - * tokens agree at deploy time. - * - * TODO: promote pause/resume to gRPC (PauseSession/ResumeSession RPCs) and - * delete this file. Until then, these two routes remain as REST proxies. - */ +/** Admin HTTP routes backed by the app-gRPC in-place pause/resume methods. */ +import { Code, ConnectError } from "@connectrpc/connect"; import { Hono } from "hono"; import { HTTPException } from "hono/http-exception"; import { getSessionFromHeaders } from "../auth/session.ts"; import { abilityFor } from "../authz/ability.ts"; -import { config } from "../config.ts"; +import { sessions } from "../control-plane/client.ts"; +import type { GetSession } from "./guard.ts"; + +type PauseResume = (request: { sessionId: string }) => Promise<{ + sessionId: string; + note: string; +}>; export function makeAdminRoute( - deps: { httpUrl?: string; bearer?: string } = {}, + deps: { + sessions?: { pauseSession: PauseResume; resumeSession: PauseResume }; + getSession?: GetSession; + } = {}, ): Hono { const app = new Hono(); - const httpBase = (deps.httpUrl ?? config.controlPlaneHttpUrl).replace(/\/$/, ""); - const bearer = deps.bearer ?? config.controlPlaneBearer; + const client = deps.sessions ?? sessions; + const getSession = deps.getSession ?? getSessionFromHeaders; - /** Require admin; throws HTTPException(401/403) otherwise. */ async function requireAdmin(headers: Headers): Promise { - const session = await getSessionFromHeaders(headers); + const session = await getSession(headers); if (!session) { throw new HTTPException(401, { message: "unauthenticated" }); } @@ -61,47 +37,41 @@ export function makeAdminRoute( } } - /** Forward a POST to the coordinator REST API. */ - async function forwardPost( - path: string, - body: unknown, - ): Promise { - const res = await fetch(`${httpBase}${path}`, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${bearer}`, - }, - body: JSON.stringify(body), - }); - return res; + // Preserve the browser's HTTP response shape while using app-gRPC upstream. + async function invoke(call: () => ReturnType): Promise { + try { + const result = await call(); + return Response.json({ session_id: result.sessionId, note: result.note }); + } catch (error) { + if (!(error instanceof ConnectError)) throw error; + const [status, slug] = (() => { + switch (error.code) { + case Code.InvalidArgument: return [400, "bad_request"] as const; + case Code.Unauthenticated: return [401, "unauthorized"] as const; + case Code.PermissionDenied: return [403, "forbidden"] as const; + case Code.NotFound: return [404, "not_found"] as const; + case Code.FailedPrecondition: return [409, "conflict"] as const; + case Code.Unimplemented: return [501, "unsupported"] as const; + case Code.Unavailable: return [503, "unavailable"] as const; + default: return [500, "internal"] as const; + } + })(); + return Response.json({ + error: error.metadata.get("engram-error-slug") ?? slug, + message: error.rawMessage, + }, { status }); + } } - // POST /api/v1/admin/sessions/:id/pause — freeze the session's microVM in place. - // Admin-only. The session stays `active`; the guest vCPUs stop until resumed. app.post("/api/v1/admin/sessions/:id/pause", async (c) => { await requireAdmin(c.req.raw.headers); - const id = c.req.param("id"); - const upstream = await forwardPost(`/api/v1/admin/sessions/${encodeURIComponent(id)}/pause`, {}); - const body = upstream.status === 204 ? null : await upstream.text(); - return new Response(body, { - status: upstream.status, - headers: { "Content-Type": "application/json" }, - }); + return invoke(() => client.pauseSession({ sessionId: c.req.param("id") })); }); - // POST /api/v1/admin/sessions/:id/resume — unfreeze the session's microVM. - // Admin-only. Counterpart to /pause; the in-place unfreeze, NOT the - // idle-rehydrate at /sessions/:id/resume (which is SessionService.Resume). + // ResumeSession unfreezes in place; Resume rehydrates an idle session. app.post("/api/v1/admin/sessions/:id/resume", async (c) => { await requireAdmin(c.req.raw.headers); - const id = c.req.param("id"); - const upstream = await forwardPost(`/api/v1/admin/sessions/${encodeURIComponent(id)}/resume`, {}); - const body = upstream.status === 204 ? null : await upstream.text(); - return new Response(body, { - status: upstream.status, - headers: { "Content-Type": "application/json" }, - }); + return invoke(() => client.resumeSession({ sessionId: c.req.param("id") })); }); return app; diff --git a/web/src/gen/engram/app/v1/session-SessionService_connectquery.ts b/web/src/gen/engram/app/v1/session-SessionService_connectquery.ts index 2a9bf465e..ff54a698d 100644 --- a/web/src/gen/engram/app/v1/session-SessionService_connectquery.ts +++ b/web/src/gen/engram/app/v1/session-SessionService_connectquery.ts @@ -114,6 +114,20 @@ export const ensureIde = SessionService.method.ensureIde; */ export const resume = SessionService.method.resume; +/** + * Admin-only: freeze the guest in place without changing session state. + * + * @generated from rpc engram.app.v1.SessionService.PauseSession + */ +export const pauseSession = SessionService.method.pauseSession; + +/** + * Admin-only: unfreeze in place. Use Resume to rehydrate an idle session. + * + * @generated from rpc engram.app.v1.SessionService.ResumeSession + */ +export const resumeSession = SessionService.method.resumeSession; + /** * @generated from rpc engram.app.v1.SessionService.EvictLocal */ diff --git a/web/src/gen/engram/app/v1/session_pb.ts b/web/src/gen/engram/app/v1/session_pb.ts index b5b3a07b1..850f826d0 100644 --- a/web/src/gen/engram/app/v1/session_pb.ts +++ b/web/src/gen/engram/app/v1/session_pb.ts @@ -12,7 +12,7 @@ import type { Message } from "@bufbuild/protobuf"; * Describes the file engram/app/v1/session.proto. */ export const file_engram_app_v1_session: GenFile = /*@__PURE__*/ - fileDesc("ChtlbmdyYW0vYXBwL3YxL3Nlc3Npb24ucHJvdG8SDWVuZ3JhbS5hcHAudjEiFQoTTGlzdFNlc3Npb25zUmVxdWVzdCJIChRMaXN0U2Vzc2lvbnNSZXNwb25zZRIwCghzZXNzaW9ucxgBIAMoCzIeLmVuZ3JhbS5hcHAudjEuU2Vzc2lvbkxpc3RJdGVtIrQBCg9TZXNzaW9uTGlzdEl0ZW0SJwoHc2Vzc2lvbhgBIAEoCzIWLmVuZ3JhbS5hcHAudjEuU2Vzc2lvbhIYCgtvd25lcl9lbWFpbBgCIAEoCUgAiAEBEhcKCm93bmVyX25hbWUYAyABKAlIAYgBARIXCgpvd25lcl9raW5kGAQgASgJSAKIAQFCDgoMX293bmVyX2VtYWlsQg0KC19vd25lcl9uYW1lQg0KC19vd25lcl9raW5kIpgCCgdTZXNzaW9uEgoK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W1lU2Vzc2lvblJlc3BvbnNlElEKCkV2aWN0TG9jYWwSIC5lbmdyYW0uYXBwLnYxLkV2aWN0TG9jYWxSZXF1ZXN0GiEuZW5ncmFtLmFwcC52MS5FdmljdExvY2FsUmVzcG9uc2USTgoJRXZpY3RJZGxlEh8uZW5ncmFtLmFwcC52MS5FdmljdElkbGVSZXF1ZXN0GiAuZW5ncmFtLmFwcC52MS5FdmljdElkbGVSZXNwb25zZRJgCg9MaXN0Q2hlY2twb2ludHMSJS5lbmdyYW0uYXBwLnYxLkxpc3RDaGVja3BvaW50c1JlcXVlc3QaJi5lbmdyYW0uYXBwLnYxLkxpc3RDaGVja3BvaW50c1Jlc3BvbnNlElYKC0dldEFydGlmYWN0EiEuZW5ncmFtLmFwcC52MS5HZXRBcnRpZmFjdFJlcXVlc3QaIi5lbmdyYW0uYXBwLnYxLkdldEFydGlmYWN0UmVzcG9uc2UwARJ1ChZDcmVhdGVBcnRpZmFjdEZyb21QYXRoEiwuZW5ncmFtLmFwcC52MS5DcmVhdGVBcnRpZmFjdEZyb21QYXRoUmVxdWVzdBotLmVuZ3JhbS5hcHAudjEuQ3JlYXRlQXJ0aWZhY3RGcm9tUGF0aFJlc3BvbnNlMmUKEVNoZWxsUmVsYXlTZXJ2aWNlElAKBVJlbGF5EiAuZW5ncmFtLmFwcC52MS5SZWxheVNoZWxsUmVxdWVzdBohLmVuZ3JhbS5hcHAudjEuUmVsYXlTaGVsbFJlc3BvbnNlKAEwATJiChBQb3J0UmVsYXlTZXJ2aWNlEk4KBVJlbGF5Eh8uZW5ncmFtLmFwcC52MS5SZWxheVBvcnRSZXF1ZXN0GiAuZW5ncmFtLmFwcC52MS5SZWxheVBvcnRSZXNwb25zZSgBMAFiBnByb3RvMw", [file_engram_app_v1_oauth]); /** * @generated from message engram.app.v1.ListSessionsRequest @@ -2256,6 +2256,84 @@ export type PortClose = Message<"engram.app.v1.PortClose"> & { export const PortCloseSchema: GenMessage = /*@__PURE__*/ messageDesc(file_engram_app_v1_session, 72); +/** + * @generated from message engram.app.v1.PauseSessionRequest + */ +export type PauseSessionRequest = Message<"engram.app.v1.PauseSessionRequest"> & { + /** + * @generated from field: string session_id = 1; + */ + sessionId: string; +}; + +/** + * Describes the message engram.app.v1.PauseSessionRequest. + * Use `create(PauseSessionRequestSchema)` to create a new message. + */ +export const PauseSessionRequestSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_engram_app_v1_session, 73); + +/** + * @generated from message engram.app.v1.PauseSessionResponse + */ +export type PauseSessionResponse = Message<"engram.app.v1.PauseSessionResponse"> & { + /** + * @generated from field: string session_id = 1; + */ + sessionId: string; + + /** + * @generated from field: string note = 2; + */ + note: string; +}; + +/** + * Describes the message engram.app.v1.PauseSessionResponse. + * Use `create(PauseSessionResponseSchema)` to create a new message. + */ +export const PauseSessionResponseSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_engram_app_v1_session, 74); + +/** + * @generated from message engram.app.v1.ResumeSessionRequest + */ +export type ResumeSessionRequest = Message<"engram.app.v1.ResumeSessionRequest"> & { + /** + * @generated from field: string session_id = 1; + */ + sessionId: string; +}; + +/** + * Describes the message engram.app.v1.ResumeSessionRequest. + * Use `create(ResumeSessionRequestSchema)` to create a new message. + */ +export const ResumeSessionRequestSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_engram_app_v1_session, 75); + +/** + * @generated from message engram.app.v1.ResumeSessionResponse + */ +export type ResumeSessionResponse = Message<"engram.app.v1.ResumeSessionResponse"> & { + /** + * @generated from field: string session_id = 1; + */ + sessionId: string; + + /** + * @generated from field: string note = 2; + */ + note: string; +}; + +/** + * Describes the message engram.app.v1.ResumeSessionResponse. + * Use `create(ResumeSessionResponseSchema)` to create a new message. + */ +export const ResumeSessionResponseSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_engram_app_v1_session, 76); + /** * The orchestrator-facing app contract (ADR 0051 §2.3, rev 2026-06-10). * The caller is a single trusted service (bearer-authed); there is no @@ -2467,6 +2545,26 @@ export const SessionService: GenService<{ input: typeof ResumeRequestSchema; output: typeof ResumeResponseSchema; }, + /** + * Admin-only: freeze the guest in place without changing session state. + * + * @generated from rpc engram.app.v1.SessionService.PauseSession + */ + pauseSession: { + methodKind: "unary"; + input: typeof PauseSessionRequestSchema; + output: typeof PauseSessionResponseSchema; + }, + /** + * Admin-only: unfreeze in place. Use Resume to rehydrate an idle session. + * + * @generated from rpc engram.app.v1.SessionService.ResumeSession + */ + resumeSession: { + methodKind: "unary"; + input: typeof ResumeSessionRequestSchema; + output: typeof ResumeSessionResponseSchema; + }, /** * @generated from rpc engram.app.v1.SessionService.EvictLocal */ From d150d1f1ddb251fc7e5ea7eea49e156a38bb318b Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:00:20 -0800 Subject: [PATCH 02/17] orchestrator: keep admin pause/resume on the coordinator REST path The chart rolls the coordinator and the orchestrator at the same time. An orchestrator that calls PauseSession or ResumeSession on a coordinator without those methods gets Unimplemented. This PR now ships only the coordinator methods, the generated clients, and the admin-only policy entries. The orchestrator route cutover moves to a follow-up that merges after this change is deployed. Restore admin.ts and config.ts to the REST proxy, keep the direct-RPC policy gate test, and make the coordinator comments state the current callers of the HTTP routes. Co-Authored-By: Claude Opus 5.5 --- crates/engram-coordinator/src/api/admin.rs | 5 +- crates/engram-coordinator/src/api/mod.rs | 8 +- .../src/__tests__/admin-routes.test.ts | 113 ------------------ .../src/__tests__/pause-resume-policy.test.ts | 43 +++++++ orchestrator/src/config.ts | 6 + orchestrator/src/routes/admin.ts | 89 +++++++------- 6 files changed, 101 insertions(+), 163 deletions(-) delete mode 100644 orchestrator/src/__tests__/admin-routes.test.ts create mode 100644 orchestrator/src/__tests__/pause-resume-policy.test.ts diff --git a/crates/engram-coordinator/src/api/admin.rs b/crates/engram-coordinator/src/api/admin.rs index 1aeb10fdd..799cacbd4 100644 --- a/crates/engram-coordinator/src/api/admin.rs +++ b/crates/engram-coordinator/src/api/admin.rs @@ -64,9 +64,8 @@ pub(crate) async fn evict_idle_core( } // Pause and resume freeze or unfreeze the guest in place. Session state does not change. -// Keep the HTTP adapters until all orchestrators use app-gRPC. Remove them in the -// contract follow-up after the rollback window. Deploy coordinators first; roll -// back orchestrators before coordinators. +// The HTTP adapters serve orchestrators that do not call the app-gRPC methods. +// Remove them only after no deployed or rollback-target orchestrator calls them. #[derive(Serialize)] pub struct PauseResumeResponse { diff --git a/crates/engram-coordinator/src/api/mod.rs b/crates/engram-coordinator/src/api/mod.rs index e9d705464..f1c4e4a9c 100644 --- a/crates/engram-coordinator/src/api/mod.rs +++ b/crates/engram-coordinator/src/api/mod.rs @@ -42,16 +42,16 @@ pub(crate) mod upload; pub fn router(state: SharedState) -> Router { // The orchestrator uses app-gRPC. HTTP serves host ingestion, in-guest - // forge requests, health probes, and the pause/resume compatibility routes. - // Keep the old orchestrator bearer in ENGRAM_AUTH_TOKENS through the - // rollback window. Remove the two admin routes in the contract follow-up. + // forge requests, health probes, and the admin pause/resume routes for + // orchestrators that do not call the app-gRPC methods. While those routes + // exist, ENGRAM_AUTH_TOKENS must include the orchestrator's bearer. let auth_state = auth::AuthState::new(state.cfg.auth_tokens.clone()); // ADR 0031 internal control-plane: host → coord ingestion. Machine // traffic authenticated by the deployment bearer (`require_bearer`). // pause/resume live here (not a human surface) behind the same bearer. let internal = Router::new() - // Compatibility for older orchestrators: in-place freeze / unfreeze. + // In-place freeze / unfreeze for orchestrators that do not use app-gRPC. .route("/admin/sessions/{id}/pause", post(admin::pause_session)) .route("/admin/sessions/{id}/resume", post(admin::resume_session)) .route("/hosts/register", post(host_http::register)) diff --git a/orchestrator/src/__tests__/admin-routes.test.ts b/orchestrator/src/__tests__/admin-routes.test.ts deleted file mode 100644 index 30ca77f65..000000000 --- a/orchestrator/src/__tests__/admin-routes.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { Code, ConnectError, createClient, createRouterTransport } from "@connectrpc/connect"; -import { makeAdminRoute } from "../routes/admin.ts"; -import { registerPassthrough } from "../rpc/passthrough.ts"; -import { SURFACE } from "../rpc/surface.ts"; -import { SessionService } from "../gen/engram/app/v1/session_pb.ts"; - -for (const operation of ["pause", "resume"] as const) { - describe(`admin ${operation}`, () => { - function fixture(role: string | null, failure?: ConnectError) { - const calls: Array<{ method: string; sessionId: string }> = []; - const app = makeAdminRoute({ - getSession: async () => role === null ? null : { user: { id: "u1", role } }, - sessions: { - pauseSession: async ({ sessionId }) => { - calls.push({ method: "pause", sessionId }); - if (failure) throw failure; - return { sessionId, note: "paused" }; - }, - resumeSession: async ({ sessionId }) => { - calls.push({ method: "resume", sessionId }); - if (failure) throw failure; - return { sessionId, note: "resumed" }; - }, - }, - }); - return { - calls, - request: (id = "s1") => app.request(`/api/v1/admin/sessions/${id}/${operation}`, { - method: "POST", - }), - }; - } - - for (const [role, status] of [[null, 401], ["user", 403]] as const) { - test(`rejects ${role ?? "anonymous"} before calling upstream`, async () => { - const f = fixture(role); - expect((await f.request()).status).toBe(status); - expect(f.calls).toEqual([]); - }); - } - - test("uses the in-place RPC and preserves the browser JSON shape", async () => { - const f = fixture("admin"); - const response = await f.request(); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ - session_id: "s1", - note: operation === "pause" ? "paused" : "resumed", - }); - expect(f.calls).toEqual([{ method: operation, sessionId: "s1" }]); - }); - - test("passes encoded input as data", async () => { - const f = fixture("admin", new ConnectError("invalid session_id", Code.InvalidArgument)); - expect((await f.request("bad%2Fid%3Fquery")).status).toBe(400); - expect(f.calls).toEqual([{ method: operation, sessionId: "bad/id?query" }]); - }); - - for (const [code, status, slug] of [ - [Code.InvalidArgument, 400, "bad_request"], - [Code.FailedPrecondition, 409, "conflict"], - [Code.Internal, 500, "internal"], - [Code.Unavailable, 503, "unavailable"], - [Code.Unimplemented, 501, "unsupported"], - ] as const) { - test(`maps ${Code[code]} to HTTP ${status}`, async () => { - const f = fixture("admin", new ConnectError("failure", code)); - const response = await f.request(); - expect(response.status).toBe(status); - expect(await response.json()).toEqual({ error: slug, message: "failure" }); - expect(f.calls).toHaveLength(1); - }); - } - }); -} - -for (const method of ["pauseSession", "resumeSession"] as const) { - for (const role of [null, "user", "admin"] as const) { - test(`direct ${method} RPC gate for ${role ?? "anonymous"}`, async () => { - const calls: string[] = []; - const upstream = createRouterTransport((router) => { - router.service(SessionService, { - pauseSession: ({ sessionId }) => { - calls.push("pauseSession"); - return { sessionId, note: "paused" }; - }, - resumeSession: ({ sessionId }) => { - calls.push("resumeSession"); - return { sessionId, note: "resumed" }; - }, - }); - }); - const transport = createRouterTransport((router) => { - registerPassthrough(router, SURFACE, upstream, - async () => role === null ? null : { user: { id: "u1", role } }, - async () => "u1"); - }); - const client = createClient(SessionService, transport); - if (role === "admin") { - const result = await client[method]({ sessionId: "s1" }); - expect(result.sessionId).toBe("s1"); - expect(result.note).toBe(method === "pauseSession" ? "paused" : "resumed"); - expect(calls).toEqual([method]); - } else { - await expect(client[method]({ sessionId: "s1" })).rejects.toMatchObject({ - code: role === null ? Code.Unauthenticated : Code.PermissionDenied, - }); - expect(calls).toEqual([]); - } - }); - } -} diff --git a/orchestrator/src/__tests__/pause-resume-policy.test.ts b/orchestrator/src/__tests__/pause-resume-policy.test.ts new file mode 100644 index 000000000..205a06e87 --- /dev/null +++ b/orchestrator/src/__tests__/pause-resume-policy.test.ts @@ -0,0 +1,43 @@ +import { expect, test } from "bun:test"; +import { Code, createClient, createRouterTransport } from "@connectrpc/connect"; +import { registerPassthrough } from "../rpc/passthrough.ts"; +import { SURFACE } from "../rpc/surface.ts"; +import { SessionService } from "../gen/engram/app/v1/session_pb.ts"; + +// In-place pause and resume are admin-only, the same gate as the HTTP admin routes. +for (const method of ["pauseSession", "resumeSession"] as const) { + for (const role of [null, "user", "admin"] as const) { + test(`direct ${method} RPC gate for ${role ?? "anonymous"}`, async () => { + const calls: string[] = []; + const upstream = createRouterTransport((router) => { + router.service(SessionService, { + pauseSession: ({ sessionId }) => { + calls.push("pauseSession"); + return { sessionId, note: "paused" }; + }, + resumeSession: ({ sessionId }) => { + calls.push("resumeSession"); + return { sessionId, note: "resumed" }; + }, + }); + }); + const transport = createRouterTransport((router) => { + registerPassthrough(router, SURFACE, upstream, + async () => role === null ? null : { user: { id: "u1", role } }, + async () => "u1"); + }); + const client = createClient(SessionService, transport); + if (role === "admin") { + const result = await client[method]({ sessionId: "s1" }); + expect(result.sessionId).toBe("s1"); + expect(result.note).toBe(method === "pauseSession" ? "paused" : "resumed"); + expect(calls).toEqual([method]); + } else { + await expect(client[method]({ sessionId: "s1" })).rejects.toMatchObject({ + code: role === null ? Code.Unauthenticated : Code.PermissionDenied, + }); + expect(calls).toEqual([]); + } + }); + } +} diff --git a/orchestrator/src/config.ts b/orchestrator/src/config.ts index 91044e262..b9d549870 100644 --- a/orchestrator/src/config.ts +++ b/orchestrator/src/config.ts @@ -30,6 +30,10 @@ export interface Config { databaseUrl: string; /** CONTROL_PLANE_GRPC_URL — default http://127.0.0.1:50061 */ controlPlaneGrpcUrl: string; + /** CONTROL_PLANE_HTTP_URL — coordinator REST base URL. Used by admin REST + * proxy routes (pause/resume session) that have no gRPC equivalent yet. + * Default: http://127.0.0.1:8090 (coordinator HTTP port in dev). */ + controlPlaneHttpUrl: string; /** CONTROL_PLANE_BEARER — required: the coordinator app-gRPC bearer token */ controlPlaneBearer: string; /** @@ -391,6 +395,7 @@ export function loadConfig(env: Record = process.env const connectionBrokerBearer = optional("CONNECTION_BROKER_BEARER", controlPlaneBearer); const githubAppLogin = optional("GITHUB_APP_LOGIN", ""); const controlPlaneGrpcUrl = optional("CONTROL_PLANE_GRPC_URL", "http://127.0.0.1:50061"); + const controlPlaneHttpUrl = optional("CONTROL_PLANE_HTTP_URL", "http://127.0.0.1:8090"); const databaseUrl = require("ORCHESTRATOR_DATABASE_URL"); const trustedOriginsRaw = optional("TRUSTED_ORIGINS", "http://localhost:5173"); const trustedOrigins = trustedOriginsRaw @@ -592,6 +597,7 @@ export function loadConfig(env: Record = process.env baseUrl, databaseUrl, controlPlaneGrpcUrl, + controlPlaneHttpUrl, controlPlaneBearer, connectionBrokerBearer, deploymentId, diff --git a/orchestrator/src/routes/admin.ts b/orchestrator/src/routes/admin.ts index 964ed93bf..abc00a89e 100644 --- a/orchestrator/src/routes/admin.ts +++ b/orchestrator/src/routes/admin.ts @@ -1,30 +1,27 @@ -/** Admin HTTP routes backed by the app-gRPC in-place pause/resume methods. */ +/** + * Admin HTTP routes for in-place pause and resume. Each route requires the + * admin role (CASL 'manage all') and forwards to the coordinator REST API with + * CONTROL_PLANE_BEARER, which the coordinator's ENGRAM_AUTH_TOKENS must + * include. These routes move to SessionService.PauseSession / ResumeSession + * after every coordinator serves those methods. + */ -import { Code, ConnectError } from "@connectrpc/connect"; import { Hono } from "hono"; import { HTTPException } from "hono/http-exception"; import { getSessionFromHeaders } from "../auth/session.ts"; import { abilityFor } from "../authz/ability.ts"; -import { sessions } from "../control-plane/client.ts"; -import type { GetSession } from "./guard.ts"; - -type PauseResume = (request: { sessionId: string }) => Promise<{ - sessionId: string; - note: string; -}>; +import { config } from "../config.ts"; export function makeAdminRoute( - deps: { - sessions?: { pauseSession: PauseResume; resumeSession: PauseResume }; - getSession?: GetSession; - } = {}, + deps: { httpUrl?: string; bearer?: string } = {}, ): Hono { const app = new Hono(); - const client = deps.sessions ?? sessions; - const getSession = deps.getSession ?? getSessionFromHeaders; + const httpBase = (deps.httpUrl ?? config.controlPlaneHttpUrl).replace(/\/$/, ""); + const bearer = deps.bearer ?? config.controlPlaneBearer; + /** Require admin; throws HTTPException(401/403) otherwise. */ async function requireAdmin(headers: Headers): Promise { - const session = await getSession(headers); + const session = await getSessionFromHeaders(headers); if (!session) { throw new HTTPException(401, { message: "unauthenticated" }); } @@ -37,41 +34,47 @@ export function makeAdminRoute( } } - // Preserve the browser's HTTP response shape while using app-gRPC upstream. - async function invoke(call: () => ReturnType): Promise { - try { - const result = await call(); - return Response.json({ session_id: result.sessionId, note: result.note }); - } catch (error) { - if (!(error instanceof ConnectError)) throw error; - const [status, slug] = (() => { - switch (error.code) { - case Code.InvalidArgument: return [400, "bad_request"] as const; - case Code.Unauthenticated: return [401, "unauthorized"] as const; - case Code.PermissionDenied: return [403, "forbidden"] as const; - case Code.NotFound: return [404, "not_found"] as const; - case Code.FailedPrecondition: return [409, "conflict"] as const; - case Code.Unimplemented: return [501, "unsupported"] as const; - case Code.Unavailable: return [503, "unavailable"] as const; - default: return [500, "internal"] as const; - } - })(); - return Response.json({ - error: error.metadata.get("engram-error-slug") ?? slug, - message: error.rawMessage, - }, { status }); - } + /** Forward a POST to the coordinator REST API. */ + async function forwardPost( + path: string, + body: unknown, + ): Promise { + const res = await fetch(`${httpBase}${path}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${bearer}`, + }, + body: JSON.stringify(body), + }); + return res; } + // POST /api/v1/admin/sessions/:id/pause — freeze the session's microVM in place. + // Admin-only. The session stays `active`; the guest vCPUs stop until resumed. app.post("/api/v1/admin/sessions/:id/pause", async (c) => { await requireAdmin(c.req.raw.headers); - return invoke(() => client.pauseSession({ sessionId: c.req.param("id") })); + const id = c.req.param("id"); + const upstream = await forwardPost(`/api/v1/admin/sessions/${encodeURIComponent(id)}/pause`, {}); + const body = upstream.status === 204 ? null : await upstream.text(); + return new Response(body, { + status: upstream.status, + headers: { "Content-Type": "application/json" }, + }); }); - // ResumeSession unfreezes in place; Resume rehydrates an idle session. + // POST /api/v1/admin/sessions/:id/resume — unfreeze the session's microVM. + // Admin-only. Counterpart to /pause; the in-place unfreeze, NOT the + // idle-rehydrate at /sessions/:id/resume (which is SessionService.Resume). app.post("/api/v1/admin/sessions/:id/resume", async (c) => { await requireAdmin(c.req.raw.headers); - return invoke(() => client.resumeSession({ sessionId: c.req.param("id") })); + const id = c.req.param("id"); + const upstream = await forwardPost(`/api/v1/admin/sessions/${encodeURIComponent(id)}/resume`, {}); + const body = upstream.status === 204 ? null : await upstream.text(); + return new Response(body, { + status: upstream.status, + headers: { "Content-Type": "application/json" }, + }); }); return app; From 89f7b9b95829a35734f025266cf71db5d3c36c4b Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:08:36 -0800 Subject: [PATCH 03/17] host-agent: pin the handoff marker disk bytes and its crash states The handoff marker type moved to engram-protocol. The successor reads the file that the previous build wrote, so pin the pretty JSON bytes the writer produces. Also cover every post-crash state of the tmp-then-rename write: a torn marker at each byte offset is removed and reads as a fresh start, and a leftover tmp sibling is ignored. Co-Authored-By: Claude Opus 5.5 --- crates/engram-host-agent/src/lib.rs | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/crates/engram-host-agent/src/lib.rs b/crates/engram-host-agent/src/lib.rs index d5bd41b5a..7abdbb9d7 100644 --- a/crates/engram-host-agent/src/lib.rs +++ b/crates/engram-host-agent/src/lib.rs @@ -1973,4 +1973,34 @@ mod tests { // Adoption is consume-once. assert!(adopt_handoff_marker(dir.path()).is_none()); } + + /// The on-disk marker bytes are pinned, and every post-crash state of the + /// tmp-then-rename write recovers: a torn marker at any byte offset is + /// removed and reads as a fresh start, and a leftover tmp sibling is ignored. + #[test] + fn handoff_marker_disk_format_and_crash_states() { + let pinned = "{\n \"declared_at_unix_ms\": 1765432100000,\n \"ttl_secs\": 600,\n \"resident_sandboxes\": 4\n}"; + let marker = engram_host_core::shutdown::HandoffMarker { + declared_at_unix_ms: 1_765_432_100_000, + ttl_secs: 600, + resident_sandboxes: 4, + }; + assert_eq!(serde_json::to_string_pretty(&marker).unwrap(), pinned); + + let dir = tempfile::tempdir().expect("tempdir"); + let bindings = dir.path().join("bindings"); + std::fs::create_dir_all(&bindings).expect("bindings dir"); + let path = bindings.join(engram_host_core::shutdown::HANDOFF_MARKER_FILE); + for len in 0..pinned.len() { + std::fs::write(&path, &pinned.as_bytes()[..len]).expect("write torn marker"); + assert!(adopt_handoff_marker(dir.path()).is_none(), "torn at {len}"); + assert!(!path.exists(), "torn marker at {len} not removed"); + } + + std::fs::write(bindings.join(".handoff.json.tmp"), &pinned.as_bytes()[..10]) + .expect("write tmp sibling"); + assert!(adopt_handoff_marker(dir.path()).is_none()); + std::fs::write(&path, pinned).expect("write marker"); + assert_eq!(adopt_handoff_marker(dir.path()), Some(marker)); + } } From c6f4d5d28afb56f6334efdee79bdd3a6c5a752e7 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Tue, 1 Dec 2026 12:15:32 -0800 Subject: [PATCH 04/17] 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 05/17] 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 06/17] 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 07/17] 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 08/17] 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 09/17] 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 From 87b314df6d147ecfa15e2b9805c001f048de9a69 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 12:43:13 -0800 Subject: [PATCH 10/17] feat(helm): add a dedicated connection-broker bearer secret value The coordinator sends ENGRAM_CONNECTION_BROKER_BEARER to the orchestrator's connection credential broker. The chart took it from the CONTROL_PLANE_BEARER key and could not set the orchestrator's CONNECTION_BROKER_BEARER, so every chart deployment used the control-plane bearer for the broker. `orchestrator.connectionBrokerSecret` (`existingSecret`, `key`) now feeds both variables from one Secret key, so they always match. When `existingSecret` is empty, the render is the same as before: the coordinator reads the CONTROL_PLANE_BEARER key, and the orchestrator env omits CONNECTION_BROKER_BEARER and falls back. This is the expand step; a later release makes the dedicated secret required. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ deploy/helm/engram/templates/deployment.yaml | 16 ++++++++++++---- .../templates/orchestrator-deployment.yaml | 11 +++++++++++ deploy/helm/engram/values.yaml | 14 ++++++++++++++ docs/deploy.md | 1 + .../content/docs/docs/reference/configuration.md | 1 + .../content/docs/docs/reference/helm-engram.md | 2 +- 7 files changed, 44 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91e1ba4ff..76c766f2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,10 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu - A session that spawns a child session gets a new prompt when the child finishes a turn. The prompt carries the child's outcome and its last message, so the parent does not have to poll for it. ([#1825]) +- The Helm value `orchestrator.connectionBrokerSecret` (`existingSecret`, `key`) gives the + connection credential broker its own bearer. The chart sets it on the coordinator and the + orchestrator. Unset, nothing changes: the broker uses the control-plane bearer. Set it + now: a later release will require it. ### Fixed diff --git a/deploy/helm/engram/templates/deployment.yaml b/deploy/helm/engram/templates/deployment.yaml index b5be3280c..e994a0452 100644 --- a/deploy/helm/engram/templates/deployment.yaml +++ b/deploy/helm/engram/templates/deployment.yaml @@ -146,13 +146,21 @@ spec: key: {{ $agKey }} {{- end }} {{- if .Values.web.enabled }} - # ADR 0109: host-only bearer for coordinator calls to the connection - # credential broker. It must match the orchestrator's validated bearer. + # ADR 0109: the bearer for coordinator calls to the connection + # credential broker. It must match the orchestrator's broker bearer + # (orchestrator-deployment.yaml reads the same Secret key). - name: ENGRAM_CONNECTION_BROKER_BEARER valueFrom: secretKeyRef: - name: {{ .Values.orchestrator.databaseSecret.existingSecret }} - key: {{ .Values.orchestrator.databaseSecret.bearerKey }} + {{- with .Values.orchestrator.connectionBrokerSecret }} + {{- if .existingSecret }} + name: {{ .existingSecret }} + key: {{ .key }} + {{- else }} + name: {{ $.Values.orchestrator.databaseSecret.existingSecret }} + key: {{ $.Values.orchestrator.databaseSecret.bearerKey }} + {{- end }} + {{- end }} {{- end }} {{- if eq .Values.forge.provider "github" }} # ADR 0023: the GitHub App private key (PEM). The coord reads diff --git a/deploy/helm/engram/templates/orchestrator-deployment.yaml b/deploy/helm/engram/templates/orchestrator-deployment.yaml index 0889f6c9c..b627db311 100644 --- a/deploy/helm/engram/templates/orchestrator-deployment.yaml +++ b/deploy/helm/engram/templates/orchestrator-deployment.yaml @@ -76,6 +76,17 @@ spec: secretKeyRef: name: {{ .Values.orchestrator.databaseSecret.existingSecret }} key: {{ .Values.orchestrator.databaseSecret.bearerKey }} + {{- with .Values.orchestrator.connectionBrokerSecret }} + {{- if .existingSecret }} + # Unset, the orchestrator's broker falls back to CONTROL_PLANE_BEARER, + # which is also what the coordinator then sends. + - name: CONNECTION_BROKER_BEARER + valueFrom: + secretKeyRef: + name: {{ .existingSecret }} + key: {{ .key }} + {{- end }} + {{- end }} - name: BETTER_AUTH_SECRET valueFrom: secretKeyRef: diff --git a/deploy/helm/engram/values.yaml b/deploy/helm/engram/values.yaml index c258ab9aa..71d099243 100644 --- a/deploy/helm/engram/values.yaml +++ b/deploy/helm/engram/values.yaml @@ -508,6 +508,20 @@ orchestrator: bearerKey: CONTROL_PLANE_BEARER authSecretKey: BETTER_AUTH_SECRET + # The bearer the coordinator presents to the orchestrator's connection + # credential broker. The chart gives the same Secret key to the coordinator + # (ENGRAM_CONNECTION_BROKER_BEARER) and the orchestrator + # (CONNECTION_BROKER_BEARER), so the two always match. + # - Default (existingSecret: ""): the broker uses CONTROL_PLANE_BEARER + # (databaseSecret.bearerKey above), and the orchestrator env omits + # CONNECTION_BROKER_BEARER. + # - Set existingSecret to a Secret that holds a DEDICATED random value + # under `key`, so a holder of the control-plane bearer cannot mint + # connection credentials. A later release requires this secret. + connectionBrokerSecret: + existingSecret: "" + key: CONNECTION_BROKER_BEARER + # ADR 0051: the orchestrator KEK-envelope-seals `user_session_secrets` at rest # (the user's harness tokens, e.g. CLAUDE_CODE_OAUTH_TOKEN) using the SAME # 32-byte key + envelope format as the coordinator's `kek.provider: env-var` diff --git a/docs/deploy.md b/docs/deploy.md index 16fd58f13..df8cd092d 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -92,6 +92,7 @@ lands where. | `ENGRAM_GCP_PROJECT_ID` | gcp secrets backend: the Secret Manager project | | `ENGRAM_CHUNK_GC_INTERVAL_SECS` / `ENGRAM_CHUNK_GC_RETAIN_SECS` | chunk-GC cadence / unreferenced retention | | `ENGRAM_APP_GRPC_TOKENS` | The orchestrator's bearer (fail-closed when empty) | +| `ENGRAM_CONNECTION_BROKER_BEARER` | The bearer for calls to the orchestrator's connection credential broker. Must match the orchestrator's `CONNECTION_BROKER_BEARER`. The chart reads both from `orchestrator.connectionBrokerSecret`; unset, both use `CONTROL_PLANE_BEARER` | Cloud credentials are ambient: GKE Workload Identity / EKS IRSA on the coordinator's ServiceAccount — no key files. diff --git a/site/src/content/docs/docs/reference/configuration.md b/site/src/content/docs/docs/reference/configuration.md index 118cdd98d..c65072d71 100644 --- a/site/src/content/docs/docs/reference/configuration.md +++ b/site/src/content/docs/docs/reference/configuration.md @@ -15,6 +15,7 @@ where, for anyone reading a manifest or running a component outside the charts. | `DATABASE_URL` | Postgres connection string, from the coordinator's Secret. | | `ENGRAM_AUTH_TOKENS` | Comma-separated bearer tokens that hosts and the orchestrator present. | | `ENGRAM_APP_GRPC_TOKENS` | The orchestrator's bearer for the coordinator's private RPC port. Empty means every call is refused. | +| `ENGRAM_CONNECTION_BROKER_BEARER` | The bearer the coordinator sends to the orchestrator's connection credential broker. It must match the orchestrator's `CONNECTION_BROKER_BEARER`. When the orchestrator has no `CONNECTION_BROKER_BEARER`, it accepts its control-plane bearer here. | | `ENGRAM_BLOB_BACKEND` | `gcs`, `s3`, or `local` for development. | | `ENGRAM_GCS_BUCKET` | With `gcs`: the chunks bucket. | | `ENGRAM_S3_BUCKET`, `ENGRAM_S3_REGION`, `ENGRAM_S3_ENDPOINT_URL` | With `s3`: the bucket, the signing region, and an optional endpoint for S3-compatible stores such as MinIO or R2, which switches the client to path-style addressing. | diff --git a/site/src/content/docs/docs/reference/helm-engram.md b/site/src/content/docs/docs/reference/helm-engram.md index bf35c33f0..673c65ccc 100644 --- a/site/src/content/docs/docs/reference/helm-engram.md +++ b/site/src/content/docs/docs/reference/helm-engram.md @@ -94,7 +94,7 @@ at boot. | `upgradeDrain` | The job that runs before an upgrade whose host agents cannot adopt the VMs running now: whether it runs and its time budget. It runs the coordinator image. See [Upgrade engrams](../../guides/upgrade/#when-a-release-changes-how-hosts-run-vms). | | `probes`, `drainSeconds`, `terminationGracePeriodSeconds` | Liveness on `/healthz`, readiness on `/readyz`, and how long a replica drains before it stops. | | `web` | The dashboard: image, Ingress, and the annotations that attach a managed certificate. | -| `orchestrator` | The orchestrator: image, its Secret with the session-signing key, `auth` (see [Sign-in](#sign-in)), the public URL, and integration settings. | +| `orchestrator` | The orchestrator: image, its Secret with the session-signing key, `auth` (see [Sign-in](#sign-in)), the public URL, and integration settings. `connectionBrokerSecret` names a Secret and key with a dedicated bearer for the connection credential broker; the chart gives it to the coordinator and the orchestrator. Unset, the broker uses the control-plane bearer. | ## Upgrades From 6826d55860658f5e326edd7c0eec734d67155b59 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 12:43:46 -0800 Subject: [PATCH 11/17] docs(changelog): link the connection-broker secret entry to its pull request Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76c766f2c..de6be7cee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,7 +46,7 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu - The Helm value `orchestrator.connectionBrokerSecret` (`existingSecret`, `key`) gives the connection credential broker its own bearer. The chart sets it on the coordinator and the orchestrator. Unset, nothing changes: the broker uses the control-plane bearer. Set it - now: a later release will require it. + now: a later release will require it. ([#1859]) ### Fixed @@ -454,3 +454,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 +[#1859]: https://github.com/cortexapps/engrams/pull/1859 From 9753afc95350d8dcc9e97b5aacd874c27338bfb8 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Tue, 1 Dec 2026 12:15:44 -0800 Subject: [PATCH 12/17] fix(cli,deploy): harden hosts.json writes, scope operator RBAC, fix Tiltfile and tooling hygiene --- .codex-review-p1.md | 17 -- .codex-review-p5.md | 14 - Tiltfile | 15 +- crates/engram-app-client/src/config.rs | 286 +++++++++++++++--- crates/engram-cli/src/commands/auth.rs | 6 +- crates/engram-cli/src/main.rs | 2 +- deploy/dev/seed-buckets.sh | 7 +- .../templates/operator.rbac.yaml | 43 ++- justfile | 2 +- 9 files changed, 286 insertions(+), 106 deletions(-) delete mode 100644 .codex-review-p1.md delete mode 100644 .codex-review-p5.md diff --git a/.codex-review-p1.md b/.codex-review-p1.md deleted file mode 100644 index cb97272fc..000000000 --- a/.codex-review-p1.md +++ /dev/null @@ -1,17 +0,0 @@ -Review scope: `main` (`23c28c55f`)..`HEAD` (`126db872d`), one commit. Read the full diff, AGENTS.md, and the surrounding restore, capture, image cleanup, coordinator teleport, and CI code. Findings are from static review; no Rust or Linux/KVM tests ran. - -1. **MEDIUM — File-backed guests without an NBD disk now enter a live move that cannot advance.** `crates/engram-sandbox-firecracker/src/lib.rs:5375` and `crates/engram-host-agent/src/pooled_backend.rs:8264`. A File-mode guest on a host without the substrate, with a checkpoint chain and page server but a file-backed rootfs, previously returned no source view and selected snapshot rehome. It now passes presetup. The disk lookup still returns `None` (`pooled_backend.rs:8310`), but the coordinator requires a disk manifest and returns `ApiError::Internal("live export has no disk manifest")` (`crates/engram-coordinator/src/teleport.rs:436`). It never persists the export or selects snapshot mode; retry repeats the same failure. This is a supported configuration: NBD setup is optional (`crates/engram-host-agent/src/main.rs:678`), and the new test itself uses no NBD pool. **Smallest fix:** reject a missing live NBD disk with `InvalidSpec` during presetup, before publishing pending state, so the existing coordinator fallback selects snapshot rehome. Add a regression for that fallback; use an NBD-backed guest for successful live-move coverage. - -2. **MEDIUM — Disabling an image makes its running File-mode guests fail capture after the pause.** `crates/engram-host-agent/src/pooled_backend.rs:8481`. Image reconciliation deliberately unlinks the per-image memfile while existing guests still map it (`crates/engram-host-agent/src/image_prefetch.rs:482-505`). Their new `memory_backing` field remains set, so presetup admits them. Linux reports the mapped pathname with ` (deleted)`, which `dirty_map::parse_maps_line` explicitly rejects (`crates/engram-host-agent/src/dirty_map.rs:82-86`). Capture therefore finds no VMAs and returns `Snapshot` after pausing. The coordinator rolls back instead of selecting snapshot rehome (`crates/engram-coordinator/src/teleport.rs:483-493`); each subsequent live attempt fails again. Re-enabling the image creates a new inode and does not repair the old mapping. **Smallest fix:** allow selection of the retained, deleted memfile mapping, with unambiguous mapping identity, or retain memfiles until their last live mapping is gone. Add an image-disable-then-capture regression. A presetup-only file-existence check is insufficient because disable can race capture. - -3. **MEDIUM — The new CI test uses stock Firecracker for a fork-only capture API.** `crates/engram-host-agent/tests/postcopy_source_fresh_create.rs:184-191`. The fixture leaves `cfg.firecracker_bin` at `"firecracker"`. CI installs stock v1.16.0 at that name and stages the fork separately in `ENGRAM_FC_FORK_BIN` (`.github/actions/fc-setup/action.yml:100-139`). The test calls `migration_capture_postcopy`, which calls `snapshot_vmstate_only_package`; this sends `vmstate_only: true`, explicitly documented as rejected by stock Firecracker (`crates/engram-sandbox-firecracker/src/lib.rs:7100-7103`, `src/client.rs:308-323`). Thus the newly added CI target fails at capture before testing the VMA scan. **Smallest fix:** select the staged fork in the fixture and make the CI lane require that artifact. Keep any local missing-fork skip explicit. - -Checked and found sound within this change: - -- The recorded UFFD backing uses the same canonical manifest selection as the actual snapshot load. File restores record the memfile passed to the load API. -- The backing field is persisted and restored on reattach. Old manifests deserialize with `None`, which causes a conservative presetup refusal and snapshot fallback. -- The authoritative guest-swap check still rejects post-copy before pause. This change does not bypass ADR 0112's snapshot disarm path. -- The changed VMA lookup remains inside the existing capture unwind guard; lookup failure does not itself remove the resume, disk-fence cleanup, or presetup-restoration path. Export registration remains after fallible capture work. -- Fresh-mode configuration removal is consistent across the binary, Tilt, and Helm. Resumes still follow `restore_mode`. No coordinator time/randomness calls, teleport writes, wire fields, or Postgres semantics changed, so this diff adds no fencing or conformance obligation there. -- The new integration target is included in the KVM CI lane, and that lane provisions its kernel and agent binary. Its Firecracker selection is the defect listed above. -- `git diff main..HEAD --check` passed. Source files were not modified; only this requested report was added. diff --git a/.codex-review-p5.md b/.codex-review-p5.md deleted file mode 100644 index 0e1ae9733..000000000 --- a/.codex-review-p5.md +++ /dev/null @@ -1,14 +0,0 @@ -Review scope: `23c28c55f..88b4b23e4` (`main..HEAD`), one commit: `88b4b23e4 fix(teleport): live is the admitted kind; the attach step wakes on the harness event`. - -1. **HIGH — Removing the destination live-capability check can turn a supported snapshot move into loss of the running session.** `crates/engram-coordinator/src/teleport.rs:709`; `crates/engram-postgres/src/lib.rs:1188`. Consider a swap-free substrate source and a Firecracker destination configured for File-mode restore, with no usable UFFD handler. The destination can serve ordinary snapshot restores. Its substrate probes report `NotApplicable`, which `host_meets_capabilities` explicitly accepts even with `needs_uffd_substrate: true` (`placement.rs:149-162`). Before this commit, the additional destination check selected `Snapshot`. Now admission always records `Live`, and only the source receives the capability RPC. The source accepts presetup and is frozen while destination restore starts (`teleport.rs:471-482`). Migration restore forces UFFD regardless of the destination's configured mode (`engram-sandbox-firecracker/src/lib.rs:1343`); a handler spawn failure returns a generic VM error (`lib.rs:2203`). It does not carry the `postcopy-never-loaded` marker. After the retry budget, `finish_live_restore` calls `fail_move(..., false)` (`teleport.rs:546-547`), which detaches the session and tombstones the healthy frozen source instead of using the previously supported snapshot path. The session loses its running memory state and falls back to disk recovery or Dead. **Smallest fix:** retain a destination-specific live-capability gate before source capture. The row can still be admitted as Live, then make a fenced transition to Snapshot when the selected destination cannot support live restore. Do not tighten the shared placement predicate, since File-mode snapshot restores must remain supported. Add a regression with a capable source and a File-mode destination; assert snapshot fallback occurs before live capture. - -Checked and found sound within this change: - -- Source presetup still refuses swap-backed guests before freeze or presetup consumption; the refusal takes the existing snapshot capture path. This preserves the ADR 0112 capture boundary. -- Admission still reserves destination capacity in the metadata transaction. The removed request field is an internal Rust field, not a wire or sandbox-manifest field; this change adds no serialization-version requirement. -- Attach uses the injected clock. Its new wait retains the executor heartbeat, and completion still uses the session fence and teleport phase CAS. -- The event wake targets queued teleport operations. The post-requeue generation read covers an event that arrived while the operation was still running and returned RetryAfter. -- PostgreSQL and simulator settlement both distinguish a generation advance with no closed runs from no advance. The shared conformance scenario checks both results. Existing snapshot-refusal and live scenarios remain present. -- Source release still waits for destination drain completion on live moves. The branch does not change capture guards, manifest recovery, or drain-role ordering. - -Validation: static review of the complete branch diff and surrounding production paths. `git diff --check main..HEAD` passed. No compilation, runtime tests, PostgreSQL tests, or KVM tests ran. Only this report was added; source files were not changed. diff --git a/Tiltfile b/Tiltfile index 6c5b2485d..da8417ca7 100644 --- a/Tiltfile +++ b/Tiltfile @@ -1142,14 +1142,13 @@ local_resource('orchestrator', # key whose plaintext lands in var/dev-api-key (gitignored, 0600). # Idempotent — re-mints only when the file is missing or the key row is gone. local_resource('dev-api-key', - cmd=( - 'cd orchestrator && ' + - 'ORCHESTRATOR_DATABASE_URL=' + orchestrator_db_url + ' ' + - 'BETTER_AUTH_SECRET="' + orchestrator_env['BETTER_AUTH_SECRET'] + '" ' + - 'CONTROL_PLANE_BEARER="' + orchestrator_env['CONTROL_PLANE_BEARER'] + '" ' + - 'ENGRAM_KEK_MASTER_KEY="' + orchestrator_env['ENGRAM_KEK_MASTER_KEY'] + '" ' + - 'bun scripts/seed-dev-key.ts ../var/dev-api-key' - ), + cmd='cd orchestrator && bun scripts/seed-dev-key.ts ../var/dev-api-key', + env={ + 'ORCHESTRATOR_DATABASE_URL': orchestrator_db_url, + 'BETTER_AUTH_SECRET': orchestrator_env['BETTER_AUTH_SECRET'], + 'CONTROL_PLANE_BEARER': orchestrator_env['CONTROL_PLANE_BEARER'], + 'ENGRAM_KEK_MASTER_KEY': orchestrator_env['ENGRAM_KEK_MASTER_KEY'], + }, resource_deps=['orchestrator-migrate'], labels=['setup']) diff --git a/crates/engram-app-client/src/config.rs b/crates/engram-app-client/src/config.rs index 587e9d465..eb53a8492 100644 --- a/crates/engram-app-client/src/config.rs +++ b/crates/engram-app-client/src/config.rs @@ -12,8 +12,9 @@ //! credentials for prod and a local dev stack side by side. use std::collections::BTreeMap; -use std::io; -use std::path::PathBuf; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use serde::{Deserialize, Serialize}; @@ -71,87 +72,272 @@ pub fn resolve_host(flag_url: Option<&str>) -> String { ) } -/// Unreadable or malformed files read as empty, as in the Bun CLI. -fn read_hosts() -> HostsFile { - std::fs::read(hosts_path()) - .ok() - .and_then(|b| serde_json::from_slice(&b).ok()) - .unwrap_or_default() +fn read_hosts(path: &Path) -> io::Result { + let body = match std::fs::read(path) { + Ok(body) => body, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(HostsFile::default()), + Err(e) => { + return Err(io::Error::new( + e.kind(), + format!("cannot read credentials from {}: {e}", path.display()), + )); + } + }; + serde_json::from_slice(&body).map_err(|e| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("invalid credentials JSON in {}: {e}", path.display()), + ) + }) } -fn write_hosts(hosts: &HostsFile) -> io::Result<()> { - let path = hosts_path(); +fn write_hosts(path: &Path, hosts: &HostsFile) -> io::Result<()> { + let dir = path.parent().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "credentials path has no parent", + ) + })?; + create_private_dir(dir)?; let mut body = serde_json::to_vec_pretty(hosts)?; body.push(b'\n'); - std::fs::write(&path, body)?; - restrict(&path) -} - -#[cfg(unix)] -fn restrict(path: &std::path::Path) -> io::Result<()> { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) -} - -#[cfg(not(unix))] -fn restrict(_path: &std::path::Path) -> io::Result<()> { - Ok(()) + static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); + let (temp_path, mut file) = loop { + let id = NEXT_TEMP.fetch_add(1, Ordering::Relaxed); + let temp_path = dir.join(format!(".hosts.{}.{id}.tmp", std::process::id())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + match options.open(&temp_path) { + Ok(file) => break (temp_path, file), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + }; + let result = (|| { + file.write_all(&body)?; + file.sync_all()?; + std::fs::rename(&temp_path, path) + })(); + drop(file); + if result.is_err() { + std::fs::remove_file(&temp_path)?; + } + result } -pub fn stored_credential(host: &str) -> Option { - read_hosts().remove(&normalize_host(host)) +pub fn stored_credential(host: &str) -> io::Result> { + Ok(read_hosts(&hosts_path())?.remove(&normalize_host(host))) } pub fn store_credential(host: &str, cred: HostCredential) -> io::Result<()> { let path = hosts_path(); - if let Some(dir) = path.parent() { - create_private_dir(dir)?; - } - let mut hosts = read_hosts(); + let mut hosts = read_hosts(&path)?; hosts.insert(normalize_host(host), cred); - write_hosts(&hosts) + write_hosts(&path, &hosts) } -#[cfg(unix)] -fn create_private_dir(dir: &std::path::Path) -> io::Result<()> { - use std::os::unix::fs::DirBuilderExt; - match std::fs::DirBuilder::new() - .recursive(true) - .mode(0o700) - .create(dir) +fn create_private_dir(dir: &Path) -> io::Result<()> { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] { - Ok(()) => Ok(()), - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()), - Err(e) => Err(e), + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); } -} - -#[cfg(not(unix))] -fn create_private_dir(dir: &std::path::Path) -> io::Result<()> { - std::fs::create_dir_all(dir) + builder.create(dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; + } + Ok(()) } /// Forget the stored login for `host`. A missing entry is not an error. pub fn delete_credential(host: &str) -> io::Result<()> { - let mut hosts = read_hosts(); + let path = hosts_path(); + let mut hosts = read_hosts(&path)?; if hosts.remove(&normalize_host(host)).is_none() { return Ok(()); } - write_hosts(&hosts) + write_hosts(&path, &hosts) } /// The key for a request against `host`, or `None` when logged out. -pub fn resolve_api_key(host: &str) -> Option { - std::env::var("ENGRAMS_API_KEY") +pub fn resolve_api_key(host: &str) -> io::Result> { + if let Some(key) = std::env::var("ENGRAMS_API_KEY") .ok() .filter(|s| !s.is_empty()) - .or_else(|| stored_credential(host).map(|c| c.api_key)) + { + return Ok(Some(key)); + } + Ok(stored_credential(host)?.map(|c| c.api_key)) } #[cfg(test)] mod tests { use super::*; + struct TestDir(PathBuf); + + impl TestDir { + fn new() -> Self { + static NEXT_DIR: AtomicU64 = AtomicU64::new(0); + loop { + let id = NEXT_DIR.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir() + .join(format!("engram-config-test-{}-{id}", std::process::id())); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("cannot create test directory: {e}"), + } + } + } + } + + impl Drop for TestDir { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + fn credential() -> HostCredential { + HostCredential { + api_key: "engk_test".into(), + key_id: "key-1".into(), + user: None, + } + } + + #[test] + fn missing_hosts_is_empty_but_read_errors_are_reported() { + let dir = TestDir::new(); + let path = dir.0.join("hosts.json"); + assert!(read_hosts(&path).unwrap().is_empty()); + std::fs::create_dir(&path).unwrap(); + let error = read_hosts(&path).unwrap_err(); + assert!(error.to_string().contains("cannot read credentials")); + assert!(error.to_string().contains(&path.display().to_string())); + } + + #[test] + fn corrupt_hosts_are_not_overwritten() { + // The child has its own environment, so parallel tests cannot change its path. + const CHILD: &str = "ENGRAM_CONFIG_TEST_CHILD"; + if std::env::var_os(CHILD).is_none() { + let dir = TestDir::new(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "config::tests::corrupt_hosts_are_not_overwritten", + ]) + .env(CHILD, "1") + .env("XDG_CONFIG_HOME", &dir.0) + .env_remove("ENGRAMS_API_KEY") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stdout) + ); + return; + } + let host = "https://test.example"; + store_credential(host, credential()).unwrap(); + assert_eq!(stored_credential(host).unwrap(), Some(credential())); + let path = hosts_path(); + for body in [ + "", + "{broken", + r#"{"https://test.example":{"apiKey":"engk_test"}}"#, + ] { + std::fs::write(&path, body).unwrap(); + let error = read_hosts(&path).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert!(error.to_string().contains("invalid credentials JSON")); + assert!(error.to_string().contains(&path.display().to_string())); + assert!(stored_credential(host).is_err()); + assert!(resolve_api_key(host).is_err()); + assert!(store_credential(host, credential()).is_err()); + assert!(delete_credential(host).is_err()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), body); + } + } + + #[test] + fn failed_rename_removes_temporary_file() { + let dir = TestDir::new(); + let path = dir.0.join("hosts.json"); + std::fs::create_dir(&path).unwrap(); + std::fs::write(path.join("keep"), b"unchanged").unwrap(); + assert!(write_hosts(&path, &HostsFile::new()).is_err()); + assert_eq!(std::fs::read(path.join("keep")).unwrap(), b"unchanged"); + assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1); + } + + #[test] + fn private_dir_rejects_existing_file() { + let dir = TestDir::new(); + let path = dir.0.join("engrams"); + std::fs::write(&path, b"unchanged").unwrap(); + assert!(create_private_dir(&path).is_err()); + assert_eq!(std::fs::read(path).unwrap(), b"unchanged"); + } + + #[cfg(unix)] + #[test] + fn writes_replace_the_file_with_private_permissions() { + use std::io::Read; + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + let dir = TestDir::new(); + let path = dir.0.join("engrams/hosts.json"); + let hosts = HostsFile::from([("https://test.example".into(), credential())]); + write_hosts(&path, &hosts).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o600); + assert_eq!(read_hosts(&path).unwrap(), hosts); + let mut old_file = std::fs::File::open(&path).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + write_hosts(&path, &HostsFile::new()).unwrap(); + assert!(read_hosts(&path).unwrap().is_empty()); + assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o600); + assert_ne!( + old_file.metadata().unwrap().ino(), + std::fs::metadata(&path).unwrap().ino() + ); + let mut old_body = Vec::new(); + old_file.read_to_end(&mut old_body).unwrap(); + assert_eq!( + serde_json::from_slice::(&old_body).unwrap(), + hosts + ); + assert_eq!( + std::fs::read_dir(path.parent().unwrap()).unwrap().count(), + 1 + ); + } + + #[cfg(unix)] + #[test] + fn private_dir_tightens_existing_permissions() { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + let dir = TestDir::new(); + let path = dir.0.join("engrams"); + create_private_dir(&path).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o700); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + write_hosts(&path.join("hosts.json"), &HostsFile::new()).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o700); + } + #[test] fn normalize_strips_trailing_slashes() { assert_eq!(normalize_host("https://x.example/"), "https://x.example"); diff --git a/crates/engram-cli/src/commands/auth.rs b/crates/engram-cli/src/commands/auth.rs index 68a2a36ca..bf36057a3 100644 --- a/crates/engram-cli/src/commands/auth.rs +++ b/crates/engram-cli/src/commands/auth.rs @@ -74,6 +74,8 @@ pub async fn login(host: &str, status: &crate::status::Status) -> CliResult { "ENGRAMS_API_KEY is set — it would shadow any stored login. Unset it to use `auth login`.", ); } + // Check the credential file before creating a new server-side key. + stored_credential(host)?; // A plain client for the non-RPC auth routes. let plain = Transport::new(host, Auth::None); let http = plain.http(); @@ -159,7 +161,7 @@ async fn whoami(host: &str, api_key: &str) -> Result { } pub async fn logout(host: &str) -> CliResult { - let Some(stored) = stored_credential(host) else { + let Some(stored) = stored_credential(host)? else { return fail(format!("no stored login for {host}")); }; // Best-effort server-side revoke, authenticated by the key being revoked. @@ -196,7 +198,7 @@ struct StatusJson<'a> { } pub async fn status(host: &str, json: bool) -> CliResult { - let key = resolve_api_key(host); + let key = resolve_api_key(host)?; let source = if env_api_key_set() { "ENGRAMS_API_KEY".to_string() } else { diff --git a/crates/engram-cli/src/main.rs b/crates/engram-cli/src/main.rs index 5ec35dc86..ae2d3574b 100644 --- a/crates/engram-cli/src/main.rs +++ b/crates/engram-cli/src/main.rs @@ -356,7 +356,7 @@ impl Ctx { /// pointer when no key is resolvable — every RPC verb calls through /// here, so the logged-out failure mode is one consistent message. fn clients(&self) -> CliResult { - let Some(key) = resolve_api_key(&self.host) else { + let Some(key) = resolve_api_key(&self.host)? else { return fail(format!( "not logged in to {} — run `engrams auth login` (or set ENGRAMS_API_KEY)", self.host diff --git a/deploy/dev/seed-buckets.sh b/deploy/dev/seed-buckets.sh index 77559f441..97ad192dc 100755 --- a/deploy/dev/seed-buckets.sh +++ b/deploy/dev/seed-buckets.sh @@ -17,6 +17,9 @@ set -euo pipefail +seed_output="$(mktemp)" +trap 'rm -f "$seed_output"' EXIT + EMULATOR="${STORAGE_EMULATOR_HOST:-http://localhost:4443}" S3_ENDPOINT="${ENGRAM_TEST_S3_ENDPOINT:-${ENGRAM_S3_ENDPOINT_URL:-}}" # Honor either env var so the script works in both contexts: @@ -55,7 +58,7 @@ seed_gcs() { # POST the bucket. The `name` field is what the SDK references; the # `location` and `storageClass` defaults match what the prod-shape # tooling expects but are otherwise irrelevant under the emulator. - HTTP_STATUS=$(curl -sw '%{http_code}' -o /tmp/seed-buckets.out \ + HTTP_STATUS=$(curl -sw '%{http_code}' -o "$seed_output" \ -X POST "${EMULATOR}/storage/v1/b?project=engram-dev" \ -H 'Content-Type: application/json' \ -d "{\"name\":\"${BUCKET}\"}" || true) @@ -69,7 +72,7 @@ seed_gcs() { ;; *) echo "seed-buckets: unexpected status ${HTTP_STATUS} from emulator:" >&2 - cat /tmp/seed-buckets.out >&2 + cat "$seed_output" >&2 exit 1 ;; esac diff --git a/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml b/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml index 9c86d867c..07da9633c 100644 --- a/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml +++ b/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml @@ -1,9 +1,5 @@ {{- if .Values.operator.enabled -}} -# ADR 0044 K3: cluster-scoped permissions the rollout operator needs — -# read its CRs, patch the host-agent DaemonSet image, and list/delete its -# pods + cordon nodes for the drain-gated roll. Node + DaemonSet/Pod access -# is cluster-wide because the host fleet spans nodes; scope is otherwise -# minimal (no secrets, no create on workloads). +# Cluster resources used to observe fleets and cordon nodes. apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: @@ -17,6 +13,34 @@ rules: - apiGroups: ["engram.io"] resources: ["hostfleets/status"] verbs: ["get", "update", "patch"] + # Cordon/uncordon the node during its roll. + - apiGroups: [""] + resources: ["nodes"] + verbs: ["get", "list", "watch", "patch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ include "hostfleet.operator.fullname" . }} + labels: + {{- include "hostfleet.operator.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ include "hostfleet.operator.fullname" . }} +subjects: + - kind: ServiceAccount + name: {{ include "hostfleet.operator.fullname" . }} + namespace: {{ .Release.Namespace }} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "hostfleet.operator.fullname" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "hostfleet.operator.labels" . | nindent 4 }} +rules: # Patch the host-agent DaemonSet's image toward the CR. - apiGroups: ["apps"] resources: ["daemonsets"] @@ -25,20 +49,17 @@ rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "list", "watch", "delete"] - # Cordon/uncordon the node during its roll. - - apiGroups: [""] - resources: ["nodes"] - verbs: ["get", "list", "watch", "patch"] --- apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding +kind: RoleBinding metadata: name: {{ include "hostfleet.operator.fullname" . }} + namespace: {{ .Release.Namespace }} labels: {{- include "hostfleet.operator.labels" . | nindent 4 }} roleRef: apiGroup: rbac.authorization.k8s.io - kind: ClusterRole + kind: Role name: {{ include "hostfleet.operator.fullname" . }} subjects: - kind: ServiceAccount diff --git a/justfile b/justfile index 457f0f20a..5ff63776d 100644 --- a/justfile +++ b/justfile @@ -10,7 +10,7 @@ # 0024). `just bake-demo` bakes the Claude image; `just pull-kernel` # fetches the right kernel. -set shell := ["bash", "-cu"] +set shell := ["bash", "-euo", "pipefail", "-c"] set dotenv-load := true # `just` with no args prints the recipe list. From acc1ad2807d724673e16be352924baf037d46667 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:06:08 -0800 Subject: [PATCH 13/17] fix(app-client): sync the config dir after the hosts.json rename write_hosts now closes the temp file before the rename, keeps the write or rename error when the cleanup also fails, and fsyncs the directory so the rename is durable. The test directory guard no longer panics in drop. Co-Authored-By: Claude Opus 5.5 --- crates/engram-app-client/src/config.rs | 35 ++++++++++++++++++-------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/crates/engram-app-client/src/config.rs b/crates/engram-app-client/src/config.rs index eb53a8492..1e2b6e055 100644 --- a/crates/engram-app-client/src/config.rs +++ b/crates/engram-app-client/src/config.rs @@ -102,7 +102,7 @@ fn write_hosts(path: &Path, hosts: &HostsFile) -> io::Result<()> { let mut body = serde_json::to_vec_pretty(hosts)?; body.push(b'\n'); static NEXT_TEMP: AtomicU64 = AtomicU64::new(0); - let (temp_path, mut file) = loop { + let (temp_path, file) = loop { let id = NEXT_TEMP.fetch_add(1, Ordering::Relaxed); let temp_path = dir.join(format!(".hosts.{}.{id}.tmp", std::process::id())); let mut options = std::fs::OpenOptions::new(); @@ -118,16 +118,29 @@ fn write_hosts(path: &Path, hosts: &HostsFile) -> io::Result<()> { Err(e) => return Err(e), } }; - let result = (|| { - file.write_all(&body)?; - file.sync_all()?; - std::fs::rename(&temp_path, path) - })(); - drop(file); - if result.is_err() { - std::fs::remove_file(&temp_path)?; + // The file closes before the rename: Windows cannot rename an open file. + if let Err(e) = write_synced(file, &body).and_then(|()| std::fs::rename(&temp_path, path)) { + // The write or rename error is the one to report. + let _ = std::fs::remove_file(&temp_path); + return Err(e); } - result + sync_dir(dir) +} + +fn write_synced(mut file: std::fs::File, body: &[u8]) -> io::Result<()> { + file.write_all(body)?; + file.sync_all() +} + +/// Makes a rename in `dir` durable. +#[cfg(unix)] +fn sync_dir(dir: &Path) -> io::Result<()> { + std::fs::File::open(dir)?.sync_all() +} + +#[cfg(not(unix))] +fn sync_dir(_dir: &Path) -> io::Result<()> { + Ok(()) } pub fn stored_credential(host: &str) -> io::Result> { @@ -203,7 +216,7 @@ mod tests { impl Drop for TestDir { fn drop(&mut self) { - std::fs::remove_dir_all(&self.0).unwrap(); + let _ = std::fs::remove_dir_all(&self.0); } } From c1096e425b2398a6f395d70f8e697ac174be53a0 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:06:09 -0800 Subject: [PATCH 14/17] docs(helm): state the namespace limit of the host-fleet operator role Co-Authored-By: Claude Opus 5.5 --- deploy/helm/engram-host-fleet/templates/operator.rbac.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml b/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml index 07da9633c..9176a6ddd 100644 --- a/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml +++ b/deploy/helm/engram-host-fleet/templates/operator.rbac.yaml @@ -33,6 +33,8 @@ subjects: name: {{ include "hostfleet.operator.fullname" . }} namespace: {{ .Release.Namespace }} --- +# The host-agent DaemonSet and its pods. A HostFleet whose daemonSet is in +# another namespace gets Forbidden. apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: From a85758a38fc0659c7ff73afd086d094b45ba7f99 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 12:59:32 -0800 Subject: [PATCH 15/17] docs(changelog): add the host-fleet operator RBAC 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..e38103701 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 host-fleet operator's DaemonSet and pod access is namespaced.** The chart moves + these rules from the operator's ClusterRole to a new Role and RoleBinding in the release + namespace. A deployer with cluster-admin rights needs no change. If you install the chart + with an identity that has limited RBAC rights, that identity must hold the new Role's + rules before you upgrade, because Kubernetes refuses to create a Role with rules its + creator does not hold: `get`, `list`, `watch` and `patch` on `daemonsets`, and `get`, + `list`, `watch` and `delete` on `pods`, in the release namespace. It also needs `create` + on `roles` and `rolebindings` there, and `bind` on the Role. A HostFleet whose + `daemonSet.namespace` is a different namespace now gets Forbidden. ([#1853]) - **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 +[#1853]: https://github.com/cortexapps/engrams/pull/1853 From bc697ec4fd2fd608098ff892e6cd99196d9a33e7 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Thu, 3 Dec 2026 09:13:41 -0800 Subject: [PATCH 16/17] test(coordinator): send the deployment bearer on the admin HTTP leg The coordinator HTTP router now fails closed when it has no auth tokens. The grpc_app fixture set only the app-gRPC tokens, so the HTTP leg of admin_pause_resume_preserves_state_and_error_mapping got 401. The fixture now gives the REST auth tokens the same list, and the HTTP request sends the bearer. Co-Authored-By: Claude Opus 5.5 --- crates/engram-coordinator/tests/grpc_app.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engram-coordinator/tests/grpc_app.rs b/crates/engram-coordinator/tests/grpc_app.rs index 5fa4ac19e..13de2003b 100644 --- a/crates/engram-coordinator/tests/grpc_app.rs +++ b/crates/engram-coordinator/tests/grpc_app.rs @@ -74,9 +74,8 @@ fn outbox_rows(meta: &SimMetadataStore) -> std::collections::BTreeMap) -> (Arc, Arc Date: Thu, 3 Dec 2026 09:14:12 -0800 Subject: [PATCH 17/17] docs(changelog): point the combined upgrade notes at #1860 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a05d85a75..b9fa47c0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +31,7 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu 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]) + `ENGRAM_OCI_ALLOW_INSECURE_LOOPBACK=1`; use it for local development only. ([#1860]) - **The host-fleet operator's DaemonSet and pod access is namespaced.** The chart moves these rules from the operator's ClusterRole to a new Role and RoleBinding in the release namespace. A deployer with cluster-admin rights needs no change. If you install the chart @@ -40,7 +40,7 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu creator does not hold: `get`, `list`, `watch` and `patch` on `daemonsets`, and `get`, `list`, `watch` and `delete` on `pods`, in the release namespace. It also needs `create` on `roles` and `rolebindings` there, and `bind` on the Role. A HostFleet whose - `daemonSet.namespace` is a different namespace now gets Forbidden. ([#1853]) + `daemonSet.namespace` is a different namespace now gets Forbidden. ([#1860]) - **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, @@ -70,7 +70,7 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu - The Helm value `orchestrator.connectionBrokerSecret` (`existingSecret`, `key`) gives the connection credential broker its own bearer. The chart sets it on the coordinator and the orchestrator. Unset, nothing changes: the broker uses the control-plane bearer. Set it - now: a later release will require it. ([#1859]) + now: a later release will require it. ([#1860]) ### Fixed @@ -479,6 +479,4 @@ The first tagged release. See the [#1826]: https://github.com/cortexapps/engrams/pull/1826 [#1849]: https://github.com/cortexapps/engrams/pull/1849 [#1850]: https://github.com/cortexapps/engrams/pull/1850 -[#1852]: https://github.com/cortexapps/engrams/pull/1852 -[#1853]: https://github.com/cortexapps/engrams/pull/1853 -[#1859]: https://github.com/cortexapps/engrams/pull/1859 +[#1860]: https://github.com/cortexapps/engrams/pull/1860