Skip to main content

vcon_server/tenants/
tenant_admin.rs

1//! What a tenant's administrator does in its own tenant: read and change
2//! the tenant's settings, make, list and revoke the tenant's keys, and
3//! list the tenant's memberships.
4//!
5//! The routes under `/tenant` reach these calls with a key that holds the
6//! scope `tenant_admin`; the route checks the scope and names the key's
7//! own tenant, so no call here reaches another tenant. Each call is
8//! recorded in the admin log, in the registry transaction that does its
9//! work, and copied to the tenant's log.
10//!
11//! The settings are the fixed list of [`crate::settings`]. A key made
12//! here holds scopes within those of the tenant's role cap
13//! ([`Tenants::set_role_cap`]) and never `admin` or `tenant_admin`: only
14//! the operator makes a key that administers a tenant.
15
16use time::OffsetDateTime;
17use time::format_description::well_known::Rfc3339;
18
19use super::keys::{KeyInfo, NewKey, key_info};
20use super::role_cap::stored_cap;
21use super::{KeyLife, RTx, Slot, TenantError, Tenants, commit};
22use crate::access::Scopes;
23use crate::audit::{Action, Actor, Entry};
24use crate::backend::TenantRow;
25use crate::clock::{from_nanos, nanos};
26use crate::ids::{KeyId, TenantId, UserId};
27use crate::roles::{Role, Roles};
28use crate::settings::{self, Settings};
29
30/// One membership in a tenant, as the tenant's administrator sees it.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct MemberInfo {
33    pub user: UserId,
34    /// The user's label.
35    pub label: String,
36    /// The roles granted, as the membership's row keeps them.
37    pub roles: Roles,
38    /// What the membership lets its user do: the scopes of those of its
39    /// roles that the tenant's role cap allows.
40    pub scopes: Scopes,
41    pub granted_at: OffsetDateTime,
42}
43
44impl MemberInfo {
45    /// The member with its user's id, its label, its roles and scopes by
46    /// name, and the time of the grant (RFC 3339, UTC). None when the time
47    /// cannot be written so.
48    #[must_use]
49    pub fn to_json(&self) -> Option<serde_json::Value> {
50        Some(serde_json::json!({
51            "user": self.user.to_string(),
52            "label": self.label,
53            "roles": self.roles.names(),
54            "scopes": self.scopes.names(),
55            "granted_at": self.granted_at.format(&Rfc3339).ok()?,
56        }))
57    }
58}
59
60/// The scopes a key made by a tenant's administrator may hold under the
61/// tenant's role cap: those of the roles the cap allows, or of every
62/// tenant role with no cap, and never `tenant_admin`.
63#[must_use]
64pub(crate) fn key_scopes(cap: Option<Roles>) -> Scopes {
65    Roles::TENANT
66        .within(cap)
67        .without(Roles::of(&[Role::TenantAdmin]))
68        .scopes()
69}
70
71/// The settings a tenant's rows make. Rows the list does not read are
72/// damage.
73fn stored_settings(tx: &mut RTx<'_>, tenant: TenantId) -> Result<Settings, TenantError> {
74    Settings::stored(&tx.settings(tenant)?).ok_or(TenantError::Io)
75}
76
77impl Tenants {
78    /// Starts a call on a tenant: the registry transaction and the
79    /// tenant's row. A tenant that is not there or is being removed is
80    /// refused here, and the refusal recorded in the admin log alone: there
81    /// is no tenant's log to copy it to.
82    fn begin(
83        &self,
84        tenant: TenantId,
85        entry: impl Fn(u16) -> Entry,
86    ) -> Result<(RTx<'_>, TenantRow), TenantError> {
87        let closing = matches!(self.stores().get(&tenant), Some(Slot::Closing));
88        let mut tx = self.registry.immediate()?;
89        let (status, refused) = match tx.tenant(tenant)? {
90            None => (404, TenantError::NotFound),
91            Some(_) if closing => (503, TenantError::Closing),
92            Some(row) => return Ok((tx, row)),
93        };
94        self.record(&mut tx, &entry(status))?;
95        commit(tx)?;
96        Err(refused)
97    }
98
99    /// Ends a call: its record in the admin log with its work, then the
100    /// copy in the tenant's log. The copy opens the tenant's Store, which
101    /// reads the registry, so it follows the commit.
102    fn end(&self, mut tx: RTx<'_>, tenant: TenantId, entry: &Entry) -> Result<(), TenantError> {
103        self.record(&mut tx, entry)?;
104        commit(tx)?;
105        self.copy_to_tenant(tenant, entry)
106    }
107
108    /// The tenant's settings: each name with what was set, or its default.
109    pub fn settings(&self, who: Actor, tenant: TenantId) -> Result<Settings, TenantError> {
110        let entry = |status| Entry {
111            actor: who,
112            action: Action::SettingsRead,
113            target: Some(tenant.to_string()),
114            version: None,
115            status,
116        };
117        let (mut tx, _) = self.begin(tenant, entry)?;
118        let settings = stored_settings(&mut tx, tenant)?;
119        self.end(tx, tenant, &entry(200))?;
120        Ok(settings)
121    }
122
123    /// Changes the tenant's settings as `change` says: a JSON object of
124    /// names, each with its new value or null for its default
125    /// ([`Settings::changed`]). Gives the settings after the change. A
126    /// refused change stores nothing. The record names the tenant and the
127    /// names changed, never a value.
128    pub fn set_settings(
129        &self,
130        who: Actor,
131        tenant: TenantId,
132        change: &serde_json::Value,
133    ) -> Result<Settings, TenantError> {
134        let entry = |status, names: &str| Entry {
135            actor: who,
136            action: Action::SettingsSet,
137            target: Some(if names.is_empty() {
138                tenant.to_string()
139            } else {
140                format!("{tenant}/{names}")
141            }),
142            version: None,
143            status,
144        };
145        let (mut tx, _) = self.begin(tenant, |status| entry(status, ""))?;
146        let (after, changes) = match stored_settings(&mut tx, tenant)?.changed(change) {
147            Ok(changed) => changed,
148            Err(error) => {
149                self.end(tx, tenant, &entry(422, ""))?;
150                return Err(TenantError::BadSetting(error));
151            }
152        };
153        for (name, value) in &changes {
154            match value {
155                Some(value) => tx.put_setting(tenant, name.as_str(), &value.text())?,
156                None => tx.delete_setting(tenant, name.as_str())?,
157            }
158        }
159        self.end(tx, tenant, &entry(200, &settings::named(&changes)))?;
160        Ok(after)
161    }
162
163    /// Makes a key for the tenant with the default life, as
164    /// [`Tenants::create_tenant_key_for`] makes one with
165    /// [`KeyLife::Default`].
166    pub fn create_tenant_key(
167        &self,
168        who: Actor,
169        tenant: TenantId,
170        scopes: Scopes,
171        label: &str,
172    ) -> Result<NewKey, TenantError> {
173        self.create_tenant_key_for(who, tenant, scopes, label, KeyLife::Default)
174    }
175
176    /// Makes a key for the tenant, as its administrator may: with at
177    /// least one scope, all among those the tenant's role cap gives a key and
178    /// never `tenant_admin`. The key expires as `life` says; a life the key
179    /// cannot have is refused after its scopes are.
180    pub fn create_tenant_key_for(
181        &self,
182        who: Actor,
183        tenant: TenantId,
184        scopes: Scopes,
185        label: &str,
186        life: KeyLife,
187    ) -> Result<NewKey, TenantError> {
188        let entry = |status, target: String| Entry {
189            actor: who,
190            action: Action::KeyCreate,
191            target: Some(target),
192            version: None,
193            status,
194        };
195        let (mut tx, row) = self.begin(tenant, |status| entry(status, tenant.to_string()))?;
196        let allowed = key_scopes(stored_cap(row.role_cap.as_deref())?);
197        if scopes.is_empty() || !scopes.within(allowed) {
198            self.end(tx, tenant, &entry(422, tenant.to_string()))?;
199            return Err(TenantError::BadScopes);
200        }
201        let now = nanos(self.clock.now());
202        if let Err(refused) = life.expires_at(now, self.no_expiry_allowed()) {
203            self.end(tx, tenant, &entry(422, tenant.to_string()))?;
204            return Err(refused);
205        }
206        let made = self.insert_key(&mut tx, Some(tenant), scopes, label, life)?;
207        self.end(tx, tenant, &entry(201, made.id.to_string()))?;
208        Ok(made)
209    }
210
211    /// The tenant's keys, oldest first.
212    pub fn tenant_keys(&self, who: Actor, tenant: TenantId) -> Result<Vec<KeyInfo>, TenantError> {
213        let entry = |status| Entry {
214            actor: who,
215            action: Action::KeyList,
216            target: Some(tenant.to_string()),
217            version: None,
218            status,
219        };
220        let (mut tx, _) = self.begin(tenant, entry)?;
221        let keys = tx
222            .keys(Some(tenant))?
223            .into_iter()
224            .map(key_info)
225            .collect::<Result<Vec<_>, TenantError>>()?;
226        self.end(tx, tenant, &entry(200))?;
227        Ok(keys)
228    }
229
230    /// Revokes a key of the tenant; revoking it again changes nothing. A
231    /// key of another tenant, an operator key and an id no key has are all
232    /// not found, and nothing is revoked.
233    pub fn revoke_tenant_key(
234        &self,
235        who: Actor,
236        tenant: TenantId,
237        id: KeyId,
238    ) -> Result<(), TenantError> {
239        let entry = |status| Entry {
240            actor: who,
241            action: Action::KeyRevoke,
242            target: Some(id.to_string()),
243            version: None,
244            status,
245        };
246        let (mut tx, _) = self.begin(tenant, entry)?;
247        if tx.key(id)?.is_none_or(|row| row.tenant != Some(tenant)) {
248            self.end(tx, tenant, &entry(404))?;
249            return Err(TenantError::NotFound);
250        }
251        tx.revoke_key(id, nanos(self.clock.now()))?;
252        self.end(tx, tenant, &entry(204))
253    }
254
255    /// The tenant's memberships, oldest first: each user with its label,
256    /// the roles granted and the scopes they give under the tenant's role
257    /// cap.
258    pub fn members(&self, who: Actor, tenant: TenantId) -> Result<Vec<MemberInfo>, TenantError> {
259        let entry = |status| Entry {
260            actor: who,
261            action: Action::MembershipList,
262            target: Some(tenant.to_string()),
263            version: None,
264            status,
265        };
266        let (mut tx, row) = self.begin(tenant, entry)?;
267        let cap = stored_cap(row.role_cap.as_deref())?;
268        let users = tx.users()?;
269        let mut held: Vec<_> = tx
270            .memberships()?
271            .into_iter()
272            .filter(|m| m.tenant == Some(tenant))
273            .collect();
274        held.sort_by_key(|m| (m.granted_at, m.user.0));
275        let members = held
276            .into_iter()
277            .map(|m| {
278                // A membership with no user, or roles that do not read
279                // back, is damage.
280                let user = users.iter().find(|user| user.id == m.user);
281                let roles = Roles::parse(&m.roles).ok_or(TenantError::Io)?;
282                Ok(MemberInfo {
283                    user: m.user,
284                    label: user.ok_or(TenantError::Io)?.label.clone(),
285                    roles,
286                    scopes: roles.within(cap).scopes(),
287                    granted_at: from_nanos(m.granted_at).ok_or(TenantError::Io)?,
288                })
289            })
290            .collect::<Result<Vec<_>, TenantError>>()?;
291        self.end(tx, tenant, &entry(200))?;
292        Ok(members)
293    }
294}
295
296#[cfg(test)]
297mod tests {
298    // By kind: what must work, what must be refused, and the limits and
299    // odd inputs.
300
301    use serde_json::{Value, json};
302
303    use super::*;
304    use crate::access::{Scope, Scopes};
305    use crate::audit::Actor;
306    use crate::audit::testing::exported;
307    use crate::ids::{KeyId, TenantId, UserId};
308    use crate::roles::{Role, Roles};
309    use crate::settings::{Name, SettingError, Settings, Value as Held};
310    use crate::tenants::tests::{Fixture, fixture};
311    use crate::tenants::{Removal, Slot, TenantError};
312
313    const CLI: Actor = Actor::Cli;
314
315    fn tenant(f: &Fixture, name: &str) -> TenantId {
316        f.tenants.create(CLI, name, None).expect("made")
317    }
318
319    /// A key of the tenant's administrator, made by the operator, and the
320    /// actor its requests are.
321    fn administrator(f: &Fixture, tenant: TenantId) -> (KeyId, Actor) {
322        let key = f
323            .tenants
324            .create_key(
325                CLI,
326                Some(tenant),
327                Scopes::of(&[Scope::TenantAdmin]),
328                "admin",
329            )
330            .expect("the operator makes the administrator's key")
331            .id;
332        (key, Actor::Key(key))
333    }
334
335    /// A tenant and its administrator.
336    fn administered(f: &Fixture, name: &str) -> (TenantId, Actor) {
337        let t = tenant(f, name);
338        (t, administrator(f, t).1)
339    }
340
341    fn cap(f: &Fixture, tenant: TenantId, of: &[Role]) {
342        f.tenants
343            .set_role_cap(CLI, tenant, Some(Roles::of(of)))
344            .expect("the cap is set");
345    }
346
347    fn member(f: &Fixture, label: &str, tenant: Option<TenantId>, of: &[Role]) -> UserId {
348        let user = f.tenants.add_user(CLI, label, None).expect("a local user");
349        f.tenants
350            .grant_membership(CLI, user, tenant, Roles::of(of))
351            .expect("granted");
352        user
353    }
354
355    /// The records of `action` in a log: actor, target and status.
356    fn records(log: &[Value], action: &str) -> Vec<(Value, Value, Value)> {
357        log.iter()
358            .filter(|r| r["action"] == action)
359            .map(|r| (r["actor"].clone(), r["target"].clone(), r["status"].clone()))
360            .collect()
361    }
362
363    fn admin(f: &Fixture, action: &str) -> Vec<(Value, Value, Value)> {
364        records(&exported(&f.conn(), None), action)
365    }
366
367    fn in_tenant(f: &Fixture, tenant: TenantId, action: &str) -> Vec<(Value, Value, Value)> {
368        records(&exported(&f.tenant_catalog(tenant), None), action)
369    }
370
371    /// The last record of `action` in the admin log: target and status.
372    fn last(f: &Fixture, action: &str) -> (Value, Value) {
373        let (_, target, status) = admin(f, action).pop().expect("a record");
374        (target, status)
375    }
376
377    fn actor(who: Actor) -> Value {
378        match who {
379            Actor::Key(key) => json!(key.to_string()),
380            _ => json!("cli"),
381        }
382    }
383
384    /// The tenant's rows of the settings table.
385    fn stored(f: &Fixture, tenant: TenantId) -> Vec<(String, String)> {
386        let conn = f.conn();
387        let mut rows = conn
388            .prepare("SELECT name, value FROM tenant_setting WHERE tenant = ?1 ORDER BY name")
389            .expect("the table");
390        rows.query_map([tenant.0], |r| Ok((r.get(0)?, r.get(1)?)))
391            .expect("rows")
392            .collect::<Result<_, _>>()
393            .expect("text")
394    }
395
396    fn pairs(of: &[(&str, &str)]) -> Vec<(String, String)> {
397        of.iter()
398            .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
399            .collect()
400    }
401
402    fn scopes(of: &[Scope]) -> Scopes {
403        Scopes::of(of)
404    }
405
406    /// Whether the key is revoked, as a request's check reads it.
407    fn revoked(f: &Fixture, key: KeyId) -> bool {
408        f.tenants
409            .stored_key(key)
410            .expect("read")
411            .expect("the key")
412            .revoked
413    }
414
415    // What must work: settings.
416
417    #[test]
418    fn a_tenant_that_set_nothing_reads_every_default() {
419        let f = fixture();
420        let (t, who) = administered(&f, "acme");
421        assert_eq!(
422            f.tenants.settings(who, t),
423            Ok(Settings::default()),
424            "the defaults"
425        );
426        assert_eq!(stored(&f, t), vec![], "and no row");
427    }
428
429    #[test]
430    fn a_change_is_kept_and_read_back() {
431        let f = fixture();
432        let (t, who) = administered(&f, "acme");
433        let change = json!({ "masking.legal": false, "session.idle_seconds": 300 });
434        let after = f.tenants.set_settings(who, t, &change).expect("set");
435        assert_eq!(
436            after.get(Name::Masking(Role::Legal)),
437            Held::Flag(false),
438            "the answer holds the change"
439        );
440        assert_eq!(f.tenants.settings(who, t), Ok(after), "and a read gives it");
441        assert_eq!(
442            stored(&f, t),
443            pairs(&[("masking.legal", "false"), ("session.idle_seconds", "300")]),
444            "one row for each name set"
445        );
446    }
447
448    #[test]
449    fn a_read_is_recorded_in_the_admin_log_and_the_tenants() {
450        let f = fixture();
451        let (t, who) = administered(&f, "acme");
452        f.tenants.settings(who, t).expect("read");
453        let record = vec![(actor(who), json!(t.to_string()), json!(200))];
454        assert_eq!(admin(&f, "settings_read"), record, "the admin log");
455        assert_eq!(in_tenant(&f, t, "settings_read"), record, "the tenant's");
456    }
457
458    #[test]
459    fn a_change_is_recorded_with_its_names_and_no_value() {
460        let f = fixture();
461        let (t, who) = administered(&f, "acme");
462        let change = json!({ "session.idle_seconds": 300, "masking.legal": false });
463        f.tenants.set_settings(who, t, &change).expect("set");
464        let record = vec![(
465            actor(who),
466            json!(format!("{t}/masking.legal,session.idle_seconds")),
467            json!(200),
468        )];
469        assert_eq!(admin(&f, "settings_set"), record, "the admin log");
470        assert_eq!(in_tenant(&f, t, "settings_set"), record, "the tenant's");
471    }
472
473    #[test]
474    fn a_null_removes_the_row_and_gives_the_default_again() {
475        let f = fixture();
476        let (t, who) = administered(&f, "acme");
477        f.tenants
478            .set_settings(
479                who,
480                t,
481                &json!({ "masking.legal": false, "masking.reader": false }),
482            )
483            .expect("set");
484        let after = f
485            .tenants
486            .set_settings(who, t, &json!({ "masking.legal": null }))
487            .expect("unset");
488        assert_eq!(
489            after.get(Name::Masking(Role::Legal)),
490            Held::Flag(true),
491            "the default"
492        );
493        assert_eq!(
494            stored(&f, t),
495            pairs(&[("masking.reader", "false")]),
496            "only the other row is left"
497        );
498    }
499
500    #[test]
501    fn a_later_change_builds_on_the_earlier_ones() {
502        let f = fixture();
503        let (t, who) = administered(&f, "acme");
504        f.tenants
505            .set_settings(
506                who,
507                t,
508                &json!({ "session.absolute_seconds": 600 , "session.idle_seconds": 300 }),
509            )
510            .expect("first");
511        let after = f
512            .tenants
513            .set_settings(who, t, &json!({ "session.idle_seconds": 600 }))
514            .expect("second: 600 is within the absolute limit already set");
515        assert_eq!(after.get(Name::SessionIdle), Held::Seconds(600), "idle");
516        assert_eq!(
517            after.get(Name::SessionAbsolute),
518            Held::Seconds(600),
519            "absolute, from the first change"
520        );
521    }
522
523    #[test]
524    fn each_tenant_has_its_own_settings() {
525        let f = fixture();
526        let (a, who_a) = administered(&f, "acme");
527        let (b, who_b) = administered(&f, "beta");
528        f.tenants
529            .set_settings(who_a, a, &json!({ "masking.reader": false }))
530            .expect("acme's");
531        assert_eq!(
532            f.tenants.settings(who_b, b),
533            Ok(Settings::default()),
534            "beta's are untouched"
535        );
536        assert_eq!(in_tenant(&f, b, "settings_set"), vec![], "nor is its log");
537    }
538
539    #[test]
540    fn settings_are_there_after_a_restart() {
541        let mut f = fixture();
542        let (t, who) = administered(&f, "acme");
543        let after = f
544            .tenants
545            .set_settings(who, t, &json!({ "session.idle_seconds": 120 }))
546            .expect("set");
547        f.restart();
548        assert_eq!(
549            f.tenants.settings(who, t),
550            Ok(after),
551            "what the registry kept"
552        );
553    }
554
555    // What must work: keys.
556
557    #[test]
558    fn an_administrator_makes_a_key_for_its_tenant() {
559        let f = fixture();
560        let (t, who) = administered(&f, "acme");
561        let made = f
562            .tenants
563            .create_tenant_key(who, t, scopes(&[Scope::Read]), "reports")
564            .expect("made");
565        let key = f.tenants.stored_key(made.id).expect("read").expect("kept");
566        assert_eq!(key.tenant, Some(t), "a key of the tenant");
567        assert_eq!(key.scopes, scopes(&[Scope::Read]), "with the scopes asked");
568        assert!(!made.token.is_empty(), "and its token, shown this once");
569    }
570
571    #[test]
572    fn making_a_key_is_recorded_in_both_logs_under_the_new_keys_id() {
573        let f = fixture();
574        let (t, who) = administered(&f, "acme");
575        let made = f
576            .tenants
577            .create_tenant_key(who, t, scopes(&[Scope::Write]), "producer")
578            .expect("made");
579        let record = (actor(who), json!(made.id.to_string()), json!(201));
580        assert_eq!(
581            admin(&f, "key_create").last(),
582            Some(&record),
583            "the admin log"
584        );
585        assert_eq!(
586            in_tenant(&f, t, "key_create").last(),
587            Some(&record),
588            "the tenant's"
589        );
590    }
591
592    #[test]
593    fn a_key_may_hold_every_scope_the_cap_gives() {
594        let f = fixture();
595        let (t, who) = administered(&f, "acme");
596        cap(&f, t, &[Role::Reader, Role::Producer, Role::TenantAdmin]);
597        let asked = scopes(&[Scope::Read, Scope::Write]);
598        let made = f
599            .tenants
600            .create_tenant_key(who, t, asked, "both")
601            .expect("within the cap");
602        let key = f.tenants.stored_key(made.id).expect("read").expect("kept");
603        assert_eq!(key.scopes, asked, "both scopes");
604    }
605
606    #[test]
607    fn an_administrator_lists_its_tenants_keys_and_no_others() {
608        let f = fixture();
609        let (a, who) = administered(&f, "acme");
610        let (b, _) = administered(&f, "beta");
611        // A later time, so the order below does not hang on the keys' ids.
612        f.clock.set(time::macros::datetime!(2026-10-23 12:05 UTC));
613        let made = f
614            .tenants
615            .create_tenant_key(who, a, scopes(&[Scope::Read]), "reports")
616            .expect("made");
617        let listed = f.tenants.tenant_keys(who, a).expect("listed");
618        assert_eq!(listed.len(), 2, "the administrator's key and the new one");
619        assert!(
620            listed.iter().all(|key| key.tenant == Some(a)),
621            "none of {b}'s: {listed:?}"
622        );
623        assert_eq!(
624            listed.last().map(|key| (key.id, key.label.as_str())),
625            Some((made.id, "reports")),
626            "oldest first"
627        );
628    }
629
630    #[test]
631    fn listing_keys_is_recorded_in_both_logs() {
632        let f = fixture();
633        let (t, who) = administered(&f, "acme");
634        f.tenants.tenant_keys(who, t).expect("listed");
635        let record = vec![(actor(who), json!(t.to_string()), json!(200))];
636        assert_eq!(admin(&f, "key_list"), record, "the admin log");
637        assert_eq!(in_tenant(&f, t, "key_list"), record, "the tenant's");
638    }
639
640    #[test]
641    fn an_administrator_revokes_a_key_of_its_tenant() {
642        let f = fixture();
643        let (t, who) = administered(&f, "acme");
644        let made = f
645            .tenants
646            .create_key(CLI, Some(t), scopes(&[Scope::Read]), "old")
647            .expect("made by the operator");
648        assert_eq!(
649            f.tenants.revoke_tenant_key(who, t, made.id),
650            Ok(()),
651            "revoked"
652        );
653        assert!(revoked(&f, made.id), "its next request is refused");
654        let record = (actor(who), json!(made.id.to_string()), json!(204));
655        assert_eq!(
656            admin(&f, "key_revoke").last(),
657            Some(&record),
658            "the admin log"
659        );
660        assert_eq!(
661            in_tenant(&f, t, "key_revoke").last(),
662            Some(&record),
663            "the tenant's"
664        );
665    }
666
667    // What must work: memberships.
668
669    #[test]
670    fn an_administrator_lists_its_tenants_memberships() {
671        let f = fixture();
672        let (t, who) = administered(&f, "acme");
673        let reader = member(&f, "Reader", Some(t), &[Role::Reader]);
674        f.clock.set(time::macros::datetime!(2026-10-23 12:05 UTC));
675        let both = member(&f, "Both", Some(t), &[Role::Legal, Role::Auditor]);
676        let listed = f.tenants.members(who, t).expect("listed");
677        let shown: Vec<(UserId, &str, Roles, Scopes)> = listed
678            .iter()
679            .map(|m| (m.user, m.label.as_str(), m.roles, m.scopes))
680            .collect();
681        assert_eq!(
682            shown,
683            [
684                (
685                    reader,
686                    "Reader",
687                    Roles::of(&[Role::Reader]),
688                    scopes(&[Scope::Read])
689                ),
690                (
691                    both,
692                    "Both",
693                    Roles::of(&[Role::Legal, Role::Auditor]),
694                    scopes(&[Scope::Legal, Scope::Audit])
695                ),
696            ],
697            "each member with its label, roles and scopes, oldest first"
698        );
699    }
700
701    #[test]
702    fn a_members_scopes_are_those_the_cap_still_gives() {
703        let f = fixture();
704        let (t, who) = administered(&f, "acme");
705        member(&f, "Both", Some(t), &[Role::Legal, Role::Reader]);
706        cap(&f, t, &[Role::Reader]);
707        let listed = f.tenants.members(who, t).expect("listed");
708        assert_eq!(
709            listed[0].roles,
710            Roles::of(&[Role::Legal, Role::Reader]),
711            "the roles as granted"
712        );
713        assert_eq!(
714            listed[0].scopes,
715            scopes(&[Scope::Read]),
716            "the scopes under the cap"
717        );
718    }
719
720    #[test]
721    fn listing_memberships_is_recorded_in_both_logs() {
722        let f = fixture();
723        let (t, who) = administered(&f, "acme");
724        f.tenants.members(who, t).expect("listed");
725        let record = vec![(actor(who), json!(t.to_string()), json!(200))];
726        assert_eq!(admin(&f, "membership_list"), record, "the admin log");
727        assert_eq!(in_tenant(&f, t, "membership_list"), record, "the tenant's");
728    }
729
730    #[test]
731    fn a_member_is_shown_as_json_with_names_and_a_time() {
732        let f = fixture();
733        let (t, who) = administered(&f, "acme");
734        let user = member(&f, "Reader", Some(t), &[Role::Reader, Role::Auditor]);
735        let listed = f.tenants.members(who, t).expect("listed");
736        let shown = listed[0].to_json().expect("a time that can be written");
737        assert_eq!(shown["user"], json!(user.to_string()), "the user's id");
738        assert_eq!(shown["label"], json!("Reader"), "the label");
739        assert_eq!(shown["roles"], json!(["reader", "auditor"]), "role names");
740        assert_eq!(shown["scopes"], json!(["read", "audit"]), "scope names");
741        assert!(
742            shown["granted_at"]
743                .as_str()
744                .is_some_and(|at| at.ends_with('Z')),
745            "RFC 3339, UTC: {}",
746            shown["granted_at"]
747        );
748        assert_eq!(
749            shown.as_object().map(serde_json::Map::len),
750            Some(5),
751            "and nothing else: {shown}"
752        );
753    }
754
755    // What must be refused: settings.
756
757    #[test]
758    fn a_name_outside_the_list_is_refused_and_recorded() {
759        let f = fixture();
760        let (t, who) = administered(&f, "acme");
761        assert_eq!(
762            f.tenants
763                .set_settings(who, t, &json!({ "bulk_export": false })),
764            Err(TenantError::BadSetting(SettingError::UnknownName)),
765            "not a setting"
766        );
767        assert_eq!(stored(&f, t), vec![], "nothing is stored");
768        assert_eq!(
769            last(&f, "settings_set"),
770            (json!(t.to_string()), json!(422)),
771            "the refusal, with no name from the body"
772        );
773        assert_eq!(
774            in_tenant(&f, t, "settings_set"),
775            vec![(actor(who), json!(t.to_string()), json!(422))],
776            "the tenant's log holds what its administrator was refused"
777        );
778    }
779
780    #[test]
781    fn a_limit_outside_its_bounds_is_refused_and_nothing_is_stored() {
782        let f = fixture();
783        let (t, who) = administered(&f, "acme");
784        let change = json!({ "masking.reader": false, "session.idle_seconds": 30 });
785        assert_eq!(
786            f.tenants.set_settings(who, t, &change),
787            Err(TenantError::BadSetting(SettingError::OutOfBounds)),
788            "30 s is under the bound"
789        );
790        assert_eq!(
791            stored(&f, t),
792            vec![],
793            "not even the good name of the change"
794        );
795    }
796
797    #[test]
798    fn an_idle_limit_above_the_absolute_limit_set_earlier_is_refused() {
799        let f = fixture();
800        let (t, who) = administered(&f, "acme");
801        f.tenants
802            .set_settings(
803                who,
804                t,
805                &json!({ "session.absolute_seconds": 300, "session.idle_seconds": 120 }),
806            )
807            .expect("first");
808        assert_eq!(
809            f.tenants
810                .set_settings(who, t, &json!({ "session.idle_seconds": 600 })),
811            Err(TenantError::BadSetting(SettingError::IdleOverAbsolute)),
812            "against the stored absolute limit"
813        );
814        assert_eq!(
815            stored(&f, t),
816            pairs(&[
817                ("session.absolute_seconds", "300"),
818                ("session.idle_seconds", "120")
819            ]),
820            "the rows are as the first change left them"
821        );
822    }
823
824    #[test]
825    fn settings_of_a_tenant_that_is_not_there_are_not_found() {
826        let f = fixture();
827        let gone = TenantId::generate();
828        let who = Actor::Key(KeyId::generate());
829        assert_eq!(
830            f.tenants.settings(who, gone),
831            Err(TenantError::NotFound),
832            "read"
833        );
834        assert_eq!(
835            f.tenants
836                .set_settings(who, gone, &json!({ "masking.reader": false })),
837            Err(TenantError::NotFound),
838            "set"
839        );
840        assert_eq!(
841            last(&f, "settings_read"),
842            (json!(gone.to_string()), json!(404)),
843            "the read's refusal"
844        );
845        assert_eq!(
846            last(&f, "settings_set"),
847            (json!(gone.to_string()), json!(404)),
848            "the change's refusal"
849        );
850        assert_eq!(stored(&f, gone), vec![], "nothing is stored for no tenant");
851    }
852
853    #[test]
854    fn a_change_for_a_tenant_being_removed_is_refused() {
855        let f = fixture();
856        let (t, who) = administered(&f, "acme");
857        f.tenants.stores().insert(t, Slot::Closing);
858        assert_eq!(
859            f.tenants
860                .set_settings(who, t, &json!({ "masking.reader": false })),
861            Err(TenantError::Closing),
862            "while the tenant closes"
863        );
864        assert_eq!(stored(&f, t), vec![], "nothing was set");
865        assert_eq!(
866            last(&f, "settings_set"),
867            (json!(t.to_string()), json!(503)),
868            "recorded"
869        );
870    }
871
872    #[test]
873    fn a_stored_row_the_list_does_not_read_is_damage_not_a_default() {
874        let f = fixture();
875        let (t, who) = administered(&f, "acme");
876        f.conn()
877            .execute(
878                "INSERT INTO tenant_setting VALUES (?1, 'masking.reader', 'off')",
879                [t.0],
880            )
881            .expect("a row by hand");
882        assert_eq!(f.tenants.settings(who, t), Err(TenantError::Io), "read");
883        assert_eq!(
884            f.tenants
885                .set_settings(who, t, &json!({ "masking.legal": false })),
886            Err(TenantError::Io),
887            "a change does not build on damage"
888        );
889        assert_eq!(
890            stored(&f, t),
891            pairs(&[("masking.reader", "off")]),
892            "and writes nothing beside it"
893        );
894    }
895
896    #[test]
897    fn a_change_whose_record_cannot_be_written_is_not_made() {
898        let f = fixture();
899        let (t, who) = administered(&f, "acme");
900        f.tenants.break_audit();
901        assert_eq!(
902            f.tenants
903                .set_settings(who, t, &json!({ "masking.reader": false })),
904            Err(TenantError::AuditFailed),
905            "no record, no change"
906        );
907        assert_eq!(stored(&f, t), vec![], "nothing was set");
908        assert_eq!(
909            f.tenants.settings(who, t),
910            Err(TenantError::AuditFailed),
911            "nor is a read answered without its record"
912        );
913    }
914
915    // What must be refused: keys.
916
917    #[test]
918    fn an_administrator_cannot_make_another_administrators_key() {
919        let f = fixture();
920        let (t, who) = administered(&f, "acme");
921        let before = f.tenants.tenant_keys(who, t).expect("listed").len();
922        for asked in [
923            scopes(&[Scope::TenantAdmin]),
924            scopes(&[Scope::Read, Scope::TenantAdmin]),
925        ] {
926            assert!(
927                matches!(
928                    f.tenants.create_tenant_key(who, t, asked, "more"),
929                    Err(TenantError::BadScopes)
930                ),
931                "only the operator gives tenant_admin: {asked}"
932            );
933        }
934        assert_eq!(
935            last(&f, "key_create"),
936            (json!(t.to_string()), json!(422)),
937            "recorded"
938        );
939        assert_eq!(
940            f.tenants.tenant_keys(who, t).expect("listed").len(),
941            before,
942            "no key was made"
943        );
944    }
945
946    #[test]
947    fn an_administrator_cannot_make_an_operator_key() {
948        let f = fixture();
949        let (t, who) = administered(&f, "acme");
950        for asked in [
951            scopes(&[Scope::Admin]),
952            scopes(&[Scope::Read, Scope::Admin]),
953        ] {
954            assert!(
955                matches!(
956                    f.tenants.create_tenant_key(who, t, asked, "more"),
957                    Err(TenantError::BadScopes)
958                ),
959                "admin is the operator's: {asked}"
960            );
961        }
962    }
963
964    #[test]
965    fn an_administrators_key_expires_in_90_days_unless_a_life_is_asked() {
966        let f = fixture();
967        let (t, who) = administered(&f, "acme");
968        f.tenants
969            .create_tenant_key(who, t, scopes(&[Scope::Read]), "default")
970            .expect("made");
971        f.tenants
972            .create_tenant_key_for(who, t, scopes(&[Scope::Read]), "week", KeyLife::Days(7))
973            .expect("made");
974        f.tenants
975            .create_tenant_key_for(who, t, scopes(&[Scope::Read]), "forever", KeyLife::Never)
976            .expect("made");
977        let keys = f.tenants.tenant_keys(who, t).expect("listed");
978        let life = |label: &str| {
979            let key = keys.iter().find(|k| k.label == label).expect("the key");
980            key.expires_at.map(|at| (at - key.created_at).whole_days())
981        };
982        assert_eq!(life("default"), Some(90), "no life asked");
983        assert_eq!(life("week"), Some(7), "seven days asked");
984        assert_eq!(life("forever"), None, "no expiry asked");
985    }
986
987    #[test]
988    fn an_expiry_the_configuration_refuses_is_refused_and_recorded_in_both_logs() {
989        let f = fixture();
990        let (t, who) = administered(&f, "acme");
991        f.tenants.allow_no_expiry(false);
992        let before = f.tenants.tenant_keys(who, t).expect("listed").len();
993        assert!(
994            matches!(
995                f.tenants.create_tenant_key_for(
996                    who,
997                    t,
998                    scopes(&[Scope::Read]),
999                    "forever",
1000                    KeyLife::Never
1001                ),
1002                Err(TenantError::BadExpiry)
1003            ),
1004            "no expiry where keys.no_expiry is false"
1005        );
1006        assert!(
1007            matches!(
1008                f.tenants.create_tenant_key_for(
1009                    who,
1010                    t,
1011                    scopes(&[Scope::Read]),
1012                    "long",
1013                    KeyLife::Days(366)
1014                ),
1015                Err(TenantError::BadExpiry)
1016            ),
1017            "more than 365 days"
1018        );
1019        let refusal = (actor(who), json!(t.to_string()), json!(422));
1020        assert_eq!(
1021            in_tenant(&f, t, "key_create")
1022                .iter()
1023                .filter(|record| **record == refusal)
1024                .count(),
1025            2,
1026            "both refusals are in the tenant's log, under the administrator's key"
1027        );
1028        assert_eq!(
1029            admin(&f, "key_create")
1030                .iter()
1031                .filter(|record| **record == refusal)
1032                .count(),
1033            2,
1034            "and in the admin log"
1035        );
1036        assert_eq!(
1037            f.tenants.tenant_keys(who, t).expect("listed").len(),
1038            before,
1039            "no key was made"
1040        );
1041    }
1042
1043    #[test]
1044    fn a_key_with_no_scope_is_refused() {
1045        let f = fixture();
1046        let (t, who) = administered(&f, "acme");
1047        assert!(
1048            matches!(
1049                f.tenants
1050                    .create_tenant_key(who, t, Scopes::default(), "nothing"),
1051                Err(TenantError::BadScopes)
1052            ),
1053            "a key holds at least one scope"
1054        );
1055    }
1056
1057    #[test]
1058    fn a_scope_outside_the_tenants_role_cap_is_refused() {
1059        let f = fixture();
1060        let (t, who) = administered(&f, "acme");
1061        cap(&f, t, &[Role::Reader, Role::TenantAdmin]);
1062        for asked in [
1063            scopes(&[Scope::Write]),
1064            scopes(&[Scope::Read, Scope::Legal]),
1065        ] {
1066            assert!(
1067                matches!(
1068                    f.tenants.create_tenant_key(who, t, asked, "more"),
1069                    Err(TenantError::BadScopes)
1070                ),
1071                "the cap gives read alone: {asked}"
1072            );
1073        }
1074        assert_eq!(
1075            last(&f, "key_create"),
1076            (json!(t.to_string()), json!(422)),
1077            "recorded"
1078        );
1079    }
1080
1081    #[test]
1082    fn a_key_of_another_tenant_is_not_found_and_not_revoked() {
1083        let f = fixture();
1084        let (a, who) = administered(&f, "acme");
1085        let (b, _) = administered(&f, "beta");
1086        let theirs = f
1087            .tenants
1088            .create_key(CLI, Some(b), scopes(&[Scope::Read]), "beta's")
1089            .expect("made");
1090        assert_eq!(
1091            f.tenants.revoke_tenant_key(who, a, theirs.id),
1092            Err(TenantError::NotFound),
1093            "as if there were no such key"
1094        );
1095        assert!(!revoked(&f, theirs.id), "the key still works");
1096        assert_eq!(
1097            last(&f, "key_revoke"),
1098            (json!(theirs.id.to_string()), json!(404)),
1099            "recorded in the admin log"
1100        );
1101        assert_eq!(
1102            in_tenant(&f, a, "key_revoke"),
1103            vec![(actor(who), json!(theirs.id.to_string()), json!(404))],
1104            "and in the log of the tenant whose administrator asked"
1105        );
1106        assert_eq!(
1107            in_tenant(&f, b, "key_revoke"),
1108            vec![],
1109            "nothing reaches the other tenant's log"
1110        );
1111    }
1112
1113    #[test]
1114    fn an_operator_key_is_not_found_and_not_revoked() {
1115        let f = fixture();
1116        let (t, who) = administered(&f, "acme");
1117        let operator = f
1118            .tenants
1119            .create_key(CLI, None, scopes(&[Scope::Admin]), "operator")
1120            .expect("made");
1121        assert_eq!(
1122            f.tenants.revoke_tenant_key(who, t, operator.id),
1123            Err(TenantError::NotFound),
1124            "not a key of the tenant"
1125        );
1126        assert!(!revoked(&f, operator.id), "the operator's key still works");
1127    }
1128
1129    #[test]
1130    fn a_key_nobody_has_is_not_found() {
1131        let f = fixture();
1132        let (t, who) = administered(&f, "acme");
1133        let unknown = KeyId::generate();
1134        assert_eq!(
1135            f.tenants.revoke_tenant_key(who, t, unknown),
1136            Err(TenantError::NotFound),
1137            "no such key"
1138        );
1139        assert_eq!(
1140            last(&f, "key_revoke"),
1141            (json!(unknown.to_string()), json!(404)),
1142            "recorded"
1143        );
1144    }
1145
1146    #[test]
1147    fn keys_of_a_tenant_that_is_not_there_are_not_found() {
1148        let f = fixture();
1149        let gone = TenantId::generate();
1150        let who = Actor::Key(KeyId::generate());
1151        assert!(
1152            matches!(
1153                f.tenants
1154                    .create_tenant_key(who, gone, scopes(&[Scope::Read]), "x"),
1155                Err(TenantError::NotFound)
1156            ),
1157            "made"
1158        );
1159        assert_eq!(
1160            f.tenants.tenant_keys(who, gone).map(|keys| keys.len()),
1161            Err(TenantError::NotFound),
1162            "listed"
1163        );
1164    }
1165
1166    #[test]
1167    fn a_key_for_a_tenant_being_removed_is_refused() {
1168        let f = fixture();
1169        let (t, who) = administered(&f, "acme");
1170        f.tenants.stores().insert(t, Slot::Closing);
1171        assert!(
1172            matches!(
1173                f.tenants
1174                    .create_tenant_key(who, t, scopes(&[Scope::Read]), "late"),
1175                Err(TenantError::Closing)
1176            ),
1177            "while the tenant closes"
1178        );
1179    }
1180
1181    // What must be refused: memberships.
1182
1183    #[test]
1184    fn memberships_of_a_tenant_that_is_not_there_are_not_found() {
1185        let f = fixture();
1186        let gone = TenantId::generate();
1187        let who = Actor::Key(KeyId::generate());
1188        assert_eq!(
1189            f.tenants.members(who, gone).map(|members| members.len()),
1190            Err(TenantError::NotFound),
1191            "no tenant"
1192        );
1193        assert_eq!(
1194            last(&f, "membership_list"),
1195            (json!(gone.to_string()), json!(404)),
1196            "recorded"
1197        );
1198    }
1199
1200    #[test]
1201    fn a_list_whose_record_cannot_be_written_is_not_answered() {
1202        let f = fixture();
1203        let (t, who) = administered(&f, "acme");
1204        member(&f, "Reader", Some(t), &[Role::Reader]);
1205        f.tenants.break_audit();
1206        assert_eq!(
1207            f.tenants.members(who, t).map(|members| members.len()),
1208            Err(TenantError::AuditFailed),
1209            "memberships"
1210        );
1211        assert_eq!(
1212            f.tenants.tenant_keys(who, t).map(|keys| keys.len()),
1213            Err(TenantError::AuditFailed),
1214            "keys"
1215        );
1216    }
1217
1218    // Limits and odd inputs.
1219
1220    #[test]
1221    fn an_empty_change_is_answered_and_recorded_with_no_name() {
1222        let f = fixture();
1223        let (t, who) = administered(&f, "acme");
1224        assert_eq!(
1225            f.tenants.set_settings(who, t, &json!({})),
1226            Ok(Settings::default()),
1227            "nothing to change"
1228        );
1229        assert_eq!(stored(&f, t), vec![], "no row");
1230        assert_eq!(
1231            last(&f, "settings_set"),
1232            (json!(t.to_string()), json!(200)),
1233            "the tenant alone as the target"
1234        );
1235    }
1236
1237    #[test]
1238    fn removing_a_tenant_removes_its_settings() {
1239        let f = fixture();
1240        let (a, who_a) = administered(&f, "acme");
1241        let (b, who_b) = administered(&f, "beta");
1242        f.tenants
1243            .set_settings(who_a, a, &json!({ "masking.reader": false }))
1244            .expect("acme's");
1245        f.tenants
1246            .set_settings(who_b, b, &json!({ "masking.legal": false }))
1247            .expect("beta's");
1248        f.tenants.remove(CLI, a, Removal::Empty).expect("removed");
1249        assert_eq!(stored(&f, a), vec![], "none of acme's rows is left");
1250        assert_eq!(
1251            stored(&f, b),
1252            pairs(&[("masking.legal", "false")]),
1253            "beta's stay"
1254        );
1255    }
1256
1257    #[test]
1258    fn with_no_cap_a_key_may_hold_all_five_scopes_of_a_tenants_data() {
1259        let f = fixture();
1260        let (t, who) = administered(&f, "acme");
1261        let all = scopes(&[
1262            Scope::Write,
1263            Scope::Read,
1264            Scope::Delete,
1265            Scope::Legal,
1266            Scope::Audit,
1267        ]);
1268        let made = f
1269            .tenants
1270            .create_tenant_key(who, t, all, "everything")
1271            .expect("no cap: every tenant role's scope");
1272        let key = f.tenants.stored_key(made.id).expect("read").expect("kept");
1273        assert_eq!(key.scopes, all, "all five");
1274    }
1275
1276    #[test]
1277    fn a_cap_of_the_administrators_role_alone_lets_no_key_be_made() {
1278        let f = fixture();
1279        let (t, who) = administered(&f, "acme");
1280        cap(&f, t, &[Role::TenantAdmin]);
1281        for scope in [
1282            Scope::Write,
1283            Scope::Read,
1284            Scope::Delete,
1285            Scope::Legal,
1286            Scope::Audit,
1287        ] {
1288            assert!(
1289                matches!(
1290                    f.tenants
1291                        .create_tenant_key(who, t, scopes(&[scope]), "none"),
1292                    Err(TenantError::BadScopes)
1293                ),
1294                "{} is outside the cap",
1295                scopes(&[scope])
1296            );
1297        }
1298    }
1299
1300    #[test]
1301    fn a_cap_narrowed_later_leaves_the_keys_made_before_it() {
1302        let f = fixture();
1303        let (t, who) = administered(&f, "acme");
1304        let made = f
1305            .tenants
1306            .create_tenant_key(who, t, scopes(&[Scope::Write]), "producer")
1307            .expect("made with no cap");
1308        cap(&f, t, &[Role::Reader]);
1309        let key = f.tenants.stored_key(made.id).expect("read").expect("kept");
1310        assert_eq!(
1311            (key.scopes, key.revoked),
1312            (scopes(&[Scope::Write]), false),
1313            "the cap bounds new keys; the administrator revokes old ones"
1314        );
1315    }
1316
1317    #[test]
1318    fn the_operator_is_not_bound_by_the_cap_when_it_makes_a_key() {
1319        let f = fixture();
1320        let t = tenant(&f, "acme");
1321        cap(&f, t, &[Role::Reader]);
1322        assert!(
1323            f.tenants
1324                .create_key(CLI, Some(t), scopes(&[Scope::Write]), "producer")
1325                .is_ok(),
1326            "the cap bounds the tenant's administrator, not the operator"
1327        );
1328    }
1329
1330    #[test]
1331    fn an_administrator_may_revoke_its_own_key() {
1332        let f = fixture();
1333        let t = tenant(&f, "acme");
1334        let (key, who) = administrator(&f, t);
1335        assert_eq!(f.tenants.revoke_tenant_key(who, t, key), Ok(()), "revoked");
1336        assert!(revoked(&f, key), "its next request is refused");
1337    }
1338
1339    #[test]
1340    fn revoking_a_key_again_changes_nothing_and_is_not_an_error() {
1341        let f = fixture();
1342        let (t, who) = administered(&f, "acme");
1343        let made = f
1344            .tenants
1345            .create_tenant_key(who, t, scopes(&[Scope::Read]), "old")
1346            .expect("made");
1347        assert_eq!(f.tenants.revoke_tenant_key(who, t, made.id), Ok(()), "once");
1348        assert_eq!(
1349            f.tenants.revoke_tenant_key(who, t, made.id),
1350            Ok(()),
1351            "twice"
1352        );
1353        assert!(revoked(&f, made.id), "still revoked");
1354    }
1355
1356    #[test]
1357    fn a_tenant_with_no_membership_lists_none() {
1358        let f = fixture();
1359        let (t, who) = administered(&f, "acme");
1360        assert_eq!(
1361            f.tenants.members(who, t).map(|members| members.len()),
1362            Ok(0),
1363            "an empty list, not an error"
1364        );
1365    }
1366
1367    #[test]
1368    fn memberships_elsewhere_are_not_listed() {
1369        let f = fixture();
1370        let (a, who) = administered(&f, "acme");
1371        let (b, _) = administered(&f, "beta");
1372        member(&f, "Theirs", Some(b), &[Role::Reader]);
1373        member(&f, "Operator", None, &[Role::Operator]);
1374        let ours = member(&f, "Ours", Some(a), &[Role::Reader]);
1375        let listed: Vec<UserId> = f
1376            .tenants
1377            .members(who, a)
1378            .expect("listed")
1379            .iter()
1380            .map(|m| m.user)
1381            .collect();
1382        assert_eq!(listed, [ours], "acme's member alone");
1383    }
1384
1385    #[test]
1386    fn a_deactivated_user_is_no_longer_a_member() {
1387        let f = fixture();
1388        let (t, who) = administered(&f, "acme");
1389        let user = member(&f, "Leaver", Some(t), &[Role::Reader]);
1390        f.tenants.deactivate_user(CLI, user).expect("deactivated");
1391        assert_eq!(
1392            f.tenants.members(who, t).map(|members| members.len()),
1393            Ok(0),
1394            "deactivation removed the membership"
1395        );
1396    }
1397
1398    #[test]
1399    fn a_user_in_two_tenants_is_listed_in_each_with_that_tenants_roles() {
1400        let f = fixture();
1401        let (a, who_a) = administered(&f, "acme");
1402        let (b, who_b) = administered(&f, "beta");
1403        let user = member(&f, "Both", Some(a), &[Role::Reader]);
1404        f.tenants
1405            .grant_membership(CLI, user, Some(b), Roles::of(&[Role::Legal]))
1406            .expect("granted in beta too");
1407        let roles_in = |who, t| f.tenants.members(who, t).expect("listed")[0].roles;
1408        assert_eq!(roles_in(who_a, a), Roles::of(&[Role::Reader]), "in acme");
1409        assert_eq!(roles_in(who_b, b), Roles::of(&[Role::Legal]), "in beta");
1410    }
1411
1412    #[test]
1413    fn scopes_within_another_set_are_told_from_those_outside_it() {
1414        let held = scopes(&[Scope::Read, Scope::Write]);
1415        assert!(scopes(&[Scope::Read]).within(held), "one of two");
1416        assert!(held.within(held), "a set is within itself");
1417        assert!(
1418            Scopes::default().within(held),
1419            "the empty set is within any"
1420        );
1421        assert!(
1422            !scopes(&[Scope::Read, Scope::Legal]).within(held),
1423            "one scope outside"
1424        );
1425        assert!(!held.within(Scopes::default()), "nothing is within none");
1426    }
1427
1428    #[test]
1429    fn the_scopes_a_cap_lets_a_key_hold_never_include_tenant_admin() {
1430        assert_eq!(
1431            key_scopes(None),
1432            scopes(&[
1433                Scope::Write,
1434                Scope::Read,
1435                Scope::Delete,
1436                Scope::Legal,
1437                Scope::Audit
1438            ]),
1439            "no cap: the five scopes of a tenant's data"
1440        );
1441        assert_eq!(
1442            key_scopes(Some(Roles::of(&[Role::Auditor, Role::TenantAdmin]))),
1443            scopes(&[Scope::Audit]),
1444            "a cap's scopes, less tenant_admin"
1445        );
1446        assert_eq!(
1447            key_scopes(Some(Roles::of(&[Role::TenantAdmin]))),
1448            Scopes::default(),
1449            "none"
1450        );
1451    }
1452}