huskarl-resource-server 0.9.0

OAuth2 resource server (JWT validation) support for the huskarl ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Accept access tokens from several issuers with one validator.
//!
//! [`MultiIssuerValidator`] routes each request to a per-issuer validator by
//! reading the token's `iss` claim, then delegates the full validation to it. It
//! implements [`AccessTokenValidator`], so it drops into a `ValidatorLayer`,
//! Pingora guard, or any other consumer exactly like a single-issuer validator.
//!
//! Per-issuer validators usually have different claims types; wrap each in
//! [`MapClaims`] to give them a common type. For why issuer-based routing is
//! safe and how to unify claim types, see the [multi-issuer routing
//! explanation](crate::_docs::explanation::multi_issuer_routing); for a worked
//! two-issuer example, see the [multi-issuer
//! guide](crate::_docs::guide::multi_issuer).

pub mod error;
mod map;
mod source;

use std::collections::HashMap;

use base64::prelude::*;
pub use error::MultiIssuerError;
use http::{HeaderName, header::AUTHORIZATION};
pub use map::MapClaims;
use serde::Deserialize;

use crate::{
    AccessTokenValidator,
    core::platform::{MaybeSendBoxFuture, MaybeSendSync},
    error::ToRfc6750Error,
    validator::{
        ValidationResult,
        extract::extract_token,
        metadata::{ProvideValidatorMetadata, ValidatorMetadata},
        multi_issuer::source::{FoldError, SourceValidator},
    },
};

/// A validator that accepts tokens from several issuers, routing each request to
/// a per-issuer validator that produces a common claims type `C`.
///
/// Build one with [`MultiIssuerValidator::builder`]. See the [module
/// documentation](self) for routing semantics and an example.
pub struct MultiIssuerValidator<C> {
    by_issuer: HashMap<String, Box<dyn SourceValidator<C>>>,
    metadata: ValidatorMetadata,
    token_header: HeaderName,
}

#[bon::bon]
impl<C: MaybeSendSync + 'static> MultiIssuerValidator<C> {
    /// Creates a [`MultiIssuerValidator`], precomputing the union of the
    /// registered validators' metadata.
    ///
    /// Register validators with [`source`](MultiIssuerValidatorBuilder::source);
    /// the build is invoked via [`MultiIssuerValidator::builder`].
    #[builder]
    pub fn new(
        /// Per-issuer validators, accumulated by
        /// [`source`](MultiIssuerValidatorBuilder::source).
        #[builder(field)]
        sources: Vec<(String, Box<dyn SourceValidator<C>>)>,
        /// The HTTP header to extract the access token from. Defaults to
        /// `Authorization`.
        #[builder(default = AUTHORIZATION)]
        token_header: HeaderName,
    ) -> Self {
        let metadata = union_metadata(&sources, None);
        Self {
            by_issuer: sources.into_iter().collect(),
            metadata,
            token_header,
        }
    }
}

impl<C: MaybeSendSync + 'static, S: multi_issuer_validator_builder::State>
    MultiIssuerValidatorBuilder<C, S>
{
    /// Registers `validator` for tokens whose `iss` claim equals `issuer`.
    ///
    /// The validator must produce `Claims = C`; wrap source-specific validators
    /// in [`MapClaims`] to normalize their claims into `C`. If the same issuer is
    /// registered twice, the last registration wins. Call repeatedly, once per
    /// authorization server.
    pub fn source<V>(mut self, issuer: impl Into<String>, validator: V) -> Self
    where
        V: AccessTokenValidator<Claims = C> + ProvideValidatorMetadata + 'static,
        V::Error: ToRfc6750Error + 'static,
    {
        self.sources
            .push((issuer.into(), Box::new(FoldError(validator))));
        self
    }
}

impl<C: MaybeSendSync + 'static> AccessTokenValidator for MultiIssuerValidator<C> {
    type Claims = C;
    type Error = MultiIssuerError;

    fn validate_request<'a>(
        &'a self,
        headers: &'a http::HeaderMap,
        method: &'a http::Method,
        uri: &'a http::Uri,
        client_cert_der: Option<&'a [u8]>,
    ) -> MaybeSendBoxFuture<'a, ValidationResult<C, MultiIssuerError>> {
        Box::pin(async move {
            // Extract the token. No token is an unauthenticated request, matching
            // the single-issuer validators (`Ok(None)`), not an error.
            let token = match extract_token(headers, &self.token_header) {
                Ok(Some((_token_type, token))) => token,
                Ok(None) => {
                    return ValidationResult {
                        outcome: Ok(None),
                        dpop_nonce: None,
                    };
                }
                Err(e) => {
                    return ValidationResult {
                        outcome: Err(MultiIssuerError::Extract { source: e }),
                        dpop_nonce: None,
                    };
                }
            };

            // Route on the unverified issuer; the selected validator does all
            // real verification. A missing/unparseable/unregistered issuer is
            // rejected.
            let Some(validator) =
                peek_issuer(token.expose_secret()).and_then(|iss| self.by_issuer.get(&iss))
            else {
                return ValidationResult {
                    outcome: Err(MultiIssuerError::UnrecognizedIssuer),
                    dpop_nonce: None,
                };
            };

            validator
                .validate_request(headers, method, uri, client_cert_der)
                .await
        })
    }
}

impl<C> ProvideValidatorMetadata for MultiIssuerValidator<C> {
    fn validator_metadata(&self, resource: Option<&str>) -> ValidatorMetadata {
        // `resource` is per-deployment, so stamp it onto the precomputed union.
        ValidatorMetadata {
            resource: resource.map(str::to_owned),
            ..self.metadata.clone()
        }
    }
}

/// Reads the `iss` claim from a JWS compact payload **without verifying the
/// signature**.
///
/// The result is used only to select a validator (see the [module
/// documentation](self)); it carries no trust. Returns `None` if the token is
/// not a three-part JWS, the payload is not valid base64url JSON, or it has no
/// string `iss`.
fn peek_issuer(token: &str) -> Option<String> {
    #[derive(Deserialize)]
    struct IssOnly {
        iss: String,
    }

    let mut parts = token.split('.');
    let _header = parts.next()?;
    let payload = parts.next()?;
    parts.next()?; // require a signature segment
    if parts.next().is_some() {
        return None; // more than three segments is not a JWS
    }

    let bytes = BASE64_URL_SAFE_NO_PAD.decode(payload).ok()?;
    serde_json::from_slice::<IssOnly>(&bytes)
        .ok()
        .map(|i| i.iss)
}

/// Builds the union of the registered validators' [`ValidatorMetadata`]:
/// concatenated `authorization_servers`, unioned `DPoP` signing algorithms,
/// `dpop_bound_access_tokens_required` only if *every* source requires it (so a
/// token may still be presented as Bearer if any source accepts Bearer),
/// mTLS-bound token support if *any* source reports it (the deployment handles
/// the binding regardless of which issuer minted the token), and the `realm`
/// and `resource_metadata` only when every source reports the same one (each
/// names something deployment-wide — the protection space and this resource's
/// metadata document — so disagreement means none).
fn union_metadata<C>(
    sources: &[(String, Box<dyn SourceValidator<C>>)],
    resource: Option<&str>,
) -> ValidatorMetadata {
    let mut authorization_servers = Vec::new();
    let mut dpop_algs: Vec<String> = Vec::new();
    let mut all_require_dpop = !sources.is_empty();
    let mut any_dpop_supported = false;
    let mut any_mtls_bound_supported = false;
    let mut realm: Option<Option<String>> = None;
    let mut resource_metadata: Option<Option<String>> = None;

    for (_issuer, validator) in sources {
        let m = validator.validator_metadata(resource);
        realm = match realm {
            None => Some(m.realm.clone()),
            Some(r) if r == m.realm => Some(r),
            Some(_) => Some(None),
        };
        resource_metadata = match resource_metadata {
            None => Some(m.resource_metadata.clone()),
            Some(r) if r == m.resource_metadata => Some(r),
            Some(_) => Some(None),
        };
        any_dpop_supported |= m.supports_dpop();
        any_mtls_bound_supported |= m.tls_client_certificate_bound_access_tokens == Some(true);
        if let Some(servers) = m.authorization_servers {
            authorization_servers.extend(servers);
        }
        if let Some(algs) = m.dpop_signing_alg_values_supported {
            for alg in algs {
                if !dpop_algs.contains(&alg) {
                    dpop_algs.push(alg);
                }
            }
        }
        all_require_dpop &= m.dpop_bound_access_tokens_required.unwrap_or(false);
    }

    ValidatorMetadata {
        realm: realm.flatten(),
        authorization_servers: (!authorization_servers.is_empty()).then_some(authorization_servers),
        dpop_supported: Some(any_dpop_supported),
        dpop_signing_alg_values_supported: (!dpop_algs.is_empty()).then_some(dpop_algs),
        dpop_bound_access_tokens_required: Some(all_require_dpop),
        tls_client_certificate_bound_access_tokens: any_mtls_bound_supported.then_some(true),
        resource: resource.map(str::to_owned),
        bearer_methods_supported: Some(vec!["header"]),
        resource_metadata: resource_metadata.flatten(),
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    /// base64url-no-pad encodes `s` as one JWS segment.
    fn seg(s: &str) -> String {
        BASE64_URL_SAFE_NO_PAD.encode(s)
    }

    /// Assembles a three-part compact JWS with the given base64url payload.
    /// The header and signature are opaque to `peek_issuer`, so they are fixed.
    fn token_with_payload(payload_b64: &str) -> String {
        format!("{}.{payload_b64}.{}", seg(r#"{"alg":"RS256"}"#), seg("sig"))
    }

    #[rstest]
    // The signature is never checked, so any non-empty signature segment works.
    #[case::standard(
        token_with_payload(&seg(r#"{"iss":"https://issuer.example","sub":"abc"}"#)),
        "https://issuer.example"
    )]
    // RFC 7519 permits an empty signature (`alg: none`); it is still three
    // segments, and routing carries no trust regardless.
    #[case::empty_signature(
        format!("{}.{}.", seg(r#"{"alg":"none"}"#), seg(r#"{"iss":"iss-a"}"#)),
        "iss-a"
    )]
    fn reads_iss_from_unverified_payload(#[case] token: String, #[case] expected: &str) {
        assert_eq!(peek_issuer(&token).as_deref(), Some(expected));
    }

    #[rstest]
    #[case::single_segment("not-a-jwt".to_owned())]
    // No signature segment: not a JWS.
    #[case::two_segments(format!("{}.{}", seg(r#"{"alg":"none"}"#), seg(r#"{"iss":"iss-a"}"#)))]
    // More than three segments (e.g. a JWE) is not a compact JWS.
    #[case::four_segments(format!(
        "{}.{}.{}.{}",
        seg(r#"{"alg":"none"}"#),
        seg(r#"{"iss":"iss-a"}"#),
        seg("sig"),
        seg("extra"),
    ))]
    fn wrong_segment_count_is_rejected(#[case] token: String) {
        assert_eq!(peek_issuer(&token), None);
    }

    #[rstest]
    // `!` is outside the base64url alphabet.
    #[case::non_base64url("not!base64".to_owned())]
    #[case::not_json(seg("this is not json"))]
    #[case::no_iss(seg(r#"{"sub":"abc","aud":"api"}"#))]
    // `iss` deserializes as a `String`; a numeric value fails to parse.
    #[case::non_string_iss(seg(r#"{"iss":42}"#))]
    fn malformed_payload_is_rejected(#[case] payload_b64: String) {
        assert_eq!(peek_issuer(&token_with_payload(&payload_b64)), None);
    }

    /// A [`SourceValidator`] double that only carries metadata.
    #[derive(Default)]
    struct StubSource {
        realm: Option<&'static str>,
        resource_metadata: Option<&'static str>,
        mtls_bound_supported: Option<bool>,
    }

    impl AccessTokenValidator for StubSource {
        type Claims = ();
        type Error = MultiIssuerError;

        fn validate_request<'a>(
            &'a self,
            _headers: &'a http::HeaderMap,
            _method: &'a http::Method,
            _uri: &'a http::Uri,
            _client_cert_der: Option<&'a [u8]>,
        ) -> MaybeSendBoxFuture<'a, ValidationResult<(), MultiIssuerError>> {
            Box::pin(async {
                ValidationResult {
                    outcome: Ok(None),
                    dpop_nonce: None,
                }
            })
        }
    }

    impl ProvideValidatorMetadata for StubSource {
        fn validator_metadata(&self, _resource: Option<&str>) -> ValidatorMetadata {
            ValidatorMetadata::builder()
                .maybe_realm(self.realm.map(str::to_owned))
                .maybe_resource_metadata(self.resource_metadata.map(str::to_owned))
                .maybe_tls_client_certificate_bound_access_tokens(self.mtls_bound_supported)
                .build()
        }
    }

    fn boxed_sources(
        stubs: impl IntoIterator<Item = StubSource>,
    ) -> Vec<(String, Box<dyn SourceValidator<()>>)> {
        stubs
            .into_iter()
            .enumerate()
            .map(|(i, stub)| {
                (
                    format!("https://issuer-{i}.example"),
                    Box::new(stub) as Box<dyn SourceValidator<()>>,
                )
            })
            .collect()
    }

    fn stub_sources(
        realms: &[Option<&'static str>],
    ) -> Vec<(String, Box<dyn SourceValidator<()>>)> {
        boxed_sources(realms.iter().map(|realm| StubSource {
            realm: *realm,
            ..StubSource::default()
        }))
    }

    #[rstest]
    // The realm names the whole deployment's protection space, so it unions
    // only when every source reports the same one.
    #[case::all_agree(&[Some("api"), Some("api")], Some("api"))]
    #[case::disagreement(&[Some("api"), Some("other")], None)]
    #[case::partial(&[Some("api"), None], None)]
    #[case::none_set(&[None, None], None)]
    fn union_realm_requires_agreement(
        #[case] realms: &[Option<&'static str>],
        #[case] expected: Option<&str>,
    ) {
        let meta = union_metadata(&stub_sources(realms), None);
        assert_eq!(meta.realm.as_deref(), expected);
    }

    #[rstest]
    // The metadata URL locates this resource's one document, so like the
    // realm it unions only when every source reports the same one.
    #[case::all_agree(&[Some("https://api.example/prm"), Some("https://api.example/prm")], Some("https://api.example/prm"))]
    #[case::disagreement(&[Some("https://api.example/prm"), Some("https://other.example/prm")], None)]
    #[case::partial(&[Some("https://api.example/prm"), None], None)]
    fn union_resource_metadata_requires_agreement(
        #[case] urls: &[Option<&'static str>],
        #[case] expected: Option<&str>,
    ) {
        let sources = boxed_sources(urls.iter().map(|url| StubSource {
            resource_metadata: *url,
            ..StubSource::default()
        }));
        assert_eq!(
            union_metadata(&sources, None).resource_metadata.as_deref(),
            expected
        );
    }

    #[rstest]
    // mTLS-bound token support is a deployment capability, so any source
    // asserting it makes the union assert it.
    #[case::any_true(&[None, Some(true)], Some(true))]
    #[case::none_assert(&[None, Some(false)], None)]
    fn union_mtls_bound_support_is_any(
        #[case] flags: &[Option<bool>],
        #[case] expected: Option<bool>,
    ) {
        let sources = boxed_sources(flags.iter().map(|flag| StubSource {
            mtls_bound_supported: *flag,
            ..StubSource::default()
        }));
        assert_eq!(
            union_metadata(&sources, None).tls_client_certificate_bound_access_tokens,
            expected
        );
    }
}