ryuk 0.1.0

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
//! Social login: an OAuth2 client for GitHub and Google (authorization code + PKCE S256 + `state`).
//!
//! ```ignore
//! let social = Social::new().github(GitHub::from_env()).google(Google::from_env());
//! let app = Router::new().merge(social.routes(MyUsers)).layer(session_layer());
//! // link: <a href="/auth/github/redirect">Sign in with GitHub</a>  (a plain navigation, not an Inertia visit)
//! ```
//!
//! Routes: `GET /auth/{provider}/redirect` and `GET /auth/{provider}/callback` (unknown provider: 404).
//! `state` and the PKCE verifier come from the CSPRNG, live only in the session, are removed on the
//! first callback (a replay finds nothing) and `state` is compared in constant time. The redirect URI is
//! `APP_URL` + `/auth/{provider}/callback`. The access token is used for one or two userinfo calls and
//! dropped; no `id_token` is parsed because the profile comes straight from the provider's
//! TLS-authenticated userinfo endpoint. Every failure (denied consent, bad state, provider or app
//! error) flashes an error and 303s to `/login`; provider bodies, codes and tokens are never logged
//! or shown. HTTP calls time out after 10 s and follow no redirects at all.
//!
//! # Account linking policy (implemented by the app in [`SocialUsers::resolve`], NOT here)
//! 1. Match by `(provider, subject)`: that identity is stable, emails are not.
//! 2. Auto-link to an existing local account by email only when `profile.email_verified` AND the local
//!    account's email is verified too. Otherwise refuse and ask the user to log in first, then link
//!    from settings. Linking on an unverified email is an account takeover.
//! 3. A new account may be created from a verified email; never from an unverified one without
//!    confirming it.
use crate::health::BoxFuture;
use axum::{
    Router,
    extract::{Path, Query, State},
    http::{StatusCode, header},
    response::{IntoResponse, Response},
    routing::get,
};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as B64};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::{collections::HashMap, sync::Arc, time::Duration};
use tower_sessions::Session;

const SESSION_KEY: &str = "social_oauth";

/// What a provider told us about the user.
#[derive(Debug, Clone, PartialEq)]
pub struct SocialProfile {
    /// `"github"` or `"google"`.
    pub provider: &'static str,
    /// The provider's stable user id.
    pub subject: String,
    /// Email, only set when the provider returned one (GitHub: primary and verified).
    pub email: Option<String>,
    /// The provider vouches for `email`.
    pub email_verified: bool,
    /// Display name.
    pub name: Option<String>,
}

/// Why the app refused a profile; shown to the user only as a generic flash, logged here.
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct SocialError(pub String);

/// Implemented by the app: map a provider profile to a local user id (see the module docs for the
/// safe linking policy).
pub trait SocialUsers: Send + Sync + 'static {
    /// Find, link or create the local user for `profile`; `Err` aborts the login.
    fn resolve<'a>(&'a self, profile: &'a SocialProfile)
    -> BoxFuture<'a, Result<i64, SocialError>>;
}

/// GitHub OAuth app credentials and endpoints (override the URLs to test against a mock).
#[derive(Clone)]
pub struct GitHub {
    pub client_id: String,
    pub client_secret: String,
    pub authorize_url: String,
    pub token_url: String,
    pub user_url: String,
    pub emails_url: String,
}

/// Google OAuth client credentials and endpoints (override the URLs to test against a mock).
#[derive(Clone)]
pub struct Google {
    pub client_id: String,
    pub client_secret: String,
    pub authorize_url: String,
    pub token_url: String,
    pub userinfo_url: String,
}

/// Never print `client_secret`: a `{:?}` of a provider (or of `Social`) must be safe to log.
impl std::fmt::Debug for GitHub {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GitHub")
            .field("client_id", &self.client_id)
            .field("client_secret", &"<redacted>")
            .finish_non_exhaustive()
    }
}

impl std::fmt::Debug for Google {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Google")
            .field("client_id", &self.client_id)
            .field("client_secret", &"<redacted>")
            .finish_non_exhaustive()
    }
}

fn env_pair(prefix: &str) -> Option<(String, String)> {
    let get = |k: &str| {
        std::env::var(format!("{prefix}_{k}"))
            .ok()
            .filter(|v| !v.is_empty())
    };
    Some((get("CLIENT_ID")?, get("CLIENT_SECRET")?))
}

impl GitHub {
    /// Production endpoints with the given credentials.
    pub fn new(id: impl Into<String>, secret: impl Into<String>) -> Self {
        GitHub {
            client_id: id.into(),
            client_secret: secret.into(),
            authorize_url: "https://github.com/login/oauth/authorize".into(),
            token_url: "https://github.com/login/oauth/access_token".into(),
            user_url: "https://api.github.com/user".into(),
            emails_url: "https://api.github.com/user/emails".into(),
        }
    }
    /// From `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`; `None` when unset (provider disabled).
    pub fn from_env() -> Option<Self> {
        env_pair("GITHUB").map(|(i, s)| Self::new(i, s))
    }
}

impl Google {
    /// Production endpoints with the given credentials.
    pub fn new(id: impl Into<String>, secret: impl Into<String>) -> Self {
        Google {
            client_id: id.into(),
            client_secret: secret.into(),
            authorize_url: "https://accounts.google.com/o/oauth2/v2/auth".into(),
            token_url: "https://oauth2.googleapis.com/token".into(),
            userinfo_url: "https://openidconnect.googleapis.com/v1/userinfo".into(),
        }
    }
    /// From `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`; `None` when unset (provider disabled).
    pub fn from_env() -> Option<Self> {
        env_pair("GOOGLE").map(|(i, s)| Self::new(i, s))
    }
}

/// Social login configuration; call [`Social::routes`] to mount it.
#[derive(Debug, Clone)]
pub struct Social {
    github: Option<GitHub>,
    google: Option<Google>,
    app_url: String,
    after_login: String,
}

impl Default for Social {
    fn default() -> Self {
        Self::new()
    }
}

impl Social {
    /// No providers yet; redirect base from `APP_URL` (default `http://127.0.0.1:3000`), then `/dashboard`.
    pub fn new() -> Self {
        Social {
            github: None,
            google: None,
            app_url: std::env::var("APP_URL").unwrap_or_else(|_| "http://127.0.0.1:3000".into()),
            after_login: "/dashboard".into(),
        }
    }
    /// Enable GitHub (`GitHub::from_env()` is accepted directly; `None` leaves it off).
    pub fn github(mut self, p: impl Into<Option<GitHub>>) -> Self {
        self.github = p.into();
        self
    }
    /// Enable Google (`Google::from_env()` is accepted directly; `None` leaves it off).
    pub fn google(mut self, p: impl Into<Option<Google>>) -> Self {
        self.google = p.into();
        self
    }
    /// Names of the configured providers, in `/auth/{provider}/redirect` form (for a login page).
    pub fn providers(&self) -> Vec<&'static str> {
        let mut v = Vec::new();
        if self.github.is_some() {
            v.push("github");
        }
        if self.google.is_some() {
            v.push("google");
        }
        v
    }
    /// Override the public base URL used for the redirect URI.
    pub fn app_url(mut self, url: &str) -> Self {
        self.app_url = url.into();
        self
    }
    /// Where a successful login lands (default `/dashboard`).
    pub fn after_login(mut self, to: &str) -> Self {
        self.after_login = to.into();
        self
    }

    /// The two routes, for any router state: `Router::new().merge(social.routes(users))`.
    pub fn routes<S: Clone + Send + Sync + 'static>(self, users: impl SocialUsers) -> Router<S> {
        let http = reqwest::Client::builder()
            .timeout(Duration::from_secs(10))
            .connect_timeout(Duration::from_secs(10))
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .expect("reqwest client (rustls) builds");
        let inner = Arc::new(Inner {
            cfg: self,
            users: Box::new(users),
            http,
        });
        Router::new()
            .route("/auth/{provider}/redirect", get(start))
            .route("/auth/{provider}/callback", get(callback))
            .with_state(inner)
    }
}

struct Inner {
    cfg: Social,
    users: Box<dyn SocialUsers>,
    http: reqwest::Client,
}

/// Provider-specific bits, borrowed from the config.
struct Prov<'a> {
    name: &'static str,
    id: &'a str,
    secret: &'a str,
    authorize: &'a str,
    token: &'a str,
    scope: &'static str,
}

impl Inner {
    fn prov(&self, name: &str) -> Option<Prov<'_>> {
        match (name, &self.cfg.github, &self.cfg.google) {
            ("github", Some(g), _) => Some(Prov {
                name: "github",
                id: &g.client_id,
                secret: &g.client_secret,
                authorize: &g.authorize_url,
                token: &g.token_url,
                scope: "read:user user:email",
            }),
            ("google", _, Some(g)) => Some(Prov {
                name: "google",
                id: &g.client_id,
                secret: &g.client_secret,
                authorize: &g.authorize_url,
                token: &g.token_url,
                scope: "openid email profile",
            }),
            _ => None,
        }
    }

    fn redirect_uri(&self, name: &str) -> String {
        format!(
            "{}/auth/{name}/callback",
            self.cfg.app_url.trim_end_matches('/')
        )
    }

    async fn fetch(&self, url: &str, token: &str) -> Result<Value, &'static str> {
        let r = self
            .http
            .get(url)
            .bearer_auth(token)
            .header(header::ACCEPT, "application/json")
            .header(header::USER_AGENT, "ryuk-social")
            .send()
            .await
            .map_err(|_| "userinfo request failed")?;
        if !r.status().is_success() {
            return Err("userinfo rejected the token");
        }
        r.json().await.map_err(|_| "userinfo unreadable")
    }

    /// Exchange the code, fetch the profile, drop the token. Errors are static strings (safe to log).
    async fn profile(
        &self,
        p: &Prov<'_>,
        code: &str,
        verifier: &str,
    ) -> Result<SocialProfile, &'static str> {
        // reqwest's `form` needs a feature the manifest does not enable; encode by hand.
        let form = url::form_urlencoded::Serializer::new(String::new())
            .append_pair("grant_type", "authorization_code")
            .append_pair("code", code)
            .append_pair("redirect_uri", &self.redirect_uri(p.name))
            .append_pair("client_id", p.id)
            .append_pair("client_secret", p.secret)
            .append_pair("code_verifier", verifier)
            .finish();
        let res = self
            .http
            .post(p.token)
            .header(header::ACCEPT, "application/json")
            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
            .body(form)
            .send()
            .await
            .map_err(|_| "token request failed")?;
        if !res.status().is_success() {
            return Err("token endpoint rejected the code");
        }
        let body: Value = res.json().await.map_err(|_| "token response unreadable")?;
        let token = body["access_token"].as_str().ok_or("no access_token")?;
        if let Some(g) = self.cfg.github.as_ref().filter(|_| p.name == "github") {
            let u = self.fetch(&g.user_url, token).await?;
            let subject = match &u["id"] {
                Value::Number(n) => n.to_string(),
                Value::String(s) => s.clone(),
                _ => return Err("no user id"),
            };
            let emails = self.fetch(&g.emails_url, token).await?;
            let email = emails
                .as_array()
                .and_then(|a| {
                    a.iter()
                        .find(|e| e["primary"] == true && e["verified"] == true)
                })
                .and_then(|e| e["email"].as_str())
                .map(str::to_owned);
            let name = u["name"].as_str().or(u["login"].as_str());
            Ok(SocialProfile {
                provider: "github",
                subject,
                email_verified: email.is_some(),
                email,
                name: name.map(str::to_owned),
            })
        } else if let Some(g) = &self.cfg.google {
            let u = self.fetch(&g.userinfo_url, token).await?;
            let subject = u["sub"].as_str().ok_or("no sub")?.to_owned();
            let verified = u["email_verified"] == true || u["email_verified"] == "true";
            let email = u["email"].as_str().map(str::to_owned);
            Ok(SocialProfile {
                provider: "google",
                subject,
                email_verified: verified && email.is_some(),
                email,
                name: u["name"].as_str().map(str::to_owned),
            })
        } else {
            Err("provider disabled")
        }
    }
}

fn random_b64() -> String {
    let b: [u8; 32] = rand::random();
    B64.encode(b)
}

fn ct_eq(a: &str, b: &str) -> bool {
    a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0
}

async fn fail(session: &Session, msg: &str) -> Response {
    crate::inertia::flash(session, "error", msg).await;
    crate::inertia::redirect("/login")
}

async fn start(
    State(s): State<Arc<Inner>>,
    Path(provider): Path<String>,
    session: Session,
) -> Response {
    let Some(p) = s.prov(&provider) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let (state, verifier) = (random_b64(), random_b64());
    let challenge = B64.encode(Sha256::digest(verifier.as_bytes()));
    let Ok(mut url) = url::Url::parse(p.authorize) else {
        tracing::error!(provider = p.name, "social: invalid authorize url");
        return fail(&session, "Sign-in is unavailable.").await;
    };
    url.query_pairs_mut()
        .append_pair("response_type", "code")
        .append_pair("client_id", p.id)
        .append_pair("redirect_uri", &s.redirect_uri(p.name))
        .append_pair("scope", p.scope)
        .append_pair("state", &state)
        .append_pair("code_challenge", &challenge)
        .append_pair("code_challenge_method", "S256");
    let saved = serde_json::json!({"provider": p.name, "state": state, "verifier": verifier});
    if session.insert(SESSION_KEY, saved).await.is_err() {
        tracing::error!(provider = p.name, "social: session write failed");
        return fail(&session, "Sign-in is unavailable.").await;
    }
    crate::inertia::redirect(url.as_str())
}

async fn callback(
    State(s): State<Arc<Inner>>,
    Path(provider): Path<String>,
    Query(q): Query<HashMap<String, String>>,
    session: Session,
) -> Response {
    let Some(p) = s.prov(&provider) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    // Consumed before anything else so a replayed callback always finds nothing.
    let saved: Option<Value> = session.remove(SESSION_KEY).await.ok().flatten();
    let state_ok = saved.as_ref().is_some_and(|v| {
        v["provider"] == p.name
            && q.get("state")
                .is_some_and(|got| ct_eq(got, v["state"].as_str().unwrap_or("")))
    });
    if !state_ok {
        tracing::warn!(provider = p.name, "social: state mismatch or missing");
        return fail(&session, "Sign-in failed. Please try again.").await;
    }
    if q.contains_key("error") {
        tracing::info!(
            provider = p.name,
            "social: consent denied or provider error"
        );
        return fail(&session, "Sign-in was cancelled.").await;
    }
    let (Some(code), Some(verifier)) = (
        q.get("code"),
        saved.as_ref().and_then(|v| v["verifier"].as_str()),
    ) else {
        return fail(&session, "Sign-in failed. Please try again.").await;
    };
    let profile = match s.profile(&p, code, verifier).await {
        Ok(pr) => pr,
        Err(why) => {
            tracing::warn!(provider = p.name, "social: {why}");
            return fail(&session, "Sign-in failed. Please try again.").await;
        }
    };
    let uid = match s.users.resolve(&profile).await {
        Ok(uid) => uid,
        Err(e) => {
            tracing::warn!(provider = p.name, "social: login refused: {e}");
            return fail(&session, "We could not sign you in with that account.").await;
        }
    };
    if crate::auth::login(&session, uid).await.is_err() {
        tracing::error!(provider = p.name, "social: session login failed");
        return fail(&session, "Sign-in failed. Please try again.").await;
    }
    crate::inertia::flash(&session, "success", "Signed in.").await;
    crate::inertia::redirect(&s.cfg.after_login)
}

#[cfg(test)]
mod tests {
    #[test]
    fn debug_never_prints_client_secrets_and_providers_lists_names() {
        let s = Social::new()
            .github(GitHub::new("gh-id", "gh-SECRET-value"))
            .google(Google::new("g-id", "goog-SECRET-value"));
        let shown = format!(
            "{s:?} {:?} {:?}",
            GitHub::new("a", "gh-SECRET-value"),
            Google::new("b", "goog-SECRET-value")
        );
        assert!(!shown.contains("SECRET-value"), "{shown}");
        assert_eq!(s.providers(), vec!["github", "google"]);
        assert!(Social::new().providers().is_empty());
        assert_eq!(
            Social::new().github(GitHub::new("i", "s")).providers(),
            vec!["github"]
        );
    }

    use super::*;
    use axum::{body::Body, http::HeaderMap, http::Request};
    use std::sync::Mutex;
    use tower::ServiceExt;

    #[derive(Default)]
    struct Mock {
        challenges: Mutex<HashMap<String, String>>, // code -> challenge
        verified: bool,
        token_fails: bool,
        deny: bool,
    }
    type M = Arc<Mock>;

    const SECRET: &str = "sek-ret-value";
    const TOKEN: &str = "tok-en-value";

    async fn authorize(State(m): State<M>, Query(q): Query<HashMap<String, String>>) -> Response {
        let (st, redir) = (&q["state"], &q["redirect_uri"]);
        assert_eq!(q["code_challenge_method"], "S256");
        let loc = if m.deny {
            format!("{redir}?error=access_denied&state={st}")
        } else {
            let mut c = m.challenges.lock().unwrap();
            let code = format!("code{}", c.len());
            c.insert(code.clone(), q["code_challenge"].clone());
            format!("{redir}?code={code}&state={st}")
        };
        (StatusCode::SEE_OTHER, [(header::LOCATION, loc)]).into_response()
    }

    async fn token(
        State(m): State<M>,
        axum::Form(f): axum::Form<HashMap<String, String>>,
    ) -> Response {
        let chal = m.challenges.lock().unwrap().remove(&f["code"]); // single use
        let ok = !m.token_fails
            && f["client_secret"] == SECRET
            && chal.is_some_and(|c| c == B64.encode(Sha256::digest(f["code_verifier"].as_bytes())));
        if ok {
            axum::Json(serde_json::json!({"access_token": TOKEN})).into_response()
        } else {
            (StatusCode::BAD_REQUEST, "secret provider error body").into_response()
        }
    }

    fn authed(h: &HeaderMap) -> bool {
        h.get(header::AUTHORIZATION)
            .is_some_and(|v| v == &format!("Bearer {TOKEN}"))
    }

    /// In-process provider on port 0; returns its base URL.
    async fn mock(m: M) -> String {
        let app = Router::new()
            .route("/authorize", get(authorize))
            .route("/token", axum::routing::post(token))
            .route(
                "/user",
                get(|h: HeaderMap| async move {
                    if authed(&h) {
                        axum::Json(serde_json::json!({"id": 7, "login": "octo"})).into_response()
                    } else {
                        StatusCode::UNAUTHORIZED.into_response()
                    }
                }),
            )
            .route(
                "/emails",
                get(|State(m): State<M>, h: HeaderMap| async move {
                    if !authed(&h) {
                        return StatusCode::UNAUTHORIZED.into_response();
                    }
                    axum::Json(serde_json::json!([
                        {"email": "other@x.test", "primary": false, "verified": true},
                        {"email": "me@x.test", "primary": true, "verified": m.verified}
                    ]))
                    .into_response()
                }),
            )
            .route(
                "/userinfo",
                get(|State(m): State<M>, h: HeaderMap| async move {
                    if !authed(&h) {
                        return StatusCode::UNAUTHORIZED.into_response();
                    }
                    axum::Json(serde_json::json!({"sub": "g1", "email": "me@x.test",
                        "email_verified": m.verified, "name": "Gee"}))
                    .into_response()
                }),
            )
            .with_state(m);
        let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", l.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(l, app).await.unwrap() });
        base
    }

    struct Users(Arc<Mutex<Vec<SocialProfile>>>);
    impl SocialUsers for Users {
        fn resolve<'a>(&'a self, p: &'a SocialProfile) -> BoxFuture<'a, Result<i64, SocialError>> {
            Box::pin(async move {
                self.0.lock().unwrap().push(p.clone());
                Ok(42)
            })
        }
    }

    struct Env {
        app: Router,
        base: String,
        seen: Arc<Mutex<Vec<SocialProfile>>>,
        cookie: String,
        http: reqwest::Client,
    }

    async fn env(m: Mock) -> Env {
        let base = mock(Arc::new(m)).await;
        let mut gh = GitHub::new("cid", SECRET);
        gh.authorize_url = format!("{base}/authorize");
        gh.token_url = format!("{base}/token");
        gh.user_url = format!("{base}/user");
        gh.emails_url = format!("{base}/emails");
        let mut gg = Google::new("gid", SECRET);
        gg.authorize_url = format!("{base}/authorize");
        gg.token_url = format!("{base}/token");
        gg.userinfo_url = format!("{base}/userinfo");
        let seen = Arc::new(Mutex::new(vec![]));
        let social = Social::new()
            .app_url("http://app.test")
            .github(gh)
            .google(gg);
        let app = Router::new()
            .merge(social.routes(Users(seen.clone())))
            .layer(crate::session::session_layer());
        let http = reqwest::Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .unwrap();
        Env {
            app,
            base,
            seen,
            cookie: String::new(),
            http,
        }
    }

    impl Env {
        /// Returns (status, Location), carrying the session cookie like a browser.
        async fn get(&mut self, uri: &str) -> (StatusCode, String) {
            let mut r = Request::get(uri);
            if !self.cookie.is_empty() {
                r = r.header(header::COOKIE, &self.cookie);
            }
            let res = self
                .app
                .clone()
                .oneshot(r.body(Body::empty()).unwrap())
                .await
                .unwrap();
            if let Some(c) = res.headers().get(header::SET_COOKIE) {
                self.cookie = c.to_str().unwrap().split(';').next().unwrap().to_owned();
            }
            let loc = res
                .headers()
                .get(header::LOCATION)
                .map(|v| v.to_str().unwrap().to_owned())
                .unwrap_or_default();
            (res.status(), loc)
        }
        /// Browser dance through the provider; returns the callback path+query it redirects to.
        async fn authorize(&mut self, provider: &str) -> String {
            let (_, loc) = self.get(&format!("/auth/{provider}/redirect")).await;
            assert!(loc.starts_with(&self.base), "{loc}");
            let res = self.http.get(&loc).send().await.unwrap();
            let back = res.headers()[header::LOCATION].to_str().unwrap().to_owned();
            back.strip_prefix("http://app.test").unwrap().to_owned()
        }
    }

    #[tokio::test]
    async fn happy_path_github_with_pkce_and_secret() {
        // the mock token endpoint rejects a wrong verifier, secret or reused code
        let mut e = env(Mock {
            verified: true,
            ..Default::default()
        })
        .await;
        let cb = e.authorize("github").await;
        assert_eq!(
            e.get(&cb).await,
            (StatusCode::SEE_OTHER, "/dashboard".into())
        );
        let seen = e.seen.lock().unwrap();
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].subject, "7");
        assert_eq!(seen[0].email.as_deref(), Some("me@x.test"));
        assert!(seen[0].email_verified);
    }

    #[tokio::test]
    async fn happy_path_google() {
        let mut e = env(Mock {
            verified: true,
            ..Default::default()
        })
        .await;
        let cb = e.authorize("google").await;
        assert_eq!(e.get(&cb).await.1, "/dashboard");
        let seen = e.seen.lock().unwrap();
        assert_eq!(
            (
                seen[0].provider,
                seen[0].subject.as_str(),
                seen[0].email_verified
            ),
            ("google", "g1", true)
        );
    }

    #[tokio::test]
    async fn unverified_email_is_reported_unverified() {
        let mut e = env(Mock::default()).await;
        let cb = e.authorize("github").await;
        assert_eq!(e.get(&cb).await.1, "/dashboard");
        let cb = e.authorize("google").await;
        e.get(&cb).await;
        let seen = e.seen.lock().unwrap();
        assert_eq!(seen[0].email, None); // GitHub: primary email unverified -> none
        assert!(!seen[0].email_verified && !seen[1].email_verified);
    }

    #[tokio::test]
    async fn state_mismatch_replay_denied_and_provider_error_go_to_login() {
        let mut e = env(Mock {
            verified: true,
            ..Default::default()
        })
        .await;
        let cb = e.authorize("github").await;
        assert_eq!(e.get(&cb.replace("state=", "state=x")).await.1, "/login");
        // the failed attempt consumed the state: the genuine callback now fails too
        assert_eq!(e.get(&cb).await.1, "/login");
        // replay after success
        let cb = e.authorize("github").await;
        assert_eq!(e.get(&cb).await.1, "/dashboard");
        assert_eq!(e.get(&cb).await.1, "/login");
        assert_eq!(e.seen.lock().unwrap().len(), 1);
        // no session at all
        let mut fresh = env(Mock::default()).await;
        assert_eq!(
            fresh.get("/auth/github/callback?code=a&state=b").await.1,
            "/login"
        );
        // denied consent
        let mut d = env(Mock {
            deny: true,
            ..Default::default()
        })
        .await;
        let cb = d.authorize("github").await;
        assert_eq!(d.get(&cb).await.1, "/login");
        // provider error
        let mut p = env(Mock {
            token_fails: true,
            ..Default::default()
        })
        .await;
        let cb = p.authorize("google").await;
        assert_eq!(
            p.get(&cb).await,
            (StatusCode::SEE_OTHER, "/login".to_string())
        );
        assert!(p.seen.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn unknown_provider_is_404() {
        let mut e = env(Mock::default()).await;
        assert_eq!(
            e.get("/auth/myspace/redirect").await.0,
            StatusCode::NOT_FOUND
        );
        assert_eq!(
            e.get("/auth/myspace/callback").await.0,
            StatusCode::NOT_FOUND
        );
    }

    #[tokio::test]
    async fn redirect_url_is_well_formed() {
        let mut e = env(Mock::default()).await;
        let (st, loc) = e.get("/auth/github/redirect").await;
        assert_eq!(st, StatusCode::SEE_OTHER);
        let q: HashMap<_, _> = url::Url::parse(&loc)
            .unwrap()
            .query_pairs()
            .into_owned()
            .collect();
        assert_eq!(q["redirect_uri"], "http://app.test/auth/github/callback");
        assert_eq!(q["client_id"], "cid");
        assert_eq!(q["state"].len(), 43);
        assert!(!loc.contains(SECRET));
    }

    #[derive(Clone, Default)]
    struct Buf(Arc<Mutex<Vec<u8>>>);
    impl std::io::Write for Buf {
        fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(b);
            Ok(b.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Buf {
        type Writer = Buf;
        fn make_writer(&'a self) -> Buf {
            self.clone()
        }
    }

    #[tokio::test]
    async fn secrets_never_logged() {
        let buf = Buf::default();
        let _g = tracing::subscriber::set_default(
            tracing_subscriber::fmt()
                .with_writer(buf.clone())
                .with_max_level(tracing::Level::TRACE)
                .finish(),
        );
        for m in [
            Mock {
                token_fails: true,
                ..Default::default()
            },
            Mock {
                verified: true,
                ..Default::default()
            },
        ] {
            let mut e = env(m).await;
            let cb = e.authorize("github").await;
            e.get(&cb).await;
            e.get(&cb).await; // replay
            e.get("/auth/github/callback?code=zzcode&state=bad").await;
        }
        let logs = String::from_utf8(buf.0.lock().unwrap().clone()).unwrap();
        assert!(logs.contains("social:"), "expected social logs: {logs}");
        for secret in [
            SECRET,
            TOKEN,
            "zzcode",
            "code0",
            "secret provider error body",
            "state=",
        ] {
            assert!(!logs.contains(secret), "{secret} leaked: {logs}");
        }
    }
}