Skip to main content

guardrail_proxy/
auth.rs

1//! Caller authentication (`[auth]`).
2//!
3//! Optional shared-secret check, separate from the upstream provider's
4//! `Authorization` header (which is always forwarded opaquely and never
5//! inspected here). See `docs/threat-model.md` for the security properties
6//! and residual risk of this mechanism.
7
8use guardrail_config::schema::AuthConfig;
9use hyper::HeaderMap;
10
11/// Endpoints that never require a caller key, regardless of `[auth]`
12/// configuration — monitoring systems need unauthenticated access to these.
13pub(crate) const AUTH_EXEMPT_PATHS: &[&str] = &["/healthz", "/metrics"];
14
15/// The header callers must present their guardrail API key in.
16pub(crate) const AUTH_HEADER_NAME: &str = "x-guardrail-key";
17
18/// Check whether a request is authorized to proceed.
19///
20/// Returns `true` if the request should be allowed past the auth gate:
21/// either `auth.require_key` is `false`, the path is exempt, or the
22/// presented key matches one of `auth.keys`.
23///
24/// Extracted as a pure function (no I/O, no state beyond what's passed in)
25/// specifically so it's unit-testable without spinning up a real TCP
26/// listener — the [`crate::server`] integration tests cover the end-to-end
27/// HTTP behavior, and the tests in this module cover every branch of the
28/// authorization decision itself in isolation.
29///
30/// # Examples
31///
32/// ```rust
33/// use guardrail_config::schema::AuthConfig;
34/// use guardrail_proxy::auth::is_authorized;
35/// use hyper::HeaderMap;
36///
37/// let config = AuthConfig { require_key: true, keys: vec!["secret".into()] };
38///
39/// let mut headers = HeaderMap::new();
40/// headers.insert("x-guardrail-key", "secret".parse().unwrap());
41/// assert!(is_authorized(&config, "/v1/chat/completions", &headers));
42///
43/// let empty_headers = HeaderMap::new();
44/// assert!(!is_authorized(&config, "/v1/chat/completions", &empty_headers));
45///
46/// // Health checks are always exempt, even with no key presented.
47/// assert!(is_authorized(&config, "/healthz", &empty_headers));
48/// ```
49pub fn is_authorized(config: &AuthConfig, path: &str, headers: &HeaderMap) -> bool {
50    if !config.require_key {
51        return true;
52    }
53    if AUTH_EXEMPT_PATHS.contains(&path) {
54        return true;
55    }
56
57    let presented_key = headers.get(AUTH_HEADER_NAME).and_then(|v| v.to_str().ok());
58
59    match presented_key {
60        Some(key) => matches_any_key(&config.keys, key),
61        None => false,
62    }
63}
64
65/// Compare `presented` against every configured key without leaking, through
66/// timing, how many leading bytes matched or which key matched.
67///
68/// Each comparison is constant-time in the key contents (`subtle`), and every
69/// key is checked even after a match. Key *lengths* can still be observed, as
70/// with any comparison that doesn't hash first; keys are meant to be long
71/// random strings, so their length isn't the secret part.
72fn matches_any_key(keys: &[String], presented: &str) -> bool {
73    use subtle::{Choice, ConstantTimeEq};
74
75    let presented = presented.as_bytes();
76    let matched = keys.iter().fold(Choice::from(0), |acc, k| {
77        acc | k.as_bytes().ct_eq(presented)
78    });
79    matched.into()
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    fn headers_with_key(key: &str) -> HeaderMap {
87        let mut h = HeaderMap::new();
88        h.insert(AUTH_HEADER_NAME, key.parse().unwrap());
89        h
90    }
91
92    #[test]
93    fn test_disabled_auth_always_allows() {
94        let config = AuthConfig {
95            require_key: false,
96            keys: vec![],
97        };
98        assert!(is_authorized(
99            &config,
100            "/v1/chat/completions",
101            &HeaderMap::new()
102        ));
103    }
104
105    #[test]
106    fn test_missing_key_rejected() {
107        let config = AuthConfig {
108            require_key: true,
109            keys: vec!["secret".into()],
110        };
111        assert!(!is_authorized(
112            &config,
113            "/v1/chat/completions",
114            &HeaderMap::new()
115        ));
116    }
117
118    #[test]
119    fn test_wrong_key_rejected() {
120        let config = AuthConfig {
121            require_key: true,
122            keys: vec!["secret".into()],
123        };
124        let headers = headers_with_key("wrong");
125        assert!(!is_authorized(&config, "/v1/chat/completions", &headers));
126    }
127
128    #[test]
129    fn test_correct_key_allowed() {
130        let config = AuthConfig {
131            require_key: true,
132            keys: vec!["secret".into()],
133        };
134        let headers = headers_with_key("secret");
135        assert!(is_authorized(&config, "/v1/chat/completions", &headers));
136    }
137
138    #[test]
139    fn test_one_of_multiple_keys_allowed() {
140        let config = AuthConfig {
141            require_key: true,
142            keys: vec!["key-a".into(), "key-b".into()],
143        };
144        assert!(is_authorized(
145            &config,
146            "/v1/chat/completions",
147            &headers_with_key("key-b")
148        ));
149    }
150
151    #[test]
152    fn test_healthz_exempt_even_without_key() {
153        let config = AuthConfig {
154            require_key: true,
155            keys: vec!["secret".into()],
156        };
157        assert!(is_authorized(&config, "/healthz", &HeaderMap::new()));
158    }
159
160    #[test]
161    fn test_metrics_exempt_even_without_key() {
162        let config = AuthConfig {
163            require_key: true,
164            keys: vec!["secret".into()],
165        };
166        assert!(is_authorized(&config, "/metrics", &HeaderMap::new()));
167    }
168
169    #[test]
170    fn test_proxy_path_not_exempt() {
171        let config = AuthConfig {
172            require_key: true,
173            keys: vec!["secret".into()],
174        };
175        assert!(!is_authorized(&config, "/v1/messages", &HeaderMap::new()));
176    }
177
178    #[test]
179    fn test_matches_any_key() {
180        let keys = vec!["key-a".to_string(), "key-b".to_string()];
181        assert!(matches_any_key(&keys, "key-a"));
182        assert!(matches_any_key(&keys, "key-b"));
183        assert!(!matches_any_key(&keys, "key-c"));
184        // Prefixes, extensions and empty strings never match.
185        assert!(!matches_any_key(&keys, "key-"));
186        assert!(!matches_any_key(&keys, "key-a2"));
187        assert!(!matches_any_key(&keys, ""));
188        assert!(!matches_any_key(&[], "key-a"));
189    }
190
191    #[test]
192    fn test_key_comparison_does_not_use_eq() {
193        // Guards against reintroducing a short-circuiting `==` on the secret.
194        let src = include_str!("auth.rs").replace("\r\n", "\n");
195        let body = src
196            .split("fn matches_any_key")
197            .nth(1)
198            .and_then(|rest| rest.split("\n}\n").next())
199            .expect("matches_any_key body");
200        assert!(body.contains("ct_eq"), "key comparison must use ct_eq");
201        assert!(!body.contains("=="), "key comparison must not use ==");
202    }
203
204    #[test]
205    fn test_empty_keys_list_rejects_everything() {
206        // Misconfiguration (require_key=true, keys=[]) is caught by config
207        // validation separately, but this function must still fail closed
208        // rather than panic or accidentally allow.
209        let config = AuthConfig {
210            require_key: true,
211            keys: vec![],
212        };
213        assert!(!is_authorized(
214            &config,
215            "/v1/chat/completions",
216            &headers_with_key("anything")
217        ));
218    }
219}