Skip to main content

hyprstream_core/services/oauth/
metadata.rs

1//! OAuth 2.1 / OpenID Connect discovery metadata.
2//!
3//! - `GET /.well-known/oauth-authorization-server` — RFC 8414
4//! - `GET /.well-known/openid-configuration` — OIDC Discovery 1.0
5
6use std::sync::Arc;
7
8use axum::{extract::State, response::IntoResponse, Json};
9
10use super::state::OAuthState;
11
12/// The full set of scopes the AS advertises in `scopes_supported` (#1113 rev2 F4).
13/// Extends the operator's default grant set with the atproto transition scopes,
14/// which are supported-but-explicit (NOT silently granted on omitted scope).
15fn advertised_scopes(default_scopes: &[String]) -> Vec<String> {
16    let mut scopes = default_scopes.to_vec();
17    for atproto_scope in &["atproto", "transition:generic"] {
18        if !scopes.iter().any(|s| s == *atproto_scope) {
19            scopes.push((*atproto_scope).to_owned());
20        }
21    }
22    scopes
23}
24
25/// Base metadata fields shared between RFC 8414 and OIDC discovery.
26fn base_metadata(issuer: &str, scopes: &[String], require_par: bool) -> serde_json::Value {
27    let mut scopes_supported = advertised_scopes(scopes);
28    if !scopes_supported.iter().any(|scope| scope == "pds:attach") {
29        scopes_supported.push("pds:attach".to_owned());
30    }
31    let endpoint_base = issuer.trim_end_matches('/');
32    serde_json::json!({
33        "issuer": issuer,
34        "authorization_endpoint": format!("{endpoint_base}/oauth/authorize"),
35        "token_endpoint": format!("{endpoint_base}/oauth/token"),
36        "registration_endpoint": format!("{endpoint_base}/oauth/register"),
37        "device_authorization_endpoint": format!("{endpoint_base}/oauth/device"),
38        "pushed_authorization_request_endpoint": format!("{endpoint_base}/oauth/par"),
39        "require_pushed_authorization_requests": require_par,
40        "jwks_uri": format!("{endpoint_base}/oauth/jwks"),
41        "response_types_supported": ["code"],
42        // #1425: the RFC 8693 token-exchange grant is advertised truthfully —
43        // the AS implements it at POST /oauth/token (generic bearer exchange,
44        // UCAN grant, and the sender-bound browser contract). Advertising a
45        // grant type the AS does not implement would be an RFC 8414 violation;
46        // omitting one it does implement hides the browser contract from
47        // RFC 8414 metadata discovery.
48        "grant_types_supported": [
49            "authorization_code",
50            "refresh_token",
51            "urn:ietf:params:oauth:grant-type:device_code",
52            "urn:ietf:params:oauth:grant-type:token-exchange"
53        ],
54        "code_challenge_methods_supported": ["S256"],
55        // #1113 rev2 finding 5: atproto profile metadata. The AS accepts both
56        // public clients (PKCE) and `private_key_jwt` (RFC 7523), signs token
57        // endpoint assertions with ES256, signals DPoP-ES256 support, and
58        // emits `authorization_endpoint` `iss` query parameter on redirects.
59        "token_endpoint_auth_methods_supported": ["none", "private_key_jwt"],
60        "token_endpoint_auth_signing_alg_values_supported": ["ES256"],
61        // RFC 9449 §9: the AS issues DPoP-bound access tokens (cnf.jkt) and
62        // accepts DPoP proofs at the token endpoint. ES256 is the
63        // browser-classical DPoP algorithm the sender-bound contract (#1425)
64        // uses; it is the value advertised, and it is supported.
65        "dpop_signing_alg_values_supported": ["ES256", "EdDSA"],
66        "dpop_bound_access_tokens_supported": true,
67        "authorization_response_iss_parameter_supported": true,
68        "scopes_supported": scopes_supported,
69        "client_id_metadata_document_supported": true,
70    })
71}
72
73fn atproto_metadata(issuer: &str, scopes: &[String], require_par: bool) -> serde_json::Value {
74    let issuer = super::state::canonical_issuer_origin(issuer).unwrap_or_else(|| issuer.to_owned());
75    base_metadata(&issuer, scopes, require_par)
76}
77
78/// GET /.well-known/oauth-authorization-server (RFC 8414)
79pub async fn authorization_server_metadata(
80    State(state): State<Arc<OAuthState>>,
81) -> impl IntoResponse {
82    Json(atproto_metadata(
83        &state.issuer_url,
84        &state.default_scopes,
85        state.require_pushed_authorization_requests,
86    ))
87}
88
89/// GET /.well-known/openid-configuration (OIDC Discovery 1.0)
90///
91/// Superset of RFC 8414 metadata with OIDC-specific fields:
92/// userinfo_endpoint, id_token_signing_alg_values_supported,
93/// subject_types_supported, claims_supported.
94pub async fn openid_configuration(State(state): State<Arc<OAuthState>>) -> impl IntoResponse {
95    let issuer = &state.issuer_url;
96    let mut meta = base_metadata(
97        issuer,
98        &state.default_scopes,
99        state.require_pushed_authorization_requests,
100    );
101
102    // OIDC-specific fields
103    let obj = meta.as_object_mut().unwrap_or_else(|| unreachable!());
104    obj.insert(
105        "userinfo_endpoint".into(),
106        serde_json::Value::String(format!("{}/oauth/userinfo", issuer.trim_end_matches('/'))),
107    );
108    obj.insert(
109        "id_token_signing_alg_values_supported".into(),
110        serde_json::json!(["EdDSA", "RS256"]),
111    );
112    obj.insert(
113        "subject_types_supported".into(),
114        serde_json::json!(["public"]),
115    );
116    obj.insert(
117        "claims_supported".into(),
118        serde_json::json!([
119            "sub",
120            "iss",
121            "aud",
122            "exp",
123            "iat",
124            "nonce",
125            "auth_time",
126            "name",
127            "email",
128            "email_verified",
129            "preferred_username"
130        ]),
131    );
132
133    Json(meta)
134}
135
136#[cfg(test)]
137#[allow(clippy::unwrap_used)]
138mod tests {
139    use super::*;
140
141    /// #1113: the atproto OAuth AS conformance scopes (`atproto`,
142    /// `transition:generic`) are advertised in `scopes_supported` so stock
143    /// atproto clients (e.g. `@atproto/oauth-client-browser`) discover them.
144    #[test]
145    fn authorization_server_metadata_advertises_atproto_scopes() {
146        let scopes = vec![
147            "read:*:*".to_owned(),
148            "write:*:*".to_owned(),
149            "atproto".to_owned(),
150            "transition:generic".to_owned(),
151        ];
152        let meta = base_metadata("https://pds.example.com", &scopes, true);
153        let advertised: Vec<&str> = meta["scopes_supported"]
154            .as_array()
155            .unwrap()
156            .iter()
157            .map(|v| v.as_str().unwrap())
158            .collect();
159        assert!(
160            advertised.contains(&"atproto"),
161            "scopes_supported missing atproto: {advertised:?}"
162        );
163        assert!(
164            advertised.contains(&"transition:generic"),
165            "scopes_supported missing transition:generic: {advertised:?}"
166        );
167    }
168
169    /// #1113: PAR is mandatory for the atproto AS profile, and the AS metadata
170    /// must reflect `require_pushed_authorization_requests: true`.
171    #[test]
172    fn authorization_server_metadata_requires_par_when_configured() {
173        let meta = base_metadata("https://pds.example.com", &[], true);
174        assert_eq!(
175            meta["require_pushed_authorization_requests"].as_bool(),
176            Some(true)
177        );
178        assert_eq!(
179            meta["pushed_authorization_request_endpoint"].as_str(),
180            Some("https://pds.example.com/oauth/par")
181        );
182    }
183
184    /// #1113 rev2 finding 5: the RFC 8414 document carries the full atproto
185    /// profile metadata surface — private_key_jwt client auth, ES256 token
186    /// signing alg, DPoP ES256, iss-parameter support, and a canonical
187    /// origin issuer (no trailing slash/path).
188    #[test]
189    fn authorization_server_metadata_has_atproto_profile_fields() {
190        let meta = atproto_metadata("https://pds.example.com/", &["atproto".to_owned()], true);
191
192        // Issuer canonicalized to exact origin (trailing slash stripped).
193        assert_eq!(meta["issuer"].as_str(), Some("https://pds.example.com"));
194        assert_eq!(
195            meta["token_endpoint"].as_str(),
196            Some("https://pds.example.com/oauth/token"),
197            "no double-slash from a trailing-slash issuer"
198        );
199
200        let auth_methods: Vec<&str> = meta["token_endpoint_auth_methods_supported"]
201            .as_array()
202            .unwrap()
203            .iter()
204            .map(|v| v.as_str().unwrap())
205            .collect();
206        assert!(
207            auth_methods.contains(&"none"),
208            "public clients (PKCE) must be accepted"
209        );
210        assert!(
211            auth_methods.contains(&"private_key_jwt"),
212            "private_key_jwt must be advertised"
213        );
214
215        let token_algs: Vec<&str> = meta["token_endpoint_auth_signing_alg_values_supported"]
216            .as_array()
217            .unwrap()
218            .iter()
219            .map(|v| v.as_str().unwrap())
220            .collect();
221        assert!(token_algs.contains(&"ES256"));
222
223        let dpop_algs: Vec<&str> = meta["dpop_signing_alg_values_supported"]
224            .as_array()
225            .unwrap()
226            .iter()
227            .map(|v| v.as_str().unwrap())
228            .collect();
229        assert!(dpop_algs.contains(&"ES256"));
230
231        assert_eq!(
232            meta["authorization_response_iss_parameter_supported"].as_bool(),
233            Some(true)
234        );
235
236        // #1425: RFC 8414 truthfulness — the token-exchange grant the AS
237        // implements is advertised, and DPoP-bound access tokens are signalled
238        // (RFC 9449 §9) so the browser sender-bound contract is discoverable.
239        let grants: Vec<&str> = meta["grant_types_supported"]
240            .as_array()
241            .unwrap()
242            .iter()
243            .map(|v| v.as_str().unwrap())
244            .collect();
245        assert!(
246            grants.contains(&"urn:ietf:params:oauth:grant-type:token-exchange"),
247            "RFC 8414 must advertise the implemented token-exchange grant: {grants:?}"
248        );
249        assert_eq!(
250            meta["dpop_bound_access_tokens_supported"].as_bool(),
251            Some(true),
252            "RFC 9449 §9 dpop_bound_access_tokens_supported must be true"
253        );
254    }
255
256    #[test]
257    fn issuer_paths_are_profile_specific() {
258        let configured = "https://as.example/tenant";
259        let generic = base_metadata(configured, &["read:*:*".to_owned()], false);
260        assert_eq!(generic["issuer"], configured);
261        assert_eq!(
262            generic["token_endpoint"],
263            "https://as.example/tenant/oauth/token"
264        );
265
266        let atproto = atproto_metadata(configured, &["atproto".to_owned()], true);
267        assert_eq!(atproto["issuer"], "https://as.example");
268        assert_eq!(atproto["token_endpoint"], "https://as.example/oauth/token");
269    }
270}