Add optional API key auth and allowed_hosts enforcement
- AuthConfig (api_key, allowed_hosts) read from the shared config; router_with_auth applies an axum middleware before any handler. - Host not in allowlist -> 403 host_not_allowed; missing/wrong key -> 401 invalid_api_key (accepts Authorization: Bearer <key> or x-api-key); /health open. - router() stays the open default: backward compatible (no key, wildcard hosts). - The non-loopback bind warning now fires only when no api_key is configured. - README updated (auth is a feature, no longer a gap). 4 new tests; 80 green + 2 real-file ignored; clippy clean; cargo fmt applied.
This commit is contained in:
1 parent
5bafd000c8
commit
b6619d30de
6 files changed
+227
-20
No files matched your search
+1
-1
@@ -11,6 +11,6 @@ pub mod stop;
|
||||
pub mod types;
|
||||
|
||||
pub use formatter::{Decoder, Formatter, Piece, Prompt};
|
||||
pub use routes::router;
|
||||
pub use routes::{router, router_with_auth, AuthConfig};
|
||||
pub use service::ChatService;
|
||||
pub use types::{ChatMessage, ChatRequest, ChatResponse, ModelList, Role};
|
||||
@@ -16,11 +16,95 @@ use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
|
||||
|
||||
/// Build the router. Mount this inside any axum `Router` or serve it directly.
|
||||
pub fn router(service: ChatService) -> Router {
|
||||
router_with_auth(service, AuthConfig::default())
|
||||
}
|
||||
|
||||
/// Build the router with optional API-key auth and a Host allowlist.
|
||||
pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router {
|
||||
Router::new()
|
||||
.route("/health", get(health))
|
||||
.route("/v1/models", get(models))
|
||||
.route("/v1/chat/completions", post(chat_completions))
|
||||
.with_state(AppState { service })
|
||||
.layer(axum::middleware::from_fn_with_state(auth, auth_middleware))
|
||||
}
|
||||
|
||||
/// Optional access control, read from the shared config. Default = open (no
|
||||
/// key, any host), matching a loopback-only deployment.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct AuthConfig {
|
||||
/// When set, every request except `/health` must carry this key, either as
|
||||
/// `Authorization: Bearer <key>` or `x-api-key: <key>`.
|
||||
pub api_key: Option<String>,
|
||||
/// Host-header allowlist. Empty or `["*"]` allows any host; otherwise the
|
||||
/// request `Host` must match one of these (DNS-rebinding protection).
|
||||
pub allowed_hosts: Vec<String>,
|
||||
}
|
||||
|
||||
impl AuthConfig {
|
||||
fn host_allowed(&self, headers: &axum::http::HeaderMap) -> bool {
|
||||
if self.allowed_hosts.is_empty() || self.allowed_hosts.iter().any(|h| h == "*") {
|
||||
return true;
|
||||
}
|
||||
let host = headers
|
||||
.get(axum::http::header::HOST)
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.unwrap_or("");
|
||||
let host = host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host);
|
||||
self.allowed_hosts
|
||||
.iter()
|
||||
.any(|h| h.eq_ignore_ascii_case(host))
|
||||
}
|
||||
|
||||
fn key_ok(&self, headers: &axum::http::HeaderMap) -> bool {
|
||||
let Some(key) = self.api_key.as_deref() else {
|
||||
return true;
|
||||
};
|
||||
if let Some(auth) = headers
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
{
|
||||
if auth.strip_prefix("Bearer ").is_some_and(|t| t == key) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
headers
|
||||
.get("x-api-key")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|k| k == key)
|
||||
}
|
||||
}
|
||||
|
||||
/// Enforces the Host allowlist and (except on `/health`) the API key before any
|
||||
/// handler runs.
|
||||
async fn auth_middleware(
|
||||
State(auth): State<AuthConfig>,
|
||||
req: axum::extract::Request,
|
||||
next: axum::middleware::Next,
|
||||
) -> axum::response::Response {
|
||||
if !auth.host_allowed(req.headers()) {
|
||||
return Error::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
ApiErrorEnvelope::new(
|
||||
"request Host is not in allowed_hosts",
|
||||
"invalid_request_error",
|
||||
Some("host_not_allowed".to_string()),
|
||||
),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
if req.uri().path() != "/health" && !auth.key_ok(req.headers()) {
|
||||
return Error::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
ApiErrorEnvelope::new(
|
||||
"missing or invalid API key",
|
||||
"invalid_request_error",
|
||||
Some("invalid_api_key".to_string()),
|
||||
),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
next.run(req).await
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
+31
-7
@@ -87,6 +87,15 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub silence_timeout_secs: Option<u64>,
|
||||
|
||||
/// Optional bearer API key. When set, every request except `/health` must
|
||||
/// carry it (`Authorization: Bearer ...` or `x-api-key`).
|
||||
#[serde(default)]
|
||||
pub api_key: Option<String>,
|
||||
/// Host-header allowlist. Absent/empty or `["*"]` allows any host; otherwise
|
||||
/// the request `Host` must match one of these (DNS-rebinding protection).
|
||||
#[serde(default)]
|
||||
pub allowed_hosts: Option<Vec<String>>,
|
||||
|
||||
/// Keys we understand but don't act on yet are NOT listed above, so they
|
||||
/// arrive here untouched — the "ignore what isn't ours" guarantee.
|
||||
#[serde(flatten)]
|
||||
@@ -247,17 +256,32 @@ mod tests {
|
||||
fn known_but_unused_fields_report_as_ignored() {
|
||||
let cfg = Config::parse(REAL, "test").unwrap();
|
||||
// we don't act on these yet, so they must not be lost or cause errors
|
||||
for k in [
|
||||
"arch",
|
||||
"cors_origins",
|
||||
"allowed_hosts",
|
||||
"drafting",
|
||||
"mcp_servers",
|
||||
] {
|
||||
for k in ["arch", "cors_origins", "drafting", "mcp_servers"] {
|
||||
assert!(cfg.extra.contains_key(k), "{k} should be in ignored extras");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_fields_are_read() {
|
||||
let cfg = Config::parse(
|
||||
r#"{"exe":"/x/e","api_key":"secret","allowed_hosts":["a.com","b.com"]}"#,
|
||||
"test",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cfg.api_key.as_deref(), Some("secret"));
|
||||
assert_eq!(
|
||||
cfg.allowed_hosts.as_deref(),
|
||||
Some(["a.com".to_string(), "b.com".to_string()].as_slice())
|
||||
);
|
||||
// the real config: no key, wildcard hosts (open)
|
||||
let real = Config::parse(REAL, "test").unwrap();
|
||||
assert!(real.api_key.is_none());
|
||||
assert_eq!(
|
||||
real.allowed_hosts.as_deref(),
|
||||
Some(["*".to_string()].as_slice())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn engine_argv_adds_serve_once() {
|
||||
// REAL args already contain --serve -> no duplicate
|
||||
|
||||
+9
-5
@@ -8,7 +8,7 @@ use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
|
||||
use strata_ctl::api::{router, ChatService};
|
||||
use strata_ctl::api::{router_with_auth, AuthConfig, ChatService};
|
||||
use strata_ctl::config::{Config, ConfigError};
|
||||
use strata_ctl::engine::Engine;
|
||||
use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer};
|
||||
@@ -171,14 +171,18 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
|
||||
);
|
||||
|
||||
let svc = ChatService::new(engine.clone(), fmt);
|
||||
let app = router(svc);
|
||||
let auth = AuthConfig {
|
||||
api_key: cfg.api_key.clone(),
|
||||
allowed_hosts: cfg.allowed_hosts.clone().unwrap_or_default(),
|
||||
};
|
||||
let app = router_with_auth(svc, auth);
|
||||
let host = cfg.bind_host(cli_host);
|
||||
let port = cfg.bind_port(cli_port);
|
||||
if !is_loopback_host(&host) {
|
||||
if !is_loopback_host(&host) && cfg.api_key.is_none() {
|
||||
tracing::warn!(
|
||||
host = %host,
|
||||
"binding a non-loopback address: the API has NO authentication and \
|
||||
`allowed_hosts` is not enforced — anyone on the network can use it"
|
||||
"binding a non-loopback address with NO API key: anyone on the network \
|
||||
can use the API (set `api_key` in the config to require authentication)"
|
||||
);
|
||||
}
|
||||
let addr = format!("{host}:{port}");
|
||||
|
||||
Reference in new issue
Block a user