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:
adm committed 2026-11-24 18:48:05 +01:00
1 parent 5bafd000c8
commit b6619d30de
6 files changed
+227 -20

No files matched your search

+31 -7
View File
@@ -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