Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(gateway): refuse requests when the auth configuration is an error (#269)
Krisztian Gajdar8c84419ac4c4
diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex afe7b2196..b4de99240 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -816,10 +816,19 @@ impl Config {));}- if !is_enabled && (has_tokens || has_admin) {+ // `admin_token` alone is not dead configuration: `Config::load` also+ // presents it to `sie-config` as the bootstrap credential+ // (`config_service_token`), so a gateway with inbound auth off still+ // legitimately carries it. Only the inbound tokens prove intent.+ if !is_enabled && has_tokens {issues.push((AuditLevel::Error,- "SIE_AUTH_TOKEN(S) or SIE_ADMIN_TOKEN is set but SIE_AUTH_MODE is not 'static'/'token'. Auth is DISABLED; the tokens are dead configuration. Set SIE_AUTH_MODE=token to enforce auth.".to_string(),+ "SIE_AUTH_TOKEN(S) is set but SIE_AUTH_MODE is not 'static'/'token'. Auth is DISABLED; the tokens are dead configuration. Set SIE_AUTH_MODE=token to enforce auth.".to_string(),+ ));+ } else if !is_enabled && has_admin {+ issues.push((+ AuditLevel::Warn,+ "SIE_ADMIN_TOKEN is set but SIE_AUTH_MODE is not 'static'/'token': admin routes are not gated inbound (auth is disabled); the token is still presented to sie-config as the bootstrap credential.".to_string(),));}@@ -847,6 +856,17 @@ impl Config {issues}+ /// The first `AuditLevel::Error` from [`Self::audit_auth`], if any.+ ///+ /// An auth configuration that audits as an error has no valid reading, so+ /// the request path treats it as a refusal instead of picking a default.+ /// Callers may resolve this once: `Config` does not change after load.+ pub fn auth_config_error(&self) -> Option<String> {+ self.audit_auth()+ .into_iter()+ .find_map(|(level, message)| matches!(level, AuditLevel::Error).then_some(message))+ }+/// Report NATS config-delta producer-trust soundness. Mirrors the/// pattern of `audit_auth` but scoped to the/// `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` /@@ -1791,6 +1811,22 @@ mod tests {);}+ /// The admin token doubles as the `sie-config` bootstrap credential+ /// (`config_service_token`), so a gateway running with inbound auth off+ /// still carries it legitimately. That must never audit as an error, or+ /// the fail-closed middleware would refuse every request on such a deploy.+ #[test]+ fn test_audit_auth_none_with_only_admin_token_is_not_an_error() {+ let cfg = cfg_with_auth("none", vec![], "admin", false);+ let issues = cfg.audit_auth();+ assert!(+ issues.iter().all(|(lvl, _)| *lvl != AuditLevel::Error),+ "admin token alone must not be an error: {:?}",+ issues+ );+ assert!(cfg.auth_config_error().is_none());+ }+#[test]fn test_audit_auth_token_mode_accepted() {let cfg = cfg_with_auth("token", vec!["t1"], "admin", false);diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rsindex 977b5ac2e..a64519e76 100644--- a/packages/sie_gateway/src/middleware/auth.rs+++ b/packages/sie_gateway/src/middleware/auth.rs@@ -40,11 +40,27 @@ const EXEMPT_OPERATIONAL_PATHS: &[&str] = &["/", "/health"];#[derive(Clone)]pub struct AuthLayer {config: Arc<Config>,+ /// First `AuditLevel::Error` from [`Config::audit_auth`], resolved once at+ /// layer construction because `Config` is immutable after load and the+ /// audit allocates. `Some` means the auth configuration has no valid+ /// interpretation, which this middleware serves as a refusal rather than+ /// as "auth off" — see [`AuthMiddleware::call`].+ misconfigured: Option<Arc<str>>,}impl AuthLayer {pub fn new(config: Arc<Config>) -> Self {- Self { config }+ let misconfigured: Option<Arc<str>> = config.auth_config_error().map(Arc::from);+ if let Some(reason) = misconfigured.as_deref() {+ tracing::error!(+ audit = "auth",+ "{reason} Refusing every non-probe request until it is corrected."+ );+ }+ Self {+ config,+ misconfigured,+ }}}@@ -55,6 +71,7 @@ impl<S> Layer<S> for AuthLayer {AuthMiddleware {inner,config: Arc::clone(&self.config),+ misconfigured: self.misconfigured.clone(),}}}@@ -63,6 +80,7 @@ impl<S> Layer<S> for AuthLayer {pub struct AuthMiddleware<S> {inner: S,config: Arc<Config>,+ misconfigured: Option<Arc<str>>,}impl<S> Service<Request<Body>> for AuthMiddleware<S>@@ -80,34 +98,49 @@ wherefn call(&mut self, req: Request<Body>) -> Self::Future {let config = Arc::clone(&self.config);+ let misconfigured = self.misconfigured.clone();let mut inner = self.inner.clone();Box::pin(async move {- if !is_auth_enabled(&config.auth_mode) {- return inner.call(req).await;- }-let path = req.uri().path();+ // Probes and the read-only API description stay reachable in every+ // configuration, including the broken ones below: gating them would+ // take the pod out of rotation and hide the very misconfiguration+ // the operator needs to see.if PROBE_PATHS.contains(&path) || EXEMPT_DOC_PATHS.contains(&path) {return inner.call(req).await;}- if config.auth_exempt_operational- && (EXEMPT_OPERATIONAL_PATHS.contains(&path) || path.starts_with("/ws/"))- {- return inner.call(req).await;- }-- if config.auth_tokens.is_empty() {+ // A configuration `audit_auth` classifies as an error has no valid+ // interpretation, so it is served as a refusal. Treating it as+ // "auth off" is the strictly worse reading: an unrecognised+ // `SIE_AUTH_MODE`, or tokens supplied against a disabled mode, both+ // describe an operator who intended auth and did not get it. The+ // reason was logged once at layer construction and is never+ // echoed, because it quotes operator input. This gate is+ // deliberately above the operational exemption: an auth config+ // that cannot be read cannot be read as consent to publish worker+ // URLs, queue depth and GPU inventory either.+ if misconfigured.is_some() {record_admission_rejection(&req, AdmissionOutcome::AuthMisconfigured);return Ok(error_response(StatusCode::INTERNAL_SERVER_ERROR,err_code::GATEWAY_AUTH_MISCONFIGURED,- "Gateway auth enabled but no tokens configured",+ "Gateway auth is misconfigured; refusing the request",));}+ if !is_auth_enabled(&config.auth_mode) {+ return inner.call(req).await;+ }++ if config.auth_exempt_operational+ && (EXEMPT_OPERATIONAL_PATHS.contains(&path) || path.starts_with("/ws/"))+ {+ return inner.call(req).await;+ }+let token = match extract_bearer_token(req.headers()) {Some(t) => t,None => {@@ -375,12 +408,11 @@ mod tests {assert!(!is_auth_enabled("none"));assert!(!is_auth_enabled(""));assert!(!is_auth_enabled("disabled"));- // Typos and unknown modes fail-closed-to-bypass by design: the- // pair (auth_mode, auth_tokens) is validated at startup in- // `Config::load`, which logs a warning when tokens are configured- // but the mode is disabled. This prevents a typo in auth_mode- // from becoming a silent auth enforcement while still allowing- // the legacy "turn off auth" workflow.+ // This predicate answers "should tokens be checked", and an+ // unrecognised mode is not a mode whose tokens can be checked. It is+ // NOT the bypass decision: the middleware refuses an unrecognised mode+ // outright via `Config::auth_config_error`, so reaching this `false`+ // for a typo is unreachable in the request path.assert!(!is_auth_enabled("staitc"));}@@ -403,7 +435,8 @@ mod tests {// dummy handler) and cover what the helper-only tests cannot:// - which paths actually reach the handler vs return 401/403// - admin vs user token routing on admin-gated prefixes- // - fail-open behavior when auth is disabled / unknown+ // - pass-through when auth is deliberately disabled, and refusal when+ // the auth configuration is an error// - the `SIE_AUTH_EXEMPT_OPERATIONAL` toggleuse axum::routing::{get, post};@@ -682,15 +715,75 @@ mod tests {}#[tokio::test]- async fn middleware_unknown_auth_mode_is_fail_open() {- // Typos in SIE_AUTH_MODE must NOT silently enforce auth (that- // would lock every pod out of every non-probe request). The- // `audit_auth()` warning covers operator visibility.+ async fn middleware_unknown_auth_mode_refuses() {+ // A typo in SIE_AUTH_MODE used to disable auth for every route while+ // `audit_auth()` logged an error nobody read. An unrecognised mode has+ // no valid reading, so it is refused rather than served unauthenticated.let cfg = cfg_for_middleware("staitc", vec!["user"], "admin", false);let r = test_router(cfg);+ assert_eq!(+ send(r, Method::POST, "/v1/encode/any", None).await,+ StatusCode::INTERNAL_SERVER_ERROR+ );+ }++ #[tokio::test]+ async fn middleware_tokens_without_enabled_mode_refuses() {+ // The likelier operator mistake: tokens supplied, mode left disabled.+ // `audit_auth()` already calls this dead configuration; serving it as+ // "auth off" hands an operator who configured a token an open gateway.+ let cfg = cfg_for_middleware("none", vec!["user"], "admin", false);+ let r = test_router(cfg);+ assert_eq!(+ send(r, Method::POST, "/v1/encode/any", Some("user")).await,+ StatusCode::INTERNAL_SERVER_ERROR+ );+ }++ #[tokio::test]+ async fn middleware_admin_token_alone_with_disabled_mode_passes_through() {+ // `SIE_ADMIN_TOKEN` is also the sie-config bootstrap credential, so+ // "auth off + admin token present" is an ordinary deployment shape.+ let cfg = cfg_for_middleware("none", vec![], "admin", false);+ let r = test_router(cfg);assert_eq!(send(r, Method::POST, "/v1/encode/any", None).await,StatusCode::OK);}++ #[tokio::test]+ async fn middleware_deliberately_disabled_auth_still_passes_through() {+ let cfg = cfg_for_middleware("none", vec![], "", false);+ let r = test_router(cfg);+ assert_eq!(+ send(r, Method::POST, "/v1/encode/any", None).await,+ StatusCode::OK+ );+ }++ #[tokio::test]+ async fn middleware_probes_survive_a_misconfigured_auth_mode() {+ // The refusal must not take the pod out of rotation: a crashlooping or+ // unready gateway hides the misconfiguration instead of surfacing it.+ for path in ["/healthz", "/readyz", "/openapi.json"] {+ let cfg = cfg_for_middleware("staitc", vec!["user"], "admin", false);+ let r = test_router(cfg);+ assert_eq!(+ send(r, Method::GET, path, None).await,+ StatusCode::OK,+ "{path} must stay reachable while auth config is broken"+ );+ }+ }++ #[tokio::test]+ async fn middleware_misconfigured_auth_overrides_the_operational_exemption() {+ let cfg = cfg_for_middleware("staitc", vec!["user"], "admin", true);+ let r = test_router(cfg);+ assert_eq!(+ send(r, Method::GET, "/health", None).await,+ StatusCode::INTERNAL_SERVER_ERROR+ );+ }}