Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<owner>/<repo>/`. It now gives the repository itself and the metadata endpoints
(events, forks, license, stargazers, subscribers, stats, rules, rulesets, topics,
Expand Down Expand Up @@ -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
3 changes: 3 additions & 0 deletions Tiltfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
178 changes: 93 additions & 85 deletions crates/engram-coordinator/src/api/auth.rs
Original file line number Diff line number Diff line change
@@ -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<String>) -> Self {
pub fn new(tokens: Vec<String>, 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 <t>` with `<t>` 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<AuthState>,
req: Request<Body>,
Expand All @@ -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"),
};

Expand All @@ -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,
Expand All @@ -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<String>, 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
);
}
}
}
33 changes: 32 additions & 1 deletion crates/engram-coordinator/src/api/forge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<dyn Integration> = 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![]]);
}
}
Loading
Loading