feat(capture): store unbound webhook events, retention-bounded
Adds POST /webhooks/capture/{source}: an unauthenticated endpoint (mounted
alongside /healthz, bypassing dashboard token auth by design) that persists
any inbound webhook archie has no binding for yet, so it can be inspected
and mapped later (t2db.2/t2db.3).
docs/prds/event-capture-storage.md decides SQLite over NATS JetStream for
storage: NATS is not unconditionally available until 7d5u.2 ships embedded
support, and capture's single-writer/single-reader access pattern doesn't
need JetStream's fan-out/replay machinery anyway.
internal/store/captures.go adds a captured_events table with prune-on-write
(retention age + row-count cap, both configurable). The HTTP handler applies
webhookguard redaction before persisting, and enforces two more independent
disk-bound mechanics before that: a per-request body-size cap and a
per-remote-address rate limit. New [capture] config section with documented
defaults; all fields optional, capture is on by default.
Adversarial review (manual, after the usual fresh-subagent pass hit a
session API limit mid-run) caught and fixed three real defects before this
landed, each with a regression test confirmed to fail against the pre-fix
code:
- the body-size cap silently no-op'd when CaptureMaxBodyBytes was left
unset, the one bound that limits a single payload's size rather than row
count or write rate
- the rate limiter was keyed by the request's own source path segment --
unregistered and attacker-chosen by design for this endpoint, violating
webhookguard.RateLimiter's documented bounded-key-space assumption and
letting a sender bypass the limit by rotating the segment; rekeyed to
remote address
- the retention prune compared time.RFC3339Nano strings, whose trimmed
variable-width fractional seconds break lexicographic ordering within the
same second; switched to fixed-width RFC3339
Closes archie-core-t2db.1.
This commit is contained in:
1 parent
3d74f0136e
commit
101c133239
17 files changed
+1066
-3
No files matched your search
@@ -0,0 +1,102 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
// handleCapture accepts an unbound inbound webhook POST and persists it --
|
||||
// no HMAC verification (there is by design no secret registered yet for a
|
||||
// source nobody has configured), no workflow binding, just "something
|
||||
// arrived." See docs/prds/event-capture-storage.md. Mounted on the bypass
|
||||
// mux alongside /healthz: capture must accept unauthenticated senders, so it
|
||||
// cannot sit behind requireToken.
|
||||
func (s *Server) handleCapture(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Captures == nil {
|
||||
http.Error(w, "capture not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
source := r.PathValue("source")
|
||||
|
||||
// webhookguard.RateLimiter's bucket map assumes a bounded, operator-
|
||||
// registered key space (see its doc comment) -- it is never evicted, and
|
||||
// a fresh key starts with a full burst allowance. source is an
|
||||
// unregistered, attacker-chosen URL segment by design (this endpoint
|
||||
// exists to capture senders archie has no registration for yet), so
|
||||
// keying on it would let a single attacker rotate a new "source" on
|
||||
// every request to bypass the limit entirely and grow the bucket map
|
||||
// without bound. Remote address is the bounded identity available here.
|
||||
if s.CaptureLimiter != nil && !s.CaptureLimiter.Allow(remoteAddrHost(r)) {
|
||||
http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, captureMaxBodyBytesOrFallback(s.CaptureMaxBodyBytes))
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
// The only realistic cause here is MaxBytesReader tripping; any other
|
||||
// read failure also means there is no usable body to capture.
|
||||
http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
}
|
||||
|
||||
headers, _ := json.Marshal(r.Header)
|
||||
redactedHeaders, err := webhookguard.RedactPayload(headers)
|
||||
if err != nil {
|
||||
redactedHeaders = headers
|
||||
}
|
||||
// A body that isn't JSON has no key-value structure for the heuristic to
|
||||
// match against, so there is nothing to redact -- store it as received
|
||||
// rather than dropping or mangling it. Best-effort, per
|
||||
// docs/prds/webhook-intake-security.md point 5.
|
||||
redactedBody, err := webhookguard.RedactPayload(body)
|
||||
if err != nil {
|
||||
redactedBody = body
|
||||
}
|
||||
|
||||
_, err = s.Captures.InsertCapture(r.Context(), store.CapturedEvent{
|
||||
Source: source,
|
||||
RemoteAddr: r.RemoteAddr,
|
||||
ContentType: r.Header.Get("Content-Type"),
|
||||
Headers: string(redactedHeaders),
|
||||
Body: string(redactedBody),
|
||||
}, s.CaptureRetention, s.CaptureMaxEvents)
|
||||
if err != nil {
|
||||
s.Log.Error("capture insert", "err", err, "source", source)
|
||||
http.Error(w, "capture failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}
|
||||
|
||||
// fallbackCaptureMaxBodyBytes bounds a capture body when CaptureMaxBodyBytes
|
||||
// is left unset (zero). The size cap is the only one of the three disk-bound
|
||||
// mechanics in docs/prds/event-capture-storage.md that limits a SINGLE
|
||||
// payload rather than total row count or write rate -- a table pruned to
|
||||
// maxEvents rows still holds one arbitrarily large row if nothing ever
|
||||
// bounded that row's size, so this must never be skippable by a missing
|
||||
// wiring value the way the rate limiter (best-effort, not disk-bound-load-
|
||||
// bearing on its own) is allowed to be.
|
||||
const fallbackCaptureMaxBodyBytes = 256 * 1024
|
||||
|
||||
func captureMaxBodyBytesOrFallback(configured int64) int64 {
|
||||
if configured > 0 {
|
||||
return configured
|
||||
}
|
||||
return fallbackCaptureMaxBodyBytes
|
||||
}
|
||||
|
||||
// remoteAddrHost strips the port from r.RemoteAddr for use as a rate-limit
|
||||
// key, falling back to the raw value if it isn't a host:port pair.
|
||||
func remoteAddrHost(r *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
)
|
||||
|
||||
// captureTestServer builds a Server whose Captures field points at the same
|
||||
// concrete *store.Store as Store, so tests can assert on persisted rows
|
||||
// through the narrower CaptureStore interface -- Server.Store's static type
|
||||
// (store.TaskStore) does not expose InsertCapture/ListCaptures.
|
||||
func captureTestServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
s, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return &Server{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Captures: s,
|
||||
CaptureMaxBodyBytes: 1024,
|
||||
CaptureRetention: 7 * 24 * time.Hour,
|
||||
CaptureMaxEvents: 100,
|
||||
CaptureLimiter: webhookguard.NewRateLimiter(1000, 1000, time.Now),
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureStoresRedactedBody(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
body := `{"action":"opened","sender":{"token":"shh-secret"}}`
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
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.Captures.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))
|
||||
}
|
||||
c := got[0]
|
||||
if c.Source != "github" {
|
||||
t.Errorf("Source = %q, want %q", c.Source, "github")
|
||||
}
|
||||
if c.ContentType != "application/json" {
|
||||
t.Errorf("ContentType = %q, want application/json", c.ContentType)
|
||||
}
|
||||
if strings.Contains(c.Body, "shh-secret") {
|
||||
t.Errorf("Body = %q, want the token value redacted", c.Body)
|
||||
}
|
||||
if !strings.Contains(c.Body, `"action":"opened"`) {
|
||||
t.Errorf("Body = %q, want the non-sensitive field preserved", c.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureAcceptsUnauthenticatedByDesign(t *testing.T) {
|
||||
// Capture must accept requests with no HMAC secret configured -- that is
|
||||
// the entire point of an unbound capture endpoint. This test documents
|
||||
// that the handler does not gate on any signature header.
|
||||
srv := captureTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/unknown-source", 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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureNonJSONBodyStoredUnredacted(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/plain", strings.NewReader("not json"))
|
||||
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.Captures.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Body != "not json" {
|
||||
t.Fatalf("captured = %+v, want raw body preserved when it is not JSON", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureRejectsOversizedBody(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.CaptureMaxBodyBytes = 8
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{"far":"too big for the cap"}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusRequestEntityTooLarge)
|
||||
}
|
||||
got, err := srv.Captures.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("captured rows = %d, want 0 (oversized body must never be persisted)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureEnforcesBodyCapEvenWhenUnconfigured pins that a caller
|
||||
// that forgets to set CaptureMaxBodyBytes (zero value) still gets a bound --
|
||||
// this is the one disk-bound mechanic that limits a single payload's size
|
||||
// rather than row count or write rate, so it must never silently no-op.
|
||||
func TestHandleCaptureEnforcesBodyCapEvenWhenUnconfigured(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.CaptureMaxBodyBytes = 0
|
||||
|
||||
oversized := strings.Repeat("x", fallbackCaptureMaxBodyBytes+1)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(oversized))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("status = %d, want %d (CaptureMaxBodyBytes=0 must still enforce the fallback cap)", w.Code, http.StatusRequestEntityTooLarge)
|
||||
}
|
||||
got, err := srv.Captures.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("captured rows = %d, want 0", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureRateLimitsPerRemoteAddr(t *testing.T) {
|
||||
// Deliberately NOT keyed by the source path segment: source is an
|
||||
// unregistered, attacker-chosen string for this endpoint (see
|
||||
// handleCapture and docs/prds/event-capture-storage.md), so both
|
||||
// requests below use the SAME source and DIFFERENT RemoteAddr to prove
|
||||
// the limiter is keyed on the sender's address, not the segment.
|
||||
srv := captureTestServer(t)
|
||||
srv.CaptureLimiter = webhookguard.NewRateLimiter(0, 1, time.Now) // burst 1, no refill
|
||||
|
||||
req := func(remoteAddr string) *http.Request {
|
||||
r := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
r.RemoteAddr = remoteAddr
|
||||
return r
|
||||
}
|
||||
|
||||
w1 := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w1, req("203.0.113.5:11111"))
|
||||
if w1.Code != http.StatusAccepted {
|
||||
t.Fatalf("first request status = %d, want %d", w1.Code, http.StatusAccepted)
|
||||
}
|
||||
|
||||
w2 := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w2, req("203.0.113.5:22222"))
|
||||
if w2.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("second request (same host, different port) status = %d, want %d", w2.Code, http.StatusTooManyRequests)
|
||||
}
|
||||
|
||||
// A different remote address, same source segment, must not be affected
|
||||
// by the exhausted budget above.
|
||||
w3 := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w3, req("198.51.100.9:33333"))
|
||||
if w3.Code != http.StatusAccepted {
|
||||
t.Fatalf("other-remote-addr request status = %d, want %d", w3.Code, http.StatusAccepted)
|
||||
}
|
||||
|
||||
got, err := srv.Captures.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("captured rows = %d, want 2 (the rate-limited request must not be persisted)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureIgnoresGetMethod(t *testing.T) {
|
||||
// The route is registered "POST /webhooks/capture/{source}"; a GET does
|
||||
// not match it and falls through to the dashboard's own routing, same as
|
||||
// every other POST-only API route in this server -- it must not be
|
||||
// treated as a capture.
|
||||
srv := captureTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/webhooks/capture/github", nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code == http.StatusAccepted {
|
||||
t.Fatalf("status = %d, a GET must never be accepted as a capture", w.Code)
|
||||
}
|
||||
got, err := srv.Captures.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("captured rows = %d, want 0 (GET must not persist a capture)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureWithoutCapturesConfiguredIs503(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d when Captures is nil", w.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCaptureBypassesTokenAuth(t *testing.T) {
|
||||
// The capture endpoint must accept unauthenticated senders even when the
|
||||
// dashboard itself is token-gated -- mirrors /healthz's precedent.
|
||||
srv := captureTestServer(t)
|
||||
srv.Token = "dashboard-secret"
|
||||
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 (capture must bypass requireToken)", w.Code, http.StatusAccepted)
|
||||
}
|
||||
}
|
||||
|
||||
// captureInsertErrorStore forces InsertCapture to fail so the handler's
|
||||
// error path is exercised without relying on a real storage failure.
|
||||
type captureInsertErrorStore struct {
|
||||
store.CaptureStore
|
||||
}
|
||||
|
||||
func (captureInsertErrorStore) InsertCapture(context.Context, store.CapturedEvent, time.Duration, int) (int64, error) {
|
||||
return 0, errors.New("boom")
|
||||
}
|
||||
|
||||
func TestHandleCaptureStorageFailureIs500(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.Captures = captureInsertErrorStore{}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/memory"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
"github.com/samcharles93/archie-core/ui"
|
||||
)
|
||||
|
||||
@@ -128,6 +129,26 @@ type Server struct {
|
||||
// seam so the Stop action cancels work before parking its task record.
|
||||
TaskStopper TaskStopper
|
||||
|
||||
// Captures persists unbound webhook captures (docs/prds/event-capture-storage.md).
|
||||
// Optional: nil makes POST /webhooks/capture/{source} answer 503 rather
|
||||
// than the dashboard failing to start -- capture is a precondition for
|
||||
// the no-code playbook epic, not a hard dependency of the dashboard.
|
||||
Captures store.CaptureStore
|
||||
// CaptureLimiter is the per-remote-address token bucket applied before a
|
||||
// capture request's body is read (keyed by remote address, not the
|
||||
// unregistered/attacker-chosen source path segment -- see
|
||||
// handleCapture). Optional: nil disables rate limiting (every request is
|
||||
// allowed), which composition never actually does in production -- it
|
||||
// is nil only in tests that don't exercise this path.
|
||||
CaptureLimiter *webhookguard.RateLimiter
|
||||
// CaptureRetention and CaptureMaxEvents are passed straight through to
|
||||
// InsertCapture's prune-on-write bounds. See config.CaptureConfig.
|
||||
CaptureRetention time.Duration
|
||||
CaptureMaxEvents int
|
||||
// CaptureMaxBodyBytes rejects (413) a capture POST body larger than
|
||||
// this via http.MaxBytesReader, before redaction or storage sees it.
|
||||
CaptureMaxBodyBytes int64
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[chan events.Event]struct{}
|
||||
}
|
||||
@@ -211,6 +232,7 @@ func (s *Server) Handler() http.Handler {
|
||||
|
||||
top := http.NewServeMux()
|
||||
top.HandleFunc("GET /healthz", s.handleHealthz)
|
||||
top.HandleFunc("POST /webhooks/capture/{source}", s.handleCapture)
|
||||
top.Handle("/", s.requireToken(mux))
|
||||
return top
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user