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:
sam committed 2026-08-22 04:51:25 +10:00
1 parent 3d74f0136e
commit 101c133239
17 files changed
+1066 -3

No files matched your search

+27
View File
@@ -385,6 +385,7 @@ type Config struct {
NATS NATSConfig `toml:"nats" yaml:"nats"`
Containers ContainerConfig `toml:"containers" yaml:"containers"`
Chat ChatConfig `toml:"chat" yaml:"chat"`
Capture CaptureConfig `toml:"capture" yaml:"capture"`
// Memory holds memory provider configuration (from config.memory.yaml).
Memory MemoryConfig `toml:"memory" yaml:"memory"`
@@ -581,6 +582,32 @@ type NATSConfig struct {
TokenEnv string `toml:"token_env" yaml:"token_env"`
}
// CaptureConfig configures the unbound webhook capture endpoint
// (docs/prds/event-capture-storage.md). All fields have defaults; an empty
// [capture] section is valid and produces them -- capture is on by default.
type CaptureConfig struct {
// Retention is how long a captured event is kept before prune-on-write
// deletes it. Zero or absent means the 7-day default; a positive value
// configured explicitly is used as-is; a deployment that wants no age
// bound sets it very large rather than using a magic "0 = unlimited"
// spelling, since 0 already means "use the default" here.
Retention Duration `toml:"retention" yaml:"retention"`
// MaxEvents caps the table at this many newest rows; older rows are
// pruned on every insert regardless of age. Zero means the 5000 default.
MaxEvents int `toml:"max_events" yaml:"max_events"`
// MaxBodyBytes rejects (413) any single POST body larger than this
// before it is read into memory. Zero means the 256 KiB default.
MaxBodyBytes int `toml:"max_body_bytes" yaml:"max_body_bytes"`
// RatePerSecond and RateBurst configure the per-remote-address token
// bucket (webhookguard.RateLimiter) applied before a request's body is
// read. Keyed by remote address, not the source path segment, since
// that segment is unregistered and attacker-chosen by design -- see
// docs/prds/event-capture-storage.md's disk-bound mechanics. Zero means
// the defaults (1 req/s, burst 5).
RatePerSecond float64 `toml:"rate_per_second" yaml:"rate_per_second"`
RateBurst int `toml:"rate_burst" yaml:"rate_burst"`
}
// ContainerConfig configures Docker sandbox execution of archie-agent.
type ContainerConfig struct {
// Enabled activates container execution. Requires agent.mode = "nats".
@@ -39,6 +39,15 @@ const (
// above trims it further. Generous enough for a documentation page,
// small enough that a large download cannot occupy the daemon.
defaultWebFetchMaxBytes = 2_000_000
// Capture defaults, per docs/prds/event-capture-storage.md's disk-bound
// mechanics: retention + row cap + per-request size cap + per-source
// rate limit, composed.
defaultCaptureRetention = 7 * 24 * time.Hour
defaultCaptureMaxEvents = 5000
defaultCaptureMaxBodyBytes = 256 * 1024
defaultCaptureRatePerSecond = 1.0
defaultCaptureRateBurst = 5
)
// applyDefaults fills in every absent value. It never reports an error and
@@ -58,6 +67,27 @@ func (l *Loader) applyDefaults(cfg *config.Config) {
applyIdentityDefaults(cfg)
applyContainerDefaults(cfg)
applyToolPolicyDefaults(cfg)
applyCaptureDefaults(cfg)
}
// applyCaptureDefaults fills the webhook capture endpoint's settings. See
// [config.CaptureConfig].
func applyCaptureDefaults(cfg *config.Config) {
if cfg.Capture.Retention == 0 {
cfg.Capture.Retention = config.Duration(defaultCaptureRetention)
}
if cfg.Capture.MaxEvents == 0 {
cfg.Capture.MaxEvents = defaultCaptureMaxEvents
}
if cfg.Capture.MaxBodyBytes == 0 {
cfg.Capture.MaxBodyBytes = defaultCaptureMaxBodyBytes
}
if cfg.Capture.RatePerSecond == 0 {
cfg.Capture.RatePerSecond = defaultCaptureRatePerSecond
}
if cfg.Capture.RateBurst == 0 {
cfg.Capture.RateBurst = defaultCaptureRateBurst
}
}
// applyToolPolicyDefaults fills the tool result limits.
@@ -0,0 +1,58 @@
package configuration
import (
"testing"
"time"
"github.com/samcharles93/archie-core/internal/config"
)
func TestApplyCaptureDefaultsFillsZeroValues(t *testing.T) {
cfg := &config.Config{}
applyCaptureDefaults(cfg)
if got, want := cfg.Capture.Retention.Std(), defaultCaptureRetention; got != want {
t.Errorf("Capture.Retention = %v, want %v", got, want)
}
if cfg.Capture.MaxEvents != defaultCaptureMaxEvents {
t.Errorf("Capture.MaxEvents = %d, want %d", cfg.Capture.MaxEvents, defaultCaptureMaxEvents)
}
if cfg.Capture.MaxBodyBytes != defaultCaptureMaxBodyBytes {
t.Errorf("Capture.MaxBodyBytes = %d, want %d", cfg.Capture.MaxBodyBytes, defaultCaptureMaxBodyBytes)
}
if cfg.Capture.RatePerSecond != defaultCaptureRatePerSecond {
t.Errorf("Capture.RatePerSecond = %v, want %v", cfg.Capture.RatePerSecond, defaultCaptureRatePerSecond)
}
if cfg.Capture.RateBurst != defaultCaptureRateBurst {
t.Errorf("Capture.RateBurst = %d, want %d", cfg.Capture.RateBurst, defaultCaptureRateBurst)
}
}
func TestApplyCaptureDefaultsLeavesExplicitValuesAlone(t *testing.T) {
cfg := &config.Config{
Capture: config.CaptureConfig{
Retention: config.Duration(24 * time.Hour),
MaxEvents: 42,
MaxBodyBytes: 1024,
RatePerSecond: 2.5,
RateBurst: 9,
},
}
applyCaptureDefaults(cfg)
if cfg.Capture.Retention.Std() != 24*time.Hour {
t.Errorf("Capture.Retention = %v, want unchanged 24h", cfg.Capture.Retention.Std())
}
if cfg.Capture.MaxEvents != 42 {
t.Errorf("Capture.MaxEvents = %d, want unchanged 42", cfg.Capture.MaxEvents)
}
if cfg.Capture.MaxBodyBytes != 1024 {
t.Errorf("Capture.MaxBodyBytes = %d, want unchanged 1024", cfg.Capture.MaxBodyBytes)
}
if cfg.Capture.RatePerSecond != 2.5 {
t.Errorf("Capture.RatePerSecond = %v, want unchanged 2.5", cfg.Capture.RatePerSecond)
}
if cfg.Capture.RateBurst != 9 {
t.Errorf("Capture.RateBurst = %d, want unchanged 9", cfg.Capture.RateBurst)
}
}
@@ -75,7 +75,35 @@ func validate(cfg *config.Config) error {
if err := validatePollInterval(cfg); err != nil {
return err
}
return validateContainers(cfg)
if err := validateContainers(cfg); err != nil {
return err
}
return validateCapture(cfg)
}
// validateCapture rejects negative capture settings. applyDefaults fills
// every zero value with a positive default, so this only fires on an
// explicit negative value -- which would make time.Duration/AddDate math
// and the token-bucket rate limiter behave nonsensically (e.g. a negative
// retention window would prune every row on every insert, including the one
// just written).
func validateCapture(cfg *config.Config) error {
if cfg.Capture.Retention < 0 {
return fmt.Errorf("%w: capture.retention must not be negative", ErrInvalidInput)
}
if cfg.Capture.MaxEvents < 0 {
return fmt.Errorf("%w: capture.max_events must not be negative", ErrInvalidInput)
}
if cfg.Capture.MaxBodyBytes < 0 {
return fmt.Errorf("%w: capture.max_body_bytes must not be negative", ErrInvalidInput)
}
if cfg.Capture.RatePerSecond < 0 {
return fmt.Errorf("%w: capture.rate_per_second must not be negative", ErrInvalidInput)
}
if cfg.Capture.RateBurst < 0 {
return fmt.Errorf("%w: capture.rate_burst must not be negative", ErrInvalidInput)
}
return nil
}
// validatePollInterval rejects a non-positive poll interval.
@@ -139,6 +139,36 @@ func TestValidate_RejectsTheSameProblemsAsLoaderLoad(t *testing.T) {
},
wantErr: true,
},
{
name: "negative capture.retention",
mutate: func(cfg *config.Config) { cfg.Capture.Retention = config.Duration(-time.Hour) },
wantErr: true,
},
{
name: "negative capture.max_events",
mutate: func(cfg *config.Config) { cfg.Capture.MaxEvents = -1 },
wantErr: true,
},
{
name: "negative capture.max_body_bytes",
mutate: func(cfg *config.Config) { cfg.Capture.MaxBodyBytes = -1 },
wantErr: true,
},
{
name: "negative capture.rate_per_second",
mutate: func(cfg *config.Config) { cfg.Capture.RatePerSecond = -1 },
wantErr: true,
},
{
name: "negative capture.rate_burst",
mutate: func(cfg *config.Config) { cfg.Capture.RateBurst = -1 },
wantErr: true,
},
{
name: "zero capture fields are valid (defaults fill them)",
mutate: func(cfg *config.Config) {},
wantErr: false,
},
}
for _, tc := range tests {
+140
View File
@@ -0,0 +1,140 @@
package store
import (
"context"
"errors"
"fmt"
"time"
)
const capturesSchema = `
CREATE TABLE IF NOT EXISTS captured_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
received_at TEXT NOT NULL,
source TEXT NOT NULL DEFAULT '',
remote_addr TEXT NOT NULL DEFAULT '',
content_type TEXT NOT NULL DEFAULT '',
headers TEXT NOT NULL DEFAULT '{}',
body TEXT NOT NULL DEFAULT '',
authenticated INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_captured_events_source ON captured_events(source, id);
`
// CapturedEvent is one unbound inbound webhook capture: no workflow binding,
// no forge/task association -- just what arrived, from where, and when.
// See docs/prds/event-capture-storage.md.
type CapturedEvent struct {
ID int64 `json:"id"`
ReceivedAt time.Time `json:"received_at"`
Source string `json:"source"`
RemoteAddr string `json:"remote_addr"`
ContentType string `json:"content_type"`
// Headers and Body are redacted (webhookguard.RedactPayload) before
// they ever reach InsertCapture; the store persists what it is given.
Headers string `json:"headers"`
Body string `json:"body"`
Authenticated bool `json:"authenticated"`
}
// captureTimeLayout is fixed-width (unlike time.RFC3339Nano, whose
// fractional-seconds field is trimmed of trailing zeros and omitted
// entirely when zero). A variable-width fractional part breaks lexicographic
// string comparison -- "15:04:05Z" (an exact second) sorts AFTER
// "15:04:05.1Z" (0.1s later) because 'Z' > '.', which would make the
// retention prune's `WHERE received_at < ?` unreliable. Second precision is
// enough here: row order already comes from id (autoincrement), and
// retention windows are measured in days, not sub-second intervals.
const captureTimeLayout = time.RFC3339
// InsertCapture persists a captured event and prunes the table in the same
// transaction: rows older than retention (when > 0) and rows beyond the
// newest maxEvents (when > 0) are deleted. Either bound of 0 or less
// disables that prune. See docs/prds/event-capture-storage.md's disk-bound
// mechanics -- this is one of three independent bounds, the other two
// (per-request size cap, per-source rate limit) are enforced by the caller
// before the body ever reaches this method.
func (s *Store) InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (int64, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer func() { _ = tx.Rollback() }()
if c.ReceivedAt.IsZero() {
c.ReceivedAt = time.Now().UTC()
}
res, err := tx.ExecContext(ctx, `
INSERT INTO captured_events (received_at, source, remote_addr, content_type, headers, body, authenticated)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
c.ReceivedAt.UTC().Format(captureTimeLayout), c.Source, c.RemoteAddr,
c.ContentType, c.Headers, c.Body, c.Authenticated)
if err != nil {
return 0, err
}
id, err := res.LastInsertId()
if err != nil {
return 0, err
}
if retention > 0 {
cutoff := time.Now().UTC().Add(-retention).Format(captureTimeLayout)
if _, err := tx.ExecContext(ctx, `DELETE FROM captured_events WHERE received_at < ?`, cutoff); err != nil {
return 0, err
}
}
if maxEvents > 0 {
if _, err := tx.ExecContext(ctx, `
DELETE FROM captured_events WHERE id NOT IN (
SELECT id FROM captured_events ORDER BY id DESC LIMIT ?
)`, maxEvents); err != nil {
return 0, err
}
}
if err := tx.Commit(); err != nil {
return 0, err
}
return id, nil
}
// ListCaptures returns up to limit captured events, newest first.
func (s *Store) ListCaptures(ctx context.Context, limit int) (out []CapturedEvent, retErr error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, received_at, source, remote_addr, content_type, headers, body, authenticated
FROM captured_events ORDER BY id DESC LIMIT ?`, limit)
if err != nil {
return nil, err
}
defer func() { retErr = errors.Join(retErr, rows.Close()) }()
for rows.Next() {
var c CapturedEvent
var receivedAt string
var authenticated int
if err := rows.Scan(&c.ID, &receivedAt, &c.Source, &c.RemoteAddr,
&c.ContentType, &c.Headers, &c.Body, &authenticated); err != nil {
return nil, err
}
parsed, err := parseCaptureTime(receivedAt)
if err != nil {
return nil, err
}
c.ReceivedAt = parsed
c.Authenticated = authenticated != 0
out = append(out, c)
}
return out, rows.Err()
}
func parseCaptureTime(v string) (time.Time, error) {
if v == "" {
return time.Time{}, nil
}
for _, layout := range []string{time.RFC3339Nano, time.RFC3339} {
if parsed, err := time.Parse(layout, v); err == nil {
return parsed.UTC(), nil
}
}
return time.Time{}, fmt.Errorf("store: unrecognised capture timestamp %q", v)
}
+169
View File
@@ -0,0 +1,169 @@
package store
import (
"testing"
"time"
)
func TestInsertCaptureRoundTrips(t *testing.T) {
s := openTest(t)
id, err := s.InsertCapture(t.Context(), CapturedEvent{
Source: "github",
RemoteAddr: "203.0.113.5",
ContentType: "application/json",
Headers: `{"x-hub-signature-256":"[redacted]"}`,
Body: `{"action":"opened"}`,
Authenticated: false,
}, 7*24*time.Hour, 0)
if err != nil {
t.Fatalf("InsertCapture: %v", err)
}
if id == 0 {
t.Fatalf("InsertCapture returned zero id")
}
got, err := s.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 1 {
t.Fatalf("ListCaptures = %d rows, want 1", len(got))
}
c := got[0]
if c.ID != id || c.Source != "github" || c.RemoteAddr != "203.0.113.5" ||
c.ContentType != "application/json" || c.Body != `{"action":"opened"}` ||
c.Authenticated {
t.Fatalf("round-tripped capture = %+v, want matching fields", c)
}
if c.ReceivedAt.IsZero() {
t.Fatalf("ReceivedAt is zero, want a timestamp stamped at insert")
}
}
func TestListCapturesOrdersNewestFirst(t *testing.T) {
s := openTest(t)
for i := range 3 {
if _, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "src", Body: "{}"}, 0, 0); err != nil {
t.Fatalf("InsertCapture[%d]: %v", i, err)
}
}
got, err := s.ListCaptures(t.Context(), 10)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 3 {
t.Fatalf("ListCaptures = %d rows, want 3", len(got))
}
if got[0].ID <= got[1].ID || got[1].ID <= got[2].ID {
t.Fatalf("ListCaptures not newest-first: ids = %d, %d, %d", got[0].ID, got[1].ID, got[2].ID)
}
}
func TestInsertCapturePrunesBeyondMaxEvents(t *testing.T) {
s := openTest(t)
var lastID int64
for i := range 5 {
id, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "src", Body: "{}"}, 0, 3)
if err != nil {
t.Fatalf("InsertCapture[%d]: %v", i, err)
}
lastID = id
}
got, err := s.ListCaptures(t.Context(), 100)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 3 {
t.Fatalf("row count = %d, want 3 (maxEvents cap)", len(got))
}
if got[0].ID != lastID {
t.Fatalf("newest surviving row id = %d, want %d (the last insert)", got[0].ID, lastID)
}
// The two oldest of the five inserts must have been pruned.
for _, c := range got {
if c.ID <= lastID-3 {
t.Fatalf("found pruned row id %d still present after maxEvents=3 cap", c.ID)
}
}
}
func TestInsertCapturePrunesOlderThanRetention(t *testing.T) {
s := openTest(t)
// Insert a row and manually age it beyond the retention window, since
// InsertCapture always stamps "now" and the test cannot wait real days.
id, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "old", Body: "{}"}, 0, 0)
if err != nil {
t.Fatalf("InsertCapture: %v", err)
}
stale := time.Now().UTC().Add(-8 * 24 * time.Hour).Format(captureTimeLayout)
if _, err := s.db.ExecContext(t.Context(),
`UPDATE captured_events SET received_at = ? WHERE id = ?`, stale, id); err != nil {
t.Fatalf("backdate row: %v", err)
}
// A fresh insert with a 7-day retention should prune the now-stale row.
if _, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "new", Body: "{}"}, 7*24*time.Hour, 0); err != nil {
t.Fatalf("InsertCapture: %v", err)
}
got, err := s.ListCaptures(t.Context(), 100)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
for _, c := range got {
if c.ID == id {
t.Fatalf("stale row id %d survived a 7-day retention prune", id)
}
}
if len(got) != 1 {
t.Fatalf("row count = %d, want 1 (only the fresh insert)", len(got))
}
}
// TestCaptureTimeLayoutSortsLexicographicallyLikeChronologically pins a real
// defect that time.RFC3339Nano has: it trims trailing fractional-second
// zeros and omits the fractional part entirely when it is exactly zero, so
// "15:04:05Z" (an exact second) sorts LEXICOGRAPHICALLY AFTER "15:04:05.1Z"
// (0.1s later) because 'Z' (0x5A) > '.' (0x2E) -- backwards from
// chronological order. A retention prune using `WHERE received_at < ?` on a
// column written that way is unreliable within the same second.
// captureTimeLayout must be fixed-width so string order and time order
// always agree.
//
// This compares captureTimeLayout's string output directly rather than
// going through InsertCapture's real prune, because the defect only shows up
// when two timestamps share the same whole-second value and differ only in
// fractional presence -- a case InsertCapture's own cutoff (computed from
// the real wall clock) cannot be steered into deterministically in a test.
func TestCaptureTimeLayoutSortsLexicographicallyLikeChronologically(t *testing.T) {
exactSecond := time.Date(2026, 1, 1, 15, 4, 5, 0, time.UTC)
fractionLater := time.Date(2026, 1, 1, 15, 4, 5, 100_000_000, time.UTC) // same second, 0.1s later
if !exactSecond.Before(fractionLater) {
t.Fatalf("test setup: %v must be before %v", exactSecond, fractionLater)
}
es, fs := exactSecond.Format(captureTimeLayout), fractionLater.Format(captureTimeLayout)
// The layout is second-precision, so two timestamps within the same
// second are allowed to format identically (that's the accepted
// precision tradeoff, not a bug) -- but a later time must never sort as
// lexicographically LESS than an earlier one.
if es > fs {
t.Fatalf("captureTimeLayout string order disagrees with chronological order: %q should not sort after %q", es, fs)
}
}
func TestInsertCaptureZeroRetentionAndMaxEventsMeansUnbounded(t *testing.T) {
s := openTest(t)
for i := range 10 {
if _, err := s.InsertCapture(t.Context(), CapturedEvent{Source: "src", Body: "{}"}, 0, 0); err != nil {
t.Fatalf("InsertCapture[%d]: %v", i, err)
}
}
got, err := s.ListCaptures(t.Context(), 100)
if err != nil {
t.Fatalf("ListCaptures: %v", err)
}
if len(got) != 10 {
t.Fatalf("row count = %d, want 10 (retention=0, maxEvents=0 disables both prunes)", len(got))
}
}
+14
View File
@@ -5,6 +5,7 @@ package store
import (
"context"
"time"
"github.com/samcharles93/archie-core/internal/events"
)
@@ -74,8 +75,21 @@ type WorkflowStore interface {
Transition(ctx context.Context, taskID int64, from, to, detail string) error
}
// CaptureStore persists unbound inbound webhook captures -- events with no
// workflow binding and no task association. Deliberately separate from
// TaskStore: a consumer that only needs capture (the intake HTTP handler)
// should not acquire the full task-lifecycle surface, mirroring why
// TaskArchiver is split out above. See docs/prds/event-capture-storage.md.
type CaptureStore interface {
InsertCapture(ctx context.Context, c CapturedEvent, retention time.Duration, maxEvents int) (int64, error)
ListCaptures(ctx context.Context, limit int) ([]CapturedEvent, error)
}
// Compile-time check: *Store satisfies TaskStore.
var _ TaskStore = (*Store)(nil)
// Compile-time check: *Store satisfies WorkflowStore.
var _ WorkflowStore = (*Store)(nil)
// Compile-time check: *Store satisfies CaptureStore.
var _ CaptureStore = (*Store)(nil)
+1 -1
View File
@@ -109,7 +109,7 @@ func Open(ctx context.Context, path string) (*Store, error) {
return nil, err
}
db.SetMaxOpenConns(1)
if _, err := db.ExecContext(ctx, schema+eventsSchema); err != nil {
if _, err := db.ExecContext(ctx, schema+eventsSchema+capturesSchema); err != nil {
return nil, errors.Join(fmt.Errorf("store: init schema: %w", err), db.Close())
}
if err := migrateTasks(ctx, db); err != nil {
+102
View File
@@ -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
}
+269
View File
@@ -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)
}
}
+22
View File
@@ -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
}