|
| 1 | +//! Bearer auth for master-only `/v1/admin/*` control-plane routes. |
| 2 | +//! |
| 3 | +//! Prod historically published these on `:80`/`:443` with no app auth. Policy: |
| 4 | +//! - token env/file set → require matching `Authorization: Bearer` |
| 5 | +//! - `BASE_GATEWAY_REQUIRE_OWNER=1` without token → fail closed at load |
| 6 | +//! - otherwise (local/test) → open + warn |
| 7 | +
|
| 8 | +use std::sync::Arc; |
| 9 | + |
| 10 | +use axum::extract::{Request, State}; |
| 11 | +use axum::http::{header, StatusCode}; |
| 12 | +use axum::middleware::Next; |
| 13 | +use axum::response::{IntoResponse, Response}; |
| 14 | +use axum::Json; |
| 15 | +use thiserror::Error; |
| 16 | + |
| 17 | +/// Env: raw admin bearer token (prefer the file form in deploy). |
| 18 | +pub const ADMIN_TOKEN_ENV: &str = "BASE_GATEWAY_ADMIN_TOKEN"; |
| 19 | +/// Env: path to a single-line admin bearer token file (mode 0400). |
| 20 | +pub const ADMIN_TOKEN_FILE_ENV: &str = "BASE_GATEWAY_ADMIN_TOKEN_FILE"; |
| 21 | +/// Same flag the gateway uses for master-only owner check. |
| 22 | +pub const REQUIRE_OWNER_ENV: &str = "BASE_GATEWAY_REQUIRE_OWNER"; |
| 23 | + |
| 24 | +/// Admin auth configuration errors. |
| 25 | +#[derive(Debug, Error)] |
| 26 | +pub enum AdminAuthError { |
| 27 | + /// Missing/empty/unreadable token configuration. |
| 28 | + #[error("{0}")] |
| 29 | + Config(String), |
| 30 | +} |
| 31 | + |
| 32 | +/// Shared admin-auth state for the axum middleware. |
| 33 | +#[derive(Clone, Debug)] |
| 34 | +pub struct AdminAuth { |
| 35 | + /// When `Some`, Bearer must match. When `None`, admin routes are open. |
| 36 | + token: Option<Arc<[u8]>>, |
| 37 | +} |
| 38 | + |
| 39 | +impl AdminAuth { |
| 40 | + /// Load from env. Fails closed when owner-check is required but no token. |
| 41 | + /// |
| 42 | + /// # Errors |
| 43 | + /// |
| 44 | + /// Missing token under `BASE_GATEWAY_REQUIRE_OWNER=1`, or unreadable file. |
| 45 | + pub fn from_env() -> Result<Self, AdminAuthError> { |
| 46 | + let token = load_token()?; |
| 47 | + let require_owner = std::env::var(REQUIRE_OWNER_ENV) |
| 48 | + .is_ok_and(|v| matches!(v.trim(), "1" | "true" | "TRUE" | "yes" | "YES")); |
| 49 | + if token.is_none() { |
| 50 | + if require_owner { |
| 51 | + return Err(AdminAuthError::Config(format!( |
| 52 | + "{REQUIRE_OWNER_ENV}=1 requires {ADMIN_TOKEN_ENV} or {ADMIN_TOKEN_FILE_ENV} \ |
| 53 | + (refusing to expose open /v1/admin/* on a public listener)" |
| 54 | + ))); |
| 55 | + } |
| 56 | + tracing::warn!( |
| 57 | + event = "gateway_admin_auth_open", |
| 58 | + "BASE_GATEWAY_ADMIN_TOKEN unset; /v1/admin/* is unauthenticated \ |
| 59 | + (OK for local tests only)" |
| 60 | + ); |
| 61 | + } else { |
| 62 | + tracing::info!( |
| 63 | + event = "gateway_admin_auth_enabled", |
| 64 | + "Bearer auth required for /v1/admin/*" |
| 65 | + ); |
| 66 | + } |
| 67 | + Ok(Self { |
| 68 | + token: token.map(Into::into), |
| 69 | + }) |
| 70 | + } |
| 71 | + |
| 72 | + /// Test helper: require this exact bearer token. |
| 73 | + #[must_use] |
| 74 | + pub fn require_token(token: impl Into<String>) -> Self { |
| 75 | + Self { |
| 76 | + token: Some(Arc::from(token.into().into_bytes().into_boxed_slice())), |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + /// Test helper: leave admin routes open. |
| 81 | + #[must_use] |
| 82 | + pub fn open() -> Self { |
| 83 | + Self { token: None } |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +fn load_token() -> Result<Option<Vec<u8>>, AdminAuthError> { |
| 88 | + if let Ok(raw) = std::env::var(ADMIN_TOKEN_ENV) { |
| 89 | + let t = raw.trim(); |
| 90 | + if t.is_empty() { |
| 91 | + return Err(AdminAuthError::Config(format!( |
| 92 | + "{ADMIN_TOKEN_ENV} is set but empty" |
| 93 | + ))); |
| 94 | + } |
| 95 | + return Ok(Some(t.as_bytes().to_vec())); |
| 96 | + } |
| 97 | + if let Ok(path) = std::env::var(ADMIN_TOKEN_FILE_ENV) { |
| 98 | + let raw = std::fs::read_to_string(&path).map_err(|e| { |
| 99 | + AdminAuthError::Config(format!("read {ADMIN_TOKEN_FILE_ENV} ({path}): {e}")) |
| 100 | + })?; |
| 101 | + let t = raw.trim(); |
| 102 | + if t.is_empty() { |
| 103 | + return Err(AdminAuthError::Config(format!( |
| 104 | + "{ADMIN_TOKEN_FILE_ENV} ({path}) is empty" |
| 105 | + ))); |
| 106 | + } |
| 107 | + return Ok(Some(t.as_bytes().to_vec())); |
| 108 | + } |
| 109 | + Ok(None) |
| 110 | +} |
| 111 | + |
| 112 | +/// Axum middleware: gate `/v1/admin` and `/v1/admin/*`. |
| 113 | +pub async fn admin_auth_middleware( |
| 114 | + State(auth): State<AdminAuth>, |
| 115 | + request: Request, |
| 116 | + next: Next, |
| 117 | +) -> Response { |
| 118 | + let path = request.uri().path(); |
| 119 | + if !is_admin_path(path) { |
| 120 | + return next.run(request).await; |
| 121 | + } |
| 122 | + let Some(expected) = auth.token.as_ref() else { |
| 123 | + return next.run(request).await; |
| 124 | + }; |
| 125 | + let provided = bearer_from_headers(request.headers()); |
| 126 | + match provided { |
| 127 | + Some(got) if ct_eq(got.as_bytes(), expected.as_ref()) => next.run(request).await, |
| 128 | + _ => ( |
| 129 | + StatusCode::UNAUTHORIZED, |
| 130 | + Json(serde_json::json!({ |
| 131 | + "error": "admin bearer token required", |
| 132 | + "code": "admin_unauthorized", |
| 133 | + })), |
| 134 | + ) |
| 135 | + .into_response(), |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +fn is_admin_path(path: &str) -> bool { |
| 140 | + path == "/v1/admin" || path.starts_with("/v1/admin/") |
| 141 | +} |
| 142 | + |
| 143 | +fn bearer_from_headers(headers: &axum::http::HeaderMap) -> Option<String> { |
| 144 | + let raw = headers.get(header::AUTHORIZATION)?.to_str().ok()?; |
| 145 | + let token = raw |
| 146 | + .strip_prefix("Bearer ") |
| 147 | + .or_else(|| raw.strip_prefix("bearer "))?; |
| 148 | + let token = token.trim(); |
| 149 | + if token.is_empty() { |
| 150 | + None |
| 151 | + } else { |
| 152 | + Some(token.to_owned()) |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +fn ct_eq(a: &[u8], b: &[u8]) -> bool { |
| 157 | + if a.len() != b.len() { |
| 158 | + return false; |
| 159 | + } |
| 160 | + let mut diff = 0u8; |
| 161 | + for (x, y) in a.iter().zip(b.iter()) { |
| 162 | + diff |= x ^ y; |
| 163 | + } |
| 164 | + diff == 0 |
| 165 | +} |
| 166 | + |
| 167 | +#[cfg(test)] |
| 168 | +mod tests { |
| 169 | + use super::{ct_eq, is_admin_path}; |
| 170 | + |
| 171 | + #[test] |
| 172 | + fn admin_path_prefix() { |
| 173 | + assert!(is_admin_path("/v1/admin/seal")); |
| 174 | + assert!(is_admin_path("/v1/admin/backends")); |
| 175 | + assert!(is_admin_path("/v1/admin")); |
| 176 | + assert!(!is_admin_path("/v1/weights/latest")); |
| 177 | + assert!(!is_admin_path("/v1/administration")); |
| 178 | + } |
| 179 | + |
| 180 | + #[test] |
| 181 | + fn ct_eq_basic() { |
| 182 | + assert!(ct_eq(b"abc", b"abc")); |
| 183 | + assert!(!ct_eq(b"abc", b"abd")); |
| 184 | + assert!(!ct_eq(b"abc", b"ab")); |
| 185 | + } |
| 186 | +} |
0 commit comments