Skip to main content

vcon_server/tenants/
keys.rs

1//! The access keys in server.sqlite: made, listed and revoked here, and
2//! read by `access` on every request.
3
4use time::OffsetDateTime;
5use time::format_description::well_known::Rfc3339;
6
7use super::{KeyLife, RTx, Slot, TenantError, Tenants, commit};
8use crate::access::{self, Scope, Scopes};
9use crate::audit::{Action, Actor, Entry};
10use crate::backend::KeyRow;
11use crate::clock::{from_nanos, nanos};
12use crate::ids::{KeyId, TenantId};
13
14/// A key as `list_keys` shows it: never its token or hash.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct KeyInfo {
17    pub id: KeyId,
18    /// None for an operator key.
19    pub tenant: Option<TenantId>,
20    pub scopes: Scopes,
21    pub label: String,
22    pub created_at: OffsetDateTime,
23    pub revoked_at: Option<OffsetDateTime>,
24    /// From when the key is refused; None for a key with no expiry.
25    pub expires_at: Option<OffsetDateTime>,
26    /// The minute of the key's latest accepted request that was written;
27    /// None for a key no request has used.
28    pub last_used_at: Option<OffsetDateTime>,
29}
30
31impl KeyInfo {
32    /// The key as the admin API and the command line show it, never its
33    /// token: id, tenant (null for an operator key), scopes, label and
34    /// times in RFC 3339, with null for a time the key does not have. None
35    /// when a time cannot be written so.
36    pub fn to_json(&self) -> Option<serde_json::Value> {
37        let time = |at: OffsetDateTime| at.format(&Rfc3339).ok();
38        let optional = |at: Option<OffsetDateTime>| match at {
39            Some(at) => time(at).map(Some),
40            None => Some(None),
41        };
42        Some(serde_json::json!({
43            "id": self.id.to_string(),
44            "tenant": self.tenant.map(|t| t.to_string()),
45            "scopes": self.scopes.names(),
46            "label": self.label,
47            "created_at": time(self.created_at)?,
48            "revoked_at": optional(self.revoked_at)?,
49            "expires_at": optional(self.expires_at)?,
50            "last_used_at": optional(self.last_used_at)?,
51        }))
52    }
53}
54
55/// A key's row as a list shows it. Scopes or a time that do not read back
56/// are damage, not none.
57pub(super) fn key_info(row: KeyRow) -> Result<KeyInfo, TenantError> {
58    let time = |at| from_nanos(at).ok_or(TenantError::Io);
59    Ok(KeyInfo {
60        id: row.id,
61        tenant: row.tenant,
62        scopes: Scopes::parse(&row.scopes).ok_or(TenantError::Io)?,
63        label: row.label,
64        created_at: time(row.created_at)?,
65        revoked_at: row.revoked_at.map(time).transpose()?,
66        expires_at: row.expires_at.map(time).transpose()?,
67        last_used_at: row.last_used_at.map(time).transpose()?,
68    })
69}
70
71/// A key just made. Its token is shown this once and never stored.
72#[derive(Debug)]
73pub struct NewKey {
74    pub id: KeyId,
75    pub token: String,
76    /// From when the key is refused; None for a key with no expiry.
77    pub expires_at: Option<OffsetDateTime>,
78}
79
80impl NewKey {
81    /// The key as the answer that makes it shows it: its id, its token
82    /// and its expiry in RFC 3339, or null for no expiry. None when the
83    /// time cannot be written so.
84    pub fn to_json(&self) -> Option<serde_json::Value> {
85        let expires_at = match self.expires_at {
86            Some(at) => Some(at.format(&Rfc3339).ok()?),
87            None => None,
88        };
89        Some(serde_json::json!({
90            "id": self.id.to_string(),
91            "token": self.token,
92            "expires_at": expires_at,
93        }))
94    }
95}
96
97/// A key as `access` checks it.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub(crate) struct StoredKey {
100    pub(crate) hash: Vec<u8>,
101    pub(crate) tenant: Option<TenantId>,
102    pub(crate) scopes: Scopes,
103    pub(crate) revoked: bool,
104    pub(crate) expires_at: Option<i64>,
105    pub(crate) last_used_at: Option<i64>,
106}
107
108impl Tenants {
109    /// Counts a failed check of a token. A known key's failures are
110    /// counted under its id in its tenant's log, or the admin log for an
111    /// operator key or a tenant whose log cannot be opened. Any other
112    /// failure is counted with no actor in the admin log, so tokens made up
113    /// one after another share a record. A failure to count leaves the
114    /// request refused all the same.
115    pub(crate) fn count_auth_failure(&self, known: Option<(KeyId, Option<TenantId>)>) {
116        self.count_refusal(Action::AuthFailed, 401, known);
117    }
118
119    /// Counts a valid key refused by a listener that serves the other
120    /// kind of key, where [`Tenants::count_auth_failure`] counts a failed
121    /// check: under the key's id, in its tenant's log, or the admin log for
122    /// an operator key or a tenant whose log cannot be opened.
123    pub(crate) fn count_wrong_listener(&self, key: KeyId, tenant: Option<TenantId>) {
124        self.count_refusal(Action::WrongListener, 403, Some((key, tenant)));
125    }
126
127    /// Counts one time that a listener found every one of its places held
128    /// (`limits.connections`), in the admin log: action `listener_full`,
129    /// no actor, the listener's configuration key (`listen` or
130    /// `operator.listen`) as the target, and no status: the record is of
131    /// a listener's state and answers no request. A failure to count changes
132    /// nothing for the listener.
133    pub(crate) fn count_listener_full(&self, listener: &str) {
134        let _ = self.count_admin(&Entry {
135            actor: Actor::Unparsed,
136            action: Action::ListenerFull,
137            target: Some(listener.to_owned()),
138            version: None,
139            status: crate::audit::NO_ANSWER,
140        });
141    }
142
143    /// Counts one report of a content-security-policy violation sent to
144    /// the console, in the admin log: action `csp_report`, no actor (a
145    /// browser sends a report with no key), no target, and the status that
146    /// answered it. Nothing of the report is kept. A failure to count
147    /// changes nothing for the sender.
148    pub(crate) fn count_csp_report(&self, status: u16) {
149        let _ = self.count_admin(&Entry {
150            actor: Actor::Unparsed,
151            action: Action::CspReport,
152            target: None,
153            version: None,
154            status,
155        });
156    }
157
158    /// Counts the reports the listener refused in the minute of `minute`
159    /// because it had taken its number for that minute
160    /// (`limits.csp_reports`): `refused` of them, in one write, as action
161    /// `csp_report` with status 429.
162    pub(crate) fn count_csp_refused(&self, minute: time::OffsetDateTime, refused: u64) {
163        let entry = Entry {
164            actor: Actor::Unparsed,
165            action: Action::CspReport,
166            target: None,
167            version: None,
168            status: 429,
169        };
170        let _ = self.count_admin_many(&entry, minute, refused);
171    }
172
173    /// Counts a request refused before any route saw it, as `action` with
174    /// `status`.
175    fn count_refusal(&self, action: Action, status: u16, known: Option<(KeyId, Option<TenantId>)>) {
176        let entry = |actor| Entry {
177            actor,
178            action,
179            target: None,
180            version: None,
181            status,
182        };
183        if let Some((id, Some(tenant))) = known
184            && self
185                .store(tenant)
186                .is_ok_and(|store| store.count(&entry(Actor::Key(id))).is_ok())
187        {
188            return;
189        }
190        let actor = known.map_or(Actor::Unparsed, |(id, _)| Actor::Key(id));
191        let _ = self.count_admin(&entry(actor));
192    }
193
194    /// The key with this id, read afresh on every call, so a revocation
195    /// counts from the next request. Nothing is recorded here; `access`
196    /// records the outcome.
197    pub(crate) fn stored_key(&self, id: KeyId) -> Result<Option<StoredKey>, TenantError> {
198        let row = self.registry.snapshot()?.key(id)?;
199        row.map(|row| {
200            Ok(StoredKey {
201                hash: row.token_hash,
202                tenant: row.tenant,
203                // Scopes that do not read back are damage, not none.
204                scopes: Scopes::parse(&row.scopes).ok_or(TenantError::Io)?,
205                revoked: row.revoked_at.is_some(),
206                expires_at: row.expires_at,
207                last_used_at: row.last_used_at,
208            })
209        })
210        .transpose()
211    }
212
213    /// Makes a key with the default life, as [`Tenants::create_key_for`]
214    /// makes one with [`KeyLife::Default`].
215    pub fn create_key(
216        &self,
217        who: Actor,
218        tenant: Option<TenantId>,
219        scopes: Scopes,
220        label: &str,
221    ) -> Result<NewKey, TenantError> {
222        self.create_key_for(who, tenant, scopes, label, KeyLife::Default)
223    }
224
225    /// Makes a key. A tenant key holds any of write, read, delete, legal
226    /// and audit; a key with no tenant is an operator key, holds only admin,
227    /// and only the command line may make one. The key expires as `life`
228    /// says; a life the key cannot have is refused after its scopes are.
229    pub fn create_key_for(
230        &self,
231        who: Actor,
232        tenant: Option<TenantId>,
233        scopes: Scopes,
234        label: &str,
235        life: KeyLife,
236    ) -> Result<NewKey, TenantError> {
237        let entry = |status, target: Option<String>| Entry {
238            actor: who,
239            action: Action::KeyCreate,
240            target,
241            version: None,
242            status,
243        };
244        let shape = match tenant {
245            None if who != Actor::Cli => Some((403, TenantError::CliOnly)),
246            None if scopes != Scopes::of(&[Scope::Admin]) => Some((422, TenantError::BadScopes)),
247            Some(_) if scopes.is_empty() || scopes.contains(Scope::Admin) => {
248                Some((422, TenantError::BadScopes))
249            }
250            _ => None,
251        };
252        let expires_at = life.expires_at(nanos(self.clock.now()), self.no_expiry_allowed());
253        let shape = shape.or(expires_at.err().map(|refused| (422, refused)));
254        let closing = tenant.is_some_and(|t| matches!(self.stores().get(&t), Some(Slot::Closing)));
255        let mut tx = self.registry.immediate()?;
256        let refused = match (shape, tenant) {
257            (Some(refused), _) => Some(refused),
258            (None, Some(t)) if tx.tenant(t)?.is_none() => Some((404, TenantError::NotFound)),
259            (None, Some(_)) if closing => Some((503, TenantError::Closing)),
260            _ => None,
261        };
262        if let Some((status, error)) = refused {
263            self.record(&mut tx, &entry(status, tenant.map(|t| t.to_string())))?;
264            commit(tx)?;
265            return Err(error);
266        }
267        let new = self.insert_key(&mut tx, tenant, scopes, label, life)?;
268        let made = entry(201, Some(new.id.to_string()));
269        self.record(&mut tx, &made)?;
270        // The copy opens the tenant's Store, which reads the registry.
271        commit(tx)?;
272        if let Some(t) = tenant {
273            self.copy_to_tenant(t, &made)?;
274        }
275        Ok(new)
276    }
277
278    /// Writes the row of a new key, made now, and gives its id and token.
279    /// Whether the key may be made is its caller's rule, but for its life:
280    /// a life the key cannot have is [`TenantError::BadExpiry`] here, with
281    /// nothing written.
282    pub(super) fn insert_key(
283        &self,
284        tx: &mut RTx<'_>,
285        tenant: Option<TenantId>,
286        scopes: Scopes,
287        label: &str,
288        life: KeyLife,
289    ) -> Result<NewKey, TenantError> {
290        let now = nanos(self.clock.now());
291        let expires_at = life.expires_at(now, self.no_expiry_allowed())?;
292        let (id, token) = access::new_token();
293        tx.insert_key(&KeyRow {
294            id,
295            tenant,
296            token_hash: access::token_hash(&token).to_vec(),
297            scopes: scopes.to_string(),
298            label: label.to_owned(),
299            created_at: now,
300            revoked_at: None,
301            expires_at,
302            last_used_at: None,
303        })?;
304        Ok(NewKey {
305            id,
306            token,
307            expires_at: expires_at
308                .map(|at| from_nanos(at).ok_or(TenantError::Io))
309                .transpose()?,
310        })
311    }
312
313    /// The keys of one tenant, or with None every key, oldest first.
314    pub fn list_keys(
315        &self,
316        who: Actor,
317        tenant: Option<TenantId>,
318    ) -> Result<Vec<KeyInfo>, TenantError> {
319        let entry = |status| Entry {
320            actor: who,
321            action: Action::KeyList,
322            target: tenant.map(|t| t.to_string()),
323            version: None,
324            status,
325        };
326        let mut tx = self.registry.immediate()?;
327        if let Some(t) = tenant
328            && tx.tenant(t)?.is_none()
329        {
330            self.record(&mut tx, &entry(404))?;
331            commit(tx)?;
332            return Err(TenantError::NotFound);
333        }
334        let keys = tx
335            .keys(tenant)?
336            .into_iter()
337            .map(key_info)
338            .collect::<Result<Vec<_>, TenantError>>()?;
339        self.record(&mut tx, &entry(200))?;
340        commit(tx)?;
341        Ok(keys)
342    }
343
344    /// Revokes a key; revoking it again changes nothing.
345    pub fn revoke_key(&self, who: Actor, id: KeyId) -> Result<(), TenantError> {
346        let mut tx = self.registry.immediate()?;
347        // The key's tenant, if the key is known: None for an operator key.
348        let found = tx.key(id)?.map(|row| row.tenant);
349        if found.is_some() {
350            tx.revoke_key(id, nanos(self.clock.now()))?;
351        }
352        let entry = Entry {
353            actor: who,
354            action: Action::KeyRevoke,
355            target: Some(id.to_string()),
356            version: None,
357            status: if found.is_some() { 204 } else { 404 },
358        };
359        self.record(&mut tx, &entry)?;
360        // The copy opens the tenant's Store, which reads the registry.
361        commit(tx)?;
362        match found {
363            None => Err(TenantError::NotFound),
364            Some(Some(t)) => self.copy_to_tenant(t, &entry),
365            Some(None) => Ok(()),
366        }
367    }
368}
369
370#[cfg(test)]
371mod tests {
372    use rusqlite::types::Value as Sql;
373    use time::macros::datetime;
374
375    use super::*;
376    use crate::access::{self, Scope};
377    use crate::tenants::Removal;
378    use crate::tenants::tests::{Fixture, fixture};
379
380    fn vcon_scopes() -> Scopes {
381        Scopes::of(&[Scope::Write, Scope::Read])
382    }
383
384    fn admin() -> Scopes {
385        Scopes::of(&[Scope::Admin])
386    }
387
388    fn tenant(f: &Fixture, name: &str) -> TenantId {
389        f.tenants.create(Actor::Cli, name, None).expect("made")
390    }
391
392    /// Every value in the key's row, as SQLite holds it.
393    fn row(f: &Fixture, id: KeyId) -> Vec<Sql> {
394        let conn = f.conn();
395        let mut stmt = conn
396            .prepare("SELECT * FROM api_key WHERE id = ?1")
397            .expect("prepare");
398        let columns = stmt.column_count();
399        stmt.query_row([id.bytes()], |r| {
400            (0..columns).map(|i| r.get::<_, Sql>(i)).collect()
401        })
402        .expect("a row")
403    }
404
405    fn holds(value: &Sql, needle: &[u8]) -> bool {
406        let bytes: &[u8] = match value {
407            Sql::Text(t) => t.as_bytes(),
408            Sql::Blob(b) => b,
409            _ => return false,
410        };
411        bytes.windows(needle.len()).any(|w| w == needle)
412    }
413
414    fn revoked_at(f: &Fixture, id: KeyId) -> Option<i64> {
415        f.conn()
416            .query_row(
417                "SELECT revoked_at FROM api_key WHERE id = ?1",
418                [id.bytes()],
419                |r| r.get(0),
420            )
421            .expect("a row")
422    }
423
424    #[test]
425    fn a_key_is_stored_as_its_hash_and_its_token_is_shown_once() {
426        let f = fixture();
427        let t = tenant(&f, "acme");
428        let key = f
429            .tenants
430            .create_key(Actor::Cli, Some(t), vcon_scopes(), "ingest")
431            .expect("made");
432        assert_eq!(access::parse(&key.token), Ok(key.id));
433        let secret = &key.token[21..];
434        let values = row(&f, key.id);
435        for value in &values {
436            assert!(!holds(value, key.token.as_bytes()), "the token is stored");
437            assert!(!holds(value, secret.as_bytes()), "the secret is stored");
438        }
439        let hash: Vec<u8> = f
440            .conn()
441            .query_row(
442                "SELECT token_hash FROM api_key WHERE id = ?1",
443                [key.id.bytes()],
444                |r| r.get(0),
445            )
446            .expect("a row");
447        assert_eq!(hash, access::token_hash(&key.token));
448        let made = f.admin_records("key_create");
449        assert_eq!(made.len(), 1);
450        assert_eq!(made[0]["actor"], "cli");
451        assert_eq!(made[0]["target"], key.id.to_string());
452        assert_eq!(made[0]["status"], 201);
453    }
454
455    #[test]
456    fn an_operator_key_holds_only_admin_and_only_the_command_line_makes_one() {
457        let f = fixture();
458        let key = f
459            .tenants
460            .create_key(Actor::Cli, None, admin(), "operator")
461            .expect("made");
462        let listed = f.tenants.list_keys(Actor::Cli, None).expect("listed");
463        assert_eq!(listed[0].id, key.id);
464        assert_eq!(listed[0].tenant, None);
465        assert_eq!(listed[0].scopes, admin());
466
467        let api = Actor::Key(key.id);
468        assert_eq!(
469            f.tenants.create_key(api, None, admin(), "another").err(),
470            Some(TenantError::CliOnly)
471        );
472        for scopes in [
473            Scopes::of(&[]),
474            Scopes::of(&[Scope::Admin, Scope::Read]),
475            vcon_scopes(),
476        ] {
477            assert_eq!(
478                f.tenants.create_key(Actor::Cli, None, scopes, "x").err(),
479                Some(TenantError::BadScopes),
480                "{scopes}"
481            );
482        }
483        let statuses: Vec<_> = f
484            .admin_records("key_create")
485            .into_iter()
486            .map(|r| r["status"].clone())
487            .collect();
488        assert_eq!(statuses, [201, 403, 422, 422, 422]);
489        assert_eq!(
490            f.tenants.list_keys(Actor::Cli, None).map(|k| k.len()),
491            Ok(1)
492        );
493    }
494
495    #[test]
496    fn a_tenant_key_may_hold_tenant_admin_alone_or_with_the_others() {
497        let f = fixture();
498        let t = tenant(&f, "acme");
499        for scopes in [
500            Scopes::of(&[Scope::TenantAdmin]),
501            Scopes::of(&[Scope::Read, Scope::TenantAdmin]),
502            Scopes::of(&[
503                Scope::Write,
504                Scope::Read,
505                Scope::Delete,
506                Scope::Legal,
507                Scope::Audit,
508                Scope::TenantAdmin,
509            ]),
510        ] {
511            let key = f
512                .tenants
513                .create_key(Actor::Cli, Some(t), scopes, "admin")
514                .unwrap_or_else(|e| panic!("{scopes}: {e:?}"));
515            let listed = f.tenants.list_keys(Actor::Cli, Some(t)).expect("listed");
516            let row = listed.iter().find(|k| k.id == key.id).expect("the new key");
517            assert_eq!(row.scopes, scopes, "the scopes read back");
518        }
519    }
520
521    #[test]
522    fn an_operator_key_never_holds_tenant_admin() {
523        let f = fixture();
524        for scopes in [
525            Scopes::of(&[Scope::TenantAdmin]),
526            Scopes::of(&[Scope::Admin, Scope::TenantAdmin]),
527        ] {
528            assert_eq!(
529                f.tenants.create_key(Actor::Cli, None, scopes, "x").err(),
530                Some(TenantError::BadScopes),
531                "{scopes}"
532            );
533        }
534        assert_eq!(
535            f.tenants.list_keys(Actor::Cli, None).map(|k| k.len()),
536            Ok(0),
537            "no operator key was made"
538        );
539    }
540
541    #[test]
542    fn tenant_admin_does_not_let_a_tenant_key_hold_admin() {
543        let f = fixture();
544        let t = tenant(&f, "acme");
545        assert_eq!(
546            f.tenants
547                .create_key(
548                    Actor::Cli,
549                    Some(t),
550                    Scopes::of(&[Scope::TenantAdmin, Scope::Admin]),
551                    "x"
552                )
553                .err(),
554            Some(TenantError::BadScopes),
555            "admin stays an operator key's"
556        );
557    }
558
559    #[test]
560    fn a_tenant_key_holds_only_vcon_scopes() {
561        let f = fixture();
562        let t = tenant(&f, "acme");
563        for scopes in [
564            Scopes::of(&[]),
565            admin(),
566            Scopes::of(&[Scope::Write, Scope::Admin]),
567        ] {
568            assert_eq!(
569                f.tenants.create_key(Actor::Cli, Some(t), scopes, "x").err(),
570                Some(TenantError::BadScopes),
571                "{scopes}"
572            );
573        }
574        let all = Scopes::of(&[
575            Scope::Write,
576            Scope::Read,
577            Scope::Delete,
578            Scope::Legal,
579            Scope::Audit,
580        ]);
581        assert!(
582            f.tenants
583                .create_key(Actor::Cli, Some(t), all, "all")
584                .is_ok()
585        );
586    }
587
588    #[test]
589    fn a_key_for_an_unknown_or_closing_tenant_is_refused() {
590        let f = fixture();
591        let unknown = TenantId::generate();
592        assert_eq!(
593            f.tenants
594                .create_key(Actor::Cli, Some(unknown), vcon_scopes(), "x")
595                .err(),
596            Some(TenantError::NotFound)
597        );
598        let t = tenant(&f, "acme");
599        f.tenants.drain(t).expect("drains");
600        assert_eq!(
601            f.tenants
602                .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
603                .err(),
604            Some(TenantError::Closing)
605        );
606        let refused = f.admin_records("key_create");
607        assert_eq!(refused[0]["status"], 404);
608        assert_eq!(refused[0]["target"], unknown.to_string());
609        assert_eq!(refused[1]["status"], 503);
610        assert_eq!(f.count_keys(), 0);
611    }
612
613    #[test]
614    fn a_key_whose_record_fails_is_not_made() {
615        let f = fixture();
616        let t = tenant(&f, "acme");
617        f.conn()
618            .execute_batch(
619                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
620                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
621            )
622            .expect("trigger");
623        assert_eq!(
624            f.tenants
625                .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
626                .err(),
627            Some(TenantError::AuditFailed)
628        );
629        assert_eq!(f.count_keys(), 0);
630    }
631
632    #[test]
633    fn keys_are_listed_per_tenant_or_all_oldest_first() {
634        let f = fixture();
635        let (a, b) = (tenant(&f, "a"), tenant(&f, "b"));
636        let first = f
637            .tenants
638            .create_key(Actor::Cli, Some(a), vcon_scopes(), "first")
639            .expect("made");
640        f.clock.set(datetime!(2026-10-23 13:00 UTC));
641        let other = f
642            .tenants
643            .create_key(Actor::Cli, Some(b), vcon_scopes(), "other")
644            .expect("made");
645        f.clock.set(datetime!(2026-10-23 14:00 UTC));
646        let second = f
647            .tenants
648            .create_key(Actor::Cli, Some(a), Scopes::of(&[Scope::Legal]), "second")
649            .expect("made");
650        f.tenants
651            .revoke_key(Actor::Cli, second.id)
652            .expect("revoked");
653
654        let a_keys = f.tenants.list_keys(Actor::Cli, Some(a)).expect("listed");
655        assert_eq!(
656            a_keys,
657            [
658                KeyInfo {
659                    id: first.id,
660                    tenant: Some(a),
661                    scopes: vcon_scopes(),
662                    label: "first".to_owned(),
663                    created_at: datetime!(2026-10-23 12:00 UTC),
664                    revoked_at: None,
665                    expires_at: Some(datetime!(2027-01-21 12:00 UTC)),
666                    last_used_at: None,
667                },
668                KeyInfo {
669                    id: second.id,
670                    tenant: Some(a),
671                    scopes: Scopes::of(&[Scope::Legal]),
672                    label: "second".to_owned(),
673                    created_at: datetime!(2026-10-23 14:00 UTC),
674                    revoked_at: Some(datetime!(2026-10-23 14:00 UTC)),
675                    expires_at: Some(datetime!(2027-01-21 14:00 UTC)),
676                    last_used_at: None,
677                },
678            ]
679        );
680        let all: Vec<KeyId> = f
681            .tenants
682            .list_keys(Actor::Cli, None)
683            .expect("listed")
684            .into_iter()
685            .map(|k| k.id)
686            .collect();
687        assert_eq!(all, [first.id, other.id, second.id]);
688        assert_eq!(
689            f.tenants
690                .list_keys(Actor::Cli, Some(TenantId::generate()))
691                .err(),
692            Some(TenantError::NotFound)
693        );
694        let lists = f.admin_records("key_list");
695        let statuses: Vec<_> = lists.iter().map(|r| r["status"].clone()).collect();
696        assert_eq!(statuses, [200, 200, 404]);
697        assert_eq!(lists[0]["target"], a.to_string());
698        assert_eq!(lists[1]["target"], serde_json::Value::Null);
699    }
700
701    #[test]
702    fn a_stored_scope_that_does_not_read_back_is_damage() {
703        let f = fixture();
704        let t = tenant(&f, "acme");
705        let key = f
706            .tenants
707            .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
708            .expect("made");
709        f.conn()
710            .execute(
711                "UPDATE api_key SET scopes = 'owner' WHERE id = ?1",
712                [key.id.bytes()],
713            )
714            .expect("damage");
715        assert_eq!(
716            f.tenants.list_keys(Actor::Cli, None).err(),
717            Some(TenantError::Io)
718        );
719    }
720
721    #[test]
722    fn a_key_is_revoked_once_and_an_unknown_one_is_not_found() {
723        let f = fixture();
724        let t = tenant(&f, "acme");
725        let key = f
726            .tenants
727            .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
728            .expect("made");
729        f.clock.set(datetime!(2026-10-23 13:00 UTC));
730        f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
731        let first = revoked_at(&f, key.id);
732        assert_eq!(
733            first,
734            Some(crate::clock::nanos(datetime!(2026-10-23 13:00 UTC))),
735            "revoked at the time of the revocation"
736        );
737        f.clock.set(datetime!(2026-10-23 14:00 UTC));
738        f.tenants
739            .revoke_key(Actor::Cli, key.id)
740            .expect("again, no change");
741        assert_eq!(revoked_at(&f, key.id), first, "the first time stands");
742        let unknown = KeyId::generate();
743        assert_eq!(
744            f.tenants.revoke_key(Actor::Cli, unknown),
745            Err(TenantError::NotFound)
746        );
747        let records = f.admin_records("key_revoke");
748        let statuses: Vec<_> = records.iter().map(|r| r["status"].clone()).collect();
749        assert_eq!(statuses, [204, 204, 404]);
750        assert_eq!(records[0]["target"], key.id.to_string());
751        assert_eq!(records[2]["target"], unknown.to_string());
752    }
753
754    fn tenant_records(f: &Fixture, t: TenantId, action: &str) -> Vec<serde_json::Value> {
755        crate::audit::testing::exported(&f.tenant_catalog(t), None)
756            .into_iter()
757            .filter(|r| r["action"] == action)
758            .collect()
759    }
760
761    #[test]
762    fn a_tenant_key_made_or_revoked_is_recorded_in_its_tenants_log_too() {
763        let f = fixture();
764        let t = tenant(&f, "acme");
765        let key = f
766            .tenants
767            .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
768            .expect("made");
769        f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
770        let made = tenant_records(&f, t, "key_create");
771        assert_eq!(made.len(), 1);
772        assert_eq!(made[0]["actor"], "cli");
773        assert_eq!(made[0]["target"], key.id.to_string());
774        assert_eq!(made[0]["status"], 201);
775        let revoked = tenant_records(&f, t, "key_revoke");
776        assert_eq!(revoked.len(), 1);
777        assert_eq!(revoked[0]["target"], key.id.to_string());
778        assert_eq!(revoked[0]["status"], 204);
779
780        let operator = f
781            .tenants
782            .create_key(Actor::Cli, None, admin(), "op")
783            .expect("made");
784        f.tenants
785            .revoke_key(Actor::Cli, operator.id)
786            .expect("revoked");
787        assert_eq!(tenant_records(&f, t, "key_create").len(), 1, "only its own");
788        let refused = f
789            .tenants
790            .create_key(Actor::Cli, Some(t), admin(), "x")
791            .err();
792        assert_eq!(refused, Some(TenantError::BadScopes));
793        assert_eq!(
794            tenant_records(&f, t, "key_create").len(),
795            1,
796            "a refusal stays in the admin log"
797        );
798    }
799
800    /// The change commits with its admin record; a failed copy in the
801    /// tenant's log leaves it standing and answers AuditFailed.
802    #[test]
803    fn a_key_change_whose_tenant_copy_fails_stands() {
804        let f = fixture();
805        let t = tenant(&f, "acme");
806        f.tenant_catalog(t)
807            .execute_batch(
808                "CREATE TRIGGER dead BEFORE INSERT ON audit
809                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
810            )
811            .expect("trigger");
812        assert_eq!(
813            f.tenants
814                .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
815                .err(),
816            Some(TenantError::AuditFailed)
817        );
818        let keys = f.tenants.list_keys(Actor::Cli, Some(t)).expect("listed");
819        assert_eq!(keys.len(), 1, "the key stands");
820        assert_eq!(
821            f.tenants.revoke_key(Actor::Cli, keys[0].id),
822            Err(TenantError::AuditFailed)
823        );
824        assert!(
825            revoked_at(&f, keys[0].id).is_some(),
826            "the revocation stands"
827        );
828    }
829
830    #[test]
831    fn removing_a_tenant_revokes_its_keys_in_the_same_transaction() {
832        let f = fixture();
833        let (a, b) = (tenant(&f, "a"), tenant(&f, "b"));
834        let mine: Vec<KeyId> = (0..2)
835            .map(|_| {
836                f.tenants
837                    .create_key(Actor::Cli, Some(a), vcon_scopes(), "a")
838                    .expect("made")
839                    .id
840            })
841            .collect();
842        let theirs = f
843            .tenants
844            .create_key(Actor::Cli, Some(b), vcon_scopes(), "b")
845            .expect("made")
846            .id;
847        let operator = f
848            .tenants
849            .create_key(Actor::Cli, None, admin(), "op")
850            .expect("made")
851            .id;
852
853        f.conn()
854            .execute_batch(
855                "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
856                 WHEN NEW.action = 'tenant_remove'
857                 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
858            )
859            .expect("trigger");
860        assert_eq!(
861            f.tenants.remove(Actor::Cli, a, Removal::Empty),
862            Err(TenantError::AuditFailed)
863        );
864        for id in &mine {
865            assert_eq!(
866                revoked_at(&f, *id),
867                None,
868                "a failed removal revokes nothing"
869            );
870        }
871        f.conn()
872            .execute_batch("DROP TRIGGER no_audit")
873            .expect("drop trigger");
874
875        f.clock.set(datetime!(2026-10-23 13:00 UTC));
876        f.tenants
877            .remove(Actor::Cli, a, Removal::Empty)
878            .expect("removed");
879        let at = crate::clock::nanos(datetime!(2026-10-23 13:00 UTC));
880        for id in &mine {
881            assert_eq!(revoked_at(&f, *id), Some(at));
882        }
883        assert_eq!(revoked_at(&f, theirs), None);
884        assert_eq!(revoked_at(&f, operator), None);
885    }
886
887    // A listener that is full.
888
889    #[test]
890    fn a_full_listener_is_counted_in_the_admin_log_under_its_configuration_key() {
891        let f = fixture();
892        f.tenants.count_listener_full("listen");
893        let counted = f.admin_records("listener_full");
894        assert_eq!(counted.len(), 1, "{counted:?}");
895        assert_eq!(counted[0]["actor"], "", "no caller: none was taken");
896        assert_eq!(counted[0]["target"], "listen", "the listener's key");
897        assert_eq!(
898            counted[0]["status"],
899            serde_json::Value::Null,
900            "no status: a listener that filled answered no request"
901        );
902        assert_eq!(counted[0]["count"], 1, "one time");
903    }
904
905    #[test]
906    fn the_times_a_listener_was_full_in_one_minute_share_a_record() {
907        let f = fixture();
908        for _ in 0..7 {
909            f.tenants.count_listener_full("listen");
910        }
911        let counted = f.admin_records("listener_full");
912        assert_eq!(counted.len(), 1, "one record for the minute: {counted:?}");
913        assert_eq!(counted[0]["count"], 7, "seven times");
914        assert_eq!(counted[0]["at"], "2026-10-23T12:00:00Z", "the minute");
915    }
916
917    #[test]
918    fn a_listener_full_in_another_minute_has_another_record() {
919        let f = fixture();
920        f.tenants.count_listener_full("listen");
921        f.clock.set(datetime!(2026-10-23 12:01:30 UTC));
922        f.tenants.count_listener_full("listen");
923        f.tenants.count_listener_full("listen");
924        let counts: Vec<_> = f
925            .admin_records("listener_full")
926            .iter()
927            .map(|r| (r["at"].clone(), r["count"].clone()))
928            .collect();
929        assert_eq!(
930            counts,
931            [
932                ("2026-10-23T12:00:00Z".into(), 1.into()),
933                ("2026-10-23T12:01:00Z".into(), 2.into()),
934            ],
935            "a record for each minute"
936        );
937    }
938
939    #[test]
940    fn each_listener_has_a_record_of_its_own() {
941        let f = fixture();
942        f.tenants.count_listener_full("listen");
943        f.tenants.count_listener_full("operator.listen");
944        f.tenants.count_listener_full("operator.listen");
945        let mut counts: Vec<_> = f
946            .admin_records("listener_full")
947            .iter()
948            .map(|r| {
949                (
950                    r["target"].as_str().expect("a target").to_owned(),
951                    r["count"].as_u64().expect("a count"),
952                )
953            })
954            .collect();
955        counts.sort();
956        assert_eq!(
957            counts,
958            [("listen".to_owned(), 1), ("operator.listen".to_owned(), 2)],
959            "each under its own key"
960        );
961    }
962
963    #[test]
964    fn a_full_listener_is_in_no_tenants_log() {
965        let f = fixture();
966        let t = tenant(&f, "acme");
967        f.tenants.count_listener_full("listen");
968        assert_eq!(
969            tenant_records(&f, t, "listener_full"),
970            Vec::<serde_json::Value>::new(),
971            "the listener is the server's, not a tenant's"
972        );
973    }
974
975    #[test]
976    fn a_count_that_cannot_be_written_is_passed_over() {
977        let f = fixture();
978        f.conn()
979            .execute_batch(
980                "CREATE TRIGGER no_audit BEFORE INSERT ON audit
981                 BEGIN SELECT RAISE(ABORT, 'no audit'); END",
982            )
983            .expect("a trigger");
984        // Nothing to assert on but that the call returns.
985        f.tenants.count_listener_full("listen");
986        f.conn()
987            .execute_batch("DROP TRIGGER no_audit")
988            .expect("drop trigger");
989        assert_eq!(f.admin_records("listener_full").len(), 0, "none written");
990        f.tenants.count_listener_full("listen");
991        assert_eq!(f.admin_records("listener_full").len(), 1, "and the next is");
992    }
993
994    impl Fixture {
995        fn count_keys(&self) -> i64 {
996            self.conn()
997                .query_row("SELECT count(*) FROM api_key", [], |r| r.get(0))
998                .expect("count")
999        }
1000    }
1001}