postgres_mcp/
http_guard.rs1use std::fmt;
4use std::sync::Arc;
5
6use axum::extract::{Request, State};
7use axum::middleware::Next;
8use axum::response::{IntoResponse, Response};
9use http::header::{AUTHORIZATION, CONTENT_TYPE, ORIGIN, WWW_AUTHENTICATE};
10use http::{HeaderMap, HeaderName, StatusCode};
11use sha2::{Digest, Sha256};
12use subtle::ConstantTimeEq;
13
14const X_API_KEY: HeaderName = HeaderName::from_static("x-api-key");
15const FORBIDDEN_BODY: &str = r#"{"error":"forbidden","message":"Origin not allowed"}"#;
16const UNAUTHORIZED_BODY: &str = r#"{"error":"unauthorized","message":"Missing or invalid API key. Send it as X-API-Key or Authorization: Bearer."}"#;
17
18#[derive(Clone)]
20pub struct ApiKey([u8; 32]);
21
22impl ApiKey {
23 pub fn new(key: &str) -> ApiKey {
24 ApiKey(Sha256::digest(key.as_bytes()).into())
25 }
26
27 pub fn matches(&self, presented: &[u8]) -> bool {
29 let digest: [u8; 32] = Sha256::digest(presented).into();
30 bool::from(self.0.as_slice().ct_eq(digest.as_slice()))
31 }
32}
33
34impl fmt::Debug for ApiKey {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 f.write_str("ApiKey(..)")
37 }
38}
39
40pub fn presented_key(headers: &HeaderMap) -> Option<Vec<u8>> {
42 if let Some(value) = headers.get(&X_API_KEY) {
43 return Some(value.as_bytes().to_vec());
44 }
45 let value = headers.get(AUTHORIZATION)?.as_bytes();
46 let space = value.iter().position(|&b| b == b' ')?;
47 let (scheme, rest) = value.split_at(space);
48 if scheme.eq_ignore_ascii_case(b"bearer") {
49 Some(rest.trim_ascii_start().to_vec())
50 } else {
51 None
52 }
53}
54
55#[derive(Debug, PartialEq, Eq)]
57pub(crate) struct OriginKey {
58 scheme: String,
59 host: String,
60 port: Option<u16>,
61}
62
63pub(crate) fn parse_origin(raw: &str) -> Option<OriginKey> {
65 let (_, rest) = raw.split_once("://")?;
66 if rest.is_empty() || rest.contains(['/', '?', '#', '@']) {
67 return None;
68 }
69 let url = url::Url::parse(raw).ok()?;
70 let host = url.host_str()?.to_ascii_lowercase();
71 if host.is_empty() {
72 return None;
73 }
74 Some(OriginKey {
75 scheme: url.scheme().to_owned(),
76 host,
77 port: url.port(),
78 })
79}
80
81fn is_loopback(origin: &OriginKey) -> bool {
82 matches!(origin.scheme.as_str(), "http" | "https")
83 && matches!(origin.host.as_str(), "localhost" | "127.0.0.1" | "[::1]")
84}
85
86pub fn origin_allowed(origin: &str, allowed: &[String]) -> bool {
88 let Some(key) = parse_origin(origin) else {
89 return false;
90 };
91 is_loopback(&key)
92 || allowed
93 .iter()
94 .filter_map(|a| parse_origin(a))
95 .any(|a| a == key)
96}
97
98#[derive(Clone)]
99pub struct GuardState {
100 pub api_key: Option<ApiKey>,
101 pub allowed_origins: Arc<Vec<String>>,
102}
103
104pub async fn guard(State(state): State<GuardState>, req: Request, next: Next) -> Response {
106 let mut origins = req.headers().get_all(ORIGIN).iter();
107 if let Some(origin) = origins.next() {
108 let allowed = origins.next().is_none()
109 && origin
110 .to_str()
111 .is_ok_and(|o| origin_allowed(o, &state.allowed_origins));
112 if !allowed {
113 tracing::warn!(path = %req.uri().path(), reason = "origin not allowed", "request rejected");
114 return forbidden();
115 }
116 }
117 if let Some(key) = &state.api_key {
118 let Some(presented) = presented_key(req.headers()) else {
119 tracing::warn!(path = %req.uri().path(), reason = "missing key", "request rejected");
120 return unauthorized();
121 };
122 if !key.matches(&presented) {
123 tracing::warn!(path = %req.uri().path(), reason = "wrong key", "request rejected");
124 return unauthorized();
125 }
126 }
127 next.run(req).await
128}
129
130fn forbidden() -> Response {
131 (
132 StatusCode::FORBIDDEN,
133 [(CONTENT_TYPE, "application/json")],
134 FORBIDDEN_BODY,
135 )
136 .into_response()
137}
138
139fn unauthorized() -> Response {
140 (
141 StatusCode::UNAUTHORIZED,
142 [
143 (WWW_AUTHENTICATE, "Bearer"),
144 (CONTENT_TYPE, "application/json"),
145 ],
146 UNAUTHORIZED_BODY,
147 )
148 .into_response()
149}