Skip to main content

systemprompt_api/services/proxy/auth/
challenge.rs

1//! OAuth challenge construction for the proxy auth boundary.
2//!
3//! [`OAuthChallengeBuilder`] builds the `WWW-Authenticate: Bearer` 401/403
4//! responses (per RFC 6750 and RFC 9728) that drive MCP and agent clients into
5//! their OAuth discovery handshake, deriving the advertised `resource_metadata`
6//! URL from the incoming request host. [`AuthValidator`] performs the bearer
7//! check and [`challenge_or_error`] maps a failed check onto a [`ProxyError`].
8//!
9//! Copyright (c) systemprompt.io — Business Source License 1.1.
10//! See <https://systemprompt.io> for licensing details.
11
12use axum::body::Body;
13use axum::http::header::{AUTHORIZATION, HOST};
14use axum::http::{HeaderMap, StatusCode};
15use axum::response::Response;
16use serde_json::json;
17
18use crate::services::proxy::backend::ProxyError;
19use crate::services::request_base_url::resolve as resolve_request_base_url;
20use systemprompt_models::RequestContext;
21use systemprompt_models::auth::AuthenticatedUser;
22use systemprompt_models::modules::ApiPaths;
23use systemprompt_oauth::services::AuthService;
24use systemprompt_runtime::AppContext;
25
26#[derive(Debug, Clone, Copy)]
27pub(super) struct AuthValidator;
28
29impl AuthValidator {
30    pub(super) fn validate_service_access(
31        headers: &HeaderMap,
32        service_name: &str,
33        req_context: Option<&RequestContext>,
34    ) -> Result<AuthenticatedUser, StatusCode> {
35        let result = AuthService::authorize_service_access(headers, service_name);
36
37        if let Err(status) = &result {
38            let trace_id =
39                req_context.map_or_else(|| "unknown".to_owned(), |rc| rc.trace_id().to_string());
40            tracing::warn!(service = %service_name, status = %status, trace_id = %trace_id, "auth failed");
41        }
42
43        result
44    }
45}
46
47pub(super) struct ChallengeRequest<'a> {
48    pub service_name: &'a str,
49    pub resource_path: &'a str,
50    pub headers: &'a HeaderMap,
51    pub ctx: &'a AppContext,
52    pub status_code: StatusCode,
53    pub has_authorization: bool,
54}
55
56#[derive(Debug, Clone, Copy)]
57pub struct OAuthChallengeBuilder;
58
59impl OAuthChallengeBuilder {
60    pub fn resource_metadata_url(
61        headers: &HeaderMap,
62        configured_api_external_url: &str,
63        resource_path: &str,
64    ) -> Result<String, url::ParseError> {
65        let configured = url::Url::parse(configured_api_external_url)?;
66        let raw_host = headers.get(HOST).and_then(|v| v.to_str().ok());
67        let base = resolve_request_base_url(raw_host, &configured).into_string();
68        Ok(format!(
69            "{base}/.well-known/oauth-protected-resource{resource_path}"
70        ))
71    }
72
73    pub(super) fn build_challenge_response(
74        req: &ChallengeRequest<'_>,
75    ) -> Result<Response<Body>, StatusCode> {
76        let ChallengeRequest {
77            service_name,
78            resource_path,
79            headers,
80            ctx,
81            status_code,
82            has_authorization,
83        } = *req;
84        tracing::warn!(service = %service_name, status = %status_code, "Building OAuth challenge");
85
86        let resource_metadata_url =
87            Self::resource_metadata_url(headers, &ctx.config().api_external_url, resource_path)
88                .map_err(|e| {
89                    tracing::error!(error = %e, "api_external_url is not a valid URL");
90                    StatusCode::INTERNAL_SERVER_ERROR
91                })?;
92
93        let (auth_header_value, error_body) = if status_code == StatusCode::UNAUTHORIZED {
94            if has_authorization {
95                let header = format!(
96                    "Bearer realm=\"{service_name}\", \
97                     resource_metadata=\"{resource_metadata_url}\", error=\"invalid_token\", \
98                     error_description=\"The access token is missing or invalid\""
99                );
100                let body = json!({
101                    "error": "invalid_token",
102                    "error_description": "The access token is missing or invalid",
103                    "server": service_name
104                });
105                (header, body)
106            } else {
107                // Why: RFC 6750 §3: omit `error` on the no-credentials challenge so clients
108                // know to start the OAuth flow rather than treat the request as rejected.
109                let header = format!(
110                    "Bearer realm=\"{service_name}\", \
111                     resource_metadata=\"{resource_metadata_url}\""
112                );
113                (header, json!({}))
114            }
115        } else {
116            let header = format!(
117                "Bearer realm=\"{service_name}\", error=\"insufficient_scope\", \
118                 error_description=\"The access token lacks required scope\""
119            );
120            let body = json!({
121                "error": "insufficient_scope",
122                "error_description": "The access token does not have the required scope for this resource",
123                "server": service_name
124            });
125            (header, body)
126        };
127
128        Response::builder()
129            .status(status_code)
130            .header("Content-Type", "application/json")
131            .header("WWW-Authenticate", auth_header_value)
132            .body(Body::from(error_body.to_string()))
133            .map_err(|e| {
134                tracing::error!(error = %e, "Failed to build OAuth challenge response");
135                StatusCode::INTERNAL_SERVER_ERROR
136            })
137    }
138}
139
140pub(crate) fn build_mcp_unknown_service_challenge(
141    service_name: &str,
142    headers: &HeaderMap,
143    ctx: &AppContext,
144    req_context: Option<&RequestContext>,
145) -> Option<ProxyError> {
146    let status_code =
147        AuthValidator::validate_service_access(headers, service_name, req_context).err()?;
148    let resource_path = ApiPaths::mcp_server_endpoint(service_name);
149    let has_authorization = headers.get(AUTHORIZATION).is_some();
150    Some(challenge_or_error(&ChallengeRequest {
151        service_name,
152        resource_path: &resource_path,
153        headers,
154        ctx,
155        status_code,
156        has_authorization,
157    }))
158}
159
160pub(super) fn challenge_or_error(req: &ChallengeRequest<'_>) -> ProxyError {
161    match OAuthChallengeBuilder::build_challenge_response(req) {
162        Ok(challenge_response) => ProxyError::AuthChallenge(Box::new(challenge_response)),
163        Err(status) if status == StatusCode::UNAUTHORIZED => ProxyError::AuthenticationRequired {
164            service: req.service_name.to_owned(),
165        },
166        Err(_) => ProxyError::Forbidden {
167            service: req.service_name.to_owned(),
168        },
169    }
170}