BlueGit

ict rusty-teams

Files

rusty-teams / crates / mcp / src / auth.rs

auth.rs

auth.rs 4.4 KiB Download Raw
1use axum::body::Body;
2use axum::extract::State;
3use axum::http::header::{AUTHORIZATION, HOST, ORIGIN};
4use axum::http::{HeaderMap, Request, StatusCode};
5use axum::middleware::Next;
6use axum::response::{IntoResponse, Response};
7use subtle::ConstantTimeEq;
8
9pub const MAX_BODY_BYTES: usize = 24 * 1024 * 1024;
10const LOOPBACK_HOSTS: [&str; 2] = ["127.0.0.1", "localhost"];
11const BEARER_PREFIX: &str = "Bearer ";
12
13#[derive(Clone)]
14pub struct AuthState {
15 pub port: u16,
16 pub token: String,
17}
18
19impl AuthState {
20 pub fn allowed_hosts(&self) -> Vec<String> {
21 LOOPBACK_HOSTS
22 .iter()
23 .map(|host| format!("{host}:{}", self.port))
24 .collect()
25 }
26
27 pub fn allowed_origins(&self) -> Vec<String> {
28 self.allowed_hosts()
29 .into_iter()
30 .map(|authority| format!("http://{authority}"))
31 .collect()
32 }
33
34 fn host_allowed(&self, headers: &HeaderMap) -> bool {
35 header_text(headers, HOST)
36 .is_some_and(|host| self.allowed_hosts().iter().any(|allowed| allowed == host))
37 }
38
39 fn origin_allowed(&self, headers: &HeaderMap) -> bool {
40 match headers.get(ORIGIN) {
41 None => true,
42 Some(origin) => origin.to_str().is_ok_and(|origin| {
43 self.allowed_origins()
44 .iter()
45 .any(|allowed| allowed == origin)
46 }),
47 }
48 }
49
50 fn token_valid(&self, headers: &HeaderMap) -> bool {
51 header_text(headers, AUTHORIZATION)
52 .and_then(|value| value.strip_prefix(BEARER_PREFIX))
53 .is_some_and(|presented| presented.as_bytes().ct_eq(self.token.as_bytes()).into())
54 }
55}
56
57fn header_text(headers: &HeaderMap, name: axum::http::HeaderName) -> Option<&str> {
58 headers.get(name)?.to_str().ok()
59}
60
61pub async fn require_auth(
62 State(auth): State<AuthState>,
63 request: Request<Body>,
64 next: Next,
65) -> Response {
66 let headers = request.headers();
67 if !auth.host_allowed(headers) || !auth.origin_allowed(headers) {
68 return StatusCode::FORBIDDEN.into_response();
69 }
70 if !auth.token_valid(headers) {
71 return StatusCode::UNAUTHORIZED.into_response();
72 }
73 next.run(request).await
74}
75
76pub async fn healthz() -> &'static str {
77 "ok"
78}
79
80#[cfg(test)]
81mod tests {
82 use axum::http::HeaderValue;
83
84 use super::*;
85
86 fn auth() -> AuthState {
87 AuthState {
88 port: 47615,
89 token: "secret".to_owned(),
90 }
91 }
92
93 fn headers(pairs: &[(axum::http::HeaderName, &str)]) -> HeaderMap {
94 let mut map = HeaderMap::new();
95 for (name, value) in pairs {
96 map.insert(name.clone(), HeaderValue::from_str(value).unwrap());
97 }
98 map
99 }
100
101 #[test]
102 fn host_must_be_loopback_with_the_port() {
103 let cases = [
104 ("127.0.0.1:47615", true),
105 ("localhost:47615", true),
106 ("localhost:1", false),
107 ("127.0.0.1", false),
108 ("evil.example:47615", false),
109 ("evil.example", false),
110 ];
111 for (host, allowed) in cases {
112 assert_eq!(
113 auth().host_allowed(&headers(&[(HOST, host)])),
114 allowed,
115 "{host}"
116 );
117 }
118 assert!(!auth().host_allowed(&HeaderMap::new()));
119 }
120
121 #[test]
122 fn origin_is_absent_or_loopback() {
123 let cases = [
124 (None, true),
125 (Some("http://127.0.0.1:47615"), true),
126 (Some("http://localhost:47615"), true),
127 (Some("https://localhost:47615"), false),
128 (Some("http://evil.example"), false),
129 (Some("null"), false),
130 ];
131 for (origin, allowed) in cases {
132 let map = origin.map_or_else(HeaderMap::new, |value| headers(&[(ORIGIN, value)]));
133 assert_eq!(auth().origin_allowed(&map), allowed, "{origin:?}");
134 }
135 }
136
137 #[test]
138 fn token_needs_the_exact_bearer_value() {
139 let cases = [
140 ("Bearer secret", true),
141 ("Bearer secre", false),
142 ("Bearer secrets", false),
143 ("bearer secret", false),
144 ("secret", false),
145 ];
146 for (value, valid) in cases {
147 assert_eq!(
148 auth().token_valid(&headers(&[(AUTHORIZATION, value)])),
149 valid,
150 "{value}"
151 );
152 }
153 assert!(!auth().token_valid(&HeaderMap::new()));
154 }
155}