feat(eda): sources own signing, with UUIDv7 paths and approved unsigned option

A source is the capture endpoint: a UUIDv7 path by default or a unique
URL-safe custom path, signed by default with an Archie-generated secret
(encrypted via the bindings cipher), or unsigned after an approval.
Intake verifies X-Hub-Signature-256/X-Signature-256 against the source
secret before redaction; an unauthenticated event on a signed source is
captured but never dispatched, an event on an approved unsigned source
dispatches and is marked unsigned. The binding secret is retired; migration
0006 derives sources from existing binding and capture source strings,
moving each binding's secret onto its source. SourceStore crosses the
State Store gRPC contract. The dashboard gains a sources panel and flags
unsigned in the capture inspector, binding list and task timeline.
This commit is contained in:
sam committed 2026-09-24 14:26:21 +10:00
1 parent 5009288729
commit 6adbdc55a9
59 files changed
+3741 -1660

No files matched your search

+11 -58
View File
@@ -44,7 +44,7 @@ type EDA struct {
notify func(events.Event)
}
// NewEDA builds an EDA store over pool. A nil cipher keeps binding secrets in
// NewEDA builds an EDA store over pool. A nil cipher keeps source secrets in
// plaintext (the behaviour that predates the option); the caller resolves the
// keyring through edastore.NewBindingCipher, exactly as the PocketBase store
// does. The pool is owned by the caller, not this store.
@@ -93,6 +93,7 @@ func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent,
Headers: c.Headers,
Body: c.Body,
Authenticated: c.Authenticated,
Unsigned: c.Unsigned,
ReceivedAt: received.UTC(),
}); err != nil {
return "", fmt.Errorf("edastore: insert capture: %w", err)
@@ -127,6 +128,7 @@ func captureValue(r postgresdb.Capture) storecontract.CapturedEvent {
Headers: r.Headers,
Body: r.Body,
Authenticated: r.Authenticated,
Unsigned: r.Unsigned,
}
}
@@ -276,19 +278,10 @@ func (s *EDA) DeleteMapping(ctx context.Context, id string) error {
// --- bindings ---
func (s *EDA) encryptSecret(secret string) (string, error) {
if s.cipher == nil {
return secret, nil
}
encrypted, err := s.cipher.Encrypt(secret)
if err != nil {
return "", fmt.Errorf("edastore: encrypt binding secret: %w", err)
}
return encrypted, nil
}
func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
b := binding.Binding{
// bindingValue takes GetBindingRow; the list queries' rows share its fields
// and convert to it.
func bindingValue(r postgresdb.GetBindingRow) binding.Binding {
return binding.Binding{
ID: r.ID,
Name: r.Name,
Matcher: binding.Matcher{Source: r.Source},
@@ -298,18 +291,9 @@ func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
Repo: r.Repo,
Version: int(r.Version),
Status: binding.Status(r.Status),
Secret: r.Secret,
CreatedAt: r.CreatedAt,
UpdatedAt: r.UpdatedAt,
}
if s.cipher != nil && b.Secret != "" {
plain, err := s.cipher.Decrypt(b.Secret)
if err != nil {
return binding.Binding{}, fmt.Errorf("edastore: decrypt binding secret: %w", err)
}
b.Secret = plain
}
return b, nil
}
// InsertBinding stores a new binding as pending_approval. "One binding per
@@ -317,14 +301,6 @@ func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
// second insert for the same source is refused by the database and surfaced
// here as ErrBindingOverlap.
func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, error) {
secret := b.Secret
if secret != "" {
var err error
secret, err = s.encryptSecret(secret)
if err != nil {
return "", err
}
}
id := newRecordID()
err := s.q.InsertBinding(ctx, postgresdb.InsertBindingParams{
ID: id,
@@ -335,7 +311,6 @@ func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, err
Owner: b.Owner,
Repo: b.Repo,
Status: string(binding.StatusPendingApproval),
Secret: secret,
})
if isUniqueViolation(err) {
return "", storecontract.ErrBindingOverlap
@@ -357,10 +332,7 @@ func (s *EDA) GetBinding(ctx context.Context, id string) (*binding.Binding, erro
if err != nil {
return nil, err
}
b, err := s.bindingValue(r)
if err != nil {
return nil, err
}
b := bindingValue(r)
return &b, nil
}
@@ -371,11 +343,7 @@ func (s *EDA) ListBindings(ctx context.Context) ([]binding.Binding, error) {
}
out := make([]binding.Binding, 0, len(rows))
for _, r := range rows {
b, err := s.bindingValue(r)
if err != nil {
return nil, err
}
out = append(out, b)
out = append(out, bindingValue(postgresdb.GetBindingRow(r)))
}
return out, nil
}
@@ -388,28 +356,14 @@ func (s *EDA) ArmedBindingsForSource(ctx context.Context, source string) ([]bind
}
out := make([]binding.Binding, 0, len(rows))
for _, r := range rows {
b, err := s.bindingValue(r)
if err != nil {
return nil, err
}
out = append(out, b)
out = append(out, bindingValue(postgresdb.GetBindingRow(r)))
}
return out, nil
}
// UpdateBinding rewrites a binding's editable fields, bumps its version and
// drops it back to pending_approval. An empty secret means "keep the stored
// one" (the CASE in the query), so an edit form that does not echo the secret
// cannot blank an armed binding's HMAC key.
// drops it back to pending_approval.
func (s *EDA) UpdateBinding(ctx context.Context, b binding.Binding) error {
secret := b.Secret
if secret != "" {
var err error
secret, err = s.encryptSecret(secret)
if err != nil {
return err
}
}
n, err := s.q.UpdateBinding(ctx, postgresdb.UpdateBindingParams{
ID: b.ID,
Name: b.Name,
@@ -419,7 +373,6 @@ func (s *EDA) UpdateBinding(ctx context.Context, b binding.Binding) error {
Owner: b.Owner,
Repo: b.Repo,
Status: string(binding.StatusPendingApproval),
Secret: secret,
})
if isUniqueViolation(err) {
return storecontract.ErrBindingOverlap
@@ -127,79 +127,6 @@ func TestConcurrentInsertBindingSameSource(t *testing.T) {
}
}
// Hazard 1: UpdateBinding with an empty secret must leave the stored envelope
// untouched, so an edit form that does not echo the secret cannot blank an
// armed binding's HMAC key.
func TestUpdateBindingEmptySecretPreservesStored(t *testing.T) {
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
if err != nil {
t.Fatalf("NewBindingCipher() error = %v", err)
}
pool, s := edaWithCipher(t, cipher)
secretID, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "src-secret"}, Workflow: "implement",
Secret: "supersecretvalue0123",
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
before := readRawSecret(t, pool, secretID)
// Edit with an empty secret: the stored envelope must not change.
if err := s.UpdateBinding(t.Context(), binding.Binding{
ID: secretID, Name: "renamed", Matcher: binding.Matcher{Source: "src-secret"}, Workflow: "escalate",
}); err != nil {
t.Fatalf("UpdateBinding() error = %v", err)
}
after := readRawSecret(t, pool, secretID)
if after != before {
t.Fatalf("stored secret changed on empty-secret edit: %q -> %q", before, after)
}
if after == "" {
t.Fatal("stored secret is empty after an empty-secret edit; the binding was silently disarmed")
}
}
func readRawSecret(t *testing.T, pool *pgxpool.Pool, id string) string {
t.Helper()
var stored string
if err := pool.QueryRow(t.Context(), "SELECT secret FROM bindings WHERE id = $1", id).Scan(&stored); err != nil {
t.Fatalf("read raw secret: %v", err)
}
return stored
}
// The cipher path must keep decrypt-in-store: what is stored is an envelope,
// what reads back is the plaintext HMAC key the intake verifies with.
func TestBindingSecretEncryptedAtRestAndDecryptedOnRead(t *testing.T) {
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
if err != nil {
t.Fatalf("NewBindingCipher() error = %v", err)
}
pool, s := edaWithCipher(t, cipher)
id, err := s.InsertBinding(t.Context(), binding.Binding{
Name: "n", Matcher: binding.Matcher{Source: "src-cipher"}, Workflow: "implement",
Secret: "supersecretvalue0123",
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
}
stored := readRawSecret(t, pool, id)
if stored == "supersecretvalue0123" {
t.Fatal("secret is stored plaintext; it must be encrypted at rest")
}
got, err := s.GetBinding(t.Context(), id)
if err != nil {
t.Fatalf("GetBinding() error = %v", err)
}
if got.Secret != "supersecretvalue0123" {
t.Errorf("Secret = %q, want the plaintext on read: the wire carries plaintext, so decrypt must happen in the store", got.Secret)
}
}
// The lifecycle gate survives the port: pending_approval -> armed, and only
// from pending_approval.
func TestBindingLifecycle(t *testing.T) {
@@ -0,0 +1,50 @@
-- Capture sources own signing (docs/prds/event-automation.md "Sources").
--
-- * path is the key. It is the URL segment a sender posts to and the string
-- captures.source and bindings.source already carry, so existing rows keep
-- resolving without a rewrite. It never changes after creation.
-- * signing is signed by default. Turning it off is a request
-- (unsigned_pending_approval) that only an approval makes effective.
-- * secret holds the cipher envelope when a bindings encryption key is
-- configured, plaintext otherwise, exactly as bindings.secret did.
-- * captures.unsigned marks an event taken on an approved unsigned source.
-- * bindings.secret is no longer read. It stays so the one-time legacy
-- import can load it and derive_sources can move it onto the source.
--
-- derive_sources creates a source for every source string bindings and
-- captures already use. A bound source takes its binding's secret (one binding
-- per source is schema-enforced), so a signed sender keeps authenticating. A
-- capture-only source gets no secret and dispatches nothing until the
-- operator generates one. The legacy import calls it again after loading.
-- +goose Up
CREATE TABLE sources (
path text PRIMARY KEY,
signing text NOT NULL DEFAULT 'signed'
CHECK (signing IN ('signed', 'unsigned_pending_approval', 'unsigned')),
secret text NOT NULL DEFAULT '',
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE captures ADD COLUMN unsigned boolean NOT NULL DEFAULT false;
-- +goose StatementBegin
CREATE FUNCTION derive_sources() RETURNS void LANGUAGE sql AS $$
INSERT INTO sources (path, secret)
SELECT source, secret FROM bindings WHERE source <> ''
ON CONFLICT (path) DO NOTHING;
INSERT INTO sources (path)
SELECT DISTINCT source FROM captures WHERE source <> ''
ON CONFLICT (path) DO NOTHING;
$$;
-- +goose StatementEnd
SELECT derive_sources();
-- +goose Down
DROP FUNCTION derive_sources();
ALTER TABLE captures DROP COLUMN unsigned;
DROP TABLE sources;
@@ -11,19 +11,33 @@ import (
)
const armedBindingsForSource = `-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC
`
func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]Binding, error) {
type ArmedBindingsForSourceRow struct {
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]ArmedBindingsForSourceRow, error) {
rows, err := q.db.Query(ctx, armedBindingsForSource, source)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Binding
var items []ArmedBindingsForSourceRow
for rows.Next() {
var i Binding
var i ArmedBindingsForSourceRow
if err := rows.Scan(
&i.ID,
&i.Name,
@@ -34,7 +48,6 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]
&i.Repo,
&i.Version,
&i.Status,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
@@ -101,14 +114,37 @@ func (q *Queries) DeletePlaybookDispatches(ctx context.Context, playbookID strin
return err
}
const deriveSources = `-- name: DeriveSources :exec
SELECT derive_sources()
`
func (q *Queries) DeriveSources(ctx context.Context) error {
_, err := q.db.Exec(ctx, deriveSources)
return err
}
const getBinding = `-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
FROM bindings WHERE id = $1
`
func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
type GetBindingRow struct {
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) GetBinding(ctx context.Context, id string) (GetBindingRow, error) {
row := q.db.QueryRow(ctx, getBinding, id)
var i Binding
var i GetBindingRow
err := row.Scan(
&i.ID,
&i.Name,
@@ -119,7 +155,6 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
&i.Repo,
&i.Version,
&i.Status,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
)
@@ -145,9 +180,26 @@ func (q *Queries) GetMapping(ctx context.Context, id string) (Mapping, error) {
return i, err
}
const getSource = `-- name: GetSource :one
SELECT path, signing, secret, created_at, updated_at FROM sources WHERE path = $1
`
func (q *Queries) GetSource(ctx context.Context, path string) (Source, error) {
row := q.db.QueryRow(ctx, getSource, path)
var i Source
err := row.Scan(
&i.Path,
&i.Signing,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertBinding = `-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status, secret)
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8, $9)
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8)
`
type InsertBindingParams struct {
@@ -159,7 +211,6 @@ type InsertBindingParams struct {
Owner string
Repo string
Status string
Secret string
}
func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) error {
@@ -172,7 +223,6 @@ func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) er
arg.Owner,
arg.Repo,
arg.Status,
arg.Secret,
)
return err
}
@@ -201,8 +251,8 @@ func (q *Queries) InsertBindingDispatch(ctx context.Context, arg InsertBindingDi
const insertCapture = `-- name: InsertCapture :exec
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
`
type InsertCaptureParams struct {
@@ -214,6 +264,7 @@ type InsertCaptureParams struct {
Body string
Authenticated bool
ReceivedAt time.Time
Unsigned bool
}
// EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls.
@@ -227,6 +278,7 @@ func (q *Queries) InsertCapture(ctx context.Context, arg InsertCaptureParams) er
arg.Body,
arg.Authenticated,
arg.ReceivedAt,
arg.Unsigned,
)
return err
}
@@ -275,6 +327,21 @@ func (q *Queries) InsertPlaybookDispatch(ctx context.Context, arg InsertPlaybook
return err
}
const insertSource = `-- name: InsertSource :exec
INSERT INTO sources (path, signing, secret) VALUES ($1, $2, $3)
`
type InsertSourceParams struct {
Path string
Signing string
Secret string
}
func (q *Queries) InsertSource(ctx context.Context, arg InsertSourceParams) error {
_, err := q.db.Exec(ctx, insertSource, arg.Path, arg.Signing, arg.Secret)
return err
}
const insertToolCall = `-- name: InsertToolCall :exec
INSERT INTO tool_calls (id, task_id, attempt, tool, result, error, called_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
@@ -304,19 +371,33 @@ func (q *Queries) InsertToolCall(ctx context.Context, arg InsertToolCallParams)
}
const listBindings = `-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
FROM bindings ORDER BY created_at DESC
`
func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
type ListBindingsRow struct {
ID string
Name string
Source string
Mapping string
Workflow string
Owner string
Repo string
Version int64
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) {
rows, err := q.db.Query(ctx, listBindings)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Binding
var items []ListBindingsRow
for rows.Next() {
var i Binding
var i ListBindingsRow
if err := rows.Scan(
&i.ID,
&i.Name,
@@ -327,7 +408,6 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
&i.Repo,
&i.Version,
&i.Status,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
@@ -342,7 +422,7 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
}
const listCaptures = `-- name: ListCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned
FROM captures
ORDER BY received_at DESC
LIMIT $1
@@ -366,6 +446,7 @@ func (q *Queries) ListCaptures(ctx context.Context, limit int32) ([]Capture, err
&i.Body,
&i.Authenticated,
&i.ReceivedAt,
&i.Unsigned,
); err != nil {
return nil, err
}
@@ -409,8 +490,38 @@ func (q *Queries) ListMappings(ctx context.Context) ([]Mapping, error) {
return items, nil
}
const listSources = `-- name: ListSources :many
SELECT path, signing, secret, created_at, updated_at FROM sources ORDER BY created_at DESC, path
`
func (q *Queries) ListSources(ctx context.Context) ([]Source, error) {
rows, err := q.db.Query(ctx, listSources)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Source
for rows.Next() {
var i Source
if err := rows.Scan(
&i.Path,
&i.Signing,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listUndispatchedCaptures = `-- name: ListUndispatchedCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned
FROM captures
WHERE source = ANY($1::text[])
AND id NOT IN (SELECT capture FROM binding_dispatches)
@@ -441,6 +552,7 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat
&i.Body,
&i.Authenticated,
&i.ReceivedAt,
&i.Unsigned,
); err != nil {
return nil, err
}
@@ -464,6 +576,53 @@ func (q *Queries) SetBindingArmed(ctx context.Context, id string) (int64, error)
return result.RowsAffected(), nil
}
const setSourceSecret = `-- name: SetSourceSecret :execrows
UPDATE sources SET secret = $2, updated_at = now() WHERE path = $1
`
type SetSourceSecretParams struct {
Path string
Secret string
}
func (q *Queries) SetSourceSecret(ctx context.Context, arg SetSourceSecretParams) (int64, error) {
result, err := q.db.Exec(ctx, setSourceSecret, arg.Path, arg.Secret)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const setSourceSigning = `-- name: SetSourceSigning :execrows
UPDATE sources SET signing = $1, updated_at = now()
WHERE path = $2 AND signing = $3
`
type SetSourceSigningParams struct {
ToSigning string
Path string
FromSigning string
}
func (q *Queries) SetSourceSigning(ctx context.Context, arg SetSourceSigningParams) (int64, error) {
result, err := q.db.Exec(ctx, setSourceSigning, arg.ToSigning, arg.Path, arg.FromSigning)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const sourceExists = `-- name: SourceExists :one
SELECT EXISTS (SELECT 1 FROM sources WHERE path = $1)
`
func (q *Queries) SourceExists(ctx context.Context, path string) (bool, error) {
row := q.db.QueryRow(ctx, sourceExists, path)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const taskToolCalls = `-- name: TaskToolCalls :many
SELECT id, task_id, attempt, tool, result, error, called_at
FROM tool_calls WHERE task_id = $1 ORDER BY called_at ASC
@@ -510,9 +669,7 @@ func (q *Queries) TaskToolCalls(ctx context.Context, taskID int64) ([]TaskToolCa
const updateBinding = `-- name: UpdateBinding :execrows
UPDATE bindings
SET name = $2, source = $3, mapping = $4, workflow = $5, owner = $6, repo = $7,
version = version + 1, status = $8,
secret = CASE WHEN $9::text = '' THEN secret ELSE $9 END,
updated_at = now()
version = version + 1, status = $8, updated_at = now()
WHERE id = $1
`
@@ -525,12 +682,8 @@ type UpdateBindingParams struct {
Owner string
Repo string
Status string
Secret string
}
// An empty secret means "keep the stored one": the CASE leaves the column
// untouched so an edit form that does not echo the secret cannot blank an
// armed binding's HMAC key.
func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (int64, error) {
result, err := q.db.Exec(ctx, updateBinding,
arg.ID,
@@ -541,7 +694,6 @@ func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (i
arg.Owner,
arg.Repo,
arg.Status,
arg.Secret,
)
if err != nil {
return 0, err
@@ -48,6 +48,7 @@ type Capture struct {
Body string
Authenticated bool
ReceivedAt time.Time
Unsigned bool
}
type ChannelStatus struct {
@@ -189,6 +190,14 @@ type Session struct {
LastActiveAt int64
}
type Source struct {
Path string
Signing string
Secret string
CreatedAt time.Time
UpdatedAt time.Time
}
type Task struct {
ID int64
Owner string
@@ -1,17 +1,17 @@
-- EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls.
-- name: InsertCapture :exec
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8);
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
-- name: ListCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned
FROM captures
ORDER BY received_at DESC
LIMIT $1;
-- name: ListUndispatchedCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned
FROM captures
WHERE source = ANY(@sources::text[])
AND id NOT IN (SELECT capture FROM binding_dispatches)
@@ -47,30 +47,25 @@ WHERE id = $1;
DELETE FROM mappings WHERE id = $1;
-- name: InsertBinding :exec
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status, secret)
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8, $9);
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8);
-- name: GetBinding :one
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
FROM bindings WHERE id = $1;
-- name: ListBindings :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
FROM bindings ORDER BY created_at DESC;
-- name: ArmedBindingsForSource :many
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC;
-- name: UpdateBinding :execrows
-- An empty secret means "keep the stored one": the CASE leaves the column
-- untouched so an edit form that does not echo the secret cannot blank an
-- armed binding's HMAC key.
UPDATE bindings
SET name = $2, source = $3, mapping = $4, workflow = $5, owner = $6, repo = $7,
version = version + 1, status = $8,
secret = CASE WHEN sqlc.arg(secret)::text = '' THEN secret ELSE sqlc.arg(secret) END,
updated_at = now()
version = version + 1, status = $8, updated_at = now()
WHERE id = $1;
-- name: SetBindingArmed :execrows
@@ -97,3 +92,25 @@ VALUES ($1, $2, $3, $4, $5, $6, $7);
-- name: TaskToolCalls :many
SELECT id, task_id, attempt, tool, result, error, called_at
FROM tool_calls WHERE task_id = $1 ORDER BY called_at ASC;
-- name: InsertSource :exec
INSERT INTO sources (path, signing, secret) VALUES ($1, $2, $3);
-- name: GetSource :one
SELECT path, signing, secret, created_at, updated_at FROM sources WHERE path = $1;
-- name: ListSources :many
SELECT path, signing, secret, created_at, updated_at FROM sources ORDER BY created_at DESC, path;
-- name: SetSourceSigning :execrows
UPDATE sources SET signing = sqlc.arg(to_signing), updated_at = now()
WHERE path = sqlc.arg(path) AND signing = sqlc.arg(from_signing);
-- name: SetSourceSecret :execrows
UPDATE sources SET secret = $2, updated_at = now() WHERE path = $1;
-- name: SourceExists :one
SELECT EXISTS (SELECT 1 FROM sources WHERE path = $1);
-- name: DeriveSources :exec
SELECT derive_sources();
+130
View File
@@ -0,0 +1,130 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var _ storecontract.SourceStore = (*EDA)(nil)
// InsertSource stores a new source. The path is the primary key, so a taken
// path is refused by the database and surfaced as ErrSourcePathTaken.
func (s *EDA) InsertSource(ctx context.Context, src source.Source) error {
secret, err := s.sealSecret(src.Secret)
if err != nil {
return err
}
err = s.q.InsertSource(ctx, postgresdb.InsertSourceParams{
Path: src.Path, Signing: string(src.Signing), Secret: secret,
})
if isUniqueViolation(err) {
return storecontract.ErrSourcePathTaken
}
if err != nil {
return fmt.Errorf("edastore: insert source: %w", err)
}
return nil
}
// GetSource returns (nil, nil) for an unknown path.
func (s *EDA) GetSource(ctx context.Context, path string) (*source.Source, error) {
r, err := s.q.GetSource(ctx, path)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("edastore: get source: %w", err)
}
src, err := s.sourceValue(r)
if err != nil {
return nil, err
}
return &src, nil
}
func (s *EDA) ListSources(ctx context.Context) ([]source.Source, error) {
rows, err := s.q.ListSources(ctx)
if err != nil {
return nil, fmt.Errorf("edastore: list sources: %w", err)
}
out := make([]source.Source, 0, len(rows))
for _, r := range rows {
src, err := s.sourceValue(r)
if err != nil {
return nil, err
}
out = append(out, src)
}
return out, nil
}
// SetSourceSigning moves a source from one signing state to another, and
// refuses when the stored state is no longer from.
func (s *EDA) SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error {
n, err := s.q.SetSourceSigning(ctx, postgresdb.SetSourceSigningParams{
Path: path, FromSigning: string(from), ToSigning: string(to),
})
if err != nil {
return fmt.Errorf("edastore: set source signing: %w", err)
}
if n == 1 {
return nil
}
exists, err := s.q.SourceExists(ctx, path)
if err != nil {
return fmt.Errorf("edastore: set source signing: %w", err)
}
if !exists {
return storecontract.ErrSourceNotFound
}
return storecontract.ErrSourceSigningStale
}
func (s *EDA) SetSourceSecret(ctx context.Context, path, secret string) error {
sealed, err := s.sealSecret(secret)
if err != nil {
return err
}
n, err := s.q.SetSourceSecret(ctx, postgresdb.SetSourceSecretParams{Path: path, Secret: sealed})
if err != nil {
return fmt.Errorf("edastore: set source secret: %w", err)
}
if n == 0 {
return storecontract.ErrSourceNotFound
}
return nil
}
// sealSecret encrypts a non-empty secret when a cipher is configured.
func (s *EDA) sealSecret(secret string) (string, error) {
if s.cipher == nil || secret == "" {
return secret, nil
}
sealed, err := s.cipher.Encrypt(secret)
if err != nil {
return "", fmt.Errorf("edastore: encrypt source secret: %w", err)
}
return sealed, nil
}
func (s *EDA) sourceValue(r postgresdb.Source) (source.Source, error) {
secret := r.Secret
if s.cipher != nil && secret != "" {
plain, err := s.cipher.Decrypt(secret)
if err != nil {
return source.Source{}, fmt.Errorf("edastore: decrypt source secret: %w", err)
}
secret = plain
}
return source.Source{
Path: r.Path, Signing: source.Signing(r.Signing), Secret: secret,
CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
}, nil
}
@@ -0,0 +1,156 @@
package postgres
import (
"errors"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
)
func readRawSourceSecret(t *testing.T, pool *pgxpool.Pool, path string) string {
t.Helper()
var stored string
if err := pool.QueryRow(t.Context(), "SELECT secret FROM sources WHERE path = $1", path).Scan(&stored); err != nil {
t.Fatalf("read raw secret: %v", err)
}
return stored
}
// A new source keeps its generated path, is signed, stores its secret as a
// cipher envelope and reads it back as plaintext.
func TestSourceRoundTripEncryptsSecret(t *testing.T) {
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
if err != nil {
t.Fatalf("NewBindingCipher() error = %v", err)
}
pool, s := edaWithCipher(t, cipher)
in, err := source.New("")
if err != nil {
t.Fatalf("source.New() error = %v", err)
}
if err := s.InsertSource(t.Context(), in); err != nil {
t.Fatalf("InsertSource() error = %v", err)
}
if raw := readRawSourceSecret(t, pool, in.Path); raw == in.Secret || raw == "" {
t.Fatalf("stored secret = %q, want a cipher envelope", raw)
}
got, err := s.GetSource(t.Context(), in.Path)
if err != nil || got == nil {
t.Fatalf("GetSource() = %v, %v", got, err)
}
if got.Path != in.Path || got.Signing != source.SigningSigned || got.Secret != in.Secret {
t.Fatalf("GetSource() = %+v, want path %q signed with the plaintext secret", got, in.Path)
}
list, err := s.ListSources(t.Context())
if err != nil || len(list) != 1 || list[0].Secret != in.Secret {
t.Fatalf("ListSources() = %+v, %v", list, err)
}
}
func TestSourceWritesRefuseBadState(t *testing.T) {
s := edaFor(t)
taken := source.Source{Path: "sentry", Signing: source.SigningSigned, Secret: "k"}
if err := s.InsertSource(t.Context(), taken); err != nil {
t.Fatalf("InsertSource() error = %v", err)
}
tests := []struct {
name string
write func() error
want error
}{
{"taken custom path", func() error { return s.InsertSource(t.Context(), taken) }, storecontract.ErrSourcePathTaken},
{"stale signing", func() error {
return s.SetSourceSigning(t.Context(), "sentry", source.SigningUnsignedPending, source.SigningUnsigned)
}, storecontract.ErrSourceSigningStale},
{"signing on unknown path", func() error {
return s.SetSourceSigning(t.Context(), "nope", source.SigningSigned, source.SigningUnsignedPending)
}, storecontract.ErrSourceNotFound},
{"secret on unknown path", func() error { return s.SetSourceSecret(t.Context(), "nope", "k") }, storecontract.ErrSourceNotFound},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := tt.write(); !errors.Is(err, tt.want) {
t.Fatalf("error = %v, want %v", err, tt.want)
}
})
}
got, err := s.GetSource(t.Context(), "nope")
if err != nil || got != nil {
t.Fatalf("GetSource(unknown) = %v, %v; want nil, nil", got, err)
}
}
func TestSourceSigningAndSecretWrites(t *testing.T) {
s := edaFor(t)
if err := s.InsertSource(t.Context(), source.Source{Path: "fw", Signing: source.SigningSigned}); err != nil {
t.Fatalf("InsertSource() error = %v", err)
}
if err := s.SetSourceSigning(t.Context(), "fw", source.SigningSigned, source.SigningUnsignedPending); err != nil {
t.Fatalf("SetSourceSigning() error = %v", err)
}
if err := s.SetSourceSecret(t.Context(), "fw", "newsecret"); err != nil {
t.Fatalf("SetSourceSecret() error = %v", err)
}
got, err := s.GetSource(t.Context(), "fw")
if err != nil || got.Signing != source.SigningUnsignedPending || got.Secret != "newsecret" {
t.Fatalf("GetSource() = %+v, %v", got, err)
}
}
func TestCaptureUnsignedRoundTrip(t *testing.T) {
s := edaFor(t)
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "fw", Unsigned: true}, 0, 0); err != nil {
t.Fatalf("InsertCapture() error = %v", err)
}
for name, list := range map[string]func() ([]storecontract.CapturedEvent, error){
"ListCaptures": func() ([]storecontract.CapturedEvent, error) { return s.ListCaptures(t.Context(), 10) },
"ListUndispatchedCaptures": func() ([]storecontract.CapturedEvent, error) {
return s.ListUndispatchedCaptures(t.Context(), []string{"fw"}, 10)
},
} {
got, err := list()
if err != nil || len(got) != 1 || !got[0].Unsigned {
t.Errorf("%s() = %+v, %v; want one unsigned capture", name, got, err)
}
}
}
// Existing source strings become sources: a bound source takes its binding's
// secret, a capture-only source gets none, and an existing source is kept.
func TestDeriveSourcesFromExistingRows(t *testing.T) {
pool, q := migrated(t)
ctx := t.Context()
for _, stmt := range []string{
`INSERT INTO bindings (id, name, source, secret) VALUES ('b1', 'n', 'sentry', 'envelope')`,
`INSERT INTO captures (id, source, received_at) VALUES ('c1', 'sentry', now()), ('c2', 'firewall', now()), ('c3', 'kept', now())`,
`INSERT INTO sources (path, signing, secret) VALUES ('kept', 'unsigned', 'x')`,
} {
if _, err := pool.Exec(ctx, stmt); err != nil {
t.Fatalf("%s: %v", stmt, err)
}
}
if err := q.DeriveSources(ctx); err != nil {
t.Fatalf("DeriveSources() error = %v", err)
}
want := map[string][2]string{
"sentry": {"signed", "envelope"},
"firewall": {"signed", ""},
"kept": {"unsigned", "x"},
}
rows, err := q.ListSources(ctx)
if err != nil {
t.Fatalf("ListSources() error = %v", err)
}
if len(rows) != len(want) {
t.Fatalf("derived %d sources, want %d: %+v", len(rows), len(want), rows)
}
for _, r := range rows {
if w := want[r.Path]; w != [2]string{r.Signing, r.Secret} {
t.Errorf("source %q = (%s, %q), want %v", r.Path, r.Signing, r.Secret, w)
}
}
}