oauth-as 0.9.3

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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (C) 2026 Matthew Jackson

//! Behavioural tests for the RFC 8628 device authorization grant state machine and the OAuth 2.1
//! refresh rotation, on the in-memory store with a manual clock (no sleeping).

use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use oauth_as::{
    AuthorizationServer, Client, ClientAuth, ClientId, Clock, DeviceGrantState, ErrorCode,
    GrantType, MemoryStorage, ScopeSet, ServerConfig, Storage, TokenRequest, TokenType,
};

/// A hand-cranked clock shared between the test and the server under test.
#[derive(Clone)]
struct ManualClock(Arc<Mutex<SystemTime>>);

impl ManualClock {
    fn at_epoch() -> Self {
        ManualClock(Arc::new(Mutex::new(
            UNIX_EPOCH + Duration::from_secs(1_700_000_000),
        )))
    }
    fn advance(&self, d: Duration) {
        let mut t = self.0.lock().unwrap();
        *t += d;
    }
}

impl Clock for ManualClock {
    fn now(&self) -> SystemTime {
        *self.0.lock().unwrap()
    }
}

fn device_client() -> Client {
    Client {
        client_id: ClientId::new("device-client"),
        auth: ClientAuth::Public,
        grant_types: vec![GrantType::DeviceCode, GrantType::RefreshToken],
        redirect_uris: vec![],
        allowed_scopes: ScopeSet::parse("read write admin").unwrap(),
        default_scopes: ScopeSet::parse("read").unwrap(),
        name: Some("Test device".into()),
        registration: None,
    }
}

async fn server_with(
    clock: ManualClock,
    clients: Vec<Client>,
) -> AuthorizationServer<MemoryStorage, ManualClock> {
    let cfg = ServerConfig::new("https://as.example", "https://as.example/device");
    let srv = AuthorizationServer::with_clock(cfg, MemoryStorage::new(), clock);
    for c in clients {
        srv.register_client(c).await.unwrap();
    }
    srv
}

fn poll(device_code: &str) -> TokenRequest {
    TokenRequest::DeviceCode {
        client_id: ClientId::new("device-client"),
        client_secret: None,
        device_code: device_code.to_string(),
    }
}

#[tokio::test]
async fn happy_path_pending_then_approved_then_single_use() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock.clone(), vec![device_client()]).await;

    let scope = ScopeSet::parse("read write").unwrap();
    let auth = srv
        .device_authorization(&ClientId::new("device-client"), None, Some(&scope))
        .await
        .unwrap();

    // Response shape per RFC 8628 section 3.2 and our config defaults.
    assert_eq!(auth.expires_in, 600);
    assert_eq!(auth.interval, 5);
    assert_eq!(auth.verification_uri, "https://as.example/device");
    // `verification_uri_complete` is OFF by default (RFC 8628 s5.4 remote phishing), so the
    // default-config response omits it. `tests/device_flow_edges.rs` covers both settings.
    assert_eq!(auth.verification_uri_complete, None);
    // User code shape: XXXX-XXXX over the section 6.1 example alphabet (20 consonants).
    let (a, b) = auth
        .user_code
        .split_once('-')
        .expect("display form has one hyphen");
    for part in [a, b] {
        assert_eq!(part.len(), 4);
        assert!(
            part.chars().all(|c| "BCDFGHJKLMNPQRSTVWXZ".contains(c)),
            "{}",
            auth.user_code
        );
    }
    assert!(
        auth.device_code.len() >= 43,
        "device code must be high-entropy, got {}",
        auth.device_code
    );

    // Poll before approval: authorization_pending.
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(err.error, ErrorCode::AuthorizationPending);
    assert_eq!(err.http_status(), 400);

    // The user enters the code sloppily: lowercase, no hyphen, padded. Still found.
    let sloppy = format!(" {} ", auth.user_code.replace('-', "").to_lowercase());
    srv.approve_device(&sloppy, "user-42").await.unwrap();

    // Respect the interval, then redeem.
    clock.advance(Duration::from_secs(5));
    let token = srv.token(poll(&auth.device_code)).await.unwrap();
    assert_eq!(token.token_type, TokenType::Bearer);
    assert_eq!(token.expires_in, 3600);
    assert_eq!(token.scope.as_deref(), Some("read write"));
    let refresh = token
        .refresh_token
        .clone()
        .expect("refresh issued by default");
    assert_ne!(refresh, token.access_token);

    // Introspection sees the token, bound to the approving subject.
    let info = srv
        .introspect(&token.access_token)
        .await
        .unwrap()
        .expect("live token");
    assert_eq!(info.subject.as_deref(), Some("user-42"));
    assert_eq!(info.scope, scope);
    assert_eq!(info.client_id, ClientId::new("device-client"));

    // Single use: the device code is spent.
    clock.advance(Duration::from_secs(5));
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(err.error, ErrorCode::InvalidGrant);
}

#[tokio::test]
async fn omitted_scope_grants_the_client_default() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock.clone(), vec![device_client()]).await;
    let auth = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();
    srv.approve_device(&auth.user_code, "u").await.unwrap();
    clock.advance(Duration::from_secs(5));
    let token = srv.token(poll(&auth.device_code)).await.unwrap();
    assert_eq!(
        token.scope.as_deref(),
        Some("read"),
        "default_scopes applies when the request names none"
    );
}

#[tokio::test]
async fn scope_outside_the_registration_is_invalid_scope() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock, vec![device_client()]).await;
    let scope = ScopeSet::parse("read forbidden").unwrap();
    let err = srv
        .device_authorization(&ClientId::new("device-client"), None, Some(&scope))
        .await
        .unwrap_err();
    assert_eq!(err.error, ErrorCode::InvalidScope);
}

#[tokio::test]
async fn polling_too_fast_is_slow_down_and_raises_the_interval_by_five_seconds() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock.clone(), vec![device_client()]).await;
    let auth = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();

    // First poll is never slow_down.
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(err.error, ErrorCode::AuthorizationPending);

    // Immediate second poll: slow_down, and the required spacing becomes 5 + 5 = 10.
    clock.advance(Duration::from_secs(1));
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(err.error, ErrorCode::SlowDown);

    // The ORIGINAL interval is no longer enough: 6 seconds later is still too fast.
    clock.advance(Duration::from_secs(6));
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(
        err.error,
        ErrorCode::SlowDown,
        "old pace after slow_down must still be slow_down"
    );

    // The raised spacing (now 15 after two slow_downs) is honored.
    clock.advance(Duration::from_secs(15));
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(
        err.error,
        ErrorCode::AuthorizationPending,
        "well-paced poll after backoff"
    );
}

#[tokio::test]
async fn expiry_is_expired_token_once_then_the_code_is_gone() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock.clone(), vec![device_client()]).await;
    let auth = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();

    clock.advance(Duration::from_secs(600));
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(err.error, ErrorCode::ExpiredToken);

    // The grant was removed; a later poll cannot distinguish it from a code that never existed.
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(err.error, ErrorCode::InvalidGrant);

    // And the user code no longer approves.
    let err = srv.approve_device(&auth.user_code, "u").await.unwrap_err();
    assert!(matches!(
        err,
        oauth_as::server::DeviceApprovalError::UnknownUserCode
    ));
}

#[tokio::test]
async fn denial_is_access_denied_then_the_code_is_gone() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock.clone(), vec![device_client()]).await;
    let auth = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();

    srv.deny_device(&auth.user_code).await.unwrap();
    clock.advance(Duration::from_secs(5));
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(err.error, ErrorCode::AccessDenied);

    clock.advance(Duration::from_secs(5));
    let err = srv.token(poll(&auth.device_code)).await.unwrap_err();
    assert_eq!(
        err.error,
        ErrorCode::InvalidGrant,
        "a denied grant is consumed by its terminal answer"
    );
}

#[tokio::test]
async fn approval_state_transitions_are_guarded() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock.clone(), vec![device_client()]).await;
    let auth = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();

    let err = srv.approve_device("XXXX-XXXX", "u").await.unwrap_err();
    assert!(matches!(
        err,
        oauth_as::server::DeviceApprovalError::UnknownUserCode
    ));

    srv.approve_device(&auth.user_code, "u").await.unwrap();
    let err = srv
        .approve_device(&auth.user_code, "someone-else")
        .await
        .unwrap_err();
    assert!(
        matches!(err, oauth_as::server::DeviceApprovalError::NotPending),
        "approval is not re-bindable"
    );
    let err = srv.deny_device(&auth.user_code).await.unwrap_err();
    assert!(
        matches!(err, oauth_as::server::DeviceApprovalError::NotPending),
        "a decided grant stays decided"
    );
}

#[tokio::test]
async fn wrong_client_unknown_client_and_bad_secret() {
    let clock = ManualClock::at_epoch();
    let mut confidential = device_client();
    confidential.client_id = ClientId::new("confidential");
    confidential.auth = ClientAuth::ConfidentialSecret {
        secret: "hunter2".into(),
    };
    let srv = server_with(clock.clone(), vec![device_client(), confidential]).await;

    let auth = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();
    srv.approve_device(&auth.user_code, "u").await.unwrap();
    clock.advance(Duration::from_secs(5));

    // A different registered client polling someone else's device_code: invalid_grant.
    let err = srv
        .token(TokenRequest::DeviceCode {
            client_id: ClientId::new("confidential"),
            client_secret: Some("hunter2".into()),
            device_code: auth.device_code.clone(),
        })
        .await
        .unwrap_err();
    assert_eq!(err.error, ErrorCode::InvalidGrant);

    // An unregistered client: invalid_client, 401.
    let err = srv
        .token(TokenRequest::DeviceCode {
            client_id: ClientId::new("nobody"),
            client_secret: None,
            device_code: auth.device_code.clone(),
        })
        .await
        .unwrap_err();
    assert_eq!(err.error, ErrorCode::InvalidClient);
    assert_eq!(err.http_status(), 401);

    // A confidential client with the wrong secret: invalid_client.
    let err = srv
        .token(TokenRequest::DeviceCode {
            client_id: ClientId::new("confidential"),
            client_secret: Some("wrong".into()),
            device_code: auth.device_code.clone(),
        })
        .await
        .unwrap_err();
    assert_eq!(err.error, ErrorCode::InvalidClient);

    // The cross-client and bad-auth attempts must not have consumed the grant.
    clock.advance(Duration::from_secs(5));
    let token = srv.token(poll(&auth.device_code)).await.unwrap();
    assert!(!token.access_token.is_empty());
}

#[tokio::test]
async fn client_without_the_device_grant_is_unauthorized_client() {
    let clock = ManualClock::at_epoch();
    let mut no_device = device_client();
    no_device.client_id = ClientId::new("web-only");
    no_device.grant_types = vec![GrantType::AuthorizationCode];
    let srv = server_with(clock, vec![no_device]).await;
    let err = srv
        .device_authorization(&ClientId::new("web-only"), None, None)
        .await
        .unwrap_err();
    assert_eq!(err.error, ErrorCode::UnauthorizedClient);
}

#[tokio::test]
async fn refresh_rotation_is_single_use_with_absolute_lifetime() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock.clone(), vec![device_client()]).await;
    let auth = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();
    srv.approve_device(&auth.user_code, "u").await.unwrap();
    clock.advance(Duration::from_secs(5));
    let first = srv.token(poll(&auth.device_code)).await.unwrap();
    let rt1 = first.refresh_token.unwrap();

    // Redeem: new access token, new refresh token.
    let second = srv
        .token(TokenRequest::RefreshToken {
            client_id: ClientId::new("device-client"),
            client_secret: None,
            refresh_token: rt1.clone(),
            scope: None,
        })
        .await
        .unwrap();
    let rt2 = second
        .refresh_token
        .clone()
        .expect("rotation issues a replacement");
    assert_ne!(rt2, rt1);
    assert_ne!(second.access_token, first.access_token);
    assert_eq!(
        second.scope.as_deref(),
        Some("read"),
        "scope carries over when not narrowed"
    );

    // Narrowing works; widening is invalid_scope and does NOT burn the presented token.
    let narrowed = srv
        .token(TokenRequest::RefreshToken {
            client_id: ClientId::new("device-client"),
            client_secret: None,
            refresh_token: rt2,
            scope: Some(ScopeSet::parse("read").unwrap()),
        })
        .await
        .unwrap();
    let rt3 = narrowed.refresh_token.clone().unwrap();
    let err = srv
        .token(TokenRequest::RefreshToken {
            client_id: ClientId::new("device-client"),
            client_secret: None,
            refresh_token: rt3.clone(),
            scope: Some(ScopeSet::parse("read admin").unwrap()),
        })
        .await
        .unwrap_err();
    assert_eq!(err.error, ErrorCode::InvalidScope);
    let again = srv
        .token(TokenRequest::RefreshToken {
            client_id: ClientId::new("device-client"),
            client_secret: None,
            refresh_token: rt3,
            scope: None,
        })
        .await
        .unwrap();
    assert!(
        again.refresh_token.is_some(),
        "an invalid_scope rejection must not consume the token"
    );
    let rt4 = again.refresh_token.expect("rotation issues a replacement");

    // The spent token is dead (OAuth 2.1 draft s6.1 single-use rotation), and presenting it is
    // REUSE, so RFC 9700 s4.14.2 revokes the whole chain with it. This assertion moved to the end
    // of the test when reuse detection landed: it used to sit immediately after the first
    // rotation, which only passed because the reused token was refused in isolation and the rest
    // of the chain was left alive. That was the defect, not the test order. See
    // tests/refresh_reuse.rs for the attack this behaviour exists to stop.
    let err = srv
        .token(TokenRequest::RefreshToken {
            client_id: ClientId::new("device-client"),
            client_secret: None,
            refresh_token: rt1,
            scope: None,
        })
        .await
        .unwrap_err();
    assert_eq!(err.error, ErrorCode::InvalidGrant);
    let err = srv
        .token(TokenRequest::RefreshToken {
            client_id: ClientId::new("device-client"),
            client_secret: None,
            refresh_token: rt4,
            scope: None,
        })
        .await
        .expect_err("detected reuse revokes every token of the grant, not just the replayed one");
    assert_eq!(err.error, ErrorCode::InvalidGrant);
}

#[tokio::test]
async fn introspection_expires_with_the_clock() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock.clone(), vec![device_client()]).await;
    let auth = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();
    srv.approve_device(&auth.user_code, "u").await.unwrap();
    clock.advance(Duration::from_secs(5));
    let token = srv.token(poll(&auth.device_code)).await.unwrap();

    assert!(srv.introspect(&token.access_token).await.unwrap().is_some());
    clock.advance(Duration::from_secs(3600));
    assert!(
        srv.introspect(&token.access_token).await.unwrap().is_none(),
        "expiry is by clock, not deletion"
    );
    assert!(srv.introspect("no-such-token").await.unwrap().is_none());
}

#[tokio::test]
async fn issued_artifacts_are_unique_across_grants() {
    let clock = ManualClock::at_epoch();
    let srv = server_with(clock.clone(), vec![device_client()]).await;
    let a = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();
    let b = srv
        .device_authorization(&ClientId::new("device-client"), None, None)
        .await
        .unwrap();
    assert_ne!(a.device_code, b.device_code);
    assert_ne!(a.user_code, b.user_code);

    // Approving one must not touch the other.
    srv.approve_device(&a.user_code, "u").await.unwrap();
    clock.advance(Duration::from_secs(5));
    let err = srv.token(poll(&b.device_code)).await.unwrap_err();
    assert_eq!(err.error, ErrorCode::AuthorizationPending);
    let grant_b = srv
        .store()
        .get_device_grant(&b.device_code)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(grant_b.state, DeviceGrantState::Pending);
}