diff --git a/CHANGELOG.md b/CHANGELOG.md index 91e1ba4ff..99b069d0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,12 @@ 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 requires `ENGRAM_AUTH_TOKENS`.** An empty or unset value used to turn off + authentication on the internal HTTP routes that hosts call. It now refuses every such + request, so hosts cannot register or send heartbeats. Set the chart's + `auth.existingSecret` (the hosts send one of its tokens as `ENGRAM_COORDINATOR_TOKEN`) + before you upgrade. For local development only, `ENGRAM_ALLOW_INSECURE_INTERNAL_AUTH=1` + keeps the old behavior when no token is set. ([#1850]) - **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 +456,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 +[#1850]: https://github.com/cortexapps/engrams/pull/1850 diff --git a/Tiltfile b/Tiltfile index 6c5b2485d..dcb66a19f 100644 --- a/Tiltfile +++ b/Tiltfile @@ -408,6 +408,9 @@ if not bin_dir: otel_endpoint = env_or('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://localhost:4317') coord_env = { + # Local hosts can call internal routes without a deployment token. + 'ENGRAM_ALLOW_INSECURE_INTERNAL_AUTH': '1', + 'ENGRAM_AUTH_TOKENS': env_or('ENGRAM_AUTH_TOKENS', ''), '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 diff --git a/crates/engram-coordinator/src/api/auth.rs b/crates/engram-coordinator/src/api/auth.rs index ba9aa8e25..ce06fcb84 100644 --- a/crates/engram-coordinator/src/api/auth.rs +++ b/crates/engram-coordinator/src/api/auth.rs @@ -1,74 +1,64 @@ -//! Bearer-token middleware. -//! -//! Wraps every protected route. The check is constant-time-ish (linear -//! scan over a small token list, byte-by-byte comparison) — at v1 we -//! don't need a separate auth service or per-token rotation. -//! -//! The empty-list short-circuit (`AuthState::accepts_anything`) is -//! load-bearing: dev `just dev` and the in-process integration tests -//! both run without `ENGRAM_AUTH_TOKENS` set, and we don't want every -//! test to grow an `Authorization` header. Production deployments set -//! the env var. +//! Bearer-token middleware for internal HTTP routes. use std::sync::Arc; +use crate::auth::{constant_time_eq, extract_bearer_token}; + use axum::body::Body; use axum::extract::Request; use axum::http::{header, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; -/// Token allow-list snapshot. Built once at router-construction time -/// and shared across all handlers. We use `Arc<[String]>` rather than -/// reaching into `AppState.cfg` so the middleware doesn't depend on -/// the full state struct (smaller test surface, cheaper to clone). +/// Token allow-list and explicit development bypass. #[derive(Clone, Debug)] pub struct AuthState { tokens: Arc<[String]>, + allow_insecure: bool, } impl AuthState { - pub fn new(tokens: Vec) -> Self { + pub fn new(tokens: Vec, allow_insecure: bool) -> Self { Self { - tokens: tokens.into(), + tokens: tokens + .into_iter() + .map(|t| t.trim().to_owned()) + .filter(|t| !t.is_empty()) + .collect(), + allow_insecure, + } + } + + /// Log when no token is configured: the routes are open or reject all requests. + pub fn log_unauthenticated_posture(&self) { + if !self.tokens.is_empty() { + return; + } + if self.allow_insecure { + tracing::warn!( + "ENGRAM_AUTH_TOKENS is empty and ENGRAM_ALLOW_INSECURE_INTERNAL_AUTH=1: \ + internal HTTP routes accept requests without authentication" + ); + } else { + tracing::error!( + "ENGRAM_AUTH_TOKENS is empty: internal HTTP routes reject every request \ + until a token is configured" + ); } } fn accepts_anything(&self) -> bool { - self.tokens.is_empty() + self.allow_insecure && self.tokens.is_empty() } fn accepts(&self, candidate: &str) -> bool { - // Linear scan + constant-time byte compare per entry. Tokens - // are short and the list is small (single-digit), so a hash - // table would be overkill and would defeat constant-time - // comparison anyway. self.tokens .iter() - .any(|t| ct_eq(t.as_bytes(), candidate.as_bytes())) - } -} - -/// Constant-time byte comparison. We don't pull `subtle` as a dep — -/// this is one tight loop, dwarfed by the network round-trip, and the -/// `forbid(unsafe_code)` rule rules out the SIMD shortcut anyway. -fn ct_eq(a: &[u8], b: &[u8]) -> bool { - if a.len() != b.len() { - return false; - } - let mut acc = 0u8; - for (x, y) in a.iter().zip(b.iter()) { - acc |= x ^ y; + .any(|t| constant_time_eq(t.as_bytes(), candidate.as_bytes())) } - acc == 0 } -/// Axum middleware. Lets the request through if: -/// 1. Auth is disabled (empty token list), OR -/// 2. The request carries `Authorization: Bearer ` with `` in -/// the allow-list. -/// -/// Otherwise returns the standard JSON error envelope with 401. +/// Require a configured token unless the development bypass is enabled. pub async fn require_bearer( axum::extract::State(state): axum::extract::State, req: Request, @@ -83,8 +73,8 @@ pub async fn require_bearer( .get(header::AUTHORIZATION) .and_then(|v| v.to_str().ok()); - let token = match header_value.and_then(|h| h.strip_prefix("Bearer ")) { - Some(t) => t.trim(), + let token = match header_value.and_then(extract_bearer_token) { + Some(t) => t, None => return unauthorized("missing or malformed Authorization header"), }; @@ -96,10 +86,6 @@ pub async fn require_bearer( } fn unauthorized(msg: &str) -> Response { - // Reuse ApiError's JSON envelope so clients can match on `error` - // the same way they do for the rest of the surface. We don't have - // an `Unauthorized` variant in ApiError; status comes from a custom - // pair instead of leaking a 500. let body = axum::Json(serde_json::json!({ "error": "unauthorized", "message": msg, @@ -110,47 +96,69 @@ fn unauthorized(msg: &str) -> Response { #[cfg(test)] mod tests { use super::*; - - #[test] - fn empty_list_signals_dev_bypass_via_accepts_anything() { - // The bypass is a separate signal from `accepts`. The middleware - // checks `accepts_anything()` first and short-circuits; - // `accepts(t)` honestly answers "is `t` in the allow-list?", - // which for an empty list is always `false`. Splitting the two - // means a refactor that drops the bypass would fail loud - // instead of silently letting traffic through. - let s = AuthState::new(vec![]); - assert!(s.accepts_anything()); - assert!(!s.accepts("anything")); + use axum::{middleware, routing::get, Router}; + use tower::ServiceExt; + + async fn status(tokens: Vec, allow_insecure: bool, header: Option<&str>) -> StatusCode { + let app = + Router::new() + .route("/", get(|| async { "ok" })) + .layer(middleware::from_fn_with_state( + AuthState::new(tokens, allow_insecure), + require_bearer, + )); + let mut request = Request::builder().uri("/"); + if let Some(header) = header { + request = request.header("authorization", header); + } + app.oneshot(request.body(Body::empty()).unwrap()) + .await + .unwrap() + .status() } - #[test] - fn populated_list_rejects_outsiders() { - let s = AuthState::new(vec!["alpha".into(), "beta".into()]); - assert!(!s.accepts_anything()); - assert!(s.accepts("alpha")); - assert!(s.accepts("beta")); - assert!(!s.accepts("gamma")); - assert!(!s.accepts(""), "empty token must not be accepted"); + #[tokio::test] + async fn empty_configuration_fails_closed() { + for tokens in [vec![], vec!["".into(), " \t".into()]] { + for header in [None, Some("Bearer "), Some("Bearer token")] { + assert_eq!( + status(tokens.clone(), false, header).await, + StatusCode::UNAUTHORIZED + ); + } + } } - #[test] - fn ct_eq_distinguishes_lengths_and_contents() { - assert!(ct_eq(b"abc", b"abc")); - assert!(!ct_eq(b"abc", b"abcd")); - assert!(!ct_eq(b"abc", b"abd")); - assert!(ct_eq(b"", b"")); - assert!(!ct_eq(b"", b"x")); + #[tokio::test] + async fn development_bypass_requires_explicit_opt_in_and_no_tokens() { + assert_eq!(status(vec![], true, None).await, StatusCode::OK); + assert_eq!(status(vec![" ".into()], true, None).await, StatusCode::OK); + assert_eq!( + status(vec!["token".into()], true, None).await, + StatusCode::UNAUTHORIZED + ); } - #[test] - fn token_list_is_case_sensitive() { - // Bearer tokens are opaque: `Foo` and `foo` are different - // values, just like JWT secrets. This locks that behaviour - // in so a casing change in a future refactor would have to - // be deliberate. - let s = AuthState::new(vec!["Foo".into()]); - assert!(s.accepts("Foo")); - assert!(!s.accepts("foo")); + #[tokio::test] + async fn configured_tokens_are_filtered_and_presented_tokens_are_exact() { + let tokens = vec!["".into(), " ".into(), " Alpha ".into(), "beta".into()]; + for header in ["Bearer Alpha", "bearer beta"] { + assert_eq!( + status(tokens.clone(), false, Some(header)).await, + StatusCode::OK + ); + } + for header in [ + "Bearer ", + "Bearer alpha", + "Bearer Alpha ", + "Bearer Al pha", + "Basic Alpha", + ] { + assert_eq!( + status(tokens.clone(), false, Some(header)).await, + StatusCode::UNAUTHORIZED + ); + } } } diff --git a/crates/engram-coordinator/src/api/forge.rs b/crates/engram-coordinator/src/api/forge.rs index db4b7a1af..e8ed5eb9d 100644 --- a/crates/engram-coordinator/src/api/forge.rs +++ b/crates/engram-coordinator/src/api/forge.rs @@ -98,7 +98,7 @@ async fn op_fetch_credential( .meta .get_session_capabilities(session) .await - .unwrap_or_default(); + .map_err(|e| format!("read session capabilities: {e}"))?; // The git remote host (e.g. github.com); the integration validates it against // its own served host. This is the one caller that legitimately sets it. let hint = CredentialHint { @@ -302,3 +302,34 @@ async fn process_request(state: &SharedState, req: ForgeRequest) -> ForgeRespons } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn capability_read_failure_prevents_credential_minting() { + let clock = engram_sim::ManualClock::new(); + let meta = engram_sim::SimMetadataStore::new( + clock.clone(), + Arc::new(engram_sim::SimEntropy::seeded(1)), + ); + let state = crate::test_support::sim_state(meta.clone(), clock); + let forge = Arc::new(engram_git_dev::StaticGitHubIntegration::github( + "test-token", + )); + let engine: Arc = forge.clone(); + let session = SessionId::from(uuid::Uuid::from_u128(1)); + meta.set_outage(true); + let error = op_fetch_credential(&state, session, &engine, None, None) + .await + .unwrap_err(); + assert!(error.starts_with("read session capabilities:"), "{error}"); + assert!(forge.recorded_mint_caps().is_empty()); + meta.set_outage(false); + op_fetch_credential(&state, session, &engine, None, None) + .await + .unwrap(); + assert_eq!(forge.recorded_mint_caps(), vec![vec![]]); + } +} diff --git a/crates/engram-coordinator/src/api/host_http.rs b/crates/engram-coordinator/src/api/host_http.rs index 4dd1aaf42..eb2040cee 100644 --- a/crates/engram-coordinator/src/api/host_http.rs +++ b/crates/engram-coordinator/src/api/host_http.rs @@ -1670,24 +1670,30 @@ pub struct RefreshInjectResponse { pub expires_at: DateTime, } -/// WS4: the egress proxy's minted inject credential (a GitHub App installation -/// token, ~1h TTL) is nearing expiry on a long-lived session. Re-mint it against -/// the session's bound capabilities — the same scope `resolve_inject_entries` -/// used at boot — and hand back the fresh header + TTL. This closes the -/// campaign's reads-401/writes-succeed asymmetry: the boot-time inject token was -/// minted ONCE and went stale ~1h later while the askpass write path re-minted -/// per call. Fail-loud (4xx/5xx) so the proxy keeps the stale secret rather than -/// injecting an empty header; the mint itself is cached + single-flighted -/// server-side (`GitHubApp::mint_basic`), so a refresh burst re-mints once. +/// Refresh a credential for a non-terminal session bound to the requesting host. pub async fn refresh_inject( State(state): State, Path((host_id, session_id)): Path<(HostId, SessionId)>, Json(req): Json, ) -> Result, ApiError> { + let session = state.services.meta.get_session(session_id).await?; + // Check ownership first, so that a host cannot read the state of a + // session that it does not run. + if session.host_id != Some(host_id) { + return Err(ApiError::Forbidden(format!( + "session {session_id} is not assigned to host {host_id}" + ))); + } + if session.status.is_terminal() { + return Err(ApiError::Conflict(format!( + "session {session_id} is terminal ({})", + session.status.as_str() + ))); + } let (header_name, secret, expires_at) = if req.purpose.as_str() == "api" { let (header, expires_at) = crate::session_boot::refresh_inject_header(&state, session_id, &req.mint_source) - .await + .await? .ok_or_else(|| { ApiError::Internal(format!( "inject refresh for {:?} on session {session_id} could not be minted", @@ -1872,30 +1878,121 @@ mod tests { use crate::Services; use engram_core::traits::SandboxBackend; - fn sim_state( - meta: Arc, - clock: Arc, - ) -> SharedState { - let blob = Arc::new(engram_sim::MemBlobStorage::new()); - let services = Services { - meta: meta.clone(), - host: Arc::new(HostRegistry::new(meta)), - host_pool: Arc::new(engram_protocol::grpc_pool::GrpcHostPool::new()), - secrets: Arc::new(engram_secrets_dev::InMemorySecretStore::new()), - kek: Arc::new(engram_crypto::EnvVarKeyProvider::from_bytes( - [0u8; 32], "test:v1", - )), - oci: Arc::new(engram_oci::OciClient::new(Arc::new( - engram_oci::AnonymousResolver, - ))), - auth_resolver: Arc::new(engram_oci::AnonymousResolver), - blob: blob.clone(), - chunk_store: engram_chunk_store::ChunkStore::new(blob), - materialize_dir: None, - clock, - entropy: Arc::new(engram_sim::SimEntropy::seeded(0xF1EE7)), + use crate::test_support::sim_state; + + #[tokio::test] + async fn refresh_requires_a_bound_nonterminal_session() { + use engram_core::traits::MetadataStore; + use engram_core::types::integration::{CredentialMintSource, CredentialPurpose}; + let clock = engram_sim::ManualClock::new(); + let meta = engram_sim::SimMetadataStore::new( + clock.clone(), + Arc::new(engram_sim::SimEntropy::seeded(1)), + ); + let mut state = sim_state(meta.clone(), clock); + let forge = Arc::new(engram_git_dev::StaticGitHubIntegration::github( + "test-token", + )); + Arc::get_mut(&mut state).unwrap().integrations = + crate::integrations::IntegrationBroker::with(forge.clone()); + let session = meta + .create_session(engram_core::types::session::SessionSpec { + image: "test/image:v1".into(), + mode: Default::default(), + }) + .await + .unwrap(); + let host = HostId::from(uuid::Uuid::from_u128(1)); + let other = HostId::from(uuid::Uuid::from_u128(2)); + let missing = SessionId::from(uuid::Uuid::from_u128(3)); + let request = || { + Json(RefreshInjectRequest { + mint_source: CredentialMintSource::Connection { + connection_id: "test-connection".into(), + provider: "github".into(), + }, + purpose: CredentialPurpose::default(), + }) }; - Arc::new(AppState::new(CoordinatorConfig::default(), services)) + let call = + |host, session| refresh_inject(State(state.clone()), Path((host, session)), request()); + assert!(matches!( + call(host, missing).await, + Err(ApiError::NotFound(_)) + )); + assert!(matches!( + call(host, session).await, + Err(ApiError::Forbidden(_)) + )); + meta.assign_session_host(session, Some(host)).await.unwrap(); + assert!(matches!( + call(other, session).await, + Err(ApiError::Forbidden(_)) + )); + for status in [ + SessionState::Completed, + SessionState::Failed, + SessionState::Dead, + ] { + meta.with_db_mut(|db| db.sessions.get_mut(&session).unwrap().session.status = status); + assert!(matches!( + call(host, session).await, + Err(ApiError::Conflict(_)) + )); + assert!(matches!( + call(other, session).await, + Err(ApiError::Forbidden(_)) + )); + } + let remote_request = || { + Json(RefreshInjectRequest { + mint_source: CredentialMintSource::Connection { + connection_id: "test-connection".into(), + provider: "gcp".into(), + }, + purpose: CredentialPurpose::new("tunnel"), + }) + }; + assert!(matches!( + refresh_inject( + State(state.clone()), + Path((host, session)), + remote_request() + ) + .await, + Err(ApiError::Conflict(_)) + )); + meta.with_db_mut(|db| { + db.sessions.get_mut(&session).unwrap().session.status = SessionState::Active + }); + assert!(matches!( + refresh_inject( + State(state.clone()), + Path((other, session)), + remote_request() + ) + .await, + Err(ApiError::Forbidden(_)) + )); + assert!(matches!( + refresh_inject( + State(state.clone()), + Path((host, missing)), + remote_request() + ) + .await, + Err(ApiError::NotFound(_)) + )); + assert!(forge.recorded_mint_caps().is_empty()); + let response = call(host, session).await.unwrap(); + assert!(!response.secret.is_empty()); + assert_eq!(forge.recorded_mint_caps().len(), 1); + meta.set_outage(true); + assert!(matches!( + call(host, session).await, + Err(ApiError::Internal(_)) + )); + assert_eq!(forge.recorded_mint_caps().len(), 1); } /// Heartbeats within one window share a read; the next window reads diff --git a/crates/engram-coordinator/src/api/mod.rs b/crates/engram-coordinator/src/api/mod.rs index 8005af779..0c6058563 100644 --- a/crates/engram-coordinator/src/api/mod.rs +++ b/crates/engram-coordinator/src/api/mod.rs @@ -54,7 +54,11 @@ pub fn router(state: SharedState) -> Router { // pending their gRPC promotion) are authenticated. The orchestrator sends // CONTROL_PLANE_BEARER on those requests; ensure both tokens agree at // deploy time. - let auth_state = auth::AuthState::new(state.cfg.auth_tokens.clone()); + let auth_state = auth::AuthState::new( + state.cfg.auth_tokens.clone(), + state.cfg.allow_insecure_internal_auth, + ); + auth_state.log_unauthenticated_posture(); // ADR 0031 internal control-plane: host → coord ingestion. Machine // traffic authenticated by the deployment bearer (`require_bearer`). diff --git a/crates/engram-coordinator/src/api/session_auth.rs b/crates/engram-coordinator/src/api/session_auth.rs index da464d2b4..4dbced93e 100644 --- a/crates/engram-coordinator/src/api/session_auth.rs +++ b/crates/engram-coordinator/src/api/session_auth.rs @@ -1,26 +1,14 @@ -//! Shared per-session broker-token auth for the in-guest capability -//! seams. -//! -//! ADR 0023 minted a per-session opaque broker token to authorize the -//! forge bridge (git credential + PR). ADR 0026 generalizes it: the -//! same token also authorizes the artifact-upload bridge, and the check -//! no longer requires a forge to be configured (uploads aren't -//! git-gated). The token still lives in `state.git_broker_tokens` (the -//! name is historical); think of it as the session's broker token. +//! Per-session broker-token authentication for guest requests. use axum::http::HeaderMap; use engram_core::types::ids::SessionId; +use crate::auth::{constant_time_eq, extract_bearer_token}; use crate::state::SharedState; -/// Verify the per-session broker token in constant time. ADR 0047: the -/// in-memory map is a read-through cache over the KEK-sealed PG row, so -/// a guest request authorizes on ANY replica (the token may have been -/// minted by a sibling pod, or by this pod's prior life). Returns -/// `true` iff the session has a token and it matches. Does NOT require -/// `state.forge` — the forge seam layers its own forge-configured check -/// on top of this. +/// Read through the token cache to the sealed metadata row, then compare. +/// A missing token or a failed metadata read denies the request. pub(crate) async fn authorize_broker_token( state: &SharedState, session: SessionId, @@ -49,20 +37,7 @@ pub(crate) fn bearer(headers: &HeaderMap) -> Option { .get(axum::http::header::AUTHORIZATION)? .to_str() .ok()?; - v.strip_prefix("Bearer ").map(str::to_string) -} - -/// Length-independent byte comparison so a forged token can't be -/// recovered by timing the compare. -pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { - if a.len() != b.len() { - return false; - } - let mut diff = 0u8; - for (x, y) in a.iter().zip(b.iter()) { - diff |= x ^ y; - } - diff == 0 + extract_bearer_token(v).map(str::to_string) } #[cfg(test)] @@ -80,12 +55,4 @@ mod tests { basic.insert(AUTHORIZATION, HeaderValue::from_static("Basic tok123")); assert!(bearer(&basic).is_none()); } - - #[test] - fn constant_time_eq_compares_exactly() { - assert!(constant_time_eq(b"secret", b"secret")); - assert!(constant_time_eq(b"", b"")); - assert!(!constant_time_eq(b"secret", b"secres")); - assert!(!constant_time_eq(b"secret", b"secret-longer")); - } } diff --git a/crates/engram-coordinator/src/api/sessions.rs b/crates/engram-coordinator/src/api/sessions.rs index 531ac09cc..174ef6629 100644 --- a/crates/engram-coordinator/src/api/sessions.rs +++ b/crates/engram-coordinator/src/api/sessions.rs @@ -338,7 +338,7 @@ pub(crate) async fn build_resume_egress_policy( .unwrap_or_default(); let injects = crate::session_boot::resolve_inject_entries(state, session_id, policy.as_ref(), image) - .await; + .await?; let observes = crate::session_boot::build_observe_entries(policy.as_ref()); // ADR 0118: replay the session's apps from the persisted RuntimeSpec. A // resume that dropped them would silently kill the app-to-app short circuit diff --git a/crates/engram-coordinator/src/api/snapshot.rs b/crates/engram-coordinator/src/api/snapshot.rs index 3bb974af7..aa1a93d9a 100644 --- a/crates/engram-coordinator/src/api/snapshot.rs +++ b/crates/engram-coordinator/src/api/snapshot.rs @@ -681,10 +681,7 @@ pub(crate) async fn try_cancel_nominated_eviction( // (the exclusive claim requires no queued op). The RESULT threads // into the ascent: it is the causal half of the non-parked gate // (cancelled-a-queued-evict = the eviction never ran). - let cancelled_nomination = meta - .op_cancel_queued(id, OpKind::Evict) - .await - .unwrap_or(false); + let cancelled_nomination = meta.op_cancel_queued(id, OpKind::Evict).await?; // ADR 0079 (review finding #2): the ascent MUST run under a REAL op // claim, not the old `op_running_for == None` probe + unfenced @@ -732,14 +729,8 @@ pub(crate) async fn try_cancel_nominated_eviction( } } -/// The ADR 0074 rung-1/rung-2 ascent core: cancel any still-queued evict -/// ops, un-pause a parked-paused VM in place, clear the park stamp, and -/// flip the session back to `Active`. The CALLER guarantees no *foreign* -/// running op owns the session — either it probed `op_running_for` first -/// (the out-of-op wire path, [`try_cancel_nominated_eviction`], which -/// passes `SessionFence::unfenced()`) or it IS the running op (the -/// deliver verb, ADR 0079) and threads its own fence, which also stamps -/// the un-pause host RPC. +/// Cancel a queued eviction or unpause a parked VM, then return it to Active. +/// The caller holds an op claim and supplies its fence for every mutation. pub(crate) async fn ascend_evicting_to_active( state: &SharedState, id: SessionId, @@ -771,8 +762,7 @@ pub(crate) async fn ascend_evicting_to_active_with( .services .meta .op_cancel_queued(id, OpKind::Evict) - .await - .unwrap_or(false); + .await?; // ADR 0074 rung 2 (parked-paused ascent): if this session was parked // by PAUSING the VM in place (park_rung == 2), the sandbox is still // bound and alive — un-pause it BEFORE flipping the row back to @@ -780,10 +770,10 @@ pub(crate) async fn ascend_evicting_to_active_with( // Only commit the Active transition if the un-pause succeeds; a // failed un-pause leaves the session Evicting for the reaper/normal // resume path rather than advertising Active over a paused VM. - let row = state.services.meta.get_session(id).await.ok(); - let parked_paused = row.as_ref().map(|r| r.park_rung).unwrap_or(0) == 2; + let row = state.services.meta.get_session(id).await?; + let parked_paused = row.park_rung == 2; if parked_paused { - if let Some(sandbox_id) = row.as_ref().and_then(|r| r.sandbox_id) { + if let Some(sandbox_id) = row.sandbox_id { if let Err(e) = state.services.host.resume(sandbox_id, fence).await { tracing::warn!(session_id = %id, %sandbox_id, error = %e, "rung-2 ascent: un-pause failed; leaving session Evicting for the standard resume path"); @@ -845,7 +835,7 @@ pub(crate) async fn ascend_evicting_to_active_with( ascending, the settle lands Idle and the resume retries"); return Ok(false); } - let Some(sandbox_id) = row.as_ref().and_then(|r| r.sandbox_id) else { + let Some(sandbox_id) = row.sandbox_id else { tracing::debug!(session_id = %id, "ascent: evicting session has no bound sandbox; leaving it to the settle"); return Ok(false); @@ -3283,3 +3273,41 @@ mod resume_queue_fence_tests { ); } } + +#[cfg(test)] +mod cancellation_failure_tests { + use super::*; + use std::sync::Arc; + + #[tokio::test] + async fn eviction_cancel_store_failure_returns_error() { + let clock = engram_sim::ManualClock::new(); + let meta = engram_sim::SimMetadataStore::new( + clock.clone(), + Arc::new(engram_sim::SimEntropy::seeded(1)), + ); + let state = crate::test_support::sim_state(meta.clone(), clock); + meta.set_outage(true); + let id = SessionId::from(uuid::Uuid::from_u128(1)); + assert!(matches!( + try_cancel_nominated_eviction(&state, id).await, + Err(ApiError::Internal(_)) + )); + assert!(matches!( + ascend_evicting_to_active_with(&state, id, SessionFence::unfenced(), false).await, + Err(ApiError::Internal(_)) + )); + assert!(matches!( + ascend_evicting_to_active_with(&state, id, SessionFence::unfenced(), true).await, + Err(ApiError::Internal(_)) + )); + meta.set_outage(false); + assert!(state + .services + .meta + .op_running_for(id) + .await + .unwrap() + .is_none()); + } +} diff --git a/crates/engram-coordinator/src/auth.rs b/crates/engram-coordinator/src/auth.rs new file mode 100644 index 000000000..202410697 --- /dev/null +++ b/crates/engram-coordinator/src/auth.rs @@ -0,0 +1,66 @@ +//! Shared bearer parsing and token comparison. + +/// Compare secrets in time that depends only on their lengths. +pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + let diff = a + .iter() + .zip(b) + .fold(0u8, |acc, (x, y)| std::hint::black_box(acc | (x ^ y))); + diff == 0 +} + +/// Parse `Bearer ` (RFC 6750 section 2.1). The scheme is +/// case-insensitive (RFC 9110 section 11.1); the token is not empty and has +/// no whitespace. +pub(crate) fn extract_bearer_token(header: &str) -> Option<&str> { + let (scheme, rest) = header.split_once(' ')?; + if !scheme.eq_ignore_ascii_case("Bearer") { + return None; + } + let token = rest.trim_start_matches(' '); + (!token.is_empty() && !token.chars().any(char::is_whitespace)).then_some(token) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn comparison_checks_lengths_and_contents() { + assert!(constant_time_eq(b"secret", b"secret")); + assert!(constant_time_eq(b"", b"")); + assert!(!constant_time_eq(b"secret", b"secres")); + assert!(!constant_time_eq(b"secret", b"Secret")); + assert!(!constant_time_eq(b"secret", b"secret-longer")); + } + + #[test] + fn bearer_scheme_is_case_insensitive_and_token_is_exact() { + for (header, token) in [ + ("Bearer tok+/=_-.~123", "tok+/=_-.~123"), + ("bearer Tok", "Tok"), + ("BEARER Tok", "Tok"), + ("Bearer Tok", "Tok"), + ] { + assert_eq!(extract_bearer_token(header), Some(token), "{header:?}"); + } + for header in [ + "", + "Basic token", + "Bearertoken", + "Bearer", + "Bearer ", + "Bearer token ", + "Bearer to ken", + "Bearer\ttoken", + "Bearer token\t", + "Bearer token\n", + " Bearer token", + ] { + assert_eq!(extract_bearer_token(header), None, "{header:?}"); + } + } +} diff --git a/crates/engram-coordinator/src/config.rs b/crates/engram-coordinator/src/config.rs index e1361a40c..67e21a97a 100644 --- a/crates/engram-coordinator/src/config.rs +++ b/crates/engram-coordinator/src/config.rs @@ -11,15 +11,11 @@ pub struct CoordinatorConfig { pub local_path: PathBuf, pub sandbox_backend: SandboxBackendChoice, pub default_image_version: String, - /// Bearer tokens accepted on protected endpoints. Empty = auth - /// disabled (dev mode). When non-empty, every request to anything - /// other than `/healthz` must carry `Authorization: Bearer ` - /// where `` is in this list. - /// - /// Stored as plaintext in memory — the production deployment is - /// expected to source tokens from a secret manager and rotate - /// the process; for v1 we don't hot-reload. + /// Bearer tokens accepted on internal HTTP routes. Empty rejects all requests + /// unless `allow_insecure_internal_auth` is explicitly enabled. pub auth_tokens: Vec, + /// Permit unauthenticated internal HTTP requests when no tokens are configured. + pub allow_insecure_internal_auth: bool, // ADR 0051: the ADR 0031 human-authentication config (the former // `engram-auth` AuthConfig) is removed along with the whole `engram-auth` // crate. The coordinator no longer resolves human identity — `auth_tokens` @@ -43,7 +39,7 @@ pub struct CoordinatorConfig { /// (different caller, different blast radius, independently /// rotatable). More than one entry only during rotation overlap. /// - /// Unlike `auth_tokens`, empty does NOT mean "auth disabled": + /// An empty list rejects all requests: /// this surface fails closed — no configured tokens, every call /// answers `unauthenticated` (boot is unaffected). pub app_grpc_tokens: Vec, @@ -70,10 +66,8 @@ impl Default for CoordinatorConfig { local_path: PathBuf::from("./var/engram"), sandbox_backend: SandboxBackendChoice::Firecracker, default_image_version: "warm-bootstrap".into(), - // Empty = auth disabled. Production deployments populate - // this from `ENGRAM_AUTH_TOKENS` (or a future secret-store - // hookup) at startup. auth_tokens: Vec::new(), + allow_insecure_internal_auth: false, harness_listen_addr: "127.0.0.1:0" .parse() .expect("default harness_listen_addr must parse"), diff --git a/crates/engram-coordinator/src/grpc_app/auth.rs b/crates/engram-coordinator/src/grpc_app/auth.rs index bfed098c8..810c35010 100644 --- a/crates/engram-coordinator/src/grpc_app/auth.rs +++ b/crates/engram-coordinator/src/grpc_app/auth.rs @@ -1,14 +1,6 @@ -//! Machine auth for the app-gRPC surface (ADR 0051 §5): one trusted -//! caller (the orchestrator), one static bearer, constant-time compare. -//! Fail closed: no configured tokens = reject everything. -//! -//! Deliberately a *separate credential* from the host-agents' -//! `ENGRAM_AUTH_TOKENS` (`api/auth.rs`): different caller, different -//! blast radius, independently rotatable. And deliberately the -//! *opposite* dev posture from `api/auth.rs`'s `accepts_anything()` -//! empty-list bypass — this surface is born strict, so a deployment -//! that forgets `ENGRAM_APP_GRPC_TOKENS` serves `unauthenticated` -//! instead of an open admin plane. Boot is unaffected either way. +//! Machine auth for the app-gRPC surface. Empty token lists reject all requests. + +use crate::auth::{constant_time_eq, extract_bearer_token}; /// Static bearer allow-list for the app-gRPC services. Built once at /// server construction from `CoordinatorConfig::app_grpc_tokens` and @@ -19,48 +11,31 @@ pub struct BearerAuth { } impl BearerAuth { - /// Drops empty-string tokens at construction: an empty token can - /// never be valid credentials (and would otherwise match an empty - /// presented bearer). The CLI layer in `main.rs` already filters - /// these out; this is defense in depth for other construction sites - /// (tests, future callers) that don't. + /// Discard empty tokens and whitespace around configured values. pub fn new(tokens: Vec) -> Self { Self { - tokens: tokens.into_iter().filter(|t| !t.is_empty()).collect(), + tokens: tokens + .into_iter() + .map(|t| t.trim().to_owned()) + .filter(|t| !t.is_empty()) + .collect(), } } - /// Per-RPC check, called at the top of every stub. Sync on purpose - /// — a metadata lookup plus a constant-time compare doesn't earn a - /// tower layer. - // - // `clippy::result_large_err`: `tonic::Status` is ~176 bytes, but it's - // the error type tonic mandates on every RPC return anyway, so the - // `?` at each call site flows straight into a `Result<_, Status>` — - // boxing here would just force an unbox at every call. The lint - // doesn't fire on the trait-impl RPCs (you can't change a trait - // method's signature); it fires here only because `check` is an - // inherent method with the same unavoidable error type. + /// Check the bearer token before the RPC reads or changes state. + // tonic requires Status as the RPC error type. #[allow(clippy::result_large_err)] pub fn check(&self, req: &tonic::Request) -> Result<(), tonic::Status> { let presented = req .metadata() .get("authorization") .and_then(|v| v.to_str().ok()) - // Byte-exact, case-sensitive scheme match: RFC 9110 makes the - // `Bearer` scheme token case-insensitive, but we deliberately - // don't honor that — one in-house machine caller we control, - // which always sends exactly `Bearer `, so a stricter match is - // a smaller surface with zero real-world cost. - .and_then(|v| v.strip_prefix("Bearer ")) + .and_then(extract_bearer_token) .ok_or_else(|| tonic::Status::unauthenticated("missing bearer token"))?; - // Linear scan + constant-time byte compare per entry, the same - // shape as `api::auth`'s `ct_eq` (an empty `tokens` list never - // matches, which is exactly the fail-closed posture we want). if self .tokens .iter() - .any(|t| ct_eq(t.as_bytes(), presented.as_bytes())) + .any(|t| constant_time_eq(t.as_bytes(), presented.as_bytes())) { Ok(()) } else { @@ -69,20 +44,6 @@ impl BearerAuth { } } -/// Constant-time byte comparison; mirrors `api::auth::ct_eq` (private -/// there, and that file is frozen — it guards host ingest). One tight -/// loop, dwarfed by the network round-trip; not worth a `subtle` dep. -fn ct_eq(a: &[u8], b: &[u8]) -> bool { - if a.len() != b.len() { - return false; - } - let mut acc = 0u8; - for (x, y) in a.iter().zip(b.iter()) { - acc |= x ^ y; - } - acc == 0 -} - #[cfg(test)] mod tests { use super::*; @@ -140,10 +101,9 @@ mod tests { #[test] fn empty_token_set_fails_closed() { - // The opposite of `api/auth.rs`'s `accepts_anything()` dev - // bypass, on purpose: no configured tokens means NOTHING is - // accepted on this surface — not even an empty bearer. - let auth = BearerAuth::new(vec![]); + let empty = BearerAuth::new(vec![]); + assert!(empty.check(&req_with_bearer("anything")).is_err()); + let auth = BearerAuth::new(vec!["".into(), " \t".into()]); let err = auth.check(&req_with_bearer("anything")).unwrap_err(); assert_eq!(err.code(), tonic::Code::Unauthenticated); let err = auth.check(&req_with_bearer("")).unwrap_err(); diff --git a/crates/engram-coordinator/src/lib.rs b/crates/engram-coordinator/src/lib.rs index 30353e314..1424e9067 100644 --- a/crates/engram-coordinator/src/lib.rs +++ b/crates/engram-coordinator/src/lib.rs @@ -10,6 +10,7 @@ use std::sync::Arc; use engram_core::traits::{BlobStorage, HostClient, MetadataStore, SecretStore}; pub mod api; +mod auth; pub mod base_snapshot_retention; pub mod boot_bundle; pub mod boot_materializer; @@ -54,6 +55,8 @@ mod span_parenting_tests; pub mod squashfs; pub mod state; pub mod teleport; +#[cfg(test)] +mod test_support; pub use config::CoordinatorConfig; pub use error::ApiError; diff --git a/crates/engram-coordinator/src/main.rs b/crates/engram-coordinator/src/main.rs index 77621b85c..320080569 100644 --- a/crates/engram-coordinator/src/main.rs +++ b/crates/engram-coordinator/src/main.rs @@ -52,10 +52,8 @@ struct Cli { #[arg(long, env = "ENGRAM_DEFAULT_IMAGE", default_value = "warm-bootstrap")] default_image_version: String, - /// Comma-separated list of bearer tokens accepted on protected - /// endpoints. Empty (the default) disables auth and is intended - /// for local dev only. Production deployments populate this from - /// `ENGRAM_AUTH_TOKENS`. + /// Comma-separated bearer tokens for internal HTTP routes. + /// Empty rejects all requests unless ENGRAM_ALLOW_INSECURE_INTERNAL_AUTH=1. #[arg( long, env = "ENGRAM_AUTH_TOKENS", @@ -73,17 +71,13 @@ struct Cli { )] harness_listen_addr: std::net::SocketAddr, - /// Address the orchestrator-facing app gRPC server binds to (ADR 0051). + /// Address the orchestrator-facing app gRPC server binds to. #[arg(long, env = "ENGRAM_APP_GRPC_ADDR", default_value = "127.0.0.1:50061")] app_grpc_addr: std::net::SocketAddr, - /// Comma-separated bearer tokens accepted on the app gRPC surface - /// (ADR 0051 §5) — the orchestrator's machine credential, separate - /// from `--auth-tokens` (different caller, different blast radius, - /// independently rotatable; >1 entry only during rotation overlap). - /// Unlike `--auth-tokens`, empty does NOT disable auth: the app - /// surface fails closed and rejects every call until a token is - /// configured. Boot is unaffected. + /// Comma-separated bearer tokens for the app gRPC surface. + /// These are separate from the internal HTTP tokens. An empty list rejects + /// every app gRPC call, including when insecure internal HTTP is enabled. #[arg( long, env = "ENGRAM_APP_GRPC_TOKENS", @@ -363,29 +357,14 @@ async fn main() -> Result<(), CoordinatorError> { local_path: cli.local_path.clone(), sandbox_backend: cli.sandbox_backend, default_image_version: cli.default_image_version.clone(), - // clap's value_delimiter splits even an empty default into a - // single "" entry — strip those so an unset env reads as truly - // empty (auth-off) rather than "exactly one token: empty string". - auth_tokens: cli - .auth_tokens - .iter() - .filter(|t| !t.is_empty()) - .cloned() - .collect(), + auth_tokens: cli.auth_tokens.clone(), + allow_insecure_internal_auth: std::env::var("ENGRAM_ALLOW_INSECURE_INTERNAL_AUTH") + .as_deref() + == Ok("1"), harness_listen_addr: cli.harness_listen_addr, app_grpc_addr: cli.app_grpc_addr, - // Same empty-entry stripping as `auth_tokens` above (clap's - // value_delimiter turns an unset env into one "" entry), plus - // trim so `a, b` rotation lists don't mint a " b" token. An - // empty result fails closed in grpc_app — never auth-off. - app_grpc_tokens: cli - .app_grpc_tokens - .iter() - .map(|t| t.trim().to_string()) - .filter(|t| !t.is_empty()) - .collect(), - // Treat a set-but-empty env var as unset (same reasoning as the - // token lists above) — an empty committer email must not stamp. + app_grpc_tokens: cli.app_grpc_tokens.clone(), + // An empty committer email must not stamp. git_committer_email: cli.git_committer_email.clone().filter(|e| !e.is_empty()), git_committer_name: cli.git_committer_name.clone(), }; diff --git a/crates/engram-coordinator/src/session_boot.rs b/crates/engram-coordinator/src/session_boot.rs index b085393d5..7468a31cd 100644 --- a/crates/engram-coordinator/src/session_boot.rs +++ b/crates/engram-coordinator/src/session_boot.rs @@ -284,10 +284,7 @@ pub(crate) async fn boot_on_reserved_host( if let Some(a) = agent.as_mut() { crate::api::sessions::inject_harness_env(state, session_id, &mut a.env).await?; } - Ok::<_, ApiError>( - resolve_inject_entries(state, session_id, integration_policy.as_ref(), &image_ref) - .await, - ) + resolve_inject_entries(state, session_id, integration_policy.as_ref(), &image_ref).await }; // Issue #535 correction: neither `coord_prepare` nor `coord_finalize` // covers this join itself — `coord_finalize` only starts once it @@ -822,31 +819,16 @@ pub(crate) fn build_observe_entries( .collect() } -/// ADR 0056 (B′): resolve an integration policy's Plane-B injections into -/// host-side egress entries. Each inject's `secret_ref` is resolved via the -/// deployment `SecretStore` (the session's image ref is the lookup context); -/// the resolved value rides the policy to the host, never to the orchestrator -/// or guest. A ref that doesn't resolve is skipped + logged (the connector -/// gates the request regardless, but without a credential it would fail -/// upstream — so we drop it rather than inject an empty header). -/// Lossy by design: a resolution failure (secret-store error, failed -/// mint, a capabilities lookup error under a mint entry) skips that -/// entry and the session boots with a reduced policy — the user is -/// present to retry, and the mint refresh seam repairs stale entries -/// on first use. Structurally invalid entries (no `mint_source` AND an -/// empty `secret_ref` — the "mutually exclusive" invariant on -/// `IntegrationInject` violated) are persistent config state: they are -/// skipped before any store call and reported once, aggregated, not -/// per-entry (prod 2026-08-03: 77 such entries logged 77 WARNs per -/// resume and starved the retry machinery built for transients). +/// Resolve the host-side inject entries. Capability read errors stop the boot. +/// Invalid entries and unavailable credentials are logged and omitted. pub(crate) async fn resolve_inject_entries( state: &SharedState, session_id: SessionId, integration_policy: Option<&engram_core::types::IntegrationPolicy>, image: &str, -) -> Vec { +) -> Result, ApiError> { let Some(policy) = integration_policy else { - return Vec::new(); + return Ok(Vec::new()); }; let structurally_invalid = policy .injects @@ -872,19 +854,11 @@ pub(crate) async fn resolve_inject_entries( // ADR 0056 amendment: mint entries scope their token to the session's bound // capabilities. Fetch them once, only when a mint entry is actually present. let caps = if policy.injects.iter().any(|i| i.mint_source.is_some()) { - match state + state .services .meta .get_session_capabilities(session_id) - .await - { - Ok(c) => c, - Err(e) => { - tracing::warn!(%session_id, error = %e, - "capabilities lookup failed under a mint inject; minting unscoped"); - Vec::new() - } - } + .await? } else { Vec::new() }; @@ -982,7 +956,7 @@ pub(crate) async fn resolve_inject_entries( }; out.push(entry); } - out + Ok(out) } /// ADR 0056 amendment: resolve a connection's egress inject header — mint a @@ -1264,28 +1238,25 @@ pub(crate) async fn mint_remote_connection_credential( } } -/// WS4: re-mint the egress inject header for a single provider on demand — the -/// reusable core the proxy-refresh route (`POST /hosts/:id/sessions/:sid/ -/// inject/refresh`) runs when the proxy's minted credential nears expiry. Fetches -/// the session's bound capabilities (the same scope `resolve_inject_entries` uses -/// at boot) and re-runs the mint. Returns the freshly rendered header + its new -/// `expires_at`, or `None` (logged in `mint_inject_header`) on any failure — the -/// proxy then keeps the stale secret rather than failing the request. +/// Refresh an inject credential with the session's bound capabilities. +/// Metadata errors stop the refresh before any credential is minted. pub(crate) async fn refresh_inject_header( state: &SharedState, session_id: SessionId, source: &CredentialMintSource, -) -> Option<( - engram_core::traits::InjectHeader, - chrono::DateTime, -)> { +) -> Result< + Option<( + engram_core::traits::InjectHeader, + chrono::DateTime, + )>, + ApiError, +> { let caps = state .services .meta .get_session_capabilities(session_id) - .await - .unwrap_or_default(); - mint_inject_header(state, session_id, source, &caps).await + .await?; + Ok(mint_inject_header(state, session_id, source, &caps).await) } // Issue #535 (b): `persist_integration_policy` (ADR 0056 B′) retired — the @@ -1391,3 +1362,62 @@ mod capture_egress_tests { ); } } + +#[cfg(test)] +mod credential_tests { + use super::*; + use engram_core::types::integration::{IntegrationInject, IntegrationPolicy}; + use std::sync::Arc; + + #[tokio::test] + async fn capability_read_failure_stops_boot_and_refresh_mints() { + let clock = engram_sim::ManualClock::new(); + let meta = engram_sim::SimMetadataStore::new( + clock.clone(), + Arc::new(engram_sim::SimEntropy::seeded(1)), + ); + let mut state = crate::test_support::sim_state(meta.clone(), clock); + let forge = Arc::new(engram_git_dev::StaticGitHubIntegration::github( + "test-token", + )); + Arc::get_mut(&mut state).unwrap().integrations = + crate::integrations::IntegrationBroker::with(forge.clone()); + let source = CredentialMintSource::Connection { + connection_id: "test-connection".into(), + provider: "github".into(), + }; + let policy = IntegrationPolicy { + injects: vec![IntegrationInject { + hosts: vec!["api.github.com".into()], + header_name: "Authorization".into(), + header_template: "Bearer {}".into(), + secret_ref: String::new(), + mint_source: Some(source.clone()), + methods: vec![], + path_globs: vec![], + graphql_operation: String::new(), + graphql_field: String::new(), + }], + ..Default::default() + }; + let session = SessionId::from(uuid::Uuid::from_u128(1)); + meta.set_outage(true); + assert!(matches!( + resolve_inject_entries(&state, session, Some(&policy), "test/image:v1").await, + Err(ApiError::Internal(_)) + )); + assert!(matches!( + refresh_inject_header(&state, session, &source).await, + Err(ApiError::Internal(_)) + )); + assert!(forge.recorded_mint_caps().is_empty()); + meta.set_outage(false); + resolve_inject_entries(&state, session, Some(&policy), "test/image:v1") + .await + .unwrap(); + refresh_inject_header(&state, session, &source) + .await + .unwrap(); + assert_eq!(forge.recorded_mint_caps(), vec![vec![], vec![]]); + } +} diff --git a/crates/engram-coordinator/src/test_support.rs b/crates/engram-coordinator/src/test_support.rs new file mode 100644 index 000000000..5a42a4c80 --- /dev/null +++ b/crates/engram-coordinator/src/test_support.rs @@ -0,0 +1,35 @@ +//! Deterministic state fixture for coordinator unit tests. + +use crate::{ + config::CoordinatorConfig, + host_registry::HostRegistry, + state::{AppState, SharedState}, + Services, +}; +use std::sync::Arc; + +pub(crate) fn sim_state( + meta: Arc, + clock: Arc, +) -> SharedState { + let blob = Arc::new(engram_sim::MemBlobStorage::new()); + let services = Services { + meta: meta.clone(), + host: Arc::new(HostRegistry::new(meta)), + host_pool: Arc::new(engram_protocol::grpc_pool::GrpcHostPool::new()), + secrets: Arc::new(engram_secrets_dev::InMemorySecretStore::new()), + kek: Arc::new(engram_crypto::EnvVarKeyProvider::from_bytes( + [0u8; 32], "test:v1", + )), + oci: Arc::new(engram_oci::OciClient::new(Arc::new( + engram_oci::AnonymousResolver, + ))), + auth_resolver: Arc::new(engram_oci::AnonymousResolver), + blob: blob.clone(), + chunk_store: engram_chunk_store::ChunkStore::new(blob), + materialize_dir: None, + clock, + entropy: Arc::new(engram_sim::SimEntropy::seeded(0xF1EE7)), + }; + Arc::new(AppState::new(CoordinatorConfig::default(), services)) +} diff --git a/crates/engram-coordinator/tests/api.rs b/crates/engram-coordinator/tests/api.rs index 87060fedd..93778d8b1 100644 --- a/crates/engram-coordinator/tests/api.rs +++ b/crates/engram-coordinator/tests/api.rs @@ -1,12 +1,4 @@ -//! Integration test for the coordinator HTTP API. -//! -//! Wires the real `axum` router against an in-memory `MetadataStore`, -//! a `MockCloud`, a `LocalStorage` blob backend, and `ProcessBackend` -//! (the dev-loop SandboxBackend that runs commands as host -//! subprocesses), then drives the surface via -//! `tower::ServiceExt::oneshot`. The goal is to lock down the public -//! contract — status codes, JSON error envelope, the routing table — -//! while exercising real exec round-trips end-to-end. +//! HTTP routing, authentication, and heartbeat tests over an in-memory store. // tests drive a live system; wall clock/OS entropy here is input, not a decision source (ADR 0098 D1) #![allow(clippy::disallowed_methods)] @@ -46,8 +38,7 @@ async fn build_app(meta: Arc) -> axum::Router { } /// Like `build_app` but seeds the bearer-token allow-list. Used by the -/// auth middleware tests; everything else relies on the default empty -/// list (auth-disabled). +/// auth middleware tests. Other fixtures explicitly enable the development bypass. fn build_app_with_tokens(meta: Arc, tokens: Vec) -> axum::Router { let sandbox_dir = tempfile::tempdir().expect("sandbox tempdir").keep(); let services = Services { @@ -133,6 +124,7 @@ async fn build_forge_app() -> ( entropy: Arc::new(engram_core::traits::OsEntropy), }; let cfg = CoordinatorConfig { + allow_insecure_internal_auth: true, default_image_version: "warm-bootstrap".into(), ..CoordinatorConfig::default() }; @@ -302,6 +294,7 @@ impl TestFixture { entropy: Arc::new(engram_core::traits::OsEntropy), }; let cfg = CoordinatorConfig { + allow_insecure_internal_auth: true, default_image_version: "warm-bootstrap".into(), ..CoordinatorConfig::default() }; @@ -379,12 +372,7 @@ fn json_request(method: Method, uri: &str, body: Value) -> Request { // Bearer-token middleware // --------------------------------------------------------------------- -// ADR 0031: the deployment bearer no longer gates *human* routes — those are -// authenticated by the principal layer (cookie / service-bearer / synthetic). -// The bearer now guards only the `internal` control-plane router (host → -// coord ingestion). These tests target an internal route (`/hosts/register`) -// to exercise that gate. A separate test below confirms human routes are -// principal-authed (synthetic admin → 200) regardless of the bearer. +// The deployment bearer protects host ingestion and internal control routes. const INTERNAL_ROUTE: &str = "/api/v1/hosts/register"; @@ -481,15 +469,6 @@ async fn healthz_returns_ok_status_and_version() { assert!(v["version"].is_string()); } -// --------------------------------------------------------------------- -// End-to-end exec wiring (POST /sessions → registry → sandbox.exec) -// -// The registry is in-process state owned by AppState. Tests that need -// create→exec to share state must reuse the *same* `axum::Router` -// across requests (cloning the Router is fine — it shares the -// Arc internally). -// --------------------------------------------------------------------- - #[tokio::test] async fn unknown_route_returns_404() { let app = build_app(sim_meta()).await; @@ -558,3 +537,17 @@ async fn heartbeat_persist_failure_returns_5xx_not_swallowed_200() { "healthy persist should ack 200", ); } + +#[tokio::test] +async fn empty_auth_configuration_rejects_internal_requests() { + let app = build_app_with_tokens(sim_meta(), vec![]); + let response = app + .oneshot( + Request::post("/api/v1/hosts/register") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); +} diff --git a/crates/engram-coordinator/tests/oauth_inject_refresh.rs b/crates/engram-coordinator/tests/oauth_inject_refresh.rs index 4606f3af4..8f4e69d02 100644 --- a/crates/engram-coordinator/tests/oauth_inject_refresh.rs +++ b/crates/engram-coordinator/tests/oauth_inject_refresh.rs @@ -30,9 +30,10 @@ struct Fixture { meta: Arc, clock: Arc, kek: EnvVarKeyProvider, + session_id: engram_core::SessionId, } -fn fixture() -> Fixture { +async fn fixture() -> Fixture { let clock = ManualClock::new(); let entropy = Arc::new(SimEntropy::seeded(24)); let meta = SimMetadataStore::new(clock.clone(), entropy.clone()); @@ -64,9 +65,27 @@ fn fixture() -> Fixture { clock: clock.clone(), entropy, }; - let state = Arc::new(AppState::new(CoordinatorConfig::default(), services)); + let session_id = meta + .create_session(engram_core::types::session::SessionSpec { + image: "test/image:v1".into(), + mode: Default::default(), + }) + .await + .unwrap(); + meta.assign_session_host( + session_id, + Some(engram_core::HostId::from(uuid::Uuid::from_u128(1))), + ) + .await + .unwrap(); + let cfg = CoordinatorConfig { + allow_insecure_internal_auth: true, + ..Default::default() + }; + let state = Arc::new(AppState::new(cfg, services)); Fixture { app: api::router(state), + session_id, meta, clock, kek: EnvVarKeyProvider::from_bytes([0u8; 32], "test:v1"), @@ -121,9 +140,9 @@ async fn seed_bundle_for(fx: &Fixture, key: OAuthCredentialKey, bundle: &Connect .expect("seed credential"); } -async fn refresh_call(app: axum::Router) -> (StatusCode, Value) { +async fn refresh_call(fx: &Fixture) -> (StatusCode, Value) { refresh_call_with( - app, + fx, json!({ "mint_source": { "oauth_connector": { @@ -136,18 +155,18 @@ async fn refresh_call(app: axum::Router) -> (StatusCode, Value) { .await } -async fn refresh_call_with(app: axum::Router, body: Value) -> (StatusCode, Value) { +async fn refresh_call_with(fx: &Fixture, body: Value) -> (StatusCode, Value) { let req = Request::builder() .method(Method::POST) .uri(format!( "/api/v1/hosts/{}/sessions/{}/inject/refresh", uuid::Uuid::from_u128(1), - uuid::Uuid::from_u128(2), + fx.session_id, )) .header("content-type", "application/json") .body(Body::from(body.to_string())) .unwrap(); - let resp = app.oneshot(req).await.unwrap(); + let resp = fx.app.clone().oneshot(req).await.unwrap(); let status = resp.status(); let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20) .await @@ -158,7 +177,7 @@ async fn refresh_call_with(app: axum::Router, body: Value) -> (StatusCode, Value #[tokio::test] async fn refresh_route_returns_the_sealed_raw_token() { - let fx = fixture(); + let fx = fixture().await; seed_bundle( &fx, &ConnectorOAuthBundle { @@ -175,7 +194,7 @@ async fn refresh_route_returns_the_sealed_raw_token() { }, ) .await; - let (status, body) = refresh_call(fx.app.clone()).await; + let (status, body) = refresh_call(&fx).await; assert_eq!(status, StatusCode::OK, "{body}"); assert_eq!(body["secret"], "at-sealed"); } @@ -205,7 +224,7 @@ async fn refresh_route_refreshes_an_expired_bundle_against_the_provider() { axum::serve(listener, router).await.unwrap(); }); - let fx = fixture(); + let fx = fixture().await; let now = fx.clock.now_utc(); seed_bundle( &fx, @@ -230,7 +249,7 @@ async fn refresh_route_refreshes_an_expired_bundle_against_the_provider() { }, ) .await; - let (status, body) = refresh_call(fx.app.clone()).await; + let (status, body) = refresh_call(&fx).await; assert_eq!(status, StatusCode::OK, "{body}"); assert_eq!(body["secret"], "at-rotated"); assert_eq!( @@ -242,8 +261,8 @@ async fn refresh_route_refreshes_an_expired_bundle_against_the_provider() { #[tokio::test] async fn refresh_route_fails_when_no_credential_exists() { - let fx = fixture(); - let (status, _body) = refresh_call(fx.app.clone()).await; + let fx = fixture().await; + let (status, _body) = refresh_call(&fx).await; assert_eq!( status, StatusCode::INTERNAL_SERVER_ERROR, @@ -269,7 +288,7 @@ fn oauth_user_body() -> Value { /// sessions within a day. #[tokio::test] async fn refresh_route_resolves_a_user_static_token_with_a_daily_horizon() { - let fx = fixture(); + let fx = fixture().await; seed_bundle_for( &fx, user_key(), @@ -286,7 +305,7 @@ async fn refresh_route_resolves_a_user_static_token_with_a_daily_horizon() { }, ) .await; - let (status, body) = refresh_call_with(fx.app.clone(), oauth_user_body()).await; + let (status, body) = refresh_call_with(&fx, oauth_user_body()).await; assert_eq!(status, StatusCode::OK, "{body}"); assert_eq!(body["secret"], "personal-pat"); let expires: chrono::DateTime = body["expires_at"] @@ -306,7 +325,7 @@ async fn refresh_route_resolves_a_user_static_token_with_a_daily_horizon() { /// user credential fails the route so the proxy keeps its stale secret. #[tokio::test] async fn refresh_route_keeps_user_and_connector_subjects_apart() { - let fx = fixture(); + let fx = fixture().await; seed_bundle( &fx, &ConnectorOAuthBundle { @@ -322,7 +341,7 @@ async fn refresh_route_keeps_user_and_connector_subjects_apart() { }, ) .await; - let (status, _body) = refresh_call_with(fx.app.clone(), oauth_user_body()).await; + let (status, _body) = refresh_call_with(&fx, oauth_user_body()).await; assert_eq!( status, StatusCode::INTERNAL_SERVER_ERROR, diff --git a/crates/engram-dst/src/world.rs b/crates/engram-dst/src/world.rs index 16fae80bd..87a880ca1 100644 --- a/crates/engram-dst/src/world.rs +++ b/crates/engram-dst/src/world.rs @@ -1268,11 +1268,11 @@ impl SimWorld { clock, entropy: self.entropy.clone(), }; - Arc::new(AppState::new_with_registry( - CoordinatorConfig::default(), - services, - registry, - )) + let cfg = CoordinatorConfig { + auth_tokens: vec![crate::workload::SIM_HTTP_TOKEN.to_string()], + ..CoordinatorConfig::default() + }; + Arc::new(AppState::new_with_registry(cfg, services, registry)) } } diff --git a/deploy/helm/engram/README.md b/deploy/helm/engram/README.md index be7f53d95..e0c624845 100644 --- a/deploy/helm/engram/README.md +++ b/deploy/helm/engram/README.md @@ -78,7 +78,7 @@ coord `ingress` without an auth proxy in front. - `DATABASE_URL` — the Postgres connection string. - (env-var KEK only) `ENGRAM_KEK_MASTER_KEY` — base64-encoded 32-byte key. - - (auth-enabled) `ENGRAM_AUTH_TOKENS` — comma-separated bearer + - `ENGRAM_AUTH_TOKENS` — comma-separated bearer allow-list. 5. (GCP / AWS) The bound ServiceAccount has the right roles on the blob bucket + KEK key + secret resources. @@ -174,7 +174,7 @@ common knobs: | `secrets.backend` | `gcp` | `env` for dev. | | `secrets.gcpProjectId` | `""` | Required for `gcp`. | | `database.existingSecret` | `engram-coordinator-secrets` | | -| `auth.existingSecret` | `""` | Empty disables bearer auth (dev). | +| `auth.existingSecret` | `""` | Required for internal HTTP access. Without tokens, requests fail authentication. | | `serviceAccount.annotations` | `{}` | Per-cloud identity binding. | | `service.type` | `ClusterIP` | Keep as ClusterIP — in-cluster path only. Out-of-cluster reach is `serviceInternal`. | | `serviceInternal.loadBalancerIP` | `""` | VPC-internal IP for FC host dial-in. Pin to a `google_compute_address`/equivalent reservation. | diff --git a/deploy/helm/engram/values.yaml b/deploy/helm/engram/values.yaml index c258ab9aa..9d133864a 100644 --- a/deploy/helm/engram/values.yaml +++ b/deploy/helm/engram/values.yaml @@ -82,8 +82,8 @@ database: # `existingSecret`/`secretKey` carry the deployment bearer token(s) for the # MACHINE path — the host-agent's coord→internal-router calls and the app-gRPC # surface (see `appGrpc.tokensSecret`, which defaults to this Secret). This -# stays set in every real deploy. An empty value disables the bearer entirely -# (dev only). +# must be set in every deployment. Without tokens, internal HTTP requests fail +# authentication. Local development can set ENGRAM_ALLOW_INSECURE_INTERNAL_AUTH=1. # # HUMAN authentication is NOT handled here anymore: post-ADR-0051 the coord # dropped its human-auth verifiers (oidc / forward-auth / synthetic / cookie), diff --git a/docs/deploy.md b/docs/deploy.md index 16fd58f13..2b0b64e0b 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -81,7 +81,7 @@ lands where. | Variable | Purpose | |---|---| | `DATABASE_URL` | Postgres connection string (from the coordinator Secret) | -| `ENGRAM_AUTH_TOKENS` | Comma-separated machine bearer allow-list (host-agents + app-gRPC default) | +| `ENGRAM_AUTH_TOKENS` | Comma-separated machine bearer allow-list (host-agents + app-gRPC default). Empty refuses every internal HTTP request | | `ENGRAM_BLOB_BACKEND` | `gcs` \| `s3` (\| `local` dev) | | `ENGRAM_GCS_BUCKET` | gcs: the chunks bucket | | `ENGRAM_S3_BUCKET` / `ENGRAM_S3_REGION` / `ENGRAM_S3_ENDPOINT_URL` | s3: bucket, SigV4 region, optional S3-compatible endpoint (MinIO/R2 — flips path-style) | diff --git a/site/src/content/docs/docs/reference/configuration.md b/site/src/content/docs/docs/reference/configuration.md index 118cdd98d..2447c3027 100644 --- a/site/src/content/docs/docs/reference/configuration.md +++ b/site/src/content/docs/docs/reference/configuration.md @@ -13,7 +13,7 @@ where, for anyone reading a manifest or running a component outside the charts. | Variable | Purpose | |---|---| | `DATABASE_URL` | Postgres connection string, from the coordinator's Secret. | -| `ENGRAM_AUTH_TOKENS` | Comma-separated bearer tokens that hosts and the orchestrator present. | +| `ENGRAM_AUTH_TOKENS` | Comma-separated bearer tokens that hosts and the orchestrator present. Empty means every host request is refused. | | `ENGRAM_APP_GRPC_TOKENS` | The orchestrator's bearer for the coordinator's private RPC port. Empty means every call is refused. | | `ENGRAM_BLOB_BACKEND` | `gcs`, `s3`, or `local` for development. | | `ENGRAM_GCS_BUCKET` | With `gcs`: the chunks bucket. |