#[derive(Debug, Clone, Default)]
pub struct AuthConfig {
pub api_key: Option<String>,
}
impl AuthConfig {
pub fn new(api_key: Option<String>) -> Self {
Self { api_key }
}
pub fn requires_auth(&self, is_loopback: bool) -> bool {
self.api_key.is_some() || !is_loopback
}
pub fn verify(&self, presented: &str) -> bool {
match self.api_key.as_deref() {
Some(expected) => constant_time_eq(expected.as_bytes(), presented.as_bytes()),
None => false,
}
}
pub fn refuse_to_start(&self, is_loopback: bool) -> Result<(), AuthStartupError> {
if !is_loopback && self.api_key.is_none() {
return Err(AuthStartupError::NonLoopbackWithoutKey);
}
Ok(())
}
}
#[derive(Clone)]
pub struct AuthLayerState {
auth: AuthConfig,
is_loopback: bool,
key_store: Option<std::sync::Arc<super::api_keys::ApiKeyStore>>,
}
impl AuthLayerState {
pub fn new(auth: AuthConfig, is_loopback: bool) -> Self {
Self {
auth,
is_loopback,
key_store: None,
}
}
pub fn with_key_store(
mut self,
key_store: std::sync::Arc<super::api_keys::ApiKeyStore>,
) -> Self {
self.key_store = Some(key_store);
self
}
fn verify_token(&self, token: &str) -> bool {
if self.auth.verify(token) {
return true;
}
match &self.key_store {
Some(store) => store.verify(token),
None => false,
}
}
}
fn parse_bearer(header: &str) -> Option<&str> {
let rest = header.strip_prefix("Bearer ").or_else(|| {
let (scheme, rest) = header.split_once(' ')?;
scheme.eq_ignore_ascii_case("bearer").then_some(rest)
})?;
let token = rest.trim();
(!token.is_empty()).then_some(token)
}
#[cfg(feature = "server")]
pub async fn require_bearer(
axum::extract::State(state): axum::extract::State<AuthLayerState>,
request: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
use axum::http::StatusCode;
use axum::response::IntoResponse;
if !state.auth.requires_auth(state.is_loopback) {
return next.run(request).await;
}
if super::admin::is_admin_public_static_path(request.uri().path()) {
return next.run(request).await;
}
let presented = request
.headers()
.get(axum::http::header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(parse_bearer);
match presented {
Some(token) if state.verify_token(token) => next.run(request).await,
_ => (
StatusCode::UNAUTHORIZED,
"Unauthorized: missing or invalid Bearer token",
)
.into_response(),
}
}
#[cfg(feature = "server")]
pub fn apply_bearer_auth(router: axum::Router, state: AuthLayerState) -> axum::Router {
router.layer(axum::middleware::from_fn_with_state(state, require_bearer))
}
#[derive(Debug, Clone)]
pub struct OriginLayerState {
allowed: std::sync::Arc<Vec<String>>,
}
impl OriginLayerState {
pub fn from_bind_addr(addr: std::net::SocketAddr) -> Self {
let port = addr.port();
let mut allowed = vec![
format!("http://{}", addr),
format!("http://{}:{}", addr.ip(), port),
];
if addr.ip().is_loopback() {
for host in ["localhost", "127.0.0.1", "[::1]"] {
allowed.push(format!("http://{host}:{port}"));
}
}
Self {
allowed: std::sync::Arc::new(allowed),
}
}
pub fn from_allowed(allowed: Vec<String>) -> Self {
Self {
allowed: std::sync::Arc::new(allowed),
}
}
fn permits(&self, origin: &str) -> bool {
let origin = origin.trim();
self.allowed.iter().any(|a| a.eq_ignore_ascii_case(origin))
}
}
#[cfg(feature = "server")]
pub async fn require_allowed_origin(
axum::extract::State(state): axum::extract::State<OriginLayerState>,
request: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
use axum::http::StatusCode;
use axum::http::header::ORIGIN;
use axum::response::IntoResponse;
match request.headers().get(ORIGIN) {
None => next.run(request).await,
Some(value) => match value.to_str() {
Ok(origin) if state.permits(origin) => next.run(request).await,
_ => (
StatusCode::FORBIDDEN,
"Forbidden: cross-origin request rejected (Origin not allowed)",
)
.into_response(),
},
}
}
#[cfg(feature = "server")]
pub fn apply_origin_gate(router: axum::Router, state: OriginLayerState) -> axum::Router {
router.layer(axum::middleware::from_fn_with_state(
state,
require_allowed_origin,
))
}
pub(crate) fn host_allow_list(bind_host: &str) -> Vec<String> {
let mut hosts = vec![
"localhost".to_string(),
"127.0.0.1".to_string(),
"::1".to_string(),
];
let host = bind_host.trim();
if !host.is_empty() && !hosts.iter().any(|allowed| allowed == host) {
hosts.push(host.to_string());
}
hosts
}
fn parse_http_authority(value: &str) -> Option<axum::http::uri::Authority> {
if value.contains(['@', ',']) || value.bytes().any(|byte| byte.is_ascii_whitespace()) {
return None;
}
let authority = value.parse::<axum::http::uri::Authority>().ok()?;
let host = authority.host();
if host.is_empty() {
return None;
}
if host.starts_with('[') {
host.strip_prefix('[')?
.strip_suffix(']')?
.parse::<std::net::Ipv6Addr>()
.ok()?;
}
let suffix = value.strip_prefix(host)?;
if !suffix.is_empty() {
let port = suffix.strip_prefix(':')?;
if !port.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
port.parse::<u16>().ok()?;
}
Some(authority)
}
fn same_authority_host(left: &str, right: &str) -> bool {
let left = left.trim_start_matches('[').trim_end_matches(']');
let right = right.trim_start_matches('[').trim_end_matches(']');
match (
left.parse::<std::net::IpAddr>(),
right.parse::<std::net::IpAddr>(),
) {
(Ok(left), Ok(right)) => left == right,
(Err(_), Err(_)) => left.eq_ignore_ascii_case(right),
_ => false,
}
}
fn request_authority(request: &axum::extract::Request) -> Option<axum::http::uri::Authority> {
let mut values = request.headers().get_all(axum::http::header::HOST).iter();
let host = match values.next() {
Some(value) => Some(parse_http_authority(value.to_str().ok()?)?),
None => None,
};
if values.next().is_some() {
return None;
}
let authority = match request.uri().authority() {
Some(value) => Some(parse_http_authority(value.as_str())?),
None => None,
};
if let (Some(host), Some(authority)) = (&host, &authority)
&& (!same_authority_host(host.host(), authority.host())
|| host.port_u16() != authority.port_u16())
{
return None;
}
authority.or(host)
}
fn authority_is_allowed(request: &axum::extract::Request, allowed: &[String]) -> bool {
request_authority(request).is_some_and(|authority| {
allowed
.iter()
.any(|host| same_authority_host(authority.host(), host))
})
}
pub(crate) async fn require_allowed_authority(
axum::extract::State(allowed): axum::extract::State<std::sync::Arc<Vec<String>>>,
request: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
use axum::response::IntoResponse;
if authority_is_allowed(&request, &allowed) {
next.run(request).await
} else {
(
axum::http::StatusCode::FORBIDDEN,
"Forbidden: request authority not allowed",
)
.into_response()
}
}
pub(crate) fn apply_http_gates(
router: axum::Router,
bound_addr: std::net::SocketAddr,
state: AuthLayerState,
) -> axum::Router {
let router = if state.auth.requires_auth(state.is_loopback) {
router
} else {
router.layer(axum::middleware::from_fn_with_state(
std::sync::Arc::new(host_allow_list(&bound_addr.ip().to_string())),
require_allowed_authority,
))
};
let router = apply_origin_gate(router, OriginLayerState::from_bind_addr(bound_addr));
apply_bearer_auth(router, state)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum AuthStartupError {
#[error(
"refusing to bind a non-loopback address without an API key: pass --api-key or --api-key-env (a routable bind must be authenticated)"
)]
NonLoopbackWithoutKey,
#[error(
"refusing an inline --api-key on a non-loopback bind: the key would be visible in process listings (ps / Task Manager). Use --api-key-env <VAR> for a network bind (inline --api-key is allowed only on loopback)"
)]
InlineKeyOnNonLoopback,
}
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
let len_xor = a.len() ^ b.len();
let mut diff: u8 = 0;
for shift in (0..usize::BITS).step_by(8) {
diff |= (len_xor >> shift) as u8;
}
let n = a.len().max(b.len());
for i in 0..n {
let x = a.get(i).copied().unwrap_or(0);
let y = b.get(i).copied().unwrap_or(0);
diff |= x ^ y;
}
diff == 0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constant_time_eq_matches_for_equal_slices() {
assert!(constant_time_eq(b"sf_demo_key", b"sf_demo_key"));
assert!(constant_time_eq(b"", b""));
}
fn authority_request(uri: &str, hosts: &[&str]) -> axum::extract::Request {
let mut builder = axum::http::Request::builder()
.uri(uri)
.version(axum::http::Version::HTTP_2);
for host in hosts {
builder = builder.header(axum::http::header::HOST, *host);
}
builder.body(axum::body::Body::empty()).unwrap()
}
#[test]
fn authority_gate_validates_http2_authority_host_and_ambiguity() {
let allowed = host_allow_list("127.0.0.1");
let cases: &[(&str, &[&str], bool)] = &[
("/", &[], false),
("/", &["LOCALHOST:8787"], true),
("http://localhost/api/v1/status", &[], true),
(
"http://LOCALHOST:8787/api/v1/status",
&["localhost:8787"],
true,
),
("http://localhost:8787/api/v1/status", &["localhost"], false),
(
"http://localhost:8787/api/v1/status",
&["localhost:8788"],
false,
),
(
"http://outside.invalid/api/v1/status",
&["localhost"],
false,
),
(
"http://localhost/api/v1/status",
&["outside.invalid"],
false,
),
("http://outside.invalid/api/v1/status", &[], false),
(
"http://[::1]:8787/api/v1/status",
&["[0:0:0:0:0:0:0:1]:8787"],
true,
),
("http://user@localhost/api/v1/status", &["localhost"], false),
("/", &["localhost", "localhost"], false),
("/", &["localhost", "outside.invalid"], false),
];
for (uri, hosts, expected) in cases {
assert_eq!(
authority_is_allowed(&authority_request(uri, hosts), &allowed),
*expected,
"{uri} {hosts:?}"
);
}
for host in [
"",
"localhost,localhost",
"user@localhost",
"localhost:",
"localhost:abc",
"localhost:+80",
"localhost:-1",
"localhost:65536",
" localhost",
"localhost ",
"[::1",
"::1",
"[localhost]",
"[::1]:junk",
"[::1]:65536",
"localhost/path",
"localhost#fragment",
] {
assert!(
!authority_is_allowed(&authority_request("/", &[host]), &allowed),
"{host}"
);
}
let mut request = authority_request("/", &[]);
request.headers_mut().insert(
axum::http::header::HOST,
axum::http::HeaderValue::from_bytes(&[0xff]).unwrap(),
);
assert!(!authority_is_allowed(&request, &allowed));
}
async fn authority_test_server(
auth: AuthConfig,
policy_ip: std::net::IpAddr,
) -> (
std::net::SocketAddr,
tokio::sync::oneshot::Sender<()>,
tokio::task::JoinHandle<()>,
) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let mcp = axum::Router::new().route("/mcp", axum::routing::get(|| async { "ok" }));
let admin =
axum::Router::new().route("/api/v1/status", axum::routing::get(|| async { "ok" }));
let app = apply_http_gates(
mcp.merge(admin),
std::net::SocketAddr::new(policy_ip, addr.port()),
AuthLayerState::new(auth, policy_ip.is_loopback()),
);
let (shutdown, receive) = tokio::sync::oneshot::channel();
let join = tokio::spawn(async move {
axum::serve(listener, app)
.with_graceful_shutdown(async {
let _ = receive.await;
})
.await
.unwrap();
});
(addr, shutdown, join)
}
#[tokio::test]
async fn authority_gate_protects_both_merged_routes_without_origin() {
use axum::http::StatusCode;
let (addr, shutdown, join) =
authority_test_server(AuthConfig::default(), std::net::Ipv4Addr::LOCALHOST.into())
.await;
let client = reqwest::Client::builder()
.no_proxy()
.timeout(std::time::Duration::from_secs(5))
.build()
.unwrap();
for path in ["/mcp", "/api/v1/status"] {
let url = format!("http://{addr}{path}");
for host in [
"localhost",
"LOCALHOST:80",
"127.0.0.1",
"127.0.0.1:65535",
"[::1]",
"[::1]:8787",
"[0:0:0:0:0:0:0:1]:443",
] {
assert_eq!(
client
.get(&url)
.header("Host", host)
.send()
.await
.unwrap()
.status(),
StatusCode::OK,
"{path}: {host}"
);
}
assert_eq!(
client
.get(&url)
.header("Host", "outside.invalid")
.send()
.await
.unwrap()
.status(),
StatusCode::FORBIDDEN
);
assert_eq!(
client
.get(&url)
.header("Host", "outside.invalid")
.header("Forwarded", "host=localhost;proto=http")
.header("X-Forwarded-Host", "localhost")
.send()
.await
.unwrap()
.status(),
StatusCode::FORBIDDEN
);
assert_eq!(
client
.get(&url)
.header("Host", "localhost")
.header("Forwarded", "host=outside.invalid")
.header("X-Forwarded-Host", "outside.invalid")
.send()
.await
.unwrap()
.status(),
StatusCode::OK
);
assert_eq!(
client
.get(&url)
.header("Host", "localhost")
.header("Origin", "http://outside.invalid")
.send()
.await
.unwrap()
.status(),
StatusCode::FORBIDDEN
);
}
let _ = shutdown.send(());
tokio::time::timeout(std::time::Duration::from_secs(5), join)
.await
.unwrap()
.unwrap();
}
#[tokio::test]
async fn authority_gate_preserves_authenticated_admin_proxy_and_bearer_order() {
use axum::http::StatusCode;
let placeholder = "[redacted-test-placeholder]".to_string();
let client = reqwest::Client::builder()
.no_proxy()
.timeout(std::time::Duration::from_secs(5))
.build()
.unwrap();
for policy_ip in [
std::net::Ipv4Addr::LOCALHOST,
std::net::Ipv4Addr::UNSPECIFIED,
] {
let (addr, shutdown, join) =
authority_test_server(AuthConfig::new(Some(placeholder.clone())), policy_ip.into())
.await;
let url = format!("http://{addr}/api/v1/status");
assert_eq!(
client
.get(&url)
.header("Host", "outside.invalid")
.header("Origin", "http://outside.invalid")
.send()
.await
.unwrap()
.status(),
StatusCode::UNAUTHORIZED
);
assert_eq!(
client
.get(&url)
.header("Host", "outside.invalid")
.bearer_auth(&placeholder)
.send()
.await
.unwrap()
.status(),
StatusCode::OK
);
assert_eq!(
client
.get(&url)
.header("Host", "outside.invalid")
.bearer_auth(&placeholder)
.header("Origin", "http://outside.invalid")
.send()
.await
.unwrap()
.status(),
StatusCode::FORBIDDEN
);
let _ = shutdown.send(());
tokio::time::timeout(std::time::Duration::from_secs(5), join)
.await
.unwrap()
.unwrap();
}
let (addr, shutdown, join) = authority_test_server(
AuthConfig::default(),
std::net::Ipv4Addr::UNSPECIFIED.into(),
)
.await;
assert_eq!(
client
.get(format!("http://{addr}/api/v1/status"))
.header("Host", "localhost")
.send()
.await
.unwrap()
.status(),
StatusCode::UNAUTHORIZED
);
let _ = shutdown.send(());
tokio::time::timeout(std::time::Duration::from_secs(5), join)
.await
.unwrap()
.unwrap();
}
#[test]
fn constant_time_eq_rejects_differing_slices() {
assert!(!constant_time_eq(b"sf_demo_key", b"sf_wrong_key"));
assert!(!constant_time_eq(b"abc", b"abd"));
}
#[test]
fn constant_time_eq_rejects_length_mismatch() {
assert!(!constant_time_eq(b"short", b"shorter"));
assert!(!constant_time_eq(b"key", b""));
assert!(!constant_time_eq(b"", b"key"));
assert!(!constant_time_eq(b"sf_demo_key_long", b"sf_demo_key"));
}
#[test]
fn constant_time_eq_rejects_length_diff_multiple_of_256() {
let empty: &[u8] = b"";
let block_256 = vec![b'a'; 256];
let block_512 = vec![b'a'; 512];
assert!(
!constant_time_eq(empty, &block_256),
"0 vs 256 (diff 256) must reject despite identical overlapping bytes"
);
assert!(
!constant_time_eq(&block_256, &block_512),
"256 vs 512 (diff 256) must reject"
);
assert!(constant_time_eq(&block_256, &vec![b'a'; 256]));
}
#[test]
fn key_set_correct_passes_wrong_and_empty_fail() {
let auth = AuthConfig::new(Some("sf_demo_key".to_string()));
assert!(auth.verify("sf_demo_key"), "correct key must pass");
assert!(!auth.verify("sf_wrong_key"), "wrong key must fail");
assert!(!auth.verify(""), "empty presented key must fail");
}
#[test]
fn key_set_requires_auth_on_any_bind() {
let auth = AuthConfig::new(Some("k".to_string()));
assert!(
auth.requires_auth(true),
"key set => auth required on loopback"
);
assert!(
auth.requires_auth(false),
"key set => auth required on non-loopback"
);
}
#[test]
fn key_set_refuse_to_start_is_ok_on_any_bind() {
let auth = AuthConfig::new(Some("k".to_string()));
assert!(auth.refuse_to_start(true).is_ok());
assert!(auth.refuse_to_start(false).is_ok());
}
#[test]
fn no_key_loopback_requires_no_auth() {
let auth = AuthConfig::new(None);
assert!(
!auth.requires_auth(true),
"no key + loopback => no auth required"
);
assert!(
auth.refuse_to_start(true).is_ok(),
"no key + loopback must start"
);
assert!(!auth.verify("anything"));
}
#[test]
fn parse_bearer_extracts_token() {
assert_eq!(parse_bearer("Bearer sf_demo_key"), Some("sf_demo_key"));
assert_eq!(parse_bearer("bearer sf_demo_key"), Some("sf_demo_key"));
assert_eq!(parse_bearer("BEARER sf_demo_key"), Some("sf_demo_key"));
assert_eq!(parse_bearer("Bearer sf_demo_key "), Some("sf_demo_key"));
}
#[test]
fn parse_bearer_rejects_non_bearer_and_empty() {
assert_eq!(parse_bearer("Basic abc123"), None);
assert_eq!(parse_bearer("sf_demo_key"), None);
assert_eq!(parse_bearer("Bearer "), None);
assert_eq!(parse_bearer("Bearer "), None);
assert_eq!(parse_bearer(""), None);
}
#[test]
fn origin_gate_permits_same_origin_and_loopback_aliases() {
let addr: std::net::SocketAddr = "127.0.0.1:8787".parse().unwrap();
let state = OriginLayerState::from_bind_addr(addr);
assert!(state.permits("http://127.0.0.1:8787"));
assert!(state.permits("http://localhost:8787"));
assert!(state.permits("http://[::1]:8787"));
}
#[test]
fn origin_gate_rejects_foreign_origin() {
let addr: std::net::SocketAddr = "127.0.0.1:8787".parse().unwrap();
let state = OriginLayerState::from_bind_addr(addr);
assert!(!state.permits("http://evil.example.com"));
assert!(!state.permits("http://127.0.0.1:9999"));
assert!(!state.permits("https://127.0.0.1:8787"));
}
#[test]
fn origin_gate_explicit_allow_list() {
let state = OriginLayerState::from_allowed(vec!["http://allowed.test".to_string()]);
assert!(state.permits("http://allowed.test"));
assert!(state.permits("HTTP://ALLOWED.TEST"));
assert!(!state.permits("http://other.test"));
}
#[test]
fn layer_state_verifies_bootstrap_and_minted_keys() {
let store = std::sync::Arc::new(
super::super::api_keys::ApiKeyStore::open_in_memory().expect("store"),
);
let minted = store.mint("agent").expect("mint");
let state = AuthLayerState::new(AuthConfig::new(Some("boot".to_string())), true)
.with_key_store(std::sync::Arc::clone(&store));
assert!(state.verify_token("boot"));
assert!(state.verify_token(&minted.raw_secret));
assert!(!state.verify_token("nope"));
store.revoke(minted.record.id).expect("revoke");
assert!(!state.verify_token(&minted.raw_secret));
assert!(state.verify_token("boot"));
}
#[test]
fn layer_state_without_store_uses_bootstrap_only() {
let state = AuthLayerState::new(AuthConfig::new(Some("boot".to_string())), true);
assert!(state.verify_token("boot"));
assert!(!state.verify_token("anything-else"));
}
#[test]
fn no_key_non_loopback_requires_auth_and_refuses_to_start() {
let auth = AuthConfig::new(None);
assert!(
auth.requires_auth(false),
"no key + non-loopback => auth required"
);
assert_eq!(
auth.refuse_to_start(false),
Err(AuthStartupError::NonLoopbackWithoutKey),
"no key + non-loopback must refuse to start"
);
}
}