Merge branch 'pg/foundation' into worktree-agent-a96503bc8828fc104
# Conflicts: # docs/data/generated/dev-docs.json # internal/app/archied/state_store_test.go # internal/app/archied/state_store_toolcalls_test.go # internal/contracts/state/v1/state.pb.go # internal/daemon/dispatch_bindings_test.go # internal/infrastructure/bindingcipher/cipher_test.go # internal/infrastructure/captureintake/receiver_test.go # internal/infrastructure/edastore/contracts_binding.go # internal/infrastructure/edastore/testsupport_test.go # internal/infrastructure/postgres/edastore.go # internal/infrastructure/postgres/edastore_test.go # internal/infrastructure/staterpc/error_test.go # internal/store/store.go # internal/webui/api_binding_test.go
This commit is contained in:
commit
f68355ca77
130 files changed
+9028
-1999
No files matched your search
@@ -595,7 +595,7 @@ func TestStateStoreRealProcessRemoteSurfaces(t *testing.T) {
|
||||
}
|
||||
bindingID, err := cl.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 = (%q, %v)", bindingID, err)
|
||||
@@ -606,7 +606,6 @@ func TestStateStoreRealProcessRemoteSurfaces(t *testing.T) {
|
||||
if err := cl.UpdateBinding(ctx, binding.Binding{
|
||||
ID: bindingID, Name: "b1", Matcher: binding.Matcher{Source: "sentry"},
|
||||
MappingID: mappingID, Workflow: "implement", Owner: "acme", Repo: "widget",
|
||||
Secret: "0123456789abcdef0123456789abcdef",
|
||||
}); err != nil {
|
||||
t.Fatalf("UpdateBinding: %v", err)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,8 @@ machine** governing whether it is live.
|
||||
type Binding struct {
|
||||
ID, Name // identity
|
||||
Matcher // { Source string } -- the webhook path segment, e.g. "sentry"
|
||||
MappingID // which Mapping resolves payload fields
|
||||
MappingID // which Mapping resolves payload fields; its event type is the binding's
|
||||
Filter // optional CEL over the mapping's parameters
|
||||
Workflow // registered workflow name to dispatch to
|
||||
Version // bumped on every edit
|
||||
Status // pending_approval | armed
|
||||
@@ -34,19 +35,23 @@ them from the dashboard while the daemon runs, without a restart.
|
||||
|
||||
### Matching
|
||||
|
||||
`Matcher.Source` is the only predicate today: the path segment a sender
|
||||
POSTs to (e.g. a webhook hitting `.../sentry` matches bindings with
|
||||
`Matcher.Source == "sentry"`). The storage column is plain `TEXT`, so adding
|
||||
predicates later is non-breaking -- extend `Matcher`, don't invent a second
|
||||
matcher shape.
|
||||
A binding applies to a capture when the capture arrived on `Matcher.Source`,
|
||||
was identified as the event type its mapping belongs to, and passes its
|
||||
`Filter` (`binding.CompileFilter`, checked against the mapping's parameters on
|
||||
save). Any number of bindings may share a source; each dispatches a capture at
|
||||
most once, claimed in `binding_dispatches` keyed by (binding, capture) before
|
||||
its task is enqueued. An event signed with any armed binding's secret on the
|
||||
source is authenticated.
|
||||
|
||||
### Mapping
|
||||
|
||||
`mapping.Resolve(fields, payload)` walks a captured JSON payload against a
|
||||
list of typed `Field`s (name, JSON path, expected type), returning resolved
|
||||
values plus a `[]Failure` for anything that didn't parse or type-match. This
|
||||
is schema-by-example in practice: a mapping is authored by pointing at a
|
||||
real captured payload in the dashboard, not by guessing a schema in advance.
|
||||
values plus a `[]Failure` for anything that didn't parse or type-match. A
|
||||
mapping belongs to an event type, and `mapping.CheckSchema` refuses a field
|
||||
whose path or type the type's inferred schema lacks. Each capture a mapping
|
||||
resolves at dispatch is counted once in `mapping_matches`, read back as
|
||||
`MatchCount` and `LastMatchedAt`.
|
||||
|
||||
### Versioning
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
"url": "/dev/architecture/bindings/",
|
||||
"title": "Playbook bindings: model and threat model",
|
||||
"section": "Architecture",
|
||||
"body": "# Playbook bindings: model and threat model\n\n**Status:** Approved foundation (documents shipped code: `archie-core-t2db.1`\nthrough `.5`, `.7`, `.9`-`.15`)\n**Date:** 2026-09-03\n\nThis document covers the binding model and the intake threat model portion\nof `archie-core-t2db.6`. It does not cover the task-lifecycle provenance rule\n(`messaging-and-work-intake.md`'s \"Intake provenance\") or the operator\nwalkthrough -- that walkthrough remains an open piece of the same ticket.\n\n## What a binding is\n\nA `binding` (`internal/domain/binding.Binding`) ties four things together:\na **matcher** (which captured events it applies to), a **mapping**\n(`internal/domain/mapping.Mapping`, how fields are pulled out of a payload),\na **workflow** (which registered workflow runs on a match), and a **state\nmachine** governing whether it is live.\n\n```go\ntype Binding struct {\n ID, Name // identity\n Matcher // { Source string } -- the webhook path segment, e.g. \"sentry\"\n MappingID // which Mapping resolves payload fields\n Workflow // registered workflow name to dispatch to\n Version // bumped on every edit\n Status // pending_approval | armed\n Secret // HMAC-SHA256 shared secret, encrypted at rest, never returned by GET\n}\n```\n\nBindings live in the store (PostgreSQL), not `config.toml` -- operators author\nthem from the dashboard while the daemon runs, without a restart.\n\n### Matching\n\n`Matcher.Source` is the only predicate today: the path segment a sender\nPOSTs to (e.g. a webhook hitting `.../sentry` matches bindings with\n`Matcher.Source == \"sentry\"`). The storage column is plain `TEXT`, so adding\npredicates later is non-breaking -- extend `Matcher`, don't invent a second\nmatcher shape.\n\n### Mapping\n\n`mapping.Resolve(fields, payload)` walks a captured JSON payload against a\nlist of typed `Field`s (name, JSON path, expected type), returning resolved\nvalues plus a `[]Failure` for anything that didn't parse or type-match. This\nis schema-by-example in practice: a mapping is authored by pointing at a\nreal captured payload in the dashboard, not by guessing a schema in advance.\n\n### Versioning\n\n`Version` increments on every `UpdateBinding` call. This exists so an\neditor's later change can never silently rewrite the historical provenance\nof a task that already fired -- a dispatched task's binding reference is\npinned to the version that was armed when it fired, not \"whatever the\nbinding currently says.\"\n\n### State machine\n\n```\ncreate ---\u003e pending_approval ---\u003e armed\n ^ |\n +----------------+\n (any edit to an armed binding drops it back to pending_approval)\n```\n\nA binding is created `pending_approval`, so the operator who creates one can\napprove it immediately. Bindings stored as `draft` by an earlier version are\nmoved to `pending_approval` when the EDA store opens.\n\nModeled directly on Telegram's existing `dangerousAction`/`pendingApproval`\nflow (`internal/channels/telegram/dangerous.go`, `approval.go`) -- not a new\napproval mechanism invented for this feature. **Only `armed` evaluates\nagainst incoming events** (`binding.Matches`, `internal/domain/binding/\nbinding.go`); a `pending_approval` binding is inert. An edit to\nan already-armed binding cannot bypass approval by silent mutation -- it\ndrops back to `pending_approval` and requires an explicit `Approve` call to\nre-arm.\n\n## The threat model\n\nThis is a public, unauthenticated-by-default intake surface whose output is\nan agent with a repo, a worktree, and tool access. The design brief\n(`archie-core-t2db.5`, `docs/prds/webhook-intake-security.md`) named five\nnon-negotiables; each is verified below against the actual shipped code,\nnot the design intent.\n\n### 1. Per-source authentication\n\nReuses `internal/channels/webhook`'s existing HMAC-SHA256 scheme --\ncapture accepts unsigned events (visible in the dashboard, marked\nunauthenticated), but **only authenticated events can ever match a\nbinding**. `binding.Matches`' doc comment states this plainly: \"an\nunauthenticated event can never trigger a binding, no matter how well it\nwould otherwise match.\" Enforced structurally at two points, not just\nconvention:\n\n- `captures.authenticated` is a real column\n (`internal/infrastructure/postgres/migrations/0002_edastore.sql`), set at\n capture time.\n- `dispatchBindings` (`internal/daemon/daemon.go:479`) walks **authenticated\n captures whose source has at least one armed binding** -- an\n unauthenticated capture is never even considered for dispatch.\n\n### 2. Human approval before a binding goes live\n\nCovered by the state machine above. Nothing self-arms: `pending_approval -\u003e\narmed` requires an explicit `Approve` call, and any edit to an armed\nbinding reverts it.\n\n### 3. Rate and volume limits per source\n\nCapturLine truncated
|
||||
"body": "# Playbook bindings: model and threat model\n\n**Status:** Approved foundation (documents shipped code: `archie-core-t2db.1`\nthrough `.5`, `.7`, `.9`-`.15`)\n**Date:** 2026-09-03\n\nThis document covers the binding model and the intake threat model portion\nof `archie-core-t2db.6`. It does not cover the task-lifecycle provenance rule\n(`messaging-and-work-intake.md`'s \"Intake provenance\") or the operator\nwalkthrough -- that walkthrough remains an open piece of the same ticket.\n\n## What a binding is\n\nA `binding` (`internal/domain/binding.Binding`) ties four things together:\na **matcher** (which captured events it applies to), a **mapping**\n(`internal/domain/mapping.Mapping`, how fields are pulled out of a payload),\na **workflow** (which registered workflow runs on a match), and a **state\nmachine** governing whether it is live.\n\n```go\ntype Binding struct {\n ID, Name // identity\n Matcher // { Source string } -- the webhook path segment, e.g. \"sentry\"\n MappingID // which Mapping resolves payload fields; its event type is the binding's\n Filter // optional CEL over the mapping's parameters\n Workflow // registered workflow name to dispatch to\n Version // bumped on every edit\n Status // pending_approval | armed\n Secret // HMAC-SHA256 shared secret, encrypted at rest, never returned by GET\n}\n```\n\nBindings live in the store (PostgreSQL), not `config.toml` -- operators author\nthem from the dashboard while the daemon runs, without a restart.\n\n### Matching\n\nA binding applies to a capture when the capture arrived on `Matcher.Source`,\nwas identified as the event type its mapping belongs to, and passes its\n`Filter` (`binding.CompileFilter`, checked against the mapping's parameters on\nsave). Any number of bindings may share a source; each dispatches a capture at\nmost once, claimed in `binding_dispatches` keyed by (binding, capture) before\nits task is enqueued. An event signed with any armed binding's secret on the\nsource is authenticated.\n\n### Mapping\n\n`mapping.Resolve(fields, payload)` walks a captured JSON payload against a\nlist of typed `Field`s (name, JSON path, expected type), returning resolved\nvalues plus a `[]Failure` for anything that didn't parse or type-match. A\nmapping belongs to an event type, and `mapping.CheckSchema` refuses a field\nwhose path or type the type's inferred schema lacks. Each capture a mapping\nresolves at dispatch is counted once in `mapping_matches`, read back as\n`MatchCount` and `LastMatchedAt`.\n\n### Versioning\n\n`Version` increments on every `UpdateBinding` call. This exists so an\neditor's later change can never silently rewrite the historical provenance\nof a task that already fired -- a dispatched task's binding reference is\npinned to the version that was armed when it fired, not \"whatever the\nbinding currently says.\"\n\n### State machine\n\n```\ncreate ---\u003e pending_approval ---\u003e armed\n ^ |\n +----------------+\n (any edit to an armed binding drops it back to pending_approval)\n```\n\nA binding is created `pending_approval`, so the operator who creates one can\napprove it immediately. Bindings stored as `draft` by an earlier version are\nmoved to `pending_approval` when the EDA store opens.\n\nModeled directly on Telegram's existing `dangerousAction`/`pendingApproval`\nflow (`internal/channels/telegram/dangerous.go`, `approval.go`) -- not a new\napproval mechanism invented for this feature. **Only `armed` evaluates\nagainst incoming events** (`binding.Matches`, `internal/domain/binding/\nbinding.go`); a `pending_approval` binding is inert. An edit to\nan already-armed binding cannot bypass approval by silent mutation -- it\ndrops back to `pending_approval` and requires an explicit `Approve` call to\nre-arm.\n\n## The threat model\n\nThis is a public, unauthenticated-by-default intake surface whose output is\nan agent with a repo, a worktree, and tool access. The design brief\n(`archie-core-t2db.5`, `docs/prds/webhook-intake-security.md`) named five\nnon-negotiables; each is verified below against the actual shipped code,\nnot the design intent.\n\n### 1. Per-source authentication\n\nReuses `internal/channels/webhook`'s existing HMAC-SHA256 scheme --\ncapture accepts unsigned events (visible in the dashboard, marked\nunauthenticated), but **only authenticated events can ever match a\nbinding**. `binding.Matches`' doc comment states this plainly: \"an\nunauthenticated event can never trigger a binding, no matter how well it\nwould otherwise match.\" Enforced structurally at two points, not just\nconvention:\n\n- `captures.authenticated` is a real column\n (`internal/infrastructure/postgres/migrations/0002_edastore.sql`), set at\n capture time.\n- `dispatchBindings` (`internal/daemon/daemon.go:479`) walks **authenticated\n captures whose souLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/architecture/configuration/",
|
||||
|
||||
@@ -1348,6 +1348,9 @@ func (b *boot) buildDaemon() {
|
||||
if bd, ok := b.stateStore.(storecontract.BindingDispatcher); ok {
|
||||
b.d.BindingDispatcher = bd
|
||||
}
|
||||
if mm, ok := b.stateStore.(storecontract.MappingMatchRecorder); ok {
|
||||
b.d.MappingMatches = mm
|
||||
}
|
||||
if btc, ok := b.stateStore.(storecontract.BindingTaskCreator); ok {
|
||||
b.d.BindingTaskCreator = btc
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"url":"nats://127.0.0.1:40943","token":"KL5KSFZT4PI5KIHF3GUOYXUTOQ"}
|
||||
{"url":"nats://127.0.0.1:34001","token":"UTTAKZ3FQ3FSB7D6XARWKTYMUQ"}
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"Created":"0001-01-01T00:00:00Z","Name":"","name":"2AiYsxvu","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":5000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
@@ -0,0 +1 @@
|
||||
1a41fdece74230be
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"Created":"0001-01-01T00:00:00Z","Name":"","name":"4ETGGNq6","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":5000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
@@ -0,0 +1 @@
|
||||
59023e4aa2a291e6
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"Created":"0001-01-01T00:00:00Z","Name":"","name":"8MNb4kc2","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":5000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
@@ -0,0 +1 @@
|
||||
461f1f0b33b1e704
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
{"Created":"2026-09-24T09:46:47.593915791Z","Name":"Bm6IdqYw","name":"Bm6IdqYw","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
@@ -0,0 +1 @@
|
||||
8b3c3f8234fa0b40
|
||||
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
{"Created":"2026-09-24T09:38:53.493195549Z","Name":"archie-daemon","durable_name":"archie-daemon","name":"archie-daemon","deliver_policy":"all","ack_policy":"explicit","ack_wait":300000000000,"max_deliver":3,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":86400000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
{"Created":"2026-09-24T09:46:47.587065821Z","Name":"archie-daemon","durable_name":"archie-daemon","name":"archie-daemon","deliver_policy":"all","ack_policy":"explicit","ack_wait":300000000000,"max_deliver":3,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":86400000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
989e2c19cd43eee8
|
||||
5eb449f03c31a0f7
|
||||
@@ -0,0 +1 @@
|
||||
{"Created":"2026-09-24T09:46:47.594292859Z","Name":"eq86DXAG","name":"eq86DXAG","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
@@ -0,0 +1 @@
|
||||
5ff54a1a5c91cc56
|
||||
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
{"Created":"2026-09-24T09:38:53.500447377Z","Name":"jRzCdtm6","name":"jRzCdtm6","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
{"Created":"0001-01-01T00:00:00Z","Name":"","name":"jRzCdtm6","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":5000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
620c347e0e296f80
|
||||
abaa43ff23e8df46
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"Created":"2026-09-24T09:38:53.500003272Z","Name":"kmNsDMt5","name":"kmNsDMt5","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
{"Created":"0001-01-01T00:00:00Z","Name":"","name":"kmNsDMt5","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":5000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
e571c54b14192a8c
|
||||
60d5c7722ea0e3a4
|
||||
@@ -0,0 +1 @@
|
||||
{"Created":"0001-01-01T00:00:00Z","Name":"","name":"vn0YoRC5","deliver_policy":"all","ack_policy":"explicit","ack_wait":30000000000,"max_deliver":-1,"filter_subject":"archie.reaction.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":5000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
@@ -0,0 +1 @@
|
||||
98548a1ca3a96fc3
|
||||
Binary file not shown.
+1
-1
@@ -1 +1 @@
|
||||
{"Created":"2026-09-24T09:38:53.492664758Z","Name":"archie-daemon","durable_name":"archie-daemon","name":"archie-daemon","deliver_policy":"all","ack_policy":"explicit","ack_wait":300000000000,"max_deliver":3,"filter_subject":"archie.task.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":86400000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
{"Created":"2026-09-24T09:46:47.585493669Z","Name":"archie-daemon","durable_name":"archie-daemon","name":"archie-daemon","deliver_policy":"all","ack_policy":"explicit","ack_wait":300000000000,"max_deliver":3,"filter_subject":"archie.task.\u003e","replay_policy":"instant","max_waiting":512,"max_ack_pending":1000,"inactive_threshold":86400000000000,"num_replicas":0,"metadata":{"_nats.req.level":"0"}}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
424323b7dcce276c
|
||||
39a729e190b2fb96
|
||||
@@ -252,6 +252,9 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
||||
deps.Bindings = b.eda
|
||||
deps.BindingDispatcher = b.eda
|
||||
deps.PlaybookDispatcher = b.eda
|
||||
deps.EventTypes = b.eda
|
||||
deps.Sources = b.eda
|
||||
deps.MappingMatches = b.eda
|
||||
}
|
||||
// tool_call events project into the tool_calls collection on the same
|
||||
// event-capture store: this process legitimately owns both, so the
|
||||
|
||||
@@ -8,12 +8,15 @@ import (
|
||||
|
||||
// eventCaptureStore is every surface the State Store serves from the
|
||||
// event-capture tables, plus the tool_call projection it writes through.
|
||||
type eventCaptureStore interface {
|
||||
type eventCaptureStore interface { //nolint:interfacebloat // composite of the store contracts the event-capture tables serve
|
||||
storecontract.CaptureStore
|
||||
storecontract.MappingStore
|
||||
storecontract.BindingStore
|
||||
storecontract.BindingDispatcher
|
||||
storecontract.MappingMatchRecorder
|
||||
storecontract.PlaybookDispatcher
|
||||
storecontract.EventTypeStore
|
||||
storecontract.SourceStore
|
||||
toolCallWriter
|
||||
}
|
||||
|
||||
|
||||
@@ -139,8 +139,8 @@ func TestStateStoreDepsServePlaybookDispatcher(t *testing.T) {
|
||||
|
||||
b := newBootstrap()
|
||||
b.st = st
|
||||
// The playbook ledger moved to the event-capture store with the rest of
|
||||
// the dispatch tables; the task store no longer serves it.
|
||||
// The playbook ledger, sources and event types are served by the
|
||||
// event-capture store; the task store no longer serves them.
|
||||
eda := pgstore.EDA(t, nil)
|
||||
b.eda = eda
|
||||
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
@@ -148,7 +148,10 @@ func TestStateStoreDepsServePlaybookDispatcher(t *testing.T) {
|
||||
t.Fatal("stateStoreDeps leaves PlaybookDispatcher nil; the standalone State Store is the only production server for the playbook dispatch ledger")
|
||||
}
|
||||
if deps.PlaybookDispatcher != storecontract.PlaybookDispatcher(eda) {
|
||||
t.Fatalf("PlaybookDispatcher = %T, want the opened *postgres.EDA", deps.PlaybookDispatcher)
|
||||
t.Fatalf("PlaybookDispatcher = %T, want the opened event-capture store", deps.PlaybookDispatcher)
|
||||
}
|
||||
if deps.Sources == nil || deps.EventTypes == nil {
|
||||
t.Fatalf("stateStoreDeps Sources = %v, EventTypes = %v; want both served, or intake verifies nothing and nothing dispatches", deps.Sources, deps.EventTypes)
|
||||
}
|
||||
// A boot without a store must not fabricate one: nil keeps the RPCs honest
|
||||
// as unavailable rather than depending on a nil receiver.
|
||||
|
||||
@@ -173,11 +173,10 @@ func TestInsertEventSucceedsWhenProjectionFails(t *testing.T) {
|
||||
// around a nil writer.
|
||||
func TestStateStoreDepsProjectToolCalls(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
|
||||
b := newBootstrap()
|
||||
b.st = st
|
||||
b.eda = eda
|
||||
b.eda = pgstore.EDA(t, nil)
|
||||
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
if _, ok := deps.Tasks.(*toolCallProjectingTaskStore); !ok {
|
||||
t.Fatalf("deps.Tasks = %T, want the tool_call projecting decorator", deps.Tasks)
|
||||
|
||||
@@ -103,6 +103,9 @@ func compose(d deps) *webui.Server {
|
||||
if bindings, ok := d.Store.(storecontract.BindingStore); ok {
|
||||
srv.Bindings = bindings
|
||||
}
|
||||
if eventTypes, ok := d.Store.(storecontract.EventTypeStore); ok {
|
||||
srv.EventTypes = eventTypes
|
||||
}
|
||||
if d.Chat != nil {
|
||||
srv.Chat = &webui.ChatService{Contract: d.Chat}
|
||||
}
|
||||
@@ -131,21 +134,25 @@ func wireTaskLogs(d deps, srv *webui.Server) {
|
||||
srv.TaskLogs = logs
|
||||
}
|
||||
|
||||
// wireCaptureSurfaces attaches the capture read and the intake receiver.
|
||||
// Both resolve from d.Store's contracts: CaptureStore backs the inspector's
|
||||
// list and the mapping preview's scan window, BindingDispatcher resolves the
|
||||
// armed binding whose secret HMAC-verifies a source. A store that does not
|
||||
// implement one degrades that half with a warning rather than aborting the
|
||||
// process, mirroring the daemon's own adapter selection.
|
||||
// wireCaptureSurfaces attaches the capture read, the source editor and the
|
||||
// intake receiver. All resolve from d.Store's contracts: CaptureStore backs
|
||||
// the inspector's list and the mapping preview's scan window, SourceStore
|
||||
// resolves the source whose signing setting verifies an event. A store that
|
||||
// does not implement one degrades that half with a warning rather than
|
||||
// aborting the process, mirroring the daemon's own adapter selection.
|
||||
func wireCaptureSurfaces(d deps, srv *webui.Server) {
|
||||
captures, hasCaptures := d.Store.(storecontract.CaptureStore)
|
||||
bindings, hasBindings := d.Store.(storecontract.BindingDispatcher)
|
||||
sources, hasSources := d.Store.(storecontract.SourceStore)
|
||||
if !hasCaptures {
|
||||
d.Log.Warn("capture storage unavailable: state store does not implement CaptureStore")
|
||||
return
|
||||
}
|
||||
if !hasBindings {
|
||||
d.Log.Warn("binding dispatcher unavailable: state store does not implement BindingDispatcher")
|
||||
var resolver captureintake.SourceResolver
|
||||
if hasSources {
|
||||
srv.Sources = sources
|
||||
resolver = sources
|
||||
} else {
|
||||
d.Log.Warn("source store unavailable: state store does not implement SourceStore; no capture will dispatch")
|
||||
}
|
||||
|
||||
capture := d.Options.Capture.withDefaults()
|
||||
@@ -154,7 +161,7 @@ func wireCaptureSurfaces(d deps, srv *webui.Server) {
|
||||
srv.CaptureIntake = &captureintake.Receiver{
|
||||
Captures: captures,
|
||||
Limiter: webhookguard.NewRateLimiter(capture.RatePerSecond, capture.RateBurst, time.Now),
|
||||
Bindings: bindings,
|
||||
Sources: resolver,
|
||||
Retention: capture.Retention,
|
||||
MaxEvents: capture.MaxEvents,
|
||||
MaxBodyBytes: int64(capture.MaxBodyBytes),
|
||||
|
||||
+2076
-722
File diff suppressed because it is too large.
Load diff
@@ -73,12 +73,22 @@ const (
|
||||
StateStoreService_ListMappings_FullMethodName = "/state.v1.StateStoreService/ListMappings"
|
||||
StateStoreService_UpdateMapping_FullMethodName = "/state.v1.StateStoreService/UpdateMapping"
|
||||
StateStoreService_DeleteMapping_FullMethodName = "/state.v1.StateStoreService/DeleteMapping"
|
||||
StateStoreService_RecordMappingMatch_FullMethodName = "/state.v1.StateStoreService/RecordMappingMatch"
|
||||
StateStoreService_InsertEventType_FullMethodName = "/state.v1.StateStoreService/InsertEventType"
|
||||
StateStoreService_UpdateEventType_FullMethodName = "/state.v1.StateStoreService/UpdateEventType"
|
||||
StateStoreService_DeleteEventType_FullMethodName = "/state.v1.StateStoreService/DeleteEventType"
|
||||
StateStoreService_ListEventTypes_FullMethodName = "/state.v1.StateStoreService/ListEventTypes"
|
||||
StateStoreService_InsertBinding_FullMethodName = "/state.v1.StateStoreService/InsertBinding"
|
||||
StateStoreService_GetBinding_FullMethodName = "/state.v1.StateStoreService/GetBinding"
|
||||
StateStoreService_ListBindings_FullMethodName = "/state.v1.StateStoreService/ListBindings"
|
||||
StateStoreService_UpdateBinding_FullMethodName = "/state.v1.StateStoreService/UpdateBinding"
|
||||
StateStoreService_DeleteBinding_FullMethodName = "/state.v1.StateStoreService/DeleteBinding"
|
||||
StateStoreService_ApproveBinding_FullMethodName = "/state.v1.StateStoreService/ApproveBinding"
|
||||
StateStoreService_InsertSource_FullMethodName = "/state.v1.StateStoreService/InsertSource"
|
||||
StateStoreService_GetSource_FullMethodName = "/state.v1.StateStoreService/GetSource"
|
||||
StateStoreService_ListSources_FullMethodName = "/state.v1.StateStoreService/ListSources"
|
||||
StateStoreService_SetSourceSigning_FullMethodName = "/state.v1.StateStoreService/SetSourceSigning"
|
||||
StateStoreService_SetSourceSecret_FullMethodName = "/state.v1.StateStoreService/SetSourceSecret"
|
||||
StateStoreService_ArmedBindingsForSource_FullMethodName = "/state.v1.StateStoreService/ArmedBindingsForSource"
|
||||
StateStoreService_RecordDispatch_FullMethodName = "/state.v1.StateStoreService/RecordDispatch"
|
||||
StateStoreService_RecordPlaybookDispatch_FullMethodName = "/state.v1.StateStoreService/RecordPlaybookDispatch"
|
||||
@@ -197,6 +207,15 @@ type StateStoreServiceClient interface {
|
||||
ListMappings(ctx context.Context, in *ListMappingsRequest, opts ...grpc.CallOption) (*ListMappingsResponse, error)
|
||||
UpdateMapping(ctx context.Context, in *UpdateMappingRequest, opts ...grpc.CallOption) (*UpdateMappingResponse, error)
|
||||
DeleteMapping(ctx context.Context, in *DeleteMappingRequest, opts ...grpc.CallOption) (*DeleteMappingResponse, error)
|
||||
// RecordMappingMatch counts one event a mapping resolved; the same
|
||||
// (mapping, capture) twice counts once.
|
||||
RecordMappingMatch(ctx context.Context, in *RecordMappingMatchRequest, opts ...grpc.CallOption) (*RecordMappingMatchResponse, error)
|
||||
// EventType (docs/prds/event-automation.md, "Event types"). Insert and
|
||||
// Update refuse an overlapping or malformed type.
|
||||
InsertEventType(ctx context.Context, in *InsertEventTypeRequest, opts ...grpc.CallOption) (*InsertEventTypeResponse, error)
|
||||
UpdateEventType(ctx context.Context, in *UpdateEventTypeRequest, opts ...grpc.CallOption) (*UpdateEventTypeResponse, error)
|
||||
DeleteEventType(ctx context.Context, in *DeleteEventTypeRequest, opts ...grpc.CallOption) (*DeleteEventTypeResponse, error)
|
||||
ListEventTypes(ctx context.Context, in *ListEventTypesRequest, opts ...grpc.CallOption) (*ListEventTypesResponse, error)
|
||||
// Binding
|
||||
InsertBinding(ctx context.Context, in *InsertBindingRequest, opts ...grpc.CallOption) (*InsertBindingResponse, error)
|
||||
GetBinding(ctx context.Context, in *GetBindingRequest, opts ...grpc.CallOption) (*GetBindingResponse, error)
|
||||
@@ -204,6 +223,13 @@ type StateStoreServiceClient interface {
|
||||
UpdateBinding(ctx context.Context, in *UpdateBindingRequest, opts ...grpc.CallOption) (*UpdateBindingResponse, error)
|
||||
DeleteBinding(ctx context.Context, in *DeleteBindingRequest, opts ...grpc.CallOption) (*DeleteBindingResponse, error)
|
||||
ApproveBinding(ctx context.Context, in *ApproveBindingRequest, opts ...grpc.CallOption) (*ApproveBindingResponse, error)
|
||||
// Source (event-automation.md "Sources"): the capture endpoint and its
|
||||
// signing setting. Secrets travel in plaintext; the store encrypts at rest.
|
||||
InsertSource(ctx context.Context, in *InsertSourceRequest, opts ...grpc.CallOption) (*InsertSourceResponse, error)
|
||||
GetSource(ctx context.Context, in *GetSourceRequest, opts ...grpc.CallOption) (*GetSourceResponse, error)
|
||||
ListSources(ctx context.Context, in *ListSourcesRequest, opts ...grpc.CallOption) (*ListSourcesResponse, error)
|
||||
SetSourceSigning(ctx context.Context, in *SetSourceSigningRequest, opts ...grpc.CallOption) (*SetSourceSigningResponse, error)
|
||||
SetSourceSecret(ctx context.Context, in *SetSourceSecretRequest, opts ...grpc.CallOption) (*SetSourceSecretResponse, error)
|
||||
// Dispatch
|
||||
ArmedBindingsForSource(ctx context.Context, in *ArmedBindingsForSourceRequest, opts ...grpc.CallOption) (*ArmedBindingsForSourceResponse, error)
|
||||
RecordDispatch(ctx context.Context, in *RecordDispatchRequest, opts ...grpc.CallOption) (*RecordDispatchResponse, error)
|
||||
@@ -789,6 +815,56 @@ func (c *stateStoreServiceClient) DeleteMapping(ctx context.Context, in *DeleteM
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) RecordMappingMatch(ctx context.Context, in *RecordMappingMatchRequest, opts ...grpc.CallOption) (*RecordMappingMatchResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(RecordMappingMatchResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_RecordMappingMatch_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) InsertEventType(ctx context.Context, in *InsertEventTypeRequest, opts ...grpc.CallOption) (*InsertEventTypeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(InsertEventTypeResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_InsertEventType_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) UpdateEventType(ctx context.Context, in *UpdateEventTypeRequest, opts ...grpc.CallOption) (*UpdateEventTypeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(UpdateEventTypeResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_UpdateEventType_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) DeleteEventType(ctx context.Context, in *DeleteEventTypeRequest, opts ...grpc.CallOption) (*DeleteEventTypeResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DeleteEventTypeResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_DeleteEventType_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ListEventTypes(ctx context.Context, in *ListEventTypesRequest, opts ...grpc.CallOption) (*ListEventTypesResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ListEventTypesResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ListEventTypes_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) InsertBinding(ctx context.Context, in *InsertBindingRequest, opts ...grpc.CallOption) (*InsertBindingResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(InsertBindingResponse)
|
||||
@@ -849,6 +925,56 @@ func (c *stateStoreServiceClient) ApproveBinding(ctx context.Context, in *Approv
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) InsertSource(ctx context.Context, in *InsertSourceRequest, opts ...grpc.CallOption) (*InsertSourceResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(InsertSourceResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_InsertSource_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) GetSource(ctx context.Context, in *GetSourceRequest, opts ...grpc.CallOption) (*GetSourceResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetSourceResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_GetSource_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ListSources(ctx context.Context, in *ListSourcesRequest, opts ...grpc.CallOption) (*ListSourcesResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ListSourcesResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ListSources_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) SetSourceSigning(ctx context.Context, in *SetSourceSigningRequest, opts ...grpc.CallOption) (*SetSourceSigningResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SetSourceSigningResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_SetSourceSigning_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) SetSourceSecret(ctx context.Context, in *SetSourceSecretRequest, opts ...grpc.CallOption) (*SetSourceSecretResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SetSourceSecretResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_SetSourceSecret_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ArmedBindingsForSource(ctx context.Context, in *ArmedBindingsForSourceRequest, opts ...grpc.CallOption) (*ArmedBindingsForSourceResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ArmedBindingsForSourceResponse)
|
||||
@@ -1038,6 +1164,15 @@ type StateStoreServiceServer interface {
|
||||
ListMappings(context.Context, *ListMappingsRequest) (*ListMappingsResponse, error)
|
||||
UpdateMapping(context.Context, *UpdateMappingRequest) (*UpdateMappingResponse, error)
|
||||
DeleteMapping(context.Context, *DeleteMappingRequest) (*DeleteMappingResponse, error)
|
||||
// RecordMappingMatch counts one event a mapping resolved; the same
|
||||
// (mapping, capture) twice counts once.
|
||||
RecordMappingMatch(context.Context, *RecordMappingMatchRequest) (*RecordMappingMatchResponse, error)
|
||||
// EventType (docs/prds/event-automation.md, "Event types"). Insert and
|
||||
// Update refuse an overlapping or malformed type.
|
||||
InsertEventType(context.Context, *InsertEventTypeRequest) (*InsertEventTypeResponse, error)
|
||||
UpdateEventType(context.Context, *UpdateEventTypeRequest) (*UpdateEventTypeResponse, error)
|
||||
DeleteEventType(context.Context, *DeleteEventTypeRequest) (*DeleteEventTypeResponse, error)
|
||||
ListEventTypes(context.Context, *ListEventTypesRequest) (*ListEventTypesResponse, error)
|
||||
// Binding
|
||||
InsertBinding(context.Context, *InsertBindingRequest) (*InsertBindingResponse, error)
|
||||
GetBinding(context.Context, *GetBindingRequest) (*GetBindingResponse, error)
|
||||
@@ -1045,6 +1180,13 @@ type StateStoreServiceServer interface {
|
||||
UpdateBinding(context.Context, *UpdateBindingRequest) (*UpdateBindingResponse, error)
|
||||
DeleteBinding(context.Context, *DeleteBindingRequest) (*DeleteBindingResponse, error)
|
||||
ApproveBinding(context.Context, *ApproveBindingRequest) (*ApproveBindingResponse, error)
|
||||
// Source (event-automation.md "Sources"): the capture endpoint and its
|
||||
// signing setting. Secrets travel in plaintext; the store encrypts at rest.
|
||||
InsertSource(context.Context, *InsertSourceRequest) (*InsertSourceResponse, error)
|
||||
GetSource(context.Context, *GetSourceRequest) (*GetSourceResponse, error)
|
||||
ListSources(context.Context, *ListSourcesRequest) (*ListSourcesResponse, error)
|
||||
SetSourceSigning(context.Context, *SetSourceSigningRequest) (*SetSourceSigningResponse, error)
|
||||
SetSourceSecret(context.Context, *SetSourceSecretRequest) (*SetSourceSecretResponse, error)
|
||||
// Dispatch
|
||||
ArmedBindingsForSource(context.Context, *ArmedBindingsForSourceRequest) (*ArmedBindingsForSourceResponse, error)
|
||||
RecordDispatch(context.Context, *RecordDispatchRequest) (*RecordDispatchResponse, error)
|
||||
@@ -1233,6 +1375,21 @@ func (UnimplementedStateStoreServiceServer) UpdateMapping(context.Context, *Upda
|
||||
func (UnimplementedStateStoreServiceServer) DeleteMapping(context.Context, *DeleteMappingRequest) (*DeleteMappingResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DeleteMapping not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) RecordMappingMatch(context.Context, *RecordMappingMatchRequest) (*RecordMappingMatchResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method RecordMappingMatch not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) InsertEventType(context.Context, *InsertEventTypeRequest) (*InsertEventTypeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method InsertEventType not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) UpdateEventType(context.Context, *UpdateEventTypeRequest) (*UpdateEventTypeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method UpdateEventType not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) DeleteEventType(context.Context, *DeleteEventTypeRequest) (*DeleteEventTypeResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method DeleteEventType not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ListEventTypes(context.Context, *ListEventTypesRequest) (*ListEventTypesResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListEventTypes not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) InsertBinding(context.Context, *InsertBindingRequest) (*InsertBindingResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method InsertBinding not implemented")
|
||||
}
|
||||
@@ -1251,6 +1408,21 @@ func (UnimplementedStateStoreServiceServer) DeleteBinding(context.Context, *Dele
|
||||
func (UnimplementedStateStoreServiceServer) ApproveBinding(context.Context, *ApproveBindingRequest) (*ApproveBindingResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ApproveBinding not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) InsertSource(context.Context, *InsertSourceRequest) (*InsertSourceResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method InsertSource not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) GetSource(context.Context, *GetSourceRequest) (*GetSourceResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetSource not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ListSources(context.Context, *ListSourcesRequest) (*ListSourcesResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListSources not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) SetSourceSigning(context.Context, *SetSourceSigningRequest) (*SetSourceSigningResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SetSourceSigning not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) SetSourceSecret(context.Context, *SetSourceSecretRequest) (*SetSourceSecretResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SetSourceSecret not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ArmedBindingsForSource(context.Context, *ArmedBindingsForSourceRequest) (*ArmedBindingsForSourceResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ArmedBindingsForSource not implemented")
|
||||
}
|
||||
@@ -2251,6 +2423,96 @@ func _StateStoreService_DeleteMapping_Handler(srv interface{}, ctx context.Conte
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_RecordMappingMatch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(RecordMappingMatchRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).RecordMappingMatch(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_RecordMappingMatch_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).RecordMappingMatch(ctx, req.(*RecordMappingMatchRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_InsertEventType_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(InsertEventTypeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).InsertEventType(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_InsertEventType_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).InsertEventType(ctx, req.(*InsertEventTypeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_UpdateEventType_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(UpdateEventTypeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).UpdateEventType(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_UpdateEventType_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).UpdateEventType(ctx, req.(*UpdateEventTypeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_DeleteEventType_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(DeleteEventTypeRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).DeleteEventType(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_DeleteEventType_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).DeleteEventType(ctx, req.(*DeleteEventTypeRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ListEventTypes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ListEventTypesRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ListEventTypes(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ListEventTypes_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ListEventTypes(ctx, req.(*ListEventTypesRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_InsertBinding_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(InsertBindingRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -2359,6 +2621,96 @@ func _StateStoreService_ApproveBinding_Handler(srv interface{}, ctx context.Cont
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_InsertSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(InsertSourceRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).InsertSource(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_InsertSource_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).InsertSource(ctx, req.(*InsertSourceRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_GetSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetSourceRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).GetSource(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_GetSource_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).GetSource(ctx, req.(*GetSourceRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ListSources_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ListSourcesRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ListSources(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ListSources_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ListSources(ctx, req.(*ListSourcesRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_SetSourceSigning_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SetSourceSigningRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).SetSourceSigning(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_SetSourceSigning_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).SetSourceSigning(ctx, req.(*SetSourceSigningRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_SetSourceSecret_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SetSourceSecretRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).SetSourceSecret(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_SetSourceSecret_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).SetSourceSecret(ctx, req.(*SetSourceSecretRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ArmedBindingsForSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ArmedBindingsForSourceRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -2693,6 +3045,26 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "DeleteMapping",
|
||||
Handler: _StateStoreService_DeleteMapping_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "RecordMappingMatch",
|
||||
Handler: _StateStoreService_RecordMappingMatch_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "InsertEventType",
|
||||
Handler: _StateStoreService_InsertEventType_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "UpdateEventType",
|
||||
Handler: _StateStoreService_UpdateEventType_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "DeleteEventType",
|
||||
Handler: _StateStoreService_DeleteEventType_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ListEventTypes",
|
||||
Handler: _StateStoreService_ListEventTypes_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "InsertBinding",
|
||||
Handler: _StateStoreService_InsertBinding_Handler,
|
||||
@@ -2717,6 +3089,26 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "ApproveBinding",
|
||||
Handler: _StateStoreService_ApproveBinding_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "InsertSource",
|
||||
Handler: _StateStoreService_InsertSource_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetSource",
|
||||
Handler: _StateStoreService_GetSource_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ListSources",
|
||||
Handler: _StateStoreService_ListSources_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SetSourceSigning",
|
||||
Handler: _StateStoreService_SetSourceSigning_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SetSourceSecret",
|
||||
Handler: _StateStoreService_SetSourceSecret_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ArmedBindingsForSource",
|
||||
Handler: _StateStoreService_ArmedBindingsForSource_Handler,
|
||||
|
||||
+74
-56
@@ -9,6 +9,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -120,6 +121,9 @@ type Daemon struct {
|
||||
// BindingStore to keep the CRUD interface under the interfacebloat
|
||||
// limit. Optional: nil disables the dispatch loop.
|
||||
BindingDispatcher storecontract.BindingDispatcher
|
||||
// MappingMatches counts each event a mapping resolved at dispatch.
|
||||
// Optional: nil leaves match counts unrecorded.
|
||||
MappingMatches storecontract.MappingMatchRecorder
|
||||
// BindingTaskCreator enqueues a task triggered by a binding. Split
|
||||
// off TaskLifecycle so the lifecycle surface stays narrow and the
|
||||
// dispatch loop does not acquire the full task-creation contract.
|
||||
@@ -611,30 +615,18 @@ func (d *Daemon) cleanupExpiredStorage(ctx context.Context) {
|
||||
// single cycle's worst-case latency on a backlog.
|
||||
const bindingDispatchBatchLimit = 100
|
||||
|
||||
// dispatchBindings walks authenticated captures whose source has at
|
||||
// least one armed binding, evaluates each binding's matcher against
|
||||
// the capture, resolves fields through the binding's mapping, and
|
||||
// enqueues a task per matched (binding, capture) pair.
|
||||
// dispatchBindings walks identified captures on sources with an armed
|
||||
// binding and offers each capture to every armed binding on its source.
|
||||
// Each binding dispatches it at most once (dispatchOneBinding).
|
||||
//
|
||||
// The binding_dispatches ledger is the at-most-once guarantee across
|
||||
// cycles and daemon restarts: RecordDispatch returns
|
||||
// storecontract.ErrAlreadyDispatched on a duplicate (binding_id, capture_id)
|
||||
// pair, and dispatchOneBinding treats that as a normal "another cycle
|
||||
// raced us" outcome rather than an error.
|
||||
//
|
||||
// Nil Bindings, BindingDispatcher or BindingTaskCreator disables the
|
||||
// loop (legacy behaviour: daemons built before t2db.4 Phase E had no
|
||||
// playbook bindings, and each field's own doc comment promises this
|
||||
// degrade-not-panic contract independently).
|
||||
// Nil Bindings, BindingDispatcher or BindingTaskCreator disables the loop.
|
||||
func (d *Daemon) dispatchBindings(ctx context.Context) {
|
||||
if d.Bindings == nil || d.BindingDispatcher == nil || d.BindingTaskCreator == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Gather armed sources first so the captures query filters down to
|
||||
// only relevant rows -- the table-level view over captured_events
|
||||
// is otherwise unbounded, and a backlog of unrelated sources
|
||||
// should never be scanned on a cycle.
|
||||
// only relevant rows.
|
||||
bindings, err := d.Bindings.ListBindings(ctx)
|
||||
if err != nil {
|
||||
d.Log.Warn("list bindings failed", "error", err)
|
||||
@@ -662,7 +654,7 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
for _, b := range armed {
|
||||
if !b.Matcher.Matches(c.Source, c.Authenticated) {
|
||||
if !b.Matcher.Matches(c.Source, c.Dispatchable()) {
|
||||
continue
|
||||
}
|
||||
d.dispatchOneBinding(ctx, b, c)
|
||||
@@ -670,45 +662,54 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchOneBinding handles a single (binding, capture) match: resolve
|
||||
// fields through the binding's mapping, enqueue a task, and record the
|
||||
// dispatch in the dedup ledger. Each step degrades independently --
|
||||
// a mapping lookup failure logs and returns, a required-field
|
||||
// resolution failure records a binding_dispatch_failure event and
|
||||
// returns without enqueueing, an enqueue failure logs and returns, and
|
||||
// a RecordDispatch returning ErrAlreadyDispatched is treated as a
|
||||
// benign race winner (another cycle already created the task).
|
||||
//
|
||||
// Owner/repo resolution currently falls back to the single configured
|
||||
// repo (when exactly one is configured); binding.Owner/Repo is a
|
||||
// follow-up so multi-repo deployments don't have to live with the
|
||||
// ambiguity.
|
||||
func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent) {
|
||||
// bindingMapping returns b's mapping, or nil after logging why it is
|
||||
// unavailable.
|
||||
func (d *Daemon) bindingMapping(ctx context.Context, b binding.Binding) *mapping.Mapping {
|
||||
if d.Mappings == nil {
|
||||
d.Log.Warn("binding dispatch: mapping store unavailable", "binding", b.ID)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
m, err := d.Mappings.GetMapping(ctx, b.MappingID)
|
||||
if err != nil {
|
||||
d.Log.Warn("binding dispatch: get mapping", "binding", b.ID, "mapping", b.MappingID, "error", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
if m == nil {
|
||||
d.Log.Warn("binding dispatch: mapping missing", "binding", b.ID, "mapping", b.MappingID)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// dispatchOneBinding offers one capture to one binding. The binding applies
|
||||
// when its mapping belongs to the capture's event type. The mapping resolves
|
||||
// the payload (a required-field failure records binding_dispatch_failure and
|
||||
// stops), counts the match, and the binding's filter must admit the resolved
|
||||
// parameters. The dispatch is then claimed in the binding_dispatches ledger
|
||||
// before the task is enqueued: a capture stays listed until every binding for
|
||||
// its event type has dispatched it, so the claim is what stops a binding that
|
||||
// already fired from firing again on a later cycle. A failed enqueue after the
|
||||
// claim loses that dispatch, which is the at-most-once side of the trade.
|
||||
func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent) {
|
||||
m := d.bindingMapping(ctx, b)
|
||||
if m == nil || m.EventTypeID != c.EventType {
|
||||
return
|
||||
}
|
||||
values, failures := mapping.Resolve(m.Fields, []byte(c.Body))
|
||||
if hasBlockingFailure(m.Fields, failures) {
|
||||
_, _ = d.Store.InsertEvent(ctx, events.Event{
|
||||
Kind: "binding_dispatch_failure",
|
||||
Detail: fmt.Sprintf("binding %q (capture %q): required field failed", b.ID, c.ID),
|
||||
Data: map[string]any{
|
||||
"binding_id": b.ID,
|
||||
"binding_version": b.Version,
|
||||
"capture_id": c.ID,
|
||||
"failures": failures,
|
||||
},
|
||||
})
|
||||
d.recordDispatchFailure(ctx, b, c, "required field failed", map[string]any{"failures": failures})
|
||||
return
|
||||
}
|
||||
if d.MappingMatches != nil {
|
||||
if err := d.MappingMatches.RecordMappingMatch(ctx, m.ID, c.ID); err != nil {
|
||||
d.Log.Warn("binding dispatch: record mapping match", "mapping", m.ID, "capture", c.ID, "error", err)
|
||||
}
|
||||
}
|
||||
filter, err := binding.CompileFilter(b.Filter, m.Fields)
|
||||
if err != nil {
|
||||
d.recordDispatchFailure(ctx, b, c, "filter does not compile", map[string]any{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if admitted, _ := filter.Admits(values); !admitted {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -716,29 +717,46 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st
|
||||
if !ok {
|
||||
return // resolveBindingRepo already logged a warning
|
||||
}
|
||||
if err := d.BindingDispatcher.RecordDispatch(ctx, b.ID, int64(b.Version), c.ID, 0); err != nil {
|
||||
if !errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
d.Log.Warn("binding dispatch: record", "binding", b.ID, "capture", c.ID, "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
title := fmt.Sprintf("binding %s/%d from %s", b.Name, b.Version, c.Source)
|
||||
body := renderBindingBody(values, c)
|
||||
|
||||
task, err := d.BindingTaskCreator.EnqueueBindingTask(ctx, owner, repo, title, body, b.Workflow, "", b.ID, b.Version)
|
||||
if err != nil {
|
||||
d.Log.Warn("binding dispatch: enqueue", "binding", b.ID, "capture", c.ID, "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := d.BindingDispatcher.RecordDispatch(ctx, b.ID, int64(b.Version), c.ID, task.ID); err != nil {
|
||||
if errors.Is(err, storecontract.ErrAlreadyDispatched) {
|
||||
// Another cycle or daemon instance raced us and already
|
||||
// recorded the dispatch. The duplicate task remains
|
||||
// queued (delete-on-races is its own can of worms),
|
||||
// but the ledger prevents the same (binding, capture)
|
||||
// pair from ever being dispatched again.
|
||||
return
|
||||
if c.Unsigned {
|
||||
if _, err := d.Store.InsertEvent(ctx, events.Event{
|
||||
TaskID: task.ID,
|
||||
Kind: events.KindUnsignedEvent,
|
||||
Detail: fmt.Sprintf("started by an unsigned event from source %q", c.Source),
|
||||
Data: map[string]any{"source": c.Source, "capture_id": c.ID, "binding_id": b.ID},
|
||||
}); err != nil {
|
||||
d.Log.Warn("binding dispatch: unsigned marker", "task", task.ID, "error", err)
|
||||
}
|
||||
d.Log.Warn("binding dispatch: record", "binding", b.ID, "capture", c.ID, "error", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// recordDispatchFailure records why a binding did not dispatch a capture.
|
||||
func (d *Daemon) recordDispatchFailure(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent, reason string, extra map[string]any) {
|
||||
data := map[string]any{
|
||||
"binding_id": b.ID,
|
||||
"binding_version": b.Version,
|
||||
"capture_id": c.ID,
|
||||
}
|
||||
maps.Copy(data, extra)
|
||||
_, _ = d.Store.InsertEvent(ctx, events.Event{
|
||||
Kind: "binding_dispatch_failure",
|
||||
Detail: fmt.Sprintf("binding %q (capture %q): %s", b.ID, c.ID, reason),
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// hasBlockingFailure reports whether any of the failures belongs to a
|
||||
// required field. The mapping package reports failures only by field
|
||||
// name and reason -- the Field's Required flag is on the Field
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"testing"
|
||||
@@ -10,9 +11,11 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"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/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
@@ -50,7 +53,7 @@ func TestDispatchBindingsCreatesTaskFromArmedCapture(t *testing.T) {
|
||||
t.Errorf("task.Status = %q, want %q", got.Status, workflow.StatusQueued)
|
||||
}
|
||||
|
||||
assertDispatchRecorded(t, s, bindingID, got.ID)
|
||||
assertDispatchRecorded(t, s, bindingID)
|
||||
}
|
||||
|
||||
// TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos is the
|
||||
@@ -80,7 +83,7 @@ func TestDispatchBindingsUsesBindingRepoPinWithMultipleConfiguredRepos(t *testin
|
||||
if tasks[0].Owner != "acme" || tasks[0].Repo != "widget" {
|
||||
t.Fatalf("task owner/repo = %s/%s, want acme/widget (the binding's own pin, not a guess)", tasks[0].Owner, tasks[0].Repo)
|
||||
}
|
||||
assertDispatchRecorded(t, s, bindingID, tasks[0].ID)
|
||||
assertDispatchRecorded(t, s, bindingID)
|
||||
}
|
||||
|
||||
// TestDispatchBindingsRefusesUnpinnedBindingWithMultipleConfiguredRepos
|
||||
@@ -152,6 +155,48 @@ func TestDispatchBindingsSkipsUnauthenticatedCaptures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// markUnsigned reports every undispatched capture as taken on an approved
|
||||
// unsigned source, which the legacy capture store cannot persist.
|
||||
type markUnsigned struct {
|
||||
storecontract.BindingDispatcher
|
||||
}
|
||||
|
||||
func (m markUnsigned) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) {
|
||||
cs, err := m.BindingDispatcher.ListUndispatchedCaptures(ctx, sources, limit)
|
||||
for i := range cs {
|
||||
cs[i].Unsigned = true
|
||||
}
|
||||
return cs, err
|
||||
}
|
||||
|
||||
// An event on an approved unsigned source dispatches without a signature,
|
||||
// and the task it starts carries an unsigned_event on its timeline.
|
||||
func TestDispatchBindingsDispatchesUnsignedCaptureAndMarksTimeline(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "fw", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString})
|
||||
seedArmedBinding(t, s, "fw", mappingID)
|
||||
seedCapture(t, s, "fw", false, `{"title":"blocked"}`)
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
d.BindingDispatcher = markUnsigned{d.BindingDispatcher}
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil || len(tasks) != 1 {
|
||||
t.Fatalf("Tasks = %d (err %v), want 1", len(tasks), err)
|
||||
}
|
||||
evs, err := s.TaskEvents(t.Context(), tasks[0].ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
for _, e := range evs {
|
||||
if e.Kind == events.KindUnsignedEvent {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("task timeline has no %s event: %+v", events.KindUnsignedEvent, evs)
|
||||
}
|
||||
|
||||
// Test 33: a required field whose path is missing in the capture body
|
||||
// blocks the dispatch -- the failure path emits a
|
||||
// binding_dispatch_failure event and creates no task.
|
||||
@@ -253,8 +298,6 @@ type dispatchStores struct {
|
||||
edaPool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// openDispatchTestStore opens fresh migrated task and event-capture stores for
|
||||
// each dispatch test.
|
||||
func openDispatchTestStore(t *testing.T) *dispatchStores {
|
||||
t.Helper()
|
||||
s := pgstore.Open(t)
|
||||
@@ -264,14 +307,20 @@ func openDispatchTestStore(t *testing.T) *dispatchStores {
|
||||
}
|
||||
|
||||
// seedMapping inserts a mapping with the given fields and returns its id.
|
||||
// The Name field is "sentry-mapping" by default; callers pass fields
|
||||
// inline.
|
||||
// The mapping belongs to a catch-all event type on sourceHint, so every
|
||||
// capture later inserted on that source is identified as its type and
|
||||
// dispatches.
|
||||
func seedMapping(t *testing.T, s *dispatchStores, sourceHint string, fields ...mapping.Field) string {
|
||||
t.Helper()
|
||||
eventTypeID, err := s.EdaStore.InsertEventType(t.Context(), eventtype.EventType{Source: sourceHint, Name: "any"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType: %v", err)
|
||||
}
|
||||
id, err := s.EdaStore.InsertMapping(t.Context(), mapping.Mapping{
|
||||
Name: sourceHint + "-mapping",
|
||||
SourceHint: sourceHint,
|
||||
Fields: fields,
|
||||
Name: sourceHint + "-mapping",
|
||||
SourceHint: sourceHint,
|
||||
EventTypeID: eventTypeID,
|
||||
Fields: fields,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping: %v", err)
|
||||
@@ -300,7 +349,6 @@ func seedArmedBindingWithRepo(t *testing.T, s *dispatchStores, source, mappingID
|
||||
Workflow: "implement",
|
||||
Owner: owner,
|
||||
Repo: repo,
|
||||
Secret: "0123456789abcdef0123456789abcdef",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding: %v", err)
|
||||
@@ -362,22 +410,15 @@ func newDispatchDaemonWithRepos(t *testing.T, s *dispatchStores, repos []config.
|
||||
}
|
||||
}
|
||||
|
||||
// assertDispatchRecorded reads the dedup ledger directly: the
|
||||
// (binding, capture) unique index is what guarantees no double
|
||||
// dispatch. Going through the SQL table rather than the public
|
||||
// BindingStore surface keeps the assertion focused on the contract
|
||||
// Phase E actually writes to, not on a ListDispatches helper that
|
||||
// may not exist.
|
||||
func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string, taskID int64) {
|
||||
// assertDispatchRecorded reads the dedup ledger directly: the (binding,
|
||||
// capture) unique index is what guarantees no double dispatch. The dispatch
|
||||
// is claimed before its task exists, so the row carries no task id.
|
||||
func assertDispatchRecorded(t *testing.T, s *dispatchStores, bindingID string) {
|
||||
t.Helper()
|
||||
var gotBindingID string
|
||||
var gotTaskID int64
|
||||
if err := s.edaPool.QueryRow(t.Context(),
|
||||
"SELECT binding, task_id FROM binding_dispatches WHERE binding = $1", bindingID).
|
||||
Scan(&gotBindingID, &gotTaskID); err != nil {
|
||||
"SELECT binding FROM binding_dispatches WHERE binding = $1", bindingID).
|
||||
Scan(&gotBindingID); err != nil {
|
||||
t.Fatalf("binding_dispatches row missing: %v", err)
|
||||
}
|
||||
if gotBindingID != bindingID || gotTaskID != taskID {
|
||||
t.Fatalf("binding_dispatches row = (%q, %d), want (%q, %d)", gotBindingID, gotTaskID, bindingID, taskID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
)
|
||||
|
||||
// fakeEDA serves bindings, mappings and one capture from memory, and records
|
||||
// dispatches and mapping matches the way the store's unique keys do.
|
||||
type fakeEDA struct {
|
||||
bindings []binding.Binding
|
||||
mappings map[string]mapping.Mapping
|
||||
captures []storecontract.CapturedEvent
|
||||
dispatched map[[2]string]bool
|
||||
matches map[[2]string]bool
|
||||
}
|
||||
|
||||
func (f *fakeEDA) InsertMapping(context.Context, mapping.Mapping) (string, error) { return "", nil }
|
||||
func (f *fakeEDA) GetMapping(_ context.Context, id string) (*mapping.Mapping, error) {
|
||||
m, ok := f.mappings[id]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
func (f *fakeEDA) ListMappings(context.Context) ([]mapping.Mapping, error) { return nil, nil }
|
||||
func (f *fakeEDA) UpdateMapping(context.Context, mapping.Mapping) error { return nil }
|
||||
func (f *fakeEDA) DeleteMapping(context.Context, string) error { return nil }
|
||||
|
||||
func (f *fakeEDA) InsertBinding(context.Context, binding.Binding) (string, error) { return "", nil }
|
||||
func (f *fakeEDA) GetBinding(context.Context, string) (*binding.Binding, error) { return nil, nil }
|
||||
|
||||
func (f *fakeEDA) ListBindings(context.Context) ([]binding.Binding, error) { return f.bindings, nil }
|
||||
func (f *fakeEDA) UpdateBinding(context.Context, binding.Binding) error { return nil }
|
||||
func (f *fakeEDA) DeleteBinding(context.Context, string) error { return nil }
|
||||
func (f *fakeEDA) ApproveBinding(context.Context, string) error { return nil }
|
||||
|
||||
func (f *fakeEDA) ArmedBindingsForSource(_ context.Context, source string) ([]binding.Binding, error) {
|
||||
var out []binding.Binding
|
||||
for _, b := range f.bindings {
|
||||
if b.Status == binding.StatusArmed && b.Matcher.Source == source {
|
||||
out = append(out, b)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeEDA) RecordDispatch(_ context.Context, bindingID string, _ int64, captureID string, _ int64) error {
|
||||
key := [2]string{bindingID, captureID}
|
||||
if f.dispatched[key] {
|
||||
return storecontract.ErrAlreadyDispatched
|
||||
}
|
||||
f.dispatched[key] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeEDA) ListUndispatchedCaptures(context.Context, []string, int) ([]storecontract.CapturedEvent, error) {
|
||||
return f.captures, nil
|
||||
}
|
||||
|
||||
func (f *fakeEDA) RecordMappingMatch(_ context.Context, mappingID, captureID string) error {
|
||||
f.matches[[2]string{mappingID, captureID}] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func armed(id, mappingID, filter string) binding.Binding {
|
||||
return binding.Binding{
|
||||
ID: id, Name: id, Matcher: binding.Matcher{Source: "fw"}, MappingID: mappingID,
|
||||
Filter: filter, Workflow: "implement", Status: binding.StatusArmed, Version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
func severityMapping(id, eventType string) mapping.Mapping {
|
||||
return mapping.Mapping{
|
||||
ID: id, Name: id, EventTypeID: eventType,
|
||||
Fields: []mapping.Field{{Name: "severity", Path: "severity", Type: mapping.TypeString, Required: true}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchPerBindingByEventTypeAndFilter(t *testing.T) {
|
||||
capture := storecontract.CapturedEvent{
|
||||
ID: "c1", Source: "fw", EventType: "blocked", Authenticated: true, Body: `{"severity":"high"}`,
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
bindings []binding.Binding
|
||||
mappings []mapping.Mapping
|
||||
wantTasks []string
|
||||
wantMatches [][2]string
|
||||
}{
|
||||
{
|
||||
name: "several bindings on one source each dispatch once",
|
||||
bindings: []binding.Binding{armed("a", "m", ""), armed("b", "m", "")},
|
||||
mappings: []mapping.Mapping{severityMapping("m", "blocked")},
|
||||
wantTasks: []string{"a", "b"},
|
||||
wantMatches: [][2]string{{"m", "c1"}},
|
||||
},
|
||||
{
|
||||
name: "a binding for another event type does not dispatch",
|
||||
bindings: []binding.Binding{armed("a", "m", "")},
|
||||
mappings: []mapping.Mapping{severityMapping("m", "allowed")},
|
||||
},
|
||||
{
|
||||
name: "a filter that excludes the event does not dispatch it",
|
||||
bindings: []binding.Binding{armed("a", "m", `severity == "low"`), armed("b", "m", `severity in ["high", "critical"]`)},
|
||||
mappings: []mapping.Mapping{severityMapping("m", "blocked")},
|
||||
wantTasks: []string{"b"},
|
||||
wantMatches: [][2]string{{"m", "c1"}},
|
||||
},
|
||||
{
|
||||
name: "a filter that does not compile does not dispatch",
|
||||
bindings: []binding.Binding{armed("a", "m", `nope ==`)},
|
||||
mappings: []mapping.Mapping{severityMapping("m", "blocked")},
|
||||
// The mapping still resolved the event.
|
||||
wantMatches: [][2]string{{"m", "c1"}},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
st := pgstore.Open(t)
|
||||
eda := &fakeEDA{
|
||||
bindings: tt.bindings, mappings: map[string]mapping.Mapping{},
|
||||
captures: []storecontract.CapturedEvent{capture},
|
||||
dispatched: map[[2]string]bool{}, matches: map[[2]string]bool{},
|
||||
}
|
||||
for _, m := range tt.mappings {
|
||||
eda.mappings[m.ID] = m
|
||||
}
|
||||
d := &Daemon{
|
||||
Cfg: config.NewHolder(config.Config{Repos: []config.Repo{{Owner: "acme", Name: "widget"}}}),
|
||||
Store: st, Mappings: eda, Bindings: eda, BindingDispatcher: eda, MappingMatches: eda,
|
||||
BindingTaskCreator: st,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
d.dispatchBindings(t.Context())
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := st.Tasks(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
got := map[string]int{}
|
||||
for _, task := range tasks {
|
||||
got[task.BindingID]++
|
||||
}
|
||||
if len(tasks) != len(tt.wantTasks) {
|
||||
t.Fatalf("tasks by binding = %v, want one each for %v", got, tt.wantTasks)
|
||||
}
|
||||
for _, id := range tt.wantTasks {
|
||||
if got[id] != 1 {
|
||||
t.Fatalf("tasks by binding = %v, want one each for %v", got, tt.wantTasks)
|
||||
}
|
||||
}
|
||||
if len(eda.matches) != len(tt.wantMatches) {
|
||||
t.Fatalf("mapping matches = %v, want %v", eda.matches, tt.wantMatches)
|
||||
}
|
||||
for _, key := range tt.wantMatches {
|
||||
if !eda.matches[key] {
|
||||
t.Fatalf("mapping matches = %v, want %v", eda.matches, tt.wantMatches)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -34,19 +34,22 @@ type Matcher struct {
|
||||
// Binding is the runtime-editable entity that ties a matcher, a payload
|
||||
// mapping, and a workflow together. Bindings live in the store, not in
|
||||
// config.toml, so operators can author them from the dashboard while the
|
||||
// daemon runs.
|
||||
// daemon runs. Any number of bindings may share a source: each one applies to
|
||||
// the event type its mapping belongs to.
|
||||
//
|
||||
// Version is bumped on every UpdateBinding so a later edit cannot
|
||||
// silently rewrite the historical provenance of a task that already
|
||||
// fired. Secret is the HMAC-SHA256 shared secret a sender must sign with
|
||||
// for an event to be marked authenticated; it is never returned by
|
||||
// GET handlers.
|
||||
// fired. Signing belongs to the source the matcher names, not to the
|
||||
// binding (internal/domain/source).
|
||||
type Binding struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Matcher Matcher `json:"matcher"`
|
||||
MappingID string `json:"mapping_id"`
|
||||
Workflow string `json:"workflow"`
|
||||
// Filter is an optional CEL expression over the mapping's parameters
|
||||
// (CompileFilter). An event it excludes is not dispatched.
|
||||
Filter string `json:"filter,omitempty"`
|
||||
Workflow string `json:"workflow"`
|
||||
// Owner and Repo pin a binding to a specific configured repo, so a
|
||||
// multi-repo deployment can dispatch correctly. Both empty means "no
|
||||
// pin" -- resolveBindingRepo falls back to the single-configured-repo
|
||||
@@ -57,52 +60,15 @@ type Binding struct {
|
||||
Repo string `json:"repo,omitempty"`
|
||||
Version int `json:"version"`
|
||||
Status Status `json:"status"`
|
||||
Secret string `json:"secret,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// minSecretLen is the floor for an acceptable shared secret. A trivially
|
||||
// short secret makes accidental binding to a known HMAC trivial; the
|
||||
// floor is chosen so a one-character typo cannot arm.
|
||||
const minSecretLen = 16
|
||||
|
||||
// Validate checks a binding is well-formed before it is newly persisted.
|
||||
// A non-empty Name, a non-empty Matcher.Source, a positive MappingID, a
|
||||
// non-empty Workflow, and a sufficiently long Secret are all required.
|
||||
// Workflow existence is checked at the API/store layer because the domain
|
||||
// package does not import the workflow registry. Use ValidateForUpdate
|
||||
// instead when editing an existing binding, where an empty Secret is a
|
||||
// meaningful "keep the current one," not a missing value.
|
||||
// Validate checks a binding is well-formed before it is persisted: a
|
||||
// non-empty Name, Matcher.Source, MappingID and Workflow, and a complete
|
||||
// owner/repo pin or none. Workflow existence is checked at the API/store
|
||||
// layer because the domain package does not import the workflow registry.
|
||||
func (b Binding) Validate() error {
|
||||
if err := b.validateCommon(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(b.Secret) < minSecretLen {
|
||||
return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateForUpdate is Validate for the edit path: every other field is
|
||||
// checked identically, but Secret is only length-checked when the caller
|
||||
// actually supplied one. UpdateBinding's own store-layer contract already
|
||||
// treats an empty Secret as "preserve the existing one" (COALESCE against
|
||||
// NULLIF) -- rejecting that here at the validation gate before the store
|
||||
// ever sees it would make the store's own documented behavior
|
||||
// unreachable. A non-empty Secret (a genuine change) is still held to the
|
||||
// same floor Validate enforces.
|
||||
func (b Binding) ValidateForUpdate() error {
|
||||
if err := b.validateCommon(); err != nil {
|
||||
return err
|
||||
}
|
||||
if b.Secret != "" && len(b.Secret) < minSecretLen {
|
||||
return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b Binding) validateCommon() error {
|
||||
if strings.TrimSpace(b.Name) == "" {
|
||||
return fmt.Errorf("binding: name is required")
|
||||
}
|
||||
@@ -121,18 +87,10 @@ func (b Binding) validateCommon() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Matches reports whether the given captured event would match this
|
||||
// binding's matcher. The Authenticated clause encodes t2db.5 point 1 --
|
||||
// an unauthenticated event can never trigger a binding, no matter how
|
||||
// well it would otherwise match.
|
||||
//
|
||||
// Note: the caller is expected to be the dispatch loop or the capture
|
||||
// intake receiver, both of which receive a CapturedEvent with the
|
||||
// Authenticated flag already set by HMAC verification. Matches is pure
|
||||
// and has no I/O.
|
||||
func (m Matcher) Matches(source string, authenticated bool) bool {
|
||||
if !authenticated {
|
||||
return false
|
||||
}
|
||||
return m.Source == source
|
||||
// Matches reports whether a captured event would trigger this binding. An
|
||||
// event that is not dispatchable (no valid signature, and not from an
|
||||
// approved unsigned source) never matches, however well it would otherwise.
|
||||
// Matches is pure and has no I/O.
|
||||
func (m Matcher) Matches(source string, dispatchable bool) bool {
|
||||
return dispatchable && m.Source == source
|
||||
}
|
||||
@@ -8,7 +8,6 @@ func validBinding() Binding {
|
||||
Matcher: Matcher{Source: "sentry"},
|
||||
MappingID: "m1",
|
||||
Workflow: "implement",
|
||||
Secret: "0123456789abcdef0123456789abcdef",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,47 +32,6 @@ func TestValidateAcceptsBothOwnerAndRepo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateRejectsPartialRepoPin: Owner and Repo are a pair. A
|
||||
// binding naming only one of them is ambiguous -- it isn't "no pin"
|
||||
// (that's both empty) and it isn't a complete pin, so it must be
|
||||
// rejected at validation time rather than silently guessing which
|
||||
// half was meant.
|
||||
// TestValidateForUpdateAcceptsEmptySecret is the fix for a real bug found
|
||||
// via browser testing (t2db.8): UpdateBinding's own documented contract
|
||||
// treats an empty Secret as "preserve the existing one" (COALESCE against
|
||||
// NULLIF), but the API handler validated with the create-time Validate,
|
||||
// which rejected any edit that didn't retype the full secret -- making
|
||||
// the store's own documented behavior unreachable.
|
||||
func TestValidateForUpdateAcceptsEmptySecret(t *testing.T) {
|
||||
b := validBinding()
|
||||
b.Secret = ""
|
||||
if err := b.ValidateForUpdate(); err != nil {
|
||||
t.Fatalf("ValidateForUpdate() = %v, want nil for an empty (preserve-existing) secret", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateForUpdateStillEnforcesLengthOnANewSecret confirms the fix
|
||||
// isn't a blanket bypass: a genuinely-supplied short secret on update is
|
||||
// still rejected, same floor as create.
|
||||
func TestValidateForUpdateStillEnforcesLengthOnANewSecret(t *testing.T) {
|
||||
b := validBinding()
|
||||
b.Secret = "short"
|
||||
if err := b.ValidateForUpdate(); err == nil {
|
||||
t.Fatal("ValidateForUpdate() = nil, want error for a too-short (but non-empty) secret")
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateRejectsEmptySecretOnCreate pins that the fix is scoped to
|
||||
// update only -- Validate (used at create time, where there is no
|
||||
// existing secret to fall back to) still requires a real one.
|
||||
func TestValidateRejectsEmptySecretOnCreate(t *testing.T) {
|
||||
b := validBinding()
|
||||
b.Secret = ""
|
||||
if err := b.Validate(); err == nil {
|
||||
t.Fatal("Validate() = nil, want error for an empty secret at create time")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsPartialRepoPin(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -92,3 +50,21 @@ func TestValidateRejectsPartialRepoPin(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatcherMatchesOnlyDispatchableEventsFromItsSource(t *testing.T) {
|
||||
m := Matcher{Source: "sentry"}
|
||||
tests := []struct {
|
||||
source string
|
||||
dispatchable bool
|
||||
want bool
|
||||
}{
|
||||
{"sentry", true, true},
|
||||
{"sentry", false, false},
|
||||
{"other", true, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := m.Matches(tt.source, tt.dispatchable); got != tt.want {
|
||||
t.Errorf("Matches(%q, %v) = %v, want %v", tt.source, tt.dispatchable, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package binding
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"cel.dev/cel-go/cel"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/expr"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
)
|
||||
|
||||
// Filter is a compiled binding filter: a CEL expression over the mapping's
|
||||
// named parameters, each declared as a variable of its field type
|
||||
// (`severity in ["high", "critical"]`). A nil Filter admits every event.
|
||||
type Filter struct {
|
||||
prg cel.Program
|
||||
}
|
||||
|
||||
// CompileFilter checks src against the mapping's fields and compiles it. An
|
||||
// empty src is no filter. A reference to a parameter the mapping lacks, a type
|
||||
// error, or a non-boolean result is refused.
|
||||
func CompileFilter(src string, fields []mapping.Field) (*Filter, error) {
|
||||
if strings.TrimSpace(src) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
opts := make([]cel.EnvOption, 0, len(fields))
|
||||
for _, f := range fields {
|
||||
opts = append(opts, cel.Variable(f.Name, celType(f.Type)))
|
||||
}
|
||||
env, err := cel.NewEnv(opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("binding: filter: %w", err)
|
||||
}
|
||||
ast, issues := env.Compile(src)
|
||||
if issues != nil && issues.Err() != nil {
|
||||
return nil, fmt.Errorf("binding: filter: %w", issues.Err())
|
||||
}
|
||||
if !ast.OutputType().IsExactType(cel.BoolType) {
|
||||
return nil, fmt.Errorf("binding: filter must be a boolean, not %s", ast.OutputType())
|
||||
}
|
||||
prg, err := env.Program(ast, cel.CostLimit(expr.DefaultCostLimit))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("binding: filter: %w", err)
|
||||
}
|
||||
return &Filter{prg: prg}, nil
|
||||
}
|
||||
|
||||
// Admits evaluates the filter over resolved parameter values. An evaluation
|
||||
// error, such as a parameter that did not resolve, excludes the event.
|
||||
func (f *Filter) Admits(values map[string]any) (bool, error) {
|
||||
if f == nil {
|
||||
return true, nil
|
||||
}
|
||||
v, _, err := f.prg.Eval(values)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("binding: filter: %w", err)
|
||||
}
|
||||
admitted, _ := v.Value().(bool)
|
||||
return admitted, nil
|
||||
}
|
||||
|
||||
func celType(t mapping.FieldType) *cel.Type {
|
||||
switch t {
|
||||
case mapping.TypeString:
|
||||
return cel.StringType
|
||||
case mapping.TypeNumber:
|
||||
return cel.DoubleType
|
||||
case mapping.TypeBool:
|
||||
return cel.BoolType
|
||||
case mapping.TypeObject:
|
||||
return cel.MapType(cel.StringType, cel.DynType)
|
||||
case mapping.TypeArray:
|
||||
return cel.ListType(cel.DynType)
|
||||
default:
|
||||
return cel.DynType
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package binding
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
)
|
||||
|
||||
var filterFields = []mapping.Field{
|
||||
{Name: "severity", Path: "severity", Type: mapping.TypeString},
|
||||
{Name: "count", Path: "count", Type: mapping.TypeNumber},
|
||||
{Name: "urgent", Path: "urgent", Type: mapping.TypeBool},
|
||||
{Name: "extra", Path: "extra", Type: mapping.TypeAny},
|
||||
}
|
||||
|
||||
func TestCompileFilterRefuses(t *testing.T) {
|
||||
tests := []struct{ name, src string }{
|
||||
{"unknown parameter", `sender == "x"`},
|
||||
{"not boolean", `severity`},
|
||||
{"type mismatch", `count == "3"`},
|
||||
{"syntax", `severity in [`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, err := CompileFilter(tt.src, filterFields); err == nil {
|
||||
t.Fatalf("CompileFilter(%q) = nil error, want refusal", tt.src)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterAdmits(t *testing.T) {
|
||||
values := map[string]any{"severity": "high", "count": float64(3), "urgent": true, "extra": "x"}
|
||||
tests := []struct {
|
||||
name string
|
||||
src string
|
||||
values map[string]any
|
||||
want bool
|
||||
}{
|
||||
{"empty filter admits everything", "", values, true},
|
||||
{"list membership admits", `severity in ["high", "critical"]`, values, true},
|
||||
{"list membership excludes", `severity in ["critical"]`, values, false},
|
||||
{"number comparison", `count > 2.0 && urgent`, values, true},
|
||||
{"dyn parameter", `extra == "x"`, values, true},
|
||||
{"unresolved parameter excludes", `severity == "high"`, map[string]any{"count": float64(1)}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f, err := CompileFilter(tt.src, filterFields)
|
||||
if err != nil {
|
||||
t.Fatalf("CompileFilter: %v", err)
|
||||
}
|
||||
got, _ := f.Admits(tt.values)
|
||||
if got != tt.want {
|
||||
t.Fatalf("Admits = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
// Package eventtype owns event types: named kinds of event from one source,
|
||||
// each defined by a match rule over headers and payload. It infers a
|
||||
// structural signature per capture, groups a source's captures into proposed
|
||||
// types, evaluates rules, and refuses two types on one source whose rules can
|
||||
// match the same event. An event that matches no type is unidentified and is
|
||||
// never dispatched. See docs/prds/event-automation.md, "Event types".
|
||||
package eventtype
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalid marks an event type that cannot be saved as written.
|
||||
ErrInvalid = errors.New("eventtype: invalid event type")
|
||||
// ErrOverlap marks an event type whose rule can match an event another
|
||||
// type on the same source also matches.
|
||||
ErrOverlap = errors.New("eventtype: rule overlaps another event type on the source")
|
||||
)
|
||||
|
||||
// Operator is a payload condition's test.
|
||||
type Operator string
|
||||
|
||||
const (
|
||||
OpEquals Operator = "equals"
|
||||
OpPresent Operator = "present"
|
||||
)
|
||||
|
||||
// HeaderCondition holds when the named header (case-insensitive) has Value.
|
||||
type HeaderCondition struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// PayloadCondition holds when Path is present or, for OpEquals, when a value
|
||||
// at Path renders as Value ("7", "true", "null", or the string itself).
|
||||
type PayloadCondition struct {
|
||||
Path string `json:"path"`
|
||||
Op Operator `json:"op"`
|
||||
Value string `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
// Rule is a conjunction: every condition must hold. An empty rule matches
|
||||
// every event from its source.
|
||||
type Rule struct {
|
||||
Headers []HeaderCondition `json:"headers"`
|
||||
Payload []PayloadCondition `json:"payload"`
|
||||
}
|
||||
|
||||
// EventType is a named kind of event from one source. Schema is the inferred
|
||||
// structure (path to type) of the payload it was created from.
|
||||
type EventType struct {
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"`
|
||||
Name string `json:"name"`
|
||||
Rule Rule `json:"rule"`
|
||||
Schema map[string]ValueType `json:"schema"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Validate refuses an event type that has no name or source or carries a
|
||||
// malformed condition.
|
||||
func (t EventType) Validate() error {
|
||||
if strings.TrimSpace(t.Name) == "" {
|
||||
return fmt.Errorf("%w: name is required", ErrInvalid)
|
||||
}
|
||||
if strings.TrimSpace(t.Source) == "" {
|
||||
return fmt.Errorf("%w: source is required", ErrInvalid)
|
||||
}
|
||||
for _, h := range t.Rule.Headers {
|
||||
if strings.TrimSpace(h.Name) == "" {
|
||||
return fmt.Errorf("%w: header condition has no name", ErrInvalid)
|
||||
}
|
||||
}
|
||||
for _, p := range t.Rule.Payload {
|
||||
if strings.TrimSpace(p.Path) == "" {
|
||||
return fmt.Errorf("%w: payload condition has no path", ErrInvalid)
|
||||
}
|
||||
if p.Op != OpEquals && p.Op != OpPresent {
|
||||
return fmt.Errorf("%w: unknown operator %q", ErrInvalid, p.Op)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Matches reports whether every condition of r holds for s.
|
||||
func (r Rule) Matches(s Sample) bool {
|
||||
for _, h := range r.Headers {
|
||||
got, ok := headerLookup(s.Headers, h.Name)
|
||||
if !ok || headerValue(h.Name, got) != headerValue(h.Name, h.Value) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if len(r.Payload) == 0 {
|
||||
return true
|
||||
}
|
||||
root, ok := decode(s.Body)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for _, p := range r.Payload {
|
||||
if !payloadHolds(root, p) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func headerLookup(headers map[string]string, name string) (string, bool) {
|
||||
for k, v := range headers {
|
||||
if strings.EqualFold(k, name) {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func payloadHolds(root any, p PayloadCondition) bool {
|
||||
values := lookup(root, p.Path)
|
||||
if p.Op == OpPresent {
|
||||
return len(values) > 0
|
||||
}
|
||||
for _, v := range values {
|
||||
if text, ok := scalarText(v); ok && text == p.Value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Overlaps reports whether some event could satisfy both rules. Two rules are
|
||||
// disjoint only when they demand different values of one header, or different
|
||||
// values at one payload path outside any array; anything else is treated as
|
||||
// overlapping, which errs towards refusing a save rather than towards an event
|
||||
// two types both claim.
|
||||
func Overlaps(a, b Rule) bool {
|
||||
for _, ha := range a.Headers {
|
||||
for _, hb := range b.Headers {
|
||||
if strings.EqualFold(ha.Name, hb.Name) && headerValue(ha.Name, ha.Value) != headerValue(hb.Name, hb.Value) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, pa := range a.Payload {
|
||||
for _, pb := range b.Payload {
|
||||
if pa.Op == OpEquals && pb.Op == OpEquals && pa.Path == pb.Path &&
|
||||
!strings.Contains(pa.Path, "[]") && pa.Value != pb.Value {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// CheckOverlap refuses candidate when its rule overlaps another type on the
|
||||
// same source. A type is not compared with itself, so an update passes.
|
||||
func CheckOverlap(existing []EventType, candidate EventType) error {
|
||||
for _, t := range existing {
|
||||
if t.Source != candidate.Source || (candidate.ID != "" && t.ID == candidate.ID) {
|
||||
continue
|
||||
}
|
||||
if Overlaps(t.Rule, candidate.Rule) {
|
||||
return fmt.Errorf("%w: %q", ErrOverlap, t.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Identify returns the one type on source whose rule matches s. No match, or
|
||||
// more than one (which overlap refusal prevents), is unidentified.
|
||||
func Identify(types []EventType, source string, s Sample) (EventType, bool) {
|
||||
var found []EventType
|
||||
for _, t := range types {
|
||||
if t.Source == source && t.Rule.Matches(s) {
|
||||
found = append(found, t)
|
||||
}
|
||||
}
|
||||
if len(found) != 1 {
|
||||
return EventType{}, false
|
||||
}
|
||||
return found[0], true
|
||||
}
|
||||
|
||||
// FromExample builds an event type from a pasted payload: its schema is the
|
||||
// example's structure, and its rule is the example's discriminator headers or,
|
||||
// when it has none, the presence of each top-level payload key.
|
||||
func FromExample(source, name string, s Sample) EventType {
|
||||
sig := Sign(s)
|
||||
t := EventType{Source: source, Name: name, Schema: sig.Paths}
|
||||
t.Rule.Headers = headerConditions(sig.Headers)
|
||||
if len(t.Rule.Headers) == 0 {
|
||||
for _, path := range slices.Sorted(maps.Keys(sig.Paths)) {
|
||||
if !strings.ContainsAny(path, ".[") {
|
||||
t.Rule.Payload = append(t.Rule.Payload, PayloadCondition{Path: path, Op: OpPresent})
|
||||
}
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func headerConditions(headers map[string]string) []HeaderCondition {
|
||||
var out []HeaderCondition
|
||||
for _, name := range slices.Sorted(maps.Keys(headers)) {
|
||||
out = append(out, HeaderCondition{Name: name, Value: headers[name]})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package eventtype
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func sample(headers map[string]string, body string) Sample {
|
||||
return Sample{Headers: headers, Body: []byte(body)}
|
||||
}
|
||||
|
||||
func TestParseHeaders(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
want map[string]string
|
||||
}{
|
||||
{"http header json", `{"X-Github-Event":["push"],"Content-Type":["application/json"]}`, map[string]string{"x-github-event": "push", "content-type": "application/json"}},
|
||||
{"empty", ``, map[string]string{}},
|
||||
{"not json", `nope`, map[string]string{}},
|
||||
{"empty value list", `{"X-A":[]}`, map[string]string{}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := ParseHeaders(tt.raw); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Fatalf("ParseHeaders = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSign(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in Sample
|
||||
wantPaths map[string]ValueType
|
||||
wantHeaders map[string]string
|
||||
}{
|
||||
{
|
||||
name: "paths with types and discriminator headers",
|
||||
in: sample(map[string]string{
|
||||
"x-github-event": "pull_request",
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
"user-agent": "GitHub-Hookshot",
|
||||
}, `{"action":"opened","number":7,"draft":false,"pull_request":{"labels":[{"name":"x"}],"body":null},"tags":[]}`),
|
||||
wantPaths: map[string]ValueType{
|
||||
"action": TypeString,
|
||||
"number": TypeNumber,
|
||||
"draft": TypeBool,
|
||||
"pull_request": TypeObject,
|
||||
"pull_request.labels": TypeArray,
|
||||
"pull_request.labels[]": TypeObject,
|
||||
"pull_request.labels[].name": TypeString,
|
||||
"pull_request.body": TypeNull,
|
||||
"tags": TypeArray,
|
||||
},
|
||||
wantHeaders: map[string]string{"x-github-event": "pull_request", "content-type": "application/json"},
|
||||
},
|
||||
{
|
||||
name: "non-json body has no paths",
|
||||
in: sample(map[string]string{"x-kind-type": "blocked"}, `plain text`),
|
||||
wantPaths: map[string]ValueType{},
|
||||
wantHeaders: map[string]string{"x-kind-type": "blocked"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := Sign(tt.in)
|
||||
if !reflect.DeepEqual(got.Paths, tt.wantPaths) {
|
||||
t.Errorf("paths = %v, want %v", got.Paths, tt.wantPaths)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Headers, tt.wantHeaders) {
|
||||
t.Errorf("headers = %v, want %v", got.Headers, tt.wantHeaders)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignatureKeyIgnoresValuesButNotShape(t *testing.T) {
|
||||
a := Sign(sample(nil, `{"a":1,"b":"x"}`))
|
||||
b := Sign(sample(nil, `{"b":"y","a":2}`))
|
||||
c := Sign(sample(nil, `{"a":"1","b":"x"}`))
|
||||
if a.Key() != b.Key() {
|
||||
t.Errorf("same shape, different keys: %q vs %q", a.Key(), b.Key())
|
||||
}
|
||||
if a.Key() == c.Key() {
|
||||
t.Errorf("different types share key %q", a.Key())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuleMatches(t *testing.T) {
|
||||
ev := sample(map[string]string{"x-github-event": "pull_request", "content-type": "application/json; charset=utf-8"},
|
||||
`{"action":"opened","number":7,"merged":false,"labels":[{"name":"bug"},{"name":"ui"}]}`)
|
||||
tests := []struct {
|
||||
name string
|
||||
rule Rule
|
||||
want bool
|
||||
}{
|
||||
{"empty rule matches", Rule{}, true},
|
||||
{"header equal, name case-insensitive", Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "pull_request"}}}, true},
|
||||
{"header differs", Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "push"}}}, false},
|
||||
{"header absent", Rule{Headers: []HeaderCondition{{Name: "X-Gitea-Event", Value: "push"}}}, false},
|
||||
{"content type compared by media type", Rule{Headers: []HeaderCondition{{Name: "Content-Type", Value: "application/json"}}}, true},
|
||||
{"path equals string", Rule{Payload: []PayloadCondition{{Path: "action", Op: OpEquals, Value: "opened"}}}, true},
|
||||
{"path equals other string", Rule{Payload: []PayloadCondition{{Path: "action", Op: OpEquals, Value: "closed"}}}, false},
|
||||
{"path equals number", Rule{Payload: []PayloadCondition{{Path: "number", Op: OpEquals, Value: "7"}}}, true},
|
||||
{"path equals bool", Rule{Payload: []PayloadCondition{{Path: "merged", Op: OpEquals, Value: "false"}}}, true},
|
||||
{"path present", Rule{Payload: []PayloadCondition{{Path: "number", Op: OpPresent}}}, true},
|
||||
{"path missing", Rule{Payload: []PayloadCondition{{Path: "sender.login", Op: OpPresent}}}, false},
|
||||
{"array element equals", Rule{Payload: []PayloadCondition{{Path: "labels[].name", Op: OpEquals, Value: "ui"}}}, true},
|
||||
{"all conditions must hold", Rule{
|
||||
Headers: []HeaderCondition{{Name: "x-github-event", Value: "pull_request"}},
|
||||
Payload: []PayloadCondition{{Path: "action", Op: OpEquals, Value: "closed"}},
|
||||
}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tt.rule.Matches(ev); got != tt.want {
|
||||
t.Fatalf("Matches = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverlaps(t *testing.T) {
|
||||
gh := func(v string) HeaderCondition { return HeaderCondition{Name: "X-GitHub-Event", Value: v} }
|
||||
eq := func(p, v string) PayloadCondition { return PayloadCondition{Path: p, Op: OpEquals, Value: v} }
|
||||
present := func(p string) PayloadCondition { return PayloadCondition{Path: p, Op: OpPresent} }
|
||||
tests := []struct {
|
||||
name string
|
||||
a, b Rule
|
||||
want bool
|
||||
}{
|
||||
{"different header values are disjoint", Rule{Headers: []HeaderCondition{gh("push")}}, Rule{Headers: []HeaderCondition{gh("pull_request")}}, false},
|
||||
{"header names compared case-insensitively", Rule{Headers: []HeaderCondition{gh("push")}}, Rule{Headers: []HeaderCondition{{Name: "x-github-event", Value: "issues"}}}, false},
|
||||
{"same header overlaps", Rule{Headers: []HeaderCondition{gh("push")}}, Rule{Headers: []HeaderCondition{gh("push")}}, true},
|
||||
{"empty rule overlaps everything", Rule{}, Rule{Headers: []HeaderCondition{gh("push")}}, true},
|
||||
{"different equals on a path are disjoint", Rule{Payload: []PayloadCondition{eq("action", "opened")}}, Rule{Payload: []PayloadCondition{eq("action", "closed")}}, false},
|
||||
{"equals and present on one path overlap", Rule{Payload: []PayloadCondition{eq("action", "opened")}}, Rule{Payload: []PayloadCondition{present("action")}}, true},
|
||||
{"unrelated conditions overlap", Rule{Payload: []PayloadCondition{present("a")}}, Rule{Payload: []PayloadCondition{present("b")}}, true},
|
||||
{"array paths never prove disjointness", Rule{Payload: []PayloadCondition{eq("l[].n", "x")}}, Rule{Payload: []PayloadCondition{eq("l[].n", "y")}}, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := Overlaps(tt.a, tt.b); got != tt.want {
|
||||
t.Fatalf("Overlaps = %v, want %v", got, tt.want)
|
||||
}
|
||||
if got := Overlaps(tt.b, tt.a); got != tt.want {
|
||||
t.Fatalf("Overlaps (swapped) = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeValidate(t *testing.T) {
|
||||
ok := EventType{Source: "gh", Name: "push", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "push"}}}}
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*EventType)
|
||||
valid bool
|
||||
}{
|
||||
{"valid", func(*EventType) {}, true},
|
||||
{"missing name", func(e *EventType) { e.Name = " " }, false},
|
||||
{"missing source", func(e *EventType) { e.Source = "" }, false},
|
||||
{"header without name", func(e *EventType) { e.Rule.Headers = []HeaderCondition{{Value: "x"}} }, false},
|
||||
{"payload without path", func(e *EventType) { e.Rule.Payload = []PayloadCondition{{Op: OpPresent}} }, false},
|
||||
{"unknown operator", func(e *EventType) { e.Rule.Payload = []PayloadCondition{{Path: "a", Op: "like"}} }, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
e := ok
|
||||
e.Rule = Rule{Headers: append([]HeaderCondition(nil), ok.Rule.Headers...)}
|
||||
tt.mutate(&e)
|
||||
err := e.Validate()
|
||||
if (err == nil) != tt.valid {
|
||||
t.Fatalf("Validate = %v, valid want %v", err, tt.valid)
|
||||
}
|
||||
if err != nil && !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("Validate error %v is not ErrInvalid", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckOverlap(t *testing.T) {
|
||||
push := EventType{ID: "1", Source: "gh", Name: "push", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "push"}}}}
|
||||
tests := []struct {
|
||||
name string
|
||||
candidate EventType
|
||||
wantErr bool
|
||||
}{
|
||||
{"disjoint on same source", EventType{Source: "gh", Name: "pr", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "pull_request"}}}}, false},
|
||||
{"overlapping on same source", EventType{Source: "gh", Name: "any", Rule: Rule{}}, true},
|
||||
{"overlapping on another source", EventType{Source: "fw", Name: "any", Rule: Rule{}}, false},
|
||||
{"an update does not overlap itself", EventType{ID: "1", Source: "gh", Name: "push2", Rule: Rule{}}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := CheckOverlap([]EventType{push}, tt.candidate)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("CheckOverlap = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if err != nil && !errors.Is(err, ErrOverlap) {
|
||||
t.Fatalf("error %v is not ErrOverlap", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentify(t *testing.T) {
|
||||
types := []EventType{
|
||||
{ID: "push", Source: "gh", Name: "push", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "push"}}}},
|
||||
{ID: "pr", Source: "gh", Name: "pr", Rule: Rule{Headers: []HeaderCondition{{Name: "X-GitHub-Event", Value: "pull_request"}}}},
|
||||
{ID: "fw", Source: "fw", Name: "any", Rule: Rule{}},
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
in Sample
|
||||
want string
|
||||
}{
|
||||
{"matches its type", "gh", sample(map[string]string{"x-github-event": "push"}, `{}`), "push"},
|
||||
{"no type matches", "gh", sample(map[string]string{"x-github-event": "issues"}, `{}`), ""},
|
||||
{"types from other sources are ignored", "other", sample(nil, `{}`), ""},
|
||||
{"catch-all on its source", "fw", sample(nil, `{"x":1}`), "fw"},
|
||||
{"two matches is unidentified", "gh", sample(map[string]string{"x-github-event": "push"}, `{}`), ""},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ts := types
|
||||
if i == len(tests)-1 {
|
||||
ts = append(ts, EventType{ID: "dup", Source: "gh", Name: "dup", Rule: Rule{}})
|
||||
}
|
||||
got, ok := Identify(ts, tt.source, tt.in)
|
||||
if got.ID != tt.want || ok != (tt.want != "") {
|
||||
t.Fatalf("Identify = %q,%v want %q", got.ID, ok, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFromExample(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in Sample
|
||||
wantRule Rule
|
||||
}{
|
||||
{
|
||||
name: "discriminator headers become the rule",
|
||||
in: sample(map[string]string{"X-GitHub-Event": "push", "User-Agent": "x"}, `{"ref":"main"}`),
|
||||
wantRule: Rule{Headers: []HeaderCondition{{Name: "x-github-event", Value: "push"}}},
|
||||
},
|
||||
{
|
||||
name: "without discriminators the top-level paths must be present",
|
||||
in: sample(nil, `{"src":"1.2.3.4","action":{"k":1}}`),
|
||||
wantRule: Rule{Payload: []PayloadCondition{{Path: "action", Op: OpPresent}, {Path: "src", Op: OpPresent}}},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := FromExample("s", "n", tt.in)
|
||||
if !reflect.DeepEqual(got.Rule, tt.wantRule) {
|
||||
t.Fatalf("rule = %+v, want %+v", got.Rule, tt.wantRule)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Schema, Sign(tt.in).Paths) {
|
||||
t.Fatalf("schema = %v, want the example's paths", got.Schema)
|
||||
}
|
||||
if !got.Rule.Matches(tt.in) {
|
||||
t.Fatal("a type made from an example must match that example")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPropose(t *testing.T) {
|
||||
gh := func(id, ev, body string) Capture {
|
||||
return Capture{ID: id, Source: "gh", Sample: sample(map[string]string{"x-github-event": ev}, body)}
|
||||
}
|
||||
captures := []Capture{
|
||||
gh("c1", "push", `{"ref":"a"}`),
|
||||
gh("c2", "pull_request", `{"action":"opened"}`),
|
||||
gh("c3", "push", `{"ref":"b"}`),
|
||||
{ID: "f1", Source: "fw", Sample: sample(nil, `{"src":"1.1.1.1","port":22}`)},
|
||||
{ID: "f2", Source: "fw", Sample: sample(nil, `{"src":"1.1.1.1","port":22,"extra":true}`)},
|
||||
}
|
||||
got := Propose(captures)
|
||||
type summary struct {
|
||||
source, sample string
|
||||
count int
|
||||
rule Rule
|
||||
}
|
||||
var sums []summary
|
||||
for _, p := range got {
|
||||
sums = append(sums, summary{p.Source, p.SampleID, p.Count, p.Rule})
|
||||
}
|
||||
want := []summary{
|
||||
{"fw", "f1", 1, Rule{}},
|
||||
{"fw", "f2", 1, Rule{Payload: []PayloadCondition{{Path: "extra", Op: OpPresent}}}},
|
||||
{"gh", "c1", 2, Rule{Headers: []HeaderCondition{{Name: "x-github-event", Value: "push"}}}},
|
||||
{"gh", "c2", 1, Rule{Headers: []HeaderCondition{{Name: "x-github-event", Value: "pull_request"}}}},
|
||||
}
|
||||
if !reflect.DeepEqual(sums, want) {
|
||||
t.Fatalf("Propose =\n%+v\nwant\n%+v", sums, want)
|
||||
}
|
||||
for _, p := range got {
|
||||
if len(p.Schema) == 0 {
|
||||
t.Errorf("proposal %s has no schema", p.SampleID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package eventtype
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Capture is one stored event as proposal grouping reads it.
|
||||
type Capture struct {
|
||||
ID string
|
||||
Source string
|
||||
ReceivedAt time.Time
|
||||
Sample Sample
|
||||
}
|
||||
|
||||
// Proposal is a group of one source's captures sharing a signature, offered
|
||||
// to the operator as an event type to name. Rule is the set of
|
||||
// discriminators that separates the group from its siblings on the source.
|
||||
type Proposal struct {
|
||||
Source string `json:"source"`
|
||||
Key string `json:"key"`
|
||||
Schema map[string]ValueType `json:"schema"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
Count int `json:"count"`
|
||||
SampleID string `json:"sample_id"`
|
||||
Rule Rule `json:"rule"`
|
||||
}
|
||||
|
||||
// Propose groups captures by source and signature. Groups are ordered by
|
||||
// source, then largest first, then first seen; the sample is the group's first
|
||||
// capture in input order.
|
||||
func Propose(captures []Capture) []Proposal {
|
||||
var groups []*Proposal
|
||||
sigs := map[*Proposal]Signature{}
|
||||
index := map[string]*Proposal{}
|
||||
for _, c := range captures {
|
||||
sig := Sign(c.Sample)
|
||||
key := sig.Key()
|
||||
id := c.Source + "\x00" + key
|
||||
if g, ok := index[id]; ok {
|
||||
g.Count++
|
||||
continue
|
||||
}
|
||||
g := &Proposal{Source: c.Source, Key: key, Schema: sig.Paths, Headers: sig.Headers, Count: 1, SampleID: c.ID}
|
||||
index[id] = g
|
||||
sigs[g] = sig
|
||||
groups = append(groups, g)
|
||||
}
|
||||
slices.SortStableFunc(groups, func(a, b *Proposal) int {
|
||||
if c := strings.Compare(a.Source, b.Source); c != 0 {
|
||||
return c
|
||||
}
|
||||
return b.Count - a.Count
|
||||
})
|
||||
out := make([]Proposal, 0, len(groups))
|
||||
for _, g := range groups {
|
||||
var siblings []Signature
|
||||
for _, s := range groups {
|
||||
if s != g && s.Source == g.Source {
|
||||
siblings = append(siblings, sigs[s])
|
||||
}
|
||||
}
|
||||
g.Rule = separatingRule(sigs[g], siblings)
|
||||
out = append(out, *g)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// separatingRule demands the group's discriminator headers, then, for each
|
||||
// sibling those do not already rule out, the presence of the first path the
|
||||
// group has and the sibling lacks. A group whose paths are a subset of a
|
||||
// sibling's cannot be separated by presence alone; saving it as proposed is
|
||||
// then refused as an overlap, and the operator edits the rule.
|
||||
func separatingRule(g Signature, siblings []Signature) Rule {
|
||||
rule := Rule{Headers: headerConditions(g.Headers)}
|
||||
paths := slices.Sorted(maps.Keys(g.Paths))
|
||||
for _, s := range siblings {
|
||||
if headersSeparate(g.Headers, s.Headers) || rulePathsSeparate(rule, s) {
|
||||
continue
|
||||
}
|
||||
for _, path := range paths {
|
||||
if _, ok := s.Paths[path]; !ok {
|
||||
rule.Payload = append(rule.Payload, PayloadCondition{Path: path, Op: OpPresent})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return rule
|
||||
}
|
||||
|
||||
func headersSeparate(g, s map[string]string) bool {
|
||||
for name, value := range g {
|
||||
if other, ok := s[name]; !ok || other != value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func rulePathsSeparate(rule Rule, s Signature) bool {
|
||||
for _, p := range rule.Payload {
|
||||
if _, ok := s.Paths[p.Path]; !ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package eventtype
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"maps"
|
||||
"mime"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ValueType is the JSON shape of one payload path. The names match
|
||||
// mapping.FieldType so a mapping can be checked against a type's schema.
|
||||
type ValueType string
|
||||
|
||||
const (
|
||||
TypeString ValueType = "string"
|
||||
TypeNumber ValueType = "number"
|
||||
TypeBool ValueType = "bool"
|
||||
TypeObject ValueType = "object"
|
||||
TypeArray ValueType = "array"
|
||||
TypeNull ValueType = "null"
|
||||
)
|
||||
|
||||
// Sample is one event as the rules see it: headers keyed by lower-case name
|
||||
// (first value only) and the raw body.
|
||||
type Sample struct {
|
||||
Headers map[string]string
|
||||
Body []byte
|
||||
}
|
||||
|
||||
// Signature is the structure of one event: every JSON path with its value
|
||||
// type, plus the discriminator headers with their values. Array elements share
|
||||
// one path segment, "[]", so two payloads differing only in list length have
|
||||
// the same signature.
|
||||
type Signature struct {
|
||||
Paths map[string]ValueType `json:"paths"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
}
|
||||
|
||||
// ParseHeaders reads a capture's stored headers (an encoded http.Header) into
|
||||
// the lower-case, first-value form a Sample carries. Anything unreadable is no
|
||||
// headers, not an error: a capture's headers are evidence, not input.
|
||||
func ParseHeaders(raw string) map[string]string {
|
||||
out := map[string]string{}
|
||||
var h map[string][]string
|
||||
if json.Unmarshal([]byte(raw), &h) != nil {
|
||||
return out
|
||||
}
|
||||
for name, values := range h {
|
||||
if len(values) > 0 {
|
||||
out[strings.ToLower(name)] = values[0]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// isDiscriminator reports whether a header names the kind of event rather than
|
||||
// describing its transport: X-GitHub-Event, X-Gitea-Event-Type, Content-Type.
|
||||
func isDiscriminator(name string) bool {
|
||||
name = strings.ToLower(name)
|
||||
return strings.HasSuffix(name, "-event") || strings.HasSuffix(name, "-type")
|
||||
}
|
||||
|
||||
// headerValue normalises a header value for comparison. Content-Type compares
|
||||
// by media type, so a charset parameter does not split one kind of event in two.
|
||||
func headerValue(name, value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if strings.EqualFold(name, "content-type") {
|
||||
if mt, _, err := mime.ParseMediaType(value); err == nil {
|
||||
return mt
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// Sign computes an event's structural signature. A body that is not JSON has
|
||||
// no paths; its headers still discriminate it.
|
||||
func Sign(s Sample) Signature {
|
||||
sig := Signature{Paths: map[string]ValueType{}, Headers: map[string]string{}}
|
||||
for name, value := range s.Headers {
|
||||
if isDiscriminator(name) {
|
||||
sig.Headers[strings.ToLower(name)] = headerValue(name, value)
|
||||
}
|
||||
}
|
||||
if root, ok := decode(s.Body); ok {
|
||||
collectPaths(root, "", sig.Paths)
|
||||
}
|
||||
return sig
|
||||
}
|
||||
|
||||
// Key is a stable string that is equal for two signatures exactly when their
|
||||
// paths, path types and discriminator headers are equal.
|
||||
func (s Signature) Key() string {
|
||||
var b strings.Builder
|
||||
for _, name := range slices.Sorted(maps.Keys(s.Headers)) {
|
||||
b.WriteString("h:" + name + "=" + s.Headers[name] + "\n")
|
||||
}
|
||||
for _, path := range slices.Sorted(maps.Keys(s.Paths)) {
|
||||
b.WriteString("p:" + path + "=" + string(s.Paths[path]) + "\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func decode(body []byte) (any, bool) {
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.UseNumber()
|
||||
var v any
|
||||
if err := dec.Decode(&v); err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
func valueType(v any) ValueType {
|
||||
switch v.(type) {
|
||||
case string:
|
||||
return TypeString
|
||||
case json.Number:
|
||||
return TypeNumber
|
||||
case bool:
|
||||
return TypeBool
|
||||
case map[string]any:
|
||||
return TypeObject
|
||||
case []any:
|
||||
return TypeArray
|
||||
default:
|
||||
return TypeNull
|
||||
}
|
||||
}
|
||||
|
||||
// collectPaths records every path below v. The root itself has no path.
|
||||
func collectPaths(v any, prefix string, out map[string]ValueType) {
|
||||
switch typed := v.(type) {
|
||||
case map[string]any:
|
||||
for key, child := range typed {
|
||||
path := key
|
||||
if prefix != "" {
|
||||
path = prefix + "." + key
|
||||
}
|
||||
out[path] = valueType(child)
|
||||
collectPaths(child, path, out)
|
||||
}
|
||||
case []any:
|
||||
for _, child := range typed {
|
||||
path := prefix + "[]"
|
||||
out[path] = valueType(child)
|
||||
collectPaths(child, path, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// lookup returns every value at path; "[]" segments fan out over array
|
||||
// elements, so a path inside a list yields one value per element that has it.
|
||||
func lookup(root any, path string) []any {
|
||||
current := []any{root}
|
||||
for seg := range strings.SplitSeq(path, ".") {
|
||||
name, arrays := seg, 0
|
||||
for strings.HasSuffix(name, "[]") {
|
||||
name, arrays = strings.TrimSuffix(name, "[]"), arrays+1
|
||||
}
|
||||
var next []any
|
||||
for _, node := range current {
|
||||
obj, ok := node.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if child, ok := obj[name]; ok {
|
||||
next = append(next, child)
|
||||
}
|
||||
}
|
||||
for range arrays {
|
||||
var elems []any
|
||||
for _, node := range next {
|
||||
if arr, ok := node.([]any); ok {
|
||||
elems = append(elems, arr...)
|
||||
}
|
||||
}
|
||||
next = elems
|
||||
}
|
||||
current = next
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
// scalarText renders a scalar the way an operator types it into an equals
|
||||
// condition; objects and arrays have no text and never equal anything.
|
||||
func scalarText(v any) (string, bool) {
|
||||
switch typed := v.(type) {
|
||||
case string:
|
||||
return typed, true
|
||||
case json.Number:
|
||||
return typed.String(), true
|
||||
case bool:
|
||||
if typed {
|
||||
return "true", true
|
||||
}
|
||||
return "false", true
|
||||
case nil:
|
||||
return "null", true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,13 @@ package mapping
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
)
|
||||
|
||||
// FieldType is the expected JSON shape of a mapped field, checked at
|
||||
@@ -46,16 +49,20 @@ type Field struct {
|
||||
Required bool `json:"required"`
|
||||
}
|
||||
|
||||
// Mapping is a named, reusable set of field bindings, authored by clicking
|
||||
// through one example captured event but not pinned to that event or its
|
||||
// source -- t2db.4's matcher decides which events a binding applies to.
|
||||
// Mapping is a named set of field bindings belonging to one event type and
|
||||
// checked against its schema (CheckSchema). Any number of bindings may reuse
|
||||
// it. MatchCount and LastMatchedAt are read-only: the store counts each
|
||||
// capture the mapping resolved at dispatch.
|
||||
type Mapping struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
SourceHint string `json:"source_hint"`
|
||||
Fields []Field `json:"fields"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
SourceHint string `json:"source_hint"`
|
||||
EventTypeID string `json:"event_type_id"`
|
||||
Fields []Field `json:"fields"`
|
||||
MatchCount int64 `json:"match_count"`
|
||||
LastMatchedAt time.Time `json:"last_matched_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// validTypes is the set of FieldType values Validate accepts.
|
||||
@@ -231,6 +238,46 @@ func walk(node any, path []pathSegment) (value any, found bool) {
|
||||
return cur, true
|
||||
}
|
||||
|
||||
// ErrSchema marks a mapping whose field paths or types disagree with its
|
||||
// event type's inferred schema.
|
||||
var ErrSchema = errors.New("mapping: field does not fit the event type's schema")
|
||||
|
||||
// CheckSchema refuses fields whose path the event type's schema lacks, or
|
||||
// whose declared type differs from the schema's. Array indices match the
|
||||
// schema's "[]" segment, and a path the example held as null accepts any type.
|
||||
func CheckSchema(fields []Field, schema map[string]eventtype.ValueType) error {
|
||||
for _, f := range fields {
|
||||
got, ok := schema[schemaPath(f.Path)]
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: %s: path %q is not in the event type", ErrSchema, f.Name, f.Path)
|
||||
}
|
||||
if f.Type != TypeAny && got != eventtype.TypeNull && string(got) != string(f.Type) {
|
||||
return fmt.Errorf("%w: %s: path %q is %s, not %s", ErrSchema, f.Name, f.Path, got, f.Type)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// schemaPath rewrites a resolve path ("items[0].id") into the schema's form
|
||||
// ("items[].id"). A malformed path has no schema form.
|
||||
func schemaPath(path string) string {
|
||||
var b strings.Builder
|
||||
for _, seg := range parsePath(path) {
|
||||
switch {
|
||||
case seg.Invalid:
|
||||
return ""
|
||||
case seg.Index >= 0:
|
||||
b.WriteString("[]")
|
||||
default:
|
||||
if b.Len() > 0 {
|
||||
b.WriteByte('.')
|
||||
}
|
||||
b.WriteString(seg.Key)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func typeMatches(v any, want FieldType) bool {
|
||||
if want == TypeAny {
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package mapping_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
)
|
||||
|
||||
func TestCheckSchema(t *testing.T) {
|
||||
schema := map[string]eventtype.ValueType{
|
||||
"action": eventtype.TypeString,
|
||||
"issue": eventtype.TypeObject,
|
||||
"issue.number": eventtype.TypeNumber,
|
||||
"labels": eventtype.TypeArray,
|
||||
"labels[]": eventtype.TypeObject,
|
||||
"labels[].name": eventtype.TypeString,
|
||||
"closed_at": eventtype.TypeNull,
|
||||
"repository.url": eventtype.TypeString,
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields []mapping.Field
|
||||
ok bool
|
||||
}{
|
||||
{"top level path with matching type", []mapping.Field{{Name: "a", Path: "action", Type: mapping.TypeString}}, true},
|
||||
{"nested number", []mapping.Field{{Name: "n", Path: "issue.number", Type: mapping.TypeNumber}}, true},
|
||||
{"indexed array element maps to the [] path", []mapping.Field{{Name: "l", Path: "labels[0].name", Type: mapping.TypeString}}, true},
|
||||
{"any accepts every schema type", []mapping.Field{{Name: "i", Path: "issue", Type: mapping.TypeAny}}, true},
|
||||
{"a null example value accepts any declared type", []mapping.Field{{Name: "c", Path: "closed_at", Type: mapping.TypeString}}, true},
|
||||
{"path the type does not have", []mapping.Field{{Name: "x", Path: "sender.login", Type: mapping.TypeString}}, false},
|
||||
{"type differs from the schema", []mapping.Field{{Name: "n", Path: "issue.number", Type: mapping.TypeString}}, false},
|
||||
{"malformed index", []mapping.Field{{Name: "l", Path: "labels[x].name", Type: mapping.TypeString}}, false},
|
||||
{"one bad field refuses the mapping", []mapping.Field{
|
||||
{Name: "a", Path: "action", Type: mapping.TypeString},
|
||||
{Name: "b", Path: "nope", Type: mapping.TypeString},
|
||||
}, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := mapping.CheckSchema(tt.fields, schema)
|
||||
if tt.ok && err != nil {
|
||||
t.Fatalf("CheckSchema() = %v, want nil", err)
|
||||
}
|
||||
if !tt.ok && !errors.Is(err, mapping.ErrSchema) {
|
||||
t.Fatalf("CheckSchema() = %v, want ErrSchema", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package source
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// NewPath returns a fresh UUIDv7 path: time-ordered, unguessable, and never
|
||||
// colliding with another source.
|
||||
func NewPath() (string, error) {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("source: generate path: %w", err)
|
||||
}
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
// NewSecret returns a fresh 32-byte HMAC secret, hex encoded.
|
||||
func NewSecret() (string, error) {
|
||||
var b [MinSecretLen / 2]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", fmt.Errorf("source: generate secret: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
// ValidatePath checks a custom path is URL-safe: RFC 3986 unreserved
|
||||
// characters only, so it needs no escaping, and never a dot segment.
|
||||
func ValidatePath(path string) error {
|
||||
if path == "" || len(path) > MaxPathLen || path == "." || path == ".." {
|
||||
return ErrInvalidPath
|
||||
}
|
||||
for i := range len(path) {
|
||||
if !unreserved(path[i]) {
|
||||
return ErrInvalidPath
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unreserved(c byte) bool {
|
||||
switch {
|
||||
case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9':
|
||||
return true
|
||||
}
|
||||
return c == '-' || c == '.' || c == '_' || c == '~'
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Package source owns the capture source: the endpoint one sender posts to,
|
||||
// and its signing setting. See docs/prds/event-automation.md "Sources".
|
||||
package source
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Signing is a source's signing state. A source is signed by default; turning
|
||||
// signing off is requested and then approved, the same two-step gate as
|
||||
// arming a binding, and only the approved state accepts unsigned events.
|
||||
type Signing string
|
||||
|
||||
const (
|
||||
SigningSigned Signing = "signed"
|
||||
SigningUnsignedPending Signing = "unsigned_pending_approval"
|
||||
SigningUnsigned Signing = "unsigned"
|
||||
)
|
||||
|
||||
// MaxPathLen bounds a custom path.
|
||||
const MaxPathLen = 128
|
||||
|
||||
// MinSecretLen is the length of a generated secret: 32 random bytes, hex.
|
||||
const MinSecretLen = 64
|
||||
|
||||
var (
|
||||
// ErrInvalidPath refuses a custom path that is not URL-safe.
|
||||
ErrInvalidPath = errors.New("source: path must be 1-128 URL-safe characters (A-Z a-z 0-9 - . _ ~), not a dot segment")
|
||||
// ErrSigningTransition refuses an approval with no pending request.
|
||||
ErrSigningTransition = errors.New("source: signing transition rejected")
|
||||
)
|
||||
|
||||
// Source is one capture endpoint. Path is its URL segment and its identity:
|
||||
// captures and binding matchers reference it, so it does not change after
|
||||
// creation. Secret is the HMAC key a signed sender signs with.
|
||||
type Source struct {
|
||||
Path string `json:"path"`
|
||||
Signing Signing `json:"signing"`
|
||||
Secret string `json:"secret,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// New builds a signed source with a generated secret. An empty customPath
|
||||
// gets a UUIDv7 path; a non-empty one must be URL-safe. Uniqueness is the
|
||||
// store's to enforce.
|
||||
func New(customPath string) (Source, error) {
|
||||
path := customPath
|
||||
if path == "" {
|
||||
generated, err := NewPath()
|
||||
if err != nil {
|
||||
return Source{}, err
|
||||
}
|
||||
path = generated
|
||||
} else if err := ValidatePath(path); err != nil {
|
||||
return Source{}, err
|
||||
}
|
||||
secret, err := NewSecret()
|
||||
if err != nil {
|
||||
return Source{}, err
|
||||
}
|
||||
return Source{Path: path, Signing: SigningSigned, Secret: secret}, nil
|
||||
}
|
||||
|
||||
// Unsigned reports whether events on this source dispatch without a
|
||||
// signature. Only an approved request counts.
|
||||
func (s *Source) Unsigned() bool { return s.Signing == SigningUnsigned }
|
||||
|
||||
// RequestUnsigned asks to turn signing off. The source stays signed until
|
||||
// ApproveUnsigned.
|
||||
func (s *Source) RequestUnsigned() error {
|
||||
if s.Signing == SigningSigned {
|
||||
s.Signing = SigningUnsignedPending
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApproveUnsigned is the only transition that turns signing off.
|
||||
func (s *Source) ApproveUnsigned() error {
|
||||
if s.Signing != SigningUnsignedPending {
|
||||
return ErrSigningTransition
|
||||
}
|
||||
s.Signing = SigningUnsigned
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequireSigning turns signing back on. It needs no approval: it only
|
||||
// narrows what dispatches.
|
||||
func (s *Source) RequireSigning() error {
|
||||
s.Signing = SigningSigned
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package source
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestNewDefaultsToSignedUUIDv7Path(t *testing.T) {
|
||||
s, err := New("")
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
id, err := uuid.Parse(s.Path)
|
||||
if err != nil {
|
||||
t.Fatalf("path %q is not a UUID: %v", s.Path, err)
|
||||
}
|
||||
if id.Version() != 7 {
|
||||
t.Fatalf("path version = %d, want 7", id.Version())
|
||||
}
|
||||
if s.Signing != SigningSigned {
|
||||
t.Fatalf("signing = %q, want %q", s.Signing, SigningSigned)
|
||||
}
|
||||
if len(s.Secret) < MinSecretLen {
|
||||
t.Fatalf("secret length = %d, want >= %d", len(s.Secret), MinSecretLen)
|
||||
}
|
||||
other, err := New("")
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
if other.Path == s.Path || other.Secret == s.Secret {
|
||||
t.Fatal("two new sources share a path or a secret")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAcceptsOrRefusesCustomPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
path string
|
||||
ok bool
|
||||
}{
|
||||
{"sentry", true},
|
||||
{"fire-wall_01.v2~x", true},
|
||||
{"a/b", false},
|
||||
{"with space", false},
|
||||
{"percent%20", false},
|
||||
{"..", false},
|
||||
{".", false},
|
||||
{strings.Repeat("a", MaxPathLen+1), false},
|
||||
{"ünicode", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.path, func(t *testing.T) {
|
||||
s, err := New(tt.path)
|
||||
if tt.ok {
|
||||
if err != nil || s.Path != tt.path {
|
||||
t.Fatalf("New(%q) = %q, %v; want path kept", tt.path, s.Path, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, ErrInvalidPath) {
|
||||
t.Fatalf("New(%q) error = %v, want ErrInvalidPath", tt.path, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSigningTransitions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
from Signing
|
||||
action func(*Source) error
|
||||
want Signing
|
||||
wantErr bool
|
||||
}{
|
||||
{"request unsigned waits for approval", SigningSigned, (*Source).RequestUnsigned, SigningUnsignedPending, false},
|
||||
{"approve pending", SigningUnsignedPending, (*Source).ApproveUnsigned, SigningUnsigned, false},
|
||||
{"approve without request", SigningSigned, (*Source).ApproveUnsigned, SigningSigned, true},
|
||||
{"approve twice", SigningUnsigned, (*Source).ApproveUnsigned, SigningUnsigned, true},
|
||||
{"resign from unsigned", SigningUnsigned, (*Source).RequireSigning, SigningSigned, false},
|
||||
{"resign from pending", SigningUnsignedPending, (*Source).RequireSigning, SigningSigned, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := Source{Path: "p", Signing: tt.from}
|
||||
err := tt.action(&s)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if s.Signing != tt.want {
|
||||
t.Fatalf("signing = %q, want %q", s.Signing, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsignedOnlyOnceApproved(t *testing.T) {
|
||||
for signing, want := range map[Signing]bool{
|
||||
SigningSigned: false,
|
||||
SigningUnsignedPending: false,
|
||||
SigningUnsigned: true,
|
||||
} {
|
||||
if got := (&Source{Signing: signing}).Unsigned(); got != want {
|
||||
t.Errorf("Unsigned() for %q = %v, want %v", signing, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
@@ -175,6 +177,25 @@ type MappingStore interface {
|
||||
DeleteMapping(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// MappingMatchRecorder counts the events each mapping resolved, which the
|
||||
// store reports as Mapping.MatchCount and LastMatchedAt. Recording the same
|
||||
// (mapping, capture) twice counts once.
|
||||
type MappingMatchRecorder interface {
|
||||
RecordMappingMatch(ctx context.Context, mappingID, captureID string) error
|
||||
}
|
||||
|
||||
// EventTypeStore persists event types (docs/prds/event-automation.md, "Event
|
||||
// types"). Insert and Update refuse a type whose rule overlaps another on the
|
||||
// same source with eventtype.ErrOverlap, and a malformed one with
|
||||
// eventtype.ErrInvalid. Update rewrites the name and rule; the schema is the
|
||||
// one the type was created with.
|
||||
type EventTypeStore interface {
|
||||
InsertEventType(ctx context.Context, t eventtype.EventType) (string, error)
|
||||
UpdateEventType(ctx context.Context, t eventtype.EventType) error
|
||||
DeleteEventType(ctx context.Context, id string) error
|
||||
ListEventTypes(ctx context.Context) ([]eventtype.EventType, error)
|
||||
}
|
||||
|
||||
// BindingStore persists playbook bindings (t2db.4 Phase B): CRUD and the
|
||||
// draft -> pending_approval -> armed state machine. Split off from
|
||||
// TaskStore and MappingStore so the webui binding editor does not acquire
|
||||
@@ -190,6 +211,20 @@ type BindingStore interface {
|
||||
ApproveBinding(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// SourceStore persists capture sources and their signing setting
|
||||
// (docs/prds/event-automation.md "Sources"). The path is the key and never
|
||||
// changes. Secrets cross this surface in plaintext; the store encrypts them
|
||||
// at rest. Signing transitions are decided by the source domain and written
|
||||
// with an expected-from guard, so two operators cannot race an approval.
|
||||
type SourceStore interface {
|
||||
InsertSource(ctx context.Context, s source.Source) error
|
||||
// GetSource returns (nil, nil) for an unknown path.
|
||||
GetSource(ctx context.Context, path string) (*source.Source, error)
|
||||
ListSources(ctx context.Context) ([]source.Source, error)
|
||||
SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error
|
||||
SetSourceSecret(ctx context.Context, path, secret string) error
|
||||
}
|
||||
|
||||
// BindingDispatcher is the dispatch-loop surface over the bindings store:
|
||||
// look up armed bindings for HMAC verification, list captures that still
|
||||
// need dispatching, and record the at-most-once ledger row. The
|
||||
@@ -204,7 +239,8 @@ type BindingDispatcher interface {
|
||||
bindingVersion int64,
|
||||
captureID string,
|
||||
// taskID addresses the SQLite-owned task tables, which are not
|
||||
// migrating: it stays an integer on purpose.
|
||||
// migrating: it stays an integer on purpose. The binding dispatch
|
||||
// loop claims before it enqueues, so it records 0.
|
||||
taskID int64,
|
||||
) error
|
||||
ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]CapturedEvent, error)
|
||||
@@ -269,8 +305,19 @@ type CapturedEvent struct {
|
||||
Headers string `json:"headers"`
|
||||
Body string `json:"body"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
// EventType is the ID of the event type the capture was identified as
|
||||
// when it arrived, or empty when it matched none. An unidentified capture
|
||||
// is never dispatched.
|
||||
EventType string `json:"event_type"`
|
||||
// Unsigned marks an event that arrived on an approved unsigned source.
|
||||
// It dispatches without Authenticated and is flagged wherever it shows.
|
||||
Unsigned bool `json:"unsigned"`
|
||||
}
|
||||
|
||||
// Dispatchable reports whether a binding may start a task from this event:
|
||||
// a valid signature, or a source approved to take unsigned events.
|
||||
func (c CapturedEvent) Dispatchable() bool { return c.Authenticated || c.Unsigned }
|
||||
|
||||
// ConfigSnapshot is the running configuration as the dashboard renders it,
|
||||
// published by whoever owns configuration for whoever displays it.
|
||||
//
|
||||
@@ -368,6 +415,15 @@ var (
|
||||
ErrAlreadyDispatched = errors.New("store: binding already dispatched for capture")
|
||||
// ErrMappingNotFound is returned when a mapping ID does not exist.
|
||||
ErrMappingNotFound = errors.New("store: mapping not found")
|
||||
// ErrEventTypeNotFound is returned when an event type ID does not exist.
|
||||
ErrEventTypeNotFound = errors.New("store: event type not found")
|
||||
// ErrSourceNotFound is returned when a source path does not exist.
|
||||
ErrSourceNotFound = errors.New("store: source not found")
|
||||
// ErrSourcePathTaken is returned when a new source's path is in use.
|
||||
ErrSourcePathTaken = errors.New("store: source path already taken")
|
||||
// ErrSourceSigningStale is returned when a signing write's expected
|
||||
// from state does not match the stored one.
|
||||
ErrSourceSigningStale = errors.New("store: source signing does not match expected state")
|
||||
|
||||
// ErrResourceNotFound is returned when a control-plane resource kind has
|
||||
// no stored document. It is in-process only (not on the gRPC wire): the
|
||||
|
||||
@@ -114,6 +114,11 @@ const (
|
||||
KindBindingChanged = "binding_changed"
|
||||
KindMappingChanged = "mapping_changed"
|
||||
|
||||
// KindUnsignedEvent marks a task started by an event from an approved
|
||||
// unsigned source, so its timeline shows that nothing authenticated
|
||||
// the sender. data: source, capture_id, binding_id.
|
||||
KindUnsignedEvent = "unsigned_event"
|
||||
|
||||
// KindUpdateReport carries the phase-2 outcome of a dashboard-initiated
|
||||
// update -- whether the restarted daemon came back up healthy and on
|
||||
// the version it claimed, relayed once on the boot that finds the
|
||||
|
||||
@@ -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/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
@@ -75,92 +75,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) ([]storecontract.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 {
|
||||
@@ -441,230 +355,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 []storecontract.CapturedEvent }
|
||||
|
||||
func (m *memCaptures) InsertCapture(_ context.Context, c storecontract.CapturedEvent, _ time.Duration, _ int) (string, error) {
|
||||
m.rows = append(m.rows, c)
|
||||
return "c", nil
|
||||
}
|
||||
|
||||
func (m *memCaptures) ListCaptures(context.Context, int) ([]storecontract.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}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -139,7 +139,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},
|
||||
|
||||
@@ -23,6 +23,19 @@ var droppedColumns = map[string]bool{
|
||||
"playbook_dispatches.id": true,
|
||||
}
|
||||
|
||||
// newColumns are target columns added after the legacy stores, with no
|
||||
// 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. An imported
|
||||
// mapping has no event type, so no binding using it dispatches until it is
|
||||
// given one, and an imported binding has no filter.
|
||||
var newColumns = map[string]bool{
|
||||
"captures.event_type": true,
|
||||
"mappings.event_type": true,
|
||||
"bindings.filter": true,
|
||||
"captures.unsigned": true,
|
||||
}
|
||||
|
||||
// targetKeys override a table's legacy key where the target has no column
|
||||
// for it.
|
||||
var targetKeys = map[string][]string{
|
||||
@@ -171,6 +184,7 @@ func plan(ctx context.Context, tx pgx.Tx, t legacyread.Table, problems *refusal)
|
||||
problems.add("%s: no target table", t.Name)
|
||||
}
|
||||
targetNames := map[string]bool{}
|
||||
cols = slices.DeleteFunc(cols, func(c column) bool { return newColumns[t.Name+"."+c.name] })
|
||||
for i := range cols {
|
||||
targetNames[cols[i].name] = true
|
||||
cols[i].source = slices.Index(t.Columns, cols[i].name)
|
||||
|
||||
@@ -26,11 +26,12 @@ import (
|
||||
// EDA is the PostgreSQL implementation of every event-capture contract, plus
|
||||
// the tool_calls transcript the composition projection writes through.
|
||||
var (
|
||||
_ storecontract.CaptureStore = (*EDA)(nil)
|
||||
_ storecontract.MappingStore = (*EDA)(nil)
|
||||
_ storecontract.BindingStore = (*EDA)(nil)
|
||||
_ storecontract.BindingDispatcher = (*EDA)(nil)
|
||||
_ storecontract.PlaybookDispatcher = (*EDA)(nil)
|
||||
_ storecontract.CaptureStore = (*EDA)(nil)
|
||||
_ storecontract.MappingStore = (*EDA)(nil)
|
||||
_ storecontract.BindingStore = (*EDA)(nil)
|
||||
_ storecontract.BindingDispatcher = (*EDA)(nil)
|
||||
_ storecontract.MappingMatchRecorder = (*EDA)(nil)
|
||||
_ storecontract.PlaybookDispatcher = (*EDA)(nil)
|
||||
)
|
||||
|
||||
// EDA is the PostgreSQL-backed EDA persistence.
|
||||
@@ -41,7 +42,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 caller resolves the keyring through
|
||||
// bindingcipher.NewBindingCipher. The pool is owned by the caller, not this store.
|
||||
func NewEDA(pool *pgxpool.Pool, cipher bindingcipher.BindingCipher) *EDA {
|
||||
@@ -70,13 +71,18 @@ func newRecordID() string { return uuid.NewString() }
|
||||
|
||||
// --- captures ---
|
||||
|
||||
// InsertCapture stores one inbound event verbatim. retention and maxEvents are
|
||||
// InsertCapture stores one inbound event verbatim, tagged with the event type
|
||||
// it is identified as on arrival (empty when unidentified). retention and maxEvents are
|
||||
// applied as a prune after the insert.
|
||||
func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent, retention time.Duration, maxEvents int) (string, error) {
|
||||
received := c.ReceivedAt
|
||||
if received.IsZero() {
|
||||
received = time.Now()
|
||||
}
|
||||
eventType, err := s.identifyCapture(ctx, c)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
id := newRecordID()
|
||||
if err := s.q.InsertCapture(ctx, postgresdb.InsertCaptureParams{
|
||||
ID: id,
|
||||
@@ -86,7 +92,9 @@ 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 {
|
||||
return "", fmt.Errorf("edastore: insert capture: %w", err)
|
||||
}
|
||||
@@ -120,6 +128,8 @@ func captureValue(r postgresdb.Capture) storecontract.CapturedEvent {
|
||||
Headers: r.Headers,
|
||||
Body: r.Body,
|
||||
Authenticated: r.Authenticated,
|
||||
EventType: r.EventType,
|
||||
Unsigned: r.Unsigned,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,8 +146,9 @@ func (s *EDA) ListCaptures(ctx context.Context, limit int) ([]storecontract.Capt
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListUndispatchedCaptures returns recent captures for the given sources that
|
||||
// no binding has dispatched yet.
|
||||
// ListUndispatchedCaptures returns recent identified captures for the given
|
||||
// sources that some armed binding for their event type has not dispatched yet.
|
||||
// An unidentified capture is never returned, so it never dispatches.
|
||||
func (s *EDA) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]storecontract.CapturedEvent, error) {
|
||||
if len(sources) == 0 || limit <= 0 {
|
||||
return nil, nil
|
||||
@@ -166,20 +177,27 @@ func marshalMappingFields(fields []mapping.Field) (string, error) {
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
func mappingValue(r postgresdb.Mapping) (mapping.Mapping, error) {
|
||||
func mappingValue(r postgresdb.Mapping, matches int64, lastMatched time.Time) (mapping.Mapping, error) {
|
||||
var fields []mapping.Field
|
||||
if raw := r.Fields; raw != "" {
|
||||
if err := json.Unmarshal([]byte(raw), &fields); err != nil {
|
||||
return mapping.Mapping{}, fmt.Errorf("edastore: decode mapping fields: %w", err)
|
||||
}
|
||||
}
|
||||
// The query reports the epoch for a mapping that never matched.
|
||||
if matches == 0 {
|
||||
lastMatched = time.Time{}
|
||||
}
|
||||
return mapping.Mapping{
|
||||
ID: r.ID,
|
||||
Name: r.Name,
|
||||
SourceHint: r.SourceHint,
|
||||
Fields: fields,
|
||||
CreatedAt: r.CreatedAt,
|
||||
UpdatedAt: r.UpdatedAt,
|
||||
ID: r.ID,
|
||||
Name: r.Name,
|
||||
SourceHint: r.SourceHint,
|
||||
EventTypeID: r.EventType,
|
||||
Fields: fields,
|
||||
MatchCount: matches,
|
||||
LastMatchedAt: lastMatched,
|
||||
CreatedAt: r.CreatedAt,
|
||||
UpdatedAt: r.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -193,6 +211,7 @@ func (s *EDA) InsertMapping(ctx context.Context, m mapping.Mapping) (string, err
|
||||
ID: id,
|
||||
Name: m.Name,
|
||||
SourceHint: m.SourceHint,
|
||||
EventType: m.EventTypeID,
|
||||
Fields: encoded,
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("edastore: insert mapping: %w", err)
|
||||
@@ -211,7 +230,7 @@ func (s *EDA) GetMapping(ctx context.Context, id string) (*mapping.Mapping, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m, err := mappingValue(r)
|
||||
m, err := mappingValue(r.Mapping, r.MatchCount, r.LastMatchedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -225,7 +244,7 @@ func (s *EDA) ListMappings(ctx context.Context) ([]mapping.Mapping, error) {
|
||||
}
|
||||
out := make([]mapping.Mapping, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
m, err := mappingValue(r)
|
||||
m, err := mappingValue(r.Mapping, r.MatchCount, r.LastMatchedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -243,6 +262,7 @@ func (s *EDA) UpdateMapping(ctx context.Context, m mapping.Mapping) error {
|
||||
ID: m.ID,
|
||||
Name: m.Name,
|
||||
SourceHint: m.SourceHint,
|
||||
EventType: m.EventTypeID,
|
||||
Fields: encoded,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -267,72 +287,52 @@ func (s *EDA) DeleteMapping(ctx context.Context, id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- bindings ---
|
||||
|
||||
func (s *EDA) encryptSecret(secret string) (string, error) {
|
||||
if s.cipher == nil {
|
||||
return secret, nil
|
||||
// RecordMappingMatch counts one event a mapping resolved. Recording the same
|
||||
// (mapping, capture) again is a no-op, so the count rises once per event no
|
||||
// matter how many bindings share the mapping.
|
||||
func (s *EDA) RecordMappingMatch(ctx context.Context, mappingID, captureID string) error {
|
||||
if err := s.q.InsertMappingMatch(ctx, postgresdb.InsertMappingMatchParams{Mapping: mappingID, Capture: captureID}); err != nil {
|
||||
return fmt.Errorf("edastore: record mapping match: %w", err)
|
||||
}
|
||||
encrypted, err := s.cipher.Encrypt(secret)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("edastore: encrypt binding secret: %w", err)
|
||||
}
|
||||
return encrypted, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
|
||||
b := binding.Binding{
|
||||
// --- bindings ---
|
||||
|
||||
// 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},
|
||||
MappingID: r.Mapping,
|
||||
Filter: r.Filter,
|
||||
Workflow: r.Workflow,
|
||||
Owner: r.Owner,
|
||||
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
|
||||
// source" is a schema constraint (idx_bindings_source), so a concurrent
|
||||
// second insert for the same source is refused by the database and surfaced
|
||||
// here as ErrBindingOverlap.
|
||||
// InsertBinding stores a new binding as pending_approval. Any number of
|
||||
// bindings may share a source.
|
||||
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,
|
||||
Name: b.Name,
|
||||
Source: b.Matcher.Source,
|
||||
Mapping: b.MappingID,
|
||||
Filter: b.Filter,
|
||||
Workflow: b.Workflow,
|
||||
Owner: b.Owner,
|
||||
Repo: b.Repo,
|
||||
Status: string(binding.StatusPendingApproval),
|
||||
Secret: secret,
|
||||
})
|
||||
if isUniqueViolation(err) {
|
||||
return "", storecontract.ErrBindingOverlap
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("edastore: insert binding: %w", err)
|
||||
}
|
||||
@@ -350,10 +350,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
|
||||
}
|
||||
|
||||
@@ -364,11 +361,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
|
||||
}
|
||||
@@ -381,42 +374,25 @@ 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,
|
||||
Source: b.Matcher.Source,
|
||||
Mapping: b.MappingID,
|
||||
Filter: b.Filter,
|
||||
Workflow: b.Workflow,
|
||||
Owner: b.Owner,
|
||||
Repo: b.Repo,
|
||||
Status: string(binding.StatusPendingApproval),
|
||||
Secret: secret,
|
||||
})
|
||||
if isUniqueViolation(err) {
|
||||
return storecontract.ErrBindingOverlap
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -439,10 +415,7 @@ func (s *EDA) DeleteBinding(ctx context.Context, id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApproveBinding is the only transition that arms a binding. "One armed
|
||||
// binding per source" is a partial unique constraint (idx_bindings_armed_source),
|
||||
// so a concurrent approval of a sibling binding on the same source is refused
|
||||
// by the database and surfaced here as ErrBindingOverlap.
|
||||
// ApproveBinding is the only transition that arms a binding.
|
||||
func (s *EDA) ApproveBinding(ctx context.Context, id string) error {
|
||||
r, err := s.q.GetBinding(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -455,9 +428,6 @@ func (s *EDA) ApproveBinding(ctx context.Context, id string) error {
|
||||
return storecontract.ErrBindingTransition
|
||||
}
|
||||
n, err := s.q.SetBindingArmed(ctx, id)
|
||||
if isUniqueViolation(err) {
|
||||
return storecontract.ErrBindingOverlap
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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/storecontract"
|
||||
)
|
||||
|
||||
// eventTypeFixture saves a type on source matching events whose "kind" equals kind.
|
||||
func eventTypeFixture(t *testing.T, s *EDA, source, kind string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertEventType(t.Context(), eventtype.EventType{
|
||||
Source: source, Name: kind,
|
||||
Rule: eventtype.Rule{Payload: []eventtype.PayloadCondition{{Path: "kind", Op: eventtype.OpEquals, Value: kind}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func armedBinding(t *testing.T, s *EDA, source, mappingID string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: source}, MappingID: mappingID, Workflow: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
if err := s.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func captureOf(t *testing.T, s *EDA, source, body string) string {
|
||||
t.Helper()
|
||||
id, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: source, Body: body}, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func undispatchedIDs(t *testing.T, s *EDA, source string) map[string]bool {
|
||||
t.Helper()
|
||||
list, err := s.ListUndispatchedCaptures(t.Context(), []string{source}, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
|
||||
}
|
||||
out := map[string]bool{}
|
||||
for _, c := range list {
|
||||
out[c.ID] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSeveralArmedBindingsShareASource(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
a := armedBinding(t, s, "github", "")
|
||||
b := armedBinding(t, s, "github", "")
|
||||
armed, err := s.ArmedBindingsForSource(t.Context(), "github")
|
||||
if err != nil {
|
||||
t.Fatalf("ArmedBindingsForSource() error = %v", err)
|
||||
}
|
||||
got := map[string]bool{}
|
||||
for _, x := range armed {
|
||||
got[x.ID] = true
|
||||
}
|
||||
if !got[a] || !got[b] || len(armed) != 2 {
|
||||
t.Fatalf("armed = %v, want both %s and %s", got, a, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingAndBindingRoundTripEventTypeAndFilter(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
typeID := eventTypeFixture(t, s, "github", "push")
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: typeID})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
m, err := s.GetMapping(t.Context(), mid)
|
||||
if err != nil || m.EventTypeID != typeID {
|
||||
t.Fatalf("GetMapping() event type = %q (err %v), want %q", m.EventTypeID, err, typeID)
|
||||
}
|
||||
bid, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "github"}, MappingID: mid, Workflow: "implement",
|
||||
Filter: `kind == "push"`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
b, err := s.GetBinding(t.Context(), bid)
|
||||
if err != nil || b.Filter != `kind == "push"` {
|
||||
t.Fatalf("GetBinding() filter = %q (err %v)", b.Filter, err)
|
||||
}
|
||||
b.Filter = ""
|
||||
if err := s.UpdateBinding(t.Context(), *b); err != nil {
|
||||
t.Fatalf("UpdateBinding() error = %v", err)
|
||||
}
|
||||
if b, _ = s.GetBinding(t.Context(), bid); b.Filter != "" {
|
||||
t.Fatalf("filter after clearing = %q, want empty", b.Filter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingMatchCountRisesOncePerEvent(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
before := time.Now().Add(-time.Minute)
|
||||
for _, capture := range []string{"c1", "c2", "c1"} {
|
||||
if err := s.RecordMappingMatch(t.Context(), mid, capture); err != nil {
|
||||
t.Fatalf("RecordMappingMatch(%s) error = %v", capture, err)
|
||||
}
|
||||
}
|
||||
list, err := s.ListMappings(t.Context())
|
||||
if err != nil || len(list) != 1 {
|
||||
t.Fatalf("ListMappings() = %d (err %v)", len(list), err)
|
||||
}
|
||||
if list[0].MatchCount != 2 {
|
||||
t.Errorf("MatchCount = %d, want 2 (one per distinct event)", list[0].MatchCount)
|
||||
}
|
||||
if !list[0].LastMatchedAt.After(before) {
|
||||
t.Errorf("LastMatchedAt = %v, want a recent time", list[0].LastMatchedAt)
|
||||
}
|
||||
got, _ := s.GetMapping(t.Context(), mid)
|
||||
if got.MatchCount != 2 {
|
||||
t.Errorf("GetMapping MatchCount = %d, want 2", got.MatchCount)
|
||||
}
|
||||
}
|
||||
|
||||
// A capture stays undispatched until every armed binding for its event type
|
||||
// has dispatched it; a binding for another event type does not hold it.
|
||||
func TestUndispatchedIsPerBinding(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
push := eventTypeFixture(t, s, "github", "push")
|
||||
issue := eventTypeFixture(t, s, "github", "issue")
|
||||
pushMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "p", EventTypeID: push})
|
||||
issueMap, _ := s.InsertMapping(t.Context(), mapping.Mapping{Name: "i", EventTypeID: issue})
|
||||
a := armedBinding(t, s, "github", pushMap)
|
||||
b := armedBinding(t, s, "github", pushMap)
|
||||
c := armedBinding(t, s, "github", issueMap)
|
||||
|
||||
capture := captureOf(t, s, "github", `{"kind":"push"}`)
|
||||
if !undispatchedIDs(t, s, "github")[capture] {
|
||||
t.Fatal("new push capture not listed")
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), a, 1, capture, 1); err != nil {
|
||||
t.Fatalf("RecordDispatch(a) error = %v", err)
|
||||
}
|
||||
if !undispatchedIDs(t, s, "github")[capture] {
|
||||
t.Fatal("capture dropped after one of two push bindings dispatched it")
|
||||
}
|
||||
if err := s.RecordDispatch(t.Context(), b, 1, capture, 2); err != nil {
|
||||
t.Fatalf("RecordDispatch(b) error = %v", err)
|
||||
}
|
||||
if undispatchedIDs(t, s, "github")[capture] {
|
||||
t.Fatalf("capture still listed after both push bindings dispatched it (issue binding %s must not hold it)", c)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
func githubType(name, event string) eventtype.EventType {
|
||||
return eventtype.EventType{
|
||||
Source: "gh", Name: name,
|
||||
Rule: eventtype.Rule{Headers: []eventtype.HeaderCondition{{Name: "X-GitHub-Event", Value: event}}},
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeSaveRefusals(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
pushID, err := s.InsertEventType(t.Context(), githubType("push", "push"))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType(push) error = %v", err)
|
||||
}
|
||||
prID, err := s.InsertEventType(t.Context(), githubType("pr", "pull_request"))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType(pr) error = %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
save func() error
|
||||
wantErr error
|
||||
}{
|
||||
{"insert overlapping rule", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("push-again", "push"))
|
||||
return err
|
||||
}, eventtype.ErrOverlap},
|
||||
{"insert catch-all beside typed", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "gh", Name: "all"})
|
||||
return err
|
||||
}, eventtype.ErrOverlap},
|
||||
{"insert duplicate name", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("push", "issues"))
|
||||
return err
|
||||
}, eventtype.ErrInvalid},
|
||||
{"insert without name", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), githubType("", "issues"))
|
||||
return err
|
||||
}, eventtype.ErrInvalid},
|
||||
{"update into overlap", func() error {
|
||||
pr := githubType("pr", "push")
|
||||
pr.ID = prID
|
||||
return s.UpdateEventType(t.Context(), pr)
|
||||
}, eventtype.ErrOverlap},
|
||||
{"update missing", func() error {
|
||||
missing := githubType("x", "x")
|
||||
missing.ID = "missing"
|
||||
return s.UpdateEventType(t.Context(), missing)
|
||||
}, storecontract.ErrEventTypeNotFound},
|
||||
{"delete missing", func() error { return s.DeleteEventType(t.Context(), "missing") }, storecontract.ErrEventTypeNotFound},
|
||||
{"other source is independent", func() error {
|
||||
_, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "all"})
|
||||
return err
|
||||
}, nil},
|
||||
{"update keeps itself out of the overlap check", func() error {
|
||||
push := githubType("push-renamed", "push")
|
||||
push.ID = pushID
|
||||
return s.UpdateEventType(t.Context(), push)
|
||||
}, nil},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.save()
|
||||
if tt.wantErr == nil && err != nil {
|
||||
t.Fatalf("error = %v, want nil", err)
|
||||
}
|
||||
if tt.wantErr != nil && !errors.Is(err, tt.wantErr) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
types, err := s.ListEventTypes(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("ListEventTypes() error = %v", err)
|
||||
}
|
||||
names := map[string]bool{}
|
||||
for _, et := range types {
|
||||
names[et.Source+"/"+et.Name] = true
|
||||
}
|
||||
for _, want := range []string{"gh/push-renamed", "gh/pr", "fw/all"} {
|
||||
if !names[want] {
|
||||
t.Errorf("ListEventTypes() lacks %s: %v", want, names)
|
||||
}
|
||||
}
|
||||
if len(types) != 3 {
|
||||
t.Errorf("ListEventTypes() = %d types, want 3", len(types))
|
||||
}
|
||||
}
|
||||
|
||||
// A type made from a pasted payload has that payload's schema, and a later
|
||||
// matching capture is identified as it and becomes dispatchable; a capture
|
||||
// matching no type stays unidentified and is never listed for dispatch.
|
||||
func TestPastedTypeIdentifiesLaterCaptures(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
pasted := eventtype.Sample{
|
||||
Headers: map[string]string{"X-GitHub-Event": "pull_request"},
|
||||
Body: []byte(`{"action":"opened","number":1}`),
|
||||
}
|
||||
id, err := s.InsertEventType(t.Context(), eventtype.FromExample("gh", "pull_request", pasted))
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
types, err := s.ListEventTypes(t.Context())
|
||||
if err != nil || len(types) != 1 {
|
||||
t.Fatalf("ListEventTypes() = %v (err %v)", types, err)
|
||||
}
|
||||
if got := types[0].Schema; got["action"] != eventtype.TypeString || got["number"] != eventtype.TypeNumber {
|
||||
t.Fatalf("schema = %v, want the pasted payload's", got)
|
||||
}
|
||||
|
||||
for _, c := range []storecontract.CapturedEvent{
|
||||
{Source: "gh", Headers: `{"X-Github-Event":["pull_request"]}`, Body: `{"action":"closed","number":9}`},
|
||||
{Source: "gh", Headers: `{"X-Github-Event":["push"]}`, Body: `{"ref":"main"}`},
|
||||
} {
|
||||
if _, err := s.InsertCapture(t.Context(), c, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
}
|
||||
all, err := s.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures() error = %v", err)
|
||||
}
|
||||
byBody := map[string]string{}
|
||||
for _, c := range all {
|
||||
byBody[c.Body] = c.EventType
|
||||
}
|
||||
if byBody[`{"action":"closed","number":9}`] != id {
|
||||
t.Errorf("matching capture event type = %q, want %q", byBody[`{"action":"closed","number":9}`], id)
|
||||
}
|
||||
if byBody[`{"ref":"main"}`] != "" {
|
||||
t.Errorf("unmatched capture event type = %q, want unidentified", byBody[`{"ref":"main"}`])
|
||||
}
|
||||
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: id})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
armedBinding(t, s, "gh", mid)
|
||||
undispatched, err := s.ListUndispatchedCaptures(t.Context(), []string{"gh"}, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUndispatchedCaptures() error = %v", err)
|
||||
}
|
||||
if len(undispatched) != 1 || undispatched[0].EventType != id {
|
||||
t.Fatalf("ListUndispatchedCaptures() = %+v, want only the identified capture", undispatched)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
var _ storecontract.EventTypeStore = (*EDA)(nil)
|
||||
|
||||
func eventTypeValue(r postgresdb.EventType) (eventtype.EventType, error) {
|
||||
t := eventtype.EventType{ID: r.ID, Source: r.Source, Name: r.Name, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
|
||||
if err := json.Unmarshal([]byte(r.Rule), &t.Rule); err != nil {
|
||||
return eventtype.EventType{}, fmt.Errorf("edastore: decode event type rule: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(r.Schema), &t.Schema); err != nil {
|
||||
return eventtype.EventType{}, fmt.Errorf("edastore: decode event type schema: %w", err)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func eventTypeValues(rows []postgresdb.EventType) ([]eventtype.EventType, error) {
|
||||
out := make([]eventtype.EventType, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
t, err := eventTypeValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// identifyCapture returns the ID of the one event type on the capture's
|
||||
// source that matches it, or "" when it is unidentified.
|
||||
func (s *EDA) identifyCapture(ctx context.Context, c storecontract.CapturedEvent) (string, error) {
|
||||
rows, err := s.q.EventTypesForSource(ctx, c.Source)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("edastore: load event types: %w", err)
|
||||
}
|
||||
types, err := eventTypeValues(rows)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
t, _ := eventtype.Identify(types, c.Source, eventtype.Sample{
|
||||
Headers: eventtype.ParseHeaders(c.Headers),
|
||||
Body: []byte(c.Body),
|
||||
})
|
||||
return t.ID, nil
|
||||
}
|
||||
|
||||
// saveEventType validates t, then, under a per-source lock, refuses it if its
|
||||
// rule overlaps another type on the source and runs write.
|
||||
func (s *EDA) saveEventType(ctx context.Context, t eventtype.EventType, write func(*postgresdb.Queries, string) error) error {
|
||||
if err := t.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
rule, err := json.Marshal(t.Rule)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: encode event type rule: %w", err)
|
||||
}
|
||||
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
q := s.q.WithTx(tx)
|
||||
if err := q.LockEventTypeSource(ctx, t.Source); err != nil {
|
||||
return fmt.Errorf("edastore: lock event types: %w", err)
|
||||
}
|
||||
rows, err := q.EventTypesForSource(ctx, t.Source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: load event types: %w", err)
|
||||
}
|
||||
existing, err := eventTypeValues(rows)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := eventtype.CheckOverlap(existing, t); err != nil {
|
||||
return err
|
||||
}
|
||||
err = write(q, string(rule))
|
||||
if isUniqueViolation(err) {
|
||||
return fmt.Errorf("%w: name %q is taken on source %q", eventtype.ErrInvalid, t.Name, t.Source)
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// InsertEventType stores a new event type.
|
||||
func (s *EDA) InsertEventType(ctx context.Context, t eventtype.EventType) (string, error) {
|
||||
t.ID = ""
|
||||
schema, err := json.Marshal(t.Schema)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("edastore: encode event type schema: %w", err)
|
||||
}
|
||||
id := newRecordID()
|
||||
err = s.saveEventType(ctx, t, func(q *postgresdb.Queries, rule string) error {
|
||||
return q.InsertEventType(ctx, postgresdb.InsertEventTypeParams{
|
||||
ID: id, Source: t.Source, Name: t.Name, Rule: rule, Schema: string(schema),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// UpdateEventType rewrites a type's name and rule. Its source and schema are
|
||||
// the stored ones.
|
||||
func (s *EDA) UpdateEventType(ctx context.Context, t eventtype.EventType) error {
|
||||
stored, err := s.q.GetEventType(ctx, t.ID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.Source = stored.Source
|
||||
return s.saveEventType(ctx, t, func(q *postgresdb.Queries, rule string) error {
|
||||
n, err := q.UpdateEventType(ctx, postgresdb.UpdateEventTypeParams{ID: t.ID, Name: t.Name, Rule: rule})
|
||||
if err == nil && n == 0 {
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteEventType removes a type. Captures already identified as it keep the
|
||||
// ID they were stored with.
|
||||
func (s *EDA) DeleteEventType(ctx context.Context, id string) error {
|
||||
n, err := s.q.DeleteEventType(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListEventTypes returns every event type, by source then name.
|
||||
func (s *EDA) ListEventTypes(ctx context.Context) ([]eventtype.EventType, error) {
|
||||
rows, err := s.q.ListEventTypes(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: list event types: %w", err)
|
||||
}
|
||||
return eventTypeValues(rows)
|
||||
}
|
||||
@@ -91,159 +91,6 @@ func TestPlaybookDispatchIsIdempotent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Hazard 3: "one binding per source" is a schema constraint, so concurrent
|
||||
// inserts for one source produce exactly one success and one ErrBindingOverlap
|
||||
// rather than two bindings that a single SQLite writer would have serialised.
|
||||
func TestConcurrentInsertBindingSameSource(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
type result struct{ err error }
|
||||
start := make(chan struct{})
|
||||
results := make(chan result, 2)
|
||||
for range 2 {
|
||||
go func() {
|
||||
<-start
|
||||
_, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
|
||||
})
|
||||
results <- result{err: err}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
|
||||
var succeeded, overlapped int
|
||||
for range 2 {
|
||||
outcome := <-results
|
||||
switch {
|
||||
case outcome.err == nil:
|
||||
succeeded++
|
||||
case errors.Is(outcome.err, storecontract.ErrBindingOverlap):
|
||||
overlapped++
|
||||
default:
|
||||
t.Fatalf("concurrent InsertBinding error = %v", outcome.err)
|
||||
}
|
||||
}
|
||||
if succeeded != 1 || overlapped != 1 {
|
||||
t.Fatalf("concurrent inserts = %d succeeded, %d overlapped; want 1 each", succeeded, overlapped)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 := bindingcipher.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 := bindingcipher.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)
|
||||
}
|
||||
}
|
||||
|
||||
// A deployment with no configured key stores plaintext.
|
||||
func TestNoCipherKeepsPlaintext(t *testing.T) {
|
||||
pool, s := edaWithCipher(t, nil)
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "src-plain"}, Workflow: "implement",
|
||||
Secret: "supersecretvalue0123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
if stored := readRawSecret(t, pool, id); stored != "supersecretvalue0123" {
|
||||
t.Errorf("stored secret = %q, want the plaintext with no cipher configured", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// A secret written under the previous key stays readable once a new active
|
||||
// key is installed; otherwise rotation bricks every armed binding.
|
||||
func TestRotatedKeyStillReadsOldRows(t *testing.T) {
|
||||
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
oldCipher, err := bindingcipher.NewBindingCipher(oldKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(old) error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, oldCipher)
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "src-rotate"}, Workflow: "implement",
|
||||
Secret: "supersecretvalue0123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
rotated, err := bindingcipher.NewBindingCipher(edaTestKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
|
||||
}
|
||||
got, err := NewEDA(pool, rotated).GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() after rotation error = %v", err)
|
||||
}
|
||||
if got.Secret != "supersecretvalue0123" {
|
||||
t.Errorf("Secret after rotation = %q: the previous key must still decrypt", got.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// The lifecycle gate survives the port: pending_approval -> armed, and only
|
||||
// from pending_approval.
|
||||
func TestBindingLifecycle(t *testing.T) {
|
||||
@@ -262,9 +109,8 @@ func TestBindingLifecycle(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A capture round-trips its payload verbatim, and a dispatched capture drops
|
||||
// out of the undispatched listing.
|
||||
func TestCaptureRoundTripAndUndispatched(t *testing.T) {
|
||||
// A capture round-trips its payload verbatim.
|
||||
func TestCaptureRoundTrip(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
body := `{"action":"created"}`
|
||||
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{
|
||||
@@ -279,19 +125,6 @@ func TestCaptureRoundTripAndUndispatched(t *testing.T) {
|
||||
if list[0].Body != body {
|
||||
t.Errorf("Body round-trip = %q, want %q", list[0].Body, body)
|
||||
}
|
||||
|
||||
undispatched, err := s.ListUndispatchedCaptures(t.Context(), []string{"sentry"}, 10)
|
||||
if err != nil || len(undispatched) != 1 {
|
||||
t.Fatalf("ListUndispatchedCaptures() = %d (err %v), want 1", len(undispatched), err)
|
||||
}
|
||||
// Dispatch it; the capture must no longer be undispatched.
|
||||
if err := s.RecordDispatch(t.Context(), "b1", 1, list[0].ID, 42); err != nil {
|
||||
t.Fatalf("RecordDispatch() error = %v", err)
|
||||
}
|
||||
undispatched, err = s.ListUndispatchedCaptures(t.Context(), []string{"sentry"}, 10)
|
||||
if err != nil || len(undispatched) != 0 {
|
||||
t.Fatalf("ListUndispatchedCaptures() after dispatch = %d (err %v), want 0", len(undispatched), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingCRUD(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;
|
||||
@@ -0,0 +1,29 @@
|
||||
-- Event types: named kinds of event from one source, each defined by a match
|
||||
-- rule (docs/prds/event-automation.md, "Event types"). rule and schema are the
|
||||
-- JSON encodings of eventtype.Rule and the inferred path-to-type schema; the
|
||||
-- store evaluates them in Go, so they are opaque text here.
|
||||
--
|
||||
-- captures.event_type records the type a capture was identified as when it
|
||||
-- arrived. Empty means unidentified, and an unidentified capture is never
|
||||
-- listed for dispatch. It is a plain text column, not a foreign key: deleting
|
||||
-- a type must not rewrite what past captures were identified as.
|
||||
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE event_types (
|
||||
id text PRIMARY KEY,
|
||||
source text NOT NULL,
|
||||
name text NOT NULL,
|
||||
rule text NOT NULL,
|
||||
schema text NOT NULL DEFAULT '{}',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE UNIQUE INDEX idx_event_types_source_name ON event_types (source, name);
|
||||
|
||||
ALTER TABLE captures ADD COLUMN event_type text NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
ALTER TABLE captures DROP COLUMN event_type;
|
||||
DROP TABLE event_types;
|
||||
@@ -0,0 +1,34 @@
|
||||
-- Mappings per event type, match counts and several bindings per source
|
||||
-- (docs/prds/event-automation.md, "Mappings" and "Bindings").
|
||||
--
|
||||
-- mappings.event_type is the event type a mapping belongs to; like
|
||||
-- captures.event_type it is plain text, not a foreign key. A binding applies
|
||||
-- to its mapping's event type, so any number of bindings may share a source
|
||||
-- and the two per-source unique indexes are dropped.
|
||||
--
|
||||
-- mapping_matches holds one row per (mapping, capture) the mapping resolved;
|
||||
-- a mapping's matched-event count and last match are read from it.
|
||||
-- bindings.filter is an optional CEL expression over the mapping's parameters.
|
||||
|
||||
-- +goose Up
|
||||
|
||||
ALTER TABLE mappings ADD COLUMN event_type text NOT NULL DEFAULT '';
|
||||
ALTER TABLE bindings ADD COLUMN filter text NOT NULL DEFAULT '';
|
||||
|
||||
DROP INDEX idx_bindings_source;
|
||||
DROP INDEX idx_bindings_armed_source;
|
||||
|
||||
CREATE TABLE mapping_matches (
|
||||
mapping text NOT NULL,
|
||||
capture text NOT NULL,
|
||||
matched_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (mapping, capture)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE mapping_matches;
|
||||
CREATE UNIQUE INDEX idx_bindings_armed_source ON bindings (source) WHERE status = 'armed';
|
||||
CREATE UNIQUE INDEX idx_bindings_source ON bindings (source);
|
||||
ALTER TABLE bindings DROP COLUMN filter;
|
||||
ALTER TABLE mappings DROP COLUMN event_type;
|
||||
@@ -11,19 +11,34 @@ 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, filter
|
||||
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
|
||||
Filter string
|
||||
}
|
||||
|
||||
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,9 +49,9 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]
|
||||
&i.Repo,
|
||||
&i.Version,
|
||||
&i.Status,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Filter,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -80,6 +95,18 @@ func (q *Queries) DeleteCapturesOlderThan(ctx context.Context, receivedAt time.T
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteEventType = `-- name: DeleteEventType :execrows
|
||||
DELETE FROM event_types WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteEventType(ctx context.Context, id string) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteEventType, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const deleteMapping = `-- name: DeleteMapping :execrows
|
||||
DELETE FROM mappings WHERE id = $1
|
||||
`
|
||||
@@ -101,14 +128,71 @@ 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
|
||||
`
|
||||
|
||||
func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]EventType, error) {
|
||||
rows, err := q.db.Query(ctx, eventTypesForSource, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []EventType
|
||||
for rows.Next() {
|
||||
var i EventType
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Source,
|
||||
&i.Name,
|
||||
&i.Rule,
|
||||
&i.Schema,
|
||||
&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 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, filter
|
||||
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
|
||||
Filter string
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -119,7 +203,27 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
|
||||
&i.Repo,
|
||||
&i.Version,
|
||||
&i.Status,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Filter,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getEventType = `-- name: GetEventType :one
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetEventType(ctx context.Context, id string) (EventType, error) {
|
||||
row := q.db.QueryRow(ctx, getEventType, id)
|
||||
var i EventType
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Source,
|
||||
&i.Name,
|
||||
&i.Rule,
|
||||
&i.Schema,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
@@ -127,18 +231,46 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
|
||||
}
|
||||
|
||||
const getMapping = `-- name: GetMapping :one
|
||||
SELECT id, name, source_hint, fields, created_at, updated_at
|
||||
SELECT mappings.id, mappings.name, mappings.source_hint, mappings.fields, mappings.created_at, mappings.updated_at, mappings.event_type,
|
||||
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
|
||||
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
|
||||
FROM mappings WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetMapping(ctx context.Context, id string) (Mapping, error) {
|
||||
type GetMappingRow struct {
|
||||
Mapping Mapping
|
||||
MatchCount int64
|
||||
LastMatchedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) GetMapping(ctx context.Context, id string) (GetMappingRow, error) {
|
||||
row := q.db.QueryRow(ctx, getMapping, id)
|
||||
var i Mapping
|
||||
var i GetMappingRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
&i.SourceHint,
|
||||
&i.Fields,
|
||||
&i.Mapping.ID,
|
||||
&i.Mapping.Name,
|
||||
&i.Mapping.SourceHint,
|
||||
&i.Mapping.Fields,
|
||||
&i.Mapping.CreatedAt,
|
||||
&i.Mapping.UpdatedAt,
|
||||
&i.Mapping.EventType,
|
||||
&i.MatchCount,
|
||||
&i.LastMatchedAt,
|
||||
)
|
||||
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,
|
||||
)
|
||||
@@ -146,8 +278,8 @@ func (q *Queries) GetMapping(ctx context.Context, id string) (Mapping, error) {
|
||||
}
|
||||
|
||||
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, filter, workflow, owner, repo, version, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9)
|
||||
`
|
||||
|
||||
type InsertBindingParams struct {
|
||||
@@ -155,11 +287,11 @@ type InsertBindingParams struct {
|
||||
Name string
|
||||
Source string
|
||||
Mapping string
|
||||
Filter string
|
||||
Workflow string
|
||||
Owner string
|
||||
Repo string
|
||||
Status string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) error {
|
||||
@@ -168,11 +300,11 @@ func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) er
|
||||
arg.Name,
|
||||
arg.Source,
|
||||
arg.Mapping,
|
||||
arg.Filter,
|
||||
arg.Workflow,
|
||||
arg.Owner,
|
||||
arg.Repo,
|
||||
arg.Status,
|
||||
arg.Secret,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -201,8 +333,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)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
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 {
|
||||
@@ -214,6 +346,8 @@ type InsertCaptureParams struct {
|
||||
Body string
|
||||
Authenticated bool
|
||||
ReceivedAt time.Time
|
||||
Unsigned bool
|
||||
EventType string
|
||||
}
|
||||
|
||||
// EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls.
|
||||
@@ -227,19 +361,46 @@ func (q *Queries) InsertCapture(ctx context.Context, arg InsertCaptureParams) er
|
||||
arg.Body,
|
||||
arg.Authenticated,
|
||||
arg.ReceivedAt,
|
||||
arg.Unsigned,
|
||||
arg.EventType,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertEventType = `-- name: InsertEventType :exec
|
||||
INSERT INTO event_types (id, source, name, rule, schema)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
type InsertEventTypeParams struct {
|
||||
ID string
|
||||
Source string
|
||||
Name string
|
||||
Rule string
|
||||
Schema string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertEventType(ctx context.Context, arg InsertEventTypeParams) error {
|
||||
_, err := q.db.Exec(ctx, insertEventType,
|
||||
arg.ID,
|
||||
arg.Source,
|
||||
arg.Name,
|
||||
arg.Rule,
|
||||
arg.Schema,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertMapping = `-- name: InsertMapping :exec
|
||||
INSERT INTO mappings (id, name, source_hint, fields)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
INSERT INTO mappings (id, name, source_hint, event_type, fields)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`
|
||||
|
||||
type InsertMappingParams struct {
|
||||
ID string
|
||||
Name string
|
||||
SourceHint string
|
||||
EventType string
|
||||
Fields string
|
||||
}
|
||||
|
||||
@@ -248,11 +409,27 @@ func (q *Queries) InsertMapping(ctx context.Context, arg InsertMappingParams) er
|
||||
arg.ID,
|
||||
arg.Name,
|
||||
arg.SourceHint,
|
||||
arg.EventType,
|
||||
arg.Fields,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertMappingMatch = `-- name: InsertMappingMatch :exec
|
||||
INSERT INTO mapping_matches (mapping, capture) VALUES ($1, $2)
|
||||
ON CONFLICT DO NOTHING
|
||||
`
|
||||
|
||||
type InsertMappingMatchParams struct {
|
||||
Mapping string
|
||||
Capture string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertMappingMatch(ctx context.Context, arg InsertMappingMatchParams) error {
|
||||
_, err := q.db.Exec(ctx, insertMappingMatch, arg.Mapping, arg.Capture)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertPlaybookDispatch = `-- name: InsertPlaybookDispatch :exec
|
||||
INSERT INTO playbook_dispatches (playbook_id, playbook_version, event_id, action_id)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
@@ -275,6 +452,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)
|
||||
@@ -304,19 +496,34 @@ 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, filter
|
||||
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
|
||||
Filter string
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -327,9 +534,9 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
|
||||
&i.Repo,
|
||||
&i.Version,
|
||||
&i.Status,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Filter,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -342,7 +549,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
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
|
||||
FROM captures
|
||||
ORDER BY received_at DESC
|
||||
LIMIT $1
|
||||
@@ -366,6 +573,41 @@ 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
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listEventTypes = `-- name: ListEventTypes :many
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types ORDER BY source, name
|
||||
`
|
||||
|
||||
func (q *Queries) ListEventTypes(ctx context.Context) ([]EventType, error) {
|
||||
rows, err := q.db.Query(ctx, listEventTypes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []EventType
|
||||
for rows.Next() {
|
||||
var i EventType
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Source,
|
||||
&i.Name,
|
||||
&i.Rule,
|
||||
&i.Schema,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -378,24 +620,65 @@ func (q *Queries) ListCaptures(ctx context.Context, limit int32) ([]Capture, err
|
||||
}
|
||||
|
||||
const listMappings = `-- name: ListMappings :many
|
||||
SELECT id, name, source_hint, fields, created_at, updated_at
|
||||
SELECT mappings.id, mappings.name, mappings.source_hint, mappings.fields, mappings.created_at, mappings.updated_at, mappings.event_type,
|
||||
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
|
||||
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
|
||||
FROM mappings ORDER BY created_at DESC
|
||||
`
|
||||
|
||||
func (q *Queries) ListMappings(ctx context.Context) ([]Mapping, error) {
|
||||
type ListMappingsRow struct {
|
||||
Mapping Mapping
|
||||
MatchCount int64
|
||||
LastMatchedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) ListMappings(ctx context.Context) ([]ListMappingsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listMappings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Mapping
|
||||
var items []ListMappingsRow
|
||||
for rows.Next() {
|
||||
var i Mapping
|
||||
var i ListMappingsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
&i.SourceHint,
|
||||
&i.Fields,
|
||||
&i.Mapping.ID,
|
||||
&i.Mapping.Name,
|
||||
&i.Mapping.SourceHint,
|
||||
&i.Mapping.Fields,
|
||||
&i.Mapping.CreatedAt,
|
||||
&i.Mapping.UpdatedAt,
|
||||
&i.Mapping.EventType,
|
||||
&i.MatchCount,
|
||||
&i.LastMatchedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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 {
|
||||
@@ -410,11 +693,16 @@ func (q *Queries) ListMappings(ctx context.Context) ([]Mapping, error) {
|
||||
}
|
||||
|
||||
const listUndispatchedCaptures = `-- name: ListUndispatchedCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at
|
||||
FROM captures
|
||||
WHERE source = ANY($1::text[])
|
||||
AND id NOT IN (SELECT capture FROM binding_dispatches)
|
||||
ORDER BY received_at DESC
|
||||
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type
|
||||
FROM captures c
|
||||
WHERE c.source = ANY($1::text[])
|
||||
AND c.event_type <> ''
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM bindings b JOIN mappings m ON m.id = b.mapping
|
||||
WHERE b.source = c.source AND b.status = 'armed' AND m.event_type = c.event_type
|
||||
AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.capture = c.id)
|
||||
)
|
||||
ORDER BY c.received_at DESC
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
@@ -423,6 +711,9 @@ type ListUndispatchedCapturesParams struct {
|
||||
EntryLimit int32
|
||||
}
|
||||
|
||||
// A capture is undispatched while some armed binding on its source, whose
|
||||
// mapping belongs to the capture's event type, has not dispatched it. An
|
||||
// unidentified capture has no event type, so it is never listed.
|
||||
func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispatchedCapturesParams) ([]Capture, error) {
|
||||
rows, err := q.db.Query(ctx, listUndispatchedCaptures, arg.Sources, arg.EntryLimit)
|
||||
if err != nil {
|
||||
@@ -441,6 +732,8 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat
|
||||
&i.Body,
|
||||
&i.Authenticated,
|
||||
&i.ReceivedAt,
|
||||
&i.Unsigned,
|
||||
&i.EventType,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -452,6 +745,17 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockEventTypeSource = `-- name: LockEventTypeSource :exec
|
||||
SELECT pg_advisory_xact_lock(hashtext('event_types:' || $1::text))
|
||||
`
|
||||
|
||||
// Serialises saves per source so two concurrent saves cannot each pass the
|
||||
// overlap check against a set that excludes the other.
|
||||
func (q *Queries) LockEventTypeSource(ctx context.Context, source string) error {
|
||||
_, err := q.db.Exec(ctx, lockEventTypeSource, source)
|
||||
return err
|
||||
}
|
||||
|
||||
const setBindingArmed = `-- name: SetBindingArmed :execrows
|
||||
UPDATE bindings SET status = 'armed', updated_at = now() WHERE id = $1
|
||||
`
|
||||
@@ -464,6 +768,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
|
||||
@@ -509,10 +860,8 @@ 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()
|
||||
SET name = $2, source = $3, mapping = $4, filter = $5, workflow = $6, owner = $7, repo = $8,
|
||||
version = version + 1, status = $9, updated_at = now()
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
@@ -521,27 +870,24 @@ type UpdateBindingParams struct {
|
||||
Name string
|
||||
Source string
|
||||
Mapping string
|
||||
Filter string
|
||||
Workflow string
|
||||
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,
|
||||
arg.Name,
|
||||
arg.Source,
|
||||
arg.Mapping,
|
||||
arg.Filter,
|
||||
arg.Workflow,
|
||||
arg.Owner,
|
||||
arg.Repo,
|
||||
arg.Status,
|
||||
arg.Secret,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -549,9 +895,27 @@ func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (i
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const updateEventType = `-- name: UpdateEventType :execrows
|
||||
UPDATE event_types SET name = $2, rule = $3, updated_at = now() WHERE id = $1
|
||||
`
|
||||
|
||||
type UpdateEventTypeParams struct {
|
||||
ID string
|
||||
Name string
|
||||
Rule string
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateEventType(ctx context.Context, arg UpdateEventTypeParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, updateEventType, arg.ID, arg.Name, arg.Rule)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const updateMapping = `-- name: UpdateMapping :execrows
|
||||
UPDATE mappings
|
||||
SET name = $2, source_hint = $3, fields = $4, updated_at = now()
|
||||
SET name = $2, source_hint = $3, event_type = $4, fields = $5, updated_at = now()
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
@@ -559,6 +923,7 @@ type UpdateMappingParams struct {
|
||||
ID string
|
||||
Name string
|
||||
SourceHint string
|
||||
EventType string
|
||||
Fields string
|
||||
}
|
||||
|
||||
@@ -567,6 +932,7 @@ func (q *Queries) UpdateMapping(ctx context.Context, arg UpdateMappingParams) (i
|
||||
arg.ID,
|
||||
arg.Name,
|
||||
arg.SourceHint,
|
||||
arg.EventType,
|
||||
arg.Fields,
|
||||
)
|
||||
if err != nil {
|
||||
|
||||
@@ -29,6 +29,7 @@ type Binding struct {
|
||||
Secret string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Filter string
|
||||
}
|
||||
|
||||
type BindingDispatch struct {
|
||||
@@ -48,6 +49,8 @@ type Capture struct {
|
||||
Body string
|
||||
Authenticated bool
|
||||
ReceivedAt time.Time
|
||||
Unsigned bool
|
||||
EventType string
|
||||
}
|
||||
|
||||
type ChannelStatus struct {
|
||||
@@ -84,6 +87,16 @@ type Event struct {
|
||||
Data string
|
||||
}
|
||||
|
||||
type EventType struct {
|
||||
ID string
|
||||
Source string
|
||||
Name string
|
||||
Rule string
|
||||
Schema string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Identity struct {
|
||||
ID string
|
||||
Kind string
|
||||
@@ -133,6 +146,13 @@ type Mapping struct {
|
||||
Fields string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
EventType string
|
||||
}
|
||||
|
||||
type MappingMatch struct {
|
||||
Mapping string
|
||||
Capture string
|
||||
MatchedAt time.Time
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
@@ -189,6 +209,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,21 +1,29 @@
|
||||
-- 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)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8);
|
||||
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
|
||||
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
|
||||
FROM captures
|
||||
WHERE source = ANY(@sources::text[])
|
||||
AND id NOT IN (SELECT capture FROM binding_dispatches)
|
||||
ORDER BY received_at DESC
|
||||
-- A capture is undispatched while some armed binding on its source, whose
|
||||
-- mapping belongs to the capture's event type, has not dispatched it. An
|
||||
-- unidentified capture has no event type, so it is never listed.
|
||||
SELECT c.id, c.source, c.remote_addr, c.content_type, c.headers, c.body, c.authenticated, c.received_at, c.unsigned, c.event_type
|
||||
FROM captures c
|
||||
WHERE c.source = ANY(@sources::text[])
|
||||
AND c.event_type <> ''
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM bindings b JOIN mappings m ON m.id = b.mapping
|
||||
WHERE b.source = c.source AND b.status = 'armed' AND m.event_type = c.event_type
|
||||
AND NOT EXISTS (SELECT 1 FROM binding_dispatches d WHERE d.binding = b.id AND d.capture = c.id)
|
||||
)
|
||||
ORDER BY c.received_at DESC
|
||||
LIMIT @entry_limit;
|
||||
|
||||
-- name: DeleteCapturesOlderThan :exec
|
||||
@@ -27,50 +35,53 @@ DELETE FROM captures WHERE id NOT IN (
|
||||
);
|
||||
|
||||
-- name: InsertMapping :exec
|
||||
INSERT INTO mappings (id, name, source_hint, fields)
|
||||
VALUES ($1, $2, $3, $4);
|
||||
INSERT INTO mappings (id, name, source_hint, event_type, fields)
|
||||
VALUES ($1, $2, $3, $4, $5);
|
||||
|
||||
-- name: GetMapping :one
|
||||
SELECT id, name, source_hint, fields, created_at, updated_at
|
||||
SELECT sqlc.embed(mappings),
|
||||
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
|
||||
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
|
||||
FROM mappings WHERE id = $1;
|
||||
|
||||
-- name: ListMappings :many
|
||||
SELECT id, name, source_hint, fields, created_at, updated_at
|
||||
SELECT sqlc.embed(mappings),
|
||||
(SELECT count(*) FROM mapping_matches mm WHERE mm.mapping = mappings.id)::bigint AS match_count,
|
||||
COALESCE((SELECT max(mm.matched_at) FROM mapping_matches mm WHERE mm.mapping = mappings.id), 'epoch')::timestamptz AS last_matched_at
|
||||
FROM mappings ORDER BY created_at DESC;
|
||||
|
||||
-- name: UpdateMapping :execrows
|
||||
UPDATE mappings
|
||||
SET name = $2, source_hint = $3, fields = $4, updated_at = now()
|
||||
SET name = $2, source_hint = $3, event_type = $4, fields = $5, updated_at = now()
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: InsertMappingMatch :exec
|
||||
INSERT INTO mapping_matches (mapping, capture) VALUES ($1, $2)
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- name: DeleteMapping :execrows
|
||||
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, filter, workflow, owner, repo, version, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9);
|
||||
|
||||
-- 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, filter
|
||||
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, filter
|
||||
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, filter
|
||||
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()
|
||||
SET name = $2, source = $3, mapping = $4, filter = $5, workflow = $6, owner = $7, repo = $8,
|
||||
version = version + 1, status = $9, updated_at = now()
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: SetBindingArmed :execrows
|
||||
@@ -97,3 +108,51 @@ VALUES ($1, $2, $3, $4, $5, $6, $7);
|
||||
-- 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;
|
||||
|
||||
-- name: InsertEventType :exec
|
||||
INSERT INTO event_types (id, source, name, rule, schema)
|
||||
VALUES ($1, $2, $3, $4, $5);
|
||||
|
||||
-- name: GetEventType :one
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types WHERE id = $1;
|
||||
|
||||
-- name: ListEventTypes :many
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types ORDER BY source, name;
|
||||
|
||||
-- name: EventTypesForSource :many
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types WHERE source = $1 ORDER BY name;
|
||||
|
||||
-- name: UpdateEventType :execrows
|
||||
UPDATE event_types SET name = $2, rule = $3, updated_at = now() WHERE id = $1;
|
||||
|
||||
-- name: DeleteEventType :execrows
|
||||
DELETE FROM event_types WHERE id = $1;
|
||||
|
||||
-- name: LockEventTypeSource :exec
|
||||
-- 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();
|
||||
@@ -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,213 @@
|
||||
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/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/bindingcipher"
|
||||
)
|
||||
|
||||
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 := bindingcipher.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)
|
||||
}
|
||||
}
|
||||
|
||||
// sourceUnder inserts a new source through a store sealing with cipher.
|
||||
func sourceUnder(t *testing.T, cipher bindingcipher.BindingCipher) (*pgxpool.Pool, source.Source) {
|
||||
t.Helper()
|
||||
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)
|
||||
}
|
||||
return pool, in
|
||||
}
|
||||
|
||||
// A deployment with no configured key stores plaintext.
|
||||
func TestSourceNoCipherKeepsPlaintext(t *testing.T) {
|
||||
pool, in := sourceUnder(t, nil)
|
||||
if raw := readRawSourceSecret(t, pool, in.Path); raw != in.Secret {
|
||||
t.Errorf("stored secret = %q, want the plaintext with no cipher configured", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// A secret written under the previous key stays readable once a new active
|
||||
// key is installed; otherwise rotation bricks every signed source.
|
||||
func TestSourceRotatedKeyStillReadsOldRows(t *testing.T) {
|
||||
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
oldCipher, err := bindingcipher.NewBindingCipher(oldKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(old) error = %v", err)
|
||||
}
|
||||
pool, in := sourceUnder(t, oldCipher)
|
||||
rotated, err := bindingcipher.NewBindingCipher(edaTestKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
|
||||
}
|
||||
got, err := NewEDA(pool, rotated).GetSource(t.Context(), in.Path)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetSource() after rotation = %v, %v", got, err)
|
||||
}
|
||||
if got.Secret != in.Secret {
|
||||
t.Errorf("Secret after rotation = %q: the previous key must still decrypt", got.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
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 with an armed binding for its type is listed
|
||||
// for dispatch; a catch-all type identifies every event on the source.
|
||||
etID, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "any"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "m", EventTypeID: etID})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
}
|
||||
armedBinding(t, s, "fw", mid)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"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/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
@@ -13,6 +14,12 @@ import (
|
||||
func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
|
||||
local := pgstore.Open(t)
|
||||
eda := pgstore.EDA(t, nil)
|
||||
// Only an identified capture is listed for dispatch; a catch-all type
|
||||
// identifies every event on the source as it arrives.
|
||||
eventTypeID, etErr := eda.InsertEventType(t.Context(), eventtype.EventType{Source: "large", Name: "any"})
|
||||
if etErr != nil {
|
||||
t.Fatal(etErr)
|
||||
}
|
||||
body := strings.Repeat("x", 256<<10)
|
||||
for range 20 {
|
||||
if _, err := eda.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
@@ -22,8 +29,9 @@ func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
|
||||
// A binding's mapping is a real relation now, so it must point at a
|
||||
// mapping that exists; the store refuses a dangling id.
|
||||
mappingID, mapErr := eda.InsertMapping(t.Context(), mapping.Mapping{
|
||||
Name: "m",
|
||||
Fields: []mapping.Field{{Name: "title", Path: "title", Type: mapping.TypeString}},
|
||||
Name: "m",
|
||||
EventTypeID: eventTypeID,
|
||||
Fields: []mapping.Field{{Name: "title", Path: "title", Type: mapping.TypeString}},
|
||||
})
|
||||
if mapErr != nil {
|
||||
t.Fatal(mapErr)
|
||||
@@ -33,14 +41,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"
|
||||
@@ -41,19 +42,21 @@ func (c *Client) ControlPlane() controlpb.ControlPlaneServiceClient { return c.c
|
||||
func (c *Client) Close() error { return nil }
|
||||
|
||||
var (
|
||||
_ task.Store = (*Client)(nil)
|
||||
_ storecontract.TaskStore = (*Client)(nil)
|
||||
_ storecontract.TaskLogStore = (*Client)(nil)
|
||||
_ storecontract.CaptureStore = (*Client)(nil)
|
||||
_ storecontract.MappingStore = (*Client)(nil)
|
||||
_ storecontract.BindingStore = (*Client)(nil)
|
||||
_ storecontract.BindingDispatcher = (*Client)(nil)
|
||||
_ storecontract.BindingTaskCreator = (*Client)(nil)
|
||||
_ storecontract.PlaybookDispatcher = (*Client)(nil)
|
||||
_ storecontract.ConfigSnapshotStore = (*Client)(nil)
|
||||
_ storecontract.ChannelStatusStore = (*Client)(nil)
|
||||
_ storecontract.ApplyStatusStore = (*Client)(nil)
|
||||
_ identity.Repository = (*Client)(nil)
|
||||
_ task.Store = (*Client)(nil)
|
||||
_ storecontract.TaskStore = (*Client)(nil)
|
||||
_ storecontract.TaskLogStore = (*Client)(nil)
|
||||
_ storecontract.CaptureStore = (*Client)(nil)
|
||||
_ storecontract.MappingStore = (*Client)(nil)
|
||||
_ storecontract.BindingStore = (*Client)(nil)
|
||||
_ storecontract.SourceStore = (*Client)(nil)
|
||||
_ storecontract.BindingDispatcher = (*Client)(nil)
|
||||
_ storecontract.MappingMatchRecorder = (*Client)(nil)
|
||||
_ storecontract.BindingTaskCreator = (*Client)(nil)
|
||||
_ storecontract.PlaybookDispatcher = (*Client)(nil)
|
||||
_ storecontract.ConfigSnapshotStore = (*Client)(nil)
|
||||
_ storecontract.ChannelStatusStore = (*Client)(nil)
|
||||
_ storecontract.ApplyStatusStore = (*Client)(nil)
|
||||
_ identity.Repository = (*Client)(nil)
|
||||
)
|
||||
|
||||
// Lifecycle
|
||||
@@ -415,6 +418,11 @@ func (c *Client) DeleteMapping(ctx context.Context, id string) error {
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) RecordMappingMatch(ctx context.Context, mappingID, captureID string) error {
|
||||
_, err := c.client.RecordMappingMatch(ctx, &pb.RecordMappingMatchRequest{MappingId: mappingID, CaptureId: captureID})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
// Binding
|
||||
|
||||
func (c *Client) InsertBinding(ctx context.Context, b binding.Binding) (string, error) {
|
||||
@@ -460,6 +468,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) {
|
||||
|
||||
@@ -380,22 +380,22 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
t.Fatalf("DeleteMapping missing = %v, want ErrMappingNotFound", err)
|
||||
}
|
||||
|
||||
// Binding: found=false, ErrBindingNotFound, ErrBindingOverlap,
|
||||
// ErrBindingTransition, and the dispatch surface incl.
|
||||
// Binding: found=false, ErrBindingNotFound, several bindings per
|
||||
// source, ErrBindingTransition, and the dispatch surface incl.
|
||||
// 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, storecontract.ErrBindingOverlap) {
|
||||
t.Fatalf("InsertBinding overlap = %v, want ErrBindingOverlap", err)
|
||||
if err != nil {
|
||||
t.Fatalf("second InsertBinding on a source = %v, want accepted", err)
|
||||
}
|
||||
missingBinding, err := ec.GetBinding(ctx, "rabsent00000000")
|
||||
if err != nil || missingBinding != nil {
|
||||
|
||||
@@ -67,7 +67,7 @@ func TestMapErrorPreservesContextIdentity(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestUnmapErrorSentinelFidelity pins the §7 sentinel rehydration round-trip
|
||||
// for each store error code, so a consumer's errors.Is(err, store.ErrX) keeps
|
||||
// for each store error code, so a consumer's errors.Is(err, storecontract.ErrX) keeps
|
||||
// working across the wire.
|
||||
func TestUnmapErrorSentinelFidelity(t *testing.T) {
|
||||
tests := []struct {
|
||||
@@ -81,6 +81,9 @@ func TestUnmapErrorSentinelFidelity(t *testing.T) {
|
||||
{name: "binding overlap", store: storecontract.ErrBindingOverlap, rehyd: storecontract.ErrBindingOverlap},
|
||||
{name: "binding transition", store: storecontract.ErrBindingTransition, rehyd: storecontract.ErrBindingTransition},
|
||||
{name: "already dispatched", store: storecontract.ErrAlreadyDispatched, rehyd: storecontract.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) {
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// fakeEventTypes records what crossed the wire and answers with err.
|
||||
type fakeEventTypes struct {
|
||||
saved eventtype.EventType
|
||||
list []eventtype.EventType
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeEventTypes) InsertEventType(_ context.Context, t eventtype.EventType) (string, error) {
|
||||
f.saved = t
|
||||
return "et-1", f.err
|
||||
}
|
||||
|
||||
func (f *fakeEventTypes) UpdateEventType(_ context.Context, t eventtype.EventType) error {
|
||||
f.saved = t
|
||||
return f.err
|
||||
}
|
||||
|
||||
func (f *fakeEventTypes) DeleteEventType(context.Context, string) error { return f.err }
|
||||
|
||||
func (f *fakeEventTypes) ListEventTypes(context.Context) ([]eventtype.EventType, error) {
|
||||
return f.list, f.err
|
||||
}
|
||||
|
||||
func remoteEventTypes(t *testing.T, store storecontract.EventTypeStore) *Client {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
RegisterServer(server, Deps{EventTypes: store})
|
||||
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 TestEventTypeRoundTrip(t *testing.T) {
|
||||
stamp := time.Date(2026, 9, 24, 9, 0, 0, 0, time.UTC)
|
||||
want := eventtype.EventType{
|
||||
ID: "et-1", Source: "gh", Name: "pull_request",
|
||||
Rule: eventtype.Rule{
|
||||
Headers: []eventtype.HeaderCondition{{Name: "x-github-event", Value: "pull_request"}},
|
||||
Payload: []eventtype.PayloadCondition{{Path: "action", Op: eventtype.OpEquals, Value: "opened"}},
|
||||
},
|
||||
Schema: map[string]eventtype.ValueType{"action": eventtype.TypeString},
|
||||
CreatedAt: stamp, UpdatedAt: stamp.Add(time.Hour),
|
||||
}
|
||||
fake := &fakeEventTypes{list: []eventtype.EventType{want}}
|
||||
c := remoteEventTypes(t, fake)
|
||||
|
||||
got, err := c.ListEventTypes(t.Context())
|
||||
if err != nil || len(got) != 1 || !reflect.DeepEqual(got[0], want) {
|
||||
t.Fatalf("ListEventTypes() = %+v (err %v), want %+v", got, err, want)
|
||||
}
|
||||
id, err := c.InsertEventType(t.Context(), want)
|
||||
if err != nil || id != "et-1" {
|
||||
t.Fatalf("InsertEventType() = %q, %v", id, err)
|
||||
}
|
||||
if !reflect.DeepEqual(fake.saved, want) {
|
||||
t.Fatalf("server received %+v, want %+v", fake.saved, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeErrorsCrossTheWire(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
}{
|
||||
{"overlap", eventtype.ErrOverlap},
|
||||
{"invalid", eventtype.ErrInvalid},
|
||||
{"not found", storecontract.ErrEventTypeNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c := remoteEventTypes(t, &fakeEventTypes{err: tt.err})
|
||||
if _, err := c.InsertEventType(t.Context(), eventtype.EventType{}); !errors.Is(err, tt.err) {
|
||||
t.Errorf("InsertEventType error = %v, want %v", err, tt.err)
|
||||
}
|
||||
if err := c.UpdateEventType(t.Context(), eventtype.EventType{}); !errors.Is(err, tt.err) {
|
||||
t.Errorf("UpdateEventType error = %v, want %v", err, tt.err)
|
||||
}
|
||||
if err := c.DeleteEventType(t.Context(), "x"); !errors.Is(err, tt.err) {
|
||||
t.Errorf("DeleteEventType error = %v, want %v", err, tt.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapturedEventCarriesEventType(t *testing.T) {
|
||||
in := storecontract.CapturedEvent{ID: "c", Source: "gh", EventType: "et-1"}
|
||||
if got := capturedEventValue(capturedEventProto(in)); got.EventType != "et-1" {
|
||||
t.Fatalf("EventType after round trip = %q, want et-1", got.EventType)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
var (
|
||||
_ storecontract.EventTypeStore = (*Client)(nil)
|
||||
|
||||
errEventTypeUnavailable = status.Error(codes.Unavailable, "event type store unavailable")
|
||||
)
|
||||
|
||||
func eventTypeProto(t eventtype.EventType) *pb.EventType {
|
||||
out := &pb.EventType{
|
||||
Id: t.ID, Source: t.Source, Name: t.Name,
|
||||
CreatedAt: timestamp(t.CreatedAt), UpdatedAt: timestamp(t.UpdatedAt),
|
||||
}
|
||||
for _, h := range t.Rule.Headers {
|
||||
out.HeaderConditions = append(out.HeaderConditions, &pb.EventTypeHeaderCondition{Name: h.Name, Value: h.Value})
|
||||
}
|
||||
for _, p := range t.Rule.Payload {
|
||||
out.PayloadConditions = append(out.PayloadConditions, &pb.EventTypePayloadCondition{Path: p.Path, Op: string(p.Op), Value: p.Value})
|
||||
}
|
||||
if len(t.Schema) > 0 {
|
||||
out.Schema = make(map[string]string, len(t.Schema))
|
||||
for path, vt := range t.Schema {
|
||||
out.Schema[path] = string(vt)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func eventTypeValue(t *pb.EventType) eventtype.EventType {
|
||||
if t == nil {
|
||||
return eventtype.EventType{}
|
||||
}
|
||||
out := eventtype.EventType{
|
||||
ID: t.Id, Source: t.Source, Name: t.Name,
|
||||
CreatedAt: timeValue(t.CreatedAt), UpdatedAt: timeValue(t.UpdatedAt),
|
||||
}
|
||||
for _, h := range t.HeaderConditions {
|
||||
out.Rule.Headers = append(out.Rule.Headers, eventtype.HeaderCondition{Name: h.Name, Value: h.Value})
|
||||
}
|
||||
for _, p := range t.PayloadConditions {
|
||||
out.Rule.Payload = append(out.Rule.Payload, eventtype.PayloadCondition{Path: p.Path, Op: eventtype.Operator(p.Op), Value: p.Value})
|
||||
}
|
||||
if len(t.Schema) > 0 {
|
||||
out.Schema = make(map[string]eventtype.ValueType, len(t.Schema))
|
||||
for path, vt := range t.Schema {
|
||||
out.Schema[path] = eventtype.ValueType(vt)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Server
|
||||
|
||||
func (s *server) eventTypes() (storecontract.EventTypeStore, error) {
|
||||
if s.deps.EventTypes == nil {
|
||||
return nil, errEventTypeUnavailable
|
||||
}
|
||||
return s.deps.EventTypes, nil
|
||||
}
|
||||
|
||||
func (s *server) InsertEventType(ctx context.Context, r *pb.InsertEventTypeRequest) (*pb.InsertEventTypeResponse, error) {
|
||||
et, err := s.eventTypes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, err := et.InsertEventType(ctx, eventTypeValue(r.EventType))
|
||||
if err != nil {
|
||||
return nil, s.logErr("InsertEventType", err)
|
||||
}
|
||||
return &pb.InsertEventTypeResponse{Id: id}, nil
|
||||
}
|
||||
|
||||
func (s *server) UpdateEventType(ctx context.Context, r *pb.UpdateEventTypeRequest) (*pb.UpdateEventTypeResponse, error) {
|
||||
et, err := s.eventTypes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := et.UpdateEventType(ctx, eventTypeValue(r.EventType)); err != nil {
|
||||
return nil, s.logErr("UpdateEventType", err)
|
||||
}
|
||||
return &pb.UpdateEventTypeResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) DeleteEventType(ctx context.Context, r *pb.DeleteEventTypeRequest) (*pb.DeleteEventTypeResponse, error) {
|
||||
et, err := s.eventTypes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := et.DeleteEventType(ctx, r.Id); err != nil {
|
||||
return nil, s.logErr("DeleteEventType", err)
|
||||
}
|
||||
return &pb.DeleteEventTypeResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListEventTypes(ctx context.Context, _ *pb.ListEventTypesRequest) (*pb.ListEventTypesResponse, error) {
|
||||
et, err := s.eventTypes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
types, err := et.ListEventTypes(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("ListEventTypes", err)
|
||||
}
|
||||
return &pb.ListEventTypesResponse{EventTypes: mapValues(types, eventTypeProto)}, nil
|
||||
}
|
||||
|
||||
// Client
|
||||
|
||||
func (c *Client) InsertEventType(ctx context.Context, t eventtype.EventType) (string, error) {
|
||||
r, err := c.client.InsertEventType(ctx, &pb.InsertEventTypeRequest{EventType: eventTypeProto(t)})
|
||||
if err != nil {
|
||||
return "", unmapError(err)
|
||||
}
|
||||
return r.Id, nil
|
||||
}
|
||||
|
||||
func (c *Client) UpdateEventType(ctx context.Context, t eventtype.EventType) error {
|
||||
_, err := c.client.UpdateEventType(ctx, &pb.UpdateEventTypeRequest{EventType: eventTypeProto(t)})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteEventType(ctx context.Context, id string) error {
|
||||
_, err := c.client.DeleteEventType(ctx, &pb.DeleteEventTypeRequest{Id: id})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) ListEventTypes(ctx context.Context) ([]eventtype.EventType, error) {
|
||||
r, err := c.client.ListEventTypes(ctx, &pb.ListEventTypesRequest{})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return mapValues(r.EventTypes, eventTypeValue), nil
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
)
|
||||
|
||||
type fakeMappingMatches struct{ mappingID, captureID string }
|
||||
|
||||
func (f *fakeMappingMatches) RecordMappingMatch(_ context.Context, mappingID, captureID string) error {
|
||||
f.mappingID, f.captureID = mappingID, captureID
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestRecordMappingMatchCrossesTheWire(t *testing.T) {
|
||||
fake := &fakeMappingMatches{}
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
RegisterServer(server, Deps{MappingMatches: fake})
|
||||
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() })
|
||||
|
||||
if err := NewClient(conn).RecordMappingMatch(t.Context(), "m1", "c1"); err != nil {
|
||||
t.Fatalf("RecordMappingMatch() error = %v", err)
|
||||
}
|
||||
if fake.mappingID != "m1" || fake.captureID != "c1" {
|
||||
t.Fatalf("server received (%q, %q), want (m1, c1)", fake.mappingID, fake.captureID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMappingAndBindingCarryEventTypeCountsAndFilter(t *testing.T) {
|
||||
stamp := time.Date(2026, 9, 24, 9, 0, 0, 0, time.UTC)
|
||||
m := mapping.Mapping{ID: "m", Name: "n", Fields: []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}}, EventTypeID: "et-1", MatchCount: 7, LastMatchedAt: stamp, CreatedAt: stamp, UpdatedAt: stamp}
|
||||
if got := mappingValue(mappingProto(m)); !reflect.DeepEqual(got, m) {
|
||||
t.Fatalf("mapping after round trip = %+v, want %+v", got, m)
|
||||
}
|
||||
b := binding.Binding{ID: "b", Filter: `severity == "high"`, CreatedAt: stamp, UpdatedAt: stamp}
|
||||
if got := bindingValue(bindingProto(b)); got.Filter != b.Filter {
|
||||
t.Fatalf("binding filter after round trip = %q, want %q", got.Filter, b.Filter)
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
@@ -73,10 +75,15 @@ type Deps struct {
|
||||
// ChannelStatus is the channel runtime state the process hosting the channels
|
||||
// reports. Optional: nil disables the pair with codes.Unavailable, which is
|
||||
// the honest answer for a store service no messaging process is writing to.
|
||||
ChannelStatus storecontract.ChannelStatusStore
|
||||
ApplyStatus storecontract.ApplyStatusStore
|
||||
Mappings storecontract.MappingStore
|
||||
ChannelStatus storecontract.ChannelStatusStore
|
||||
ApplyStatus storecontract.ApplyStatusStore
|
||||
Mappings storecontract.MappingStore
|
||||
EventTypes storecontract.EventTypeStore
|
||||
// MappingMatches counts the events each mapping resolved. Optional: nil
|
||||
// answers RecordMappingMatch with codes.Unavailable.
|
||||
MappingMatches storecontract.MappingMatchRecorder
|
||||
Bindings storecontract.BindingStore
|
||||
Sources storecontract.SourceStore
|
||||
BindingDispatcher storecontract.BindingDispatcher
|
||||
BindingTaskCreator storecontract.BindingTaskCreator
|
||||
// PlaybookDispatcher is the side-effecting-action idempotency ledger
|
||||
@@ -568,6 +575,16 @@ func (s *server) DeleteMapping(ctx context.Context, r *pb.DeleteMappingRequest)
|
||||
return &pb.DeleteMappingResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) RecordMappingMatch(ctx context.Context, r *pb.RecordMappingMatchRequest) (*pb.RecordMappingMatchResponse, error) {
|
||||
if s.deps.MappingMatches == nil {
|
||||
return nil, status.Error(codes.Unavailable, "mapping match recorder unavailable")
|
||||
}
|
||||
if err := s.deps.MappingMatches.RecordMappingMatch(ctx, r.MappingId, r.CaptureId); err != nil {
|
||||
return nil, s.logErr("RecordMappingMatch", err)
|
||||
}
|
||||
return &pb.RecordMappingMatchResponse{}, nil
|
||||
}
|
||||
|
||||
// Binding
|
||||
|
||||
func (s *server) binding() (storecontract.BindingStore, error) {
|
||||
@@ -646,6 +663,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)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"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/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
@@ -39,7 +40,7 @@ func grantsServer(t *testing.T, adminToken string) (grants *TaskGrants, dial fun
|
||||
RegisterServer(server, Deps{
|
||||
Tasks: local, ConfigSnapshots: local, ApplyStatus: local,
|
||||
Captures: eda, Mappings: eda, Bindings: eda,
|
||||
BindingDispatcher: eda, PlaybookDispatcher: eda,
|
||||
BindingDispatcher: eda, PlaybookDispatcher: eda, EventTypes: eda,
|
||||
Grants: grants,
|
||||
})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
@@ -77,6 +78,12 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) {
|
||||
admin := dial(t, adminToken)
|
||||
ctx := t.Context()
|
||||
|
||||
// Only an identified capture is listed for dispatch; a catch-all type
|
||||
// identifies every event on the source as it arrives.
|
||||
eventTypeID, etErr := admin.InsertEventType(ctx, eventtype.EventType{Source: "large", Name: "any"})
|
||||
if etErr != nil {
|
||||
t.Fatal(etErr)
|
||||
}
|
||||
body := strings.Repeat("x", 256<<10)
|
||||
for range 20 {
|
||||
if _, err := admin.InsertCapture(ctx, storecontract.CapturedEvent{Source: "large", Body: body, Authenticated: true}, 0, 0); err != nil {
|
||||
@@ -87,8 +94,9 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) {
|
||||
// A binding's mapping is a real relation now, so it must point at a
|
||||
// mapping that exists; the store refuses a dangling id.
|
||||
mappingID, mapErr := admin.InsertMapping(t.Context(), mapping.Mapping{
|
||||
Name: "m",
|
||||
Fields: []mapping.Field{{Name: "title", Path: "title", Type: mapping.TypeString}},
|
||||
Name: "m",
|
||||
EventTypeID: eventTypeID,
|
||||
Fields: []mapping.Field{{Name: "title", Path: "title", Type: mapping.TypeString}},
|
||||
})
|
||||
if mapErr != nil {
|
||||
t.Fatal(mapErr)
|
||||
@@ -97,14 +105,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)
|
||||
}
|
||||
|
||||
@@ -13,7 +13,9 @@ import (
|
||||
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"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"
|
||||
@@ -149,7 +151,8 @@ func capturedEventProto(c storecontract.CapturedEvent) *pb.CapturedEvent {
|
||||
return &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,
|
||||
Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType,
|
||||
Unsigned: c.Unsigned,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +163,25 @@ func capturedEventValue(c *pb.CapturedEvent) storecontract.CapturedEvent {
|
||||
return 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,
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,8 +198,9 @@ func mappingFieldValue(f *pb.MappingField) mapping.Field {
|
||||
|
||||
func mappingProto(m mapping.Mapping) *pb.Mapping {
|
||||
return &pb.Mapping{
|
||||
Id: m.ID, Name: m.Name, SourceHint: m.SourceHint,
|
||||
Fields: mapValues(m.Fields, mappingFieldProto),
|
||||
Id: m.ID, Name: m.Name, SourceHint: m.SourceHint, EventTypeId: m.EventTypeID,
|
||||
Fields: mapValues(m.Fields, mappingFieldProto),
|
||||
MatchCount: m.MatchCount, LastMatchedAt: timestamp(m.LastMatchedAt),
|
||||
CreatedAt: timestamp(m.CreatedAt), UpdatedAt: timestamp(m.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -188,8 +210,9 @@ func mappingValue(m *pb.Mapping) mapping.Mapping {
|
||||
return mapping.Mapping{}
|
||||
}
|
||||
return mapping.Mapping{
|
||||
ID: m.Id, Name: m.Name, SourceHint: m.SourceHint,
|
||||
Fields: mapValues(m.Fields, mappingFieldValue),
|
||||
ID: m.Id, Name: m.Name, SourceHint: m.SourceHint, EventTypeID: m.EventTypeId,
|
||||
Fields: mapValues(m.Fields, mappingFieldValue),
|
||||
MatchCount: m.MatchCount, LastMatchedAt: timeValue(m.LastMatchedAt),
|
||||
CreatedAt: timeValue(m.CreatedAt), UpdatedAt: timeValue(m.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -197,8 +220,8 @@ func mappingValue(m *pb.Mapping) mapping.Mapping {
|
||||
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,
|
||||
MappingId: b.MappingID, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
|
||||
Version: int64(b.Version), Status: string(b.Status),
|
||||
CreatedAt: timestamp(b.CreatedAt), UpdatedAt: timestamp(b.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -213,8 +236,8 @@ 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,
|
||||
MappingID: b.MappingId, Filter: b.Filter, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
|
||||
Version: int(b.Version), Status: binding.Status(b.Status),
|
||||
CreatedAt: timeValue(b.CreatedAt), UpdatedAt: timeValue(b.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -267,9 +290,15 @@ const (
|
||||
msgStaleTransition = "stale transition"
|
||||
msgBindingNotFound = "binding not found"
|
||||
msgMappingNotFound = "mapping not found"
|
||||
msgEventTypeNotFound = "event type not found"
|
||||
msgEventTypeOverlap = "event type overlap"
|
||||
msgEventTypeInvalid = "event type invalid"
|
||||
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
|
||||
@@ -302,22 +331,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.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
|
||||
@@ -364,35 +383,46 @@ func unmapError(err error) error {
|
||||
// are part of the wire contract (§4). A code whose message is not one this
|
||||
// package defines returns nil, so the caller falls back to the wrapped form.
|
||||
func sentinelForStatus(st *status.Status) error {
|
||||
switch st.Code() {
|
||||
case codes.FailedPrecondition:
|
||||
switch st.Message() {
|
||||
case msgStaleTransition:
|
||||
return storecontract.ErrStaleTransition
|
||||
case msgBindingOverlap:
|
||||
return storecontract.ErrBindingOverlap
|
||||
case msgBindingTransition:
|
||||
return storecontract.ErrBindingTransition
|
||||
}
|
||||
case codes.NotFound:
|
||||
switch st.Message() {
|
||||
case msgBindingNotFound:
|
||||
return storecontract.ErrBindingNotFound
|
||||
case msgMappingNotFound:
|
||||
return storecontract.ErrMappingNotFound
|
||||
}
|
||||
case codes.AlreadyExists:
|
||||
if st.Message() == msgAlreadyDispatched {
|
||||
return storecontract.ErrAlreadyDispatched
|
||||
}
|
||||
case codes.Unavailable:
|
||||
if st.Message() == msgTaskLogsUnavailable {
|
||||
return logging.ErrTaskLogsUnavailable
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return wireSentinels[wireStatus{st.Code(), st.Message()}]
|
||||
}
|
||||
|
||||
type wireStatus struct {
|
||||
code codes.Code
|
||||
message string
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -16,14 +16,21 @@ type bindingRequest struct {
|
||||
Name string `json:"name"`
|
||||
Matcher binding.Matcher `json:"matcher"`
|
||||
MappingID string `json:"mapping_id"`
|
||||
Filter string `json:"filter"`
|
||||
Workflow string `json:"workflow"`
|
||||
// Owner and Repo optionally pin the binding to one configured repo,
|
||||
// for multi-repo deployments. Both empty is valid (falls back to the
|
||||
// daemon's single-configured-repo behaviour); binding.Validate
|
||||
// rejects setting only one.
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Secret string `json:"secret"`
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
}
|
||||
|
||||
// bindingView is a listed binding with its source's signing state, so the
|
||||
// list can flag a binding that dispatches unsigned events.
|
||||
type bindingView struct {
|
||||
binding.Binding
|
||||
Unsigned bool `json:"unsigned"`
|
||||
}
|
||||
|
||||
func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -37,8 +44,17 @@ func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
stripBindingSecrets(bindings)
|
||||
writeJSON(w, map[string]any{"bindings": bindings})
|
||||
unsigned, err := s.unsignedSources(r.Context())
|
||||
if err != nil {
|
||||
s.Log.Error("list sources", "err", err)
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
views := make([]bindingView, 0, len(bindings))
|
||||
for _, b := range bindings {
|
||||
views = append(views, bindingView{Binding: b, Unsigned: unsigned[b.Matcher.Source]})
|
||||
}
|
||||
writeJSON(w, map[string]any{"bindings": views})
|
||||
}
|
||||
|
||||
func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -67,22 +83,21 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
Name: req.Name,
|
||||
Matcher: req.Matcher,
|
||||
MappingID: req.MappingID,
|
||||
Filter: req.Filter,
|
||||
Workflow: req.Workflow,
|
||||
Owner: req.Owner,
|
||||
Repo: req.Repo,
|
||||
Secret: req.Secret,
|
||||
Status: binding.StatusPendingApproval,
|
||||
}
|
||||
if err := b.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !s.checkBindingFilter(w, r, b) {
|
||||
return
|
||||
}
|
||||
id, err := s.Bindings.InsertBinding(r.Context(), b)
|
||||
if err != nil {
|
||||
if errors.Is(err, storecontract.ErrBindingOverlap) {
|
||||
http.Error(w, "binding source overlaps an existing binding", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
s.Log.Error("insert binding", "err", err)
|
||||
http.Error(w, "create binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
@@ -93,7 +108,6 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "create binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
created.Secret = ""
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, created)
|
||||
}
|
||||
@@ -118,7 +132,6 @@ func (s *Server) handleBindingGet(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
b.Secret = ""
|
||||
writeJSON(w, b)
|
||||
}
|
||||
|
||||
@@ -154,21 +167,22 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
Name: req.Name,
|
||||
Matcher: req.Matcher,
|
||||
MappingID: req.MappingID,
|
||||
Filter: req.Filter,
|
||||
Workflow: req.Workflow,
|
||||
Owner: req.Owner,
|
||||
Repo: req.Repo,
|
||||
Secret: req.Secret,
|
||||
}
|
||||
if err := b.ValidateForUpdate(); err != nil {
|
||||
if err := b.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !s.checkBindingFilter(w, r, b) {
|
||||
return
|
||||
}
|
||||
if err := s.Bindings.UpdateBinding(r.Context(), b); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrBindingNotFound):
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
case errors.Is(err, storecontract.ErrBindingOverlap):
|
||||
http.Error(w, "binding source overlaps an existing binding", http.StatusConflict)
|
||||
default:
|
||||
s.Log.Error("update binding", "err", err, "id", id)
|
||||
http.Error(w, "update binding failed", http.StatusInternalServerError)
|
||||
@@ -181,7 +195,6 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "update binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
updated.Secret = ""
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
|
||||
@@ -229,8 +242,6 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
case errors.Is(err, storecontract.ErrBindingTransition):
|
||||
http.Error(w, "binding cannot be approved from its current state", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrBindingOverlap):
|
||||
http.Error(w, "binding source overlaps an existing binding", http.StatusConflict)
|
||||
default:
|
||||
s.Log.Error("approve binding", "err", err, "id", id)
|
||||
http.Error(w, "approve binding failed", http.StatusInternalServerError)
|
||||
@@ -243,15 +254,29 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "approve binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
updated.Secret = ""
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
|
||||
// stripBindingSecrets zeroes the Secret field on every binding in the slice
|
||||
// so the list handler never leaks a shared HMAC secret through /api/bindings.
|
||||
// Single-binding reads do the same inline; this covers the list path.
|
||||
func stripBindingSecrets(bs []binding.Binding) {
|
||||
for i := range bs {
|
||||
bs[i].Secret = ""
|
||||
// checkBindingFilter refuses a binding whose mapping does not exist or whose
|
||||
// filter does not compile against the mapping's parameters.
|
||||
func (s *Server) checkBindingFilter(w http.ResponseWriter, r *http.Request, b binding.Binding) bool {
|
||||
if s.Mappings == nil {
|
||||
http.Error(w, "mappings not configured", http.StatusServiceUnavailable)
|
||||
return false
|
||||
}
|
||||
m, err := s.Mappings.GetMapping(r.Context(), b.MappingID)
|
||||
if err != nil {
|
||||
s.Log.Error("get mapping for binding", "err", err, "mapping", b.MappingID)
|
||||
http.Error(w, "get mapping failed", http.StatusInternalServerError)
|
||||
return false
|
||||
}
|
||||
if m == nil {
|
||||
http.Error(w, "binding: mapping not found: "+b.MappingID, http.StatusBadRequest)
|
||||
return false
|
||||
}
|
||||
if _, err := binding.CompileFilter(b.Filter, m.Fields); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
// memBindings keeps mappings and bindings in memory with no per-source limit,
|
||||
// as the Postgres store does.
|
||||
type memBindings struct {
|
||||
mappings map[string]mapping.Mapping
|
||||
bindings map[string]binding.Binding
|
||||
}
|
||||
|
||||
func newMemBindings() *memBindings {
|
||||
return &memBindings{mappings: map[string]mapping.Mapping{}, bindings: map[string]binding.Binding{}}
|
||||
}
|
||||
|
||||
func (m *memBindings) InsertMapping(_ context.Context, v mapping.Mapping) (string, error) {
|
||||
v.ID = fmt.Sprintf("m%d", len(m.mappings)+1)
|
||||
m.mappings[v.ID] = v
|
||||
return v.ID, nil
|
||||
}
|
||||
|
||||
func (m *memBindings) GetMapping(_ context.Context, id string) (*mapping.Mapping, error) {
|
||||
v, ok := m.mappings[id]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
func (m *memBindings) ListMappings(context.Context) ([]mapping.Mapping, error) { return nil, nil }
|
||||
func (m *memBindings) UpdateMapping(context.Context, mapping.Mapping) error { return nil }
|
||||
func (m *memBindings) DeleteMapping(context.Context, string) error { return nil }
|
||||
|
||||
func (m *memBindings) InsertBinding(_ context.Context, b binding.Binding) (string, error) {
|
||||
b.ID = fmt.Sprintf("b%d", len(m.bindings)+1)
|
||||
m.bindings[b.ID] = b
|
||||
return b.ID, nil
|
||||
}
|
||||
|
||||
func (m *memBindings) GetBinding(_ context.Context, id string) (*binding.Binding, error) {
|
||||
v, ok := m.bindings[id]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
func (m *memBindings) ListBindings(context.Context) ([]binding.Binding, error) { return nil, nil }
|
||||
func (m *memBindings) UpdateBinding(_ context.Context, b binding.Binding) error {
|
||||
if _, ok := m.bindings[b.ID]; !ok {
|
||||
return storecontract.ErrBindingNotFound
|
||||
}
|
||||
m.bindings[b.ID] = b
|
||||
return nil
|
||||
}
|
||||
func (m *memBindings) DeleteBinding(context.Context, string) error { return nil }
|
||||
func (m *memBindings) ApproveBinding(context.Context, string) error { return nil }
|
||||
|
||||
func memBindingServer(t *testing.T) (*Server, string) {
|
||||
t.Helper()
|
||||
store := newMemBindings()
|
||||
mappingID, _ := store.InsertMapping(t.Context(), mapping.Mapping{
|
||||
Name: "m", EventTypeID: "et-1",
|
||||
Fields: []mapping.Field{{Name: "title", Path: "issue.title", Type: mapping.TypeString}},
|
||||
})
|
||||
return &Server{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Mappings: store,
|
||||
Bindings: store,
|
||||
ControlPlane: workflowControlPlane(t, workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "implement", YAML: "id: implement\nsteps:\n - type: implement.prepare\n"}}}),
|
||||
}, mappingID
|
||||
}
|
||||
|
||||
// Several bindings may share a source.
|
||||
func TestHandleBindingCreateAllowsSeveralPerSource(t *testing.T) {
|
||||
srv, mappingID := memBindingServer(t)
|
||||
for _, suffix := range []string{"first", "second"} {
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest(suffix, "sentry", mappingID))
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("%s create status = %d, want %d; body = %s", suffix, w.Code, http.StatusCreated, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A binding's filter is checked against its mapping's parameters on save.
|
||||
func TestHandleBindingFilterIsCheckedAgainstMapping(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
filter string
|
||||
want int
|
||||
}{
|
||||
{"no filter", "", http.StatusCreated},
|
||||
{"filter on a mapped parameter", `title.startsWith("P1")`, http.StatusCreated},
|
||||
{"unknown parameter", `severity == "high"`, http.StatusBadRequest},
|
||||
{"not boolean", `title`, http.StatusBadRequest},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv, mappingID := memBindingServer(t)
|
||||
req := validBindingRequest("f", "sentry", mappingID)
|
||||
req["filter"] = tt.filter
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != tt.want {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
if w.Code == http.StatusCreated {
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
if created.Filter != tt.filter {
|
||||
t.Fatalf("created.Filter = %q, want %q", created.Filter, tt.filter)
|
||||
}
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("update status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingRejectsUnknownMapping(t *testing.T) {
|
||||
srv, _ := memBindingServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("x", "sentry", "absent"))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
@@ -47,16 +46,13 @@ func seedMapping(t *testing.T, srv *Server, name string) string {
|
||||
}
|
||||
|
||||
// validBindingRequest returns a populated bindingRequest that passes
|
||||
// binding.Validate and server-side workflow validation. The Secret is 32
|
||||
// bytes (above the 16-byte floor) so length never accidentally trips
|
||||
// validation in a test that isn't about secret length.
|
||||
// binding.Validate and server-side workflow validation.
|
||||
func validBindingRequest(suffix, source, mappingID string) map[string]any {
|
||||
return map[string]any{
|
||||
"name": "binding " + suffix,
|
||||
"matcher": map[string]any{"source": source},
|
||||
"mapping_id": mappingID,
|
||||
"workflow": "implement",
|
||||
"secret": "0123456789abcdef0123456789abcdef",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,9 +74,6 @@ func TestHandleBindingCreateAndGet(t *testing.T) {
|
||||
if created.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("created.Status = %q, want %q", created.Status, binding.StatusPendingApproval)
|
||||
}
|
||||
if created.Secret != "" {
|
||||
t.Fatalf("created.Secret = %q, want \"\" (response must strip secret)", created.Secret)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/bindings/"+created.ID, nil)
|
||||
if w.Code != http.StatusOK {
|
||||
@@ -93,15 +86,12 @@ func TestHandleBindingCreateAndGet(t *testing.T) {
|
||||
if got.ID != created.ID {
|
||||
t.Fatalf("got.ID = %q, want %q", got.ID, created.ID)
|
||||
}
|
||||
if got.Secret != "" {
|
||||
t.Fatalf("get.Secret = %q, want \"\"", got.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo covers the
|
||||
// multi-repo fix at the API layer: a create/update request carrying
|
||||
// owner/repo persists them, and they're visible in the response
|
||||
// (they're not secret, unlike Secret).
|
||||
// (they're not secret).
|
||||
func TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
@@ -154,51 +144,6 @@ func TestHandleBindingCreateRejectsPartialOwnerRepo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingsListStripsSecrets(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("list status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Bindings []binding.Binding `json:"bindings"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(body.Bindings) != 1 {
|
||||
t.Fatalf("bindings = %d, want 1", len(body.Bindings))
|
||||
}
|
||||
if body.Bindings[0].Secret != "" {
|
||||
t.Fatalf("listed Secret = %q, want \"\"", body.Bindings[0].Secret)
|
||||
}
|
||||
// Defence against accidental echo in the raw JSON: the "secret" key
|
||||
// must not appear at all (the binding.Binding tag is omitempty).
|
||||
if strings.Contains(w.Body.String(), `"secret"`) {
|
||||
t.Fatalf("list response leaked secret key: %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingCreateRejectsOverlap(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("first", "sentry", mappingID))
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("first create status = %d, want %d; body = %s", w.Code, http.StatusCreated, w.Body.String())
|
||||
}
|
||||
|
||||
// Overlap because Per bead t2db.4, two bindings may not own the same
|
||||
// source; the second insert must surface ErrBindingOverlap -> 409.
|
||||
w = doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("second", "sentry", mappingID))
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("second create status = %d, want %d; body = %s", w.Code, http.StatusConflict, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingCreateRejectsMissingWorkflow(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
@@ -215,10 +160,8 @@ func TestHandleBindingCreateRejectsValidationFailure(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
// Short secret trips binding.Validate's length floor regardless of
|
||||
// any store-side check.
|
||||
req := validBindingRequest("a", "sentry", mappingID)
|
||||
req["secret"] = "short"
|
||||
req["name"] = " "
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
@@ -272,35 +215,6 @@ func TestHandleBindingUpdatePreservesOtherFields(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBindingUpdateWithEmptySecretPreservesExisting is the API-layer
|
||||
// half of UpdateBinding's own documented contract ("Secret is preserved
|
||||
// when the caller passes an empty string ... so a partial update cannot
|
||||
// erase the HMAC secret"): an edit that never touches the secret field
|
||||
// must not be rejected by Validate's create-time secret-length floor,
|
||||
// since nothing about the existing secret is changing.
|
||||
func TestHandleBindingUpdateWithEmptySecretPreservesExisting(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
update := validBindingRequest("renamed", "sentry", mappingID)
|
||||
update["secret"] = ""
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, update)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("patch status = %d, want %d (empty secret must mean 'keep existing', not fail validation); body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
|
||||
stored, err := srv.Bindings.GetBinding(t.Context(), created.ID)
|
||||
if err != nil || stored == nil {
|
||||
t.Fatalf("GetBinding: %+v, %v", stored, err)
|
||||
}
|
||||
if stored.Secret != "0123456789abcdef0123456789abcdef" {
|
||||
t.Fatalf("stored secret = %q, want the original secret preserved", stored.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingApproveArmedRejected(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// proposalScanLimit bounds how many recent captures are grouped into
|
||||
// proposals on one read.
|
||||
const proposalScanLimit = 500
|
||||
|
||||
// eventTypeExample is a pasted (or sampled) event: headers by name and the
|
||||
// raw body. The type's schema is inferred from it.
|
||||
type eventTypeExample struct {
|
||||
Headers map[string]string `json:"headers"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
// eventTypeRequest is POST /api/event-types. Rule, when absent, is the one
|
||||
// inferred from the example.
|
||||
type eventTypeRequest struct {
|
||||
Source string `json:"source"`
|
||||
Name string `json:"name"`
|
||||
Rule *eventtype.Rule `json:"rule"`
|
||||
Example eventTypeExample `json:"example"`
|
||||
}
|
||||
|
||||
// eventTypeUpdate is PUT /api/event-types/{id}: the name and rule are the
|
||||
// editable parts of a type.
|
||||
type eventTypeUpdate struct {
|
||||
Name string `json:"name"`
|
||||
Rule eventtype.Rule `json:"rule"`
|
||||
}
|
||||
|
||||
// handleEventTypes lists the named event types and the proposals grouped from
|
||||
// recent captures that were unidentified on arrival and still match no type.
|
||||
func (s *Server) handleEventTypes(w http.ResponseWriter, r *http.Request) {
|
||||
if s.EventTypes == nil {
|
||||
writeJSON(w, map[string]any{"enabled": false, "event_types": []any{}, "proposals": []any{}})
|
||||
return
|
||||
}
|
||||
types, err := s.EventTypes.ListEventTypes(r.Context())
|
||||
if err != nil {
|
||||
s.Log.Error("list event types", "err", err)
|
||||
http.Error(w, "list event types failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
proposals := []eventtype.Proposal{}
|
||||
if s.Captures != nil {
|
||||
captures, err := s.Captures.ListCaptures(r.Context(), proposalScanLimit)
|
||||
if err != nil {
|
||||
s.Log.Error("list captures for proposals", "err", err)
|
||||
http.Error(w, "list captures failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
proposals = append(proposals, eventtype.Propose(unmatchedCaptures(types, captures))...)
|
||||
}
|
||||
if types == nil {
|
||||
types = []eventtype.EventType{}
|
||||
}
|
||||
writeJSON(w, map[string]any{"enabled": true, "event_types": types, "proposals": proposals})
|
||||
}
|
||||
|
||||
// unmatchedCaptures keeps the captures that were unidentified on arrival and
|
||||
// that no current type would identify either. A capture a newer type now
|
||||
// matches stays unidentified (it was never dispatched) but is no longer
|
||||
// proposed.
|
||||
func unmatchedCaptures(types []eventtype.EventType, captures []storecontract.CapturedEvent) []eventtype.Capture {
|
||||
var out []eventtype.Capture
|
||||
for _, c := range captures {
|
||||
if c.EventType != "" {
|
||||
continue
|
||||
}
|
||||
sample := eventtype.Sample{Headers: eventtype.ParseHeaders(c.Headers), Body: []byte(c.Body)}
|
||||
if _, ok := eventtype.Identify(types, c.Source, sample); ok {
|
||||
continue
|
||||
}
|
||||
out = append(out, eventtype.Capture{ID: c.ID, Source: c.Source, ReceivedAt: c.ReceivedAt, Sample: sample})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) handleEventTypeCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req eventTypeRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
t := eventtype.FromExample(req.Source, req.Name, eventtype.Sample{
|
||||
Headers: req.Example.Headers,
|
||||
Body: []byte(req.Example.Body),
|
||||
})
|
||||
if req.Rule != nil {
|
||||
t.Rule = *req.Rule
|
||||
}
|
||||
id, err := s.EventTypes.InsertEventType(r.Context(), t)
|
||||
if err != nil {
|
||||
s.writeEventTypeError(w, "create", err)
|
||||
return
|
||||
}
|
||||
t.ID = id
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, t)
|
||||
}
|
||||
|
||||
func (s *Server) handleEventTypeUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req eventTypeUpdate
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// Source is not editable: the store validates against the stored one.
|
||||
t := eventtype.EventType{ID: r.PathValue("id"), Name: req.Name, Rule: req.Rule}
|
||||
if err := s.EventTypes.UpdateEventType(r.Context(), t); err != nil {
|
||||
s.writeEventTypeError(w, "update", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]string{"id": t.ID})
|
||||
}
|
||||
|
||||
func (s *Server) handleEventTypeDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if err := s.EventTypes.DeleteEventType(r.Context(), r.PathValue("id")); err != nil {
|
||||
s.writeEventTypeError(w, "delete", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) writeEventTypeError(w http.ResponseWriter, action string, err error) {
|
||||
switch {
|
||||
case errors.Is(err, eventtype.ErrOverlap):
|
||||
http.Error(w, "this rule can match events another type on the source already matches", http.StatusConflict)
|
||||
case errors.Is(err, eventtype.ErrInvalid):
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
case errors.Is(err, storecontract.ErrEventTypeNotFound):
|
||||
http.Error(w, "event type not found", http.StatusNotFound)
|
||||
default:
|
||||
s.Log.Error(action+" event type", "err", err)
|
||||
http.Error(w, action+" event type failed", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
type memCaptures struct{ list []storecontract.CapturedEvent }
|
||||
|
||||
func (m *memCaptures) InsertCapture(_ context.Context, c storecontract.CapturedEvent, _ time.Duration, _ int) (string, error) {
|
||||
m.list = append(m.list, c)
|
||||
return c.ID, nil
|
||||
}
|
||||
|
||||
func (m *memCaptures) ListCaptures(context.Context, int) ([]storecontract.CapturedEvent, error) {
|
||||
return m.list, nil
|
||||
}
|
||||
|
||||
// memEventTypes applies the domain's validation and overlap refusal, as the
|
||||
// real store does.
|
||||
type memEventTypes struct{ types []eventtype.EventType }
|
||||
|
||||
func (m *memEventTypes) InsertEventType(_ context.Context, t eventtype.EventType) (string, error) {
|
||||
if err := t.Validate(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := eventtype.CheckOverlap(m.types, t); err != nil {
|
||||
return "", err
|
||||
}
|
||||
t.ID = "et-" + t.Name
|
||||
m.types = append(m.types, t)
|
||||
return t.ID, nil
|
||||
}
|
||||
|
||||
func (m *memEventTypes) UpdateEventType(_ context.Context, t eventtype.EventType) error {
|
||||
for i, existing := range m.types {
|
||||
if existing.ID == t.ID {
|
||||
t.Source, t.Schema = existing.Source, existing.Schema
|
||||
if err := eventtype.CheckOverlap(m.types, t); err != nil {
|
||||
return err
|
||||
}
|
||||
m.types[i] = t
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
|
||||
func (m *memEventTypes) DeleteEventType(_ context.Context, id string) error {
|
||||
for i, existing := range m.types {
|
||||
if existing.ID == id {
|
||||
m.types = append(m.types[:i], m.types[i+1:]...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return storecontract.ErrEventTypeNotFound
|
||||
}
|
||||
|
||||
func (m *memEventTypes) ListEventTypes(context.Context) ([]eventtype.EventType, error) {
|
||||
return m.types, nil
|
||||
}
|
||||
|
||||
func eventTypeServer(captures ...storecontract.CapturedEvent) (*Server, *memEventTypes) {
|
||||
types := &memEventTypes{}
|
||||
return &Server{
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Captures: &memCaptures{list: captures},
|
||||
EventTypes: types,
|
||||
}, types
|
||||
}
|
||||
|
||||
func serve(t *testing.T, srv *Server, method, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), method, path, strings.NewReader(body))
|
||||
req.Header.Set("X-Archie-CSRF", "1")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
type eventTypesView struct {
|
||||
EventTypes []eventtype.EventType `json:"event_types"`
|
||||
Proposals []eventtype.Proposal `json:"proposals"`
|
||||
}
|
||||
|
||||
func listEventTypes(t *testing.T, srv *Server) eventTypesView {
|
||||
t.Helper()
|
||||
w := serve(t, srv, http.MethodGet, "/api/event-types", "")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d; body %s", w.Code, w.Body.String())
|
||||
}
|
||||
var v eventTypesView
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func ghCapture(id, event, body string) storecontract.CapturedEvent {
|
||||
return storecontract.CapturedEvent{ID: id, Source: "gh", Headers: `{"X-Github-Event":["` + event + `"]}`, Body: body}
|
||||
}
|
||||
|
||||
// Two GitHub events with different X-GitHub-Event headers are two proposals,
|
||||
// and a firewall payload is a third.
|
||||
func TestEventTypesProposesGroupsFromUnidentifiedCaptures(t *testing.T) {
|
||||
srv, _ := eventTypeServer(
|
||||
ghCapture("c1", "push", `{"ref":"a"}`),
|
||||
ghCapture("c2", "pull_request", `{"action":"opened"}`),
|
||||
storecontract.CapturedEvent{ID: "f1", Source: "fw", Body: `{"src":"1.1.1.1"}`},
|
||||
// Already identified on arrival: not a proposal.
|
||||
func() storecontract.CapturedEvent {
|
||||
c := ghCapture("c3", "issues", `{}`)
|
||||
c.EventType = "et-x"
|
||||
return c
|
||||
}(),
|
||||
)
|
||||
v := listEventTypes(t, srv)
|
||||
var samples []string
|
||||
for _, p := range v.Proposals {
|
||||
samples = append(samples, p.SampleID)
|
||||
}
|
||||
if strings.Join(samples, ",") != "f1,c1,c2" {
|
||||
t.Fatalf("proposal samples = %v, want f1,c1,c2", samples)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeCreateFromProposalRemovesIt(t *testing.T) {
|
||||
srv, types := eventTypeServer(ghCapture("c1", "push", `{"ref":"a"}`), ghCapture("c2", "pull_request", `{"action":"opened"}`))
|
||||
w := serve(t, srv, http.MethodPost, "/api/event-types", `{
|
||||
"source":"gh","name":"push",
|
||||
"rule":{"headers":[{"name":"x-github-event","value":"push"}]},
|
||||
"example":{"headers":{"x-github-event":"push"},"body":"{\"ref\":\"a\"}"}}`)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("POST status = %d; body %s", w.Code, w.Body.String())
|
||||
}
|
||||
if got := types.types[0].Schema["ref"]; got != eventtype.TypeString {
|
||||
t.Fatalf("schema[ref] = %q, want string", got)
|
||||
}
|
||||
v := listEventTypes(t, srv)
|
||||
if len(v.EventTypes) != 1 || len(v.Proposals) != 1 || v.Proposals[0].SampleID != "c2" {
|
||||
t.Fatalf("after naming push: types %d, proposals %+v", len(v.EventTypes), v.Proposals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypeWriteStatuses(t *testing.T) {
|
||||
srv, _ := eventTypeServer()
|
||||
pasted := `{"source":"gh","name":"%s","example":{"headers":{"X-GitHub-Event":"push"},"body":"{}"}}`
|
||||
tests := []struct {
|
||||
name, method, path, body string
|
||||
want int
|
||||
}{
|
||||
{"create from pasted payload", http.MethodPost, "/api/event-types", strings.Replace(pasted, "%s", "push", 1), http.StatusCreated},
|
||||
{"overlapping type is refused", http.MethodPost, "/api/event-types", strings.Replace(pasted, "%s", "push2", 1), http.StatusConflict},
|
||||
{"nameless type is refused", http.MethodPost, "/api/event-types", strings.Replace(pasted, "%s", "", 1), http.StatusBadRequest},
|
||||
{"bad json", http.MethodPost, "/api/event-types", `{`, http.StatusBadRequest},
|
||||
{"rename", http.MethodPut, "/api/event-types/et-push", `{"name":"pushed","rule":{"headers":[{"name":"X-GitHub-Event","value":"push"}]}}`, http.StatusOK},
|
||||
{"update missing", http.MethodPut, "/api/event-types/nope", `{"name":"x","rule":{}}`, http.StatusNotFound},
|
||||
{"delete", http.MethodDelete, "/api/event-types/et-push", ``, http.StatusNoContent},
|
||||
{"delete missing", http.MethodDelete, "/api/event-types/et-push", ``, http.StatusNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if w := serve(t, srv, tt.method, tt.path, tt.body); w.Code != tt.want {
|
||||
t.Fatalf("status = %d, want %d; body %s", w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventTypesDisabledWithoutStore(t *testing.T) {
|
||||
srv := &Server{Log: slog.New(slog.DiscardHandler)}
|
||||
w := serve(t, srv, http.MethodGet, "/api/event-types", "")
|
||||
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"enabled":false`) {
|
||||
t.Fatalf("GET without store = %d %s, want 200 with enabled false", w.Code, w.Body.String())
|
||||
}
|
||||
if w := serve(t, srv, http.MethodPost, "/api/event-types", `{}`); w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("POST without store = %d, want 503", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,40 @@ import (
|
||||
// PATCH /api/mappings/{id} both accept. ID/CreatedAt/UpdatedAt are
|
||||
// server-assigned, never taken from the request body.
|
||||
type mappingRequest struct {
|
||||
Name string `json:"name"`
|
||||
SourceHint string `json:"source_hint"`
|
||||
Fields []mapping.Field `json:"fields"`
|
||||
Name string `json:"name"`
|
||||
SourceHint string `json:"source_hint"`
|
||||
EventTypeID string `json:"event_type_id"`
|
||||
Fields []mapping.Field `json:"fields"`
|
||||
}
|
||||
|
||||
// validateMapping checks m is well-formed and fits its event type's schema.
|
||||
// It writes the refusal and returns false when it does not.
|
||||
func (s *Server) validateMapping(w http.ResponseWriter, r *http.Request, m mapping.Mapping) bool {
|
||||
if err := m.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return false
|
||||
}
|
||||
if s.EventTypes == nil {
|
||||
http.Error(w, "event types not configured", http.StatusServiceUnavailable)
|
||||
return false
|
||||
}
|
||||
types, err := s.EventTypes.ListEventTypes(r.Context())
|
||||
if err != nil {
|
||||
s.Log.Error("list event types", "err", err)
|
||||
http.Error(w, "list event types failed", http.StatusInternalServerError)
|
||||
return false
|
||||
}
|
||||
for _, t := range types {
|
||||
if t.ID == m.EventTypeID {
|
||||
if err := mapping.CheckSchema(m.Fields, t.Schema); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
http.Error(w, "mapping: event type not found: "+m.EventTypeID, http.StatusBadRequest)
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) handleMappingsList(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -46,9 +77,8 @@ func (s *Server) handleMappingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
m := mapping.Mapping{Name: req.Name, SourceHint: req.SourceHint, Fields: req.Fields}
|
||||
if err := m.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
m := mapping.Mapping{Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
|
||||
if !s.validateMapping(w, r, m) {
|
||||
return
|
||||
}
|
||||
id, err := s.Mappings.InsertMapping(r.Context(), m)
|
||||
@@ -108,9 +138,8 @@ func (s *Server) handleMappingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
m := mapping.Mapping{ID: id, Name: req.Name, SourceHint: req.SourceHint, Fields: req.Fields}
|
||||
if err := m.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
m := mapping.Mapping{ID: id, Name: req.Name, SourceHint: req.SourceHint, EventTypeID: req.EventTypeID, Fields: req.Fields}
|
||||
if !s.validateMapping(w, r, m) {
|
||||
return
|
||||
}
|
||||
if err := s.Mappings.UpdateMapping(r.Context(), m); err != nil {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
@@ -22,10 +23,66 @@ func mappingTestServer(t *testing.T) *Server {
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
eda := pgstore.EDA(t, nil)
|
||||
return &Server{
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Mappings: eda,
|
||||
Captures: eda,
|
||||
Store: s,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Mappings: eda,
|
||||
Captures: eda,
|
||||
EventTypes: testEventTypes(),
|
||||
}
|
||||
}
|
||||
|
||||
// testEventTypes holds one event type, et-1, whose schema has every path the
|
||||
// mapping tests write.
|
||||
func testEventTypes() *memEventTypes {
|
||||
return &memEventTypes{types: []eventtype.EventType{{
|
||||
ID: "et-1", Source: "sentry", Name: "issue",
|
||||
Schema: map[string]eventtype.ValueType{
|
||||
"a": eventtype.TypeString, "b": eventtype.TypeBool,
|
||||
"issue": eventtype.TypeObject, "issue.title": eventtype.TypeString,
|
||||
},
|
||||
}}}
|
||||
}
|
||||
|
||||
// A mapping belongs to an event type and is checked against its schema.
|
||||
func TestHandleMappingSaveChecksEventTypeSchema(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
eventType string
|
||||
path string
|
||||
fieldType mapping.FieldType
|
||||
want int
|
||||
}{
|
||||
{"fits the schema", "et-1", "issue.title", mapping.TypeString, http.StatusCreated},
|
||||
{"no event type", "", "issue.title", mapping.TypeString, http.StatusBadRequest},
|
||||
{"unknown event type", "et-9", "issue.title", mapping.TypeString, http.StatusBadRequest},
|
||||
{"path the type does not have", "et-1", "sender.login", mapping.TypeString, http.StatusBadRequest},
|
||||
{"type differs from the schema", "et-1", "issue.title", mapping.TypeNumber, http.StatusBadRequest},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
req := map[string]any{
|
||||
"name": "m",
|
||||
"event_type_id": tt.eventType,
|
||||
"fields": []mapping.Field{{Name: "f", Path: tt.path, Type: tt.fieldType}},
|
||||
}
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/mappings", req); w.Code != tt.want {
|
||||
t.Fatalf("create status = %d, want %d; body = %s", w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
ok := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "base", "event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
var created mapping.Mapping
|
||||
_ = json.Unmarshal(ok.Body.Bytes(), &created)
|
||||
want := tt.want
|
||||
if want == http.StatusCreated {
|
||||
want = http.StatusOK
|
||||
}
|
||||
if w := doJSON(t, srv, http.MethodPatch, "/api/mappings/"+created.ID, req); w.Code != want {
|
||||
t.Fatalf("update status = %d, want %d; body = %s", w.Code, want, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,8 +127,9 @@ func doJSONWithHeaders(t *testing.T, srv *Server, method, path string, body any,
|
||||
func TestHandleMappingCreateAndGet(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "sentry issue opened",
|
||||
"source_hint": "sentry",
|
||||
"name": "sentry issue opened",
|
||||
"source_hint": "sentry",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{
|
||||
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
|
||||
},
|
||||
@@ -120,8 +178,9 @@ func TestHandleMappingsList(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
for range 3 {
|
||||
doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "m",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
"name": "m",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
}
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/mappings", nil)
|
||||
@@ -142,15 +201,17 @@ func TestHandleMappingsList(t *testing.T) {
|
||||
func TestHandleMappingUpdate(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "orig",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
"name": "orig",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
var created mapping.Mapping
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/mappings/"+created.ID, map[string]any{
|
||||
"name": "renamed",
|
||||
"fields": []mapping.Field{{Name: "b", Path: "b", Type: mapping.TypeBool}},
|
||||
"name": "renamed",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "b", Path: "b", Type: mapping.TypeBool}},
|
||||
})
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("update status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
@@ -167,8 +228,9 @@ func TestHandleMappingUpdate(t *testing.T) {
|
||||
func TestHandleMappingUpdateMissingReturns404(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPatch, "/api/mappings/999", map[string]any{
|
||||
"name": "x",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
"name": "x",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusNotFound, w.Body.String())
|
||||
@@ -178,8 +240,9 @@ func TestHandleMappingUpdateMissingReturns404(t *testing.T) {
|
||||
func TestHandleMappingDelete(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/mappings", map[string]any{
|
||||
"name": "m",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
"name": "m",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{{Name: "a", Path: "a", Type: mapping.TypeString}},
|
||||
})
|
||||
var created mapping.Mapping
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
@@ -270,8 +333,9 @@ func TestHandleMappingsUnavailableWhenNotConfigured(t *testing.T) {
|
||||
func TestHandleMappingMutationsRequireCSRFHeader(t *testing.T) {
|
||||
srv := mappingTestServer(t)
|
||||
newMapping := map[string]any{
|
||||
"name": "sentry issue opened",
|
||||
"source_hint": "sentry",
|
||||
"name": "sentry issue opened",
|
||||
"source_hint": "sentry",
|
||||
"event_type_id": "et-1",
|
||||
"fields": []mapping.Field{
|
||||
{Name: "title", Path: "issue.title", Type: mapping.TypeString, Required: true},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// Capture sources and their signing setting (docs/prds/event-automation.md
|
||||
// "Sources"). A secret is returned only by the two writes that generate it,
|
||||
// so the operator can copy it into the sender; every other read withholds it.
|
||||
// Turning signing off is a request plus an approval, both behind the same
|
||||
// mutation gate that arms a binding.
|
||||
|
||||
func (s *Server) handleSourcesList(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
list, err := s.Sources.ListSources(r.Context())
|
||||
if err != nil {
|
||||
s.Log.Error("list sources", "err", err)
|
||||
http.Error(w, "list sources failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
for i := range list {
|
||||
list[i].Secret = ""
|
||||
}
|
||||
writeJSON(w, map[string]any{"sources": list})
|
||||
}
|
||||
|
||||
func (s *Server) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
src, err := source.New(req.Path)
|
||||
if errors.Is(err, source.ErrInvalidPath) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
err = s.Sources.InsertSource(r.Context(), src)
|
||||
}
|
||||
if err != nil {
|
||||
s.sourceError(w, "create source", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceSigning turns signing on at once, or requests turning it off.
|
||||
func (s *Server) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Signed bool `json:"signed"`
|
||||
}
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
transition := (*source.Source).RequestUnsigned
|
||||
if req.Signed {
|
||||
transition = (*source.Source).RequireSigning
|
||||
}
|
||||
s.transitionSource(w, r, transition)
|
||||
}
|
||||
|
||||
func (s *Server) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
s.transitionSource(w, r, (*source.Source).ApproveUnsigned)
|
||||
}
|
||||
|
||||
// transitionSource applies one domain signing transition and writes it with
|
||||
// the state it was decided from, so a concurrent change is refused.
|
||||
func (s *Server) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
|
||||
src, ok := s.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
from := src.Signing
|
||||
if err := transition(src); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if err := s.Sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
|
||||
s.sourceError(w, "set source signing", err)
|
||||
return
|
||||
}
|
||||
src.Secret = ""
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceSecret generates a new secret and returns it once.
|
||||
func (s *Server) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
src, ok := s.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
secret, err := source.NewSecret()
|
||||
if err == nil {
|
||||
err = s.Sources.SetSourceSecret(r.Context(), src.Path, secret)
|
||||
}
|
||||
if err != nil {
|
||||
s.sourceError(w, "set source secret", err)
|
||||
return
|
||||
}
|
||||
src.Secret = secret
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
func (s *Server) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return nil, false
|
||||
}
|
||||
src, err := s.Sources.GetSource(r.Context(), r.PathValue("path"))
|
||||
if err != nil {
|
||||
s.sourceError(w, "get source", err)
|
||||
return nil, false
|
||||
}
|
||||
if src == nil {
|
||||
http.Error(w, "source not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
return src, true
|
||||
}
|
||||
|
||||
func (s *Server) sourceError(w http.ResponseWriter, what string, err error) {
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrSourcePathTaken):
|
||||
http.Error(w, "source path already taken", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrSourceSigningStale):
|
||||
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrSourceNotFound):
|
||||
http.Error(w, "source not found", http.StatusNotFound)
|
||||
default:
|
||||
s.Log.Error(what, "err", err)
|
||||
http.Error(w, what+" failed", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// unsignedSources is the set of source paths approved to take unsigned
|
||||
// events. With no source store nothing is unsigned.
|
||||
func (s *Server) unsignedSources(ctx context.Context) (map[string]bool, error) {
|
||||
out := map[string]bool{}
|
||||
if s.Sources == nil {
|
||||
return out, nil
|
||||
}
|
||||
list, err := s.Sources.ListSources(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, src := range list {
|
||||
if src.Unsigned() {
|
||||
out[src.Path] = true
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// memSources is an in-memory SourceStore with the store's error contract.
|
||||
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 sourceTestServer(t *testing.T) (*Server, memSources) {
|
||||
t.Helper()
|
||||
srv := bindingTestServer(t)
|
||||
sources := memSources{}
|
||||
srv.Sources = sources
|
||||
return srv, sources
|
||||
}
|
||||
|
||||
func decodeSource(t *testing.T, body []byte) source.Source {
|
||||
t.Helper()
|
||||
var s source.Source
|
||||
if err := json.Unmarshal(body, &s); err != nil {
|
||||
t.Fatalf("unmarshal source: %v; body = %s", err, body)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestSourceCreateDefaultsToSignedUUIDv7AndShowsSecretOnce(t *testing.T) {
|
||||
srv, _ := sourceTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{})
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
created := decodeSource(t, w.Body.Bytes())
|
||||
if id, err := uuid.Parse(created.Path); err != nil || id.Version() != 7 {
|
||||
t.Fatalf("path %q is not a UUIDv7 (%v)", created.Path, err)
|
||||
}
|
||||
if created.Signing != source.SigningSigned || len(created.Secret) != source.MinSecretLen {
|
||||
t.Fatalf("created = %+v, want signed with a generated secret shown once", created)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/sources", nil)
|
||||
if w.Code != http.StatusOK || strings.Contains(w.Body.String(), created.Secret) || strings.Contains(w.Body.String(), `"secret"`) {
|
||||
t.Fatalf("list = %d %s; want the secret withheld", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceCreateRefusesTakenOrUnsafePath(t *testing.T) {
|
||||
srv, _ := sourceTestServer(t)
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{"path": "sentry"}); w.Code != http.StatusCreated {
|
||||
t.Fatalf("first create = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
tests := []struct {
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{"sentry", http.StatusConflict},
|
||||
{"a/b", http.StatusBadRequest},
|
||||
{"has space", http.StatusBadRequest},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{"path": tt.path}); w.Code != tt.want {
|
||||
t.Errorf("create %q = %d, want %d; body = %s", tt.path, w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceUnsignedNeedsApproval(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningSigned, Secret: "k"}
|
||||
steps := []struct {
|
||||
name, path string
|
||||
body any
|
||||
code int
|
||||
want source.Signing
|
||||
}{
|
||||
{"approve with no request", "/api/sources/fw/approve-unsigned", nil, http.StatusConflict, source.SigningSigned},
|
||||
{"request unsigned", "/api/sources/fw/signing", map[string]any{"signed": false}, http.StatusOK, source.SigningUnsignedPending},
|
||||
{"approve", "/api/sources/fw/approve-unsigned", nil, http.StatusOK, source.SigningUnsigned},
|
||||
{"approve twice", "/api/sources/fw/approve-unsigned", nil, http.StatusConflict, source.SigningUnsigned},
|
||||
{"sign again", "/api/sources/fw/signing", map[string]any{"signed": true}, http.StatusOK, source.SigningSigned},
|
||||
{"unknown source", "/api/sources/nope/signing", map[string]any{"signed": false}, http.StatusNotFound, source.SigningSigned},
|
||||
}
|
||||
for _, st := range steps {
|
||||
w := doJSON(t, srv, http.MethodPost, st.path, st.body)
|
||||
if w.Code != st.code {
|
||||
t.Fatalf("%s: status = %d, want %d; body = %s", st.name, w.Code, st.code, w.Body.String())
|
||||
}
|
||||
if got := sources["fw"].Signing; got != st.want {
|
||||
t.Fatalf("%s: signing = %q, want %q", st.name, got, st.want)
|
||||
}
|
||||
if strings.Contains(w.Body.String(), `"secret"`) {
|
||||
t.Fatalf("%s: response leaked the secret: %s", st.name, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceRegenerateSecret(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningSigned}
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/sources/fw/secret", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
got := decodeSource(t, w.Body.Bytes())
|
||||
if len(got.Secret) != source.MinSecretLen || sources["fw"].Secret != got.Secret {
|
||||
t.Fatalf("secret = %q (stored %q), want a new stored secret shown once", got.Secret, sources["fw"].Secret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceMutationsRequireCSRFHeader(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningUnsignedPending}
|
||||
for _, path := range []string{"/api/sources", "/api/sources/fw/signing", "/api/sources/fw/approve-unsigned", "/api/sources/fw/secret"} {
|
||||
if w := doJSONNoCSRF(t, srv, http.MethodPost, path, map[string]any{}); w.Code != http.StatusForbidden {
|
||||
t.Errorf("%s without CSRF = %d, want %d", path, w.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingListMarksUnsignedSources(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningUnsigned}
|
||||
sources["sentry"] = source.Source{Path: "sentry", Signing: source.SigningSigned}
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
for _, src := range []string{"fw", "sentry"} {
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest(src, src, mappingID)); w.Code != http.StatusCreated {
|
||||
t.Fatalf("create binding = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
|
||||
var body struct {
|
||||
Bindings []struct {
|
||||
Matcher struct{ Source string } `json:"matcher"`
|
||||
Unsigned bool `json:"unsigned"`
|
||||
} `json:"bindings"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || len(body.Bindings) != 2 {
|
||||
t.Fatalf("list = %s (%v)", w.Body.String(), err)
|
||||
}
|
||||
for _, b := range body.Bindings {
|
||||
if want := b.Matcher.Source == "fw"; b.Unsigned != want {
|
||||
t.Errorf("binding on %q unsigned = %v, want %v", b.Matcher.Source, b.Unsigned, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,12 +146,21 @@ type Server struct {
|
||||
// the dashboard failing to start.
|
||||
Mappings storecontract.MappingStore
|
||||
|
||||
// EventTypes persists event types (docs/prds/event-automation.md). Optional:
|
||||
// nil reports the inspector's event types as disabled.
|
||||
EventTypes storecontract.EventTypeStore
|
||||
|
||||
// Bindings persists playbook bindings: matcher + mapping + workflow
|
||||
// triples that turn a captured webhook into an archie task
|
||||
// (docs/prds/webhook-intake-security.md). Optional: nil makes every
|
||||
// /api/bindings route answer 503 rather than the dashboard failing to start.
|
||||
Bindings storecontract.BindingStore
|
||||
|
||||
// Sources persists capture sources and their signing setting
|
||||
// (docs/prds/event-automation.md "Sources"). Optional: nil makes every
|
||||
// /api/sources route answer 503 and marks no binding unsigned.
|
||||
Sources storecontract.SourceStore
|
||||
|
||||
// TelegramUpdateReportPath and TelegramUpdateChatID let a dashboard-
|
||||
// initiated update use the same post-restart notification route as a
|
||||
// Telegram-initiated update. The web UI has no durable chat identity, so
|
||||
@@ -254,6 +263,10 @@ func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
|
||||
func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/event-types", s.handleEventTypes)
|
||||
mux.HandleFunc("POST /api/event-types", s.handleEventTypeCreate)
|
||||
mux.HandleFunc("PUT /api/event-types/{id}", s.handleEventTypeUpdate)
|
||||
mux.HandleFunc("DELETE /api/event-types/{id}", s.handleEventTypeDelete)
|
||||
mux.HandleFunc("GET /api/mappings", s.handleMappingsList)
|
||||
mux.HandleFunc("POST /api/mappings", s.handleMappingCreate)
|
||||
mux.HandleFunc("GET /api/mappings/{id}", s.handleMappingGet)
|
||||
@@ -266,6 +279,11 @@ func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("PATCH /api/bindings/{id}", s.handleBindingUpdate)
|
||||
mux.HandleFunc("DELETE /api/bindings/{id}", s.handleBindingDelete)
|
||||
mux.HandleFunc("POST /api/bindings/{id}/approve", s.handleBindingApprove)
|
||||
mux.HandleFunc("GET /api/sources", s.handleSourcesList)
|
||||
mux.HandleFunc("POST /api/sources", s.handleSourceCreate)
|
||||
mux.HandleFunc("POST /api/sources/{path}/signing", s.handleSourceSigning)
|
||||
mux.HandleFunc("POST /api/sources/{path}/approve-unsigned", s.handleSourceApproveUnsigned)
|
||||
mux.HandleFunc("POST /api/sources/{path}/secret", s.handleSourceSecret)
|
||||
}
|
||||
|
||||
func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
|
||||
|
||||
+108
-1
@@ -119,6 +119,16 @@ service StateStoreService {
|
||||
rpc ListMappings(ListMappingsRequest) returns (ListMappingsResponse);
|
||||
rpc UpdateMapping(UpdateMappingRequest) returns (UpdateMappingResponse);
|
||||
rpc DeleteMapping(DeleteMappingRequest) returns (DeleteMappingResponse);
|
||||
// RecordMappingMatch counts one event a mapping resolved; the same
|
||||
// (mapping, capture) twice counts once.
|
||||
rpc RecordMappingMatch(RecordMappingMatchRequest) returns (RecordMappingMatchResponse);
|
||||
|
||||
// EventType (docs/prds/event-automation.md, "Event types"). Insert and
|
||||
// Update refuse an overlapping or malformed type.
|
||||
rpc InsertEventType(InsertEventTypeRequest) returns (InsertEventTypeResponse);
|
||||
rpc UpdateEventType(UpdateEventTypeRequest) returns (UpdateEventTypeResponse);
|
||||
rpc DeleteEventType(DeleteEventTypeRequest) returns (DeleteEventTypeResponse);
|
||||
rpc ListEventTypes(ListEventTypesRequest) returns (ListEventTypesResponse);
|
||||
|
||||
// Binding
|
||||
rpc InsertBinding(InsertBindingRequest) returns (InsertBindingResponse);
|
||||
@@ -128,6 +138,14 @@ service StateStoreService {
|
||||
rpc DeleteBinding(DeleteBindingRequest) returns (DeleteBindingResponse);
|
||||
rpc ApproveBinding(ApproveBindingRequest) returns (ApproveBindingResponse);
|
||||
|
||||
// Source (event-automation.md "Sources"): the capture endpoint and its
|
||||
// signing setting. Secrets travel in plaintext; the store encrypts at rest.
|
||||
rpc InsertSource(InsertSourceRequest) returns (InsertSourceResponse);
|
||||
rpc GetSource(GetSourceRequest) returns (GetSourceResponse);
|
||||
rpc ListSources(ListSourcesRequest) returns (ListSourcesResponse);
|
||||
rpc SetSourceSigning(SetSourceSigningRequest) returns (SetSourceSigningResponse);
|
||||
rpc SetSourceSecret(SetSourceSecretRequest) returns (SetSourceSecretResponse);
|
||||
|
||||
// Dispatch
|
||||
rpc ArmedBindingsForSource(ArmedBindingsForSourceRequest) returns (ArmedBindingsForSourceResponse);
|
||||
rpc RecordDispatch(RecordDispatchRequest) returns (RecordDispatchResponse);
|
||||
@@ -308,6 +326,37 @@ message CapturedEvent {
|
||||
string headers = 6;
|
||||
string body = 7;
|
||||
bool authenticated = 8;
|
||||
// event_type is the ID of the event type the capture was identified as on
|
||||
// arrival; empty is unidentified.
|
||||
string event_type = 9;
|
||||
// unsigned marks an event taken on an approved unsigned source.
|
||||
bool unsigned = 10;
|
||||
}
|
||||
|
||||
// EventTypeHeaderCondition mirrors internal/domain/eventtype.HeaderCondition.
|
||||
message EventTypeHeaderCondition {
|
||||
string name = 1;
|
||||
string value = 2;
|
||||
}
|
||||
|
||||
// EventTypePayloadCondition mirrors internal/domain/eventtype.PayloadCondition.
|
||||
message EventTypePayloadCondition {
|
||||
string path = 1;
|
||||
string op = 2;
|
||||
string value = 3;
|
||||
}
|
||||
|
||||
// EventType mirrors internal/domain/eventtype.EventType. header_conditions and
|
||||
// payload_conditions are its rule; schema maps each payload path to its type.
|
||||
message EventType {
|
||||
string id = 1;
|
||||
string source = 2;
|
||||
string name = 3;
|
||||
repeated EventTypeHeaderCondition header_conditions = 4;
|
||||
repeated EventTypePayloadCondition payload_conditions = 5;
|
||||
map<string, string> schema = 6;
|
||||
google.protobuf.Timestamp created_at = 7;
|
||||
google.protobuf.Timestamp updated_at = 8;
|
||||
}
|
||||
|
||||
// MappingField mirrors internal/domain/mapping.Field.
|
||||
@@ -326,6 +375,10 @@ message Mapping {
|
||||
repeated MappingField fields = 4;
|
||||
google.protobuf.Timestamp created_at = 5;
|
||||
google.protobuf.Timestamp updated_at = 6;
|
||||
string event_type_id = 7;
|
||||
// match_count and last_matched_at are read-only: the store counts them.
|
||||
int64 match_count = 8;
|
||||
google.protobuf.Timestamp last_matched_at = 9;
|
||||
}
|
||||
|
||||
// BindingMatcher mirrors internal/domain/binding.Matcher.
|
||||
@@ -344,9 +397,20 @@ message Binding {
|
||||
string repo = 7;
|
||||
int64 version = 8;
|
||||
string status = 9;
|
||||
string secret = 10;
|
||||
// Unused: signing moved to Source. Kept so the field number is never reused.
|
||||
string secret = 10 [deprecated = true];
|
||||
google.protobuf.Timestamp created_at = 11;
|
||||
google.protobuf.Timestamp updated_at = 12;
|
||||
string filter = 13;
|
||||
}
|
||||
|
||||
// Source mirrors internal/domain/source.Source.
|
||||
message Source {
|
||||
string path = 1;
|
||||
string signing = 2;
|
||||
string secret = 3;
|
||||
google.protobuf.Timestamp created_at = 4;
|
||||
google.protobuf.Timestamp updated_at = 5;
|
||||
}
|
||||
|
||||
// WorkflowStat mirrors storecontract.WorkflowStat.
|
||||
@@ -688,6 +752,24 @@ message UpdateMappingResponse {}
|
||||
message DeleteMappingRequest { string id = 1; }
|
||||
message DeleteMappingResponse {}
|
||||
|
||||
message RecordMappingMatchRequest {
|
||||
string mapping_id = 1;
|
||||
string capture_id = 2;
|
||||
}
|
||||
message RecordMappingMatchResponse {}
|
||||
|
||||
message InsertEventTypeRequest { EventType event_type = 1; }
|
||||
message InsertEventTypeResponse { string id = 1; }
|
||||
|
||||
message UpdateEventTypeRequest { EventType event_type = 1; }
|
||||
message UpdateEventTypeResponse {}
|
||||
|
||||
message DeleteEventTypeRequest { string id = 1; }
|
||||
message DeleteEventTypeResponse {}
|
||||
|
||||
message ListEventTypesRequest {}
|
||||
message ListEventTypesResponse { repeated EventType event_types = 1; }
|
||||
|
||||
message InsertBindingRequest { Binding binding = 1; }
|
||||
message InsertBindingResponse { string id = 1; }
|
||||
|
||||
@@ -709,6 +791,31 @@ message DeleteBindingResponse {}
|
||||
message ApproveBindingRequest { string id = 1; }
|
||||
message ApproveBindingResponse {}
|
||||
|
||||
message InsertSourceRequest { Source source = 1; }
|
||||
message InsertSourceResponse {}
|
||||
|
||||
message GetSourceRequest { string path = 1; }
|
||||
message GetSourceResponse {
|
||||
Source source = 1;
|
||||
bool found = 2;
|
||||
}
|
||||
|
||||
message ListSourcesRequest {}
|
||||
message ListSourcesResponse { repeated Source sources = 1; }
|
||||
|
||||
message SetSourceSigningRequest {
|
||||
string path = 1;
|
||||
string from = 2;
|
||||
string to = 3;
|
||||
}
|
||||
message SetSourceSigningResponse {}
|
||||
|
||||
message SetSourceSecretRequest {
|
||||
string path = 1;
|
||||
string secret = 2;
|
||||
}
|
||||
message SetSourceSecretResponse {}
|
||||
|
||||
message ArmedBindingsForSourceRequest { string source = 1; }
|
||||
message ArmedBindingsForSourceResponse { repeated Binding bindings = 1; }
|
||||
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
.identities-page[data-v-8ab739de]{max-width:960px}.identity-create[data-v-8ab739de]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-8ab739de]{flex:1}.identity-create input[data-v-8ab739de],.identity-create select[data-v-8ab739de],.identity-create button[data-v-8ab739de],.actions button[data-v-8ab739de]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-8ab739de]{border-top:1px solid var(--border)}.identity-row[data-v-8ab739de]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-8ab739de]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-8ab739de]{gap:.5rem;display:flex}.actions .danger[data-v-8ab739de],.error[data-v-8ab739de]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer theme{:root,:host{--font-sans:"Geist Variable", sans-serif;--color-black:#000;--spacing:.25rem;--container-xs:20rem;--container-sm:24remLine truncated
|
||||
.identities-page[data-v-8ab739de]{max-width:960px}.identity-create[data-v-8ab739de]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-8ab739de]{flex:1}.identity-create input[data-v-8ab739de],.identity-create select[data-v-8ab739de],.identity-create button[data-v-8ab739de],.actions button[data-v-8ab739de]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-8ab739de]{border-top:1px solid var(--border)}.identity-row[data-v-8ab739de]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-8ab739de]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-8ab739de]{gap:.5rem;display:flex}.actions .danger[data-v-8ab739de],.error[data-v-8ab739de]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer thLine truncated
|
||||
Vendored
+13
-12
@@ -1,19 +1,20 @@
|
||||
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n=window.location.hash;if(n.startsWith(`#/`)){let e=n.slice(1);window.history.replaceState(null,``,e+window.location.search)}function r(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var i={},a=[],o=()=>{},s=()=>!1,c=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),l=e=>e.startsWith(`onUpdate:`),u=Object.assign,d=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},f=Object.prototype.hasOwnProperty,p=(e,t)=>f.call(e,t),m=Array.isArray,h=e=>T(e)===`[object Map]`,g=e=>T(e)===`[object Set]`,_=e=>T(e)===`[object Date]`,v=e=>T(e)===`[object RegExp]`,y=e=>typeof e==`function`,b=e=>typeof e==`string`,x=e=>typeof e==`symbol`,S=e=>typeof e==`object`&&!!e,C=e=>(S(e)||y(e))&&y(e.then)&&y(e.catch),w=Object.prototype.toString,T=e=>w.call(e),ee=e=>T(e).slice(8,-1),te=e=>T(e)===`[object Object]`,ne=e=>b(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,re=r(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),ie=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},ae=/-\w/g,oe=ie(e=>e.replace(ae,e=>e.slice(1).toUpperCase())),se=/\B([A-Z])/g,ce=ie(e=>e.replace(se,`-$1`).toLowerCase()),le=ie(e=>e.charAt(0).toUpperCase()+e.slice(1)),E=ie(e=>e?`on${le(e)}`:``),ue=(e,t)=>!Object.is(e,t),de=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},fe=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},pe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},me=e=>{let t=b(e)?Number(e):NaN;return isNaN(t)?e:t},he,ge=()=>he||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},_e=r(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function ve(e){if(m(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=b(r)?Se(r):ve(r);if(i)for(let e in i)t[e]=i[e]}return t}if(b(e)||S(e))return e}var ye=/;(?![^(]*\))/g,be=/:([^]+)/,xe=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function Se(e){let t={};return e.replace(xe,e=>e.startsWith(`/*`)?``:e).split(ye).forEach(e=>{if(e){let n=e.split(be);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function D(e){let t=``;if(b(e))t=e;else if(m(e))for(let n=0;n<e.length;n++){let r=D(e[n]);r&&(t+=r+` `)}else if(S(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function Ce(e){if(!e)return null;let{class:t,style:n}=e;return t&&!b(t)&&(e.class=D(t)),n&&(e.style=ve(n)),e}var we=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,Te=r(we);we+``;function Ee(e){return!!e||e===``}function De(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=je(e[i],t[i],n);return r}function Oe(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&je(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function ke(e,t,n){let r=h(e),i=h(t);if(r||i||(r=g(e),i=g(t),r||i))return r&&i?Oe(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=e.hasOwnProperty(r),a=t.hasOwnProperty(r);if(i&&!a||!i&&a||!je(e[r],t[r],n))return!1}return String(e)===String(t)}function Ae(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function je(e,t,n){if(e===t)return!0;let r=_(e),i=_(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=x(e),i=x(t),r||i?e===t:(r=m(e),i=m(t),r||i?r&&i?Ae(e,t,n,De):!1:(r=S(e),i=S(t),r||i?!r||!i?!1:Ae(e,t,n,ke):String(e)===String(t))))}function Me(e,t){return e.findIndex(e=>je(e,t))}var Ne=e=>!!(e&&e.__v_isRef===!0),O=e=>b(e)?e:e==null?``:m(e)||S(e)&&(e.toString===w||!y(e.toString))?Ne(e)?O(e.value):JSON.stringify(e,Pe,2):String(e),Pe=(e,t)=>Ne(t)?Pe(e,t.value):h(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Fe(t,r)+` =>`]=n,e),{})}:g(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Fe(e))}:x(t)?FLine truncated
|
||||
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n=window.location.hash;if(n.startsWith(`#/`)){let e=n.slice(1);window.history.replaceState(null,``,e+window.location.search)}function r(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var i={},a=[],o=()=>{},s=()=>!1,c=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),l=e=>e.startsWith(`onUpdate:`),u=Object.assign,d=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},f=Object.prototype.hasOwnProperty,p=(e,t)=>f.call(e,t),m=Array.isArray,h=e=>ee(e)===`[object Map]`,g=e=>ee(e)===`[object Set]`,_=e=>ee(e)===`[object Date]`,v=e=>ee(e)===`[object RegExp]`,y=e=>typeof e==`function`,b=e=>typeof e==`string`,x=e=>typeof e==`symbol`,S=e=>typeof e==`object`&&!!e,C=e=>(S(e)||y(e))&&y(e.then)&&y(e.catch),w=Object.prototype.toString,ee=e=>w.call(e),te=e=>ee(e).slice(8,-1),ne=e=>ee(e)===`[object Object]`,re=e=>b(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ie=r(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),ae=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},oe=/-\w/g,se=ae(e=>e.replace(oe,e=>e.slice(1).toUpperCase())),ce=/\B([A-Z])/g,le=ae(e=>e.replace(ce,`-$1`).toLowerCase()),ue=ae(e=>e.charAt(0).toUpperCase()+e.slice(1)),T=ae(e=>e?`on${ue(e)}`:``),de=(e,t)=>!Object.is(e,t),fe=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},pe=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},me=e=>{let t=parseFloat(e);return isNaN(t)?e:t},he=e=>{let t=b(e)?Number(e):NaN;return isNaN(t)?e:t},ge,_e=()=>ge||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},ve=r(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function ye(e){if(m(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=b(r)?Ce(r):ye(r);if(i)for(let e in i)t[e]=i[e]}return t}if(b(e)||S(e))return e}var be=/;(?![^(]*\))/g,xe=/:([^]+)/,Se=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function Ce(e){let t={};return e.replace(Se,e=>e.startsWith(`/*`)?``:e).split(be).forEach(e=>{if(e){let n=e.split(xe);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function E(e){let t=``;if(b(e))t=e;else if(m(e))for(let n=0;n<e.length;n++){let r=E(e[n]);r&&(t+=r+` `)}else if(S(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function we(e){if(!e)return null;let{class:t,style:n}=e;return t&&!b(t)&&(e.class=E(t)),n&&(e.style=ye(n)),e}var Te=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,Ee=r(Te);Te+``;function De(e){return!!e||e===``}function Oe(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=Me(e[i],t[i],n);return r}function ke(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&Me(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function Ae(e,t,n){let r=h(e),i=h(t);if(r||i||(r=g(e),i=g(t),r||i))return r&&i?ke(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=e.hasOwnProperty(r),a=t.hasOwnProperty(r);if(i&&!a||!i&&a||!Me(e[r],t[r],n))return!1}return String(e)===String(t)}function je(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function Me(e,t,n){if(e===t)return!0;let r=_(e),i=_(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=x(e),i=x(t),r||i?e===t:(r=m(e),i=m(t),r||i?r&&i?je(e,t,n,Oe):!1:(r=S(e),i=S(t),r||i?!r||!i?!1:je(e,t,n,Ae):String(e)===String(t))))}function Ne(e,t){return e.findIndex(e=>Me(e,t))}var Pe=e=>!!(e&&e.__v_isRef===!0),D=e=>b(e)?e:e==null?``:m(e)||S(e)&&(e.toString===w||!y(e.toString))?Pe(e)?D(e.value):JSON.stringify(e,Fe,2):String(e),Fe=(e,t)=>Pe(t)?Fe(e,t.value):h(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Ie(t,r)+` =>`]=n,e),{})}:g(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Ie(e))}Line truncated
|
||||
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
|
||||
`)&&(ki(e,0)||yi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||c(a)&&!re(a)||a[0]===`.`||t&&!re(a)||u&&u.includes(a)){if(Ei(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&cn(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ns(x,n,t),h&&wr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&ls(()=>{x&&Ns(x,n,t),l&&g.enter(e),h&&wr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t<p;t++){let h=u?d[t]:d[t]=As(d[t]),g=h.type===fs;e?(g&&!u&&t+1<p&&As(d[t+1]).type===fs&&(l(i(e.data.slice(h.children.length)),r,a(e)),e.data=h.children),e=f(e,h,o,s,c,u)):g&&!h.children?l(h.el=i(``),r):(m||(m=!0,ki(r,1)||yi()),n(null,h,r,null,o,s,Si(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&Ci(f)&&f.data===`]`?a(t.anchor=f):(yi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,c,l)=>{if(ji(e,t)||yi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)s(n);else break}}let u=a(e),d=o(e);return s(e),n(null,t,d,u,r,i,Si(d),c),r&&(r.vnode.el=t.el,So(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&Ci(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ti=new Set([`src`,`srcset`,`href`,`poster`]);function Ei(e,t,n){return Ti.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Di=`data-allow-mismatch`,Oi={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function ki(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Di);)e=e.parentElement;return Ai(e&&e.getAttribute(Di),t)}function Ai(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(Oi[t])}}function ji(e,t){return ki(e.parentElement,1)||Mi(e)||Ni(t)}function Mi(e){return e.nodeType===1&&Ai(e.getAttribute(Di),1)}function Ni({props:e}){let t=e&&e[Di];return typeof t==`string`&&Ai(t,1)}var Pi=ge().requestIdleCallback||(e=>setTimeout(e,1)),Fi=ge().cancelIdleCallback||(e=>clearTimeout(e)),Ii=(e=1e4)=>t=>{let n=Pi(t,{timeout:e});return()=>Fi(n)};function Li(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var Ri=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e);return n(e=>{if(e instanceof Element){if(Li(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},zi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Bi=(e=[])=>(t,n)=>{b(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Vi(e,t){if(Ci(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(Ci(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Hi=e=>!!e.type.__asyncLoader;function Ui(e){y(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return N({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Vi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Ls;if(fi(e),u)return()=>Wi(u,e);let t=t=>{l=null,Xn(t,e,13,!r)};if(s&&e.suspense||Ws)return p().then(t=>()=>Wi(t,e)).catch(e=>(t(e),()=>r?V(r,{error:e}):null));let a=k(!1),c=k(),d=k(!!i),f,m;return sa(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&Gi(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Wi(u,e);if(c.value&&r)return V(r,{error:c.value});if(n&&
Line truncated
|
||||
`))),e[Gl]=Hl(i);let a=r||i.props&&i.props.type===`number`;ll(e,t?`change`:`input`,t=>{t.target.composing||e[Gl](ql(e.value,n,a))}),(n||a)&&ll(e,`change`,()=>{e.value=ql(e.value,n,a)}),t||(ll(e,`compositionstart`,Ul),ll(e,`compositionend`,Wl),ll(e,`change`,Wl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[Kl];delete e[Kl],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Gl](ql(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Gl]=Hl(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?pe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},Yl={deep:!0,created(e,t,n){e[Gl]=Hl(n),ll(e,`change`,()=>{let t=e._modelValue,n=tu(e),r=e.checked,i=e[Gl];if(m(t)){let e=Me(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(g(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(nu(e,r))})},mounted:Xl,beforeUpdate(e,t,n){e[Gl]=Hl(n),Xl(e,t,n)}};function Xl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(m(t))i=Me(t,r.props.value)>-1;else if(g(t))i=t.has(r.props.value);else{if(t===n)return;i=je(t,nu(e,!0))}e.checked!==i&&(e.checked=i)}var Zl={created(e,{value:t},n){e.checked=je(t,n.props.value),e[Gl]=Hl(n),ll(e,`change`,()=>{e[Gl](tu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Gl]=Hl(r),t!==n&&(e.checked=je(t,r.props.value))}},Ql={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ll(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?pe(tu(e)):tu(e)),r=e.multiple,i=r?g(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?m(i)?t.slice():t:i];try{e[Gl](i)}finally{ar(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Gl]=Hl(r)},mounted(e,{value:t}){eu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Gl]=Hl(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!$l(t,n[1],n[0]))&&eu(e,t)}};function $l(e,t,n){if(!n||m(e))return je(e,t);if(g(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function eu(e,t){let n=e.multiple,r=m(t);if(!n||r||g(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=tu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Me(t,o)>-1}else a.selected=t.has(o)}else if(je(tu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function tu(e){return`_value`in e?e._value:e.value}function nu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var ru={created(e,t,n){au(e,t,n,null,`created`)},mounted(e,t,n){au(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){au(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){au(e,t,n,r,`updated`)}};function iu(e,t){switch(e){case`SELECT`:return Ql;case`TEXTAREA`:return Jl;default:switch(t){case`checkbox`:return Yl;case`radio`:return Zl;default:return Jl}}}function au(e,t,n,r,i){let a=iu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function ou(){Jl.getSSRProps=({value:e})=>({value:e}),Zl.getSSRProps=({value:e},t)=>{if(t.props&&je(t.props.value,e))return{checked:!0}},Yl.getSSRProps=({value:e},t)=>{if(m(e)){if(t.props&&Me(e,t.props.value)>-1)return{checked:!0}}else if(g(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},ru.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=iu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var su=[`ctrl`,`shift`,`alt`,`meta`],cu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>su.some(n=>e[`${n}Key`]&&!t.includes(n))},lu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=cu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},uu={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},du=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=ce(n.key);if(t.some(e=>e===r||uu[e]===r))return e(n)}))},fu=u({patchProp:xl},xc),pu,mu=!1;function hu(){return pu||=Ho(fu)}function gu(){return pu=mu?pu:Uo(fu),mu=!0,pu}var _u=((...e)=>{hu().render(...e)}),vu=((...e)=>{gu().hydrate(...e)}),yu=((...e)=>{let t=hu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Su(e);if(!r)return;let i=t._component;!y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,xu(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),bu=((
Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var kp;function Ap(e){kp=e}var jp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Mp(e){let t=e instanceof jp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Np(e,t){let n=await fetch(e,t);if(kp?.(n.status===401),!n.ok)throw new jp(await Op(n),n.status);return n}async function Pp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Ep,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Np(e,s);return a?await c.json():void 0}var Y={health:()=>Pp(`/health/detailed`),summary:()=>Pp(`/api/summary`),tasks:()=>Pp(`/api/tasks`),taskMeta:()=>Pp(`/api/task-meta`),task:e=>Pp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Pp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/changes`+Dp(t)),taskDebug:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/debug`+Dp(t)),taskAction:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Pp(`/api/setup`),capabilities:()=>Pp(`/api/capabilities`),workflows:()=>Pp(`/api/workflows`),workRequest:e=>Pp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Pp(`/api/skills`),channels:()=>Pp(`/api/channels`),curators:()=>Pp(`/api/curators`),channelReload:e=>Pp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Pp(`/api/config`),logs:e=>Pp(`/api/logs`+Dp(e)),taskLogs:(e,t)=>Pp(`/api/tasks/${encodeURIComponent(e)}/logs`+Dp(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Pp(`/api/version`),updateSnapshot:()=>Pp(`/api/chat/update`),updateInstall:e=>Pp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Pp(`/api/captures`+Dp({limit:e})),mappings:()=>Pp(`/api/mappings`),mappingCreate:e=>Pp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Pp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Pp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Pp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Pp(`/api/bindings`),bindingCreate:e=>Pp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Pp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Pp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Pp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),chatSessions:()=>Pp(`/api/chat/sessions`),chatMessages:e=>Pp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Pp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Pp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Pp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:Tp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Pp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Pp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Pp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Pp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Np(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Fp(e,t){let n=new EventSource(`/api/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Ip(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(wp(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Lp=`archie.web.chat.channel`;function Rp(){let e=localStorage.getItem(Lp);return e||(e=Tp(),localStorage.setItem(Lp,e)),e}var zp=/(?:^|\s)\/([^\s]*)$/,Bp=/(?:^|\s)\/[^\s]*$/,Vp=8;function Hp(e,t,n){let r=t.slice(0,n).match(zp);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description??``}`.toLowerCase().includes(i)).slice(0,Vp)}function Up(e,t,n){let r=e.slice(0,t),i=e.slice(t),a=r.search(Bp),o=a<0?r.length:a+ +(r[a]===` `);return{text:`${r.slice(0,o)}${n} ${i}`,cursor:o+n.length+1}}function Wp(e,t){let n=t.trim();return e.some(e=>e.command===n)}function Gp(e){return{text:e,sourceID:Tp()}}function Kp(e){return{...e}}function qp(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.tri
Line truncated
|
||||
`)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||c(a)&&!ie(a)||a[0]===`.`||t&&!ie(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ps(x,n,t),h&&Tr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&us(()=>{x&&Ps(x,n,t),l&&g.enter(e),h&&Tr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t<p;t++){let h=u?d[t]:d[t]=js(d[t]),g=h.type===ps;e?(g&&!u&&t+1<p&&js(d[t+1]).type===ps&&(l(i(e.data.slice(h.children.length)),r,a(e)),e.data=h.children),e=f(e,h,o,s,c,u)):g&&!h.children?l(h.el=i(``),r):(m||(m=!0,Ai(r,1)||bi()),n(null,h,r,null,o,s,Ci(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,c,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)s(n);else break}}let u=a(e),d=o(e);return s(e),n(null,t,d,u,r,i,Ci(d),c),r&&(r.vnode.el=t.el,Co(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=_e().requestIdleCallback||(e=>setTimeout(e,1)),Ii=_e().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var zi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e);return n(e=>{if(e instanceof Element){if(Ri(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},Bi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Vi=(e=[])=>(t,n)=>{b(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Hi(e,t){if(wi(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(wi(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ui=e=>!!e.type.__asyncLoader;function Wi(e){y(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return M({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Hi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Rs;if(pi(e),u)return()=>Gi(u,e);let t=t=>{l=null,Zn(t,e,13,!r)};if(s&&e.suspense||Gs)return p().then(t=>()=>Gi(t,e)).catch(e=>(t(e),()=>r?B(r,{error:e}):null));let a=O(!1),c=O(),d=O(!!i),f,m;return ca(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&Ki(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Gi(u,e);if(c.value&&r)return B(r,{error:c.value});if(n&&
Line truncated
|
||||
`))),e[Kl]=Ul(i);let a=r||i.props&&i.props.type===`number`;ul(e,t?`change`:`input`,t=>{t.target.composing||e[Kl](Jl(e.value,n,a))}),(n||a)&&ul(e,`change`,()=>{e.value=Jl(e.value,n,a)}),t||(ul(e,`compositionstart`,Wl),ul(e,`compositionend`,Gl),ul(e,`change`,Gl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[ql];delete e[ql],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Kl](Jl(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Kl]=Ul(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?me(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},Xl={deep:!0,created(e,t,n){e[Kl]=Ul(n),ul(e,`change`,()=>{let t=e._modelValue,n=nu(e),r=e.checked,i=e[Kl];if(m(t)){let e=Ne(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(g(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(ru(e,r))})},mounted:Zl,beforeUpdate(e,t,n){e[Kl]=Ul(n),Zl(e,t,n)}};function Zl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(m(t))i=Ne(t,r.props.value)>-1;else if(g(t))i=t.has(r.props.value);else{if(t===n)return;i=Me(t,ru(e,!0))}e.checked!==i&&(e.checked=i)}var Ql={created(e,{value:t},n){e.checked=Me(t,n.props.value),e[Kl]=Ul(n),ul(e,`change`,()=>{e[Kl](nu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Kl]=Ul(r),t!==n&&(e.checked=Me(t,r.props.value))}},$l={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ul(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?me(nu(e)):nu(e)),r=e.multiple,i=r?g(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?m(i)?t.slice():t:i];try{e[Kl](i)}finally{or(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Kl]=Ul(r)},mounted(e,{value:t}){tu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Kl]=Ul(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!eu(t,n[1],n[0]))&&tu(e,t)}};function eu(e,t,n){if(!n||m(e))return Me(e,t);if(g(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function tu(e,t){let n=e.multiple,r=m(t);if(!n||r||g(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=nu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Ne(t,o)>-1}else a.selected=t.has(o)}else if(Me(nu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function nu(e){return`_value`in e?e._value:e.value}function ru(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var iu={created(e,t,n){ou(e,t,n,null,`created`)},mounted(e,t,n){ou(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){ou(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){ou(e,t,n,r,`updated`)}};function au(e,t){switch(e){case`SELECT`:return $l;case`TEXTAREA`:return Yl;default:switch(t){case`checkbox`:return Xl;case`radio`:return Ql;default:return Yl}}}function ou(e,t,n,r,i){let a=au(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function su(){Yl.getSSRProps=({value:e})=>({value:e}),Ql.getSSRProps=({value:e},t)=>{if(t.props&&Me(t.props.value,e))return{checked:!0}},Xl.getSSRProps=({value:e},t)=>{if(m(e)){if(t.props&&Ne(e,t.props.value)>-1)return{checked:!0}}else if(g(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},iu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=au(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var cu=[`ctrl`,`shift`,`alt`,`meta`],lu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>cu.some(n=>e[`${n}Key`]&&!t.includes(n))},uu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=lu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},du={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},fu=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=le(n.key);if(t.some(e=>e===r||du[e]===r))return e(n)}))},pu=u({patchProp:Sl},Sc),mu,hu=!1;function gu(){return mu||=Uo(pu)}function _u(){return mu=hu?mu:Wo(pu),hu=!0,mu}var vu=((...e)=>{gu().render(...e)}),yu=((...e)=>{_u().hydrate(...e)}),bu=((...e)=>{let t=gu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Cu(e);if(!r)return;let i=t._component;!y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,Su(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),xu=((
Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Fp;function Ip(e){Fp=e}var Lp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Rp(e){let t=e instanceof Lp?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function zp(e,t){let n=await fetch(e,t);if(Fp?.(n.status===401),!n.ok)throw new Lp(await Pp(n),n.status);return n}async function Bp(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Mp,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await zp(e,s);return a?await c.json():void 0}var J={health:()=>Bp(`/health/detailed`),summary:()=>Bp(`/api/summary`),tasks:()=>Bp(`/api/tasks`),taskMeta:()=>Bp(`/api/task-meta`),task:e=>Bp(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Bp(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Bp(`/api/tasks/${encodeURIComponent(e)}/changes`+Np(t)),taskDebug:(e,t)=>Bp(`/api/tasks/${encodeURIComponent(e)}/debug`+Np(t)),taskAction:(e,t)=>Bp(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Bp(`/api/setup`),capabilities:()=>Bp(`/api/capabilities`),workflows:()=>Bp(`/api/workflows`),workRequest:e=>Bp(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Bp(`/api/skills`),channels:()=>Bp(`/api/channels`),curators:()=>Bp(`/api/curators`),channelReload:e=>Bp(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Bp(`/api/config`),logs:e=>Bp(`/api/logs`+Np(e)),taskLogs:(e,t)=>Bp(`/api/tasks/${encodeURIComponent(e)}/logs`+Np(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Bp(`/api/version`),updateSnapshot:()=>Bp(`/api/chat/update`),updateInstall:e=>Bp(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Bp(`/api/captures`+Np({limit:e})),eventTypes:()=>Bp(`/api/event-types`),eventTypeCreate:e=>Bp(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>Bp(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>Bp(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>Bp(`/api/mappings`),mappingCreate:e=>Bp(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Bp(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Bp(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Bp(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Bp(`/api/bindings`),bindingCreate:e=>Bp(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Bp(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Bp(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Bp(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),sources:()=>Bp(`/api/sources`),sourceCreate:e=>Bp(`/api/sources`,{method:`POST`,body:{path:e}}),sourceSigning:(e,t)=>Bp(`/api/sources/${encodeURIComponent(e)}/signing`,{method:`POST`,body:{signed:t}}),sourceApproveUnsigned:e=>Bp(`/api/sources/${encodeURIComponent(e)}/approve-unsigned`,{method:`POST`}),sourceSecret:e=>Bp(`/api/sources/${encodeURIComponent(e)}/secret`,{method:`POST`}),chatSessions:()=>Bp(`/api/chat/sessions`),chatMessages:e=>Bp(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Bp(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Bp(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Bp(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:jp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Bp(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Bp(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Bp(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Bp(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>zp(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Vp(e,t){let n=new EventSource(`/api/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Hp(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Ap(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Up=`archie.web.chat.channel`;function Wp(){let e=localStorage.getItem(Up);return e||(e=
Line truncated
|
||||
|
||||
`);u=r.pop()||``;for(let e of r){let t=e.split(`
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(Zp.value=n.session_id),n.type===`delta`&&(o+=n.text,nm.value=nm.value?{...nm.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],nm.value=nm.value?{...nm.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);Qp.value=[...Qp.value,{from:`assistant`,text:o,tool_calls:a}],nm.value=null,em.value=`Ready`,await _m()}catch(e){let t=e;t.name===`AbortError`&&!c?(nm.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},em.value=`Stopped`):(nm.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Kp(r):void 0,isRetry:i},em.value=`Error — retry available`)}finally{clearTimeout(l),hm=null,tm.value=!1}}function Am(){em.value=`Stopping…`,Zp.value&&Y.chatCancel(Zp.value).catch(()=>{}),gm()}function jm(){ra(()=>{_m().catch(e=>{em.value=e.message||`Chat unavailable`})}),sa(()=>{gm()})}var Mm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Nm=N({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return J(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(L(),R(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":A(Jp),onClick:i[0]||=e=>n(`toggle`)},[B(`span`,{"aria-hidden":`true`,class:D(r(!e.open))},[V(A(Md),{size:22})],2),B(`span`,{"aria-hidden":`true`,class:D(r(e.open))},[V(A(Jd),{size:22})],2)],8,Mm))}});function Pm(e){return typeof e==`string`?`'${e}'`:new Rm().serialize(e)}var Fm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Im=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Fm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Lm(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&Im[n]?Im[n]:n+128,s=a<128&&Im[a]?Im[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var Rm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Lm(e,t):n===`number`&&r===`number`?e-t:Lm(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort(Lm),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`InLine truncated
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(rm.value=n.session_id),n.type===`delta`&&(o+=n.text,cm.value=cm.value?{...cm.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],cm.value=cm.value?{...cm.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);im.value=[...im.value,{from:`assistant`,text:o,tool_calls:a}],cm.value=null,om.value=`Ready`,await Cm()}catch(e){let t=e;t.name===`AbortError`&&!c?(cm.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},om.value=`Stopped`):(cm.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Qp(r):void 0,isRetry:i},om.value=`Error — retry available`)}finally{clearTimeout(l),xm=null,sm.value=!1}}function Im(){om.value=`Stopping…`,rm.value&&J.chatCancel(rm.value).catch(()=>{}),Sm()}function Lm(){ia(()=>{Cm().catch(e=>{om.value=e.message||`Chat unavailable`})}),ca(()=>{Sm()})}var Rm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],zm=M({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return q(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(I(),L(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":k(em),onClick:i[0]||=e=>n(`toggle`)},[z(`span`,{"aria-hidden":`true`,class:E(r(!e.open))},[B(k(Ld),{size:22})],2),z(`span`,{"aria-hidden":`true`,class:E(r(e.open))},[B(k(ef),{size:22})],2)],8,Rm))}});function Bm(e){return typeof e==`string`?`'${e}'`:new Wm().serialize(e)}var Vm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Hm=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Vm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Um(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&Hm[n]?Hm[n]:n+128,s=a<128&&Hm[a]?Hm[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var Wm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Um(e,t):n===`number`&&r===`number`?e-t:Um(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort(Um),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`InLine truncated
|
||||
`)].join(`
|
||||
`))}return()=>i.value||r.value||o.value?ic(t.default({present:o.value})[0],{ref:e=>{let t=fh(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),vg=N({name:`PrimitiveSlot`,inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{if(!n.default)return null;let e=xh(n.default()),r=e.findIndex(e=>e.type!==ps);if(r===-1)return e;let i=e[r];delete i.props?.ref;let a=i.props?W(t,i.props):t,o=Os({...i,props:{}},a);return e.length===1?o:(e[r]=o,e)}}}),yg=[`area`,`img`,`input`],Z=N({name:`Primitive`,inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:`div`}},setup(e,{attrs:t,slots:n}){let r=e.asChild?`template`:e.as;return typeof r==`string`&&yg.includes(r)?()=>ic(r,t):r===`template`?()=>ic(vg,t,{default:n.default}):()=>ic(e.as,t,{default:n.default})}});function bg(){let e=k();return{primitiveElement:e,currentElement:G(()=>[`#text`,`#comment`].includes(e.value?.$el.nodeName)?e.value?.$el.nextElementSibling:fh(e))}}function xg({type:e,defaultValue:t,modelValue:n}){let r=n||t;return n!==void 0||t!==void 0?Array.isArray(r)?`multiple`:`single`:e??`single`}function Sg({type:e,defaultValue:t,modelValue:n}){return e||xg({type:e,defaultValue:t,modelValue:n})}function Cg({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function wg(e,t){let n=G(()=>Sg(e)),r=bh(e,`modelValue`,t,{defaultValue:Cg(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=zm(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(Gm(t,e)){let n=t.findIndex(t=>zm(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:G(()=>n.value===`single`)}}var[Tg,Eg]=Vm(`DialogRoot`),Dg=N({inheritAttrs:!1,__name:`DialogRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1,default:!1},modal:{type:Boolean,required:!1,default:!0},unmountOnHide:{type:Boolean,required:!1,default:!0}},emits:[`update:open`],setup(e,{emit:t}){let n=e,r=bh(n,`open`,t,{defaultValue:n.defaultOpen,passive:n.open===void 0}),i=k(),a=k(),{modal:o,unmountOnHide:s}=En(n);return Eg({open:r,modal:o,unmountOnHide:s,openModal:()=>{r.value=!0},onOpenChange:e=>{r.value=e},onOpenToggle:()=>{r.value=!r.value},contentId:``,titleId:``,descriptionId:``,triggerElement:i,contentElement:a}),(e,t)=>F(e.$slots,`default`,{open:A(r),close:()=>r.value=!1})}}),Og=N({__name:`DialogClose`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;X();let n=Tg();return(e,r)=>(L(),z(A(Z),W(t,{type:e.as===`button`?`button`:void 0,onClick:r[0]||=e=>A(n).onOpenChange(!1)}),{default:j(()=>[F(e.$slots,`default`)]),_:3},16,[`type`]))}}),kg=`dismissableLayer.pointerDownOutside`,Ag=`dismissableLayer.focusOutside`;function jg(e,t){if(!(t instanceof Element))return!1;let n=t.closest(`[data-dismissable-layer]`),r=e.dataset.dismissableLayer===``?e:e.querySelector(`[data-dismissable-layer]`),i=Array.from(e.ownerDocument.querySelectorAll(`[data-dismissable-layer]`));return!!(n&&(r===n||i.indexOf(r)<i.indexOf(n)))}function Mg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=k(!1),a=k(()=>{});return Ar(o=>{if(!Ym||!xn(n))return;let s=async n=>{let o=n.target;if(t?.value&&o){if(jg(t.value,o)){i.value=!1;return}if(n.target&&!i.value){let t={originalEvent:n};function i(){Um(kg,e,t)}n.pointerType===`touch`?(r.removeEventListener(`click`,a.value),a.value=i,r.addEventListener(`click`,a.value,{once:!0})):i()}else r.removeEventListener(`click`,a.value);i.value=!1}},c=window.setTimeout(()=>{r.addEventListener(`pointerdown`,s)},0);o(()=>{window.clearTimeout(c),r.removeEventListener(`pointerdown`,s),r.removeEventListener(`click`,a.value)})}),{onPointerDownCapture:()=>{xn(n)&&(i.value=!0)}}}function Ng(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=k(!1);return Ar(a=>{if(!Ym||!xn(n))return;let o=async n=>{if(!t?.value)return;await ar(),await ar();let r=n.target;t.value&&r&&!jg(t.value,r)&&n.target&&!i.value&&Um(Ag,e,{originalEvent:n})};r.addEventListener(`focusin`,o),a(()=>r.removeEventListener(`focusin`,o))}),{onFocusCapture:()=>{xn(n)&&(i.value=!0)},onBlurCapture:()=>{xn(n)&&(i.value=!1)}}}var Pg=N({__name:`DismissableLayer`,props:{disableOutsidePointerEvents:{type:Boolean,required:!1,default:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},present:{type:Boolean,required:!1,default:!0}},emits:[`escapeKeyDown`,`pointerDownOutside`,`focusOutside`,`interactOutside`,`dismiss`],setup(e,{emit:t}){let n=e,r=t,{forwardRef:i,currentElement:a}=X(),o=G(()=>a.value?.ownerDocument??globalThis.document),s=G(()=>Dh.layersRoot),c=G(()=>a.value?Array.from(s.value).indexOf(a.value):-1),l=G(()=>Dh.layersWithOutsidePointerEventsDisabled.size>0),u=G(()=>{let e=Array.from(s.value),[t]=[...Dh.layersWithOutsidePointerEventsDisabled].slice(-1),n=e.indexOf(t);return c.value>=n}),d=Mg
Line truncated
|
||||
`))}return()=>i.value||r.value||o.value?ac(t.default({present:o.value})[0],{ref:e=>{let t=vh(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),wg=M({name:`PrimitiveSlot`,inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{if(!n.default)return null;let e=Dh(n.default()),r=e.findIndex(e=>e.type!==ms);if(r===-1)return e;let i=e[r];delete i.props?.ref;let a=i.props?U(t,i.props):t,o=ks({...i,props:{}},a);return e.length===1?o:(e[r]=o,e)}}}),Tg=[`area`,`img`,`input`],X=M({name:`Primitive`,inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:`div`}},setup(e,{attrs:t,slots:n}){let r=e.asChild?`template`:e.as;return typeof r==`string`&&Tg.includes(r)?()=>ac(r,t):r===`template`?()=>ac(wg,t,{default:n.default}):()=>ac(e.as,t,{default:n.default})}});function Eg(){let e=O();return{primitiveElement:e,currentElement:W(()=>[`#text`,`#comment`].includes(e.value?.$el.nodeName)?e.value?.$el.nextElementSibling:vh(e))}}function Dg({type:e,defaultValue:t,modelValue:n}){let r=n||t;return n!==void 0||t!==void 0?Array.isArray(r)?`multiple`:`single`:e??`single`}function Og({type:e,defaultValue:t,modelValue:n}){return e||Dg({type:e,defaultValue:t,modelValue:n})}function kg({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function Ag(e,t){let n=W(()=>Og(e)),r=Eh(e,`modelValue`,t,{defaultValue:kg(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=Gm(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(Zm(t,e)){let n=t.findIndex(t=>Gm(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:W(()=>n.value===`single`)}}var[jg,Mg]=qm(`DialogRoot`),Ng=M({inheritAttrs:!1,__name:`DialogRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1,default:!1},modal:{type:Boolean,required:!1,default:!0},unmountOnHide:{type:Boolean,required:!1,default:!0}},emits:[`update:open`],setup(e,{emit:t}){let n=e,r=Eh(n,`open`,t,{defaultValue:n.defaultOpen,passive:n.open===void 0}),i=O(),a=O(),{modal:o,unmountOnHide:s}=Dn(n);return Mg({open:r,modal:o,unmountOnHide:s,openModal:()=>{r.value=!0},onOpenChange:e=>{r.value=e},onOpenToggle:()=>{r.value=!r.value},contentId:``,titleId:``,descriptionId:``,triggerElement:i,contentElement:a}),(e,t)=>P(e.$slots,`default`,{open:k(r),close:()=>r.value=!1})}}),Pg=M({__name:`DialogClose`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;Y();let n=jg();return(e,r)=>(I(),R(k(X),U(t,{type:e.as===`button`?`button`:void 0,onClick:r[0]||=e=>k(n).onOpenChange(!1)}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`type`]))}}),Fg=`dismissableLayer.pointerDownOutside`,Ig=`dismissableLayer.focusOutside`;function Lg(e,t){if(!(t instanceof Element))return!1;let n=t.closest(`[data-dismissable-layer]`),r=e.dataset.dismissableLayer===``?e:e.querySelector(`[data-dismissable-layer]`),i=Array.from(e.ownerDocument.querySelectorAll(`[data-dismissable-layer]`));return!!(n&&(r===n||i.indexOf(r)<i.indexOf(n)))}function Rg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1),a=O(()=>{});return jr(o=>{if(!th||!Sn(n))return;let s=async n=>{let o=n.target;if(t?.value&&o){if(Lg(t.value,o)){i.value=!1;return}if(n.target&&!i.value){let t={originalEvent:n};function i(){Ym(Fg,e,t)}n.pointerType===`touch`?(r.removeEventListener(`click`,a.value),a.value=i,r.addEventListener(`click`,a.value,{once:!0})):i()}else r.removeEventListener(`click`,a.value);i.value=!1}},c=window.setTimeout(()=>{r.addEventListener(`pointerdown`,s)},0);o(()=>{window.clearTimeout(c),r.removeEventListener(`pointerdown`,s),r.removeEventListener(`click`,a.value)})}),{onPointerDownCapture:()=>{Sn(n)&&(i.value=!0)}}}function zg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1);return jr(a=>{if(!th||!Sn(n))return;let o=async n=>{if(!t?.value)return;await or(),await or();let r=n.target;t.value&&r&&!Lg(t.value,r)&&n.target&&!i.value&&Ym(Ig,e,{originalEvent:n})};r.addEventListener(`focusin`,o),a(()=>r.removeEventListener(`focusin`,o))}),{onFocusCapture:()=>{Sn(n)&&(i.value=!0)},onBlurCapture:()=>{Sn(n)&&(i.value=!1)}}}var Bg=M({__name:`DismissableLayer`,props:{disableOutsidePointerEvents:{type:Boolean,required:!1,default:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},present:{type:Boolean,required:!1,default:!0}},emits:[`escapeKeyDown`,`pointerDownOutside`,`focusOutside`,`interactOutside`,`dismiss`],setup(e,{emit:t}){let n=e,r=t,{forwardRef:i,currentElement:a}=Y(),o=W(()=>a.value?.ownerDocument??globalThis.document),s=W(()=>Nh.layersRoot),c=W(()=>a.value?Array.from(s.value).indexOf(a.value):-1),l=W(()=>Nh.layersWithOutsidePointerEventsDisabled.size>0),u=W(()=>{let e=Array.from(s.value),[t]=[...Nh.layersWithOutsidePointerEventsDisabled].slice(-1),n=e.indexOf(t);return c.value>=n}),d=Rg
Line truncated
|
||||
- a positive number
|
||||
- less than the value passed to \`max\` (or ${xx} if no \`max\` prop is set)
|
||||
- less than the value passed to \`max\` (or ${Dx} if no \`max\` prop is set)
|
||||
- \`null\` or \`undefined\` if the progress is indeterminate.
|
||||
|
||||
Defaulting to \`null\`.`),null)}function Ex(e){return wx(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${xx}\`.`),xx)}var Dx=N({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:xx},getValueLabel:{type:Function,required:!1,default:(e,t)=>wx(e)?`${Math.round(e/t*xx)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;X();let i=bh(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=bh(n,`max`,r,{passive:n.max===void 0});M(()=>i.value,async e=>{let t=Tx(e,n.max);t!==e&&(await ar(),i.value=t)},{immediate:!0}),M(()=>n.max,e=>{let t=Ex(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=G(()=>Wm(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Cx({modelValue:i,max:a,progressState:o}),(e,t)=>(L(),z(A(Z),{"as-child":e.asChild,as:e.as,"aria-valuemax":A(a),"aria-valuemin":0,"aria-valuenow":wx(A(i))?A(i):void 0,"aria-valuetext":e.getValueText?.(A(i),A(a)),"aria-label":e.getValueLabel(A(i),A(a)),role:`progressbar`,"data-state":o.value,"data-value":A(i)??void 0,"data-max":A(a)},{default:j(()=>[F(e.$slots,`default`,{modelValue:A(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Ox=N({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Sx();return X(),(e,r)=>(L(),z(A(Z),W(t,{"data-state":A(n).progressState.value,"data-value":A(n).modelValue?.value??void 0,"data-max":A(n).max.value}),{default:j(()=>[F(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),kx=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Ax=[` `,`Enter`];function jx(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Mx(e,t,n)):Mx(e,t,n)}function Mx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:zm(e,t)}function Nx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Px=[`value`],[Fx,Ix]=Vm(`SelectRoot`),Lx=N({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=En(n),c=bh(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=bh(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=k(),d=k(),f=k({x:0,y:0}),p=G(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Wm(c.value));O_({isProvider:!0});let m=Ih(s),h=Vh(u),g=k(new Set),_=G(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>Mx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>jx(e,t.value,n.by))}return Ix({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(L(),z(A(V_),null,{default:j(()=>[F(e.$slots,`default`,{modelValue:A(c),open:A(l)}),A(h)&&e.name?(L(),z(Rx,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:A(o),required:A(i),name:e.name,autocomplete:e.autocomplete,disabled:A(a),value:A(c)},{default:j(()=>[A(Wm)(A(c))?(L(),R(`option`,{key:0,value:e.nullableValue},null,8,Px)):U(`v-if`,!0),(L(!0),R(I,null,P(Array.from(g.value),e=>(L(),R(`option`,W({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):U(`v-if`,!0)]),_:3}))}}),Rx=N({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=k(),r=Fx();M(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:rT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>rT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
|
||||
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=aT(c),u=e+1<n.length?aT(n[e+1]):null;if(l&&u&&oT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=aT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>rT(e)),rows:r.map(e=>e.map(e=>rT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:rT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:rT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
|
||||
`)}),t}function aT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function oT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var sT={class:`[overflow-wrap:anywhere]`},cT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},lT={class:`font-mono text-[0.85em]`},uT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},dT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},fT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},pT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},mT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},hT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},gT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},_T={key:8,class:`mb-2.5 last:mb-0`},vT=N({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=G(()=>iT(t.text));return(e,t)=>(L(),R(`div`,sT,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(I,{key:t},[e.kind===`pre`?(L(),R(`pre`,cT,[B(`code`,lT,O(e.code),1)])):e.kind===`table`?(L(),R(`table`,uT,[B(`thead`,null,[B(`tr`,null,[(L(!0),R(I,null,P(e.head,(e,t)=>(L(),R(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[V(tT,{inline:e},null,8,[`inline`])]))),128))])]),B(`tbody`,null,[(L(!0),R(I,null,P(e.rows,(e,t)=>(L(),R(`tr`,{key:t},[(L(!0),R(I,null,P(e,(e,t)=>(L(),R(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[V(tT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),R(`blockquote`,dT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),R(`h1`,fT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),R(`h2`,pT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),R(`h3`,mT,[V(tT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),R(`ul`,hT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(tT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),R(`ol`,gT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(tT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),R(`p`,_T,[V(tT,{inline:e.inline},null,8,[`inline`])])):U(``,!0)],64))),128))]))}}),yT={class:`truncate`},bT=N({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ma(`RouterLink`);return L(),z(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:j(()=>[V(A(yd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),B(`span`,yT,O(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),xT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},ST={class:`font-semibold text-foreground`},CT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},wT=N({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=G(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=G(()=>t.tool.parameters||t.tool.Parameters||``),i=G(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=G(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(L(),z(bT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(L(),R(`div`,xT,[V(A(qd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),B(`span`,ST,O(n.value),1),r.value?(L(),R(`code`,CT,O(r.value),1)):U(``,!0),B(`span`,{class:D(A(J)(`text-fg-muted`,i.value&&`text-danger`))},O(a.value),3)]))}}),TT={key:0,class:`mb-2 grid gap-0.5 text-xs`},ET={key:2,class:`whitespace-pre-wrap`},DT=N({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(L(),R(`div`,{class:D([`flex`,e.assistant?`justify-start`:`justify-end`])},[B(`div`,{class:D(A(J)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(L(),R(`div`,TT,[(L(!0),R(I,null,P(e.tools,(t,n)=>(L(),z(wT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):U(``,!0),e.assistant?(L(),z(vT,{key:1,text:e.text},null,8,[`text`])):(L(),R(`div`,ET,O(e.text),1)),F(t.$slots,`default`)],2)],2))}}),OT={class:`w-full self-center justify-self-center py-6 text-center`},kT={class:`grid gap-2`},AT=[`onClick`],jT=N({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(L(),R(`div`,OT,[t[0]||=B(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
|
||||
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>tA?`${n.slice(0,tA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var rA=[`title`],iA=N({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=G(()=>Ok(n.event)),a=G(()=>nA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=G(()=>n.event.at?yO(n.event.at):`—`);return(e,t)=>(L(),z(A(Qk),{class:D(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[du(lu(o,[`prevent`]),[`enter`]),du(lu(o,[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[H(O(n.event.kind||n.event.type||`event`),1)]),_:1}),V(A($),{class:`font-mono`},{default:j(()=>[H(O(i.value>0?`#${i.value}`:`—`),1)]),_:1}),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},O(a.value.text),9,rA)]),_:1}),V(A($),null,{default:j(()=>[H(O(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function aA(e,t){return`${e}:${t??0}`}function oA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=aA(nA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var sA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},cA={class:`max-h-[28rem] overflow-y-auto`},lA=[`aria-expanded`,`aria-label`,`onClick`],uA=[`title`],dA=N({__name:`LiveActivityCard`,setup(e){let t=eE(),{activity:n,streamKind:r,streamState:i}=ad(tk()),a=nn(new Set),o=G(()=>oA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return nA(e.representative)}function u(e){return e.representative.at?yO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(L(),z(A(dO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[V(A(_O),null,{default:j(()=>[...t[0]||=[H(`Live activity`,-1)]]),_:1}),V(A(fO),null,{default:j(()=>[V(A(ZD),{variant:A(r)},{default:j(()=>[H(O(A(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),V(A(pO),null,{default:j(()=>[B(`div`,sA,[B(`div`,cA,[V(A(Xk),null,{default:j(()=>[V(A(eA),{class:`sticky top-0 z-10 bg-card`},{default:j(()=>[V(A(Qk),null,{default:j(()=>[V(A($k),null,{default:j(()=>[...t[1]||=[H(`Event`,-1)]]),_:1}),V(A($k),null,{default:j(()=>[...t[2]||=[H(`Task`,-1)]]),_:1}),V(A($k),null,{default:j(()=>[...t[3]||=[H(`Detail`,-1)]]),_:1}),V(A($k),null,{default:j(()=>[...t[4]||=[H(`When`,-1)]]),_:1})]),_:1})]),_:1}),V(A(Zk),null,{default:j(()=>[A(n).length?U(``,!0):(L(),z(A(Qk),{key:0},{default:j(()=>[V(A($),{colspan:`4`},{default:j(()=>[V(A(UD),null,{default:j(()=>[V(A(KD),null,{default:j(()=>[V(A(YD),null,{default:j(()=>[...t[5]||=[H(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),A(n).length?(L(!0),R(I,{key:1},P(o.value,e=>(L(),R(I,{key:e.key},[e.count===1?(L(),z(iA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(L(),R(I,{key:1},[V(A(Qk),{class:D(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[B(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:lu(t=>s(e.key),[`stop`])},[c(e)?(L(),z(A(xd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(L(),z(A(Cd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),H(` `+O(e.label)+` `,1),V(A(ZD),{variant:`idle`},{default:j(()=>[H(`×`+O(e.count),1)]),_:2},1024)],8,lA)]),_:2},1024),V(A($),{class:`font-mono`},{default:j(()=>[H(O(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},O(l(e).text),9,uA)]),_:2},1024),V(A($),null,{default:j(()=>[H(O(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(L(!0),R(I,{key:0},P(e.events,(t,n)=>(L(),z(iA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):U(``,!0)],64))],64))),128)):U(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),fA=N({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=$S(t,`class`);return(e,r)=>(L(),z(A(Dx),W({"data-slot":`progress`},A(n),{class:A(J)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:j(()=>[V(A(Ox),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ve(`tLine truncated
|
||||
Defaulting to \`null\`.`),null)}function Mx(e){return Ax(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${Dx}\`.`),Dx)}var Nx=M({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:Dx},getValueLabel:{type:Function,required:!1,default:(e,t)=>Ax(e)?`${Math.round(e/t*Dx)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;Y();let i=Eh(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=Eh(n,`max`,r,{passive:n.max===void 0});j(()=>i.value,async e=>{let t=jx(e,n.max);t!==e&&(await or(),i.value=t)},{immediate:!0}),j(()=>n.max,e=>{let t=Mx(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=W(()=>Xm(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return kx({modelValue:i,max:a,progressState:o}),(e,t)=>(I(),R(k(X),{"as-child":e.asChild,as:e.as,"aria-valuemax":k(a),"aria-valuemin":0,"aria-valuenow":Ax(k(i))?k(i):void 0,"aria-valuetext":e.getValueText?.(k(i),k(a)),"aria-label":e.getValueLabel(k(i),k(a)),role:`progressbar`,"data-state":o.value,"data-value":k(i)??void 0,"data-max":k(a)},{default:A(()=>[P(e.$slots,`default`,{modelValue:k(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Px=M({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Ox();return Y(),(e,r)=>(I(),R(k(X),U(t,{"data-state":k(n).progressState.value,"data-value":k(n).modelValue?.value??void 0,"data-max":k(n).max.value}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Fx=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Ix=[` `,`Enter`];function Lx(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Rx(e,t,n)):Rx(e,t,n)}function Rx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:Gm(e,t)}function zx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Bx=[`value`],[Vx,Hx]=qm(`SelectRoot`),Ux=M({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=Dn(n),c=Eh(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=Eh(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=O(),d=O(),f=O({x:0,y:0}),p=W(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Xm(c.value));P_({isProvider:!0});let m=Hh(s),h=qh(u),g=O(new Set),_=W(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>Rx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>Lx(e,t.value,n.by))}return Hx({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(I(),R(k(q_),null,{default:A(()=>[P(e.$slots,`default`,{modelValue:k(c),open:k(l)}),k(h)&&e.name?(I(),R(Wx,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:k(o),required:k(i),name:e.name,autocomplete:e.autocomplete,disabled:k(a),value:k(c)},{default:A(()=>[k(Xm)(k(c))?(I(),L(`option`,{key:0,value:e.nullableValue},null,8,Bx)):H(`v-if`,!0),(I(!0),L(F,null,N(Array.from(g.value),e=>(I(),L(`option`,U({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):H(`v-if`,!0)]),_:3}))}}),Wx=M({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=O(),r=Vx();j(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:lT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>lT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
|
||||
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=dT(c),u=e+1<n.length?dT(n[e+1]):null;if(l&&u&&fT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=dT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>lT(e)),rows:r.map(e=>e.map(e=>lT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:lT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:lT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
|
||||
`)}),t}function dT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function fT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var pT={class:`[overflow-wrap:anywhere]`},mT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},hT={class:`font-mono text-[0.85em]`},gT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},_T={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},vT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},yT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},bT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},xT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},ST={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},CT={key:8,class:`mb-2.5 last:mb-0`},wT=M({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=W(()=>uT(t.text));return(e,t)=>(I(),L(`div`,pT,[(I(!0),L(F,null,N(n.value,(e,t)=>(I(),L(F,{key:t},[e.kind===`pre`?(I(),L(`pre`,mT,[z(`code`,hT,D(e.code),1)])):e.kind===`table`?(I(),L(`table`,gT,[z(`thead`,null,[z(`tr`,null,[(I(!0),L(F,null,N(e.head,(e,t)=>(I(),L(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[B(sT,{inline:e},null,8,[`inline`])]))),128))])]),z(`tbody`,null,[(I(!0),L(F,null,N(e.rows,(e,t)=>(I(),L(`tr`,{key:t},[(I(!0),L(F,null,N(e,(e,t)=>(I(),L(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[B(sT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(I(),L(`blockquote`,_T,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(I(),L(`h1`,vT,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(I(),L(`h2`,yT,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(I(),L(`h3`,bT,[B(sT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(I(),L(`ul`,xT,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(sT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(I(),L(`ol`,ST,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(sT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(I(),L(`p`,CT,[B(sT,{inline:e.inline},null,8,[`inline`])])):H(``,!0)],64))),128))]))}}),TT={class:`truncate`},ET=M({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return I(),R(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:A(()=>[B(k(bd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),z(`span`,TT,D(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),DT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},OT={class:`font-semibold text-foreground`},kT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},AT=M({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=W(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=W(()=>t.tool.parameters||t.tool.Parameters||``),i=W(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=W(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(I(),R(ET,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(I(),L(`div`,DT,[B(k($d),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),z(`span`,OT,D(n.value),1),r.value?(I(),L(`code`,kT,D(r.value),1)):H(``,!0),z(`span`,{class:E(k(q)(`text-fg-muted`,i.value&&`text-danger`))},D(a.value),3)]))}}),jT={key:0,class:`mb-2 grid gap-0.5 text-xs`},MT={key:2,class:`whitespace-pre-wrap`},NT=M({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(I(),L(`div`,{class:E([`flex`,e.assistant?`justify-start`:`justify-end`])},[z(`div`,{class:E(k(q)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(I(),L(`div`,jT,[(I(!0),L(F,null,N(e.tools,(t,n)=>(I(),R(AT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):H(``,!0),e.assistant?(I(),R(wT,{key:1,text:e.text},null,8,[`text`])):(I(),L(`div`,MT,D(e.text),1)),P(t.$slots,`default`)],2)],2))}}),PT={class:`w-full self-center justify-self-center py-6 text-center`},FT={class:`grid gap-2`},IT=[`onClick`],LT=M({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(I(),L(`div`,PT,[t[0]||=z(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
|
||||
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>oA?`${n.slice(0,oA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var cA=[`title`],lA=M({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=W(()=>Pk(n.event)),a=W(()=>sA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=W(()=>n.event.at?TO(n.event.at):`—`);return(e,t)=>(I(),R(k(iA),{class:E(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[V(D(n.event.kind||n.event.type||`event`),1)]),_:1}),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(i.value>0?`#${i.value}`:`—`),1)]),_:1}),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},D(a.value.text),9,cA)]),_:1}),B(k(Q),null,{default:A(()=>[V(D(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function uA(e,t){return`${e}:${t??0}`}function dA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=uA(sA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var fA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},pA={class:`max-h-[28rem] overflow-y-auto`},mA=[`aria-expanded`,`aria-label`,`onClick`],hA=[`title`],gA=M({__name:`LiveActivityCard`,setup(e){let t=oE(),{activity:n,streamKind:r,streamState:i}=od(sk()),a=rn(new Set),o=W(()=>dA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return sA(e.representative)}function u(e){return e.representative.at?TO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(I(),R(k(_O),null,{default:A(()=>[B(k(SO),null,{default:A(()=>[B(k(CO),null,{default:A(()=>[...t[0]||=[V(`Live activity`,-1)]]),_:1}),B(k(vO),null,{default:A(()=>[B(k(rO),{variant:k(r)},{default:A(()=>[V(D(k(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),B(k(yO),null,{default:A(()=>[z(`div`,fA,[z(`div`,pA,[B(k(nA),null,{default:A(()=>[B(k(aA),{class:`sticky top-0 z-10 bg-card`},{default:A(()=>[B(k(iA),null,{default:A(()=>[B(k($),null,{default:A(()=>[...t[1]||=[V(`Event`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[2]||=[V(`Task`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[3]||=[V(`Detail`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[4]||=[V(`When`,-1)]]),_:1})]),_:1})]),_:1}),B(k(rA),null,{default:A(()=>[k(n).length?H(``,!0):(I(),R(k(iA),{key:0},{default:A(()=>[B(k(Q),{colspan:`4`},{default:A(()=>[B(k(YD),null,{default:A(()=>[B(k(QD),null,{default:A(()=>[B(k(tO),null,{default:A(()=>[...t[5]||=[V(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),k(n).length?(I(!0),L(F,{key:1},N(o.value,e=>(I(),L(F,{key:e.key},[e.count===1?(I(),R(lA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(I(),L(F,{key:1},[B(k(iA),{class:E(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[z(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(I(),R(k(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(I(),R(k(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),V(` `+D(e.label)+` `,1),B(k(rO),{variant:`idle`},{default:A(()=>[V(`×`+D(e.count),1)]),_:2},1024)],8,mA)]),_:2},1024),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},D(l(e).text),9,hA)]),_:2},1024),B(k(Q),null,{default:A(()=>[V(D(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(I(!0),L(F,{key:0},N(e.events,(t,n)=>(I(),R(lA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):H(``,!0)],64))],64))),128)):H(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),_A=M({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=aC(t,`class`);return(e,r)=>(I(),R(k(Nx),U({"data-slot":`progress`},k(n),{class:k(q)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:A(()=>[B(k(Px),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine truncated
|
||||
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function Bj(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function Vj(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function Hj(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function Uj(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}function Wj(e,t){return t?e.filter(e=>e.event_type_id===t):[]}var Gj={pending_approval:`pending approval`,armed:`armed`},Kj={pending_approval:`warn`,armed:`ok`};function qj(e){return e?Gj[e]??e:`unknown`}function Jj(e){return Kj[e??``]??`idle`}function Yj(){return{id:null,name:``,eventTypeId:``,mappingId:``,filter:``,workflow:``,owner:``,repo:``}}function Xj(e,t){let n=t.find(t=>t.id===e.mapping_id);return{id:e.id,name:e.name,eventTypeId:n?.event_type_id||``,mappingId:e.mapping_id||``,filter:e.filter||``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``}}function Zj(e,t){let n=t.find(t=>t.id===e.eventTypeId);return{name:e.name,matcher:{source:n?.source||``},mapping_id:e.mappingId,filter:e.filter.trim(),workflow:e.workflow,owner:e.owner,repo:e.repo}}function Qj(e){return e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`}function $j(e,t){return t.find(t=>t.id===e.mapping_id)?.event_type_id}var eM={class:`grid grid-cols-2 items-start gap-3`},tM=M({__name:`BindingEditor`,props:Va({binding:{},mappings:{},eventTypes:{},workflows:{},saving:{type:Boolean},error:{}},{open:{type:Boolean,required:!0},openModifiers:{}}),emits:Va([`save`],[`update:open`]),setup(e,{emit:t}){let n=e,r=lo(e,`open`),i=t,a=O(Yj());j(r,e=>{e&&(a.value=n.binding?Xj(n.binding,n.mappings):Yj())},{immediate:!0});let o=W(()=>Wj(n.mappings,a.value.eventTypeId));j(()=>a.value.eventTypeId,()=>{o.value.some(e=>e.id===a.value.mappingId)||(a.value.mappingId=``)});let s=W(()=>n.binding?`Edit binding`:`New binding`);return(e,t)=>(I(),R(k(Mj),{open:r.value,"onUpdate:open":t[9]||=e=>r.value=e},{default:A(()=>[B(k(Pj),{class:`max-h-[85vh] overflow-y-auto sm:max-w-lg`},{default:A(()=>[B(k(Lj),null,{default:A(()=>[B(k(Rj),null,{default:A(()=>[V(D(s.value),1)]),_:1}),B(k(Fj),null,{default:A(()=>[...t[10]||=[V(` A binding is not armed until it is approved, and editing one drops it back to pending approval. `,-1)]]),_:1})]),_:1}),z(`form`,{onSubmit:t[8]||=uu(e=>i(`save`,a.value),[`prevent`])},[B(k(IC),null,{default:A(()=>[B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-name`},{default:A(()=>[...t[11]||=[V(`Name`,-1)]]),_:1}),B(k(LO),{id:`binding-name`,modelValue:a.value.name,"onUpdate:modelValue":t[0]||=e=>a.value.name=e},null,8,[`modelValue`])]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-event-type`},{default:A(()=>[...t[12]||=[V(`Event type`,-1)]]),_:1}),B(k(JS),{modelValue:a.value.eventTypeId,"onUpdate:modelValue":t[1]||=e=>a.value.eventTypeId=e},{default:A(()=>[B(k(CC),{id:`binding-event-type`,class:`w-full`},{default:A(()=>[B(k(wC),{placeholder:`Pick an event type`})]),_:1}),B(k(_C),null,{default:A(()=>[B(k(vC),null,{default:A(()=>[(I(!0),L(F,null,N(n.eventTypes,e=>(I(),R(k(bC),{key:e.id,value:e.id},{default:A(()=>[V(D(k(Vj)(e.id,n.eventTypes)),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`modelValue`])]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-mapping`},{default:A(()=>[...t[13]||=[V(`Field mapping`,-1)]]),_:1}),B(k(JS),{modelValue:a.value.mappingId,"onUpdate:modelValue":t[2]||=e=>a.value.mappingId=e,disabled:!o.value.length},{default:A(()=>[B(k(CC),{id:`binding-mapping`,class:`w-full`},{default:A(()=>[B(k(wC),{placeholder:a.value.eventTypeId&&!o.value.length?`No mappings for this event type`:`Pick a mapping`},null,8,[`placeholder`])]),_:1}),B(k(_C),null,{default:A(()=>[B(k(vC),null,{default:A(()=>[(I(!0),L(F,null,N(o.value,e=>(I(),R(k(bC),{key:e.id,value:String(e.id)},{default:A(()=>[V(D(e.name),1)]),_:2},1032,[`value`]))),128))]),_:1})]),_:1})]),_:1},8,[`modelValue`,`disabled`])]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-filter`},{default:A(()=>[...t[14]||=[V(`Filter`,-1)]]),_:1}),B(k(LO),{id:`binding-filter`,modelValue:a.value.filter,"onUpdate:modelValue":t[3]||=e=>a.value.filter=e,class:`font-mono text-xs`,placeholder:`severity in ["high", "critical"]`},null,8,[`modelValue`]),B(k(FC),null,{default:A(()=>[...t[15]||=[V(`Optional CEL over the mapping's parameters.`,-1)]]),_:1})]),_:1}),B(k(PC),null,{default:A(()=>[B(k(RC),{for:`binding-workflow`},{default:A(()=>[...t[16]||=[V(`Workflow`,-1)]]),_:1}),B(k(JS),{modelValue:a.va
Line truncated
|
||||
@@ -1,5 +1,4 @@
|
||||
<script setup lang="ts">
|
||||
import { Check, Copy, RefreshCw } from "@lucide/vue";
|
||||
import { computed, ref, watch } from "vue";
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
@@ -7,14 +6,13 @@ import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";
|
||||
import { eventTypeLabel, type EventType } from "@/captures/event-types";
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import {
|
||||
draftFromBinding,
|
||||
emptyDraft,
|
||||
generateSecret,
|
||||
mappingsForEventType,
|
||||
type Binding,
|
||||
type BindingDraft,
|
||||
type MappingOption,
|
||||
@@ -22,15 +20,16 @@ import {
|
||||
} from "./binding-draft";
|
||||
|
||||
/**
|
||||
* The binding editor: name, the matcher source senders POST to, the field
|
||||
* mapping, the workflow, an optional repo pin, and the shared secret their
|
||||
* signature is checked against.
|
||||
* The binding editor: name, the event type it applies to, one of that type's
|
||||
* mappings, an optional filter over the mapping's parameters, the workflow and
|
||||
* an optional repo pin. Signing is the source's.
|
||||
*/
|
||||
|
||||
const props = defineProps<{
|
||||
/** null is a new binding; a binding is an edit. */
|
||||
binding: Binding | null;
|
||||
mappings: MappingOption[];
|
||||
eventTypes: EventType[];
|
||||
workflows: WorkflowOption[];
|
||||
saving: boolean;
|
||||
error: string | null;
|
||||
@@ -45,23 +44,28 @@ const draft = ref<BindingDraft>(emptyDraft());
|
||||
watch(
|
||||
open,
|
||||
(isOpen) => {
|
||||
if (isOpen) draft.value = props.binding ? draftFromBinding(props.binding) : emptyDraft();
|
||||
if (isOpen) draft.value = props.binding ? draftFromBinding(props.binding, props.mappings) : emptyDraft();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const typeMappings = computed(() => mappingsForEventType(props.mappings, draft.value.eventTypeId));
|
||||
|
||||
// A mapping belongs to one event type, so changing the type clears a mapping
|
||||
// that no longer fits it.
|
||||
watch(
|
||||
() => draft.value.eventTypeId,
|
||||
() => {
|
||||
if (!typeMappings.value.some((m) => m.id === draft.value.mappingId)) draft.value.mappingId = "";
|
||||
},
|
||||
);
|
||||
|
||||
const title = computed(() => (props.binding ? "Edit binding" : "New binding"));
|
||||
const copied = ref(false);
|
||||
async function copySecret(): Promise<void> {
|
||||
await navigator.clipboard.writeText(draft.value.secret);
|
||||
copied.value = true;
|
||||
setTimeout(() => (copied.value = false), 1500);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<!-- Seven fields make this taller than a short window; the dialog itself
|
||||
<!-- Six fields make this taller than a short window; the dialog itself
|
||||
scrolls rather than clipping its own Save button. -->
|
||||
<DialogContent class="max-h-[85vh] overflow-y-auto sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
@@ -79,20 +83,30 @@ async function copySecret(): Promise<void> {
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel for="binding-source">Source</FieldLabel>
|
||||
<Input id="binding-source" v-model="draft.source" />
|
||||
<FieldDescription>The path segment senders POST to, for example "sentry".</FieldDescription>
|
||||
<FieldLabel for="binding-event-type">Event type</FieldLabel>
|
||||
<Select v-model="draft.eventTypeId">
|
||||
<SelectTrigger id="binding-event-type" class="w-full">
|
||||
<SelectValue placeholder="Pick an event type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem v-for="type in props.eventTypes" :key="type.id" :value="type.id">
|
||||
{{ eventTypeLabel(type.id, props.eventTypes) }}
|
||||
</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel for="binding-mapping">Field mapping</FieldLabel>
|
||||
<Select v-model="draft.mappingId">
|
||||
<Select v-model="draft.mappingId" :disabled="!typeMappings.length">
|
||||
<SelectTrigger id="binding-mapping" class="w-full">
|
||||
<SelectValue placeholder="Pick a saved mapping" />
|
||||
<SelectValue :placeholder="draft.eventTypeId && !typeMappings.length ? 'No mappings for this event type' : 'Pick a mapping'" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem v-for="mapping in props.mappings" :key="mapping.id" :value="String(mapping.id)">
|
||||
<SelectItem v-for="mapping in typeMappings" :key="mapping.id" :value="String(mapping.id)">
|
||||
{{ mapping.name }}
|
||||
</SelectItem>
|
||||
</SelectGroup>
|
||||
@@ -100,6 +114,12 @@ async function copySecret(): Promise<void> {
|
||||
</Select>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel for="binding-filter">Filter</FieldLabel>
|
||||
<Input id="binding-filter" v-model="draft.filter" class="font-mono text-xs" placeholder='severity in ["high", "critical"]' />
|
||||
<FieldDescription>Optional CEL over the mapping's parameters.</FieldDescription>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel for="binding-workflow">Workflow</FieldLabel>
|
||||
<Select v-model="draft.workflow">
|
||||
@@ -132,38 +152,6 @@ async function copySecret(): Promise<void> {
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel for="binding-secret">Signing secret</FieldLabel>
|
||||
<InputGroup v-if="draft.secret">
|
||||
<InputGroupInput id="binding-secret" :model-value="draft.secret" class="font-mono text-xs" readonly />
|
||||
<InputGroupAddon align="inline-end">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<InputGroupButton size="icon-xs" aria-label="Copy secret" @click="copySecret">
|
||||
<Check v-if="copied" />
|
||||
<Copy v-else />
|
||||
</InputGroupButton>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Copy secret</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<InputGroupButton size="icon-xs" aria-label="Regenerate secret" @click="draft.secret = generateSecret()">
|
||||
<RefreshCw />
|
||||
</InputGroupButton>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Regenerate</TooltipContent>
|
||||
</Tooltip>
|
||||
</InputGroupAddon>
|
||||
</InputGroup>
|
||||
<div v-else class="flex h-9 items-center justify-between rounded-md border px-3 text-sm">
|
||||
<span class="text-fg-muted">Stored · HMAC-SHA256</span>
|
||||
<Button type="button" variant="ghost" size="sm" @click="draft.secret = generateSecret()">
|
||||
<RefreshCw data-icon="inline-start" />
|
||||
Replace
|
||||
</Button>
|
||||
</div>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
|
||||
<!-- Beside the buttons, not at the top: the dialog scrolls, and Save is
|
||||
|
||||
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user