From 150bfd46056a8bde5564e58de4457c7a508286d7 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 13 Oct 2026 03:15:06 +1100 Subject: [PATCH] fix(postgres): quote the alert lock key so a NUL cannot reach Postgres text --- internal/infrastructure/postgres/alerts.go | 5 +++- .../postgres/alerts_lock_test.go | 30 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 internal/infrastructure/postgres/alerts_lock_test.go diff --git a/internal/infrastructure/postgres/alerts.go b/internal/infrastructure/postgres/alerts.go index 6ba5e3640..56c90ce6a 100644 --- a/internal/infrastructure/postgres/alerts.go +++ b/internal/infrastructure/postgres/alerts.go @@ -50,7 +50,10 @@ func alertParams(a alert.Alert) postgresdb.UpsertAlertParams { } } -func alertLockKey(k alert.Key) string { return string(k.Org) + "\x00" + k.Kind + "\x00" + k.Subject } +// Quoted so a NUL in a field is escaped: Postgres text rejects a raw NUL. +func alertLockKey(k alert.Key) string { + return fmt.Sprintf("%q|%q|%q", string(k.Org), k.Kind, k.Subject) +} // lockedAlert takes the key's lock and returns the stored alert, nil when // there is none. diff --git a/internal/infrastructure/postgres/alerts_lock_test.go b/internal/infrastructure/postgres/alerts_lock_test.go new file mode 100644 index 000000000..21bb95201 --- /dev/null +++ b/internal/infrastructure/postgres/alerts_lock_test.go @@ -0,0 +1,30 @@ +package postgres + +import ( + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/alert" +) + +// The lock key is sent to Postgres as text, which rejects a NUL byte. +func TestAlertLockKeyHasNoNUL(t *testing.T) { + keys := []alert.Key{ + {Org: "org", Kind: "provider.no_credential", Subject: "openai"}, + {Org: "", Kind: "", Subject: ""}, + {Org: "a", Kind: "b", Subject: "c\x00d"}, + } + for _, k := range keys { + if got := alertLockKey(k); strings.Contains(got, "\x00") { + t.Errorf("alertLockKey(%+v) = %q contains a NUL byte", k, got) + } + } +} + +func TestAlertLockKeyDistinguishesFields(t *testing.T) { + a := alertLockKey(alert.Key{Org: "ab", Kind: "c", Subject: "d"}) + b := alertLockKey(alert.Key{Org: "a", Kind: "bc", Subject: "d"}) + if a == b { + t.Errorf("keys with shifted field boundaries collide: %q", a) + } +}