From 7705fda777dc47fb67338f3ce280f32b6fb98ec1 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Thu, 3 Sep 2026 04:38:45 +1000 Subject: [PATCH] fix(binding): add Owner/Repo pin, fixing multi-repo dispatch Root-cause fix for the correctness gap named in archie-core-t2db.8: resolveBindingRepo refused to dispatch with zero or multiple configured repos, meaning a multi-repo deployment could never use bindings at all. - binding.Binding gains optional Owner/Repo fields; Validate rejects setting only one (a pin is a complete pair or not a pin at all). - Persisted as new owner/repo columns (NOT NULL DEFAULT '', additive -- no migration needed since bindings is a CREATE TABLE IF NOT EXISTS with no existing deployment yet). - resolveBindingRepo now takes the binding: a pinned binding dispatches to its own owner/repo unconditionally; an unpinned binding keeps today's single-configured-repo fallback (0 or 2+ repos still refuses, unchanged -- verified by a dedicated regression test, not just assumed preserved). - Wired through the API request/response shape (create/update accept and return owner/repo); no repo-existence validation against config added -- smallest workable change, not the named bug. Red-green throughout: 8 new tests across domain/store/daemon/webui layers, each proven to fail before the corresponding implementation step. Zero regressions in existing binding/dispatch test suites. Dashboard UI to expose this (the other half of t2db.8) is unstarted -- this closes the backend correctness gap only. --- internal/daemon/daemon.go | 24 +++---- internal/daemon/dispatch_bindings_test.go | 77 ++++++++++++++++++++++- internal/domain/binding/binding.go | 21 +++++-- internal/domain/binding/binding_test.go | 58 +++++++++++++++++ internal/store/bindings.go | 20 +++--- internal/store/bindings_test.go | 35 +++++++++++ internal/webui/api_binding.go | 12 +++- internal/webui/api_binding_test.go | 56 +++++++++++++++++ 8 files changed, 274 insertions(+), 29 deletions(-) create mode 100644 internal/domain/binding/binding_test.go diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 060fa3cbb..3a8db12bb 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -575,7 +575,7 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st return } - owner, repo, ok := d.resolveBindingRepo() + owner, repo, ok := d.resolveBindingRepo(b) if !ok { return // resolveBindingRepo already logged a warning } @@ -642,22 +642,24 @@ func renderBindingBody(values map[string]any, c store.CapturedEvent) string { } // resolveBindingRepo picks the owner/repo a binding-spawned task -// operates against. Today the binding vocabulary doesn't carry -// owner/repo fields -- every binding applies to whatever repo the -// daemon happens to be configured for. With exactly one configured -// repo the choice is unambiguous; with zero or more than one the -// loop refuses to dispatch (logged below) so a binding cannot +// operates against. A binding that pins Owner/Repo (binding.Binding's +// Owner/Repo fields, validated as a complete pair or not set at all) +// dispatches to that target unconditionally -- multi-repo deployments +// use this to disambiguate. An unpinned binding falls back to the +// single-configured-repo behaviour that predates the pin: with exactly +// one configured repo the choice is unambiguous; with zero or more than +// one the loop refuses to dispatch (logged below) so a binding cannot // silently fire against the wrong target. -// -// A binding.Owner/Repo field is the natural follow-up; until then -// this fallback is what Phase E can ship. -func (d *Daemon) resolveBindingRepo() (string, string, bool) { +func (d *Daemon) resolveBindingRepo(b binding.Binding) (string, string, bool) { + if b.Owner != "" && b.Repo != "" { + return b.Owner, b.Repo, true + } repos := d.Cfg.Get().Repos if len(repos) == 1 { return repos[0].Owner, repos[0].Name, true } d.Log.Warn("binding dispatch: cannot resolve target repo", - "hint", "configure exactly one [[repos]] entry, or extend the binding schema with owner/repo fields", + "hint", "configure exactly one [[repos]] entry, or pin the binding to a specific owner/repo", "configured_repos", len(repos)) return "", "", false } diff --git a/internal/daemon/dispatch_bindings_test.go b/internal/daemon/dispatch_bindings_test.go index f6eadcb6d..2a8b896a7 100644 --- a/internal/daemon/dispatch_bindings_test.go +++ b/internal/daemon/dispatch_bindings_test.go @@ -49,6 +49,61 @@ func TestDispatchBindingsCreatesTaskFromArmedCapture(t *testing.T) { assertDispatchRecorded(t, s, bindingID, got.ID) } +// TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos is the +// multi-repo fix: a binding that pins Owner/Repo dispatches to that +// target even when the daemon has zero or several [[repos]] configured, +// where resolveBindingRepo's old single-repo-only fallback would have +// refused entirely. +func TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos(t *testing.T) { + s := openDispatchTestStore(t) + mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true}) + bindingID, _ := seedArmedBindingWithRepo(t, s, "sentry", mappingID, "acme", "widget") + seedCapture(t, s, "sentry", true, `{"title":"hello"}`) + + d := newDispatchDaemonWithRepos(t, s, []config.Repo{ + {Owner: "acme", Name: "widget"}, + {Owner: "other-org", Name: "other-repo"}, + }) + d.dispatchBindings(t.Context()) + + tasks, err := s.Tasks(t.Context(), 10) + if err != nil { + t.Fatalf("Tasks: %v", err) + } + if len(tasks) != 1 { + t.Fatalf("Tasks len = %d, want 1 (pinned binding must dispatch despite 2 configured repos)", len(tasks)) + } + if tasks[0].Owner != "acme" || tasks[0].Repo != "widget" { + t.Fatalf("task owner/repo = %s/%s, want acme/widget (the binding's own pin, not a guess)", tasks[0].Owner, tasks[0].Repo) + } + assertDispatchRecorded(t, s, bindingID, tasks[0].ID) +} + +// TestDispatchBindingsRefusesUnpinnedBindingWithMultipleConfiguredRepos +// pins the existing safety behaviour: a binding with no Owner/Repo pin +// must still refuse to dispatch when the target repo is ambiguous, +// exactly as it did before this field existed. +func TestDispatchBindingsRefusesUnpinnedBindingWithMultipleConfiguredRepos(t *testing.T) { + s := openDispatchTestStore(t) + mappingID := seedMapping(t, s, "sentry", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString, Required: true}) + seedArmedBinding(t, s, "sentry", mappingID) // no owner/repo pin + seedCapture(t, s, "sentry", true, `{"title":"hello"}`) + + d := newDispatchDaemonWithRepos(t, s, []config.Repo{ + {Owner: "acme", Name: "widget"}, + {Owner: "other-org", Name: "other-repo"}, + }) + d.dispatchBindings(t.Context()) + + tasks, err := s.Tasks(t.Context(), 10) + if err != nil { + t.Fatalf("Tasks: %v", err) + } + if len(tasks) != 0 { + t.Fatalf("Tasks len = %d, want 0 (an unpinned binding must still refuse an ambiguous target)", len(tasks)) + } +} + // Test 31: the binding_dispatches ledger is the at-most-once // guarantee across cycles -- running dispatchBindings twice must // yield exactly one task even though the undispatched-captures query @@ -202,12 +257,22 @@ func seedMapping(t *testing.T, s *store.Store, sourceHint string, fields ...mapp // accessor -- production callers must use the structured methods // (bindings.go) rather than touching the SQL directly. func seedArmedBinding(t *testing.T, s *store.Store, source string, mappingID int64) (int64, int) { + t.Helper() + return seedArmedBindingWithRepo(t, s, source, mappingID, "", "") +} + +// seedArmedBindingWithRepo is seedArmedBinding with an explicit +// owner/repo pin (pass "", "" for the unpinned case seedArmedBinding +// covers). +func seedArmedBindingWithRepo(t *testing.T, s *store.Store, source string, mappingID int64, owner, repo string) (int64, int) { t.Helper() id, err := s.InsertBinding(t.Context(), binding.Binding{ Name: "test " + source, Matcher: binding.Matcher{Source: source}, MappingID: mappingID, Workflow: "implement", + Owner: owner, + Repo: repo, Secret: "0123456789abcdef0123456789abcdef", }) if err != nil { @@ -253,9 +318,15 @@ func seedCapture(t *testing.T, s *store.Store, source string, authenticated bool // positive assertions. func newDispatchDaemon(t *testing.T, s *store.Store) *Daemon { t.Helper() - cfg := config.Config{ - Repos: []config.Repo{{Owner: "acme", Name: "widget"}}, - } + return newDispatchDaemonWithRepos(t, s, []config.Repo{{Owner: "acme", Name: "widget"}}) +} + +// newDispatchDaemonWithRepos is newDispatchDaemon with an explicit repo +// list, for tests exercising resolveBindingRepo's owner/repo-pin path +// against zero, one, or several configured repos. +func newDispatchDaemonWithRepos(t *testing.T, s *store.Store, repos []config.Repo) *Daemon { + t.Helper() + cfg := config.Config{Repos: repos} return &Daemon{ Cfg: config.NewHolder(cfg), Store: s, diff --git a/internal/domain/binding/binding.go b/internal/domain/binding/binding.go index 38e5f8bb3..f4802da15 100644 --- a/internal/domain/binding/binding.go +++ b/internal/domain/binding/binding.go @@ -43,11 +43,19 @@ type Matcher struct { // for an event to be marked authenticated; it is never returned by // GET handlers. type Binding struct { - ID int64 `json:"id"` - Name string `json:"name"` - Matcher Matcher `json:"matcher"` - MappingID int64 `json:"mapping_id"` - Workflow string `json:"workflow"` + ID int64 `json:"id"` + Name string `json:"name"` + Matcher Matcher `json:"matcher"` + MappingID int64 `json:"mapping_id"` + Workflow string `json:"workflow"` + // Owner and Repo pin a binding to a specific configured repo, so a + // multi-repo deployment can dispatch correctly. Both empty means "no + // pin" -- resolveBindingRepo falls back to the single-configured-repo + // behaviour that predates this field. Setting only one is invalid + // (Validate rejects it): a pin is a complete owner/repo pair or not a + // pin at all, never a half-guess. + Owner string `json:"owner,omitempty"` + Repo string `json:"repo,omitempty"` Version int `json:"version"` Status Status `json:"status"` Secret string `json:"secret,omitempty"` @@ -81,6 +89,9 @@ func (b Binding) Validate() error { if len(b.Secret) < minSecretLen { return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen) } + if (b.Owner == "") != (b.Repo == "") { + return fmt.Errorf("binding: owner and repo must both be set or both be empty") + } return nil } diff --git a/internal/domain/binding/binding_test.go b/internal/domain/binding/binding_test.go new file mode 100644 index 000000000..2a6bc1916 --- /dev/null +++ b/internal/domain/binding/binding_test.go @@ -0,0 +1,58 @@ +package binding + +import "testing" + +func validBinding() Binding { + return Binding{ + Name: "sentry alerts", + Matcher: Matcher{Source: "sentry"}, + MappingID: 1, + Workflow: "implement", + Secret: "0123456789abcdef0123456789abcdef", + } +} + +// TestValidateAcceptsNoRepoPin pins backward compatibility: a binding +// with neither Owner nor Repo set (today's only shape) must remain +// valid -- resolveBindingRepo's single-configured-repo fallback still +// applies to it. +func TestValidateAcceptsNoRepoPin(t *testing.T) { + b := validBinding() + if err := b.Validate(); err != nil { + t.Fatalf("Validate() = %v, want nil", err) + } +} + +// TestValidateAcceptsBothOwnerAndRepo is the multi-repo fix: a binding +// naming a specific owner/repo must be accepted. +func TestValidateAcceptsBothOwnerAndRepo(t *testing.T) { + b := validBinding() + b.Owner, b.Repo = "acme", "widget" + if err := b.Validate(); err != nil { + t.Fatalf("Validate() = %v, want nil", err) + } +} + +// TestValidateRejectsPartialRepoPin: Owner and Repo are a pair. A +// binding naming only one of them is ambiguous -- it isn't "no pin" +// (that's both empty) and it isn't a complete pin, so it must be +// rejected at validation time rather than silently guessing which +// half was meant. +func TestValidateRejectsPartialRepoPin(t *testing.T) { + tests := []struct { + name string + owner, repo string + }{ + {"owner only", "acme", ""}, + {"repo only", "", "widget"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + b := validBinding() + b.Owner, b.Repo = tt.owner, tt.repo + if err := b.Validate(); err == nil { + t.Fatalf("Validate() = nil, want error for partial owner/repo pin (owner=%q repo=%q)", tt.owner, tt.repo) + } + }) + } +} diff --git a/internal/store/bindings.go b/internal/store/bindings.go index 6efac6434..56a33414b 100644 --- a/internal/store/bindings.go +++ b/internal/store/bindings.go @@ -18,6 +18,8 @@ CREATE TABLE IF NOT EXISTS bindings ( source TEXT NOT NULL DEFAULT '', mapping_id INTEGER NOT NULL DEFAULT 0, workflow TEXT NOT NULL DEFAULT '', + owner TEXT NOT NULL DEFAULT '', + repo TEXT NOT NULL DEFAULT '', version INTEGER NOT NULL DEFAULT 1, status TEXT NOT NULL DEFAULT 'draft', secret TEXT NOT NULL DEFAULT '', @@ -90,9 +92,9 @@ func (s *Store) InsertBinding(ctx context.Context, b binding.Binding) (int64, er return 0, err } res, err := tx.ExecContext(ctx, ` - INSERT INTO bindings (name, source, mapping_id, workflow, version, status, secret, created_at, updated_at) - VALUES (?, ?, ?, ?, 1, 'draft', ?, ?, ?)`, - b.Name, b.Matcher.Source, b.MappingID, b.Workflow, secret, now, now) + INSERT INTO bindings (name, source, mapping_id, workflow, owner, repo, version, status, secret, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, 1, 'draft', ?, ?, ?)`, + b.Name, b.Matcher.Source, b.MappingID, b.Workflow, b.Owner, b.Repo, secret, now, now) if err != nil { return 0, err } @@ -110,7 +112,7 @@ func (s *Store) InsertBinding(ctx context.Context, b binding.Binding) (int64, er // exists. func (s *Store) GetBinding(ctx context.Context, id int64) (*binding.Binding, error) { row := s.db.QueryRowContext(ctx, ` - SELECT id, name, source, mapping_id, workflow, version, status, secret, created_at, updated_at + SELECT id, name, source, mapping_id, workflow, owner, repo, version, status, secret, created_at, updated_at FROM bindings WHERE id=?`, id) b, err := scanBindingRow(row) if errors.Is(err, sql.ErrNoRows) { @@ -128,7 +130,7 @@ func (s *Store) GetBinding(ctx context.Context, id int64) (*binding.Binding, err // ListBindings returns every binding, newest first. func (s *Store) ListBindings(ctx context.Context) (out []binding.Binding, retErr error) { rows, err := s.db.QueryContext(ctx, ` - SELECT id, name, source, mapping_id, workflow, version, status, secret, created_at, updated_at + SELECT id, name, source, mapping_id, workflow, owner, repo, version, status, secret, created_at, updated_at FROM bindings ORDER BY id DESC`) if err != nil { return nil, err @@ -179,12 +181,12 @@ func (s *Store) UpdateBinding(ctx context.Context, b binding.Binding) error { return err } res, err := tx.ExecContext(ctx, ` - UPDATE bindings SET name=?, source=?, mapping_id=?, workflow=?, secret=COALESCE(NULLIF(?, ''), secret), + UPDATE bindings SET name=?, source=?, mapping_id=?, workflow=?, owner=?, repo=?, secret=COALESCE(NULLIF(?, ''), secret), status = 'pending_approval', version = version + 1, updated_at = ? WHERE id=?`, - b.Name, b.Matcher.Source, b.MappingID, b.Workflow, secret, now, b.ID) + b.Name, b.Matcher.Source, b.MappingID, b.Workflow, b.Owner, b.Repo, secret, now, b.ID) if err != nil { return err } @@ -285,7 +287,7 @@ func (s *Store) ApproveBinding(ctx context.Context, id int64) error { // practice, but the store returns the full set rather than collapsing). func (s *Store) ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error) { rows, err := s.db.QueryContext(ctx, ` - SELECT id, name, source, mapping_id, workflow, version, status, secret, created_at, updated_at + SELECT id, name, source, mapping_id, workflow, owner, repo, version, status, secret, created_at, updated_at FROM bindings WHERE source=? AND status='armed' ORDER BY id`, source) if err != nil { return nil, err @@ -434,7 +436,7 @@ func scanBindingRow(row bindingScanner) (*binding.Binding, error) { var b binding.Binding var createdAt, updatedAt string if err := row.Scan(&b.ID, &b.Name, &b.Matcher.Source, &b.MappingID, &b.Workflow, - &b.Version, &b.Status, &b.Secret, &createdAt, &updatedAt); err != nil { + &b.Owner, &b.Repo, &b.Version, &b.Status, &b.Secret, &createdAt, &updatedAt); err != nil { return nil, err } created, err := time.Parse(bindingTimeLayout, createdAt) diff --git a/internal/store/bindings_test.go b/internal/store/bindings_test.go index a14d6b088..56b519a01 100644 --- a/internal/store/bindings_test.go +++ b/internal/store/bindings_test.go @@ -62,6 +62,41 @@ func TestInsertBindingRoundTrips(t *testing.T) { } } +// TestInsertBindingRoundTripsOwnerRepo covers the multi-repo fix: a +// binding pinned to a specific owner/repo persists and reads back +// unchanged, and UpdateBinding can change the pin the same way it +// changes any other editable field. +func TestInsertBindingRoundTripsOwnerRepo(t *testing.T) { + s := openTest(t) + b := testBinding("sentry") + b.Owner, b.Repo = "acme", "widget" + id, err := s.InsertBinding(t.Context(), b) + if err != nil { + t.Fatalf("InsertBinding: %v", err) + } + + got, err := s.GetBinding(t.Context(), id) + if err != nil || got == nil { + t.Fatalf("GetBinding: %+v, %v", got, err) + } + if got.Owner != "acme" || got.Repo != "widget" { + t.Fatalf("round-tripped owner/repo = %q/%q, want acme/widget", got.Owner, got.Repo) + } + + updated := *got + updated.Owner, updated.Repo = "other-org", "other-repo" + if err := s.UpdateBinding(t.Context(), updated); err != nil { + t.Fatalf("UpdateBinding: %v", err) + } + got, err = s.GetBinding(t.Context(), id) + if err != nil || got == nil { + t.Fatalf("GetBinding after update: %+v, %v", got, err) + } + if got.Owner != "other-org" || got.Repo != "other-repo" { + t.Fatalf("updated owner/repo = %q/%q, want other-org/other-repo", got.Owner, got.Repo) + } +} + func TestGetBindingMissingReturnsNilNoError(t *testing.T) { s := openTest(t) got, err := s.GetBinding(t.Context(), 99999) diff --git a/internal/webui/api_binding.go b/internal/webui/api_binding.go index 5cd2fbf7e..722e29303 100644 --- a/internal/webui/api_binding.go +++ b/internal/webui/api_binding.go @@ -18,7 +18,13 @@ type bindingRequest struct { Matcher binding.Matcher `json:"matcher"` MappingID int64 `json:"mapping_id"` Workflow string `json:"workflow"` - Secret string `json:"secret"` + // Owner and Repo optionally pin the binding to one configured repo, + // for multi-repo deployments. Both empty is valid (falls back to the + // daemon's single-configured-repo behaviour); binding.Validate + // rejects setting only one. + Owner string `json:"owner"` + Repo string `json:"repo"` + Secret string `json:"secret"` } func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) { @@ -55,6 +61,8 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) { Matcher: req.Matcher, MappingID: req.MappingID, Workflow: req.Workflow, + Owner: req.Owner, + Repo: req.Repo, Secret: req.Secret, Status: binding.Normalize(binding.StatusDraft), } @@ -132,6 +140,8 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) { Matcher: req.Matcher, MappingID: req.MappingID, Workflow: req.Workflow, + Owner: req.Owner, + Repo: req.Repo, Secret: req.Secret, } if err := b.Validate(); err != nil { diff --git a/internal/webui/api_binding_test.go b/internal/webui/api_binding_test.go index 225f5759e..2055d8f74 100644 --- a/internal/webui/api_binding_test.go +++ b/internal/webui/api_binding_test.go @@ -102,6 +102,62 @@ func TestHandleBindingCreateAndGet(t *testing.T) { } } +// TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo covers the +// multi-repo fix at the API layer: a create/update request carrying +// owner/repo persists them, and they're visible in the response +// (they're not secret, unlike Secret). +func TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo(t *testing.T) { + srv := bindingTestServer(t) + mappingID := seedMapping(t, srv, "m") + + req := validBindingRequest("a", "sentry", mappingID) + req["owner"] = "acme" + req["repo"] = "widget" + w := doJSON(t, srv, http.MethodPost, "/api/bindings", req) + if w.Code != http.StatusCreated { + t.Fatalf("create status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String()) + } + var created binding.Binding + if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil { + t.Fatalf("unmarshal created: %v", err) + } + if created.Owner != "acme" || created.Repo != "widget" { + t.Fatalf("created owner/repo = %q/%q, want acme/widget; body = %s", created.Owner, created.Repo, w.Body.String()) + } + + updateReq := validBindingRequest("a", "sentry", mappingID) + updateReq["owner"] = "other-org" + updateReq["repo"] = "other-repo" + w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+strconv.FormatInt(created.ID, 10), updateReq) + if w.Code != http.StatusOK { + t.Fatalf("update status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String()) + } + var updated binding.Binding + if err := json.Unmarshal(w.Body.Bytes(), &updated); err != nil { + t.Fatalf("unmarshal updated: %v", err) + } + if updated.Owner != "other-org" || updated.Repo != "other-repo" { + t.Fatalf("updated owner/repo = %q/%q, want other-org/other-repo; body = %s", updated.Owner, updated.Repo, w.Body.String()) + } +} + +// TestHandleBindingCreateRejectsPartialOwnerRepo confirms the domain +// validation (owner and repo must both be set or both empty) is +// actually reached from the HTTP layer, not just unit-tested in +// isolation. +func TestHandleBindingCreateRejectsPartialOwnerRepo(t *testing.T) { + srv := bindingTestServer(t) + mappingID := seedMapping(t, srv, "m") + + req := validBindingRequest("a", "sentry", mappingID) + req["owner"] = "acme" + // repo deliberately omitted + w := doJSON(t, srv, http.MethodPost, "/api/bindings", req) + if w.Code != http.StatusBadRequest { + t.Fatalf("create status = %d, want %d (partial owner/repo pin); body = %s", w.Code, http.StatusBadRequest, w.Body.String()) + } +} + func TestHandleBindingsListStripsSecrets(t *testing.T) { srv := bindingTestServer(t) mappingID := seedMapping(t, srv, "m")