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

@@ -15,14 +15,13 @@ package captureintake
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"time"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/webhookguard"
@@ -42,10 +41,10 @@ type Receiver struct {
// is read. Nil disables rate limiting, which composition never does in
// production.
Limiter *webhookguard.RateLimiter
// Bindings resolves the armed binding whose secret authenticates a
// source. Nil disables per-source HMAC verification and every event
// records as authenticated=false.
Bindings storecontract.BindingDispatcher
// Sources resolves the source a path names and its signing setting.
// Nil disables verification: every event records as neither
// authenticated nor unsigned, so none dispatches.
Sources SourceResolver
// Retention and MaxEvents are passed straight to InsertCapture's
// prune-on-write bounds. See config.CaptureConfig.
Retention time.Duration
@@ -61,23 +60,28 @@ type Receiver struct {
Log *slog.Logger
}
// SourceResolver is the one SourceStore read intake needs.
type SourceResolver interface {
GetSource(ctx context.Context, path string) (*source.Source, error)
}
// Register mounts the receiver on mux.
func (rc *Receiver) Register(mux *http.ServeMux) {
mux.HandleFunc(Path, rc.ServeHTTP)
}
// ServeHTTP accepts an inbound webhook POST and persists it. If a binding is
// armed for this source the body must also carry a valid HMAC signature; only
// correctly-signed events are recorded as authenticated (t2db.5 point 1). An
// unauthenticated event is still captured, visible in the inspector, and
// marked unauthenticated -- the dispatch loop's auth check
// (binding.Matcher.Matches) is the actual gate against false task creation.
// ServeHTTP accepts an inbound webhook POST and persists it. On a signed
// source only a valid HMAC under the source's secret marks the event
// authenticated; on an approved unsigned source every event is marked
// unsigned. Anything else is still captured and visible in the inspector,
// but is neither, so the dispatch loop's check (binding.Matcher.Matches over
// CapturedEvent.Dispatchable) never starts a task from it.
func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if rc.Captures == nil {
http.Error(w, "capture not configured", http.StatusServiceUnavailable)
return
}
source := r.PathValue("source")
path := r.PathValue("source")
// webhookguard.RateLimiter's bucket map assumes a bounded, operator-
// registered key space (see its doc comment) -- it is never evicted, and
@@ -92,10 +96,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
armed, ok := rc.armedBindings(w, r, source)
if !ok {
return
}
src := rc.resolveSource(r, path)
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytesOrFallback(rc.MaxBodyBytes))
body, err := io.ReadAll(r.Body)
@@ -106,20 +107,8 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
// HMAC verification -- only when exactly one binding is armed for this
// source. Mirrors channels/webhook/webhook.go's header precedence:
// GitHub-style X-Hub-Signature-256 first, X-Signature-256 fallback.
// Empty header + non-empty secret is never valid (VerifyHMAC's own
// guard), so an absent signature with an armed binding lands here as
// authenticated=false rather than authenticated=true.
authenticated := false
if len(armed) == 1 {
sig := r.Header.Get("X-Hub-Signature-256")
if sig == "" {
sig = r.Header.Get("X-Signature-256")
}
authenticated = webhookguard.VerifyHMAC(body, sig, armed[0].Secret)
}
// Verified on the raw bytes, before redaction parses them.
authenticated, unsigned := verify(src, r.Header, body)
headers, _ := json.Marshal(r.Header)
redactedHeaders, err := webhookguard.RedactPayload(headers)
@@ -137,16 +126,17 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := storecontract.CapturedEvent{
ReceivedAt: time.Now().UTC(),
Source: source,
Source: path,
RemoteAddr: r.RemoteAddr,
ContentType: r.Header.Get("Content-Type"),
Headers: string(redactedHeaders),
Body: string(redactedBody),
Authenticated: authenticated,
Unsigned: unsigned,
}
id, err := rc.Captures.InsertCapture(r.Context(), c, rc.Retention, rc.MaxEvents)
if err != nil {
rc.logger().Error("capture insert", "err", err, "source", source)
rc.logger().Error("capture insert", "err", err, "source", path)
http.Error(w, "capture failed", http.StatusInternalServerError)
return
}
@@ -161,42 +151,49 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if rc.Publish != nil {
rc.Publish(r.Context(), events.Event{
Kind: "capture",
Detail: "capture from " + source,
Data: map[string]any{"id": id, "source": source},
Detail: "capture from " + path,
Data: map[string]any{"id": id, "source": path, "unsigned": unsigned},
})
}
w.WriteHeader(http.StatusAccepted)
}
// armedBindings resolves the bindings armed for source before the body is
// read. A lookup error is logged and treated as "no armed binding" -- the
// dispatch loop's auth check is the actual gate, so failing closed here would
// amplify a transient store hiccup into a capture outage for every
// sender-not-yet-bound flow. If a future phase wants fail-closed semantics,
// that is a separate decision and should not silently land here.
//
// Two armed bindings for one source would race over every inbound webhook for
// that source: the write-time overlap check should make this state
// impossible, but the dispatch loop needs a single binding per capture, so
// the overlap surfaces as 409 at capture time (belt-and-braces TOCTOU guard
// -- see the store's ApproveBinding).
func (rc *Receiver) armedBindings(w http.ResponseWriter, r *http.Request, source string) ([]binding.Binding, bool) {
if rc.Bindings == nil {
return nil, true
// resolveSource looks up the source a path names. A lookup error is logged
// and treated as an unknown source: the event is still captured but cannot
// dispatch, so failing open here costs no safety, while failing closed would
// turn a transient store hiccup into a capture outage.
func (rc *Receiver) resolveSource(r *http.Request, path string) *source.Source {
if rc.Sources == nil {
return nil
}
armed, err := rc.Bindings.ArmedBindingsForSource(r.Context(), source)
src, err := rc.Sources.GetSource(r.Context(), path)
if err != nil {
rc.logger().Warn("armed bindings lookup", "source", source, "err", err)
return nil, true
rc.logger().Warn("source lookup", "source", path, "err", err)
return nil
}
if len(armed) > 1 {
http.Error(w,
fmt.Sprintf("multiple armed bindings for source %q -- overlap rejected", source),
http.StatusConflict)
return nil, false
return src
}
// verify decides how an event on src may dispatch. An approved unsigned
// source marks it unsigned. Otherwise a valid HMAC under the source's secret
// authenticates it: X-Hub-Signature-256 first, X-Signature-256 as fallback.
// A source with no secret yet authenticates nothing, since an empty key is
// one anybody can sign with.
func verify(src *source.Source, h http.Header, body []byte) (authenticated, unsigned bool) {
switch {
case src == nil:
return false, false
case src.Unsigned():
return false, true
case src.Secret == "":
return false, false
}
return armed, true
sig := h.Get("X-Hub-Signature-256")
if sig == "" {
sig = h.Get("X-Signature-256")
}
return webhookguard.VerifyHMAC(body, sig, src.Secret), false
}
func (rc *Receiver) logger() *slog.Logger {
@@ -13,7 +13,7 @@ import (
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
"github.com/samcharles93/archie-core/internal/store"
@@ -74,92 +74,6 @@ func captureTestServer(t *testing.T) testReceiver {
}
}
// stubBindingStore injects a configurable armed-binding lookup result so
// handleCapture tests can exercise the single-binding HMAC path and the
// belt-and-braces 409-on-multiple path without seeding the real store
// (which would either run into the overlap-rejection guard or require
// bypassing the draft -> pending_approval -> armed lifecycle). The 409
// path exists exactly for the case where the write-time check was
// bypassed somehow, so simulating that case directly is the most honest
// way to cover it.
type stubBindingStore struct {
armedBySource map[string][]binding.Binding
lookupErr error
}
func (s *stubBindingStore) ArmedBindingsForSource(_ context.Context, source string) ([]binding.Binding, error) {
if s.lookupErr != nil {
return nil, s.lookupErr
}
return s.armedBySource[source], nil
}
// handleCapture only touches ArmedBindingsForSource on the binding
// surface. The rest of BindingStore is stubbed so the type satisfies the
// interface and Phase C's other handlers can be exercised elsewhere.
func (s *stubBindingStore) InsertBinding(_ context.Context, _ binding.Binding) (int64, error) {
return 0, nil
}
func (s *stubBindingStore) GetBinding(_ context.Context, _ int64) (*binding.Binding, error) {
return nil, nil
}
func (s *stubBindingStore) ListBindings(_ context.Context) ([]binding.Binding, error) {
return nil, nil
}
func (s *stubBindingStore) UpdateBinding(_ context.Context, _ binding.Binding) error {
return nil
}
func (s *stubBindingStore) DeleteBinding(_ context.Context, _ int64) error {
return nil
}
func (s *stubBindingStore) ApproveBinding(_ context.Context, _ int64) error {
return nil
}
func (s *stubBindingStore) RecordDispatch(
_ context.Context,
_ string,
_ int64,
_ string,
_ int64,
) error {
return nil
}
func (s *stubBindingStore) ListUndispatchedCaptures(_ context.Context, _ []string, _ int) ([]store.CapturedEvent, error) {
return nil, nil
}
// captureBindingServer builds a Server with both a real CaptureStore (so
// ListCaptures can read back what handleCapture persisted) and a stub
// BindingDispatcher configured with one armed binding for the given
// source. The mapping/workflow fields are placeholders -- handleCapture
// never reads them, only the Secret.
func captureBindingServer(t *testing.T, secret, source string) testReceiver {
t.Helper()
srv := captureTestServer(t)
srv.Bindings = &stubBindingStore{
armedBySource: map[string][]binding.Binding{
source: {{
ID: "rbind0000000001",
Name: "test",
Matcher: binding.Matcher{Source: source},
MappingID: "rmap00000000001",
Workflow: "implement",
Version: 1,
Status: binding.StatusArmed,
Secret: secret,
}},
},
}
return srv
}
// hmacSHA256 returns the GitHub-style "sha256=<hex>" signature for body
// under secret, the same form webhookguard.VerifyHMAC accepts.
func hmacSHA256(secret, body string) string {
@@ -440,230 +354,99 @@ func TestHandleCaptureStorageFailureIs500(t *testing.T) {
}
}
// TestHandleCaptureMarksAuthenticatedWhenHMACMatches is the green half of
// the t2db.5 point 1 wiring: a capture POST signed with the armed
// binding's secret must be recorded with Authenticated=true so the
// dispatch loop's binding.Matcher.Matches check (which gates on
// authenticated) can fire.
func TestHandleCaptureMarksAuthenticatedWhenHMACMatches(t *testing.T) {
const secret = "abcdefghijklmnop" // exactly 16 bytes (binding.Validate floor)
srv := captureBindingServer(t, secret, "github")
body := `{"action":"opened"}`
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Hub-Signature-256", hmacSHA256(secret, body))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusAccepted, w.Body.String())
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 {
t.Fatalf("captured rows = %d, want 1", len(got))
}
if !got[0].Authenticated {
t.Errorf("Authenticated = false, want true (signature matched armed binding's secret)")
}
// stubSources resolves a fixed set of sources, or fails every lookup.
type stubSources struct {
byPath map[string]source.Source
err error
}
// TestHandleCaptureMarksUnauthenticatedWhenHMACMismatches covers the
// negative side of the HMAC verification: a body signed with the WRONG
// secret is still captured (per t2db.5 point 1 -- captures must remain
// inspectable even when auth fails) but flagged as unauthenticated so
// the dispatch loop's auth gate can drop it.
func TestHandleCaptureMarksUnauthenticatedWhenHMACMismatches(t *testing.T) {
func (s stubSources) GetSource(_ context.Context, path string) (*source.Source, error) {
if s.err != nil {
return nil, s.err
}
src, ok := s.byPath[path]
if !ok {
return nil, nil
}
return &src, nil
}
// memCaptures records inserted captures, including the Unsigned flag the
// legacy store does not persist.
type memCaptures struct{ rows []store.CapturedEvent }
func (m *memCaptures) InsertCapture(_ context.Context, c store.CapturedEvent, _ time.Duration, _ int) (string, error) {
m.rows = append(m.rows, c)
return "c", nil
}
func (m *memCaptures) ListCaptures(context.Context, int) ([]store.CapturedEvent, error) {
return m.rows, nil
}
// TestHandleCaptureSigning pins the source signing rule: a signed source
// authenticates only a valid X-Hub-Signature-256 or X-Signature-256 HMAC
// under its secret; an approved unsigned source marks every event unsigned;
// anything else is captured and neither authenticated nor unsigned, so it
// never dispatches.
func TestHandleCaptureSigning(t *testing.T) {
const secret = "abcdefghijklmnop"
srv := captureBindingServer(t, secret, "github")
body := `{"action":"opened"}`
wrong := hmacSHA256("not-the-real-secret-aaaaaaaaa", body)
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
req.Header.Set("X-Hub-Signature-256", wrong)
w := httptest.NewRecorder()
const body = `{"action":"opened"}`
signed := source.Source{Path: "github", Signing: source.SigningSigned, Secret: secret}
pending := source.Source{Path: "github", Signing: source.SigningUnsignedPending, Secret: secret}
unsigned := source.Source{Path: "github", Signing: source.SigningUnsigned, Secret: secret}
noSecret := source.Source{Path: "github", Signing: source.SigningSigned}
tests := []struct {
name string
sources SourceResolver
header, sig string
authenticated bool
unsigned bool
}{
{"signed, valid hub signature", sources(signed), "X-Hub-Signature-256", hmacSHA256(secret, body), true, false},
{"signed, valid fallback signature", sources(signed), "X-Signature-256", hmacSHA256(secret, body), true, false},
{"signed, wrong signature", sources(signed), "X-Hub-Signature-256", hmacSHA256("not-the-real-secret", body), false, false},
{"signed, no signature", sources(signed), "", "", false, false},
{"signed, no secret yet", sources(noSecret), "X-Hub-Signature-256", hmacSHA256("", body), false, false},
{"unsigned request not yet approved", sources(pending), "", "", false, false},
{"unsigned request not yet approved, signed event", sources(pending), "X-Hub-Signature-256", hmacSHA256(secret, body), true, false},
{"approved unsigned", sources(unsigned), "", "", false, true},
{"unknown source", sources(), "X-Hub-Signature-256", hmacSHA256(secret, body), false, false},
{"lookup error fails open at capture", stubSources{err: errors.New("db locked")}, "", "", false, false},
{"no source store", nil, "X-Hub-Signature-256", hmacSHA256(secret, body), false, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
captures := &memCaptures{}
rc := &Receiver{Log: slog.New(slog.DiscardHandler), Captures: captures, Sources: tt.sources}
mux := http.NewServeMux()
rc.Register(mux)
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
if tt.header != "" {
req.Header.Set(tt.header, tt.sig)
}
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
mux.ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d (a mismatched signature must still produce a capture, not reject the request)", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 {
t.Fatalf("captured rows = %d, want 1", len(got))
}
if got[0].Authenticated {
t.Errorf("Authenticated = true, want false (signature did not match armed binding's secret)")
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
if len(captures.rows) != 1 {
t.Fatalf("captured rows = %d, want 1", len(captures.rows))
}
got := captures.rows[0]
if got.Authenticated != tt.authenticated || got.Unsigned != tt.unsigned {
t.Fatalf("authenticated, unsigned = %v, %v; want %v, %v", got.Authenticated, got.Unsigned, tt.authenticated, tt.unsigned)
}
})
}
}
// TestHandleCaptureWithNoSignatureMarksUnauthenticated covers the
// "sender forgot the header" case: the binding is armed, the secret is
// registered, but the request carries no signature at all. The handler
// must fall through to authenticated=false (the empty-signature guard
// in webhookguard.VerifyHMAC). Captures are still recorded -- the
// operator can see the unsigned attempt in the inspector.
func TestHandleCaptureWithNoSignatureMarksUnauthenticated(t *testing.T) {
const secret = "abcdefghijklmnop"
srv := captureBindingServer(t, secret, "github")
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
// Deliberately no X-Hub-Signature-256 / X-Signature-256 header.
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
}
}
// TestHandleCaptureWithMultipleArmedBindingsReturns409 covers the
// belt-and-braces TOCTOU guard: two armed bindings for the same source
// would race over every inbound webhook for that source, so the
// capture-time handler returns 409 Conflict instead of silently picking
// a winner. The store's overlap check should make this impossible in
// practice; the 409 is the safety net. The stub injects the state
// directly to exercise that safety net.
func TestHandleCaptureWithMultipleArmedBindingsReturns409(t *testing.T) {
srv := captureTestServer(t)
srv.Bindings = &stubBindingStore{
armedBySource: map[string][]binding.Binding{
"github": {
{ID: "rbind0000000001", Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "abcdefghijklmnop"},
{ID: "rbind0000000002", Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "qrstuvwxyz123456"},
},
},
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusConflict {
t.Fatalf("status = %d, want %d (multiple armed bindings must surface as 409 at capture time)", w.Code, http.StatusConflict)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 0 {
t.Fatalf("captured rows = %d, want 0 (a 409 must never persist a row)", len(got))
}
}
// TestHandleCaptureAcceptsWhenNoArmedBindingExists documents the
// "source has never been bound" path: Bindings is wired but
// ArmedBindingsForSource returns an empty slice. The handler must
// still capture, with authenticated=false -- there is no armed binding
// to check against, so HMAC is meaningless, but the event itself is
// still worth recording for the inspector.
func TestHandleCaptureAcceptsWhenNoArmedBindingExists(t *testing.T) {
srv := captureTestServer(t)
srv.Bindings = &stubBindingStore{armedBySource: map[string][]binding.Binding{}}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
}
}
// TestHandleCaptureAcceptsWithBindingsNil pins the legacy backwards-
// compatibility behaviour: Bindings is nil (composition never wired the
// binding surface, or the dashboard is running without the feature).
// handleCapture must behave as it did before this phase landed -- still
// capture, still record authenticated=false.
func TestHandleCaptureAcceptsWithBindingsNil(t *testing.T) {
srv := captureTestServer(t)
if srv.Bindings != nil {
t.Fatalf("captureTestServer must not wire Bindings by default for this test")
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
}
}
// TestHandleCaptureBindingsLookupErrorFailsOpenAtCapture pins the
// documented fail-open posture: if ArmedBindingsForSource errors, the
// capture still goes through (the dispatch loop's auth check is the
// actual gate). A transient store hiccup must not amplify into a
// capture outage for sends-that-haven't-been-bound-yet.
func TestHandleCaptureBindingsLookupErrorFailsOpenAtCapture(t *testing.T) {
srv := captureTestServer(t)
srv.Bindings = &stubBindingStore{lookupErr: errors.New("db locked")}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d (a transient lookup error must not fail closed at capture)", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
}
}
// TestHandleCaptureAcceptsXSignature256FallbackHeader pins the second
// header in the precedence list: when X-Hub-Signature-256 is absent but
// X-Signature-256 is present, the fallback is honoured. Mirrors
// channels/webhook/webhook.go's header precedence.
func TestHandleCaptureAcceptsXSignature256FallbackHeader(t *testing.T) {
const secret = "abcdefghijklmnop"
srv := captureBindingServer(t, secret, "github")
body := `{"action":"opened"}`
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
// No X-Hub-Signature-256; signature is in X-Signature-256 only.
req.Header.Set("X-Signature-256", hmacSHA256(secret, body))
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusAccepted {
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
}
got, err := srv.store.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 || !got[0].Authenticated {
t.Fatalf("captured = %+v, want 1 row with Authenticated=true (X-Signature-256 fallback must work)", got)
func sources(list ...source.Source) stubSources {
byPath := map[string]source.Source{}
for _, s := range list {
byPath[s.Path] = s
}
return stubSources{byPath: byPath}
}
@@ -2,7 +2,6 @@ package edastore
import (
"encoding/base64"
"path/filepath"
"strings"
"testing"
)
@@ -122,111 +121,6 @@ func TestBindingCipherDerivesDistinctKeys(t *testing.T) {
}
// openWithCipher builds a store whose binding secrets are encrypted at rest.
func openWithCipher(t *testing.T, cipher BindingCipher) *Store {
t.Helper()
dir := t.TempDir()
s, err := Open(Config{
DBPath: filepath.Join(dir, "eda.sqlite"),
DataDir: filepath.Join(dir, "pb_data"),
Cipher: cipher,
})
if err != nil {
t.Fatalf("Open() error = %v", err)
}
t.Cleanup(func() { _ = s.Close() })
return s
}
func sampleBinding() bindingInput {
return bindingInput{Name: "n", Source: "sentry", Workflow: "implement", Secret: "supersecretvalue0123"}
}
// TestBindingSecretIsEncryptedAtRest pins that the plaintext secret never
// reaches the database file. Reading the column directly is the point: a
// round-trip through the store would decrypt and prove nothing.
func TestBindingSecretIsEncryptedAtRest(t *testing.T) {
cipher, err := NewBindingCipher(testBindingKey, nil)
if err != nil {
t.Fatalf("NewBindingCipher() error = %v", err)
}
s := openWithCipher(t, cipher)
in := sampleBinding()
id := insertBinding(t, s, in)
var stored string
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
t.Fatalf("read raw secret: %v", err)
}
if stored == in.Secret {
t.Fatal("secret is stored as plaintext; it must be encrypted at rest")
}
if !strings.Contains(stored, ":") {
t.Errorf("stored secret %q does not look like a cipher envelope", stored)
}
}
// TestBindingSecretDecryptsOnRead pins the other half: what was encrypted
// comes back as the original plaintext.
func TestBindingSecretDecryptsOnRead(t *testing.T) {
cipher, _ := NewBindingCipher(testBindingKey, nil)
s := openWithCipher(t, cipher)
in := sampleBinding()
id := insertBinding(t, s, in)
got, err := s.GetBinding(t.Context(), id)
if err != nil {
t.Fatalf("GetBinding() error = %v", err)
}
if got.Secret != in.Secret {
t.Errorf("Secret = %q, want %q", got.Secret, in.Secret)
}
}
// TestNoCipherKeepsPlaintext pins the behaviour that predates encryption: a
// deployment with no configured key still works, storing plaintext.
func TestNoCipherKeepsPlaintext(t *testing.T) {
s := openWithCipher(t, nil)
in := sampleBinding()
id := insertBinding(t, s, in)
var stored string
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
t.Fatalf("read raw secret: %v", err)
}
if stored != in.Secret {
t.Errorf("stored secret = %q, want the plaintext %q with no cipher configured", stored, in.Secret)
}
}
// TestRotatedKeyStillReadsOldRows pins key rotation: a secret written under
// the previous key must stay readable once a new active key is installed,
// otherwise a rotation silently bricks every armed binding.
func TestRotatedKeyStillReadsOldRows(t *testing.T) {
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
oldCipher, _ := NewBindingCipher(oldKey, nil)
s := openWithCipher(t, oldCipher)
in := sampleBinding()
id := insertBinding(t, s, in)
rotated, err := NewBindingCipher(testBindingKey, []string{oldKey})
if err != nil {
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
}
s.cipher = rotated
got, err := s.GetBinding(t.Context(), id)
if err != nil {
t.Fatalf("GetBinding() after rotation error = %v", err)
}
if got.Secret != in.Secret {
t.Errorf("Secret after rotation = %q, want %q: the previous key must still decrypt", got.Secret, in.Secret)
}
}
// tamperEnvelope flips one byte inside the ciphertext region so Decrypt must
// fail authentication rather than return altered plaintext.
func tamperEnvelope(t *testing.T, envelope string) string {
t.Helper()
parts := strings.SplitN(envelope, ":", 4)
@@ -133,17 +133,9 @@ func (s *Store) bindingValue(r *core.Record) (binding.Binding, error) {
Repo: r.GetString("repo"),
Version: r.GetInt("version"),
Status: binding.Status(r.GetString("status")),
Secret: r.GetString("secret"),
CreatedAt: r.GetDateTime("created_at").Time(),
UpdatedAt: r.GetDateTime("updated_at").Time(),
}
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
}
@@ -154,20 +146,6 @@ func (s *Store) applyBinding(r *core.Record, b binding.Binding) error {
r.Set("workflow", b.Workflow)
r.Set("owner", b.Owner)
r.Set("repo", b.Repo)
// An empty secret means "keep the stored one". An edit form that does not
// echo the secret back must not silently disarm the binding by erasing it.
if b.Secret == "" {
return nil
}
secret := b.Secret
if s.cipher != nil {
encrypted, err := s.cipher.Encrypt(secret)
if err != nil {
return fmt.Errorf("edastore: encrypt binding secret: %w", err)
}
secret = encrypted
}
r.Set("secret", secret)
return nil
}
@@ -12,7 +12,6 @@ type bindingInput struct {
Name string
Source string
Workflow string
Secret string
}
func insertBinding(t *testing.T, s *Store, in bindingInput) string {
@@ -21,7 +20,6 @@ func insertBinding(t *testing.T, s *Store, in bindingInput) string {
Name: in.Name,
Matcher: binding.Matcher{Source: in.Source},
Workflow: in.Workflow,
Secret: in.Secret,
})
if err != nil {
t.Fatalf("InsertBinding() error = %v", err)
@@ -284,6 +284,13 @@ func importInto(ctx context.Context, tx pgx.Tx, present []domain, sources map[st
return Report{}, err
}
}
// Sources are derived, not imported: the migration derived them from an
// empty target, so derive again from what was just loaded.
if sources["eda"] != nil {
if err := postgresdb.New(tx).DeriveSources(ctx); err != nil {
return Report{}, fmt.Errorf("legacy import: derive sources: %w", err)
}
}
if gw := sources["gateway"]; gw != nil {
var err error
if report.UnindexedMessages, err = unindexedMessages(ctx, gw, loaded); err != nil {
@@ -281,7 +281,7 @@ func TestImportCopiesEverySourceAndLeavesThemUntouched(t *testing.T) {
}{
{"SELECT review_cursor FROM tasks WHERE id = 1", &reviewCursor},
{"SELECT value FROM resource_history WHERE id = 1", &value},
{"SELECT secret FROM bindings WHERE id = 'rbind1'", &gotSecret},
{"SELECT secret FROM sources WHERE path = 'gh'", &gotSecret},
{"SELECT headers FROM captures WHERE id = 'rcap2'", &headers},
{"SELECT result FROM tool_calls WHERE id = 'rtool1'", &result},
{"SELECT configured FROM channel_status WHERE id = 'tg'", &configured},
+4 -2
View File
@@ -24,10 +24,12 @@ var droppedColumns = map[string]bool{
}
// newColumns are target columns added after the legacy stores, with no
// legacy value to carry. Imported rows take the column default: an imported
// capture has no event type, so it stays unidentified and never dispatches.
// legacy value to carry; an imported row takes the column default. An
// imported capture has no event type, so it stays unidentified and never
// dispatches, and no legacy source could take unsigned events.
var newColumns = map[string]bool{
"captures.event_type": true,
"captures.unsigned": true,
}
// targetKeys override a table's legacy key where the target has no column
+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.
@@ -98,6 +98,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(),
EventType: eventType,
}); err != nil {
@@ -134,6 +135,7 @@ func captureValue(r postgresdb.Capture) storecontract.CapturedEvent {
Body: r.Body,
Authenticated: r.Authenticated,
EventType: r.EventType,
Unsigned: r.Unsigned,
}
}
@@ -284,19 +286,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},
@@ -306,18 +299,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
@@ -325,14 +309,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,
@@ -343,7 +319,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
@@ -365,10 +340,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
}
@@ -379,11 +351,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
}
@@ -396,28 +364,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,
@@ -427,7 +381,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
@@ -128,79 +128,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 {
@@ -113,6 +126,15 @@ 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 eventTypesForSource = `-- name: EventTypesForSource :many
SELECT id, source, name, rule, schema, created_at, updated_at
FROM event_types WHERE source = $1 ORDER BY name
@@ -147,13 +169,27 @@ func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]Eve
}
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,
@@ -164,7 +200,6 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
&i.Repo,
&i.Version,
&i.Status,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
)
@@ -210,9 +245,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 {
@@ -224,7 +276,6 @@ type InsertBindingParams struct {
Owner string
Repo string
Status string
Secret string
}
func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) error {
@@ -237,7 +288,6 @@ func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) er
arg.Owner,
arg.Repo,
arg.Status,
arg.Secret,
)
return err
}
@@ -266,8 +316,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, event_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
`
type InsertCaptureParams struct {
@@ -279,6 +329,7 @@ type InsertCaptureParams struct {
Body string
Authenticated bool
ReceivedAt time.Time
Unsigned bool
EventType string
}
@@ -293,6 +344,7 @@ func (q *Queries) InsertCapture(ctx context.Context, arg InsertCaptureParams) er
arg.Body,
arg.Authenticated,
arg.ReceivedAt,
arg.Unsigned,
arg.EventType,
)
return err
@@ -366,6 +418,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)
@@ -395,19 +462,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,
@@ -418,7 +499,6 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
&i.Repo,
&i.Version,
&i.Status,
&i.Secret,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
@@ -433,7 +513,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, event_type
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
FROM captures
ORDER BY received_at DESC
LIMIT $1
@@ -457,6 +537,7 @@ func (q *Queries) ListCaptures(ctx context.Context, limit int32) ([]Capture, err
&i.Body,
&i.Authenticated,
&i.ReceivedAt,
&i.Unsigned,
&i.EventType,
); err != nil {
return nil, err
@@ -534,8 +615,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, event_type
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
FROM captures
WHERE source = ANY($1::text[])
-- An unidentified capture is never dispatched.
@@ -568,6 +679,7 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat
&i.Body,
&i.Authenticated,
&i.ReceivedAt,
&i.Unsigned,
&i.EventType,
); err != nil {
return nil, err
@@ -603,6 +715,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
@@ -649,9 +808,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
`
@@ -664,12 +821,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,
@@ -680,7 +833,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
EventType string
}
@@ -200,6 +201,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, event_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);
-- name: ListCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
FROM captures
ORDER BY received_at DESC
LIMIT $1;
-- name: ListUndispatchedCaptures :many
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
FROM captures
WHERE source = ANY(@sources::text[])
-- An unidentified capture is never dispatched.
@@ -49,30 +49,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
@@ -126,3 +121,24 @@ DELETE FROM event_types WHERE id = $1;
-- Serialises saves per source so two concurrent saves cannot each pass the
-- overlap check against a set that excludes the other.
SELECT pg_advisory_xact_lock(hashtext('event_types:' || sqlc.arg(source)::text));
-- 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,162 @@
package postgres
import (
"errors"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/domain/eventtype"
"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)
// Only an identified capture is listed for dispatch; a catch-all type
// identifies every event on the source.
if _, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "any"}); err != nil {
t.Fatalf("InsertEventType() error = %v", err)
}
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)
}
}
}
@@ -33,14 +33,14 @@ func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
// public draft -> pending_approval -> armed lifecycle.
id, err := eda.InsertBinding(t.Context(), binding.Binding{
Name: "large binding", Matcher: binding.Matcher{Source: "large"},
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
MappingID: mappingID, Workflow: "implement",
})
if err != nil {
t.Fatal(err)
}
if err := eda.UpdateBinding(t.Context(), binding.Binding{
ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"},
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
MappingID: mappingID, Workflow: "implement",
}); err != nil {
t.Fatal(err)
}
@@ -13,6 +13,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
@@ -47,6 +48,7 @@ var (
_ storecontract.CaptureStore = (*Client)(nil)
_ storecontract.MappingStore = (*Client)(nil)
_ storecontract.BindingStore = (*Client)(nil)
_ storecontract.SourceStore = (*Client)(nil)
_ storecontract.BindingDispatcher = (*Client)(nil)
_ storecontract.BindingTaskCreator = (*Client)(nil)
_ storecontract.PlaybookDispatcher = (*Client)(nil)
@@ -460,6 +462,43 @@ func (c *Client) ApproveBinding(ctx context.Context, id string) error {
return unmapError(err)
}
// Source
func (c *Client) InsertSource(ctx context.Context, s source.Source) error {
_, err := c.client.InsertSource(ctx, &pb.InsertSourceRequest{Source: sourceProto(s)})
return unmapError(err)
}
func (c *Client) GetSource(ctx context.Context, path string) (*source.Source, error) {
r, err := c.client.GetSource(ctx, &pb.GetSourceRequest{Path: path})
if err != nil {
return nil, unmapError(err)
}
if !r.Found {
return nil, nil
}
v := sourceValue(r.Source)
return &v, nil
}
func (c *Client) ListSources(ctx context.Context) ([]source.Source, error) {
r, err := c.client.ListSources(ctx, &pb.ListSourcesRequest{})
if err != nil {
return nil, unmapError(err)
}
return mapValues(r.Sources, sourceValue), nil
}
func (c *Client) SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error {
_, err := c.client.SetSourceSigning(ctx, &pb.SetSourceSigningRequest{Path: path, From: string(from), To: string(to)})
return unmapError(err)
}
func (c *Client) SetSourceSecret(ctx context.Context, path, secret string) error {
_, err := c.client.SetSourceSecret(ctx, &pb.SetSourceSecretRequest{Path: path, Secret: secret})
return unmapError(err)
}
// Dispatch
func (c *Client) ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error) {
@@ -384,14 +384,14 @@ func TestStateStoreConformance(t *testing.T) {
// ErrAlreadyDispatched.
bindingID, err := ec.InsertBinding(ctx, binding.Binding{
Name: "b1", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
Workflow: "implement",
})
if err != nil || bindingID == "" {
t.Fatalf("InsertBinding: %v %v", bindingID, err)
}
_, err = ec.InsertBinding(ctx, binding.Binding{
Name: "b2", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
Workflow: "implement",
})
if !errors.Is(err, store.ErrBindingOverlap) {
t.Fatalf("InsertBinding overlap = %v, want ErrBindingOverlap", err)
@@ -9,6 +9,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/store"
)
@@ -81,6 +82,9 @@ func TestUnmapErrorSentinelFidelity(t *testing.T) {
{name: "binding overlap", store: store.ErrBindingOverlap, rehyd: store.ErrBindingOverlap},
{name: "binding transition", store: store.ErrBindingTransition, rehyd: store.ErrBindingTransition},
{name: "already dispatched", store: store.ErrAlreadyDispatched, rehyd: store.ErrAlreadyDispatched},
{name: "source not found", store: storecontract.ErrSourceNotFound, rehyd: storecontract.ErrSourceNotFound},
{name: "source path taken", store: storecontract.ErrSourcePathTaken, rehyd: storecontract.ErrSourcePathTaken},
{name: "source signing stale", store: storecontract.ErrSourceSigningStale, rehyd: storecontract.ErrSourceSigningStale},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -20,6 +20,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/logging"
)
@@ -35,6 +36,7 @@ var (
errApplyStatusUnavailable = status.Error(codes.Unavailable, "apply status store unavailable")
errMappingUnavailable = status.Error(codes.Unavailable, "mapping store unavailable")
errBindingUnavailable = status.Error(codes.Unavailable, "binding store unavailable")
errSourceUnavailable = status.Error(codes.Unavailable, "source store unavailable")
errBindingDispatchUnavailable = status.Error(codes.Unavailable, "binding dispatcher unavailable")
errBindingTaskCreatorUnavailable = status.Error(codes.Unavailable, "binding task creator unavailable")
errPlaybookDispatcherUnavailable = status.Error(codes.Unavailable, "playbook dispatcher unavailable")
@@ -78,6 +80,7 @@ type Deps struct {
Mappings storecontract.MappingStore
EventTypes storecontract.EventTypeStore
Bindings storecontract.BindingStore
Sources storecontract.SourceStore
BindingDispatcher storecontract.BindingDispatcher
BindingTaskCreator storecontract.BindingTaskCreator
// PlaybookDispatcher is the side-effecting-action idempotency ledger
@@ -647,6 +650,75 @@ func (s *server) ApproveBinding(ctx context.Context, r *pb.ApproveBindingRequest
return &pb.ApproveBindingResponse{}, nil
}
// Source
func (s *server) sources() (storecontract.SourceStore, error) {
if s.deps.Sources == nil {
return nil, errSourceUnavailable
}
return s.deps.Sources, nil
}
func (s *server) InsertSource(ctx context.Context, r *pb.InsertSourceRequest) (*pb.InsertSourceResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
if err := ss.InsertSource(ctx, sourceValue(r.Source)); err != nil {
return nil, s.logErr("InsertSource", err)
}
return &pb.InsertSourceResponse{}, nil
}
func (s *server) GetSource(ctx context.Context, r *pb.GetSourceRequest) (*pb.GetSourceResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
src, err := ss.GetSource(ctx, r.Path)
if err != nil {
return nil, s.logErr("GetSource", err)
}
if src == nil {
return &pb.GetSourceResponse{}, nil
}
return &pb.GetSourceResponse{Source: sourceProto(*src), Found: true}, nil
}
func (s *server) ListSources(ctx context.Context, _ *pb.ListSourcesRequest) (*pb.ListSourcesResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
list, err := ss.ListSources(ctx)
if err != nil {
return nil, s.logErr("ListSources", err)
}
return &pb.ListSourcesResponse{Sources: mapValues(list, sourceProto)}, nil
}
func (s *server) SetSourceSigning(ctx context.Context, r *pb.SetSourceSigningRequest) (*pb.SetSourceSigningResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
if err := ss.SetSourceSigning(ctx, r.Path, source.Signing(r.From), source.Signing(r.To)); err != nil {
return nil, s.logErr("SetSourceSigning", err)
}
return &pb.SetSourceSigningResponse{}, nil
}
func (s *server) SetSourceSecret(ctx context.Context, r *pb.SetSourceSecretRequest) (*pb.SetSourceSecretResponse, error) {
ss, err := s.sources()
if err != nil {
return nil, err
}
if err := ss.SetSourceSecret(ctx, r.Path, r.Secret); err != nil {
return nil, s.logErr("SetSourceSecret", err)
}
return &pb.SetSourceSecretResponse{}, nil
}
// Dispatch
func (s *server) ArmedBindingsForSource(ctx context.Context, r *pb.ArmedBindingsForSourceRequest) (*pb.ArmedBindingsForSourceResponse, error) {
@@ -0,0 +1,147 @@
package staterpc
import (
"context"
"errors"
"net"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// memSources is an in-memory SourceStore with the Postgres store's error
// contract, so the wire test checks the adapter rather than a database.
type memSources map[string]source.Source
func (m memSources) InsertSource(_ context.Context, s source.Source) error {
if _, ok := m[s.Path]; ok {
return storecontract.ErrSourcePathTaken
}
m[s.Path] = s
return nil
}
func (m memSources) GetSource(_ context.Context, path string) (*source.Source, error) {
s, ok := m[path]
if !ok {
return nil, nil
}
return &s, nil
}
func (m memSources) ListSources(context.Context) ([]source.Source, error) {
out := make([]source.Source, 0, len(m))
for _, s := range m {
out = append(out, s)
}
return out, nil
}
func (m memSources) SetSourceSigning(_ context.Context, path string, from, to source.Signing) error {
s, ok := m[path]
switch {
case !ok:
return storecontract.ErrSourceNotFound
case s.Signing != from:
return storecontract.ErrSourceSigningStale
}
s.Signing = to
m[path] = s
return nil
}
func (m memSources) SetSourceSecret(_ context.Context, path, secret string) error {
s, ok := m[path]
if !ok {
return storecontract.ErrSourceNotFound
}
s.Secret = secret
m[path] = s
return nil
}
func remoteSources(t *testing.T, sources storecontract.SourceStore) *Client {
t.Helper()
listener := bufconn.Listen(1 << 20)
server := grpc.NewServer()
RegisterServer(server, Deps{Sources: sources})
go func() { _ = server.Serve(listener) }()
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
conn, err := grpc.NewClient("passthrough:///state",
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
return NewClient(conn)
}
func TestSourceStoreOverTheWire(t *testing.T) {
ctx := t.Context()
c := remoteSources(t, memSources{})
stamp := time.Date(2026, 9, 24, 9, 0, 0, 0, time.UTC)
in := source.Source{Path: "sentry", Signing: source.SigningSigned, Secret: "k", CreatedAt: stamp, UpdatedAt: stamp}
if err := c.InsertSource(ctx, in); err != nil {
t.Fatalf("InsertSource() error = %v", err)
}
got, err := c.GetSource(ctx, "sentry")
if err != nil || got == nil || *got != in {
t.Fatalf("GetSource() = %+v, %v; want %+v", got, err, in)
}
if missing, err := c.GetSource(ctx, "nope"); err != nil || missing != nil {
t.Fatalf("GetSource(unknown) = %+v, %v; want nil, nil", missing, err)
}
if err := c.SetSourceSigning(ctx, "sentry", source.SigningSigned, source.SigningUnsignedPending); err != nil {
t.Fatalf("SetSourceSigning() error = %v", err)
}
if err := c.SetSourceSecret(ctx, "sentry", "k2"); err != nil {
t.Fatalf("SetSourceSecret() error = %v", err)
}
list, err := c.ListSources(ctx)
if err != nil || len(list) != 1 || list[0].Signing != source.SigningUnsignedPending || list[0].Secret != "k2" {
t.Fatalf("ListSources() = %+v, %v", list, err)
}
errs := []struct {
name string
call func() error
want error
}{
{"taken path", func() error { return c.InsertSource(ctx, in) }, storecontract.ErrSourcePathTaken},
{"stale signing", func() error {
return c.SetSourceSigning(ctx, "sentry", source.SigningSigned, source.SigningUnsigned)
}, storecontract.ErrSourceSigningStale},
{"unknown path", func() error { return c.SetSourceSecret(ctx, "nope", "k") }, storecontract.ErrSourceNotFound},
}
for _, tt := range errs {
t.Run(tt.name, func(t *testing.T) {
if err := tt.call(); !errors.Is(err, tt.want) {
t.Fatalf("error = %v, want %v", err, tt.want)
}
})
}
}
func TestSourceStoreUnavailableWithoutBackend(t *testing.T) {
c := remoteSources(t, nil)
_, err := c.ListSources(t.Context())
if status.Code(err) != codes.Unavailable {
t.Fatalf("ListSources() with no backend = %v, want Unavailable", err)
}
}
func TestCapturedEventUnsignedSurvivesTheWire(t *testing.T) {
in := storecontract.CapturedEvent{ID: "c", Source: "fw", Unsigned: true}
if got := capturedEventValue(capturedEventProto(in)); got != in {
t.Fatalf("round trip = %+v, want %+v", got, in)
}
}
@@ -97,14 +97,14 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) {
// public draft -> pending_approval -> armed lifecycle.
id, err := admin.InsertBinding(ctx, binding.Binding{
Name: "large binding", Matcher: binding.Matcher{Source: "large"},
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
MappingID: mappingID, Workflow: "implement",
})
if err != nil {
t.Fatal(err)
}
if err := admin.UpdateBinding(ctx, binding.Binding{
ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"},
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
MappingID: mappingID, Workflow: "implement",
}); err != nil {
t.Fatal(err)
}
+60 -36
View File
@@ -15,6 +15,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/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
@@ -151,6 +152,7 @@ func capturedEventProto(c storecontract.CapturedEvent) *pb.CapturedEvent {
Id: c.ID, ReceivedAt: timestamp(c.ReceivedAt), Source: c.Source,
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType,
Unsigned: c.Unsigned,
}
}
@@ -162,6 +164,24 @@ func capturedEventValue(c *pb.CapturedEvent) storecontract.CapturedEvent {
ID: c.Id, ReceivedAt: timeValue(c.ReceivedAt), Source: c.Source,
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType,
Unsigned: c.Unsigned,
}
}
func sourceProto(s source.Source) *pb.Source {
return &pb.Source{
Path: s.Path, Signing: string(s.Signing), Secret: s.Secret,
CreatedAt: timestamp(s.CreatedAt), UpdatedAt: timestamp(s.UpdatedAt),
}
}
func sourceValue(s *pb.Source) source.Source {
if s == nil {
return source.Source{}
}
return source.Source{
Path: s.Path, Signing: source.Signing(s.Signing), Secret: s.Secret,
CreatedAt: timeValue(s.CreatedAt), UpdatedAt: timeValue(s.UpdatedAt),
}
}
@@ -199,7 +219,7 @@ func bindingProto(b binding.Binding) *pb.Binding {
return &pb.Binding{
Id: b.ID, Name: b.Name, Matcher: &pb.BindingMatcher{Source: b.Matcher.Source},
MappingId: b.MappingID, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
Version: int64(b.Version), Status: string(b.Status), Secret: b.Secret,
Version: int64(b.Version), Status: string(b.Status),
CreatedAt: timestamp(b.CreatedAt), UpdatedAt: timestamp(b.UpdatedAt),
}
}
@@ -215,7 +235,7 @@ func bindingValue(b *pb.Binding) binding.Binding {
return binding.Binding{
ID: b.Id, Name: b.Name, Matcher: binding.Matcher{Source: source},
MappingID: b.MappingId, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
Version: int(b.Version), Status: binding.Status(b.Status), Secret: b.Secret,
Version: int(b.Version), Status: binding.Status(b.Status),
CreatedAt: timeValue(b.CreatedAt), UpdatedAt: timeValue(b.UpdatedAt),
}
}
@@ -274,6 +294,9 @@ const (
msgBindingOverlap = "binding overlap"
msgBindingTransition = "binding transition rejected"
msgAlreadyDispatched = "already dispatched"
msgSourceNotFound = "source not found"
msgSourcePathTaken = "source path taken"
msgSourceSigning = "source signing stale"
msgInternal = "state store: internal error"
// msgTaskLogsUnavailable is the public phrase for "this service has no
// task-log reader". It is a wire contract like the sentinels above: the
@@ -306,28 +329,12 @@ func mapError(err error) error {
if errors.Is(err, context.DeadlineExceeded) {
return status.Error(codes.DeadlineExceeded, context.DeadlineExceeded.Error())
}
switch {
case errors.Is(err, storecontract.ErrStaleTransition):
return status.Error(codes.FailedPrecondition, msgStaleTransition)
case errors.Is(err, storecontract.ErrBindingNotFound):
return status.Error(codes.NotFound, msgBindingNotFound)
case errors.Is(err, storecontract.ErrMappingNotFound):
return status.Error(codes.NotFound, msgMappingNotFound)
case errors.Is(err, storecontract.ErrEventTypeNotFound):
return status.Error(codes.NotFound, msgEventTypeNotFound)
case errors.Is(err, eventtype.ErrOverlap):
return status.Error(codes.FailedPrecondition, msgEventTypeOverlap)
case errors.Is(err, eventtype.ErrInvalid):
return status.Error(codes.InvalidArgument, msgEventTypeInvalid)
case errors.Is(err, storecontract.ErrBindingOverlap):
return status.Error(codes.FailedPrecondition, msgBindingOverlap)
case errors.Is(err, storecontract.ErrBindingTransition):
return status.Error(codes.FailedPrecondition, msgBindingTransition)
case errors.Is(err, storecontract.ErrAlreadyDispatched):
return status.Error(codes.AlreadyExists, msgAlreadyDispatched)
default:
return status.Error(codes.Internal, msgInternal)
for _, w := range wireErrors {
if errors.Is(err, w.sentinel) {
return status.Error(w.code, w.message)
}
}
return status.Error(codes.Internal, msgInternal)
}
// unmapError rehydrates a gRPC status error back to the store sentinel it
@@ -382,21 +389,38 @@ type wireStatus struct {
message string
}
// wireSentinels is the (code, canonical message) to sentinel table
// sentinelForStatus reads.
var wireSentinels = map[wireStatus]error{
{codes.FailedPrecondition, msgStaleTransition}: storecontract.ErrStaleTransition,
{codes.FailedPrecondition, msgBindingOverlap}: storecontract.ErrBindingOverlap,
{codes.FailedPrecondition, msgBindingTransition}: storecontract.ErrBindingTransition,
{codes.FailedPrecondition, msgEventTypeOverlap}: eventtype.ErrOverlap,
{codes.InvalidArgument, msgEventTypeInvalid}: eventtype.ErrInvalid,
{codes.NotFound, msgBindingNotFound}: storecontract.ErrBindingNotFound,
{codes.NotFound, msgMappingNotFound}: storecontract.ErrMappingNotFound,
{codes.NotFound, msgEventTypeNotFound}: storecontract.ErrEventTypeNotFound,
{codes.AlreadyExists, msgAlreadyDispatched}: storecontract.ErrAlreadyDispatched,
{codes.Unavailable, msgTaskLogsUnavailable}: logging.ErrTaskLogsUnavailable,
// wireErrors pairs each sentinel with its canonical (code, message). mapError
// reads it forward and sentinelForStatus backward, so the two directions
// cannot drift.
var wireErrors = []struct {
sentinel error
code codes.Code
message string
}{
{storecontract.ErrStaleTransition, codes.FailedPrecondition, msgStaleTransition},
{storecontract.ErrBindingOverlap, codes.FailedPrecondition, msgBindingOverlap},
{storecontract.ErrBindingTransition, codes.FailedPrecondition, msgBindingTransition},
{storecontract.ErrSourceSigningStale, codes.FailedPrecondition, msgSourceSigning},
{eventtype.ErrOverlap, codes.FailedPrecondition, msgEventTypeOverlap},
{eventtype.ErrInvalid, codes.InvalidArgument, msgEventTypeInvalid},
{storecontract.ErrBindingNotFound, codes.NotFound, msgBindingNotFound},
{storecontract.ErrMappingNotFound, codes.NotFound, msgMappingNotFound},
{storecontract.ErrEventTypeNotFound, codes.NotFound, msgEventTypeNotFound},
{storecontract.ErrSourceNotFound, codes.NotFound, msgSourceNotFound},
{storecontract.ErrAlreadyDispatched, codes.AlreadyExists, msgAlreadyDispatched},
{storecontract.ErrSourcePathTaken, codes.AlreadyExists, msgSourcePathTaken},
{logging.ErrTaskLogsUnavailable, codes.Unavailable, msgTaskLogsUnavailable},
}
// wireSentinels indexes wireErrors by (code, canonical message).
var wireSentinels = func() map[wireStatus]error {
m := make(map[wireStatus]error, len(wireErrors))
for _, w := range wireErrors {
m[wireStatus{w.code, w.message}] = w.sentinel
}
return m
}()
// configSnapshotProto and configSnapshotValue carry the dashboard's
// configuration projection. document crosses as bytes, unread by either side
// of this hop: the store holds it and the page renders it.