#[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,
))
}
#[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""));
}
#[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"
);
}
}