gunnar-core 1.5.0

gunnar's repository model, identity table, ACL and path sandbox. gunnar-ssh, gunnar-grpc and gunnar-cli all sit on it.
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
877
878
879
880
881
882
//! **Company SSO in the identity table** — the writers of the rows
//! [`crate::sso`] describes. Every one is a single compare-and-swap on
//! `refs/gunnar/auth`, so a first login's NEW employee and the subject it is
//! bound to, or a deactivation's gate and the sessions it ends, are never seen
//! half-written.

use super::{AuthDoc, AuthTable, RoomAsk, SeatLot};
use crate::error::{Error, Result};
use crate::gate::{AccountGate, GateReason};
use crate::model::{Principal, PublicKey, UnixMillis};
use crate::sso::{ScimToken, SsoGroup, SsoProvider, SsoSource, SsoUser};

/// What one SSO login asks of the table.
#[derive(Clone, Debug)]
pub struct SsoLogin {
    /// The account whose identity provider verified the person.
    pub account: String,
    /// [`crate::sso::subject_key`] of the verified IdP subject.
    pub subject: String,
    /// The directory user name the IdP named (normalized), for a first
    /// login: a provisioned user of that name is claimed, or a NEW employee
    /// is created under it.
    pub user_name: String,
    /// The person's name, as the IdP says it.
    pub display_name: String,
    /// The person's address, as the IdP says it.
    pub email: String,
    /// The ids a NEW employee may take, in order, already filtered against
    /// the namespaces (which the table does not hold). The first one that is
    /// no principal and no name is taken.
    pub candidates: Vec<Principal>,
    /// The room a NEW employee holds: an open seat when the account has one,
    /// else `room.room_bytes` out of its unused room.
    pub room: RoomAsk,
    /// The web session key to enrol (one OpenSSH line) and when it expires;
    /// `None` when a second factor must come first.
    pub session: Option<(String, UnixMillis)>,
    /// The caller's clock.
    pub now: UnixMillis,
}

/// What a committed SSO login answers.
#[derive(Clone, Debug)]
pub struct SsoLoginDone {
    /// The employee who logged in.
    pub principal: Principal,
    /// Its directory row, as written.
    pub user: SsoUser,
    /// This login created the employee (just in time).
    pub created: bool,
    /// This login bound a provisioned user (SCIM/CSV) to its subject.
    pub claimed: bool,
    /// The session key enrolled, when one was asked.
    pub session: Option<PublicKey>,
}

/// A NEW provisioned employee (SCIM create, a CSV row).
#[derive(Clone, Debug)]
pub struct SsoProvision {
    /// The account the employee is provisioned into.
    pub account: String,
    /// The directory user name (normalized, unique within the account).
    pub user_name: String,
    /// The person's name.
    pub display_name: String,
    /// The person's address.
    pub email: String,
    /// The directory's own id for the person (SCIM `externalId`).
    pub external_id: String,
    /// False: provisioned deactivated.
    pub active: bool,
    /// SCIM or CSV.
    pub source: SsoSource,
    /// The ids the NEW employee may take, in order (see [`SsoLogin::candidates`]).
    pub candidates: Vec<Principal>,
    /// The room it holds (see [`SsoLogin::room`]).
    pub room: RoomAsk,
    /// Who provisioned it (the bearer's account admin, or the importer).
    pub actor: String,
    /// The caller's clock.
    pub now: UnixMillis,
}

/// A change to a directory user; `None` leaves a field as it is.
#[derive(Clone, Debug, Default)]
pub struct SsoUserPatch {
    /// A new directory user name.
    pub user_name: Option<String>,
    /// A new name.
    pub display_name: Option<String>,
    /// A new address.
    pub email: Option<String>,
    /// A new external id.
    pub external_id: Option<String>,
    /// Deactivate (false) or reactivate (true).
    pub active: Option<bool>,
}

fn subject_index(account: &str, subject: &str) -> String {
    format!("s\u{1f}{account}\u{1f}{subject}")
}

fn user_index(account: &str, user_name: &str) -> String {
    format!("u\u{1f}{account}\u{1f}{user_name}")
}

fn refused(reason: impl Into<String>) -> Error {
    Error::SsoRefused(reason.into())
}

impl AuthTable {
    /// Does this `sso_index` key belong to `account`?
    pub(super) fn sso_index_of_account(key: &str, account: &str) -> bool {
        let mut parts = key.splitn(3, '\u{1f}');
        let _kind = parts.next();
        parts.next() == Some(account)
    }

    // ── providers ─────────────────────────────────────────────────────────

    /// An account's identity provider, if it has one.
    pub fn sso_provider(&self, account: &str) -> Result<Option<SsoProvider>> {
        self.doc.load()?.sso_providers.get(account)
    }

    /// Every account's identity provider. A listing.
    pub fn sso_providers(&self) -> Result<Vec<SsoProvider>> {
        self.doc.load()?.sso_providers.values()
    }

    /// The account an email domain leads to.
    pub fn sso_account_for_domain(&self, domain: &str) -> Result<Option<String>> {
        self.doc.load()?.sso_domains.get(domain)
    }

    /// **Configure an account's identity provider** (replacing the one it
    /// had). The account must be a principal; its domains must be free or
    /// already its own — one domain, one company.
    pub fn set_sso_provider(&self, provider: SsoProvider) -> Result<SsoProvider> {
        self.doc.update(|doc| {
            if !doc.principals.contains_key(&provider.account)? {
                return Err(Error::NoSuchPrincipal(provider.account.clone()));
            }
            if doc.employers.contains_key(&provider.account)? {
                return Err(Error::InvalidInput {
                    what: "identity provider",
                    reason: format!(
                        "{} is an employee, not an account: only an account has an identity provider",
                        provider.account
                    ),
                });
            }
            for domain in &provider.domains {
                if let Some(holder) = doc.sso_domains.get(domain)? {
                    if holder != provider.account {
                        return Err(Error::InvalidInput {
                            what: "identity provider",
                            reason: format!("the domain {domain} already leads to another account's sign-in"),
                        });
                    }
                }
            }
            if let Some(old) = doc.sso_providers.get(&provider.account)? {
                for domain in old.domains {
                    doc.sso_domains.remove(&domain)?;
                }
            }
            for domain in &provider.domains {
                doc.sso_domains.insert(domain.clone(), provider.account.clone())?;
            }
            doc.sso_providers.insert(provider.account.clone(), provider.clone())?;
            Ok(provider.clone())
        })
    }

    /// Remove an account's identity provider. Its directory stays: its
    /// employees are still employees (and a re-configured IdP finds them).
    pub fn remove_sso_provider(&self, account: &str) -> Result<Option<SsoProvider>> {
        self.doc.update(|doc| {
            let removed = doc.sso_providers.remove(account)?;
            if let Some(provider) = &removed {
                for domain in &provider.domains {
                    doc.sso_domains.remove(domain)?;
                }
            }
            Ok(removed)
        })
    }

    // ── the directory ─────────────────────────────────────────────────────

    /// One directory user, by principal id.
    pub fn sso_user(&self, principal_id: &str) -> Result<Option<SsoUser>> {
        self.doc.load()?.sso_users.get(principal_id)
    }

    /// An account's directory (deleted users included; the caller filters).
    pub fn sso_users_of(&self, account: &str) -> Result<Vec<SsoUser>> {
        let mut rows: Vec<SsoUser> = self
            .doc
            .load()?
            .sso_users
            .values()?
            .into_iter()
            .filter(|u| u.account == account)
            .collect();
        rows.sort_by(|a, b| {
            a.user_name
                .cmp(&b.user_name)
                .then_with(|| a.principal_id.cmp(&b.principal_id))
        });
        Ok(rows)
    }

    /// The principal a subject is bound to in `account`, if any.
    pub fn sso_principal_for_subject(
        &self,
        account: &str,
        subject: &str,
    ) -> Result<Option<String>> {
        self.doc
            .load()?
            .sso_index
            .get(&subject_index(account, subject))
    }

    /// The first free candidate id: no principal of that id, no principal
    /// named so.
    fn free_candidate(doc: &AuthDoc, candidates: &[Principal]) -> Result<Option<Principal>> {
        for candidate in candidates {
            if doc.principals.contains_key(&candidate.id)? {
                continue;
            }
            if Self::refuse_taken_name(doc, &candidate.name, &candidate.id).is_err() {
                continue;
            }
            if Self::resolve_name(doc, &candidate.id)?.is_some() {
                continue;
            }
            return Ok(Some(candidate.clone()));
        }
        Ok(None)
    }

    /// **A NEW employee for the directory**, inside the caller's update: the
    /// room planned (an open seat first), the employee written by the one
    /// writer ([`AuthTable::write_employee`]), its directory row and index.
    fn create_directory_employee(
        doc: &mut AuthDoc,
        account: &str,
        candidates: &[Principal],
        room: &RoomAsk,
        user: SsoUser,
    ) -> Result<(Principal, SsoUser)> {
        let principal = Self::free_candidate(doc, candidates)?.ok_or_else(|| {
            refused(format!(
                "no free id for {:?} in {account}: every candidate is taken",
                user.user_name
            ))
        })?;
        let principal = Principal {
            created: user.created,
            ..principal
        };
        let lots: Vec<SeatLot> = doc.seats.get(account)?.unwrap_or_default();
        let ask = RoomAsk {
            from_seat: lots.iter().any(|lot| lot.open() > 0),
            seats: 0,
            dry_run: false,
            order: String::new(),
            ..room.clone()
        };
        let plan = Self::plan_room(doc, account, Some(&principal), &ask)?;
        if plan.answer.shortfall_bytes > 0 {
            return Err(Error::RoomShort {
                account: account.to_owned(),
                need: plan.answer.need_bytes,
                unused: plan.answer.unused_bytes.unwrap_or(0),
                short: plan.answer.shortfall_bytes,
            });
        }
        let mut seats = lots;
        Self::write_employee(
            doc,
            account,
            &principal,
            plan.lot,
            "",
            plan.answer.room_bytes,
            &mut seats,
        )?;
        if !seats.is_empty() {
            doc.seats.insert(account.to_owned(), seats)?;
        }
        let user = SsoUser {
            principal_id: principal.id.clone(),
            ..user
        };
        doc.sso_index
            .insert(user_index(account, &user.user_name), principal.id.clone())?;
        if let Some(subject) = &user.subject {
            doc.sso_index
                .insert(subject_index(account, subject), principal.id.clone())?;
        }
        doc.sso_users.insert(principal.id.clone(), user.clone())?;
        Ok((principal, user))
    }

    /// **Commit one verified SSO login.** In one update:
    ///
    /// 1. the subject is looked up in THIS account's index; a bound user must
    ///    be an employee of the account and active;
    /// 2. else a provisioned user (SCIM/CSV) of the IdP's user name that no
    ///    subject has claimed yet is bound to this subject (a user name
    ///    another subject already holds is refused — never re-pointed);
    /// 3. else a NEW employee is created (never an existing principal
    ///    attached), bound, with room;
    ///
    /// and the session key, when asked, is enrolled on the employee.
    pub fn sso_login(&self, login: &SsoLogin) -> Result<SsoLoginDone> {
        let session_key = match &login.session {
            Some((openssh, expires)) => {
                let parsed = super::parse_public_key(openssh)?;
                let fingerprint = super::Fingerprint::of_key(&parsed);
                Some(PublicKey {
                    fingerprint_sha256: fingerprint.as_str().to_owned(),
                    algo: parsed.algorithm().as_str().to_owned(),
                    principal_id: String::new(),
                    added: login.now,
                    last_used: None,
                    expires: Some(*expires),
                    openssh: parsed.to_openssh().map_err(Error::from)?.trim().to_owned(),
                })
            }
            None => None,
        };
        let account = login.account.as_str();
        self.doc.update(|doc| {
            if !doc.sso_providers.contains_key(account)? {
                return Err(refused(format!("{account} has no identity provider")));
            }
            let mut created = false;
            let mut claimed = false;
            let bound = doc.sso_index.get(&subject_index(account, &login.subject))?;
            let (principal, mut user) = match bound {
                Some(id) => {
                    let user = doc
                        .sso_users
                        .get(&id)?
                        .filter(|u| u.account == account)
                        .ok_or_else(|| refused(format!("the subject is bound to {id}, which is not in {account}'s directory")))?;
                    let principal = doc.principals.get(&id)?.ok_or_else(|| Error::NoSuchPrincipal(id.clone()))?;
                    (principal, user)
                }
                None => match doc.sso_index.get(&user_index(account, &login.user_name))? {
                    Some(id) => {
                        let mut user = doc
                            .sso_users
                            .get(&id)?
                            .filter(|u| u.account == account && !u.deleted)
                            .ok_or_else(|| refused(format!("{:?} is not in {account}'s directory", login.user_name)))?;
                        if user.subject.is_some() {
                            return Err(refused(format!(
                                "the directory user {:?} is already bound to another identity at the IdP; \
                                 it is never re-pointed — the account admin removes it first",
                                login.user_name
                            )));
                        }
                        if user.source == SsoSource::Jit {
                            return Err(refused(format!("{:?} was created by another login", login.user_name)));
                        }
                        user.subject = Some(login.subject.clone());
                        doc.sso_index.insert(subject_index(account, &login.subject), id.clone())?;
                        claimed = true;
                        let principal = doc.principals.get(&id)?.ok_or_else(|| Error::NoSuchPrincipal(id.clone()))?;
                        (principal, user)
                    }
                    None => {
                        let user = SsoUser {
                            principal_id: String::new(),
                            account: account.to_owned(),
                            user_name: login.user_name.clone(),
                            display_name: login.display_name.clone(),
                            email: login.email.clone(),
                            external_id: String::new(),
                            subject: Some(login.subject.clone()),
                            active: true,
                            source: SsoSource::Jit,
                            created: login.now,
                            last_login: None,
                            sessions: Vec::new(),
                            deleted: false,
                        };
                        created = true;
                        Self::create_directory_employee(doc, account, &login.candidates, &login.room, user)?
                    }
                },
            };
            // Never across accounts, and only an employee: the index is the
            // account's own, and this is the second lock on the same door.
            if doc.employers.get(&principal.id)?.as_deref() != Some(account) {
                return Err(refused(format!("{} is not an employee of {account}", principal.id)));
            }
            if !user.active || user.deleted {
                return Err(refused(format!(
                    "{} is deactivated in {account}'s directory",
                    principal.id
                )));
            }
            if Self::gated(doc, &principal.id)? {
                return Err(refused(format!("{} is locked out", principal.id)));
            }
            if !created {
                if !login.display_name.is_empty() {
                    user.display_name = login.display_name.clone();
                }
                if !login.email.is_empty() {
                    user.email = login.email.clone();
                }
            }
            user.last_login = Some(login.now);
            let mut enrolled = None;
            if let Some(key) = &session_key {
                if let Some(existing) = doc.keys.get(&key.fingerprint_sha256)? {
                    return Err(Error::KeyExists {
                        fingerprint: key.fingerprint_sha256.clone(),
                        principal_id: existing.principal_id,
                    });
                }
                let key = PublicKey { principal_id: principal.id.clone(), ..key.clone() };
                let mut live = Vec::with_capacity(user.sessions.len() + 1);
                for held in std::mem::take(&mut user.sessions) {
                    if doc.keys.get(&held)?.is_some_and(|k| k.is_valid_at(login.now)) {
                        live.push(held);
                    }
                }
                live.push(key.fingerprint_sha256.clone());
                user.sessions = live;
                doc.keys.insert(key.fingerprint_sha256.clone(), key.clone())?;
                enrolled = Some(key);
            }
            doc.sso_users.insert(principal.id.clone(), user.clone())?;
            Ok(SsoLoginDone { principal, user, created, claimed, session: enrolled })
        })
    }

    /// **Provision a NEW employee** from the company's directory (SCIM
    /// create, a CSV row): unbound until its first login claims it. A user
    /// name the account's directory already holds is refused
    /// ([`Error::NameExists`]): SCIM's `uniqueness`.
    pub fn sso_provision(&self, provision: &SsoProvision) -> Result<SsoUser> {
        let account = provision.account.as_str();
        self.doc.update(|doc| {
            if !doc.principals.contains_key(account)? {
                return Err(Error::NoSuchPrincipal(account.to_owned()));
            }
            if let Some(held) = doc
                .sso_index
                .get(&user_index(account, &provision.user_name))?
            {
                return Err(Error::NameExists {
                    name: provision.user_name.clone(),
                    principal_id: held,
                });
            }
            let user = SsoUser {
                principal_id: String::new(),
                account: account.to_owned(),
                user_name: provision.user_name.clone(),
                display_name: provision.display_name.clone(),
                email: provision.email.clone(),
                external_id: provision.external_id.clone(),
                subject: None,
                active: true,
                source: provision.source,
                created: provision.now,
                last_login: None,
                sessions: Vec::new(),
                deleted: false,
            };
            let (_, mut user) = Self::create_directory_employee(
                doc,
                account,
                &provision.candidates,
                &provision.room,
                user,
            )?;
            if !provision.active {
                Self::deactivate(doc, &mut user, &provision.actor, provision.now)?;
                doc.sso_users
                    .insert(user.principal_id.clone(), user.clone())?;
            }
            Ok(user)
        })
    }

    /// **Change a directory user**: its names and, with `active`, whether it
    /// may log in — a deactivation gates the employee (holder
    /// [`crate::sso::gate_holder`]) and revokes its web sessions in the same
    /// update; a reactivation lifts that gate only (an operator's suspension
    /// stays). Returns the row as it stands and whether `active` changed.
    pub fn sso_user_update(
        &self,
        account: &str,
        principal_id: &str,
        patch: &SsoUserPatch,
        actor: &str,
        now: UnixMillis,
    ) -> Result<(SsoUser, bool)> {
        self.doc.update(|doc| {
            let mut user = doc
                .sso_users
                .get(principal_id)?
                .filter(|u| u.account == account && !u.deleted)
                .ok_or_else(|| Error::NoSuchPrincipal(principal_id.to_owned()))?;
            if let Some(name) = &patch.user_name {
                if *name != user.user_name {
                    if let Some(held) = doc.sso_index.get(&user_index(account, name))? {
                        if held != user.principal_id {
                            return Err(Error::NameExists {
                                name: name.clone(),
                                principal_id: held,
                            });
                        }
                    }
                    doc.sso_index
                        .remove(&user_index(account, &user.user_name))?;
                    doc.sso_index
                        .insert(user_index(account, name), user.principal_id.clone())?;
                    user.user_name = name.clone();
                }
            }
            if let Some(v) = &patch.display_name {
                user.display_name = v.clone();
            }
            if let Some(v) = &patch.email {
                user.email = v.clone();
            }
            if let Some(v) = &patch.external_id {
                user.external_id = v.clone();
            }
            let mut changed = false;
            match patch.active {
                Some(false) if user.active => {
                    Self::deactivate(doc, &mut user, actor, now)?;
                    changed = true;
                }
                Some(true) if !user.active => {
                    user.active = true;
                    let holder = crate::sso::gate_holder(account);
                    if doc
                        .gates
                        .get(&user.principal_id)?
                        .is_some_and(|g| g.holder == holder)
                    {
                        doc.gates.remove(&user.principal_id)?;
                    }
                    changed = true;
                }
                _ => {}
            }
            doc.sso_users
                .insert(user.principal_id.clone(), user.clone())?;
            Ok((user, changed))
        })
    }

    /// **Remove a user from the directory** (SCIM DELETE): deactivated —
    /// gated, sessions revoked — and no longer listed or claimable. The
    /// employee and everything it pushed stay; its user name is free for a
    /// NEW person, never for this one again.
    pub fn sso_user_delete(
        &self,
        account: &str,
        principal_id: &str,
        actor: &str,
        now: UnixMillis,
    ) -> Result<SsoUser> {
        self.doc.update(|doc| {
            let mut user = doc
                .sso_users
                .get(principal_id)?
                .filter(|u| u.account == account && !u.deleted)
                .ok_or_else(|| Error::NoSuchPrincipal(principal_id.to_owned()))?;
            if user.active {
                Self::deactivate(doc, &mut user, actor, now)?;
            }
            user.deleted = true;
            doc.sso_index
                .remove(&user_index(account, &user.user_name))?;
            for (gid, mut group) in doc.sso_groups.entries()? {
                if group.account == account && group.members.contains(&user.principal_id) {
                    group.members.retain(|m| *m != user.principal_id);
                    doc.sso_groups.insert(gid, group)?;
                }
            }
            doc.sso_users
                .insert(user.principal_id.clone(), user.clone())?;
            Ok(user)
        })
    }

    /// Inside an update: `active = false`, every web session key of the
    /// person revoked (SSO's and its passkeys'), and the directory's gate —
    /// unless another holder's gate is already in force, which stays.
    fn deactivate(
        doc: &mut AuthDoc,
        user: &mut SsoUser,
        actor: &str,
        now: UnixMillis,
    ) -> Result<()> {
        user.active = false;
        let id = user.principal_id.clone();
        let mut ended: Vec<String> = std::mem::take(&mut user.sessions);
        for (cid, mut credential) in doc.credentials.entries()? {
            if credential.principal_id == id && !credential.sessions.is_empty() {
                ended.append(&mut credential.sessions);
                doc.credentials.insert(cid, credential)?;
            }
        }
        for fingerprint in ended {
            if doc
                .keys
                .get(&fingerprint)?
                .is_some_and(|k| k.principal_id == id)
            {
                doc.keys.remove(&fingerprint)?;
            }
        }
        let holder = crate::sso::gate_holder(&user.account);
        let held_by_another = doc
            .gates
            .get(&id)?
            .is_some_and(|g| g.holder != holder && g.is_live_at(now));
        if !held_by_another {
            doc.gates.insert(
                id.clone(),
                AccountGate {
                    account: id.clone(),
                    reason: GateReason::Administrative,
                    holder,
                    actor: actor.to_owned(),
                    note: format!("deactivated in {}'s directory", user.account),
                    at: now,
                    expires: None,
                },
            )?;
        }
        Ok(())
    }

    // ── SCIM bearers ──────────────────────────────────────────────────────

    /// Store a new SCIM bearer (its hash).
    pub fn create_scim_token(&self, token: ScimToken) -> Result<ScimToken> {
        self.doc.update(|doc| {
            if !doc.principals.contains_key(&token.account)? {
                return Err(Error::NoSuchPrincipal(token.account.clone()));
            }
            if doc.scim_tokens.contains_key(&token.secret_hash)? {
                return Err(Error::TokenExists {
                    hash: token.secret_hash.clone(),
                    principal_id: token.account.clone(),
                });
            }
            doc.scim_tokens
                .insert(token.secret_hash.clone(), token.clone())?;
            Ok(token.clone())
        })
    }

    /// The bearer a secret's hash names, if any. One probe.
    pub fn scim_token_by_hash(&self, hash: &str) -> Result<Option<ScimToken>> {
        self.doc.load()?.scim_tokens.get(hash)
    }

    /// An account's SCIM bearers.
    pub fn scim_tokens_of(&self, account: &str) -> Result<Vec<ScimToken>> {
        let mut rows: Vec<ScimToken> = self
            .doc
            .load()?
            .scim_tokens
            .values()?
            .into_iter()
            .filter(|t| t.account == account)
            .collect();
        rows.sort_by(|a, b| (a.created, &a.id).cmp(&(b.created, &b.id)));
        Ok(rows)
    }

    /// Revoke one of an account's bearers by its public id.
    pub fn revoke_scim_token(&self, account: &str, id: &str) -> Result<Option<ScimToken>> {
        self.doc.update(|doc| {
            let hit = doc
                .scim_tokens
                .values()?
                .into_iter()
                .find(|t| t.account == account && t.id == id);
            match hit {
                Some(token) => doc.scim_tokens.remove(&token.secret_hash),
                None => Ok(None),
            }
        })
    }

    /// Note a bearer's use, at most once a minute.
    pub fn touch_scim_token(&self, hash: &str, now: UnixMillis) -> Result<()> {
        let stale = self.doc.load()?.scim_tokens.get(hash)?.is_some_and(|t| {
            t.last_used
                .is_none_or(|at| now - at >= super::LAST_USED_GRANULARITY)
        });
        if !stale {
            return Ok(());
        }
        self.doc.update(|doc| {
            doc.scim_tokens.modify(hash, |t| t.last_used = Some(now))?;
            Ok(())
        })
    }

    // ── SCIM groups ───────────────────────────────────────────────────────

    /// An account's groups.
    pub fn sso_groups_of(&self, account: &str) -> Result<Vec<SsoGroup>> {
        let mut rows: Vec<SsoGroup> = self
            .doc
            .load()?
            .sso_groups
            .values()?
            .into_iter()
            .filter(|g| g.account == account)
            .collect();
        rows.sort_by(|a, b| {
            a.display_name
                .cmp(&b.display_name)
                .then_with(|| a.id.cmp(&b.id))
        });
        Ok(rows)
    }

    /// Write a group (create or replace). Members must be the account's own
    /// directory users; a display name is unique within the account.
    pub fn put_sso_group(&self, group: SsoGroup) -> Result<SsoGroup> {
        self.doc.update(|doc| {
            for member in &group.members {
                let ok = doc
                    .sso_users
                    .get(member)?
                    .is_some_and(|u| u.account == group.account && !u.deleted);
                if !ok {
                    return Err(Error::InvalidInput {
                        what: "group",
                        reason: format!("{member} is not a user of {}'s directory", group.account),
                    });
                }
            }
            for other in doc.sso_groups.values()? {
                if other.account == group.account
                    && other.id != group.id
                    && other.display_name.eq_ignore_ascii_case(&group.display_name)
                {
                    return Err(Error::NameExists {
                        name: group.display_name.clone(),
                        principal_id: other.id,
                    });
                }
            }
            if let Some(old) = doc.sso_groups.get(&group.id)? {
                if old.account != group.account {
                    return Err(Error::InvalidInput {
                        what: "group",
                        reason: "the group is another account's".to_owned(),
                    });
                }
            }
            doc.sso_groups.insert(group.id.clone(), group.clone())?;
            Ok(group.clone())
        })
    }

    /// Remove one of an account's groups.
    pub fn remove_sso_group(&self, account: &str, id: &str) -> Result<Option<SsoGroup>> {
        self.doc.update(|doc| match doc.sso_groups.get(id)? {
            Some(group) if group.account == account => doc.sso_groups.remove(id),
            _ => Ok(None),
        })
    }

    /// A pruned copy of the live web sessions of a directory user (for a
    /// listing): the ones still held and unexpired.
    pub fn sso_live_sessions(&self, principal_id: &str, now: UnixMillis) -> Result<usize> {
        let doc = self.doc.load()?;
        let Some(user) = doc.sso_users.get(principal_id)? else {
            return Ok(0);
        };
        let mut n = 0;
        for fp in &user.sessions {
            if doc.keys.get(fp)?.is_some_and(|k| k.is_valid_at(now)) {
                n += 1;
            }
        }
        Ok(n)
    }
}

#[cfg(test)]
mod older_reader_tests {
    use std::collections::BTreeSet;
    use std::sync::Arc;

    use super::super::{AuthTable, AUTH_REF};
    use crate::control::ControlStore;
    use crate::model::{Principal, PrincipalKind};
    use crate::sso::{OidcSettings, SsoProtocol, SsoProvider};

    /// The identity table's keys a gunnar from BEFORE company SSO and clans
    /// knows (test2's line, feat/test2-next-2026-10-05) — its `AuthDoc` is
    /// `deny_unknown_fields`, so a key outside this list is a table it cannot
    /// read at all. It guards every map added since — SSO's six, and the
    /// enterprise list's `operator_access` — the same way.
    const OLDER: &[&str] = &[
        "principals", "keys", "grants", "tokens", "memberships", "bootstrap", "gates", "names",
        "employers", "rooms", "seats", "room_orders", "credentials", "invites",
    ];

    fn stored_keys(store: &Arc<dyn ControlStore>) -> BTreeSet<String> {
        let id = store.read_doc(AUTH_REF).unwrap().expect("the table was written");
        let bytes = store.get_blob(&id).unwrap().expect("its blob");
        let doc: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        doc.as_object().expect("an object").keys().cloned().collect()
    }

    fn provider(account: &str) -> SsoProvider {
        SsoProvider {
            account: account.to_owned(),
            protocol: SsoProtocol::Oidc,
            display_name: format!("{account} corp"),
            domains: vec![format!("{account}.example")],
            oidc: Some(OidcSettings {
                issuer: "https://idp.example.test".into(),
                client_id: "c".into(),
                ..Default::default()
            }),
            saml: None,
            require_sso: false,
            require_passkey: false,
            console_origin: "https://gunnar.example".into(),
            updated: 1,
            updated_by: account.to_owned(),
        }
    }

    /// ★ **A table that never used SSO is one an older gunnar still reads**
    /// (a downgrade, or a twin still on the older line): SSO's maps are
    /// written only once there is something in them, as clans' are — and
    /// gone again once the last row is.
    #[test]
    fn sso_maps_are_written_only_when_used() {
        let store = crate::memory_control_store().expect("store");
        let auth = AuthTable::new(Arc::clone(&store)).expect("table");
        auth.add_principal(Principal::new("acme", "acme", PrincipalKind::User).unwrap())
            .expect("account");
        let keys = stored_keys(&store);
        let unknown: Vec<&String> = keys.iter().filter(|k| !OLDER.contains(&k.as_str())).collect();
        assert!(
            unknown.is_empty(),
            "a table without SSO carries keys an older gunnar refuses: {unknown:?}"
        );

        auth.set_sso_provider(provider("acme")).expect("provider");
        let keys = stored_keys(&store);
        assert!(
            keys.contains("sso_providers") && keys.contains("sso_domains"),
            "a provider is written: {keys:?}"
        );

        auth.remove_sso_provider("acme").expect("removed");
        let keys = stored_keys(&store);
        let unknown: Vec<&String> = keys.iter().filter(|k| !OLDER.contains(&k.as_str())).collect();
        assert!(unknown.is_empty(), "the provider is gone, its maps must be too: {unknown:?}");
    }
}