merge: t2db.40 sources and signing into pg/foundation

Resolves against t2db.36: captures carry both event_type and unsigned (proto field 10), the State Store serves sources and event types from the Postgres EDA store, the capture row shows event type and signature together, and the staterpc sentinels map both ways from one table.
This commit is contained in:
sam committed 2026-09-24 14:38:40 +10:00
commit 8a2b5b95f9
63 files changed
+3839 -1753

No files matched your search

+12 -58
View File
@@ -38,9 +38,8 @@ type Matcher struct {
//
// Version is bumped on every UpdateBinding so a later edit cannot
// silently rewrite the historical provenance of a task that already
// fired. Secret is the HMAC-SHA256 shared secret a sender must sign with
// for an event to be marked authenticated; it is never returned by
// GET handlers.
// fired. Signing belongs to the source the matcher names, not to the
// binding (internal/domain/source).
type Binding struct {
ID string `json:"id"`
Name string `json:"name"`
@@ -57,52 +56,15 @@ type Binding struct {
Repo string `json:"repo,omitempty"`
Version int `json:"version"`
Status Status `json:"status"`
Secret string `json:"secret,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// minSecretLen is the floor for an acceptable shared secret. A trivially
// short secret makes accidental binding to a known HMAC trivial; the
// floor is chosen so a one-character typo cannot arm.
const minSecretLen = 16
// Validate checks a binding is well-formed before it is newly persisted.
// A non-empty Name, a non-empty Matcher.Source, a positive MappingID, a
// non-empty Workflow, and a sufficiently long Secret are all required.
// Workflow existence is checked at the API/store layer because the domain
// package does not import the workflow registry. Use ValidateForUpdate
// instead when editing an existing binding, where an empty Secret is a
// meaningful "keep the current one," not a missing value.
// Validate checks a binding is well-formed before it is persisted: a
// non-empty Name, Matcher.Source, MappingID and Workflow, and a complete
// owner/repo pin or none. Workflow existence is checked at the API/store
// layer because the domain package does not import the workflow registry.
func (b Binding) Validate() error {
if err := b.validateCommon(); err != nil {
return err
}
if len(b.Secret) < minSecretLen {
return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen)
}
return nil
}
// ValidateForUpdate is Validate for the edit path: every other field is
// checked identically, but Secret is only length-checked when the caller
// actually supplied one. UpdateBinding's own store-layer contract already
// treats an empty Secret as "preserve the existing one" (COALESCE against
// NULLIF) -- rejecting that here at the validation gate before the store
// ever sees it would make the store's own documented behavior
// unreachable. A non-empty Secret (a genuine change) is still held to the
// same floor Validate enforces.
func (b Binding) ValidateForUpdate() error {
if err := b.validateCommon(); err != nil {
return err
}
if b.Secret != "" && len(b.Secret) < minSecretLen {
return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen)
}
return nil
}
func (b Binding) validateCommon() error {
if strings.TrimSpace(b.Name) == "" {
return fmt.Errorf("binding: name is required")
}
@@ -121,18 +83,10 @@ func (b Binding) validateCommon() error {
return nil
}
// Matches reports whether the given captured event would match this
// binding's matcher. The Authenticated clause encodes t2db.5 point 1 --
// an unauthenticated event can never trigger a binding, no matter how
// well it would otherwise match.
//
// Note: the caller is expected to be the dispatch loop or the capture
// intake receiver, both of which receive a CapturedEvent with the
// Authenticated flag already set by HMAC verification. Matches is pure
// and has no I/O.
func (m Matcher) Matches(source string, authenticated bool) bool {
if !authenticated {
return false
}
return m.Source == source
// Matches reports whether a captured event would trigger this binding. An
// event that is not dispatchable (no valid signature, and not from an
// approved unsigned source) never matches, however well it would otherwise.
// Matches is pure and has no I/O.
func (m Matcher) Matches(source string, dispatchable bool) bool {
return dispatchable && m.Source == source
}
+18 -42
View File
@@ -8,7 +8,6 @@ func validBinding() Binding {
Matcher: Matcher{Source: "sentry"},
MappingID: "m1",
Workflow: "implement",
Secret: "0123456789abcdef0123456789abcdef",
}
}
@@ -33,47 +32,6 @@ func TestValidateAcceptsBothOwnerAndRepo(t *testing.T) {
}
}
// 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.
// TestValidateForUpdateAcceptsEmptySecret is the fix for a real bug found
// via browser testing (t2db.8): UpdateBinding's own documented contract
// treats an empty Secret as "preserve the existing one" (COALESCE against
// NULLIF), but the API handler validated with the create-time Validate,
// which rejected any edit that didn't retype the full secret -- making
// the store's own documented behavior unreachable.
func TestValidateForUpdateAcceptsEmptySecret(t *testing.T) {
b := validBinding()
b.Secret = ""
if err := b.ValidateForUpdate(); err != nil {
t.Fatalf("ValidateForUpdate() = %v, want nil for an empty (preserve-existing) secret", err)
}
}
// TestValidateForUpdateStillEnforcesLengthOnANewSecret confirms the fix
// isn't a blanket bypass: a genuinely-supplied short secret on update is
// still rejected, same floor as create.
func TestValidateForUpdateStillEnforcesLengthOnANewSecret(t *testing.T) {
b := validBinding()
b.Secret = "short"
if err := b.ValidateForUpdate(); err == nil {
t.Fatal("ValidateForUpdate() = nil, want error for a too-short (but non-empty) secret")
}
}
// TestValidateRejectsEmptySecretOnCreate pins that the fix is scoped to
// update only -- Validate (used at create time, where there is no
// existing secret to fall back to) still requires a real one.
func TestValidateRejectsEmptySecretOnCreate(t *testing.T) {
b := validBinding()
b.Secret = ""
if err := b.Validate(); err == nil {
t.Fatal("Validate() = nil, want error for an empty secret at create time")
}
}
func TestValidateRejectsPartialRepoPin(t *testing.T) {
tests := []struct {
name string
@@ -92,3 +50,21 @@ func TestValidateRejectsPartialRepoPin(t *testing.T) {
})
}
}
func TestMatcherMatchesOnlyDispatchableEventsFromItsSource(t *testing.T) {
m := Matcher{Source: "sentry"}
tests := []struct {
source string
dispatchable bool
want bool
}{
{"sentry", true, true},
{"sentry", false, false},
{"other", true, false},
}
for _, tt := range tests {
if got := m.Matches(tt.source, tt.dispatchable); got != tt.want {
t.Errorf("Matches(%q, %v) = %v, want %v", tt.source, tt.dispatchable, got, tt.want)
}
}
}
+50
View File
@@ -0,0 +1,50 @@
package source
import (
"crypto/rand"
"encoding/hex"
"fmt"
"github.com/google/uuid"
)
// NewPath returns a fresh UUIDv7 path: time-ordered, unguessable, and never
// colliding with another source.
func NewPath() (string, error) {
id, err := uuid.NewV7()
if err != nil {
return "", fmt.Errorf("source: generate path: %w", err)
}
return id.String(), nil
}
// NewSecret returns a fresh 32-byte HMAC secret, hex encoded.
func NewSecret() (string, error) {
var b [MinSecretLen / 2]byte
if _, err := rand.Read(b[:]); err != nil {
return "", fmt.Errorf("source: generate secret: %w", err)
}
return hex.EncodeToString(b[:]), nil
}
// ValidatePath checks a custom path is URL-safe: RFC 3986 unreserved
// characters only, so it needs no escaping, and never a dot segment.
func ValidatePath(path string) error {
if path == "" || len(path) > MaxPathLen || path == "." || path == ".." {
return ErrInvalidPath
}
for i := range len(path) {
if !unreserved(path[i]) {
return ErrInvalidPath
}
}
return nil
}
func unreserved(c byte) bool {
switch {
case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9':
return true
}
return c == '-' || c == '.' || c == '_' || c == '~'
}
+93
View File
@@ -0,0 +1,93 @@
// Package source owns the capture source: the endpoint one sender posts to,
// and its signing setting. See docs/prds/event-automation.md "Sources".
package source
import (
"errors"
"time"
)
// Signing is a source's signing state. A source is signed by default; turning
// signing off is requested and then approved, the same two-step gate as
// arming a binding, and only the approved state accepts unsigned events.
type Signing string
const (
SigningSigned Signing = "signed"
SigningUnsignedPending Signing = "unsigned_pending_approval"
SigningUnsigned Signing = "unsigned"
)
// MaxPathLen bounds a custom path.
const MaxPathLen = 128
// MinSecretLen is the length of a generated secret: 32 random bytes, hex.
const MinSecretLen = 64
var (
// ErrInvalidPath refuses a custom path that is not URL-safe.
ErrInvalidPath = errors.New("source: path must be 1-128 URL-safe characters (A-Z a-z 0-9 - . _ ~), not a dot segment")
// ErrSigningTransition refuses an approval with no pending request.
ErrSigningTransition = errors.New("source: signing transition rejected")
)
// Source is one capture endpoint. Path is its URL segment and its identity:
// captures and binding matchers reference it, so it does not change after
// creation. Secret is the HMAC key a signed sender signs with.
type Source struct {
Path string `json:"path"`
Signing Signing `json:"signing"`
Secret string `json:"secret,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// New builds a signed source with a generated secret. An empty customPath
// gets a UUIDv7 path; a non-empty one must be URL-safe. Uniqueness is the
// store's to enforce.
func New(customPath string) (Source, error) {
path := customPath
if path == "" {
generated, err := NewPath()
if err != nil {
return Source{}, err
}
path = generated
} else if err := ValidatePath(path); err != nil {
return Source{}, err
}
secret, err := NewSecret()
if err != nil {
return Source{}, err
}
return Source{Path: path, Signing: SigningSigned, Secret: secret}, nil
}
// Unsigned reports whether events on this source dispatch without a
// signature. Only an approved request counts.
func (s *Source) Unsigned() bool { return s.Signing == SigningUnsigned }
// RequestUnsigned asks to turn signing off. The source stays signed until
// ApproveUnsigned.
func (s *Source) RequestUnsigned() error {
if s.Signing == SigningSigned {
s.Signing = SigningUnsignedPending
}
return nil
}
// ApproveUnsigned is the only transition that turns signing off.
func (s *Source) ApproveUnsigned() error {
if s.Signing != SigningUnsignedPending {
return ErrSigningTransition
}
s.Signing = SigningUnsigned
return nil
}
// RequireSigning turns signing back on. It needs no approval: it only
// narrows what dispatches.
func (s *Source) RequireSigning() error {
s.Signing = SigningSigned
return nil
}
+108
View File
@@ -0,0 +1,108 @@
package source
import (
"errors"
"strings"
"testing"
"github.com/google/uuid"
)
func TestNewDefaultsToSignedUUIDv7Path(t *testing.T) {
s, err := New("")
if err != nil {
t.Fatalf("New() error = %v", err)
}
id, err := uuid.Parse(s.Path)
if err != nil {
t.Fatalf("path %q is not a UUID: %v", s.Path, err)
}
if id.Version() != 7 {
t.Fatalf("path version = %d, want 7", id.Version())
}
if s.Signing != SigningSigned {
t.Fatalf("signing = %q, want %q", s.Signing, SigningSigned)
}
if len(s.Secret) < MinSecretLen {
t.Fatalf("secret length = %d, want >= %d", len(s.Secret), MinSecretLen)
}
other, err := New("")
if err != nil {
t.Fatalf("New() error = %v", err)
}
if other.Path == s.Path || other.Secret == s.Secret {
t.Fatal("two new sources share a path or a secret")
}
}
func TestNewAcceptsOrRefusesCustomPath(t *testing.T) {
tests := []struct {
path string
ok bool
}{
{"sentry", true},
{"fire-wall_01.v2~x", true},
{"a/b", false},
{"with space", false},
{"percent%20", false},
{"..", false},
{".", false},
{strings.Repeat("a", MaxPathLen+1), false},
{"ünicode", false},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
s, err := New(tt.path)
if tt.ok {
if err != nil || s.Path != tt.path {
t.Fatalf("New(%q) = %q, %v; want path kept", tt.path, s.Path, err)
}
return
}
if !errors.Is(err, ErrInvalidPath) {
t.Fatalf("New(%q) error = %v, want ErrInvalidPath", tt.path, err)
}
})
}
}
func TestSigningTransitions(t *testing.T) {
tests := []struct {
name string
from Signing
action func(*Source) error
want Signing
wantErr bool
}{
{"request unsigned waits for approval", SigningSigned, (*Source).RequestUnsigned, SigningUnsignedPending, false},
{"approve pending", SigningUnsignedPending, (*Source).ApproveUnsigned, SigningUnsigned, false},
{"approve without request", SigningSigned, (*Source).ApproveUnsigned, SigningSigned, true},
{"approve twice", SigningUnsigned, (*Source).ApproveUnsigned, SigningUnsigned, true},
{"resign from unsigned", SigningUnsigned, (*Source).RequireSigning, SigningSigned, false},
{"resign from pending", SigningUnsignedPending, (*Source).RequireSigning, SigningSigned, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := Source{Path: "p", Signing: tt.from}
err := tt.action(&s)
if (err != nil) != tt.wantErr {
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
}
if s.Signing != tt.want {
t.Fatalf("signing = %q, want %q", s.Signing, tt.want)
}
})
}
}
func TestUnsignedOnlyOnceApproved(t *testing.T) {
for signing, want := range map[Signing]bool{
SigningSigned: false,
SigningUnsignedPending: false,
SigningUnsigned: true,
} {
if got := (&Source{Signing: signing}).Unsigned(); got != want {
t.Errorf("Unsigned() for %q = %v, want %v", signing, got, want)
}
}
}
@@ -24,6 +24,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
@@ -205,6 +206,20 @@ type BindingStore interface {
ApproveBinding(ctx context.Context, id string) error
}
// SourceStore persists capture sources and their signing setting
// (docs/prds/event-automation.md "Sources"). The path is the key and never
// changes. Secrets cross this surface in plaintext; the store encrypts them
// at rest. Signing transitions are decided by the source domain and written
// with an expected-from guard, so two operators cannot race an approval.
type SourceStore interface {
InsertSource(ctx context.Context, s source.Source) error
// GetSource returns (nil, nil) for an unknown path.
GetSource(ctx context.Context, path string) (*source.Source, error)
ListSources(ctx context.Context) ([]source.Source, error)
SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error
SetSourceSecret(ctx context.Context, path, secret string) error
}
// BindingDispatcher is the dispatch-loop surface over the bindings store:
// look up armed bindings for HMAC verification, list captures that still
// need dispatching, and record the at-most-once ledger row. The
@@ -288,8 +303,15 @@ type CapturedEvent struct {
// when it arrived, or empty when it matched none. An unidentified capture
// is never dispatched.
EventType string `json:"event_type"`
// Unsigned marks an event that arrived on an approved unsigned source.
// It dispatches without Authenticated and is flagged wherever it shows.
Unsigned bool `json:"unsigned"`
}
// Dispatchable reports whether a binding may start a task from this event:
// a valid signature, or a source approved to take unsigned events.
func (c CapturedEvent) Dispatchable() bool { return c.Authenticated || c.Unsigned }
// ConfigSnapshot is the running configuration as the dashboard renders it,
// published by whoever owns configuration for whoever displays it.
//
@@ -389,6 +411,13 @@ var (
ErrMappingNotFound = errors.New("store: mapping not found")
// ErrEventTypeNotFound is returned when an event type ID does not exist.
ErrEventTypeNotFound = errors.New("store: event type not found")
// ErrSourceNotFound is returned when a source path does not exist.
ErrSourceNotFound = errors.New("store: source not found")
// ErrSourcePathTaken is returned when a new source's path is in use.
ErrSourcePathTaken = errors.New("store: source path already taken")
// ErrSourceSigningStale is returned when a signing write's expected
// from state does not match the stored one.
ErrSourceSigningStale = errors.New("store: source signing does not match expected state")
// ErrResourceNotFound is returned when a control-plane resource kind has
// no stored document. It is in-process only (not on the gRPC wire): the