oficina / home Public

Diagnose historical directory schema without granting admission

Paul Campbell pushed by paul@keymail.dev 52aa7c7318fc9b25444575336331d9c2cb271298 parent dd5ee8d
5 files changed, +1031 −0
  • internal/home/diagnostic_profiles/legacy-directory-v1.json +446 −0
  • internal/home/diagnostic_profiles/provenance.json +22 −0
  • internal/home/legacy_schema_diagnostic.go +194 −0
  • internal/home/legacy_schema_diagnostic_test.go +368 −0
  • internal/home/schema_inventory.go +1 −0

CI passed — run details

diff --git a/internal/home/diagnostic_profiles/legacy-directory-v1.json b/internal/home/diagnostic_profiles/legacy-directory-v1.json
new file mode 100644
index 0000000..f2392c7
--- /dev/null
+++ b/internal/home/diagnostic_profiles/legacy-directory-v1.json
@@ -0,0 +1,446 @@
+[
+ {
+ "Type": "index",
+ "Name": "idx_signin_links_expires_at",
+ "Table": "signin_links",
+ "SQL": "CREATE INDEX idx_signin_links_expires_at ON signin_links(expires_at)"
+ },
+ {
+ "Type": "index",
+ "Name": "memberships_person",
+ "Table": "memberships",
+ "SQL": "CREATE INDEX memberships_person ON memberships(person_ref, team_id)"
+ },
+ {
+ "Type": "index",
+ "Name": "oficina_handoff_inbox_expiry",
+ "Table": "oficina_handoff_inbox",
+ "SQL": "CREATE INDEX oficina_handoff_inbox_expiry ON oficina_handoff_inbox(expires_at)"
+ },
+ {
+ "Type": "index",
+ "Name": "oficina_handoff_pending_expiry",
+ "Table": "oficina_handoff_pending",
+ "SQL": "CREATE INDEX oficina_handoff_pending_expiry ON oficina_handoff_pending(expires_at)"
+ },
+ {
+ "Type": "index",
+ "Name": "oficina_handoff_replay_expiry",
+ "Table": "oficina_handoff_replay",
+ "SQL": "CREATE INDEX oficina_handoff_replay_expiry ON oficina_handoff_replay(expires_at)"
+ },
+ {
+ "Type": "index",
+ "Name": "passkey_credentials_subject",
+ "Table": "passkey_credentials",
+ "SQL": "CREATE INDEX passkey_credentials_subject\n ON passkey_credentials (subject)"
+ },
+ {
+ "Type": "index",
+ "Name": "passkey_recovery_codes_subject",
+ "Table": "passkey_recovery_codes",
+ "SQL": "CREATE INDEX passkey_recovery_codes_subject\n ON passkey_recovery_codes (subject)"
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_directory_operator_consumer_records_1",
+ "Table": "directory_operator_consumer_records",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_directory_operator_consumer_records_2",
+ "Table": "directory_operator_consumer_records",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_directory_operator_owner_receipts_1",
+ "Table": "directory_operator_owner_receipts",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_directory_operator_owner_receipts_2",
+ "Table": "directory_operator_owner_receipts",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_directory_operator_owner_receipts_3",
+ "Table": "directory_operator_owner_receipts",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_directory_operator_results_1",
+ "Table": "directory_operator_results",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_directory_operator_results_2",
+ "Table": "directory_operator_results",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_memberships_1",
+ "Table": "memberships",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_oficina_handoff_inbox_1",
+ "Table": "oficina_handoff_inbox",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_oficina_handoff_inbox_2",
+ "Table": "oficina_handoff_inbox",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_oficina_handoff_pending_1",
+ "Table": "oficina_handoff_pending",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_oficina_handoff_pending_2",
+ "Table": "oficina_handoff_pending",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_oficina_handoff_replay_1",
+ "Table": "oficina_handoff_replay",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_passkey_challenges_1",
+ "Table": "passkey_challenges",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_passkey_credentials_1",
+ "Table": "passkey_credentials",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_passkey_pending_1",
+ "Table": "passkey_pending",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_passkey_recovery_codes_1",
+ "Table": "passkey_recovery_codes",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_people_1",
+ "Table": "people",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_people_2",
+ "Table": "people",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_rastrillo_migrations_1",
+ "Table": "rastrillo_migrations",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_roster_consumers_1",
+ "Table": "roster_consumers",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_roster_operator_receipts_1",
+ "Table": "roster_operator_receipts",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_roster_tokens_1",
+ "Table": "roster_tokens",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_roster_tokens_2",
+ "Table": "roster_tokens",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_sessions_1",
+ "Table": "sessions",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_signin_links_1",
+ "Table": "signin_links",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_team_instances_1",
+ "Table": "team_instances",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_team_instances_2",
+ "Table": "team_instances",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_team_instances_3",
+ "Table": "team_instances",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_teams_1",
+ "Table": "teams",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_teams_2",
+ "Table": "teams",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_verification_active_1",
+ "Table": "verification_active",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_verification_active_2",
+ "Table": "verification_active",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_verification_attempts_1",
+ "Table": "verification_attempts",
+ "SQL": ""
+ },
+ {
+ "Type": "index",
+ "Name": "sqlite_autoindex_verification_outcomes_1",
+ "Table": "verification_outcomes",
+ "SQL": ""
+ },
+ {
+ "Type": "table",
+ "Name": "_litestream_lock",
+ "Table": "_litestream_lock",
+ "SQL": "CREATE TABLE _litestream_lock (id INTEGER)"
+ },
+ {
+ "Type": "table",
+ "Name": "_litestream_seq",
+ "Table": "_litestream_seq",
+ "SQL": "CREATE TABLE _litestream_seq (id INTEGER PRIMARY KEY, seq INTEGER)"
+ },
+ {
+ "Type": "table",
+ "Name": "directory_operator_consumer_records",
+ "Table": "directory_operator_consumer_records",
+ "SQL": "CREATE TABLE directory_operator_consumer_records (\n consumer_id TEXT PRIMARY KEY REFERENCES roster_consumers(consumer_id),\n operation_id TEXT NOT NULL UNIQUE REFERENCES roster_operator_receipts(operation_id),\n sequence INTEGER NOT NULL CHECK(typeof(sequence)='integer' AND sequence\u003e0),\n generation TEXT NOT NULL CHECK(length(generation)=43),\n record_digest BLOB NOT NULL CHECK(typeof(record_digest)='blob' AND length(record_digest)=32)\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "directory_operator_owner_receipts",
+ "Table": "directory_operator_owner_receipts",
+ "SQL": "CREATE TABLE directory_operator_owner_receipts (\n issuer TEXT NOT NULL,\n owner_operation_id TEXT NOT NULL CHECK(length(owner_operation_id)=43),\n directory_operation_id TEXT NOT NULL UNIQUE REFERENCES directory_operator_results(operation_id) DEFERRABLE INITIALLY DEFERRED,\n team_id INTEGER NOT NULL UNIQUE REFERENCES teams(id),\n PRIMARY KEY(issuer,owner_operation_id)\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "directory_operator_results",
+ "Table": "directory_operator_results",
+ "SQL": "CREATE TABLE directory_operator_results (\n operation_id TEXT PRIMARY KEY CHECK(length(operation_id)=43),\n action TEXT NOT NULL,\n sequence INTEGER NOT NULL UNIQUE CHECK(typeof(sequence)='integer' AND sequence\u003e0),\n authorization_head TEXT NOT NULL CHECK(length(authorization_head)=43),\n request_mac BLOB NOT NULL CHECK(typeof(request_mac)='blob' AND length(request_mac)=32),\n sealed_result BLOB NOT NULL CHECK(typeof(sealed_result)='blob' AND length(sealed_result) BETWEEN 29 AND 49180),\n completed_at INTEGER NOT NULL CHECK(typeof(completed_at)='integer' AND completed_at\u003e0)\n, operator_ref TEXT NOT NULL DEFAULT '')"
+ },
+ {
+ "Type": "table",
+ "Name": "directory_operator_state",
+ "Table": "directory_operator_state",
+ "SQL": "CREATE TABLE directory_operator_state (\n singleton INTEGER PRIMARY KEY CHECK(singleton=1),\n origin TEXT NOT NULL,\n installation TEXT NOT NULL,\n registry TEXT NOT NULL,\n device TEXT NOT NULL,\n sequence INTEGER NOT NULL CHECK(typeof(sequence)='integer' AND sequence\u003e0),\n head TEXT NOT NULL CHECK(length(head)=43),\n completed_at INTEGER NOT NULL CHECK(typeof(completed_at)='integer' AND completed_at\u003e0)\n, key_id TEXT NOT NULL DEFAULT '')"
+ },
+ {
+ "Type": "table",
+ "Name": "memberships",
+ "Table": "memberships",
+ "SQL": "CREATE TABLE memberships (\n team_id INTEGER NOT NULL REFERENCES teams(id) ON DELETE RESTRICT,\n person_ref TEXT NOT NULL CHECK(length(person_ref) = 29 AND substr(person_ref,1,3) = 'pr_' AND substr(person_ref,4) NOT GLOB '*[^a-z2-7]*'),\n role TEXT NOT NULL CHECK(role IN ('owner', 'member')),\n PRIMARY KEY(team_id, person_ref)\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "oficina_handoff_clock",
+ "Table": "oficina_handoff_clock",
+ "SQL": "CREATE TABLE oficina_handoff_clock (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n observed INTEGER NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "oficina_handoff_inbox",
+ "Table": "oficina_handoff_inbox",
+ "SQL": "CREATE TABLE oficina_handoff_inbox (\n handle_hash TEXT PRIMARY KEY,\n jti_hash TEXT NOT NULL UNIQUE,\n sealed_token BLOB NOT NULL,\n created_at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "oficina_handoff_pending",
+ "Table": "oficina_handoff_pending",
+ "SQL": "CREATE TABLE oficina_handoff_pending (\n secret_hash TEXT PRIMARY KEY,\n nonce_hash TEXT NOT NULL UNIQUE,\n sealed_path BLOB NOT NULL,\n created_at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "oficina_handoff_replay",
+ "Table": "oficina_handoff_replay",
+ "SQL": "CREATE TABLE oficina_handoff_replay (\n jti_hash TEXT PRIMARY KEY,\n expires_at INTEGER NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "passkey_challenges",
+ "Table": "passkey_challenges",
+ "SQL": "CREATE TABLE passkey_challenges (\n challenge TEXT PRIMARY KEY,\n subject TEXT NOT NULL,\n purpose TEXT NOT NULL,\n expires_at TEXT NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "passkey_credentials",
+ "Table": "passkey_credentials",
+ "SQL": "CREATE TABLE passkey_credentials (\n id TEXT PRIMARY KEY,\n subject TEXT NOT NULL,\n public_key BLOB NOT NULL,\n sign_count INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "passkey_pending",
+ "Table": "passkey_pending",
+ "SQL": "CREATE TABLE passkey_pending (\n token_hash TEXT PRIMARY KEY,\n subject TEXT NOT NULL,\n method TEXT NOT NULL DEFAULT '',\n return_to TEXT NOT NULL DEFAULT '',\n expires_at TEXT NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "passkey_recovery_codes",
+ "Table": "passkey_recovery_codes",
+ "SQL": "CREATE TABLE passkey_recovery_codes (\n code_hash TEXT PRIMARY KEY,\n subject TEXT NOT NULL,\n created_at TEXT NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "people",
+ "Table": "people",
+ "SQL": "CREATE TABLE people (\n person_ref TEXT PRIMARY KEY,\n blind_index TEXT NOT NULL UNIQUE, -- UNIQUE already indexes it; no second index\n created_at TEXT NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "rastrillo_migrations",
+ "Table": "rastrillo_migrations",
+ "SQL": "CREATE TABLE rastrillo_migrations (\n id TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL,\n checksum TEXT NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "roster_consumers",
+ "Table": "roster_consumers",
+ "SQL": "CREATE TABLE roster_consumers (\n consumer_id TEXT PRIMARY KEY REFERENCES team_instances(consumer_id) ON DELETE RESTRICT,\n team_id INTEGER NOT NULL REFERENCES teams(id) ON DELETE RESTRICT,\n app TEXT NOT NULL,\n origin TEXT NOT NULL,\n enabled INTEGER NOT NULL CHECK(enabled IN (0,1)),\n FOREIGN KEY(team_id,app) REFERENCES team_instances(team_id,app) ON DELETE RESTRICT\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "roster_generation",
+ "Table": "roster_generation",
+ "SQL": "CREATE TABLE roster_generation (\n singleton INTEGER PRIMARY KEY CHECK(singleton = 1),\n generation TEXT NOT NULL CHECK(length(generation) = 43 AND generation NOT GLOB '*[^a-zA-Z0-9_-]*')\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "roster_operator_receipts",
+ "Table": "roster_operator_receipts",
+ "SQL": "CREATE TABLE roster_operator_receipts (\n operation_id TEXT PRIMARY KEY CHECK(length(operation_id) BETWEEN 1 AND 128 AND operation_id NOT GLOB '*[^a-zA-Z0-9_-]*'),\n sequence INTEGER NOT NULL CHECK(typeof(sequence) = 'integer' AND sequence \u003e 0),\n operation TEXT NOT NULL CHECK(operation IN ('bootstrap','provision','rotate','disable','restore')),\n consumer_id TEXT CHECK(consumer_id IS NULL OR (length(consumer_id) BETWEEN 1 AND 128 AND consumer_id NOT GLOB '*[^a-zA-Z0-9_-]*')),\n generation TEXT NOT NULL CHECK(length(generation) = 43 AND generation NOT GLOB '*[^a-zA-Z0-9_-]*'),\n record_digest BLOB NOT NULL CHECK(typeof(record_digest) = 'blob' AND length(record_digest) = 32),\n completed_at INTEGER NOT NULL CHECK(typeof(completed_at) = 'integer' AND completed_at \u003e 0)\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "roster_tokens",
+ "Table": "roster_tokens",
+ "SQL": "CREATE TABLE roster_tokens (\n token_hash BLOB PRIMARY KEY CHECK(typeof(token_hash) = 'blob' AND length(token_hash) = 32),\n consumer_id TEXT NOT NULL REFERENCES roster_consumers(consumer_id) ON DELETE RESTRICT,\n slot TEXT NOT NULL CHECK(slot IN ('current','previous')),\n issued_at INTEGER NOT NULL CHECK(typeof(issued_at) = 'integer' AND issued_at \u003e 0),\n expires_at INTEGER,\n UNIQUE(consumer_id,slot),\n CHECK((slot = 'current' AND expires_at IS NULL) OR\n (slot = 'previous' AND typeof(expires_at) = 'integer' AND expires_at \u003e issued_at AND expires_at - issued_at \u003c= 300))\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "sessions",
+ "Table": "sessions",
+ "SQL": "CREATE TABLE sessions (\n token_hash TEXT PRIMARY KEY,\n subject TEXT NOT NULL,\n method TEXT NOT NULL DEFAULT '',\n auth_time TEXT NOT NULL DEFAULT '',\n created_at TEXT NOT NULL,\n expires_at TEXT NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "signin_links",
+ "Table": "signin_links",
+ "SQL": "CREATE TABLE signin_links (\n token_hash TEXT PRIMARY KEY,\n sealed_address BLOB NOT NULL,\n purpose TEXT NOT NULL,\n expires_at TEXT NOT NULL\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "sqlite_sequence",
+ "Table": "sqlite_sequence",
+ "SQL": "CREATE TABLE sqlite_sequence(name,seq)"
+ },
+ {
+ "Type": "table",
+ "Name": "team_instances",
+ "Table": "team_instances",
+ "SQL": "CREATE TABLE team_instances (\n team_id INTEGER NOT NULL REFERENCES teams(id) ON DELETE RESTRICT,\n app TEXT NOT NULL,\n origin TEXT NOT NULL UNIQUE,\n consumer_id TEXT NOT NULL UNIQUE,\n state TEXT NOT NULL CHECK(state IN ('pending', 'live', 'disabled')),\n PRIMARY KEY(team_id, app)\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "teams",
+ "Table": "teams",
+ "SQL": "CREATE TABLE teams (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n sqid TEXT NOT NULL UNIQUE CHECK(length(sqid) BETWEEN 1 AND 64 AND sqid NOT GLOB '*[^a-zA-Z0-9]*'),\n label TEXT NOT NULL UNIQUE CHECK(length(label) BETWEEN 1 AND 63 AND label NOT GLOB '*[^a-z0-9-]*' AND substr(label,1,1) != '-' AND substr(label,-1,1) != '-'),\n sealed_name BLOB NOT NULL CHECK(typeof(sealed_name) = 'blob' AND length(sealed_name) BETWEEN 29 AND 284),\n created_at INTEGER NOT NULL CHECK(created_at \u003e 0),\n roster_epoch INTEGER NOT NULL DEFAULT 1 CHECK(typeof(roster_epoch) = 'integer' AND roster_epoch \u003e 0)\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "verification_active",
+ "Table": "verification_active",
+ "SQL": "CREATE TABLE verification_active (\n consumer_id TEXT PRIMARY KEY REFERENCES roster_consumers(consumer_id),\n operation_id TEXT NOT NULL UNIQUE REFERENCES verification_attempts(operation_id)\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "verification_attempts",
+ "Table": "verification_attempts",
+ "SQL": "CREATE TABLE verification_attempts (\n operation_id TEXT PRIMARY KEY CHECK(length(operation_id)=43),\n consumer_id TEXT NOT NULL REFERENCES roster_consumers(consumer_id),\n team_id INTEGER NOT NULL REFERENCES teams(id),\n app TEXT NOT NULL,\n origin TEXT NOT NULL,\n generation TEXT NOT NULL CHECK(length(generation)=43),\n record_sequence INTEGER NOT NULL CHECK(typeof(record_sequence)='integer' AND record_sequence\u003e0),\n record_digest BLOB NOT NULL CHECK(typeof(record_digest)='blob' AND length(record_digest)=32),\n expected_epoch INTEGER NOT NULL CHECK(typeof(expected_epoch)='integer' AND expected_epoch\u003e0),\n owner_ref TEXT NOT NULL CHECK(length(owner_ref)=29),\n issued_at INTEGER NOT NULL CHECK(typeof(issued_at)='integer' AND issued_at\u003e0),\n expires_at INTEGER NOT NULL CHECK(typeof(expires_at)='integer' AND expires_at\u003eissued_at AND expires_at-issued_at\u003c=600),\n authorization_digest BLOB NOT NULL CHECK(typeof(authorization_digest)='blob' AND length(authorization_digest)=32)\n)"
+ },
+ {
+ "Type": "table",
+ "Name": "verification_outcomes",
+ "Table": "verification_outcomes",
+ "SQL": "CREATE TABLE verification_outcomes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n attempt_id TEXT NOT NULL REFERENCES verification_attempts(operation_id),\n operator_operation_id TEXT NOT NULL CHECK(length(operator_operation_id)=43),\n kind TEXT NOT NULL CHECK(kind IN ('opened','expired','activated')),\n completed_at INTEGER NOT NULL CHECK(typeof(completed_at)='integer' AND completed_at\u003e0),\n UNIQUE(attempt_id,operator_operation_id,kind)\n)"
+ },
+ {
+ "Type": "trigger",
+ "Name": "memberships_epoch_delete",
+ "Table": "memberships",
+ "SQL": "CREATE TRIGGER memberships_epoch_delete AFTER DELETE ON memberships BEGIN\n SELECT CASE WHEN (SELECT roster_epoch FROM teams WHERE id = OLD.team_id) = 9223372036854775807 THEN RAISE(ABORT,'roster epoch exhausted') END;\n UPDATE teams SET roster_epoch = roster_epoch + 1 WHERE id = OLD.team_id;\nEND"
+ },
+ {
+ "Type": "trigger",
+ "Name": "memberships_epoch_insert",
+ "Table": "memberships",
+ "SQL": "CREATE TRIGGER memberships_epoch_insert AFTER INSERT ON memberships BEGIN\n SELECT CASE WHEN (SELECT roster_epoch FROM teams WHERE id = NEW.team_id) = 9223372036854775807 THEN RAISE(ABORT,'roster epoch exhausted') END;\n UPDATE teams SET roster_epoch = roster_epoch + 1 WHERE id = NEW.team_id;\nEND"
+ },
+ {
+ "Type": "trigger",
+ "Name": "memberships_epoch_update",
+ "Table": "memberships",
+ "SQL": "CREATE TRIGGER memberships_epoch_update AFTER UPDATE ON memberships BEGIN\n SELECT CASE WHEN EXISTS(SELECT 1 FROM teams WHERE id IN (OLD.team_id,NEW.team_id) AND roster_epoch = 9223372036854775807) THEN RAISE(ABORT,'roster epoch exhausted') END;\n UPDATE teams SET roster_epoch = roster_epoch + 1 WHERE id IN (OLD.team_id,NEW.team_id);\nEND"
+ }
+]
diff --git a/internal/home/diagnostic_profiles/provenance.json b/internal/home/diagnostic_profiles/provenance.json
new file mode 100644
index 0000000..69c980f
--- /dev/null
+++ b/internal/home/diagnostic_profiles/provenance.json
@@ -0,0 +1,22 @@
+{
+ "home/0001_people": {
+ "SHA256": "52de6c3fa2c323f0e7ba54c62f7c518811a4d684f4a76208647fe71e33e130fe",
+ "Checksum": "5e65372f0796be99d6fcbba09c97b92ed36a5faf1bf36a53be6f5caf0771eb9b",
+ "Source": "651e5b3d3f95be0d788847f38272a5fda081b14c",
+ "Path": "internal/home/migrations/0001_people.sql",
+ "GitBlob": "9666a9da13bf88017b56919f9c33ae84e2b74545"
+ },
+ "home/0002_signin_links": {
+ "SHA256": "8dc8b9c64f2b8222b7b2f3161a77de3903a26e436f1d9ee28552c984ff1ae884",
+ "Checksum": "11429f3a12f605f0e24f890952a2831a44d8e5030d10471c7a5c1c3672e630a7",
+ "Source": "651e5b3d3f95be0d788847f38272a5fda081b14c",
+ "Path": "internal/home/migrations/0002_signin_links.sql",
+ "GitBlob": "69a4bc9b654b28dbcc712a842b7a6174190cec71"
+ },
+ "passkey/0001_init": {
+ "SHA256": "c488dfac6b479b517dd7e34bfccdef246a4f8b4602c15b96be95f67b52f278ce",
+ "Checksum": "56d5073a880c3b1b8330654873b13cbd42a72596138499380b5a013e4d43196e",
+ "Source": "github.com/carlosframework/rastrillo@v0.22.0",
+ "Path": "passkey/migrations/0001_init.sql"
+ }
+}
diff --git a/internal/home/legacy_schema_diagnostic.go b/internal/home/legacy_schema_diagnostic.go
new file mode 100644
index 0000000..848f47f
--- /dev/null
+++ b/internal/home/legacy_schema_diagnostic.go
@@ -0,0 +1,194 @@
+package home
+
+import (
+ "context"
+ "database/sql"
+ "database/sql/driver"
+ _ "embed"
+ "encoding/json"
+ "log/slog"
+
+ "github.com/carlosframework/rastrillo/migrate"
+)
+
+const (
+ legacyDiagnosticProfile = "legacy-directory-v1"
+ legacyDiagnosticMaxRows = 1000
+ legacyDiagnosticNameBytes = 256
+ legacyDiagnosticSQLBytes = 65536
+)
+
+//go:embed diagnostic_profiles/legacy-directory-v1.json
+var legacyDiagnosticJSON []byte
+
+type legacyDiagnosticObject struct{ Type, Name, Table, SQL string }
+type legacyDiagnosticResult struct {
+ status string
+ occupied bool
+}
+
+var legacyDiagnosticObjects = func() []legacyDiagnosticObject {
+ var objects []legacyDiagnosticObject
+ if err := json.Unmarshal(legacyDiagnosticJSON, &objects); err != nil {
+ panic(err)
+ }
+ return objects
+}()
+
+func legacyDiagnosticMigrations() ([]migrate.Migration, bool) {
+ return uniqueLegacyMigrations(BootSchema.All(), (Runtime{role: "directory"}).Schema().All())
+}
+
+func uniqueLegacyMigrations(groups ...[]migrate.Migration) ([]migrate.Migration, bool) {
+ seen := map[string]migrate.Migration{}
+ var result []migrate.Migration
+ for _, group := range groups {
+ for _, m := range group {
+ if m.Fn != nil || m.ID == "" || m.SQL == "" {
+ return nil, false
+ }
+ if prior, exists := seen[m.ID]; exists {
+ if prior.SQL != m.SQL {
+ return nil, false
+ }
+ continue
+ }
+ seen[m.ID] = m
+ result = append(result, m)
+ }
+ }
+ return result, len(result) > 0
+}
+
+func logLegacySchemaDiagnostic(ctx context.Context, d *sql.DB, role string, logger *slog.Logger) {
+ if role != "directory" {
+ return
+ }
+ result := inspectLegacySchema(ctx, d)
+ fields := []any{"profile", legacyDiagnosticProfile, "result", result.status}
+ if result.status == "match" {
+ fields = append(fields, "legacy_credentials_present", result.occupied)
+ }
+ logger.Info("legacy schema diagnostic", fields...)
+}
+
+func inspectLegacySchema(ctx context.Context, d *sql.DB) (result legacyDiagnosticResult) {
+ result.status = "unavailable"
+ if ctx == nil || d == nil || len(legacyDiagnosticObjects) == 0 {
+ return
+ }
+ conn, err := d.Conn(ctx)
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ if _, err = conn.ExecContext(ctx, "BEGIN"); err != nil {
+ return
+ }
+ defer func() {
+ if !rollbackLegacyDiagnostic(ctx, conn) {
+ result = legacyDiagnosticResult{status: "unavailable"}
+ }
+ }()
+ result = readLegacySchema(ctx, conn)
+ return
+}
+
+func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResult {
+ unavailable := legacyDiagnosticResult{status: "unavailable"}
+ mismatch := legacyDiagnosticResult{status: "mismatch"}
+ migrations, ok := legacyDiagnosticMigrations()
+ if !ok {
+ return unavailable
+ }
+ expected := map[string]string{}
+ for _, m := range migrations {
+ expected[m.ID] = migrate.Checksum(m.SQL)
+ }
+ rows, err := conn.QueryContext(ctx, `SELECT
+ CASE WHEN typeof(id)='text' AND length(CAST(id AS BLOB))<=256 THEN id END,
+ CASE WHEN typeof(checksum)='text' AND length(CAST(checksum AS BLOB))=64 THEN checksum END
+ FROM rastrillo_migrations LIMIT 1001`)
+ if err != nil {
+ return unavailable
+ }
+ matched, count := true, 0
+ for rows.Next() {
+ count++
+ var id, sum sql.NullString
+ if rows.Scan(&id, &sum) != nil {
+ rows.Close()
+ return unavailable
+ }
+ if !id.Valid || !sum.Valid || count > legacyDiagnosticMaxRows || expected[id.String] != sum.String {
+ matched = false
+ }
+ delete(expected, id.String)
+ }
+ scanErr, closeErr := rows.Err(), rows.Close()
+ if scanErr != nil || closeErr != nil || ctx.Err() != nil {
+ return unavailable
+ }
+ if !matched || len(expected) != 0 {
+ return mismatch
+ }
+ objects := map[string]legacyDiagnosticObject{}
+ for _, object := range legacyDiagnosticObjects {
+ objects[object.Type+"/"+object.Name] = object
+ }
+ rows, err = conn.QueryContext(ctx, `SELECT
+ CASE WHEN typeof(type)='text' AND length(CAST(type AS BLOB))<=16 THEN type END,
+ CASE WHEN typeof(name)='text' AND length(CAST(name AS BLOB))<=256 THEN name END,
+ CASE WHEN typeof(tbl_name)='text' AND length(CAST(tbl_name AS BLOB))<=256 THEN tbl_name END,
+ CASE WHEN typeof(coalesce(sql,''))='text' AND length(CAST(coalesce(sql,'') AS BLOB))<=65536 THEN coalesce(sql,'') END
+ FROM sqlite_schema LIMIT 1001`)
+ if err != nil {
+ return unavailable
+ }
+ count = 0
+ for rows.Next() {
+ count++
+ var kind, name, table, statement sql.NullString
+ if rows.Scan(&kind, &name, &table, &statement) != nil {
+ rows.Close()
+ return unavailable
+ }
+ object := legacyDiagnosticObject{kind.String, name.String, table.String, statement.String}
+ key := kind.String + "/" + name.String
+ prior, exists := objects[key]
+ if !kind.Valid || !name.Valid || !table.Valid || !statement.Valid || count > legacyDiagnosticMaxRows || !exists || prior != object {
+ matched = false
+ }
+ delete(objects, key)
+ }
+ scanErr, closeErr = rows.Err(), rows.Close()
+ if scanErr != nil || closeErr != nil || ctx.Err() != nil {
+ return unavailable
+ }
+ if !matched || len(objects) != 0 {
+ return mismatch
+ }
+ var occupied bool
+ // Pending challenges and recovery material count too: none is disposable here.
+ err = conn.QueryRowContext(ctx, `SELECT
+ EXISTS(SELECT 1 FROM people) OR EXISTS(SELECT 1 FROM signin_links) OR
+ EXISTS(SELECT 1 FROM passkey_credentials) OR EXISTS(SELECT 1 FROM passkey_challenges) OR
+ EXISTS(SELECT 1 FROM passkey_pending) OR EXISTS(SELECT 1 FROM passkey_recovery_codes)`).Scan(&occupied)
+ if err != nil || ctx.Err() != nil {
+ return unavailable
+ }
+ return legacyDiagnosticResult{status: "match", occupied: occupied}
+}
+
+type legacyDiagnosticConnection interface {
+ ExecContext(context.Context, string, ...any) (sql.Result, error)
+ Raw(func(any) error) error
+}
+
+func rollbackLegacyDiagnostic(ctx context.Context, conn legacyDiagnosticConnection) bool {
+ if _, err := conn.ExecContext(context.WithoutCancel(ctx), "ROLLBACK"); err != nil {
+ conn.Raw(func(any) error { return driver.ErrBadConn })
+ return false
+ }
+ return true
+}
diff --git a/internal/home/legacy_schema_diagnostic_test.go b/internal/home/legacy_schema_diagnostic_test.go
new file mode 100644
index 0000000..ef19708
--- /dev/null
+++ b/internal/home/legacy_schema_diagnostic_test.go
@@ -0,0 +1,368 @@
+//go:build linux
+
+package home
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "database/sql/driver"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io/fs"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/home/internal/home/sealtest"
+ "amadan.net/oficina/home/internal/operator"
+ "github.com/carlosframework/rastrillo/db"
+ "github.com/carlosframework/rastrillo/migrate"
+)
+
+func legacyDiagnosticFixture(t *testing.T, historical, replication bool) *db.DB {
+ t.Helper()
+ RegisterSecureDelete()
+ d, err := db.Open(filepath.Join(t.TempDir(), "legacy.db"), quietLogger())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { d.Close() })
+ if historical {
+ if _, err = migrate.Apply(t.Context(), d, BootSchema); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err = migrate.Apply(t.Context(), d, (Runtime{role: "directory"}).Schema()); err != nil {
+ t.Fatal(err)
+ }
+ if replication {
+ var profile []legacyDiagnosticObject
+ raw, err := compatibilityProfiles.ReadFile("compatibility_profiles/directory.json")
+ if err != nil || json.Unmarshal(raw, &profile) != nil {
+ t.Fatal("frozen replication profile")
+ }
+ count := 0
+ for _, obj := range profile {
+ if obj.Type == "table" && (obj.Name == "_litestream_lock" || obj.Name == "_litestream_seq") {
+ if _, err = d.Writer().Exec(obj.SQL); err != nil {
+ t.Fatal(err)
+ }
+ count++
+ }
+ }
+ if count != 2 {
+ t.Fatal("replication profile changed")
+ }
+ }
+ return d
+}
+
+func legacyObjects(t *testing.T, d *sql.DB) []legacyDiagnosticObject {
+ t.Helper()
+ rows, err := d.Query("SELECT type,name,tbl_name,coalesce(sql,'') FROM sqlite_schema ORDER BY type,name")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var objects []legacyDiagnosticObject
+ for rows.Next() {
+ var object legacyDiagnosticObject
+ if rows.Scan(&object.Type, &object.Name, &object.Table, &object.SQL) != nil {
+ t.Fatal("schema scan")
+ }
+ objects = append(objects, object)
+ }
+ if rows.Err() != nil {
+ t.Fatal(rows.Err())
+ }
+ return objects
+}
+
+func TestLegacyDiagnosticFrozenProfile(t *testing.T) {
+ d := legacyDiagnosticFixture(t, true, true)
+ objects := legacyObjects(t, d.Writer())
+ raw, err := json.MarshalIndent(objects, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw = append(raw, '\n')
+ if os.Getenv("OFICINA_GENERATE_LEGACY_DIAGNOSTIC_PROFILE") == "1" {
+ if err = os.WriteFile("diagnostic_profiles/legacy-directory-v1.json", raw, 0600); err != nil {
+ t.Fatal(err)
+ }
+ return
+ }
+ if !bytes.Equal(raw, legacyDiagnosticJSON) {
+ t.Fatal("frozen historical diagnostic schema changed")
+ }
+ if len(objects) == 0 || len(objects) > legacyDiagnosticMaxRows {
+ t.Fatal("invalid profile size")
+ }
+ for _, o := range objects {
+ if len(o.Type) > 16 || len(o.Name) > legacyDiagnosticNameBytes || len(o.Table) > legacyDiagnosticNameBytes || len(o.SQL) > legacyDiagnosticSQLBytes {
+ t.Fatal("profile exceeds bounded fields")
+ }
+ }
+ migrations, ok := legacyDiagnosticMigrations()
+ if !ok {
+ t.Fatal("migration union invalid")
+ }
+ replay, err := migrate.Replay(t.Context(), migrations)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer replay.Close()
+ for _, o := range objects {
+ if o.Type == "table" && (o.Name == "rastrillo_migrations" || o.Name == "_litestream_lock" || o.Name == "_litestream_seq") {
+ if _, err = replay.Exec(o.SQL); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ reraw, _ := json.MarshalIndent(legacyObjects(t, replay), "", " ")
+ if !bytes.Equal(raw, append(reraw, '\n')) {
+ t.Fatal("historical sequential apply differs from unique replay")
+ }
+}
+
+func TestLegacyDiagnosticExactProfileAndOccupancy(t *testing.T) {
+ d := legacyDiagnosticFixture(t, true, true)
+ before := legacyObjects(t, d.Writer())
+ var ledgerBefore, ledgerAfter string
+ if err := d.Writer().QueryRow("SELECT group_concat(id || checksum || applied_at) FROM (SELECT * FROM rastrillo_migrations ORDER BY id)").Scan(&ledgerBefore); err != nil {
+ t.Fatal(err)
+ }
+ result := inspectLegacySchema(t.Context(), d.Writer())
+ if result.status != "match" || result.occupied {
+ t.Fatal("empty historical schema not recognized", result)
+ }
+ inserts := map[string]string{
+ "people": "INSERT INTO people VALUES('person','index','time')",
+ "signin_links": "INSERT INTO signin_links VALUES('token',x'00','purpose','time')",
+ "passkey_credentials": "INSERT INTO passkey_credentials VALUES('id','person',x'00',0,'time')",
+ "passkey_challenges": "INSERT INTO passkey_challenges VALUES('challenge','person','purpose','time')",
+ "passkey_pending": "INSERT INTO passkey_pending VALUES('token','person','method','/','time')",
+ "passkey_recovery_codes": "INSERT INTO passkey_recovery_codes VALUES('code','person','time')",
+ }
+ for table, statement := range inserts {
+ t.Run(table, func(t *testing.T) {
+ if _, err := d.Writer().Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+ result := inspectLegacySchema(t.Context(), d.Writer())
+ if result.status != "match" || !result.occupied {
+ t.Fatal("historical credentials were missed", result)
+ }
+ var n int
+ if d.Writer().QueryRow("SELECT count(*) FROM "+table).Scan(&n) != nil || n != 1 {
+ t.Fatal("diagnostic changed rows")
+ }
+ if _, err := d.Writer().Exec("DELETE FROM " + table); err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+ after := legacyObjects(t, d.Writer())
+ if err := d.Writer().QueryRow("SELECT group_concat(id || checksum || applied_at) FROM (SELECT * FROM rastrillo_migrations ORDER BY id)").Scan(&ledgerAfter); err != nil || ledgerAfter != ledgerBefore {
+ t.Fatal("diagnostic changed migration ledger")
+ }
+ a, _ := json.Marshal(before)
+ b, _ := json.Marshal(after)
+ if !bytes.Equal(a, b) {
+ t.Fatal("diagnostic changed schema")
+ }
+ conn, err := d.Writer().Conn(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ if operator.VerifyLedger(t.Context(), conn, (Runtime{role: "directory"}).Schema()) != operator.ErrRefused {
+ t.Fatal("operator accepted historical extras")
+ }
+}
+
+func TestLegacyDiagnosticRefusesDrift(t *testing.T) {
+ changes := map[string]string{
+ "wrong_checksum": "UPDATE rastrillo_migrations SET checksum='" + strings.Repeat("0", 64) + "' WHERE id='home/0001_people'",
+ "missing_migration": "DELETE FROM rastrillo_migrations WHERE id='home/0001_people'",
+ "unknown_migration": "INSERT INTO rastrillo_migrations VALUES('foreign/0001','time','" + strings.Repeat("0", 64) + "')",
+ "wrong_type": "UPDATE rastrillo_migrations SET checksum=x'00' WHERE id='home/0001_people'",
+ "oversized_id": "INSERT INTO rastrillo_migrations VALUES('" + strings.Repeat("x", 257) + "','time','" + strings.Repeat("0", 64) + "')",
+ "unknown_table": "CREATE TABLE foreign_table(value INTEGER)",
+ "unknown_index": "CREATE INDEX foreign_index ON people(created_at)",
+ "unknown_trigger": "CREATE TRIGGER foreign_trigger AFTER INSERT ON people BEGIN SELECT 1; END",
+ "changed_table": "ALTER TABLE people ADD COLUMN foreign_value INTEGER",
+ "missing_replication": "DROP TABLE _litestream_lock",
+ "oversized_object_name": "CREATE TABLE \"" + strings.Repeat("x", 257) + "\"(value INTEGER)",
+ "oversized_sql": "CREATE TABLE foreign_big(value TEXT DEFAULT '" + strings.Repeat("x", legacyDiagnosticSQLBytes) + "')",
+ }
+ for name, statement := range changes {
+ t.Run(name, func(t *testing.T) {
+ d := legacyDiagnosticFixture(t, true, true)
+ if _, err := d.Writer().Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+ result := inspectLegacySchema(t.Context(), d.Writer())
+ if result.status != "mismatch" || result.occupied {
+ t.Fatal("drift accepted", result)
+ }
+ })
+ }
+ for _, test := range []struct{ historical, replication bool }{{false, true}, {true, false}} {
+ d := legacyDiagnosticFixture(t, test.historical, test.replication)
+ if result := inspectLegacySchema(t.Context(), d.Writer()); result.status != "mismatch" || result.occupied {
+ t.Fatal("partial profile accepted", result)
+ }
+ }
+}
+
+func TestLegacyDiagnosticLogAndCancellation(t *testing.T) {
+ d := legacyDiagnosticFixture(t, true, true)
+ if _, err := d.Writer().Exec("INSERT INTO people VALUES(?,?,'time')", sealtest.CanaryAddress, "secret-marker"); err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ logger := slog.New(slog.NewJSONHandler(&out, nil))
+ logLegacySchemaDiagnostic(t.Context(), d.Writer(), "credential", logger)
+ if out.Len() != 0 {
+ t.Fatal("credential role emitted diagnostic")
+ }
+ logLegacySchemaDiagnostic(t.Context(), d.Writer(), "directory", logger)
+ var event map[string]any
+ if json.Unmarshal(out.Bytes(), &event) != nil {
+ t.Fatal("invalid event")
+ }
+ if len(event) != 6 || event["msg"] != "legacy schema diagnostic" || event["profile"] != legacyDiagnosticProfile || event["result"] != "match" || event["legacy_credentials_present"] != true {
+ t.Fatal("wrong event keys or values")
+ }
+ if strings.Contains(out.String(), sealtest.CanaryAddress) || strings.Contains(out.String(), "secret-marker") {
+ t.Fatal("diagnostic leaked row data")
+ }
+ if _, err := d.Writer().Exec("CREATE TABLE \"" + sealtest.CanaryAddress + "\"(value TEXT)"); err != nil {
+ t.Fatal(err)
+ }
+ out.Reset()
+ logLegacySchemaDiagnostic(t.Context(), d.Writer(), "directory", logger)
+ event = map[string]any{}
+ if json.Unmarshal(out.Bytes(), &event) != nil || len(event) != 5 || event["result"] != "mismatch" {
+ t.Fatal("mismatch event included occupancy")
+ }
+ if strings.Contains(out.String(), sealtest.CanaryAddress) {
+ t.Fatal("diagnostic leaked schema name")
+ }
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ out.Reset()
+ logLegacySchemaDiagnostic(ctx, d.Writer(), "directory", logger)
+ event = map[string]any{}
+ if json.Unmarshal(out.Bytes(), &event) != nil || len(event) != 5 || event["result"] != "unavailable" {
+ t.Fatal("cancellation event incorrect")
+ }
+ if _, err := d.Writer().Exec("INSERT INTO people VALUES('after','after','time')"); err != nil {
+ t.Fatal("diagnostic stranded writer", err)
+ }
+}
+
+func TestLegacyDiagnosticCannotExpandAcceptedProfiles(t *testing.T) {
+ paths, err := fs.Glob(compatibilityProfiles, "compatibility_profiles/*.json")
+ if err != nil || strings.Join(paths, ",") != "compatibility_profiles/credential.json,compatibility_profiles/directory.json" {
+ t.Fatal("diagnostic expanded accepted profile embed")
+ }
+ raw, err := os.ReadFile("legacy_schema_diagnostic.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(raw, []byte(`"amadan.net/oficina/home/internal/operator"`)) || bytes.Contains(raw, []byte("compatibilityProfiles")) {
+ t.Fatal("diagnostic depends on authority profiles")
+ }
+ migrations, ok := legacyDiagnosticMigrations()
+ if !ok {
+ t.Fatal("migration union")
+ }
+ if _, ok = uniqueLegacyMigrations(migrations, []migrate.Migration{{ID: migrations[0].ID, SQL: "SELECT 1"}}); ok {
+ t.Fatal("conflicting duplicate migration accepted")
+ }
+}
+
+func TestLegacyDiagnosticOriginalMigrationProvenance(t *testing.T) {
+ raw, err := os.ReadFile("diagnostic_profiles/provenance.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var provenance map[string]struct{ SHA256, Checksum string }
+ if json.Unmarshal(raw, &provenance) != nil || len(provenance) != 3 {
+ t.Fatal("invalid original provenance")
+ }
+ found := 0
+ for _, m := range BootSchema.All() {
+ if p, ok := provenance[m.ID]; ok {
+ sum := sha256.Sum256([]byte(m.SQL))
+ if hex.EncodeToString(sum[:]) != p.SHA256 || migrate.Checksum(m.SQL) != p.Checksum {
+ t.Fatal("original migration changed", m.ID)
+ }
+ found++
+ }
+ }
+ if found != 3 {
+ t.Fatal("original migration missing")
+ }
+}
+
+type legacyRollbackProbe struct {
+ t *testing.T
+ fail, evicted bool
+}
+
+func (p *legacyRollbackProbe) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
+ if ctx.Err() != nil || query != "ROLLBACK" || len(args) != 0 {
+ p.t.Fatal("cleanup reused cancellation or changed SQL")
+ }
+ if p.fail {
+ return nil, errors.New("fixture rollback failure")
+ }
+ return nil, nil
+}
+func (p *legacyRollbackProbe) Raw(f func(any) error) error {
+ if f(nil) != driver.ErrBadConn {
+ p.t.Fatal("failed cleanup did not evict driver connection")
+ }
+ p.evicted = true
+ return nil
+}
+func TestLegacyDiagnosticRollbackAndEviction(t *testing.T) {
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ for _, fail := range []bool{false, true} {
+ probe := &legacyRollbackProbe{t: t, fail: fail}
+ if rollbackLegacyDiagnostic(ctx, probe) == fail || probe.evicted != fail {
+ t.Fatal("cleanup result or eviction wrong")
+ }
+ }
+ d := legacyDiagnosticFixture(t, true, true)
+ conn, err := d.Writer().Conn(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = conn.ExecContext(t.Context(), "BEGIN"); err != nil {
+ t.Fatal(err)
+ }
+ if !rollbackLegacyDiagnostic(ctx, conn) {
+ t.Fatal("canceled context prevented real rollback")
+ }
+ conn.Close()
+ // A query error after BEGIN must also leave the sole writer usable.
+ if _, err = d.Writer().Exec("DROP TABLE rastrillo_migrations"); err != nil {
+ t.Fatal(err)
+ }
+ if result := inspectLegacySchema(t.Context(), d.Writer()); result.status != "unavailable" {
+ t.Fatal("malformed database accepted")
+ }
+ if _, err = d.Writer().Exec("BEGIN IMMEDIATE; INSERT INTO people VALUES('after','after','time'); COMMIT"); err != nil {
+ t.Fatal("failed diagnostic stranded writer", err)
+ }
+}
diff --git a/internal/home/schema_inventory.go b/internal/home/schema_inventory.go
index c1a5c65..941513e 100644
--- a/internal/home/schema_inventory.go
+++ b/internal/home/schema_inventory.go
@@ -18,6 +18,7 @@ func LogSchemaInventory(parent context.Context, d *db.DB, cfg Runtime, logger *s
}
ctx, cancel := context.WithTimeout(parent, 2*time.Second)
defer cancel()
+ defer logLegacySchemaDiagnostic(ctx, d.Writer(), cfg.role, logger)
expected := map[string]bool{}
known := map[string]bool{}
for _, m := range cfg.Schema().All() {