1use time::OffsetDateTime;
5use time::format_description::well_known::Rfc3339;
6
7use super::{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#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct KeyInfo {
17 pub id: KeyId,
18 pub tenant: Option<TenantId>,
20 pub scopes: Scopes,
21 pub label: String,
22 pub created_at: OffsetDateTime,
23 pub revoked_at: Option<OffsetDateTime>,
24}
25
26impl KeyInfo {
27 pub fn to_json(&self) -> Option<serde_json::Value> {
31 let time = |at: OffsetDateTime| at.format(&Rfc3339).ok();
32 let revoked_at = match self.revoked_at {
33 Some(at) => Some(time(at)?),
34 None => None,
35 };
36 Some(serde_json::json!({
37 "id": self.id.to_string(),
38 "tenant": self.tenant.map(|t| t.to_string()),
39 "scopes": self.scopes.names(),
40 "label": self.label,
41 "created_at": time(self.created_at)?,
42 "revoked_at": revoked_at,
43 }))
44 }
45}
46
47#[derive(Debug)]
49pub struct NewKey {
50 pub id: KeyId,
51 pub token: String,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56pub(crate) struct StoredKey {
57 pub(crate) hash: Vec<u8>,
58 pub(crate) tenant: Option<TenantId>,
59 pub(crate) scopes: Scopes,
60 pub(crate) revoked: bool,
61}
62
63impl Tenants {
64 pub(crate) fn count_auth_failure(&self, known: Option<(KeyId, Option<TenantId>)>) {
71 self.count_refusal(Action::AuthFailed, 401, known);
72 }
73
74 pub(crate) fn count_wrong_listener(&self, key: KeyId, tenant: Option<TenantId>) {
79 self.count_refusal(Action::WrongListener, 403, Some((key, tenant)));
80 }
81
82 pub(crate) fn count_listener_full(&self, listener: &str) {
89 let _ = self.count_admin(&Entry {
90 actor: Actor::Unparsed,
91 action: Action::ListenerFull,
92 target: Some(listener.to_owned()),
93 version: None,
94 status: crate::audit::NO_ANSWER,
95 });
96 }
97
98 pub(crate) fn count_csp_report(&self, status: u16) {
104 let _ = self.count_admin(&Entry {
105 actor: Actor::Unparsed,
106 action: Action::CspReport,
107 target: None,
108 version: None,
109 status,
110 });
111 }
112
113 pub(crate) fn count_csp_refused(&self, minute: time::OffsetDateTime, refused: u64) {
118 let entry = Entry {
119 actor: Actor::Unparsed,
120 action: Action::CspReport,
121 target: None,
122 version: None,
123 status: 429,
124 };
125 let _ = self.count_admin_many(&entry, minute, refused);
126 }
127
128 fn count_refusal(&self, action: Action, status: u16, known: Option<(KeyId, Option<TenantId>)>) {
131 let entry = |actor| Entry {
132 actor,
133 action,
134 target: None,
135 version: None,
136 status,
137 };
138 if let Some((id, Some(tenant))) = known
139 && self
140 .store(tenant)
141 .is_ok_and(|store| store.count(&entry(Actor::Key(id))).is_ok())
142 {
143 return;
144 }
145 let actor = known.map_or(Actor::Unparsed, |(id, _)| Actor::Key(id));
146 let _ = self.count_admin(&entry(actor));
147 }
148
149 pub(crate) fn stored_key(&self, id: KeyId) -> Result<Option<StoredKey>, TenantError> {
153 let row = self.registry.snapshot()?.key(id)?;
154 row.map(|row| {
155 Ok(StoredKey {
156 hash: row.token_hash,
157 tenant: row.tenant,
158 scopes: Scopes::parse(&row.scopes).ok_or(TenantError::Io)?,
160 revoked: row.revoked_at.is_some(),
161 })
162 })
163 .transpose()
164 }
165
166 pub fn create_key(
170 &self,
171 who: Actor,
172 tenant: Option<TenantId>,
173 scopes: Scopes,
174 label: &str,
175 ) -> Result<NewKey, TenantError> {
176 let entry = |status, target: Option<String>| Entry {
177 actor: who,
178 action: Action::KeyCreate,
179 target,
180 version: None,
181 status,
182 };
183 let shape = match tenant {
184 None if who != Actor::Cli => Some((403, TenantError::CliOnly)),
185 None if scopes != Scopes::of(&[Scope::Admin]) => Some((422, TenantError::BadScopes)),
186 Some(_) if scopes.is_empty() || scopes.contains(Scope::Admin) => {
187 Some((422, TenantError::BadScopes))
188 }
189 _ => None,
190 };
191 let closing = tenant.is_some_and(|t| matches!(self.stores().get(&t), Some(Slot::Closing)));
192 let mut tx = self.registry.immediate()?;
193 let refused = match (shape, tenant) {
194 (Some(refused), _) => Some(refused),
195 (None, Some(t)) if tx.tenant(t)?.is_none() => Some((404, TenantError::NotFound)),
196 (None, Some(_)) if closing => Some((503, TenantError::Closing)),
197 _ => None,
198 };
199 if let Some((status, error)) = refused {
200 self.record(&mut tx, &entry(status, tenant.map(|t| t.to_string())))?;
201 commit(tx)?;
202 return Err(error);
203 }
204 let (id, token) = access::new_token();
205 tx.insert_key(&KeyRow {
206 id,
207 tenant,
208 token_hash: access::token_hash(&token).to_vec(),
209 scopes: scopes.to_string(),
210 label: label.to_owned(),
211 created_at: nanos(self.clock.now()),
212 revoked_at: None,
213 })?;
214 let made = entry(201, Some(id.to_string()));
215 self.record(&mut tx, &made)?;
216 commit(tx)?;
218 if let Some(t) = tenant {
219 self.copy_to_tenant(t, &made)?;
220 }
221 Ok(NewKey { id, token })
222 }
223
224 pub fn list_keys(
226 &self,
227 who: Actor,
228 tenant: Option<TenantId>,
229 ) -> Result<Vec<KeyInfo>, TenantError> {
230 let entry = |status| Entry {
231 actor: who,
232 action: Action::KeyList,
233 target: tenant.map(|t| t.to_string()),
234 version: None,
235 status,
236 };
237 let mut tx = self.registry.immediate()?;
238 if let Some(t) = tenant
239 && tx.tenant(t)?.is_none()
240 {
241 self.record(&mut tx, &entry(404))?;
242 commit(tx)?;
243 return Err(TenantError::NotFound);
244 }
245 let keys = tx
246 .keys(tenant)?
247 .into_iter()
248 .map(|row| {
249 let time = |at| from_nanos(at).ok_or(TenantError::Io);
250 Ok(KeyInfo {
251 id: row.id,
252 tenant: row.tenant,
253 scopes: Scopes::parse(&row.scopes).ok_or(TenantError::Io)?,
255 label: row.label,
256 created_at: time(row.created_at)?,
257 revoked_at: row.revoked_at.map(time).transpose()?,
258 })
259 })
260 .collect::<Result<Vec<_>, TenantError>>()?;
261 self.record(&mut tx, &entry(200))?;
262 commit(tx)?;
263 Ok(keys)
264 }
265
266 pub fn revoke_key(&self, who: Actor, id: KeyId) -> Result<(), TenantError> {
268 let mut tx = self.registry.immediate()?;
269 let found = tx.key(id)?.map(|row| row.tenant);
271 if found.is_some() {
272 tx.revoke_key(id, nanos(self.clock.now()))?;
273 }
274 let entry = Entry {
275 actor: who,
276 action: Action::KeyRevoke,
277 target: Some(id.to_string()),
278 version: None,
279 status: if found.is_some() { 204 } else { 404 },
280 };
281 self.record(&mut tx, &entry)?;
282 commit(tx)?;
284 match found {
285 None => Err(TenantError::NotFound),
286 Some(Some(t)) => self.copy_to_tenant(t, &entry),
287 Some(None) => Ok(()),
288 }
289 }
290}
291
292#[cfg(test)]
293mod tests {
294 use rusqlite::types::Value as Sql;
295 use time::macros::datetime;
296
297 use super::*;
298 use crate::access::{self, Scope};
299 use crate::tenants::Removal;
300 use crate::tenants::tests::{Fixture, fixture};
301
302 fn vcon_scopes() -> Scopes {
303 Scopes::of(&[Scope::Write, Scope::Read])
304 }
305
306 fn admin() -> Scopes {
307 Scopes::of(&[Scope::Admin])
308 }
309
310 fn tenant(f: &Fixture, name: &str) -> TenantId {
311 f.tenants.create(Actor::Cli, name, None).expect("made")
312 }
313
314 fn row(f: &Fixture, id: KeyId) -> Vec<Sql> {
316 let conn = f.conn();
317 let mut stmt = conn
318 .prepare("SELECT * FROM api_key WHERE id = ?1")
319 .expect("prepare");
320 let columns = stmt.column_count();
321 stmt.query_row([id.bytes()], |r| {
322 (0..columns).map(|i| r.get::<_, Sql>(i)).collect()
323 })
324 .expect("a row")
325 }
326
327 fn holds(value: &Sql, needle: &[u8]) -> bool {
328 let bytes: &[u8] = match value {
329 Sql::Text(t) => t.as_bytes(),
330 Sql::Blob(b) => b,
331 _ => return false,
332 };
333 bytes.windows(needle.len()).any(|w| w == needle)
334 }
335
336 fn revoked_at(f: &Fixture, id: KeyId) -> Option<i64> {
337 f.conn()
338 .query_row(
339 "SELECT revoked_at FROM api_key WHERE id = ?1",
340 [id.bytes()],
341 |r| r.get(0),
342 )
343 .expect("a row")
344 }
345
346 #[test]
347 fn a_key_is_stored_as_its_hash_and_its_token_is_shown_once() {
348 let f = fixture();
349 let t = tenant(&f, "acme");
350 let key = f
351 .tenants
352 .create_key(Actor::Cli, Some(t), vcon_scopes(), "ingest")
353 .expect("made");
354 assert_eq!(access::parse(&key.token), Ok(key.id));
355 let secret = &key.token[21..];
356 let values = row(&f, key.id);
357 for value in &values {
358 assert!(!holds(value, key.token.as_bytes()), "the token is stored");
359 assert!(!holds(value, secret.as_bytes()), "the secret is stored");
360 }
361 let hash: Vec<u8> = f
362 .conn()
363 .query_row(
364 "SELECT token_hash FROM api_key WHERE id = ?1",
365 [key.id.bytes()],
366 |r| r.get(0),
367 )
368 .expect("a row");
369 assert_eq!(hash, access::token_hash(&key.token));
370 let made = f.admin_records("key_create");
371 assert_eq!(made.len(), 1);
372 assert_eq!(made[0]["actor"], "cli");
373 assert_eq!(made[0]["target"], key.id.to_string());
374 assert_eq!(made[0]["status"], 201);
375 }
376
377 #[test]
378 fn an_operator_key_holds_only_admin_and_only_the_command_line_makes_one() {
379 let f = fixture();
380 let key = f
381 .tenants
382 .create_key(Actor::Cli, None, admin(), "operator")
383 .expect("made");
384 let listed = f.tenants.list_keys(Actor::Cli, None).expect("listed");
385 assert_eq!(listed[0].id, key.id);
386 assert_eq!(listed[0].tenant, None);
387 assert_eq!(listed[0].scopes, admin());
388
389 let api = Actor::Key(key.id);
390 assert_eq!(
391 f.tenants.create_key(api, None, admin(), "another").err(),
392 Some(TenantError::CliOnly)
393 );
394 for scopes in [
395 Scopes::of(&[]),
396 Scopes::of(&[Scope::Admin, Scope::Read]),
397 vcon_scopes(),
398 ] {
399 assert_eq!(
400 f.tenants.create_key(Actor::Cli, None, scopes, "x").err(),
401 Some(TenantError::BadScopes),
402 "{scopes}"
403 );
404 }
405 let statuses: Vec<_> = f
406 .admin_records("key_create")
407 .into_iter()
408 .map(|r| r["status"].clone())
409 .collect();
410 assert_eq!(statuses, [201, 403, 422, 422, 422]);
411 assert_eq!(
412 f.tenants.list_keys(Actor::Cli, None).map(|k| k.len()),
413 Ok(1)
414 );
415 }
416
417 #[test]
418 fn a_tenant_key_holds_only_vcon_scopes() {
419 let f = fixture();
420 let t = tenant(&f, "acme");
421 for scopes in [
422 Scopes::of(&[]),
423 admin(),
424 Scopes::of(&[Scope::Write, Scope::Admin]),
425 ] {
426 assert_eq!(
427 f.tenants.create_key(Actor::Cli, Some(t), scopes, "x").err(),
428 Some(TenantError::BadScopes),
429 "{scopes}"
430 );
431 }
432 let all = Scopes::of(&[
433 Scope::Write,
434 Scope::Read,
435 Scope::Delete,
436 Scope::Legal,
437 Scope::Audit,
438 ]);
439 assert!(
440 f.tenants
441 .create_key(Actor::Cli, Some(t), all, "all")
442 .is_ok()
443 );
444 }
445
446 #[test]
447 fn a_key_for_an_unknown_or_closing_tenant_is_refused() {
448 let f = fixture();
449 let unknown = TenantId::generate();
450 assert_eq!(
451 f.tenants
452 .create_key(Actor::Cli, Some(unknown), vcon_scopes(), "x")
453 .err(),
454 Some(TenantError::NotFound)
455 );
456 let t = tenant(&f, "acme");
457 f.tenants.drain(t).expect("drains");
458 assert_eq!(
459 f.tenants
460 .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
461 .err(),
462 Some(TenantError::Closing)
463 );
464 let refused = f.admin_records("key_create");
465 assert_eq!(refused[0]["status"], 404);
466 assert_eq!(refused[0]["target"], unknown.to_string());
467 assert_eq!(refused[1]["status"], 503);
468 assert_eq!(f.count_keys(), 0);
469 }
470
471 #[test]
472 fn a_key_whose_record_fails_is_not_made() {
473 let f = fixture();
474 let t = tenant(&f, "acme");
475 f.conn()
476 .execute_batch(
477 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
478 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
479 )
480 .expect("trigger");
481 assert_eq!(
482 f.tenants
483 .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
484 .err(),
485 Some(TenantError::AuditFailed)
486 );
487 assert_eq!(f.count_keys(), 0);
488 }
489
490 #[test]
491 fn keys_are_listed_per_tenant_or_all_oldest_first() {
492 let f = fixture();
493 let (a, b) = (tenant(&f, "a"), tenant(&f, "b"));
494 let first = f
495 .tenants
496 .create_key(Actor::Cli, Some(a), vcon_scopes(), "first")
497 .expect("made");
498 f.clock.set(datetime!(2026-10-23 13:00 UTC));
499 let other = f
500 .tenants
501 .create_key(Actor::Cli, Some(b), vcon_scopes(), "other")
502 .expect("made");
503 f.clock.set(datetime!(2026-10-23 14:00 UTC));
504 let second = f
505 .tenants
506 .create_key(Actor::Cli, Some(a), Scopes::of(&[Scope::Legal]), "second")
507 .expect("made");
508 f.tenants
509 .revoke_key(Actor::Cli, second.id)
510 .expect("revoked");
511
512 let a_keys = f.tenants.list_keys(Actor::Cli, Some(a)).expect("listed");
513 assert_eq!(
514 a_keys,
515 [
516 KeyInfo {
517 id: first.id,
518 tenant: Some(a),
519 scopes: vcon_scopes(),
520 label: "first".to_owned(),
521 created_at: datetime!(2026-10-23 12:00 UTC),
522 revoked_at: None,
523 },
524 KeyInfo {
525 id: second.id,
526 tenant: Some(a),
527 scopes: Scopes::of(&[Scope::Legal]),
528 label: "second".to_owned(),
529 created_at: datetime!(2026-10-23 14:00 UTC),
530 revoked_at: Some(datetime!(2026-10-23 14:00 UTC)),
531 },
532 ]
533 );
534 let all: Vec<KeyId> = f
535 .tenants
536 .list_keys(Actor::Cli, None)
537 .expect("listed")
538 .into_iter()
539 .map(|k| k.id)
540 .collect();
541 assert_eq!(all, [first.id, other.id, second.id]);
542 assert_eq!(
543 f.tenants
544 .list_keys(Actor::Cli, Some(TenantId::generate()))
545 .err(),
546 Some(TenantError::NotFound)
547 );
548 let lists = f.admin_records("key_list");
549 let statuses: Vec<_> = lists.iter().map(|r| r["status"].clone()).collect();
550 assert_eq!(statuses, [200, 200, 404]);
551 assert_eq!(lists[0]["target"], a.to_string());
552 assert_eq!(lists[1]["target"], serde_json::Value::Null);
553 }
554
555 #[test]
556 fn a_stored_scope_that_does_not_read_back_is_damage() {
557 let f = fixture();
558 let t = tenant(&f, "acme");
559 let key = f
560 .tenants
561 .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
562 .expect("made");
563 f.conn()
564 .execute(
565 "UPDATE api_key SET scopes = 'owner' WHERE id = ?1",
566 [key.id.bytes()],
567 )
568 .expect("damage");
569 assert_eq!(
570 f.tenants.list_keys(Actor::Cli, None).err(),
571 Some(TenantError::Io)
572 );
573 }
574
575 #[test]
576 fn a_key_is_revoked_once_and_an_unknown_one_is_not_found() {
577 let f = fixture();
578 let t = tenant(&f, "acme");
579 let key = f
580 .tenants
581 .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
582 .expect("made");
583 f.clock.set(datetime!(2026-10-23 13:00 UTC));
584 f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
585 let first = revoked_at(&f, key.id);
586 assert_eq!(
587 first,
588 Some(crate::clock::nanos(datetime!(2026-10-23 13:00 UTC))),
589 "revoked at the time of the revocation"
590 );
591 f.clock.set(datetime!(2026-10-23 14:00 UTC));
592 f.tenants
593 .revoke_key(Actor::Cli, key.id)
594 .expect("again, no change");
595 assert_eq!(revoked_at(&f, key.id), first, "the first time stands");
596 let unknown = KeyId::generate();
597 assert_eq!(
598 f.tenants.revoke_key(Actor::Cli, unknown),
599 Err(TenantError::NotFound)
600 );
601 let records = f.admin_records("key_revoke");
602 let statuses: Vec<_> = records.iter().map(|r| r["status"].clone()).collect();
603 assert_eq!(statuses, [204, 204, 404]);
604 assert_eq!(records[0]["target"], key.id.to_string());
605 assert_eq!(records[2]["target"], unknown.to_string());
606 }
607
608 fn tenant_records(f: &Fixture, t: TenantId, action: &str) -> Vec<serde_json::Value> {
609 crate::audit::testing::exported(&f.tenant_catalog(t), None)
610 .into_iter()
611 .filter(|r| r["action"] == action)
612 .collect()
613 }
614
615 #[test]
616 fn a_tenant_key_made_or_revoked_is_recorded_in_its_tenants_log_too() {
617 let f = fixture();
618 let t = tenant(&f, "acme");
619 let key = f
620 .tenants
621 .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
622 .expect("made");
623 f.tenants.revoke_key(Actor::Cli, key.id).expect("revoked");
624 let made = tenant_records(&f, t, "key_create");
625 assert_eq!(made.len(), 1);
626 assert_eq!(made[0]["actor"], "cli");
627 assert_eq!(made[0]["target"], key.id.to_string());
628 assert_eq!(made[0]["status"], 201);
629 let revoked = tenant_records(&f, t, "key_revoke");
630 assert_eq!(revoked.len(), 1);
631 assert_eq!(revoked[0]["target"], key.id.to_string());
632 assert_eq!(revoked[0]["status"], 204);
633
634 let operator = f
635 .tenants
636 .create_key(Actor::Cli, None, admin(), "op")
637 .expect("made");
638 f.tenants
639 .revoke_key(Actor::Cli, operator.id)
640 .expect("revoked");
641 assert_eq!(tenant_records(&f, t, "key_create").len(), 1, "only its own");
642 let refused = f
643 .tenants
644 .create_key(Actor::Cli, Some(t), admin(), "x")
645 .err();
646 assert_eq!(refused, Some(TenantError::BadScopes));
647 assert_eq!(
648 tenant_records(&f, t, "key_create").len(),
649 1,
650 "a refusal stays in the admin log"
651 );
652 }
653
654 #[test]
657 fn a_key_change_whose_tenant_copy_fails_stands() {
658 let f = fixture();
659 let t = tenant(&f, "acme");
660 f.tenant_catalog(t)
661 .execute_batch(
662 "CREATE TRIGGER dead BEFORE INSERT ON audit
663 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
664 )
665 .expect("trigger");
666 assert_eq!(
667 f.tenants
668 .create_key(Actor::Cli, Some(t), vcon_scopes(), "x")
669 .err(),
670 Some(TenantError::AuditFailed)
671 );
672 let keys = f.tenants.list_keys(Actor::Cli, Some(t)).expect("listed");
673 assert_eq!(keys.len(), 1, "the key stands");
674 assert_eq!(
675 f.tenants.revoke_key(Actor::Cli, keys[0].id),
676 Err(TenantError::AuditFailed)
677 );
678 assert!(
679 revoked_at(&f, keys[0].id).is_some(),
680 "the revocation stands"
681 );
682 }
683
684 #[test]
685 fn removing_a_tenant_revokes_its_keys_in_the_same_transaction() {
686 let f = fixture();
687 let (a, b) = (tenant(&f, "a"), tenant(&f, "b"));
688 let mine: Vec<KeyId> = (0..2)
689 .map(|_| {
690 f.tenants
691 .create_key(Actor::Cli, Some(a), vcon_scopes(), "a")
692 .expect("made")
693 .id
694 })
695 .collect();
696 let theirs = f
697 .tenants
698 .create_key(Actor::Cli, Some(b), vcon_scopes(), "b")
699 .expect("made")
700 .id;
701 let operator = f
702 .tenants
703 .create_key(Actor::Cli, None, admin(), "op")
704 .expect("made")
705 .id;
706
707 f.conn()
708 .execute_batch(
709 "CREATE TEMP TRIGGER no_audit BEFORE INSERT ON audit
710 WHEN NEW.action = 'tenant_remove'
711 BEGIN SELECT RAISE(ABORT, 'no audit'); END;",
712 )
713 .expect("trigger");
714 assert_eq!(
715 f.tenants.remove(Actor::Cli, a, Removal::Empty),
716 Err(TenantError::AuditFailed)
717 );
718 for id in &mine {
719 assert_eq!(
720 revoked_at(&f, *id),
721 None,
722 "a failed removal revokes nothing"
723 );
724 }
725 f.conn()
726 .execute_batch("DROP TRIGGER no_audit")
727 .expect("drop trigger");
728
729 f.clock.set(datetime!(2026-10-23 13:00 UTC));
730 f.tenants
731 .remove(Actor::Cli, a, Removal::Empty)
732 .expect("removed");
733 let at = crate::clock::nanos(datetime!(2026-10-23 13:00 UTC));
734 for id in &mine {
735 assert_eq!(revoked_at(&f, *id), Some(at));
736 }
737 assert_eq!(revoked_at(&f, theirs), None);
738 assert_eq!(revoked_at(&f, operator), None);
739 }
740
741 #[test]
744 fn a_full_listener_is_counted_in_the_admin_log_under_its_configuration_key() {
745 let f = fixture();
746 f.tenants.count_listener_full("listen");
747 let counted = f.admin_records("listener_full");
748 assert_eq!(counted.len(), 1, "{counted:?}");
749 assert_eq!(counted[0]["actor"], "", "no caller: none was taken");
750 assert_eq!(counted[0]["target"], "listen", "the listener's key");
751 assert_eq!(
752 counted[0]["status"],
753 serde_json::Value::Null,
754 "no status: a listener that filled answered no request"
755 );
756 assert_eq!(counted[0]["count"], 1, "one time");
757 }
758
759 #[test]
760 fn the_times_a_listener_was_full_in_one_minute_share_a_record() {
761 let f = fixture();
762 for _ in 0..7 {
763 f.tenants.count_listener_full("listen");
764 }
765 let counted = f.admin_records("listener_full");
766 assert_eq!(counted.len(), 1, "one record for the minute: {counted:?}");
767 assert_eq!(counted[0]["count"], 7, "seven times");
768 assert_eq!(counted[0]["at"], "2026-10-23T12:00:00Z", "the minute");
769 }
770
771 #[test]
772 fn a_listener_full_in_another_minute_has_another_record() {
773 let f = fixture();
774 f.tenants.count_listener_full("listen");
775 f.clock.set(datetime!(2026-10-23 12:01:30 UTC));
776 f.tenants.count_listener_full("listen");
777 f.tenants.count_listener_full("listen");
778 let counts: Vec<_> = f
779 .admin_records("listener_full")
780 .iter()
781 .map(|r| (r["at"].clone(), r["count"].clone()))
782 .collect();
783 assert_eq!(
784 counts,
785 [
786 ("2026-10-23T12:00:00Z".into(), 1.into()),
787 ("2026-10-23T12:01:00Z".into(), 2.into()),
788 ],
789 "a record for each minute"
790 );
791 }
792
793 #[test]
794 fn each_listener_has_a_record_of_its_own() {
795 let f = fixture();
796 f.tenants.count_listener_full("listen");
797 f.tenants.count_listener_full("operator.listen");
798 f.tenants.count_listener_full("operator.listen");
799 let mut counts: Vec<_> = f
800 .admin_records("listener_full")
801 .iter()
802 .map(|r| {
803 (
804 r["target"].as_str().expect("a target").to_owned(),
805 r["count"].as_u64().expect("a count"),
806 )
807 })
808 .collect();
809 counts.sort();
810 assert_eq!(
811 counts,
812 [("listen".to_owned(), 1), ("operator.listen".to_owned(), 2)],
813 "each under its own key"
814 );
815 }
816
817 #[test]
818 fn a_full_listener_is_in_no_tenants_log() {
819 let f = fixture();
820 let t = tenant(&f, "acme");
821 f.tenants.count_listener_full("listen");
822 assert_eq!(
823 tenant_records(&f, t, "listener_full"),
824 Vec::<serde_json::Value>::new(),
825 "the listener is the server's, not a tenant's"
826 );
827 }
828
829 #[test]
830 fn a_count_that_cannot_be_written_is_passed_over() {
831 let f = fixture();
832 f.conn()
833 .execute_batch(
834 "CREATE TRIGGER no_audit BEFORE INSERT ON audit
835 BEGIN SELECT RAISE(ABORT, 'no audit'); END",
836 )
837 .expect("a trigger");
838 f.tenants.count_listener_full("listen");
840 f.conn()
841 .execute_batch("DROP TRIGGER no_audit")
842 .expect("drop trigger");
843 assert_eq!(f.admin_records("listener_full").len(), 0, "none written");
844 f.tenants.count_listener_full("listen");
845 assert_eq!(f.admin_records("listener_full").len(), 1, "and the next is");
846 }
847
848 impl Fixture {
849 fn count_keys(&self) -> i64 {
850 self.conn()
851 .query_row("SELECT count(*) FROM api_key", [], |r| r.get(0))
852 .expect("count")
853 }
854 }
855}