Implements archie-core-t2db.4: the runtime-editable binding entity that turns a captured webhook into an archie task, plus the per-source HMAC verification at handleCapture that makes t2db.5's 'unauthenticated event cannot trigger a binding' invariant structurally enforceable. Captures, mappings and bindings are now separate concerns on the same single *store.Store; the new BindingStore / BindingDispatcher / BindingTaskCreator split keeps each interface under the interfacebloat limit (8 methods). State machine: draft -> pending_approval -> armed; any edit on an armed binding drops it back to pending_approval, enforced in SQL via status='pending_approval' on UPDATE so the rule cannot be bypassed by a direct status field in the request body. Approve is the only sanctioned transition into armed (WHERE status='pending_approval' guard). Overlap: two bindings may not share a source in any status; enforced at InsertBinding and UpdateBinding (transaction-local SELECT). Approve has a separate TOCTOU guard so a race between Insert and Approve cannot // bypass the check. HMAC at handleCapture: reads X-Hub-Signature-256 (then X-Signature-256) // fallback, verifies via webhookguard.VerifyHMAC against the binding's // per-source secret, marks CapturedEvent.Authenticated=true on match. // Captures with no armed binding, missing signature, or wrong signature all persist as authenticated=false -- the dispatch loop's binding.Matcher.Matches gate (requires authenticated) is what stops them from spawning a task. Two armed bindings for one source returns 409 at capture time as a belt-and-braces TOCTOU guard. Dispatch loop: added Daemon.dispatchBindings, called from both Cycle and maintainAndDrain between poll and drain. Walks captured_events where authenticated=1 AND source IN armed bindings AND id NOT IN binding_dispatches, runs the binding's matcher, resolves the mapping, enqueues a chat-style task with binding_id / // binding_version provenance stamped in the same transaction as the // row insert. The binding_dispatches ledger (composite PK on (binding_id, capture_id)) is the at-most-once guarantee across cycles // and daemon restarts. Tasks schema migration: binding_id INTEGER NOT NULL DEFAULT 0 + binding_version INTEGER NOT NULL DEFAULT 0 (taskSchemaVersion bumped 1 -> 2). Existing tasks keep 0 / 0. Out of scope (documented follow-ups): - secret encryption at rest (plaintext today) - full dashboard HTML for the binding editor (CRUD API only this bead) - per-binding rate limits (existing per-remote-address limit applies) - binding.Owner / binding.Repo fields (dispatch falls back to the single configured repo; multi-repo deployments log and skip)
126 lines
4.6 KiB
Go
126 lines
4.6 KiB
Go
// Package binding owns the playbook binding vocabulary: the matcher +
|
|
// mapping + workflow + state-machine entity that turns a captured webhook
|
|
// into an archie task. See docs/prds/webhook-intake-security.md and
|
|
// docs/prds/payload-field-mapping.md.
|
|
package binding
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Status is the binding lifecycle state. Mirrors telegram's
|
|
// dangerousAction / pendingApproval shape: armed is the only state that
|
|
// evaluates against incoming events; any edit drops armed back to
|
|
// pending_approval; only an explicit Approve call moves
|
|
// pending_approval -> armed.
|
|
type Status string
|
|
|
|
const (
|
|
StatusDraft Status = "draft"
|
|
StatusPendingApproval Status = "pending_approval"
|
|
StatusArmed Status = "armed"
|
|
)
|
|
|
|
// Matcher decides which captured events a binding applies to. Source is
|
|
// the only dimension today -- the path segment the sender POSTs to
|
|
// (e.g. "sentry"). Extend with additional predicates if a use case
|
|
// demands it; the storage column is plain TEXT so widening is
|
|
// non-breaking.
|
|
type Matcher struct {
|
|
Source string `json:"source"`
|
|
}
|
|
|
|
// Binding is the runtime-editable entity that ties a matcher, a payload
|
|
// mapping, and a workflow together. Bindings live in the store, not in
|
|
// config.toml, so operators can author them from the dashboard while the
|
|
// daemon runs.
|
|
//
|
|
// 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.
|
|
type Binding struct {
|
|
ID int64 `json:"id"`
|
|
Name string `json:"name"`
|
|
Matcher Matcher `json:"matcher"`
|
|
MappingID int64 `json:"mapping_id"`
|
|
Workflow string `json:"workflow"`
|
|
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 persisted or
|
|
// evaluated. 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.
|
|
func (b Binding) Validate() error {
|
|
if strings.TrimSpace(b.Name) == "" {
|
|
return fmt.Errorf("binding: name is required")
|
|
}
|
|
if strings.TrimSpace(b.Matcher.Source) == "" {
|
|
return fmt.Errorf("binding: matcher.source is required")
|
|
}
|
|
if b.MappingID <= 0 {
|
|
return fmt.Errorf("binding: mapping_id must be positive")
|
|
}
|
|
if strings.TrimSpace(b.Workflow) == "" {
|
|
return fmt.Errorf("binding: workflow is required")
|
|
}
|
|
if len(b.Secret) < minSecretLen {
|
|
return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen)
|
|
}
|
|
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 handleCapture,
|
|
// 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
|
|
}
|
|
|
|
// Overlaps reports whether two matchers cover any plausible event
|
|
// together. With a single-string matcher this collapses to: both have
|
|
// a non-empty Source equal to each other. Two empty matchers would
|
|
// overlap trivially; Validate rejects empty Sources upstream so this
|
|
// case cannot arise in practice.
|
|
func (m Matcher) Overlaps(other Matcher) bool {
|
|
if m.Source == "" || other.Source == "" {
|
|
return false
|
|
}
|
|
return m.Source == other.Source
|
|
}
|
|
|
|
// Normalize clamps an arbitrary string into a recognised Status, falling
|
|
// back to StatusDraft for any unknown value. The DB CHECK constraint
|
|
// already rejects bad strings at write time; Normalize is the API-edge
|
|
// guard for inputs that arrive before they ever reach the store.
|
|
func Normalize(s Status) Status {
|
|
switch s {
|
|
case StatusDraft, StatusPendingApproval, StatusArmed:
|
|
return s
|
|
default:
|
|
return StatusDraft
|
|
}
|
|
}
|