mirror of
https://gitea.ingwaz.work/Ingwaz/openbrain-mcp.git
synced 2026-06-15 22:07:08 +00:00
Scope memories by API token and add shared-token e2e coverage
This commit is contained in:
43
src/auth.rs
43
src/auth.rs
@@ -4,7 +4,7 @@
|
||||
|
||||
use axum::{
|
||||
extract::{Request, State},
|
||||
http::{HeaderMap, StatusCode, header::AUTHORIZATION},
|
||||
http::{header::AUTHORIZATION, HeaderMap, StatusCode},
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
@@ -14,6 +14,8 @@ use tracing::warn;
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
pub const PUBLIC_AUTH_SCOPE: &str = "public";
|
||||
|
||||
/// Hash an API key for secure comparison
|
||||
pub fn hash_api_key(key: &str) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
@@ -99,24 +101,25 @@ pub fn get_optional_agent_type(headers: &HeaderMap) -> Option<String> {
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
/// Extract agent ID from request headers or default
|
||||
pub fn get_agent_id(request: &Request) -> String {
|
||||
get_optional_agent_id(request.headers())
|
||||
.unwrap_or_else(|| "default".to_string())
|
||||
pub fn get_auth_scope(headers: &HeaderMap, auth_enabled: bool) -> String {
|
||||
if !auth_enabled {
|
||||
return PUBLIC_AUTH_SCOPE.to_string();
|
||||
}
|
||||
|
||||
extract_api_key(headers)
|
||||
.map(|key| hash_api_key(&key))
|
||||
.unwrap_or_else(|| PUBLIC_AUTH_SCOPE.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::http::{HeaderValue, header::AUTHORIZATION};
|
||||
use axum::http::{header::AUTHORIZATION, HeaderValue};
|
||||
|
||||
#[test]
|
||||
fn extracts_api_key_from_bearer_header() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_static("Bearer test-token"),
|
||||
);
|
||||
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer test-token"));
|
||||
|
||||
assert_eq!(extract_api_key(&headers).as_deref(), Some("test-token"));
|
||||
}
|
||||
@@ -137,9 +140,21 @@ mod tests {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("X-Agent-Type", HeaderValue::from_static("codex"));
|
||||
|
||||
assert_eq!(
|
||||
get_optional_agent_type(&headers).as_deref(),
|
||||
Some("codex")
|
||||
);
|
||||
assert_eq!(get_optional_agent_type(&headers).as_deref(), Some("codex"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derives_auth_scope_from_api_key_when_enabled() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("X-API-Key", HeaderValue::from_static("test-token"));
|
||||
|
||||
assert_eq!(get_auth_scope(&headers, true), hash_api_key("test-token"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_public_scope_when_auth_disabled() {
|
||||
let headers = HeaderMap::new();
|
||||
|
||||
assert_eq!(get_auth_scope(&headers, false), PUBLIC_AUTH_SCOPE);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user