Skip to main content

structured_proxy/auth/
forward.rs

1//! Forward-auth verification endpoint.
2//!
3//! Exposes `forward_auth.path` (default `/auth/verify`) so a fronting reverse
4//! proxy (nginx `auth_request`, Traefik `forwardAuth`) can delegate auth to this
5//! proxy: it validates the request's `Bearer` token against the configured route
6//! policies and answers 200 (with the verified claim headers) or 401/403.
7
8use std::sync::Arc;
9
10use axum::extract::Request;
11use axum::http::header::{HeaderValue, LOCATION};
12use axum::http::{HeaderMap, StatusCode};
13use axum::response::{IntoResponse, Response};
14use axum::routing::any;
15use axum::Router;
16
17use super::{forbidden, unauthorized, Auth, AuthDecision};
18use crate::config::AuthConfig;
19
20/// A verification endpoint backed by the shared [`Auth`] machinery.
21pub struct ForwardAuth {
22    auth: Arc<Auth>,
23    path: String,
24    login_url: Option<String>,
25}
26
27impl ForwardAuth {
28    /// Build the endpoint, or `None` when forward-auth is disabled.
29    ///
30    /// Shares the already-built [`Auth`], so the verify endpoint and the JWT
31    /// middleware evaluate identical keys and policies.
32    pub fn build(config: &AuthConfig, auth: Arc<Auth>) -> Option<Arc<Self>> {
33        let fa = config.forward_auth.as_ref()?;
34        if !fa.enabled {
35            return None;
36        }
37        Some(Arc::new(Self {
38            auth,
39            path: fa.path.clone(),
40            login_url: fa.login_url.clone(),
41        }))
42    }
43
44    /// The verification route, mounted at `forward_auth.path`.
45    pub fn routes<S>(self: &Arc<Self>) -> Router<S>
46    where
47        S: Clone + Send + Sync + 'static,
48    {
49        let fa = self.clone();
50        // Any method: the fronting proxy issues its own sub-request verb; the
51        // original verb arrives via the forwarding headers.
52        Router::new().route(
53            &self.path,
54            any(move |req: Request| {
55                let fa = fa.clone();
56                async move { fa.verify(req).await }
57            }),
58        )
59    }
60
61    async fn verify(&self, request: Request) -> Response {
62        let headers = request.headers();
63        let method = original_method(headers)
64            .unwrap_or_else(|| request.method().as_str().to_ascii_uppercase());
65        let path = original_path(headers).unwrap_or_else(|| request.uri().path().to_string());
66
67        match self.auth.decide(headers, &path, &method).await {
68            // 200 carries the verified claim headers for the fronting proxy to
69            // copy upstream.
70            AuthDecision::Allow(claim_headers, _) => {
71                (StatusCode::OK, claim_headers).into_response()
72            }
73            AuthDecision::Unauthenticated(msg) => self.deny(msg),
74            AuthDecision::Forbidden(msg) => forbidden(msg),
75        }
76    }
77
78    /// A 401, adding `Location: login_url` when configured so a fronting proxy
79    /// can drive an error-page redirect to the login flow.
80    fn deny(&self, msg: &'static str) -> Response {
81        let mut response = unauthorized(msg);
82        if let Some(url) = &self.login_url {
83            if let Ok(value) = HeaderValue::try_from(url.as_str()) {
84                response.headers_mut().insert(LOCATION, value);
85            }
86        }
87        response
88    }
89}
90
91/// The original request method, from the fronting proxy's forwarding headers.
92fn original_method(headers: &HeaderMap) -> Option<String> {
93    forwarded(headers, &["x-forwarded-method", "x-original-method"]).map(|m| m.to_ascii_uppercase())
94}
95
96/// The original request path (query stripped), from the forwarding headers.
97fn original_path(headers: &HeaderMap) -> Option<String> {
98    let raw = forwarded(headers, &["x-forwarded-uri", "x-original-uri"])?;
99    let path = raw.split_once('?').map_or(raw.as_str(), |(p, _)| p);
100    Some(path.to_string())
101}
102
103/// First non-empty value among `names`.
104fn forwarded(headers: &HeaderMap, names: &[&str]) -> Option<String> {
105    names
106        .iter()
107        .filter_map(|n| headers.get(*n).and_then(|v| v.to_str().ok()))
108        .find(|v| !v.is_empty())
109        .map(str::to_string)
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use crate::config::{AuthConfig, ForwardAuthConfig, JwtConfig, RoutePolicyConfig};
116    use axum::body::Body;
117    use axum::http::Request as HttpRequest;
118    use ed25519_dalek::{Signer, SigningKey};
119    use std::collections::HashMap;
120    use tower::ServiceExt;
121
122    // A fixed Ed25519 keypair so tests can sign tokens the proxy will accept.
123    fn keypair() -> (SigningKey, String) {
124        let sk = SigningKey::from_bytes(&[7u8; 32]);
125        let spki_prefix: [u8; 12] = [
126            0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
127        ];
128        let mut der = spki_prefix.to_vec();
129        der.extend_from_slice(sk.verifying_key().as_bytes());
130        use base64::Engine;
131        let b64 = base64::engine::general_purpose::STANDARD.encode(&der);
132        let pem = format!("-----BEGIN PUBLIC KEY-----\n{b64}\n-----END PUBLIC KEY-----\n");
133        (sk, pem)
134    }
135
136    fn sign(sk: &SigningKey, claims: &serde_json::Value) -> String {
137        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
138        use base64::Engine;
139        let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"EdDSA","typ":"JWT"}"#);
140        let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).unwrap());
141        let signing_input = format!("{header}.{payload}");
142        let sig = sk.sign(signing_input.as_bytes());
143        format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(sig.to_bytes()))
144    }
145
146    fn write_pem(pem: &str) -> std::path::PathBuf {
147        use std::sync::atomic::{AtomicU32, Ordering};
148        static N: AtomicU32 = AtomicU32::new(0);
149        let p = std::env::temp_dir().join(format!(
150            "sp_fa_{}_{}.pem",
151            std::process::id(),
152            N.fetch_add(1, Ordering::Relaxed)
153        ));
154        std::fs::write(&p, pem).unwrap();
155        p
156    }
157
158    fn forward_auth(pem_path: std::path::PathBuf, login_url: Option<String>) -> Arc<ForwardAuth> {
159        let mut claims_headers = HashMap::new();
160        claims_headers.insert("sub".to_string(), "x-forwarded-user".to_string());
161        let config = AuthConfig {
162            mode: "jwt".into(),
163            jwt: Some(JwtConfig {
164                issuer: None,
165                audience: None,
166                jwks_uri: None,
167                public_key_pem_file: Some(pem_path),
168                claims_headers,
169                roles_claim: "roles".into(),
170            }),
171            forward_auth: Some(ForwardAuthConfig {
172                enabled: true,
173                path: "/auth/verify".into(),
174                policies: vec![RoutePolicyConfig {
175                    path: "/v1/admin/**".into(),
176                    methods: vec!["*".into()],
177                    require_auth: true,
178                    required_roles: vec!["admin".into()],
179                }],
180                login_url,
181                applications_path: None,
182            }),
183            authz: None,
184        };
185        let auth = Auth::build(&config).unwrap().unwrap();
186        ForwardAuth::build(&config, auth).unwrap()
187    }
188
189    async fn call(fa: &Arc<ForwardAuth>, req: HttpRequest<Body>) -> Response {
190        let app: Router = fa.routes();
191        app.oneshot(req).await.unwrap()
192    }
193
194    fn verify_request(method: &str, uri: &str, token: Option<&str>) -> HttpRequest<Body> {
195        let mut b = HttpRequest::get("/auth/verify")
196            .header("x-forwarded-method", method)
197            .header("x-forwarded-uri", uri);
198        if let Some(t) = token {
199            b = b.header("authorization", format!("Bearer {t}"));
200        }
201        b.body(Body::empty()).unwrap()
202    }
203
204    #[tokio::test]
205    async fn allows_and_echoes_claim_header() {
206        let (sk, pem) = keypair();
207        let fa = forward_auth(write_pem(&pem), None);
208        let token = sign(
209            &sk,
210            &serde_json::json!({ "sub": "alice", "roles": ["admin"], "exp": 9999999999u64 }),
211        );
212        let resp = call(&fa, verify_request("GET", "/v1/admin/things", Some(&token))).await;
213        assert_eq!(resp.status(), StatusCode::OK);
214        // The verified identity is echoed for the fronting proxy to copy upstream.
215        assert_eq!(resp.headers()["x-forwarded-user"], "alice");
216    }
217
218    #[tokio::test]
219    async fn denies_without_token_and_sets_login_location() {
220        let (_sk, pem) = keypair();
221        let fa = forward_auth(write_pem(&pem), Some("https://login.example.com".into()));
222        let resp = call(&fa, verify_request("GET", "/v1/admin/things", None)).await;
223        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
224        assert_eq!(resp.headers()[LOCATION], "https://login.example.com");
225    }
226
227    #[tokio::test]
228    async fn forbids_when_role_missing() {
229        let (sk, pem) = keypair();
230        let fa = forward_auth(write_pem(&pem), None);
231        let token = sign(
232            &sk,
233            &serde_json::json!({ "sub": "bob", "roles": ["user"], "exp": 9999999999u64 }),
234        );
235        let resp = call(&fa, verify_request("GET", "/v1/admin/things", Some(&token))).await;
236        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
237    }
238
239    #[tokio::test]
240    async fn denies_invalid_token() {
241        // A token signed by a different key fails verification; the endpoint
242        // must reject it (401), never leak it through as authenticated.
243        let (_sk, pem) = keypair();
244        let fa = forward_auth(write_pem(&pem), None);
245        let wrong_key = SigningKey::from_bytes(&[9u8; 32]);
246        let token = sign(
247            &wrong_key,
248            &serde_json::json!({ "sub": "mallory", "roles": ["admin"], "exp": 9999999999u64 }),
249        );
250        let resp = call(&fa, verify_request("GET", "/v1/admin/things", Some(&token))).await;
251        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
252    }
253
254    #[tokio::test]
255    async fn allows_unprotected_original_path() {
256        // The verify sub-request hits /auth/verify, but the original path is a
257        // public route, so no token is required.
258        let (_sk, pem) = keypair();
259        let fa = forward_auth(write_pem(&pem), None);
260        let resp = call(&fa, verify_request("GET", "/v1/public/info", None)).await;
261        assert_eq!(resp.status(), StatusCode::OK);
262    }
263}