rustango 0.65.0

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
//! `SsoProvider` — one configurable OpenID Connect / social login provider,
//! stored as a row and managed from the admin UI (`sso` feature).
//!
//! This replaces the old flat `Org.sso_*` columns (single provider per
//! tenant). A tenant/app can now have **many** providers, each a row:
//! enter an OIDC `issuer_url` + `client_id` + a `secret_ref`, and the login
//! endpoints are auto-discovered at login time via
//! `OAuth2Provider::from_discovery`. Known social keys (`google`,
//! `microsoft`, `github`, `gitlab`, `discord`) use the built-in presets and
//! need no issuer.
//!
//! Scope: **tenant** (default) — the table lives in each tenant's own
//! storage, so tenant admins manage their own providers (granular) and the
//! bare/standalone admin uses it as a plain global table. The registry-wide
//! shared set is the sibling [`crate::tenancy::sso::SharedSsoProvider`].
//!
//! The client secret is stored in `client_secret`, **encrypted at rest**
//! (XChaCha20-Poly1305, key from `RUSTANGO_SECRET_KEY`) and decrypted in-memory
//! only at login time — so a leaked DB dump never exposes it, and each tenant
//! keeps its own secret without any per-tenant env var.

use crate::casts::{Cast, EncryptedString};
use crate::sql::Auto;

/// A single SSO/OpenID provider offered on the login page.
///
/// `slug` is the stable route key and button id (`{login}/sso/{slug}`);
/// `kind` selects a built-in preset or `"oidc"` for issuer discovery.
#[derive(crate::Model, Debug, Clone)]
#[rustango(
    table = "rustango_sso_providers",
    access = "admin_only",
    admin(
        list_display = "slug, label, kind, enabled, sort_order",
        ordering = "sort_order",
        readonly_fields = "created_at, updated_at",
        formfield_overrides = "client_secret: password, label: text, client_id: text, issuer_url: text, scopes: text, role_claims: text",
    )
)]
#[allow(dead_code)]
pub struct SsoProvider {
    #[rustango(primary_key)]
    pub id: Auto<i64>,

    /// Stable route key + button id — used in `{login_url}/sso/{slug}` and
    /// its callback. Unique within the table (per-tenant in tenancy mode,
    /// since the table is physically per-tenant).
    #[rustango(max_length = 64, unique)]
    #[rustango(
        help_text = "Short id in this provider's URLs, e.g. `google`: the IdP sends users back to `<login>/sso/<slug>/callback`. Unique; a new slug means a new callback URL at the IdP."
    )]
    #[rustango(verbose_name = "Slug")]
    pub slug: String,

    /// Button label, e.g. `"Sign in with Google"`.
    #[rustango(max_length = 150)]
    #[rustango(help_text = "Text on the sign-in button, e.g. `Sign in with Google`.")]
    #[rustango(verbose_name = "Button label")]
    pub label: String,

    /// Provider kind: a built-in preset key (`"google"`, `"microsoft"`,
    /// `"github"`, `"gitlab"`, `"discord"`) or `"oidc"` for a generic
    /// OpenID Connect provider configured via `issuer_url`.
    #[rustango(
        max_length = 32,
        choices = "google:Google, microsoft:Microsoft Entra ID, github:GitHub, gitlab:GitLab, discord:Discord, oidc:Generic OpenID Connect"
    )]
    #[rustango(
        help_text = "`google`, `microsoft`, `github`, `gitlab` or `discord` for a built-in provider, or `oidc` for any other OpenID Connect provider (then fill in the issuer URL)."
    )]
    #[rustango(verbose_name = "Provider kind")]
    pub kind: String,

    /// OIDC issuer base URL (e.g. a Keycloak realm or Okta domain), used
    /// with `kind = "oidc"` to auto-discover endpoints via
    /// `{issuer}/.well-known/openid-configuration`. Unused for presets.
    #[rustango(max_length = 255)]
    #[rustango(
        help_text = "Only for `oidc`: the issuer URL, e.g. `https://<org>.okta.com` or `https://<host>/realms/<realm>`. The endpoints are read from `<issuer>/.well-known/openid-configuration`; for Microsoft Entra ID use the `microsoft` kind."
    )]
    #[rustango(verbose_name = "Issuer URL")]
    pub issuer_url: Option<String>,

    /// OAuth2 client id issued by the IdP.
    #[rustango(max_length = 255)]
    #[rustango(
        help_text = "Client ID (application ID) from your identity provider's app registration."
    )]
    #[rustango(verbose_name = "Client ID")]
    pub client_id: String,

    /// The OAuth2 client secret, **encrypted at rest** (XChaCha20-Poly1305,
    /// key from `RUSTANGO_SECRET_KEY`). Each tenant stores its own here via the
    /// admin UI; decrypted in-memory only at login time to authenticate to the
    /// IdP's token endpoint. The single home for a provider's secret — no env
    /// var, no plaintext-in-DB.
    #[rustango(max_length = 1024)]
    #[rustango(
        help_text = "Client secret from the same app registration. Stored encrypted with `RUSTANGO_SECRET_KEY`."
    )]
    #[rustango(verbose_name = "Client secret")]
    pub client_secret: Cast<EncryptedString>,

    /// Offer this provider on the login page when `true`.
    #[rustango(default = "true")]
    #[rustango(help_text = "Show this provider's button on the sign-in page.")]
    #[rustango(verbose_name = "Enabled")]
    pub enabled: bool,

    /// Button ordering on the login page (ascending).
    #[rustango(default = "0")]
    #[rustango(help_text = "Button order on the sign-in page; lower numbers come first.")]
    #[rustango(verbose_name = "Sort order")]
    pub sort_order: i32,

    /// Optional space-separated OAuth scope override. When set, replaces the
    /// default `openid email profile` scopes for this provider.
    #[rustango(max_length = 255)]
    #[rustango(
        help_text = "OAuth scopes, space separated, e.g. `openid email profile`. Empty: the kind's default scopes."
    )]
    #[rustango(verbose_name = "Scopes")]
    pub scopes: Option<String>,

    /// Link a first-time SSO user to the account with the same verified
    /// email. Never links a superuser or staff account; the bare admin ignores it.
    /// Only a superuser can add or change provider rows in the admin.
    #[rustango(default = "false")]
    #[rustango(
        help_text = "Security: link a first-time sign-in to the existing account with the same verified email; that account's password stops working, its sessions end, its API keys are deleted and its agent keys are turned off. Never a superuser, and a user with any role or permission only with email linking for staff; the bare admin ignores it."
    )]
    #[rustango(verbose_name = "Allow email linking")]
    pub allow_email_link: bool,

    /// Only emails in these domains sign in: `client.org`, `*.client.org`
    /// (subdomains only), comma or newline separated. Empty: any domain.
    #[rustango(max_length = 2000)]
    #[rustango(
        help_text = "Security: only users whose verified email is in these domains may sign in. Comma or newline list: `client.org` is that domain only, `*.client.org` its subdomains only. Empty: any domain."
    )]
    #[rustango(verbose_name = "Allowed email domains")]
    pub allowed_email_domains: Option<String>,

    /// Emails in these domains never sign in; beats the allowed list.
    #[rustango(max_length = 2000)]
    #[rustango(
        help_text = "Users with an email in these domains never sign in, even if the allowed list has them. Same format as the allowed list."
    )]
    #[rustango(verbose_name = "Blocked email domains")]
    pub blocked_email_domains: Option<String>,

    /// Microsoft directory ids (`tid`) allowed to sign in. Needs a verified id_token.
    #[rustango(max_length = 1000)]
    #[rustango(
        help_text = "Microsoft Entra directory (tenant) IDs allowed to sign in, comma separated, read from a verified id_token. Empty: any Entra directory can sign in through a `microsoft` provider."
    )]
    #[rustango(verbose_name = "Allowed Microsoft directories")]
    pub allowed_idp_tenants: Option<String>,

    /// Google Workspace domains (`hd`) allowed to sign in.
    #[rustango(max_length = 1000)]
    #[rustango(
        help_text = "Google Workspace domains (the `hd` claim) allowed to sign in, comma separated, e.g. `client.org`."
    )]
    #[rustango(verbose_name = "Allowed Google Workspace domains")]
    pub allowed_hosted_domains: Option<String>,

    /// `{"claim": ["value", ...]}`: each claim must hold one of its values.
    /// `{"iss": [...]}` pins the issuer.
    #[rustango(default = "'{}'")]
    #[rustango(
        help_text = "JSON object of claims a sign-in must carry, each holding one of its values: `{\"roles\": [\"App.User\"]}`. `{}`: no claim is required."
    )]
    #[rustango(verbose_name = "Required claims")]
    pub required_claims: serde_json::Value,

    /// Who may sign up: `closed`, `invite_only`, `allowlist` or `open`.
    /// Empty: the sign-in surface's default.
    #[rustango(
        max_length = 16,
        choices = "closed:Closed, invite_only:Invite only, allowlist:Allowlist, open:Open"
    )]
    #[rustango(
        help_text = "Security: who gets a new account at first sign-in: `closed` (no one), `invite_only` (an invite for the email), `allowlist` (an invite for the email or its domain) or `open` (anyone the sign-in rules let in). Empty: the sign-in page's default."
    )]
    #[rustango(verbose_name = "Sign-up mode")]
    pub signup_mode: Option<String>,

    /// Roles granted to a user created through this provider.
    #[rustango(max_length = 1000)]
    #[rustango(
        help_text = "Tenant roles a new user gets, comma separated, e.g. `Viewer`. An invite with roles replaces them."
    )]
    #[rustango(verbose_name = "Default roles")]
    pub default_roles: Option<String>,

    /// `{"<IdP group or role>": "<tenant role>"}`.
    #[rustango(default = "'{}'")]
    #[rustango(
        help_text = "JSON object from an IdP group or app role to tenant roles: `{\"Admins\": \"Editor\"}` or `{\"Admins\": [\"Editor\", \"Viewer\"]}`."
    )]
    #[rustango(verbose_name = "Role map")]
    pub role_map: serde_json::Value,

    /// Claims [`Self::role_map`] reads. Empty: `groups,roles`.
    #[rustango(max_length = 255)]
    #[rustango(help_text = "Claims the role map reads, comma separated. Empty: `groups,roles`.")]
    #[rustango(verbose_name = "Role claims")]
    pub role_claims: Option<String>,

    /// Re-apply [`Self::role_map`] on every sign-in, not just the first.
    #[rustango(default = "false")]
    #[rustango(
        help_text = "Apply the role map at every sign-in, not only the first. Only roles named in the role map are added or removed."
    )]
    #[rustango(verbose_name = "Sync roles at every sign-in")]
    pub sync_roles_on_login: bool,

    /// Where a new user's username comes from.
    #[rustango(
        max_length = 24,
        default = "'email_local'",
        choices = "email_local:Email local part, email:Email, preferred_username:Preferred username"
    )]
    #[rustango(
        help_text = "Where a new user's username comes from: the email's local part, the whole email, or the IdP's `preferred_username` (falls back to the local part)."
    )]
    #[rustango(verbose_name = "Username from")]
    pub username_from: String,

    /// What a taken username does on sign-up.
    #[rustango(
        max_length = 16,
        default = "'suffix'",
        choices = "suffix:Add a suffix, refuse:Refuse"
    )]
    #[rustango(
        help_text = "What happens when that username is taken: add a short suffix, or refuse the sign-up."
    )]
    #[rustango(verbose_name = "When the username is taken")]
    pub username_clash: String,

    /// Refresh name and email from the IdP on every sign-in.
    #[rustango(default = "false")]
    #[rustango(
        help_text = "Update the user's name and email from the IdP at every sign-in. Never for a superuser."
    )]
    #[rustango(verbose_name = "Sync name and email")]
    pub sync_profile: bool,

    /// Email linking may also link role holders (never superusers).
    #[rustango(default = "false")]
    #[rustango(
        help_text = "Security: with email linking on, also link users who hold any role or permission. A superuser is never linked by email."
    )]
    #[rustango(verbose_name = "Allow email linking for staff")]
    pub allow_email_link_staff: bool,

    /// Users of this provider may not sign in with a password.
    #[rustango(default = "false")]
    #[rustango(
        help_text = "Users linked through this provider may not sign in with a password, even while the provider is off."
    )]
    #[rustango(verbose_name = "Sign-in only through SSO")]
    pub sso_only: bool,

    /// Deactivate users this provider created after this many idle days.
    #[rustango(
        help_text = "After this many days without use, `sso-deactivate-idle` turns off the users this provider signed up who cannot use a password: SSO only here, or password login off for the tenant. Empty: never."
    )]
    #[rustango(verbose_name = "Deactivate after idle days")]
    pub auto_deactivate_after_days: Option<i32>,

    /// Session lifetime after a sign-in through this provider.
    #[rustango(
        help_text = "Longest session, in seconds, after a sign-in through this provider. Empty: the normal session length."
    )]
    #[rustango(verbose_name = "Session length (seconds)")]
    pub session_ttl_secs: Option<i64>,

    /// Session lifetime for a superuser.
    #[rustango(
        help_text = "Longest session, in seconds, for a superuser who signs in through this provider. Empty: the normal session length."
    )]
    #[rustango(verbose_name = "Superuser session length (seconds)")]
    pub superuser_session_ttl_secs: Option<i64>,

    /// Set on INSERT via `DEFAULT NOW()`.
    #[rustango(auto_now_add)]
    #[rustango(verbose_name = "Created at")]
    #[rustango(help_text = "When the row was created. Set by the database.")]
    pub created_at: Auto<chrono::DateTime<chrono::Utc>>,

    /// Bumped to `NOW()` on every save.
    #[rustango(auto_now)]
    #[rustango(verbose_name = "Updated at")]
    #[rustango(help_text = "When the row last changed. Set on every save.")]
    pub updated_at: Auto<chrono::DateTime<chrono::Utc>>,
}

use super::link::{LinkSource, ProviderKey};
use super::{parse_scopes, ProviderButton, ResolvedSso, SsoError};
use crate::core::{Model, SqlValue};
use crate::query::QuerySet;
use crate::sql::{ExecError, Pool};

// The admin writes raw form values, so the secret is encrypted here, as
// `Cast<EncryptedString>` does for ORM writes (#1764).
#[cfg(feature = "admin")]
pub(crate) fn admin_encrypt_secret<'a>(
    values: &'a mut Vec<(&'static str, SqlValue)>,
    _before: Option<&'a serde_json::Value>,
) -> crate::admin::derived_fields::DeriveFuture<'a> {
    let out = match crate::admin::derived_fields::take_secret(values, "client_secret") {
        None => Ok(()),
        Some(plain) => crate::casts::encrypt(plain.as_bytes())
            .map(|c| values.push(("client_secret", SqlValue::String(c))))
            .map_err(|e| e.to_string()),
    };
    Box::pin(async move { out })
}

#[cfg(feature = "admin")]
inventory::submit! {
    crate::admin::derived_fields::AdminDerivedField {
        table: "rustango_sso_providers",
        derive: admin_encrypt_secret,
    }
}

/// Columns provider reads leave out. `allow_email_link` and the policy are
/// read on their own, so a table not yet migrated still serves logins.
const DEFERRED: &[&str] = &[
    "allow_email_link",
    "created_at",
    "updated_at",
    "allowed_email_domains",
    "blocked_email_domains",
    "allowed_idp_tenants",
    "allowed_hosted_domains",
    "required_claims",
    "signup_mode",
    "default_roles",
    "role_map",
    "role_claims",
    "sync_roles_on_login",
    "username_from",
    "username_clash",
    "sync_profile",
    "allow_email_link_staff",
    "sso_only",
    "auto_deactivate_after_days",
    "session_ttl_secs",
    "superuser_session_ttl_secs",
];

/// The password and session columns.
#[cfg(any(feature = "tenancy", feature = "admin"))]
const LIFECYCLE_COLUMNS: &[&str] = &[
    "sso_only",
    "auto_deactivate_after_days",
    "session_ttl_secs",
    "superuser_session_ttl_secs",
];

/// Every policy column, read in one go when a provider resolves.
const POLICY_COLUMNS: &[&str] = &[
    "allowed_email_domains",
    "blocked_email_domains",
    "allowed_idp_tenants",
    "allowed_hosted_domains",
    "required_claims",
    "signup_mode",
    "default_roles",
    "role_map",
    "role_claims",
    "sync_roles_on_login",
    "username_from",
    "username_clash",
    "sync_profile",
    "allow_email_link_staff",
    "sso_only",
    "auto_deactivate_after_days",
    "session_ttl_secs",
    "superuser_session_ttl_secs",
];

/// Which of some columns a table has, by the catalog.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Columns {
    /// None of them: added by a migration not run yet.
    None,
    /// Some, named here.
    Some(Vec<&'static str>),
    All,
}

/// Which of `cols` `table` has.
///
/// # Errors
/// The catalog cannot be read, or shows the table with no columns at all
/// (another schema, missing privileges): nothing can be told from it.
pub(crate) async fn columns_present(
    pool: &Pool,
    table: &str,
    cols: &[&'static str],
) -> Result<Columns, String> {
    let have = crate::migrate::ensure::live_columns(pool, table)
        .await
        .map_err(|e| format!("catalog: {e}"))?;
    if have.is_empty() {
        return Err(format!("the catalog shows no columns for {table}"));
    }
    let present: Vec<&'static str> = cols.iter().copied().filter(|c| have.contains(*c)).collect();
    Ok(match present.len() {
        0 => Columns::None,
        n if n == cols.len() => Columns::All,
        _ => Columns::Some(present),
    })
}

/// Row `id`'s `cols`. `None` when none of them exist yet: the defaults
/// apply (with a warning). Some but not all of them, an unreadable catalog,
/// or any other read error, is an error, and sign-in through the row refuses.
async fn read_columns<T: Model>(
    pool: &Pool,
    id: i64,
    cols: &'static [&'static str],
) -> Result<Option<std::collections::HashMap<String, SqlValue>>, super::policy::PolicyError> {
    use super::policy::PolicyError;
    let err = match QuerySet::<T>::new()
        .filter("id", id)
        .only(cols)
        .fetch(pool)
        .await
    {
        Ok(mut rows) => {
            if rows.is_empty() {
                return Err(PolicyError("the provider row vanished".into()));
            }
            let r = rows.swap_remove(0);
            // SQLite can answer for columns it lacks: let the catalog decide.
            if cols.iter().all(|c| r.contains_key(*c)) {
                return Ok(Some(r));
            }
            "the read returned no policy columns".to_owned()
        }
        Err(e) => e.to_string(),
    };
    let present = columns_present(pool, T::SCHEMA.table, cols).await;
    columns_after_read_error(present, T::SCHEMA.table, &err).map(|()| None)
}

/// Row `id`'s sign-in, sign-up and lifecycle rules, in one read; see [`read_columns`].
pub(crate) async fn read_rules<T: Model>(pool: &Pool, id: i64) -> Rules {
    use super::policy::{Lifecycle, SignInPolicy, SignupPolicy};
    match read_columns::<T>(pool, id, POLICY_COLUMNS).await {
        Ok(Some(r)) => (policy_of_row(&r), signup_of_row(&r), lifecycle_of_row(&r)),
        Ok(None) => (
            Ok(SignInPolicy::default()),
            Ok(SignupPolicy::default()),
            Ok(Lifecycle::default()),
        ),
        Err(e) => (Err(e.clone()), Err(e.clone()), Err(e)),
    }
}

/// What [`read_rules`] returns: each part refuses on its own error.
pub(crate) type Rules = (
    Result<super::policy::SignInPolicy, super::policy::PolicyError>,
    Result<super::policy::SignupPolicy, super::policy::PolicyError>,
    Result<super::policy::Lifecycle, super::policy::PolicyError>,
);

/// Row `id`'s password and session rules; see [`read_columns`].
#[cfg(any(feature = "tenancy", feature = "admin"))]
pub(crate) async fn read_lifecycle<T: Model>(
    pool: &Pool,
    id: i64,
) -> Result<super::policy::Lifecycle, super::policy::PolicyError> {
    match read_columns::<T>(pool, id, LIFECYCLE_COLUMNS).await? {
        Some(r) => lifecycle_of_row(&r),
        None => Ok(super::policy::Lifecycle::default()),
    }
}

/// The rules in one row read with every [`LIFECYCLE_COLUMNS`] column.
fn lifecycle_of_row(
    r: &std::collections::HashMap<String, SqlValue>,
) -> Result<super::policy::Lifecycle, super::policy::PolicyError> {
    use super::policy::{Lifecycle, PolicyError};
    let bad = |c: &str| PolicyError(format!("{c}: unexpected value {:?}", r.get(c)));
    let number = |c: &str| match r.get(c) {
        Some(SqlValue::Null) => Ok(None),
        Some(SqlValue::I64(n)) => Ok(Some(*n)),
        Some(SqlValue::I32(n)) => Ok(Some(i64::from(*n))),
        Some(SqlValue::I16(n)) => Ok(Some(i64::from(*n))),
        _ => Err(bad(c)),
    };
    Lifecycle::parse(
        flag(r, "sso_only").ok_or_else(|| bad("sso_only"))?,
        number("auto_deactivate_after_days")?,
        number("session_ttl_secs")?,
        number("superuser_session_ttl_secs")?,
    )
}

/// What a failed policy read means, by which policy columns exist: none is
/// a schema not yet migrated (`Ok`: the defaults); anything else refuses.
fn columns_after_read_error(
    present: Result<Columns, String>,
    table: &str,
    err: &str,
) -> Result<(), super::policy::PolicyError> {
    use super::policy::PolicyError;
    match present {
        Ok(Columns::None) => {
            tracing::warn!(
                target: "rustango::sso",
                table,
                "SSO policy columns missing; run `migrate`. Using the default policy: {err}"
            );
            Ok(())
        }
        // A missing column may hold a rule: refuse until migrated.
        Ok(Columns::Some(have)) => Err(PolicyError(format!(
            "only some policy columns exist ({}); run `migrate`",
            have.join(", ")
        ))),
        Ok(Columns::All) => Err(PolicyError(format!("read: {err}"))),
        Err(e) => Err(PolicyError(format!("read: {err}; {e}"))),
    }
}

/// A stored flag: a bool, or an integer on backends without one. NULL is no value.
fn flag(r: &std::collections::HashMap<String, SqlValue>, c: &str) -> Option<bool> {
    match r.get(c) {
        Some(SqlValue::Bool(b)) => Some(*b),
        Some(SqlValue::I64(n)) => Some(*n != 0),
        Some(SqlValue::I32(n)) => Some(*n != 0),
        Some(SqlValue::I16(n)) => Some(*n != 0),
        _ => None,
    }
}

/// A stored JSON column, as JSON or as its text.
fn json_of(
    r: &std::collections::HashMap<String, SqlValue>,
    c: &str,
) -> Result<serde_json::Value, super::policy::PolicyError> {
    use super::policy::PolicyError;
    match r.get(c) {
        Some(SqlValue::Json(v)) => Ok(v.clone()),
        Some(SqlValue::String(s)) => {
            serde_json::from_str(s).map_err(|e| PolicyError(format!("{c}: {e}")))
        }
        other => Err(PolicyError(format!("{c}: unexpected value {other:?}"))),
    }
}

/// The sign-up policy in one row read with every [`POLICY_COLUMNS`] column.
fn signup_of_row(
    r: &std::collections::HashMap<String, SqlValue>,
) -> Result<super::policy::SignupPolicy, super::policy::PolicyError> {
    use super::policy::{PolicyError, SignupColumns, SignupPolicy};
    let bad = |c: &str| PolicyError(format!("{c}: unexpected value {:?}", r.get(c)));
    let text = |c: &str| match r.get(c) {
        Some(SqlValue::Null) => Ok(None),
        Some(SqlValue::String(s)) => Ok(Some(s.as_str())),
        _ => Err(bad(c)),
    };
    let on = |c: &str| flag(r, c).ok_or_else(|| bad(c));
    let role_map = json_of(r, "role_map")?;
    SignupPolicy::parse(&SignupColumns {
        signup_mode: text("signup_mode")?,
        default_roles: text("default_roles")?,
        role_map: Some(&role_map),
        role_claims: text("role_claims")?,
        sync_roles_on_login: on("sync_roles_on_login")?,
        username_from: text("username_from")?,
        username_clash: text("username_clash")?,
        sync_profile: on("sync_profile")?,
        allow_email_link_staff: on("allow_email_link_staff")?,
    })
}

/// The sign-in policy in one row read with every [`POLICY_COLUMNS`] column.
fn policy_of_row(
    r: &std::collections::HashMap<String, SqlValue>,
) -> Result<super::policy::SignInPolicy, super::policy::PolicyError> {
    use super::policy::{PolicyError, SignInColumns, SignInPolicy};
    let bad = |c: &str, v: Option<&SqlValue>| PolicyError(format!("{c}: unexpected value {v:?}"));
    let list = |c: &str| match r.get(c) {
        Some(SqlValue::Null) => Ok(None),
        Some(SqlValue::String(s)) => Ok(Some(s.as_str())),
        other => Err(bad(c, other)),
    };
    let claims = json_of(r, "required_claims")?;
    SignInPolicy::parse(&SignInColumns {
        allowed_email_domains: list("allowed_email_domains")?,
        blocked_email_domains: list("blocked_email_domains")?,
        allowed_idp_tenants: list("allowed_idp_tenants")?,
        allowed_hosted_domains: list("allowed_hosted_domains")?,
        required_claims: Some(&claims),
    })
}

/// A provider row, shared by [`SsoProvider`] and `SharedSsoProvider`.
/// `client_secret` is still encrypted.
pub(crate) struct ProviderRow {
    pub id: i64,
    pub slug: String,
    pub label: String,
    pub kind: String,
    pub issuer_url: Option<String>,
    pub client_id: String,
    client_secret: String,
    pub enabled: bool,
    pub sort_order: i32,
    pub scopes: Option<String>,
}

pub(super) fn text(v: Option<&SqlValue>) -> Option<String> {
    match v {
        Some(SqlValue::String(s)) => Some(s.clone()),
        _ => None,
    }
}

pub(super) fn int(v: Option<&SqlValue>) -> i64 {
    match v {
        Some(SqlValue::I64(n)) => *n,
        Some(SqlValue::I32(n)) => i64::from(*n),
        Some(SqlValue::I16(n)) => i64::from(*n),
        Some(SqlValue::Bool(b)) => i64::from(*b),
        _ => 0,
    }
}

/// Provider rows matching `qs`, without the [`DEFERRED`] columns. A missing
/// table holds none, so a tenant without one falls through to the shared set (#2366).
pub(crate) async fn load_rows<T: Model>(
    qs: QuerySet<T>,
    pool: &Pool,
) -> Result<Vec<ProviderRow>, ExecError> {
    if !crate::migrate::try_table_exists_here(pool, T::SCHEMA.table).await? {
        return Ok(Vec::new());
    }
    let rows = qs.defer(DEFERRED).fetch(pool).await?;
    Ok(rows
        .iter()
        .map(|r| ProviderRow {
            id: int(r.get("id")),
            slug: text(r.get("slug")).unwrap_or_default(),
            label: text(r.get("label")).unwrap_or_default(),
            kind: text(r.get("kind")).unwrap_or_default(),
            issuer_url: text(r.get("issuer_url")),
            client_id: text(r.get("client_id")).unwrap_or_default(),
            client_secret: text(r.get("client_secret")).unwrap_or_default(),
            enabled: int(r.get("enabled")) != 0,
            sort_order: i32::try_from(int(r.get("sort_order"))).unwrap_or(0),
            scopes: text(r.get("scopes")),
        })
        .collect())
}

/// A resolved provider plus what the link step needs.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ResolvedProvider {
    pub sso: ResolvedSso,
    /// Provider row id.
    pub id: i64,
    /// The row's `allow_email_link`; `false` when it can't be read.
    pub allow_email_link: bool,
    /// The row's sign-in rules; an error refuses every sign-in.
    pub policy: Result<super::policy::SignInPolicy, super::policy::PolicyError>,
    /// The row's sign-up settings; an error refuses every sign-in.
    pub signup: Result<super::policy::SignupPolicy, super::policy::PolicyError>,
    /// The row's password and session rules; an error refuses every sign-in.
    pub lifecycle: Result<super::policy::Lifecycle, super::policy::PolicyError>,
}

impl ResolvedProvider {
    /// Link key for this provider as seen from `source`.
    #[must_use]
    pub fn key(&self, source: LinkSource) -> ProviderKey {
        ProviderKey::for_row(
            source,
            self.id,
            &self.sso.provider,
            self.sso.issuer_url.as_deref(),
        )
    }

    /// The policy a sign-in through this row runs under.
    #[must_use]
    pub fn effective_policy(&self) -> super::policy::EffectivePolicy {
        super::policy::EffectivePolicy::new(self.policy.clone(), self.allow_email_link)
            .with_signup(self.signup.clone())
            .with_lifecycle(self.lifecycle.clone())
    }
}

/// Resolve the enabled `T` row with this `slug`. `Ok(None)` when none matches.
pub(crate) async fn resolve_row<T: Model>(
    pool: &Pool,
    slug: &str,
    redirect_uri: String,
) -> Result<Option<ResolvedProvider>, SsoError> {
    Ok(match lookup_row::<T>(pool, slug, redirect_uri).await? {
        Lookup::Enabled(p) => Some(*p),
        _ => None,
    })
}

/// A provider slug looked up in one table.
#[cfg_attr(not(all(feature = "tenancy", feature = "admin-sso")), allow(dead_code))]
pub(crate) enum Lookup {
    Enabled(Box<ResolvedProvider>),
    /// Only a disabled row has the slug.
    Disabled,
    Missing,
}

/// [`resolve_row`], also telling a disabled row from none.
pub(crate) async fn lookup_row<T: Model>(
    pool: &Pool,
    slug: &str,
    redirect_uri: String,
) -> Result<Lookup, SsoError> {
    use crate::casts::CastValue as _;
    let rows = load_rows(QuerySet::<T>::new().filter("slug", slug.to_owned()), pool)
        .await
        .map_err(|e| SsoError::Config(format!("db: {e}")))?;
    let disabled = rows.iter().any(|r| r.slug == slug);
    let Some(r) = rows.into_iter().find(|r| r.enabled) else {
        return Ok(if disabled {
            Lookup::Disabled
        } else {
            Lookup::Missing
        });
    };
    let client_secret =
        EncryptedString::from_db(&r.client_secret).map_err(|e| SsoError::Secret(e.to_string()))?;
    let allow_email_link = match QuerySet::<T>::new()
        .filter("id", r.id)
        .values_list_flat("allow_email_link")
        .fetch::<bool>(pool)
        .await
    {
        Ok(v) => v.first().copied().unwrap_or(false),
        Err(e) => {
            tracing::warn!(target: "rustango::sso", "allow_email_link unreadable, treated as off: {e}");
            false
        }
    };
    let (policy, signup, lifecycle) = read_rules::<T>(pool, r.id).await;
    Ok(Lookup::Enabled(Box::new(ResolvedProvider {
        policy,
        signup,
        lifecycle,
        sso: ResolvedSso {
            provider: r.kind,
            issuer_url: r.issuer_url,
            client_id: r.client_id,
            client_secret,
            redirect_uri,
            scopes: parse_scopes(r.scopes.as_deref()),
        },
        id: r.id,
        allow_email_link,
    })))
}

/// Enabled providers for the bare admin login page, sorted by `sort_order`.
/// `login_base` is the login path (e.g. `/admin/login`); each button links
/// to `{login_base}/sso/{slug}`. A DB error yields an empty list (the login
/// page still renders the password form).
pub async fn list_enabled(pool: &Pool, login_base: &str) -> Vec<ProviderButton> {
    let mut rows = load_rows(QuerySet::<SsoProvider>::new(), pool)
        .await
        .unwrap_or_default();
    rows.retain(|r| r.enabled);
    rows.sort_by_key(|r| r.sort_order);
    rows.into_iter()
        .map(|r| ProviderButton {
            login_url: format!("{login_base}/sso/{}", r.slug),
            slug: r.slug,
            label: r.label,
        })
        .collect()
}

/// Resolve one enabled [`SsoProvider`] by `slug`. `Ok(None)` when no enabled
/// row matches.
///
/// # Errors
/// [`SsoError::Config`] on a DB error, [`SsoError::Secret`] when the
/// stored secret can't be decrypted.
pub async fn resolve_by_slug(
    pool: &Pool,
    slug: &str,
    redirect_uri: String,
) -> Result<Option<ResolvedProvider>, SsoError> {
    resolve_row::<SsoProvider>(pool, slug, redirect_uri).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    /// Only a schema with none of the policy columns falls back to no rules.
    #[test]
    fn a_read_error_falls_back_only_when_no_policy_column_exists() {
        let t = "rustango_sso_providers";
        assert_eq!(columns_after_read_error(Ok(Columns::None), t, "e"), Ok(()));
        for refused in [
            Ok(Columns::Some(vec!["allowed_email_domains"])),
            Ok(Columns::All),
            Err("the catalog shows no columns".to_owned()),
        ] {
            assert!(columns_after_read_error(refused, t, "e").is_err());
        }
    }

    fn row(over: &[(&str, SqlValue)]) -> HashMap<String, SqlValue> {
        let mut r: HashMap<String, SqlValue> = [
            (
                "allowed_email_domains",
                SqlValue::String("client.org".into()),
            ),
            ("blocked_email_domains", SqlValue::Null),
            ("allowed_idp_tenants", SqlValue::Null),
            ("allowed_hosted_domains", SqlValue::Null),
            ("required_claims", SqlValue::String("{}".into())),
        ]
        .into_iter()
        .map(|(k, v)| (k.to_owned(), v))
        .collect();
        for (k, v) in over {
            r.insert((*k).to_owned(), v.clone());
        }
        r
    }

    /// A value of the wrong type refuses rather than reading as "no rule".
    #[test]
    fn an_unexpected_value_refuses() {
        let p = policy_of_row(&row(&[])).unwrap();
        assert!(p.allowed_email_domains.is_some());
        for bad in [
            ("allowed_email_domains", SqlValue::I64(5)),
            ("blocked_email_domains", SqlValue::Bool(true)),
            ("required_claims", SqlValue::Null),
        ] {
            assert!(policy_of_row(&row(&[bad.clone()])).is_err(), "{bad:?}");
        }
        let mut gone = row(&[]);
        gone.remove("allowed_idp_tenants");
        assert!(policy_of_row(&gone).is_err(), "a column the read lacks");
    }

    /// A table the catalog cannot see tells nothing: an error, not "no columns".
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn an_empty_catalog_is_an_error() {
        let pool = Pool::connect("sqlite::memory:").await.unwrap();
        assert!(
            columns_present(&pool, "rustango_sso_providers", POLICY_COLUMNS)
                .await
                .is_err()
        );
    }
}