arium 0.1.4

Framework-agnostic authentication engine (passwords, sessions, OAuth, MFA, RBAC, API tokens, audit) for axum + sqlx apps.
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! End-to-end OAuth callback against a `wiremock` token endpoint.
//!
//! The unit-level `oauth_link.rs` tests already cover the DB upsert
//! semantics. This file targets the *axum-layer* code path that the
//! upsert tests can't reach:
//!
//! - Authorize URL generation (scopes + CSRF state)
//! - State persistence across the login → callback round trip via the
//!   session cookie
//! - State mismatch and missing-state error branches
//! - Token-exchange success against a controlled `/token` endpoint
//! - Token-exchange failure (provider 5xx / malformed body → 502)
//! - Audit `user.login.success` emission on the happy path
//!
//! We do NOT mock the user-info endpoint over HTTP — the provider trait's
//! `fetch_profile` is a Rust function and the mock returns a profile
//! directly. That keeps the test focused on the OAuth wire shape that
//! lives in `oauth.rs::oauth_callback`.

#![cfg(feature = "oauth-github")]

mod common;

use arium::oauth::{NormalizedProfile, OAuthProvider};
use arium::{AuditConfig, AuthConfig, Mailer};
use async_trait::async_trait;
use axum::Router;
use reqwest::Client;
use reqwest::redirect::Policy;
use serde_json::json;
use sqlx::SqlitePool;
use std::net::SocketAddr;
use tokio::net::TcpListener;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

// ============================================================
// Mock provider — parameterizable URLs so each test can swap the
// wiremock-backed token endpoint without rebuilding the registry shape.
// ============================================================

struct MockProvider {
    name: &'static str,
    auth_url: String,
    token_url: String,
    redirect_url: String,
    profile: NormalizedProfile,
    use_pkce: bool,
}

#[async_trait]
impl OAuthProvider for MockProvider {
    fn name(&self) -> &str {
        self.name
    }
    fn display_name(&self) -> &str {
        "Test"
    }
    fn client_id(&self) -> &str {
        "test-client-id"
    }
    fn client_secret(&self) -> &str {
        "test-client-secret"
    }
    fn redirect_url(&self) -> &str {
        &self.redirect_url
    }
    fn auth_url(&self) -> &str {
        &self.auth_url
    }
    fn token_url(&self) -> &str {
        &self.token_url
    }
    fn scopes(&self) -> &[&str] {
        &["read:user", "user:email"]
    }
    fn use_pkce(&self) -> bool {
        self.use_pkce
    }
    async fn fetch_profile(
        &self,
        _http: &reqwest::Client,
        _access_token: &str,
    ) -> anyhow::Result<NormalizedProfile> {
        Ok(self.profile.clone())
    }
}

// ============================================================
// Test app bootstrap — stand up the arium Router on 127.0.0.1:<rand>,
// return the pool, base URL, and a cookie-jar reqwest client.
// ============================================================

struct TestApp {
    pool: SqlitePool,
    base_url: String,
    client: Client,
    _serve: tokio::task::JoinHandle<()>,
}

async fn boot(mock_token_url: &str, profile: NormalizedProfile) -> TestApp {
    boot_inner(mock_token_url, profile, false).await
}

async fn boot_inner(mock_token_url: &str, profile: NormalizedProfile, use_pkce: bool) -> TestApp {
    let pool = common::pool().await;
    let mailer = Mailer::from_env().expect("mailer build");

    let provider = MockProvider {
        name: "test",
        // We never follow this URL — the test calls /callback directly.
        auth_url: "https://example.invalid/authorize".to_string(),
        token_url: mock_token_url.to_string(),
        redirect_url: "http://127.0.0.1/auth/test/callback".to_string(),
        profile,
        use_pkce,
    };

    let cfg = AuthConfig::builder(pool.clone(), mailer)
        .oauth_provider(provider)
        .unwrap()
        // Disable rate limiting + audit prune — extra noise for these tests.
        .rate_limit(None)
        .audit(AuditConfig {
            capture_ip: false,
            capture_user_agent: false,
            retention_days: 0,
        })
        .build()
        .unwrap();

    let router: Router = arium::install(Router::new(), cfg).await.expect("install");

    // Bind to an ephemeral port so parallel tests don't collide.
    let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
    let addr: SocketAddr = listener.local_addr().expect("local_addr");
    let base_url = format!("http://{addr}");

    let serve = tokio::spawn(async move {
        let _ = axum::serve(
            listener,
            router.into_make_service_with_connect_info::<SocketAddr>(),
        )
        .await;
    });

    let client = Client::builder()
        .cookie_store(true)
        .redirect(Policy::none())
        .build()
        .expect("client");

    TestApp {
        pool,
        base_url,
        client,
        _serve: serve,
    }
}

fn standard_profile() -> NormalizedProfile {
    NormalizedProfile {
        provider_user_id: "ext-1".to_string(),
        login: "testuser".to_string(),
        name: Some("Test User".to_string()),
        email: Some("test@example.invalid".to_string()),
        avatar_url: None,
        html_url: None,
    }
}

// ============================================================
// Tests
// ============================================================

#[tokio::test]
async fn login_redirects_to_authorize_url_with_state_and_scopes() {
    // No mock needed for the login leg — login doesn't call out.
    let app = boot("http://localhost:1/unused", standard_profile()).await;

    let resp = app
        .client
        .get(format!("{}/auth/test/login", app.base_url))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 303); // axum::response::Redirect::to is 303

    let loc = resp.headers().get("location").unwrap().to_str().unwrap();
    let parsed = url::Url::parse(loc).expect("location is a URL");
    assert_eq!(parsed.host_str(), Some("example.invalid"));
    assert_eq!(parsed.path(), "/authorize");

    let q: std::collections::HashMap<_, _> = parsed.query_pairs().collect();
    assert_eq!(q.get("response_type").map(|s| s.as_ref()), Some("code"));
    assert_eq!(
        q.get("client_id").map(|s| s.as_ref()),
        Some("test-client-id")
    );
    assert!(q.contains_key("state"), "state must be present");
    let scope = q.get("scope").map(|s| s.to_string()).unwrap_or_default();
    assert!(scope.contains("read:user"), "scope={scope:?}");
    assert!(scope.contains("user:email"), "scope={scope:?}");
}

#[tokio::test]
async fn callback_happy_path_creates_user_and_records_audit_event() {
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "access_token": "test-access-token",
            "token_type": "bearer",
            "scope": "read:user",
        })))
        .expect(1)
        .mount(&mock)
        .await;

    let app = boot(&format!("{}/token", mock.uri()), standard_profile()).await;

    // Step 1: login leg, captures the session cookie + the state.
    let resp = app
        .client
        .get(format!("{}/auth/test/login", app.base_url))
        .send()
        .await
        .unwrap();
    let loc = resp.headers().get("location").unwrap().to_str().unwrap();
    let parsed = url::Url::parse(loc).unwrap();
    let state = parsed
        .query_pairs()
        .find(|(k, _)| k == "state")
        .map(|(_, v)| v.to_string())
        .unwrap();

    // Step 2: synthesize the provider callback. Cookie jar replays the
    // session cookie from step 1 automatically.
    let resp = app
        .client
        .get(format!(
            "{}/auth/test/callback?code=fake-code&state={state}",
            app.base_url
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status().as_u16(),
        303,
        "callback success redirects to /"
    );
    assert_eq!(
        resp.headers().get("location").unwrap().to_str().unwrap(),
        "/"
    );

    // The upsert ran: user + oauth_accounts row exist.
    let user_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM users WHERE anonymous = false")
        .fetch_one(&app.pool)
        .await
        .unwrap();
    assert_eq!(user_count, 1);

    let oa: (String, String) =
        sqlx::query_as("SELECT provider, provider_user_id FROM oauth_accounts LIMIT 1")
            .fetch_one(&app.pool)
            .await
            .unwrap();
    assert_eq!(oa, ("test".to_string(), "ext-1".to_string()));

    // Audit event recorded with method=oauth in the details JSON.
    let row: (String, Option<String>) = sqlx::query_as(
        "SELECT event_type, details FROM audit_events \
         WHERE event_type = 'user.login.success' LIMIT 1",
    )
    .fetch_one(&app.pool)
    .await
    .unwrap();
    assert_eq!(row.0, "user.login.success");
    let details = row.1.unwrap_or_default();
    assert!(details.contains("\"method\":\"oauth\""), "{details}");
    assert!(details.contains("\"provider\":\"test\""), "{details}");
}

#[tokio::test]
async fn callback_with_no_session_returns_400_missing_state() {
    // No prior /login call, so no `oauth_state:test` in the session.
    let app = boot("http://localhost:1/unused", standard_profile()).await;

    let resp = app
        .client
        .get(format!(
            "{}/auth/test/callback?code=fake&state=anything",
            app.base_url
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 400);
    let body = resp.text().await.unwrap();
    assert!(body.contains("missing oauth state"), "body={body:?}");
}

#[tokio::test]
async fn callback_with_state_mismatch_returns_400() {
    let app = boot("http://localhost:1/unused", standard_profile()).await;

    // Establish a session via /login so the state cookie exists.
    app.client
        .get(format!("{}/auth/test/login", app.base_url))
        .send()
        .await
        .unwrap();

    // Hit /callback with a *wrong* state.
    let resp = app
        .client
        .get(format!(
            "{}/auth/test/callback?code=fake&state=not-the-real-state",
            app.base_url
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 400);
    let body = resp.text().await.unwrap();
    assert!(body.contains("state mismatch"), "body={body:?}");
}

#[tokio::test]
async fn callback_state_is_consumed_after_one_attempt() {
    // The state must be single-use: even a *correct* state replay after a
    // failed attempt should now miss because the handler removes the state
    // from the session before checking it. Verifies the
    // `session.remove(&state_key)` line in `oauth_callback`.
    let app = boot("http://localhost:1/unused", standard_profile()).await;

    let resp = app
        .client
        .get(format!("{}/auth/test/login", app.base_url))
        .send()
        .await
        .unwrap();
    let loc = resp.headers().get("location").unwrap().to_str().unwrap();
    let state = url::Url::parse(loc)
        .unwrap()
        .query_pairs()
        .find(|(k, _)| k == "state")
        .map(|(_, v)| v.to_string())
        .unwrap();

    // First attempt with a wrong state → 400, but session.remove fired.
    let _ = app
        .client
        .get(format!(
            "{}/auth/test/callback?code=x&state=wrong",
            app.base_url
        ))
        .send()
        .await
        .unwrap();

    // Now a second attempt with the *correct* state must fail too — the
    // state's already been pulled from the session.
    let resp = app
        .client
        .get(format!(
            "{}/auth/test/callback?code=x&state={state}",
            app.base_url
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 400);
    let body = resp.text().await.unwrap();
    assert!(body.contains("missing oauth state"), "body={body:?}");
}

#[tokio::test]
async fn callback_when_token_endpoint_returns_500_returns_502() {
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/token"))
        .respond_with(ResponseTemplate::new(500).set_body_string("upstream boom"))
        .mount(&mock)
        .await;

    let app = boot(&format!("{}/token", mock.uri()), standard_profile()).await;

    // Establish state.
    let resp = app
        .client
        .get(format!("{}/auth/test/login", app.base_url))
        .send()
        .await
        .unwrap();
    let state = url::Url::parse(resp.headers().get("location").unwrap().to_str().unwrap())
        .unwrap()
        .query_pairs()
        .find(|(k, _)| k == "state")
        .map(|(_, v)| v.to_string())
        .unwrap();

    let resp = app
        .client
        .get(format!(
            "{}/auth/test/callback?code=x&state={state}",
            app.base_url
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status().as_u16(),
        502,
        "provider 5xx must surface as Bad Gateway",
    );
}

#[tokio::test]
async fn callback_with_malformed_token_body_returns_502() {
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/token"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string("this is not json")
                .insert_header("content-type", "application/json"),
        )
        .mount(&mock)
        .await;

    let app = boot(&format!("{}/token", mock.uri()), standard_profile()).await;

    let resp = app
        .client
        .get(format!("{}/auth/test/login", app.base_url))
        .send()
        .await
        .unwrap();
    let state = url::Url::parse(resp.headers().get("location").unwrap().to_str().unwrap())
        .unwrap()
        .query_pairs()
        .find(|(k, _)| k == "state")
        .map(|(_, v)| v.to_string())
        .unwrap();

    let resp = app
        .client
        .get(format!(
            "{}/auth/test/callback?code=x&state={state}",
            app.base_url
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 502);
}

#[tokio::test]
async fn callback_for_unknown_provider_returns_404() {
    let app = boot("http://localhost:1/unused", standard_profile()).await;
    let resp = app
        .client
        .get(format!(
            "{}/auth/nosuch/callback?code=x&state=y",
            app.base_url
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 404);
}

#[tokio::test]
async fn login_for_unknown_provider_returns_404() {
    let app = boot("http://localhost:1/unused", standard_profile()).await;
    let resp = app
        .client
        .get(format!("{}/auth/nosuch/login", app.base_url))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 404);
}

#[tokio::test]
async fn token_request_carries_client_credentials_and_code() {
    // Verify the wire shape of the outbound token request: client id +
    // secret as HTTP Basic, `code` + `grant_type=authorization_code` in
    // the form body. This is the bit the oauth2 crate owns, but a regression
    // in our wiring (e.g. swapping client id/secret) would slip past unit
    // tests of `upsert_oauth_user`.
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/token"))
        .and(wiremock::matchers::body_string_contains(
            "grant_type=authorization_code",
        ))
        .and(wiremock::matchers::body_string_contains("code=fake-code"))
        .and(wiremock::matchers::header(
            "authorization",
            // base64("test-client-id:test-client-secret")
            "Basic dGVzdC1jbGllbnQtaWQ6dGVzdC1jbGllbnQtc2VjcmV0",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "access_token": "tok",
            "token_type": "bearer",
        })))
        .expect(1)
        .mount(&mock)
        .await;

    let app = boot(&format!("{}/token", mock.uri()), standard_profile()).await;
    let resp = app
        .client
        .get(format!("{}/auth/test/login", app.base_url))
        .send()
        .await
        .unwrap();
    let state = url::Url::parse(resp.headers().get("location").unwrap().to_str().unwrap())
        .unwrap()
        .query_pairs()
        .find(|(k, _)| k == "state")
        .map(|(_, v)| v.to_string())
        .unwrap();
    let resp = app
        .client
        .get(format!(
            "{}/auth/test/callback?code=fake-code&state={state}",
            app.base_url
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 303);
    // Mock's `.expect(1)` is verified on drop.
    drop(app);
    drop(mock);
}

// ============================================================
// PKCE (RFC 7636) — opt-in via `use_pkce()` on the default begin/finish path.
// ============================================================

#[tokio::test]
async fn pkce_off_by_default_omits_code_challenge() {
    // The standard MockProvider has use_pkce = false → no PKCE params.
    let app = boot("http://localhost:1/unused", standard_profile()).await;
    let resp = app
        .client
        .get(format!("{}/auth/test/login", app.base_url))
        .send()
        .await
        .unwrap();
    let loc = resp.headers().get("location").unwrap().to_str().unwrap();
    assert!(
        !loc.contains("code_challenge"),
        "no PKCE expected by default, got {loc}"
    );
}

#[tokio::test]
async fn pkce_round_trips_challenge_in_authorize_and_verifier_at_token() {
    // With PKCE enabled, the authorize URL must carry a sha256 challenge, and
    // the subsequent token request must replay the matching code_verifier.
    let mock = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/token"))
        .and(wiremock::matchers::body_string_contains("code_verifier="))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "access_token": "test-access-token",
            "token_type": "bearer",
        })))
        .expect(1)
        .mount(&mock)
        .await;

    let app = boot_inner(&format!("{}/token", mock.uri()), standard_profile(), true).await;

    let resp = app
        .client
        .get(format!("{}/auth/test/login", app.base_url))
        .send()
        .await
        .unwrap();
    let loc = resp.headers().get("location").unwrap().to_str().unwrap();
    let parsed = url::Url::parse(loc).unwrap();
    let q: std::collections::HashMap<_, _> = parsed.query_pairs().collect();
    assert!(q.contains_key("code_challenge"), "loc={loc}");
    assert_eq!(
        q.get("code_challenge_method").map(|s| s.as_ref()),
        Some("S256")
    );
    let state = q.get("state").map(|s| s.to_string()).unwrap();

    let resp = app
        .client
        .get(format!(
            "{}/auth/test/callback?code=fake-code&state={state}",
            app.base_url
        ))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 303);
    // The `body_string_contains("code_verifier=")` matcher + `.expect(1)` prove
    // the verifier was replayed.
    drop(app);
    drop(mock);
}

#[tokio::test]
async fn github_provider_pkce_opt_in_adds_code_challenge() {
    // The GitHub provider gains a `with_pkce` opt-in over the default flow.
    use arium::oauth::github::GithubProvider;

    let off = GithubProvider::new(
        "id".to_string(),
        "secret".to_string(),
        "http://localhost/cb".to_string(),
    );
    let (url_off, attempt_off) = off.begin().unwrap();
    assert!(attempt_off.pkce_verifier.is_none());
    assert!(!url_off.contains("code_challenge"), "url_off={url_off}");

    let on = GithubProvider::new(
        "id".to_string(),
        "secret".to_string(),
        "http://localhost/cb".to_string(),
    )
    .with_pkce(true);
    let (url_on, attempt_on) = on.begin().unwrap();
    assert!(attempt_on.pkce_verifier.is_some());
    assert!(url_on.contains("code_challenge="), "url_on={url_on}");
    assert!(
        url_on.contains("code_challenge_method=S256"),
        "url_on={url_on}"
    );
}