-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2309 lines (2218 loc) · 109 KB
/
Copy pathlib.rs
File metadata and controls
2309 lines (2218 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026 Busbar Inc and contributors
//! The **Postgres** backend for busbar's durable governance store — the shared, multi-node `db`
//! plugin. Implements `busbar_contract::records::RecordStore` over a mutex-guarded synchronous `postgres` client,
//! depending only on the `busbar-contract` crate (plus the `postgres` driver), never on the engine.
//!
//! Schema v10 (busbar 1.6.0): the kind-tagged plane-record tables, the name-keyed usage ledger and
//! the dated metering key, upgraded IN PLACE from a 1.5.x (v6) database — see `SCHEMA_VERSION`.
//!
//! Schema v5 (1.5.0, the generic-credentials redesign): `virtual_keys`/`aws_credentials` are
//! replaced by `keys` (pure principal attributes, `generation_hash` instead of `key_hash`,
//! `expires_at`/`deleted_at`/`revision`) and `credentials` (kind-polymorphic row-looked-up
//! credentials — today only `kind='sigv4'`). `DELETE` is a TOMBSTONE, not a hard delete: the `keys`
//! row survives (so `usage_metering.key_id` keeps resolving forever) while every credential row for
//! it is destroyed and `enabled`/`deleted_at` are set, atomically, in the same transaction and the
//! same `revision` stamp — this is what makes revision-delta hydration observe the tombstone AND
//! the credential disappearance as one atomic delta (see `delete_key`'s doc comment for why this
//! matters: a naive implementation that tombstoned the key in one transaction and deleted
//! credentials in another would let a `REPEATABLE READ` hydration snapshot land between them and
//! observe a "deleted" key whose credential is still live).
//!
//! Like the prior schema, this is a **single mutex-guarded connection** used off the request hot
//! path (key CRUD + the write-behind usage flush) — governance is off the reactor entirely.
//!
//! ## Known limitations (documented honestly, not papered over)
//!
//! - **No TLS in this build (`NoTls`).** Run the connection over a trusted network segment, a local
//! socket, or a TLS-terminating proxy (pgbouncer/stunnel).
//! - **No automatic reconnect.** A persistently dropped connection surfaces as store errors; a
//! permanently broken connection requires a process restart.
//! - **No partitioning, no LISTEN/NOTIFY-accelerated hydration, no column-level secret grants in
//! this pass.** The design session that produced this schema recommended all three as scale/perf
//! layers on top of this contract — deliberately deferred here in favor of getting the
//! correctness-critical surface (tombstone semantics, revoke fan-out via `revoke_credential`,
//! hydration-delta soundness, slot-safe credential minting) right first. None of the three change
//! the `Store` trait's observable behavior; they're purely internal to this crate and can be
//! added later without another schema bump.
use busbar_contract::records::{
AuditRecord, CredentialMeta, CredentialSecret, MeteringDelta, MeteringRow, ModelTokens,
PlaneDisposition, PlaneRecord, PlaneSelector, RecordStore, RecordStoreError, RecordStoreResult,
ScopeRef, SecretForm, UsageDelta, UsageLedger, VirtualKey, UNIT_CACHE_READ, UNIT_CACHE_WRITE,
UNIT_INPUT, UNIT_OUTPUT,
};
use postgres::types::ToSql;
use postgres::{Client, NoTls, Row, Transaction};
use std::collections::BTreeMap;
use std::sync::Mutex;
// postgres driver error -> the api's backend-agnostic `RecordStoreError` (the contract crate stays
// storage-free, so the `From` impl that powers `?` cannot live there).
trait IntoStoreResult<T> {
fn store(self) -> RecordStoreResult<T>;
}
impl<T> IntoStoreResult<T> for Result<T, postgres::Error> {
fn store(self) -> RecordStoreResult<T> {
self.map_err(|e| RecordStoreError(render_pg_error(&e)))
}
}
/// Render a driver error with its CAUSE attached. `postgres::Error`'s own `Display` for a
/// server-side failure is the literal string "db error" and nothing else: the SQLSTATE, the server
/// message and the violated constraint all live behind `as_db_error()`. Mapping straight through
/// `to_string()` therefore handed operators (and this crate's own callers) a two-word error for
/// every constraint violation, permission failure and bad statement alike, which is unactionable
/// and indistinguishable between causes.
///
/// The server's `detail` field is deliberately NOT included: on a unique violation Postgres puts
/// the offending ROW VALUES in it, and this string reaches logs. The SQLSTATE, the primary message
/// and the constraint name identify the failure without echoing data.
fn render_pg_error(e: &postgres::Error) -> String {
match e.as_db_error() {
Some(db) => {
let mut out = format!("{}: {}", db.code().code(), db.message());
if let Some(constraint) = db.constraint() {
out.push_str(&format!(" (constraint {constraint})"));
}
out
}
None => e.to_string(),
}
}
/// True when a postgres error is SQLSTATE 42P01 (`undefined_table`) - the ONE case migrate() treats
/// as an unversioned (version 0) database. Every other error class (connection, timeout, permission)
/// is transient/fatal and must never be read as "fresh DB": treating a connection or permission
/// failure as version 0 would drop and recreate a populated database.
fn is_undefined_table(e: &postgres::Error) -> bool {
e.code() == Some(&postgres::error::SqlState::UNDEFINED_TABLE)
}
/// Extract the PASSWORD from a Postgres DSN. Supports both the URL form
/// (`postgres://user:pass@host:5432/db`) and the libpq keyword form (`... password=secret ...`), so
/// a connect-error string can be scrubbed of the secret regardless of which shape the operator used.
fn dsn_password(dsn: &str) -> Option<String> {
if let Some(rest) = dsn.split("://").nth(1) {
if let Some((userinfo, _)) = rest.rsplit_once('@') {
if let Some((_, pass)) = userinfo.split_once(':') {
if !pass.is_empty() {
return Some(pass.to_string());
}
}
}
}
// The URL QUERY-PARAMETER form (`postgres://user@host/db?password=secret`). libpq accepts it,
// the README tells operators to use the query string for other options, and it does not go
// through the userinfo branch above, so without this it reached the keyword scan below and was
// never redacted.
if let Some((_, query)) = dsn.split_once('?') {
for param in query.split('&') {
if let Some(v) = param.strip_prefix("password=") {
if !v.is_empty() {
return Some(v.to_string());
}
}
}
}
// The libpq KEYWORD form. libpq allows whitespace around the separator (`password = secret`)
// and single-quoted values (`password='se cret'`); a plain `strip_prefix("password=")` over
// whitespace tokens sees neither, returns None, and `scrub` then passes the connect error
// through with the secret intact. Collapse the whitespace around every `=` first, then match
// the key only at a token boundary so `sslpassword=` (a different libpq option) is not mistaken
// for it.
let normalized = collapse_around_equals(dsn);
let mut search = normalized.as_str();
while let Some(at) = search.find("password=") {
let at_token_start = at == 0
|| search[..at]
.chars()
.next_back()
.is_some_and(char::is_whitespace);
let rest = &search[at + "password=".len()..];
if at_token_start {
let value = match rest.strip_prefix('\'') {
Some(quoted) => quoted.split('\'').next().unwrap_or(""),
None => rest.split_whitespace().next().unwrap_or(""),
};
if !value.is_empty() {
return Some(value.to_string());
}
}
search = rest;
}
None
}
/// Remove whitespace immediately before and after every `=`, so `key = value` and `key=value`
/// scan identically. Only used by `dsn_password`.
fn collapse_around_equals(s: &str) -> String {
let chars: Vec<char> = s.chars().collect();
let mut out = String::with_capacity(s.len());
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if c.is_whitespace() {
let mut j = i;
while j < chars.len() && chars[j].is_whitespace() {
j += 1;
}
// Whitespace that only separates a key from its `=` is not a token boundary.
if !(j < chars.len() && chars[j] == '=') {
out.push(' ');
}
i = j;
continue;
}
if c == '=' {
out.push('=');
let mut j = i + 1;
while j < chars.len() && chars[j].is_whitespace() {
j += 1;
}
i = j;
continue;
}
out.push(c);
i += 1;
}
out
}
/// Percent-DECODE a URL component (`%40` -> `@`). A malformed escape is left verbatim. So the scrub
/// redacts BOTH the raw and decoded forms of a URL-embedded password.
fn percent_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hi = (bytes[i + 1] as char).to_digit(16);
let lo = (bytes[i + 2] as char).to_digit(16);
if let (Some(hi), Some(lo)) = (hi, lo) {
out.push((hi * 16 + lo) as u8);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// Replace every occurrence of `secret` (in BOTH raw and percent-decoded forms) with `<redacted>`.
fn scrub(msg: String, secret: Option<&str>) -> String {
let Some(s) = secret.filter(|s| !s.is_empty()) else {
return msg;
};
let mut out = msg;
if out.contains(s) {
out = out.replace(s, "<redacted>");
}
let decoded = percent_decode(s);
if decoded != s && !decoded.is_empty() && out.contains(&decoded) {
out = out.replace(&decoded, "<redacted>");
}
out
}
/// Store schema version. v5 (1.5.0 generic-credentials redesign): `virtual_keys`/`aws_credentials`
/// -> `keys`/`credentials` (kind-polymorphic, slot-bounded, tombstone-delete, revision-stamped for
/// incremental hydration). 1.5.0 is unreleased, so a pre-v5 database is dropped and recreated - a
/// bump, never a migration.
///
/// v6: ONE-TIME, DURABLE backfill of `usage_windows.billable_requests` for any row still shaped
/// `billable_requests=0, requests>0` at the moment this migration runs. Exists to retire a bug in
/// busbar core's `governance::state::hydrate_budgets`, which used to infer "legacy pre-split
/// row" from that exact counter shape at EVERY boot - but a fully-refunded window (every request
/// in it non-2xx; `refund_bucket` decrements `billable_requests` but deliberately never
/// `requests`) produces the identical shape, so hydrate_budgets could not tell "never migrated"
/// from "correctly refunded to zero" and silently re-billed refunded fees on restart. Doing the
/// value-based backfill HERE, ONCE, gated on the version crossing, is safe ONLY because 1.5.0 has
/// never shipped to a real customer - there is no genuine "currently, legitimately refunded to
/// zero" row in existence anywhere to accidentally re-bill at the moment this migration ships.
/// This would NOT be safe to run again, or to run as a per-boot heuristic (that was the bug) -
/// which is exactly why it is gated on `version < 6` and will never fire a second time on any
/// store that has already crossed into v6. `hydrate_budgets` itself drops the heuristic entirely
/// once every store it reads from has passed through this migration.
///
/// v7-v9 (never released — dev builds of 1.5.x only): the protocol-NAMED durable tables
/// `mcp_calls`, `tasks`/`task_events`, `mcp_demotions` and `spent_ask_states`, one per typed trait
/// method busbar 1.6.0 has since deleted. v10 no longer creates, reads or writes them. A database a
/// dev build carried to v9 keeps them exactly as they were — NOTHING is dropped or rewritten — so
/// the rows remain on disk for an operator who wants them; the 1.6.0 engine writes its plane records
/// in its own opaque body format through the tables below instead, and guessing that format for a
/// row written under the old typed shape would be inventing data, not migrating it.
///
/// v10 (busbar 1.6.0 store interface), an IN-PLACE, ADDITIVE upgrade of a v6 (released 1.5.x)
/// database — no table is dropped and no existing row changes meaning:
/// * `keys` gains `idp_subject`/`binding_mode`/`minted_by` (NULL for every pre-existing key, which
/// is exactly what `VirtualKey` reads for a key minted before those fields existed) and
/// `allowed_scopes_by_kind`, the non-`pool` scope grants (`mcp_server`, `agent`, …) keyed by
/// kind. `allowed_pools` keeps holding the pool grants byte-for-byte as before, so a pool-only
/// key reads back unchanged; NULL in both columns is still the omitted-grant wildcard.
/// * the usage ledger keeps the four reserved token classes in its existing columns and carries
/// every OPEN unit class (1.6.0 M1b `usage_units`) in the new `usage_ledger_units` table.
/// * `usage_metering` gains `priced_from_ms` (DEFAULT 0 — the opening rate-card entry, which is
/// how busbar reads an undated 1.5.x row) and it JOINS the primary key, so a rate-card edit
/// inside a UTC day opens a second row rather than folding two prices into one (#79). Open unit
/// classes ride in the new `usage_metering_units` table.
/// * the kind-tagged PLANE-RECORD verbs get `plane_records` (upserted, keyed `(kind, id)`),
/// `plane_chain` (appended, keyed `(kind, parent, seq)`) and `plane_tokens` (the single-use
/// token ledger, keyed `(kind, token)`).
const SCHEMA_VERSION: i64 = 10;
/// The plane-record kinds whose retention is TERMINAL-ONLY: `purge_plane_records_before` drops a row
/// of one of these kinds only once its `disposition` sidecar says `Terminal`. An interrupted task
/// waiting on a human is exactly the row that sits still longest, and sweeping it is losing the
/// work. Every other kind drops any row older than the cutoff — the same split busbar's reference
/// backends (`store-memory`, `store-example-plugin`) draw.
const TERMINAL_ONLY_RETENTION_KINDS: [&str; 1] = ["task"];
/// `(parent kind, child kind)`: purging a parent record takes the child CHAIN hanging off it in the
/// same transaction. A task's event chain has no retention path of its own, so leaving it behind
/// would let it grow forever under tasks that no longer exist — the cascade busbar's
/// `store-example-plugin` makes, and this store made before 1.6.0.
const PLANE_CHILD_KINDS: [(&str, &str); 1] = [("task", "task_event")];
const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS busbar_schema (
version BIGINT PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS store_revision (
only_row BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (only_row),
revision BIGINT NOT NULL DEFAULT 0 CHECK (revision >= 0)
);
INSERT INTO store_revision (only_row, revision) VALUES (TRUE, 0) ON CONFLICT (only_row) DO NOTHING;
CREATE TABLE IF NOT EXISTS keys (
id TEXT PRIMARY KEY,
-- Rotation fingerprint (VirtualKey::generation_hash), NOT a lookup key -- deliberately no
-- UNIQUE constraint, see the type's own doc for why.
generation_hash TEXT NOT NULL,
name TEXT NOT NULL,
-- NULL = the pool grant was OMITTED at mint = ALL pools; a JSON array (possibly empty) = the
-- exhaustive grant. NULL and '[]' must never collapse into each other.
allowed_pools TEXT,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at BIGINT NOT NULL,
key_group TEXT,
labels TEXT NOT NULL DEFAULT '{}',
expires_at BIGINT,
-- TOMBSTONE marker. NULL = live. The row is never removed once tombstoned; see delete_key.
deleted_at BIGINT,
revision BIGINT NOT NULL DEFAULT 0,
-- v10 (busbar 1.6.0): attribution/provenance, NULL for every key minted before they existed.
idp_subject TEXT,
binding_mode TEXT,
minted_by TEXT,
-- v10: the NON-pool scope grants, a JSON object {kind: [value, ...]}. NULL = none. Pool grants
-- stay in allowed_pools; NULL in BOTH columns is the omitted-grant wildcard.
allowed_scopes_by_kind TEXT,
CONSTRAINT keys_tombstone_disabled CHECK (deleted_at IS NULL OR enabled = FALSE)
);
CREATE INDEX IF NOT EXISTS idx_keys_revision ON keys (revision);
-- Row-looked-up credentials ONLY (today: sigv4). Bearer/signed-token auth is never represented
-- here -- verify_token never looks up a row, it only compares VirtualKey::generation_hash. Slot
-- bounds cardinality to exactly 2 rows per (key_id, kind), for safe overlap-window rotation.
CREATE TABLE IF NOT EXISTS credentials (
id TEXT PRIMARY KEY,
key_id TEXT NOT NULL REFERENCES keys(id) ON DELETE CASCADE,
kind TEXT NOT NULL CHECK (kind IN ('sigv4')),
slot SMALLINT NOT NULL CHECK (slot IN (0, 1)),
public_id TEXT NOT NULL,
secret TEXT,
secret_form TEXT NOT NULL CHECK (secret_form IN ('none', 'recoverable', 'digest')),
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
expires_at BIGINT,
revoked_at BIGINT,
revoke_reason TEXT,
revision BIGINT NOT NULL DEFAULT 0,
CONSTRAINT credentials_public_id_uniq UNIQUE (kind, public_id),
CONSTRAINT credentials_slot_uniq UNIQUE (key_id, kind, slot),
CONSTRAINT credentials_secret_form_matches CHECK ((secret_form = 'none') = (secret IS NULL))
);
CREATE INDEX IF NOT EXISTS idx_credentials_revision ON credentials (revision);
CREATE INDEX IF NOT EXISTS idx_credentials_key_id ON credentials (key_id);
CREATE TABLE IF NOT EXISTS usage_windows (
bucket_id TEXT NOT NULL,
window_start BIGINT NOT NULL,
requests BIGINT NOT NULL DEFAULT 0,
billable_requests BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (bucket_id, window_start)
);
CREATE TABLE IF NOT EXISTS usage_ledger (
bucket_id TEXT NOT NULL,
window_start BIGINT NOT NULL,
model TEXT NOT NULL,
tokens_input BIGINT NOT NULL DEFAULT 0,
tokens_output BIGINT NOT NULL DEFAULT 0,
tokens_cache_read BIGINT NOT NULL DEFAULT 0,
tokens_cache_write BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (bucket_id, window_start, model)
);
-- v10: every OPEN unit class of a (bucket, window, model) ledger row — the 1.6.0 M1b `usage_units`
-- keys that are not one of the four reserved token classes above (which keep their columns, so a
-- 1.5.x ledger row needs no rewrite). Additive on the flush path like the token columns.
CREATE TABLE IF NOT EXISTS usage_ledger_units (
bucket_id TEXT NOT NULL,
window_start BIGINT NOT NULL,
model TEXT NOT NULL,
unit TEXT COLLATE \"C\" NOT NULL,
count BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (bucket_id, window_start, model, unit)
);
CREATE TABLE IF NOT EXISTS usage_metering (
key_id TEXT NOT NULL,
bucket BIGINT NOT NULL,
model TEXT NOT NULL,
provider TEXT NOT NULL,
tokens_input BIGINT NOT NULL DEFAULT 0,
tokens_output BIGINT NOT NULL DEFAULT 0,
tokens_cache_read BIGINT NOT NULL DEFAULT 0,
tokens_cache_write BIGINT NOT NULL DEFAULT 0,
requests BIGINT NOT NULL DEFAULT 0,
billable_requests BIGINT NOT NULL DEFAULT 0,
key_group_at_use TEXT NOT NULL DEFAULT '',
pricing_version TEXT NOT NULL DEFAULT '',
-- v10: the instant this row's price started (#79). Part of the accrual key.
priced_from_ms BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (key_id, bucket, model, provider, priced_from_ms)
);
CREATE INDEX IF NOT EXISTS idx_usage_metering_bucket ON usage_metering (bucket);
-- v10: every ledgered class the token columns do not hold (MeteringRow::usage_units), per metering
-- row. Additive like the token columns.
CREATE TABLE IF NOT EXISTS usage_metering_units (
key_id TEXT NOT NULL,
bucket BIGINT NOT NULL,
model TEXT NOT NULL,
provider TEXT NOT NULL,
priced_from_ms BIGINT NOT NULL DEFAULT 0,
unit TEXT COLLATE \"C\" NOT NULL,
count BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (key_id, bucket, model, provider, priced_from_ms, unit)
);
CREATE INDEX IF NOT EXISTS idx_usage_metering_units_bucket ON usage_metering_units (bucket);
CREATE TABLE IF NOT EXISTS audit_log (
seq BIGINT PRIMARY KEY,
ts BIGINT NOT NULL,
action TEXT NOT NULL,
resource TEXT NOT NULL,
outcome TEXT NOT NULL,
principal TEXT NOT NULL,
prev_hash TEXT NOT NULL,
hash TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS denylist (
sub TEXT PRIMARY KEY,
reason TEXT NOT NULL DEFAULT '',
created_at BIGINT NOT NULL DEFAULT 0
);
-- THE KIND-TAGGED PLANE RECORDS (v10, busbar 1.6.0). The typed per-protocol tables of v7-v9 are
-- replaced by one neutral surface: a plane record is an OPAQUE body the engine serialized plus the
-- typed sidecar columns (kind, id, parent, seq, ts, disposition) that let this store key, order and
-- retention-sweep without ever decoding the body. This store NEVER decodes a body and never
-- computes or recomputes a digest inside one: it persists what it was handed and returns it
-- verbatim.
--
-- COLLATE \"C\" on every identity column is BYTE-EXACT comparison, stated rather than inherited.
-- Postgres's default collations are deterministic, so this changes nothing on a normally-created
-- database — but one created with a NON-DETERMINISTIC ICU collation (case- and accent-insensitive)
-- would otherwise make two task ids differing only in case COLLIDE on the primary key and silently
-- upsert onto one row, fold a single-use token onto its case-variant, and let `vk_alice` read
-- `vk_Alice`'s call chain. A kind, an id, a parent and a token are opaque strings, never words.
-- UPSERTED records (a task, a demotion, a push configuration, ...): one current row per (kind, id).
CREATE TABLE IF NOT EXISTS plane_records (
kind TEXT COLLATE \"C\" NOT NULL,
id TEXT COLLATE \"C\" NOT NULL,
parent TEXT COLLATE \"C\",
seq BIGINT NOT NULL DEFAULT 0,
ts BIGINT NOT NULL,
disposition TEXT NOT NULL CHECK (disposition IN ('active', 'terminal')),
body BYTEA NOT NULL,
PRIMARY KEY (kind, id)
);
-- The retention sweep's access path: purge_plane_records_before filters on (kind, ts).
CREATE INDEX IF NOT EXISTS plane_records_kind_ts_idx ON plane_records (kind, ts);
CREATE INDEX IF NOT EXISTS plane_records_kind_parent_idx ON plane_records (kind, parent);
-- APPENDED chains (a task's event chain, a principal's call log): append-only, keyed by the chain
-- position (kind, parent, seq). A second record at an occupied position is either the write-through
-- retrying (identical: Ok) or a fork (different: refused) — never an overwrite.
CREATE TABLE IF NOT EXISTS plane_chain (
kind TEXT COLLATE \"C\" NOT NULL,
parent TEXT COLLATE \"C\" NOT NULL,
seq BIGINT NOT NULL,
id TEXT COLLATE \"C\" NOT NULL,
ts BIGINT NOT NULL,
disposition TEXT NOT NULL CHECK (disposition IN ('active', 'terminal')),
body BYTEA NOT NULL,
PRIMARY KEY (kind, parent, seq)
);
CREATE INDEX IF NOT EXISTS plane_chain_kind_ts_idx ON plane_chain (kind, ts);
-- THE SINGLE-USE TOKEN LEDGER behind redeem_plane_token (an `ask` approval nonce, ...). A sealed
-- single-use token verifies identically on its second presentation; only a RECORD THAT THE FIRST
-- HAPPENED tells them apart, and it has to be one ledger for the whole fleet to be true of every
-- node. Every redemption is a point INSERT on the primary key; expires_at bounds the table.
CREATE TABLE IF NOT EXISTS plane_tokens (
kind TEXT COLLATE \"C\" NOT NULL,
token TEXT COLLATE \"C\" NOT NULL,
expires_at BIGINT NOT NULL,
PRIMARY KEY (kind, token)
);
";
/// The v10 column additions on tables a 1.5.x database already has. `IF NOT EXISTS`, so a re-run
/// after a crash part-way through is harmless; `migrate_locked` runs it only when crossing into v10.
const MIGRATE_V10_COLUMNS: &str = "
ALTER TABLE keys ADD COLUMN IF NOT EXISTS idp_subject TEXT;
ALTER TABLE keys ADD COLUMN IF NOT EXISTS binding_mode TEXT;
ALTER TABLE keys ADD COLUMN IF NOT EXISTS minted_by TEXT;
ALTER TABLE keys ADD COLUMN IF NOT EXISTS allowed_scopes_by_kind TEXT;
ALTER TABLE usage_metering ADD COLUMN IF NOT EXISTS priced_from_ms BIGINT NOT NULL DEFAULT 0;
";
/// Postgres `Store` backend (durable, shared across a cluster). A single mutex-guarded connection —
/// governance is off the request hot path, so serializing access is fine.
pub struct PostgresStore {
client: Mutex<Client>,
}
/// Clamp a `u64` into `i64` for a BIGINT column (a value above `i64::MAX` pins to `i64::MAX`, never
/// wraps).
fn clamp(v: u64) -> i64 {
i64::try_from(v).unwrap_or(i64::MAX)
}
/// Read a signed BIGINT back as a `u64`, clamping a (corrupt / direct-DB) negative to 0 instead of
/// wrapping via `as`.
fn read_u64(v: i64) -> u64 {
v.max(0) as u64
}
/// The four RESERVED unit classes, in the order of the `usage_ledger` token columns
/// (`tokens_input`, `tokens_output`, `tokens_cache_read`, `tokens_cache_write`). Every other unit
/// class is an OPEN one and lives in `usage_ledger_units`.
const RESERVED_COLUMNS: [&str; 4] = [UNIT_INPUT, UNIT_OUTPUT, UNIT_CACHE_READ, UNIT_CACHE_WRITE];
fn is_reserved_unit(unit: &str) -> bool {
RESERVED_COLUMNS.contains(&unit)
}
/// Current Unix time in seconds, 0 if the system clock is before the epoch. The ONE source of
/// wall-clock stamps in this crate (`deleted_at`, `revoked_at`), so no write path can reach for a
/// convenient nearby integer instead: `revision` is also a BIGINT and binding it to a timestamp
/// column type-checks, round-trips, and satisfies every "is it set" assertion while recording a
/// time a few seconds after 1970.
fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
impl PostgresStore {
/// Connect to Postgres with the given libpq connection string / URL and ensure the schema. TLS
/// is not wired in this build (`NoTls`); front the database with a TLS-terminating proxy or a
/// local socket.
pub fn connect(conn_str: &str) -> RecordStoreResult<Self> {
let secret = dsn_password(conn_str);
// `render_pg_error`, not `e.to_string()`. A server-side refusal (bad database name, failed
// authentication, an unavailable extension) is a `db_error` whose Display is the literal
// two words "db error" — so the ONE error an operator hits before anything else works
// rendered as the least actionable string in the crate, while every query error had already
// been fixed to carry its SQLSTATE and message. Still scrubbed of the DSN password.
let client = Client::connect(conn_str, NoTls)
.map_err(|e| RecordStoreError(scrub(render_pg_error(&e), secret.as_deref())))?;
let store = Self {
client: Mutex::new(client),
};
store.migrate()?;
Ok(store)
}
fn lock(&self) -> std::sync::MutexGuard<'_, Client> {
self.client.lock().unwrap_or_else(|p| p.into_inner())
}
/// Open a transaction that gives every statement inside it ONE consistent snapshot, taken at the
/// transaction's first statement — REPEATABLE READ, not the default READ COMMITTED (which gives
/// each statement its own fresh snapshot, a torn-read hazard for any multi-statement read like
/// `get_usage` or the hydration delta queries).
pub(crate) fn snapshot_consistent_tx<'a>(
client: &'a mut Client,
) -> RecordStoreResult<postgres::Transaction<'a>> {
client
.build_transaction()
.isolation_level(postgres::IsolationLevel::RepeatableRead)
.start()
.store()
}
const MIGRATE_LOCK_KEY: i64 = 0x6275_7362_6172_5f70; // ASCII "busbar_p"
fn migrate(&self) -> RecordStoreResult<()> {
let mut client = self.lock();
client
.batch_execute(&format!(
"SELECT pg_advisory_lock({})",
Self::MIGRATE_LOCK_KEY
))
.store()?;
let result = Self::migrate_locked(&mut client);
let unlocked = client.batch_execute(&format!(
"SELECT pg_advisory_unlock({})",
Self::MIGRATE_LOCK_KEY
));
// A migration failure is the more important thing to report; don't mask it with an unlock
// failure. But if the migration itself SUCCEEDED and the unlock did not, that must not be
// swallowed: an un-released session-held advisory lock can hang a sibling node's connect()
// (which takes the same lock before its own migrate) for the remaining lifetime of this
// process's connection, with previously zero trace that it happened.
match (result, unlocked) {
(Ok(()), Err(e)) => Err(RecordStoreError(format!(
"migrate: schema migration succeeded but releasing the advisory lock failed ({e}); \
a sibling node's own migrate() may now hang waiting for this lock"
))),
(result, _) => result,
}
}
fn migrate_locked(client: &mut Client) -> RecordStoreResult<()> {
client
.batch_execute("CREATE TABLE IF NOT EXISTS busbar_schema (version BIGINT PRIMARY KEY)")
.store()?;
let version: i64 =
match client.query_opt("SELECT COALESCE(MAX(version), 0) FROM busbar_schema", &[]) {
Ok(Some(r)) => r.get(0),
Ok(None) => 0,
Err(e) if is_undefined_table(&e) => 0,
Err(e) => return Err(RecordStoreError(e.to_string())),
};
// ALREADY CURRENT: run no DDL at all. Every node runs `migrate()` on every connect, and
// `SCHEMA`'s `CREATE INDEX IF NOT EXISTS` takes a SHARE lock on its table before it
// discovers the index exists — first on `keys`, then on `credentials`. A `delete_key` on
// another node writes them in the OTHER order (credentials, then keys), so re-running the
// no-op DDL on a current database deadlocked a live key delete against a node merely
// connecting (observed: `40P01` on `UPDATE keys ... deleted_at`). A database at (or past)
// this build's version has every table and index this build creates.
if version >= SCHEMA_VERSION {
return Ok(());
}
let mut tx = client.transaction().store()?;
if version < 5 {
let legacy: bool = tx
.query_one(
"SELECT to_regclass('usage_counters') IS NOT NULL
OR to_regclass('virtual_keys') IS NOT NULL
OR to_regclass('aws_credentials') IS NOT NULL",
&[],
)
.store()?
.get(0);
if legacy {
tx.batch_execute(
"DROP TABLE IF EXISTS virtual_keys;
DROP TABLE IF EXISTS aws_credentials;
DROP TABLE IF EXISTS keys CASCADE;
DROP TABLE IF EXISTS credentials;
DROP TABLE IF EXISTS usage_counters;
DROP TABLE IF EXISTS usage_windows;
DROP TABLE IF EXISTS usage_ledger;
DROP TABLE IF EXISTS usage_metering;
DROP TABLE IF EXISTS audit_log;
DROP TABLE IF EXISTS denylist;
DROP TABLE IF EXISTS store_revision;",
)
.store()?;
}
}
tx.batch_execute(SCHEMA).store()?;
// v6 one-time backfill — see SCHEMA_VERSION's doc comment for why this is safe as a
// gated-once value backfill and would NOT be safe as a repeated/per-boot heuristic. Only
// fires when crossing INTO v6 (a store already at v6+ never re-runs this).
if version < 6 {
tx.execute(
"UPDATE usage_windows SET billable_requests = requests \
WHERE billable_requests = 0 AND requests > 0",
&[],
)
.store()?;
}
// v10 — see SCHEMA_VERSION. `SCHEMA`'s `CREATE TABLE IF NOT EXISTS` never alters a table
// that already exists, so on a 1.5.x (v6) database these statements ARE the upgrade.
// Nothing is dropped and no existing value is rewritten.
//
// Crossing INTO v10 only, and that gate is load-bearing rather than tidy: `ALTER TABLE`
// takes an ACCESS EXCLUSIVE lock on the table even when `IF NOT EXISTS` turns it into a
// no-op, and every node's connect runs `migrate()` — so an unconditional ALTER here locks
// `keys` out from under every other node's in-flight transaction on every connect (and
// deadlocks against one holding the `store_revision` row this transaction's `SCHEMA` insert
// also touches). The whole migration is ONE transaction with the version stamp, so a crash
// part-way leaves `version < 10` and the next connect re-runs it from the start.
if version < 10 {
tx.batch_execute(MIGRATE_V10_COLUMNS).store()?;
// The one v10 step that is not a pure addition: `priced_from_ms` joins the metering
// primary key. Every existing row carries `priced_from_ms = 0` (the column default),
// so the old key `(key_id, bucket, model, provider)` was already unique and the widened
// key admits every existing row unchanged.
tx.batch_execute(
"ALTER TABLE usage_metering DROP CONSTRAINT IF EXISTS usage_metering_pkey;
ALTER TABLE usage_metering ADD CONSTRAINT usage_metering_pkey
PRIMARY KEY (key_id, bucket, model, provider, priced_from_ms);",
)
.store()?;
}
tx.execute(
"INSERT INTO busbar_schema (version) VALUES ($1) ON CONFLICT (version) DO NOTHING",
&[&SCHEMA_VERSION],
)
.store()?;
tx.commit().store()?;
Ok(())
}
/// Bump and return the store-global revision INSIDE the caller's already-open transaction. Must
/// be the FIRST statement of any transaction that mutates `keys`/`credentials`/`denylist` (not
/// `denylist` directly — `add_denylist` doesn't take a revision param on the trait — but keys
/// and credentials do): calling it first fixes a single lock-acquisition order
/// (`store_revision` row, then whatever else the transaction touches) across every mutating
/// method, which is what makes cross-method deadlock structurally impossible.
fn next_revision(tx: &mut Transaction<'_>) -> RecordStoreResult<i64> {
tx.query_one(
"UPDATE store_revision SET revision = revision + 1 WHERE only_row RETURNING revision",
&[],
)
.store()?
.try_get(0)
.store()
}
}
fn labels_to_storage(labels: &std::collections::BTreeMap<String, String>) -> String {
serde_json::to_string(labels).unwrap_or_else(|_| "{}".to_string())
}
fn labels_from_storage(stored: &str) -> std::collections::BTreeMap<String, String> {
serde_json::from_str(stored).unwrap_or_default()
}
// SCOPE STORAGE. `allowed_pools` is unchanged since 1.5.x: a JSON array of bare pool names, or
// NULL. The v10 `allowed_scopes_by_kind` column carries every NON-pool grant as a JSON object
// `{kind: [value, ...]}` (NULL when there are none), so a pool-only key is stored byte-identically
// to what a 1.5.x build wrote, and a pre-v10 row (NULL in the new column) reads back exactly as it
// did. The partition mirrors the VirtualKey wire (`allowed_pools` + one field per kind):
// * `None` (grant omitted = every scope of every kind) -> both columns NULL;
// * `Some(list)` (exhaustive across ALL kinds, possibly empty) -> `allowed_pools` is ALWAYS a
// JSON array (possibly `[]`), so `Some([])` = no scopes never collapses into `None` = all, and
// a grant of only non-pool kinds never reads back as "every pool".
// A non-pool kind is NEVER folded into `allowed_pools`: that is the pre-1.6.0 defect where an
// `mcp_server` grant became a POOL grant on a store round-trip.
type ScopeColumns = (Option<String>, Option<String>);
fn scopes_to_storage(scopes: &Option<Vec<ScopeRef>>) -> ScopeColumns {
let Some(list) = scopes else {
return (None, None);
};
let mut pools: Vec<&str> = Vec::new();
let mut by_kind: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
for s in list {
if s.kind == "pool" {
pools.push(s.value.as_str());
} else {
by_kind
.entry(s.kind.as_str())
.or_default()
.push(s.value.as_str());
}
}
let pools = serde_json::to_string(&pools).unwrap_or_else(|_| "[]".to_string());
let by_kind = if by_kind.is_empty() {
None
} else {
Some(serde_json::to_string(&by_kind).unwrap_or_else(|_| "{}".to_string()))
};
(Some(pools), by_kind)
}
/// The inverse of [`scopes_to_storage`]: pools first, then every other kind in kind order — the
/// same canonical order the VirtualKey wire reassembles in.
fn scopes_from_storage(pools: Option<String>, by_kind: Option<String>) -> Option<Vec<ScopeRef>> {
if pools.is_none() && by_kind.is_none() {
return None;
}
let mut out: Vec<ScopeRef> = pools
.map(|p| serde_json::from_str::<Vec<String>>(p.trim()).unwrap_or_default())
.unwrap_or_default()
.into_iter()
.map(ScopeRef::pool)
.collect();
if let Some(by_kind) = by_kind {
let map: BTreeMap<String, Vec<String>> =
serde_json::from_str(by_kind.trim()).unwrap_or_default();
for (kind, values) in map {
out.extend(values.into_iter().map(|value| ScopeRef {
kind: kind.clone(),
value,
}));
}
}
Some(out)
}
fn row_to_key(r: &Row) -> VirtualKey {
VirtualKey {
id: r.get(0),
generation_hash: r.get(1),
name: r.get(2),
allowed_scopes: scopes_from_storage(
r.get::<_, Option<String>>(3),
r.get::<_, Option<String>>(14),
),
enabled: r.get(4),
created_at: read_u64(r.get::<_, i64>(5)),
group: r.get(6),
labels: labels_from_storage(&r.get::<_, String>(7)),
expires_at: r.get::<_, Option<i64>>(8).map(read_u64),
deleted_at: r.get::<_, Option<i64>>(9).map(read_u64),
revision: read_u64(r.get::<_, i64>(10)),
idp_subject: r.get(11),
binding_mode: r.get(12),
minted_by: r.get(13),
}
}
const KEY_COLUMNS: &str = "id,generation_hash,name,allowed_pools,enabled,created_at,key_group,labels,expires_at,deleted_at,revision,idp_subject,binding_mode,minted_by,allowed_scopes_by_kind";
fn secret_form_to_storage(f: SecretForm) -> &'static str {
match f {
SecretForm::None => "none",
SecretForm::Recoverable => "recoverable",
SecretForm::Digest => "digest",
}
}
fn secret_form_from_storage(s: &str) -> SecretForm {
match s {
"recoverable" => SecretForm::Recoverable,
"digest" => SecretForm::Digest,
_ => SecretForm::None,
}
}
const CRED_META_COLUMNS: &str = "id,key_id,kind,slot,public_id,secret_form,created_at,updated_at,expires_at,revoked_at,revoke_reason,revision";
/// The row index of `secret` in `SELECT {CRED_META_COLUMNS},secret FROM credentials ...` -- always
/// exactly the column COUNT of CRED_META_COLUMNS (12: id,key_id,kind,slot,public_id,secret_form,
/// created_at,updated_at,expires_at,revoked_at,revoke_reason,revision -- indices 0-11), since every
/// query that reads `secret` builds its SELECT by appending it right after that column list. Named
/// here instead of a bare `12` at each call site. The drift guard is a test, not an inline
/// assertion: `cred_secret_column_index_matches_cred_meta_columns_count` in this crate's `tests`
/// module fails if CRED_META_COLUMNS' column count ever changes without this constant being
/// updated to match, which is as close as stable Rust gets while `str::split` is not
/// const-evaluable.
const CRED_SECRET_COLUMN_INDEX: usize = 12;
fn row_to_cred_meta(r: &Row) -> CredentialMeta {
CredentialMeta {
id: r.get(0),
key_id: r.get(1),
kind: r.get(2),
slot: r.get::<_, i16>(3) as u8,
public_id: r.get(4),
secret_form: secret_form_from_storage(r.get::<_, &str>(5)),
created_at: read_u64(r.get::<_, i64>(6)),
updated_at: read_u64(r.get::<_, i64>(7)),
expires_at: r.get::<_, Option<i64>>(8).map(read_u64),
revoked_at: r.get::<_, Option<i64>>(9).map(read_u64),
revoke_reason: r.get(10),
revision: read_u64(r.get::<_, i64>(11)),
}
}
impl RecordStore for PostgresStore {
fn put_key(&self, key: &VirtualKey) -> RecordStoreResult<()> {
let (pools, by_kind) = scopes_to_storage(&key.allowed_scopes);
let labels = labels_to_storage(&key.labels);
let created = clamp(key.created_at);
let expires = key.expires_at.map(clamp);
let deleted = key.deleted_at.map(clamp);
let mut client = self.lock();
let mut tx = client.transaction().store()?;
let rev = Self::next_revision(&mut tx)?;
// The `WHERE` on the conflict branch is the TOMBSTONE PRECONDITION (see `Store::put_key`):
// a live-shaped write (`EXCLUDED.deleted_at IS NULL`) must not overwrite a tombstoned row,
// which would reissue an id the contract says is never reissued and revive every token
// minted before the delete. It rides on the statement rather than a preceding SELECT for
// the same reason `delete_key`'s `AND deleted_at IS NULL` does: under READ COMMITTED the
// conflict branch re-evaluates its WHERE against post-lock committed data, so this actually
// closes the TOCTOU window a separate SELECT leaves wide open.
// A write that CARRIES a tombstone is unaffected and still applies.
let changed = tx.execute(
"INSERT INTO keys
(id,generation_hash,name,allowed_pools,enabled,created_at,key_group,labels,expires_at,deleted_at,revision,
idp_subject,binding_mode,minted_by,allowed_scopes_by_kind)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)
ON CONFLICT (id) DO UPDATE SET
generation_hash=EXCLUDED.generation_hash, name=EXCLUDED.name,
allowed_pools=EXCLUDED.allowed_pools, enabled=EXCLUDED.enabled,
key_group=EXCLUDED.key_group, labels=EXCLUDED.labels,
expires_at=EXCLUDED.expires_at, deleted_at=EXCLUDED.deleted_at,
revision=EXCLUDED.revision, idp_subject=EXCLUDED.idp_subject,
binding_mode=EXCLUDED.binding_mode, minted_by=EXCLUDED.minted_by,
allowed_scopes_by_kind=EXCLUDED.allowed_scopes_by_kind
WHERE EXCLUDED.deleted_at IS NOT NULL OR keys.deleted_at IS NULL",
&[
&key.id, &key.generation_hash, &key.name, &pools, &key.enabled, &created,
&key.group, &labels, &expires, &deleted, &rev, &key.idp_subject,
&key.binding_mode, &key.minted_by, &by_kind,
],
)
.store()?;
if changed == 0 {
// The conflict branch matched a row but its WHERE rejected the write: the stored row is
// tombstoned and this one is not. That is the only way to reach 0 here.
return Err(RecordStoreError(format!(
"put_key: '{}' is tombstoned and its id is never reissued; refusing to clear the \
tombstone",
key.id
)));
}
tx.commit().store()?;
Ok(())
}
fn get_key(&self, id: &str) -> RecordStoreResult<Option<VirtualKey>> {
let sql = format!("SELECT {KEY_COLUMNS} FROM keys WHERE id=$1");
let row = self.lock().query_opt(&sql, &[&id]).store()?;
Ok(row.map(|r| row_to_key(&r)))
}
fn list_keys(&self) -> RecordStoreResult<Vec<VirtualKey>> {
// Deliberately UNFILTERED (tombstoned rows included) -- see the trait doc: this serves both
// the admin-listing caller (which filters deleted_at.is_none() itself) and list_keys_since's
// default fallback, which needs tombstones visible to drive credential eviction downstream.
let sql = format!("SELECT {KEY_COLUMNS} FROM keys ORDER BY created_at");
let rows = self.lock().query(&sql, &[]).store()?;
Ok(rows.iter().map(row_to_key).collect())
}
fn list_keys_since(&self, since: u64) -> RecordStoreResult<Vec<VirtualKey>> {
let sql = format!("SELECT {KEY_COLUMNS} FROM keys WHERE revision > $1 ORDER BY revision");
let rows = self.lock().query(&sql, &[&clamp(since)]).store()?;
Ok(rows.iter().map(row_to_key).collect())
}
fn delete_key(&self, id: &str) -> RecordStoreResult<()> {
// TOMBSTONE, not a hard delete: the `keys` row survives (billing/audit attribution keeps
// resolving it forever) while every credential row for it is destroyed. Both happen in ONE
// transaction stamped with the SAME revision, which is the load-bearing property for
// hydration soundness: a REPEATABLE READ hydration snapshot can never observe the
// tombstoned key without the credentials already being gone, so a delta-consumer that
// reacts to "this key's revision-delta shows deleted_at newly set" by evicting all its
// cached credentials is provably correct -- there is no window where the credential rows'
// own (now-nonexistent) deltas would have been needed to convey the deletion.
let mut client = self.lock();
let mut tx = client.transaction().store()?;
let already_deleted: Option<bool> = tx
.query_opt(
"SELECT deleted_at IS NOT NULL FROM keys WHERE id=$1",
&[&id],
)
.store()?
.map(|r| r.get(0));
match already_deleted {
None => {
// Unknown id: an ERROR, and deliberately NOT the same case as the already-tombstoned
// one below. The trait settles them apart because "already tombstoned" means the
// operator's intent is satisfied and the evidence is on disk, while "no such id"
// means nothing was touched - and answering Ok there tells an operator who typo'd
// an id that a key was revoked when none was.
return Err(RecordStoreError(format!("delete_key: unknown id '{id}'")));
}
Some(true) => {
// Already tombstoned: no-op, not an error.
tx.commit().store()?;
return Ok(());
}
Some(false) => {}
}
let rev = Self::next_revision(&mut tx)?;
// `deleted_at` is a WALL-CLOCK stamp and `revision` is the store-global counter. They are
// both BIGINT, so binding one value to both columns compiles, round-trips and satisfies
// every "is this key tombstoned" check -- while telling every operator, retention job and
// cross-backend comparison that the key was deleted a few seconds after 1970. Bound
// separately, and pinned by
// `delete_key_stamps_deleted_at_with_a_wall_clock_time_not_the_revision`.
let now = clamp(now_secs());
tx.execute("DELETE FROM credentials WHERE key_id=$1", &[&id])
.store()?;
// `AND deleted_at IS NULL` re-states the guard the SELECT above already checked, IN the
// UPDATE's own WHERE clause: under Postgres' READ COMMITTED semantics, an UPDATE takes a row
// lock and re-evaluates its WHERE against the post-lock committed data, so this closes the
// TOCTOU window the plain `SELECT` above cannot -- two concurrent delete_key calls on the
// same id now genuinely serialize (the loser's UPDATE matches 0 rows) instead of both
// unconditionally overwriting `deleted_at`/`revision` regardless of which committed first.
let changed = tx
.execute(
"UPDATE keys SET enabled=FALSE, deleted_at=$2, revision=$3 \
WHERE id=$1 AND deleted_at IS NULL",
&[&id, &now, &rev],
)
.store()?;
// A concurrent delete_key committed between our SELECT and this UPDATE: idempotent no-op,
// same as the `Some(true)` branch above -- not an error.
if changed == 0 {
tx.commit().store()?;
return Ok(());
}
tx.commit().store()?;
Ok(())
}
fn scrub_key(&self, id: &str) -> RecordStoreResult<()> {
// PII-erasure only: null name/labels on an ALREADY-tombstoned key. Errors if unknown or
// still live -- scrubbing a live key would be silent, un-auditable data loss on an active
// principal (the trait doc's own guard: go through delete_key first).
let mut client = self.lock();
let mut tx = client.transaction().store()?;
let deleted: Option<bool> = tx
.query_opt(
"SELECT deleted_at IS NOT NULL FROM keys WHERE id=$1",
&[&id],
)
.store()?
.map(|r| r.get(0));
match deleted {
None => return Err(RecordStoreError(format!("scrub_key: unknown key {id}"))),
Some(false) => {
return Err(RecordStoreError(format!(
"scrub_key: key {id} is not tombstoned -- call delete_key first"
)))
}
Some(true) => {}
}
let rev = Self::next_revision(&mut tx)?;