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