oauth-as 0.9.2

An embeddable OAuth 2.1 Authorization Server library: spec-mirroring types (RFC 6749, RFC 8628, RFC 7636), a full device-authorization-grant state machine, and a storage trait the host implements. Deliberately host-agnostic with a tiny dependency set; nothing is allocated until the host constructs an AuthorizationServer, so an embedding host pays zero memory until its config enables the feature.
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (C) 2026 Matthew Jackson

//! Unit tests for the consent and RFC 9470 step-up primitives.
//!
//! These are the decisions the module makes on its own, away from a server: what "already
//! consented" means, what satisfies an `acr_values` / `max_age` requirement, and what the RFC 9470
//! section 3 challenge looks like on the wire. The behavioural half, where the answers reach a
//! token, lives in `tests/consent.rs` and `tests/step_up.rs`.

use std::time::{Duration, UNIX_EPOCH};

use super::*;

fn at(secs: u64) -> SystemTime {
    UNIX_EPOCH + Duration::from_secs(secs)
}

fn scopes(s: &str) -> ScopeSet {
    ScopeSet::parse(s).unwrap()
}

fn record(scope: &str, resource: &[&str]) -> ConsentRecord {
    ConsentRecord {
        consent_id: "consent-1".into(),
        client_id: ClientId::new("app"),
        subject: "user-1".into(),
        scope: scopes(scope),
        resource: resource.iter().map(|r| r.to_string()).collect(),
        granted_at: at(1_000),
        authentication: None,
    }
}

// -------------------------------------------------------------------------- remembered consent

/// A remembered consent covers a request for LESS than was approved. This is the ordinary case and
/// the only one where skipping a prompt could ever be defensible.
#[test]
fn a_narrower_request_is_covered() {
    let r = record("read write", &[]);
    assert!(r.covers(&scopes("read"), &[], RequestedDetails::none()));
    assert!(r.covers(&scopes("read write"), &[], RequestedDetails::none()));
    assert!(r.covers(&ScopeSet::empty(), &[], RequestedDetails::none()));
}

/// One scope token more than was approved is NOT covered. This is the whole security content of
/// `covers`: a remembered consent that grew by one token would be a permission the user never saw.
#[test]
fn one_extra_scope_token_is_not_covered() {
    let r = record("read", &[]);
    assert!(!r.covers(&scopes("read write"), &[], RequestedDetails::none()));
    assert!(!r.covers(&scopes("admin"), &[], RequestedDetails::none()));
}

/// RFC 8707 s2 makes the resource the audience the token will be good at, so a consent that named
/// no resource does not cover a request that names one. "Approved for no particular resource" is
/// not "approved for that resource", and reading it the other way would let a remembered consent
/// acquire an audience silently.
#[test]
fn a_resource_the_consent_never_named_is_not_covered() {
    let none = record("read", &[]);
    assert!(!none.covers(
        &scopes("read"),
        &["https://rs.example/".to_string()],
        RequestedDetails::none()
    ));

    let one = record("read", &["https://rs.example/"]);
    assert!(one.covers(
        &scopes("read"),
        &["https://rs.example/".to_string()],
        RequestedDetails::none()
    ));
    assert!(!one.covers(
        &scopes("read"),
        &["https://other.example/".to_string()],
        RequestedDetails::none()
    ));
    // Naming one of two approved resources is a narrowing, which is covered.
    let two = record("read", &["https://rs.example/", "https://other.example/"]);
    assert!(two.covers(
        &scopes("read"),
        &["https://other.example/".to_string()],
        RequestedDetails::none()
    ));
}

/// RFC 9396 section 2 makes the ELEMENT the thing being authorized — an amount, a creditor account,
/// an `identifier` — and a [`ConsentRecord`] records none of them. So a request carrying any is not
/// covered, whatever its scope: answering otherwise would let a scope string stand in for a
/// transaction, which is the one thing RFC 9396 exists because a scope string cannot do.
#[cfg(feature = "rar")]
#[test]
fn a_request_carrying_authorization_details_is_never_covered() {
    let details = crate::rar::AuthorizationDetails::parse(
        r#"[{"type":"payment","identifier":"IBAN-1","amount":"50"}]"#,
    )
    .expect("the fixture parses");
    let r = record("read", &[]);
    // The scope half is satisfied; only the details half decides this.
    assert!(r.covers(&scopes("read"), &[], RequestedDetails::none()));
    assert!(
        !r.covers(&scopes("read"), &[], RequestedDetails::of(&details)),
        "a remembered consent recorded no authorization detail, so it covers none"
    );
}

/// An EMPTY array is the same request as an absent parameter, and must not re-prompt a user for
/// nothing: `authorization_details=[]` asks for no element at all.
#[cfg(feature = "rar")]
#[test]
fn an_empty_details_array_is_the_same_as_asking_for_none() {
    let empty = crate::rar::AuthorizationDetails::none();
    let r = record("read", &[]);
    assert!(r.covers(&scopes("read"), &[], RequestedDetails::of(&empty)));
}

/// Widening accumulates rather than replacing: a user who approves `write` today has not withdrawn
/// the `read` they approved last month, and the identifier and the original grant instant survive
/// so that one relationship stays one row in a user's consent list.
#[test]
fn extend_accumulates_and_keeps_the_identity_of_the_consent() {
    let mut r = record("read", &["https://rs.example/"]);
    r.extend(&scopes("write"), &["https://other.example/".to_string()]);
    assert_eq!(r.scope, scopes("read write"));
    assert_eq!(
        r.resource,
        vec![
            "https://rs.example/".to_string(),
            "https://other.example/".to_string()
        ]
    );
    assert_eq!(&*r.consent_id, "consent-1");
    assert_eq!(r.granted_at, at(1_000));
}

/// Widening by something already covered changes nothing at all, and in particular does not
/// duplicate a resource indicator: a record that grew a copy of an entry on every approval would
/// grow without bound for a client a user visits every day.
#[test]
fn extend_by_what_is_already_covered_is_a_no_op() {
    let mut r = record("read write", &["https://rs.example/"]);
    let before = r.clone();
    r.extend(&scopes("read"), &["https://rs.example/".to_string()]);
    assert_eq!(r, before);
}

// -------------------------------------------------------------------------- parsing (RFC 9470 s4)

/// An ordinary authorization request carries neither parameter, and must not acquire a requirement
/// by being parsed.
#[test]
fn a_request_with_neither_parameter_requires_nothing() {
    let req = AuthenticationRequirement::from_pairs([("client_id", "app"), ("scope", "read")])
        .expect("no step-up parameters is not an error");
    assert!(req.is_empty());
    assert_eq!(req, AuthenticationRequirement::none());
}

#[test]
fn acr_values_is_a_space_delimited_ordered_list() {
    let req =
        AuthenticationRequirement::from_pairs([("acr_values", "  urn:mace:silver  phr ")]).unwrap();
    assert_eq!(
        req.acr_values,
        vec![Box::<str>::from("urn:mace:silver"), Box::<str>::from("phr")]
    );
    assert!(!req.is_empty());
}

/// The boundary of [`MAX_ACR_VALUES`], both sides of it. Exactly the cap is stored WHOLE, because
/// this cap refuses rather than truncates: a shortened list would answer a resource server's
/// challenge with a class the user never satisfied, or drop the one class the client could meet, and
/// say nothing. One past the cap is `invalid_request`.
///
/// The allocation budget this bound exists for is measured in `tests/allocation_paths.rs`; what is
/// checked here is the arithmetic of the edge and the error code.
#[test]
fn acr_values_is_bounded_and_refuses_rather_than_truncating() {
    let at_cap = vec!["phr"; MAX_ACR_VALUES].join(" ");
    let req = AuthenticationRequirement::from_pairs([("acr_values", at_cap.as_str())])
        .expect("exactly the cap is a legal request");
    assert_eq!(req.acr_values.len(), MAX_ACR_VALUES);

    let over = vec!["phr"; MAX_ACR_VALUES + 1].join(" ");
    let err = AuthenticationRequirement::from_pairs([("acr_values", over.as_str())])
        .expect_err("one past the cap must be refused, not truncated");
    assert_eq!(err.error, ErrorCode::InvalidRequest);

    // The count is over NON-EMPTY segments, so runs of spaces are not classes and a parameter made
    // of nothing but separators is not an oversized one.
    let spaced = format!("{}{}", " ".repeat(1000), at_cap.replace(' ', "   "));
    let req = AuthenticationRequirement::from_pairs([("acr_values", spaced.as_str())])
        .expect("separators are not classes");
    assert_eq!(req.acr_values.len(), MAX_ACR_VALUES);
}

/// `max_age=0` means re-authenticate NOW. It must not collapse into "absent", which is the reading
/// that would turn the strongest possible request into no request at all.
#[test]
fn max_age_zero_is_a_requirement_and_not_an_absence() {
    let req = AuthenticationRequirement::from_pairs([("max_age", "0")]).unwrap();
    assert_eq!(req.max_age, Some(Duration::ZERO));
    assert!(!req.is_empty());
}

/// A `max_age` that is not a number of seconds is REFUSED, not ignored. Ignoring it would answer a
/// step-up challenge with a token that never had the freshness the resource server asked for.
#[test]
fn a_malformed_max_age_is_invalid_request() {
    for bad in ["", "-1", "soon", "60s", "1.5", "9999999999999999999999"] {
        let err = AuthenticationRequirement::from_pairs([("max_age", bad)])
            .expect_err("a max_age that is not a number of seconds must be refused");
        assert_eq!(err.error, ErrorCode::InvalidRequest, "max_age={bad:?}");
    }
}

/// RFC 6749 s3.1 says a parameter MUST NOT appear more than once; where one does, the FIRST wins,
/// matching `AuthorizationRequest::from_pairs`. Last-wins is the smuggling-friendly choice when two
/// intermediaries disagree about which copy counts.
#[test]
fn a_repeated_parameter_keeps_the_first_occurrence() {
    let req = AuthenticationRequirement::from_pairs([
        ("acr_values", "strong"),
        ("acr_values", "weak"),
        ("max_age", "60"),
        ("max_age", "86400"),
    ])
    .unwrap();
    assert_eq!(req.acr_values, vec![Box::<str>::from("strong")]);
    assert_eq!(req.max_age, Some(Duration::from_secs(60)));
}

// -------------------------------------------------------------------------- enforcement

/// No requirement means no check, whether or not the host reported anything.
#[test]
fn an_empty_requirement_is_satisfied_by_anything() {
    let req = AuthenticationRequirement::none();
    assert_eq!(req.satisfied_by(None, at(5_000)), Ok(()));
    assert_eq!(
        req.satisfied_by(Some(&Authentication::at(at(1))), at(5_000)),
        Ok(())
    );
}

/// THE FAILURE THAT MATTERS: a host that reports nothing must not satisfy a requirement. "We were
/// not told" reading as "there is nothing to check" is what would make an unwired host silently
/// satisfy every step-up challenge it is ever sent.
#[test]
fn an_unreported_authentication_satisfies_nothing() {
    let fresh = AuthenticationRequirement {
        acr_values: Vec::new(),
        max_age: Some(Duration::from_secs(60)),
    };
    assert_eq!(
        fresh.satisfied_by(None, at(5_000)),
        Err(StepUpFailure::NotReported)
    );
    let strong = AuthenticationRequirement {
        acr_values: vec!["phr".into()],
        max_age: None,
    };
    assert_eq!(
        strong.satisfied_by(None, at(5_000)),
        Err(StepUpFailure::NotReported)
    );
}

/// `max_age` is measured from `auth_time`, and the boundary is inclusive: an authentication exactly
/// `max_age` old still satisfies it, one second older does not.
#[test]
fn max_age_is_enforced_against_auth_time_at_the_boundary() {
    let req = AuthenticationRequirement {
        acr_values: Vec::new(),
        max_age: Some(Duration::from_secs(300)),
    };
    let auth = Authentication::at(at(1_000));
    assert_eq!(req.satisfied_by(Some(&auth), at(1_300)), Ok(()));
    assert_eq!(
        req.satisfied_by(Some(&auth), at(1_301)),
        Err(StepUpFailure::Stale)
    );
    // max_age=0 means now: any elapsed time at all fails.
    let now_only = AuthenticationRequirement {
        acr_values: Vec::new(),
        max_age: Some(Duration::ZERO),
    };
    assert_eq!(now_only.satisfied_by(Some(&auth), at(1_000)), Ok(()));
    assert_eq!(
        now_only.satisfied_by(Some(&auth), at(1_001)),
        Err(StepUpFailure::Stale)
    );
}

/// An `auth_time` in the future is a clock skew between two machines, not an attack, and reads as
/// zero elapsed time. Failing it would lock a user out of a deployment whose AS and login service
/// disagree by a second.
#[test]
fn an_auth_time_in_the_future_reads_as_no_elapsed_time() {
    let req = AuthenticationRequirement {
        acr_values: Vec::new(),
        max_age: Some(Duration::ZERO),
    };
    let auth = Authentication::at(at(2_000));
    assert_eq!(req.satisfied_by(Some(&auth), at(1_000)), Ok(()));
}

/// `acr_values` is an ordered preference, so ANY of the requested classes satisfies it. A host that
/// answered with the second-choice class has still answered.
#[test]
fn any_requested_acr_satisfies_the_request() {
    let req = AuthenticationRequirement {
        acr_values: vec!["phr".into(), "mfa".into()],
        max_age: None,
    };
    let mfa = Authentication::at(at(1_000)).with_acr("mfa");
    assert_eq!(req.satisfied_by(Some(&mfa), at(1_000)), Ok(()));
    let pwd = Authentication::at(at(1_000)).with_acr("pwd");
    assert_eq!(
        req.satisfied_by(Some(&pwd), at(1_000)),
        Err(StepUpFailure::AcrNotMet)
    );
    // Reported nothing at all: a request for a specific class is not satisfied by silence.
    let bare = Authentication::at(at(1_000));
    assert_eq!(
        req.satisfied_by(Some(&bare), at(1_000)),
        Err(StepUpFailure::AcrNotMet)
    );
}

/// `acr` values are compared as OPAQUE strings, byte for byte. This crate has no registry to check
/// them against and no business case-folding somebody else's vocabulary.
#[test]
fn acr_comparison_is_exact() {
    let req = AuthenticationRequirement {
        acr_values: vec!["PHR".into()],
        max_age: None,
    };
    let lower = Authentication::at(at(1_000)).with_acr("phr");
    assert_eq!(
        req.satisfied_by(Some(&lower), at(1_000)),
        Err(StepUpFailure::AcrNotMet)
    );
}

/// Freshness is checked BEFORE class, so a login that is both stale and of the wrong class is
/// reported as stale: logging in again is the action that fixes either, and it does not tell the
/// client which `acr` a stale session happened to hold.
#[test]
fn staleness_is_reported_before_the_class_mismatch() {
    let req = AuthenticationRequirement {
        acr_values: vec!["phr".into()],
        max_age: Some(Duration::from_secs(60)),
    };
    let old_and_wrong = Authentication::at(at(1_000)).with_acr("pwd");
    assert_eq!(
        req.satisfied_by(Some(&old_and_wrong), at(9_000)),
        Err(StepUpFailure::Stale)
    );
}

/// Every failure is reported as RFC 9470 s3's `insufficient_user_authentication`, and the
/// description is a `&'static str`, so a refusal on a path an unauthenticated caller can drive
/// allocates nothing for it.
#[test]
fn every_failure_is_insufficient_user_authentication() {
    for failure in [
        StepUpFailure::NotReported,
        StepUpFailure::Stale,
        StepUpFailure::AcrNotMet,
    ] {
        let err = failure.error_response();
        assert_eq!(err.error, ErrorCode::InsufficientUserAuthentication);
        assert_eq!(
            err.error_description.as_deref(),
            Some(failure.description()),
            "{failure}"
        );
        // The description must not name the user's actual acr or auth_time: it goes to the CLIENT.
        let text = failure.description();
        assert!(!text.contains("1970"), "{text}");
    }
    assert_eq!(
        ErrorCode::InsufficientUserAuthentication.as_str(),
        "insufficient_user_authentication"
    );
}

// -------------------------------------------------------------------------- the s3 challenge

/// RFC 9470 s3's challenge, in the shape a resource server sends it.
#[test]
fn the_challenge_carries_the_error_and_both_parameters() {
    let challenge = step_up_challenge(
        "Bearer",
        &["phr".into(), "mfa".into()],
        Some(Duration::from_secs(300)),
    );
    assert_eq!(
        challenge,
        "Bearer error=\"insufficient_user_authentication\", \
         error_description=\"the user authentication does not meet the requirements of this \
         resource\", acr_values=\"phr mfa\", max_age=\"300\""
    );
}

/// An empty `acr_values` is OMITTED rather than sent blank: an empty list reads as "no class is
/// acceptable", which is the opposite of "any class will do". Same for an absent `max_age`.
#[test]
fn the_challenge_omits_what_was_not_asked_for() {
    let challenge = step_up_challenge("DPoP", &[], None);
    assert_eq!(
        challenge,
        "DPoP error=\"insufficient_user_authentication\", \
         error_description=\"the user authentication does not meet the requirements of this \
         resource\""
    );
    assert!(!challenge.contains("acr_values"));
    assert!(!challenge.contains("max_age"));
}

/// A quote or a backslash inside an `acr` value would otherwise close the quoted string early and
/// forge the parameter after it (RFC 9110 s5.6.4). Escaped, not rejected: this crate does not own
/// the host's `acr` vocabulary.
#[test]
fn the_challenge_escapes_quotes_in_an_acr_value() {
    let challenge = step_up_challenge("Bearer", &["a\"b\\c".into()], None);
    assert!(
        challenge.contains("acr_values=\"a\\\"b\\\\c\""),
        "{challenge}"
    );
    // Nothing after the escaped value could be read as a new parameter.
    assert_eq!(challenge.matches("error=").count(), 1);
}

/// THE FINDING. A backslash escape is not available for a control character: RFC 9110 s5.6.4's
/// `qdtext` excludes `%x00-%x08`, `%x0A-%x1F` and `%x7F`, and `quoted-pair` is `"\" ( HTAB / SP /
/// VCHAR / obs-text )`, which does not admit them either. So a CR or an LF in an `acr` value cannot
/// be escaped into a legal `quoted-string`; it can only be removed. `push_quoted` used to pass it
/// through verbatim, which is header injection out of a value the doc calls escaped.
///
/// Reachable: the parameter type here is exactly `AuthenticationRequirement::acr_values`, which
/// `from_raw` fills straight from the client-supplied `acr_values` query parameter with no
/// character validation at all, and the point of this helper is that the resource server echoes the
/// classes back into a header.
#[test]
fn the_challenge_cannot_carry_a_header_break() {
    let challenge = step_up_challenge("Bearer", &["a\r\nX-Evil: 1".into()], None);
    assert!(!challenge.contains('\r'), "{challenge:?}");
    assert!(!challenge.contains('\n'), "{challenge:?}");
    assert!(!challenge.contains('\u{7f}'), "{challenge:?}");
    // The rest of the value survives: what is dropped is only what cannot be spelled.
    assert!(
        challenge.contains("acr_values=\"aX-Evil: 1\""),
        "{challenge}"
    );
}

/// The `scheme` is written into the challenge OUTSIDE any quoted string, so it is the one part of
/// the output with no escaping available to it at all: a space or a `"` in it forges the whole rest
/// of the header. RFC 9110 s11.1 makes it a `token`, and anything else is dropped.
#[test]
fn the_challenge_scheme_is_a_token() {
    let challenge = step_up_challenge("Bea rer\r\nX-Evil: 1\"", &["phr".into()], None);
    // `:` and SP are not `tchar` either, so what is left of the injected header name is the part
    // that happened to be spellable. It is now inside the scheme, where it names nothing.
    assert!(challenge.starts_with("BearerX-Evil1 error="), "{challenge}");
    assert!(!challenge.contains('\r'), "{challenge:?}");
    assert!(!challenge.contains('\n'), "{challenge:?}");
    assert_eq!(challenge.matches('"').count(), 6, "{challenge}");
}

/// Every byte a legal `quoted-string` DOES admit survives, because dropping one would rename the
/// class and challenge for something the host never defined. `obs-text` (`%x80-%xFF`) is included,
/// which for a Rust `str` means every non-ASCII scalar value.
#[test]
fn the_challenge_keeps_everything_that_is_spellable() {
    let value = "urn:acr:\tsecure level-3 \u{e9}\u{7ff}";
    let challenge = step_up_challenge("Bearer", &[value.into()], None);
    assert!(
        challenge.contains(&format!("acr_values=\"{value}\"")),
        "{challenge}"
    );
}