feat(events,drafts): give sources an immutable id and a scope (#2127, #2027)

A source is keyed by a uuid, owned by the organisation or one person, and
labelled within that scope. The webhook path is a separate unique column, so
renaming either leaves stored events, event types, triggers, groups, mappings
and drafts alone. Delivery policies, sealed secrets and group keys use the id.
This commit is contained in:
sam committed 2026-11-24 02:43:51 +11:00
1 parent 4a9f30ef04
commit 30aa351eb6
54 files changed
+1444 -682

No files matched your search

+249 -101
View File
@@ -997,12 +997,55 @@ components:
rule:
$ref: "#/components/schemas/EventtypeRule"
description: The conditions that identify the type; inferred from the example when absent
source:
source_id:
format: uuid
type: string
required:
- source
- source_id
- name
type: object
CreateSourceInputBody:
additionalProperties: false
properties:
connector:
description: The connector that parses this source's events
type: string
hmac_header:
description: The header that carries the signature (hmac only)
type: string
hmac_prefix:
description: Text before the hex digest in the signature header, such as sha256= (hmac only)
examples:
- sha256=
type: string
hmac_secret:
description: "The shared signing secret (hmac only). Write-only: it is sealed and never returned. When none is stored or sent, one is generated and returned once"
type: string
label:
description: The name people see, unique among the sources of the same owner
maxLength: 100
minLength: 1
type: string
scope:
description: "Who owns the source: the organisation (default) or the caller, who alone can see and use it"
enum:
- org
- person
type: string
verification:
description: "How deliveries are verified: a bearer token, an HMAC-SHA256 signature of the body, or no verification"
enum:
- token
- hmac
- none
type: string
webhook_path:
description: Lowercase letters, digits and hyphens; the webhook URL ends in it. Defaults to the label
type: string
required:
- label
- connector
type: object
CreateTokenInputBody:
additionalProperties: false
properties:
@@ -1123,8 +1166,10 @@ components:
filter: {}
source:
type: string
source_id:
type: string
required:
- source
- source_id
- event_type
- filter
type: object
@@ -1265,6 +1310,9 @@ components:
remote_addr:
type: string
source:
description: The source's label
type: string
source_id:
type: string
verification:
enum:
@@ -1276,7 +1324,6 @@ components:
required:
- id
- received_at
- source
- headers
- body
- verification
@@ -1348,9 +1395,13 @@ components:
type: string
type: object
source:
description: The source's label
type: string
source_id:
type: string
required:
- id
- source_id
- source
- name
- rule
@@ -1399,13 +1450,14 @@ components:
type: string
source:
type: string
source_id:
type: string
type:
type: string
verification:
type: string
required:
- id
- source
- type
- fields
- received_at
@@ -1460,7 +1512,9 @@ components:
- "null"
name:
type: string
source_hint:
source_id:
description: The source the mapping was made for, a hint only
format: uuid
type: string
required:
- name
@@ -1491,7 +1545,8 @@ components:
type: integer
name:
type: string
source_hint:
source_id:
description: The source the mapping was made for, a hint only
type: string
updated_at:
format: date-time
@@ -1499,7 +1554,6 @@ components:
required:
- id
- name
- source_hint
- event_type_id
- fields
- match_count
@@ -1529,10 +1583,14 @@ components:
type: string
filter: {}
source:
description: The source's label
type: string
source_id:
type: string
workflow:
type: string
required:
- source_id
- source
- event_type
- filter
@@ -1549,11 +1607,11 @@ components:
EventsSourceCreated:
additionalProperties: false
properties:
id:
type: string
secret:
description: A signing secret generated for an HMAC source, returned once
type: string
source:
type: string
token:
description: Returned once for a token source; only its hash is stored
type: string
@@ -1561,9 +1619,36 @@ components:
description: Where the sender posts its events
type: string
required:
- source
- id
- url
type: object
EventsSourceSettings:
additionalProperties: false
properties:
connector:
description: The connector that parses this source's events
type: string
hmac_header:
description: The header that carries the signature (hmac only)
type: string
hmac_prefix:
description: Text before the hex digest in the signature header, such as sha256= (hmac only)
examples:
- sha256=
type: string
hmac_secret:
description: "The shared signing secret (hmac only). Write-only: it is sealed and never returned. When none is stored or sent, one is generated and returned once"
type: string
verification:
description: "How deliveries are verified: a bearer token, an HMAC-SHA256 signature of the body, or no verification"
enum:
- token
- hmac
- none
type: string
required:
- connector
type: object
EventsSourceView:
additionalProperties: false
properties:
@@ -1573,21 +1658,26 @@ components:
type: string
delivery_header:
type: string
display_name:
type: string
hmac_header:
type: string
hmac_prefix:
type: string
hmac_secret_set:
type: boolean
id:
type: string
key_fields:
items:
type: string
type:
- array
- "null"
name:
label:
type: string
scope:
enum:
- org
- person
type: string
secret:
type: string
@@ -1602,8 +1692,13 @@ components:
type: boolean
verification:
type: string
webhook_path:
type: string
required:
- name
- id
- scope
- label
- webhook_path
- connector
- key_fields
- token_set
@@ -1660,6 +1755,8 @@ components:
type: string
source:
type: string
source_id:
type: string
status:
enum:
- pending_approval
@@ -1672,7 +1769,6 @@ components:
type: string
required:
- name
- source
- event_type
- filter
- workflow
@@ -1724,10 +1820,10 @@ components:
additionalProperties:
type: string
type: object
source:
source_id:
type: string
required:
- source
- source_id
- key
- schema
- headers
@@ -3203,33 +3299,6 @@ components:
- array
- "null"
type: object
PutSourceInputBody:
additionalProperties: false
properties:
connector:
description: The connector that parses this source's events
type: string
hmac_header:
description: The header that carries the signature (hmac only)
type: string
hmac_prefix:
description: Text before the hex digest in the signature header, such as sha256= (hmac only)
examples:
- sha256=
type: string
hmac_secret:
description: "The shared signing secret (hmac only). Write-only: it is sealed and never returned. When none is stored or sent, one is generated and returned once"
type: string
verification:
description: "How deliveries are verified: a bearer token, an HMAC-SHA256 signature of the body, or no verification"
enum:
- token
- hmac
- none
type: string
required:
- connector
type: object
PutTriggerInputBody:
additionalProperties: false
properties:
@@ -3259,8 +3328,9 @@ components:
pending:
description: Save the trigger waiting for approval; it fires once a person approves it
type: boolean
source:
description: The source whose events fire it; fixed when every is set
source_id:
description: The source whose events fire it; none when every is set
format: uuid
type: string
workflow:
description: The workflow each match runs
@@ -3527,12 +3597,15 @@ components:
type: string
source:
type: string
source_id:
type: string
trigger:
type: string
type:
type: string
required:
- event_id
- source_id
- source
- type
- fields
@@ -4045,14 +4118,16 @@ components:
required:
- signed
type: object
SourceNameInputBody:
SourceLabelInputBody:
additionalProperties: false
properties:
name:
label:
description: The name people see, unique among the sources of the same owner
maxLength: 100
minLength: 1
type: string
required:
- name
- label
type: object
SystemAdminToken:
additionalProperties: false
@@ -4229,6 +4304,15 @@ components:
- completion_tokens
- total_tokens
type: object
WebhookPathInputBody:
additionalProperties: false
properties:
path:
description: Lowercase letters, digits and hyphens; the webhook URL ends in it. Senders must post to the new address.
type: string
required:
- path
type: object
securitySchemes:
bearer:
description: A personal API token, or the bootstrap admin token
@@ -5928,8 +6012,9 @@ paths:
type: integer
- explode: false
in: query
name: source
name: source_id
schema:
format: uuid
type: string
- explode: false
in: query
@@ -8178,42 +8263,13 @@ paths:
summary: List sources
tags:
- Events
/api/sources/{name}:
delete:
operationId: delete-source
parameters:
- in: path
name: name
required: true
schema:
type: string
responses:
"204":
description: No Content
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Delete a source
tags:
- Events
put:
operationId: put-source
parameters:
- description: Lowercase letters, digits and hyphens; the webhook URL ends in it
in: path
name: name
required: true
schema:
description: Lowercase letters, digits and hyphens; the webhook URL ends in it
type: string
post:
operationId: create-source
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/PutSourceInputBody"
$ref: "#/components/schemas/CreateSourceInputBody"
required: true
responses:
"200":
@@ -8228,17 +8284,71 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Add or update a source, its verification scheme and its token
summary: Add a source, owned by the organisation or by the caller
tags:
- Events
/api/sources/{name}/approve-unsigned:
/api/sources/{id}:
delete:
operationId: delete-source
parameters:
- in: path
name: id
required: true
schema:
format: uuid
type: string
responses:
"204":
description: No Content
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Delete a source
tags:
- Events
put:
operationId: update-source
parameters:
- in: path
name: id
required: true
schema:
format: uuid
type: string
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/EventsSourceSettings"
required: true
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/EventsSourceCreated"
description: OK
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Change a source's connector, verification scheme and token
tags:
- Events
/api/sources/{id}/approve-unsigned:
post:
operationId: approve-source-unsigned
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
responses:
"200":
@@ -8256,14 +8366,15 @@ paths:
summary: Accept deliveries that carry no signature
tags:
- Events
/api/sources/{name}/capture:
/api/sources/{id}/capture:
put:
operationId: set-source-capture
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
requestBody:
content:
@@ -8287,14 +8398,15 @@ paths:
summary: Keep or stop keeping the headers and payloads a source receives
tags:
- Events
/api/sources/{name}/delivery-header:
/api/sources/{id}/delivery-header:
put:
operationId: set-source-delivery-header
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
requestBody:
content:
@@ -8318,14 +8430,15 @@ paths:
summary: Name the header a sender repeats when it retries a delivery
tags:
- Events
/api/sources/{name}/key-fields:
/api/sources/{id}/key-fields:
put:
operationId: put-source-key-fields
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
requestBody:
content:
@@ -8349,20 +8462,21 @@ paths:
summary: Set the fields a source's events are grouped by
tags:
- Events
/api/sources/{name}/name:
/api/sources/{id}/label:
put:
operationId: set-source-name
operationId: set-source-label
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/SourceNameInputBody"
$ref: "#/components/schemas/SourceLabelInputBody"
required: true
responses:
"200":
@@ -8377,17 +8491,18 @@ paths:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Label a source
summary: Rename a source
tags:
- Events
/api/sources/{name}/secret:
/api/sources/{id}/secret:
post:
operationId: rotate-source-secret
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
responses:
"200":
@@ -8405,14 +8520,15 @@ paths:
summary: Replace a signed source's secret and return it once
tags:
- Events
/api/sources/{name}/signing:
/api/sources/{id}/signing:
post:
operationId: set-source-signing
parameters:
- in: path
name: name
name: id
required: true
schema:
format: uuid
type: string
requestBody:
content:
@@ -8436,6 +8552,38 @@ paths:
summary: Require an HMAC signature, or ask to take unsigned deliveries
tags:
- Events
/api/sources/{id}/webhook-path:
put:
operationId: set-source-webhook-path
parameters:
- in: path
name: id
required: true
schema:
format: uuid
type: string
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/WebhookPathInputBody"
required: true
responses:
"200":
content:
application/json:
schema:
$ref: "#/components/schemas/EventsSourceView"
description: OK
default:
content:
application/problem+json:
schema:
$ref: "#/components/schemas/ErrorModel"
description: Error
summary: Move the address a source receives deliveries at
tags:
- Events
/api/stream:
get:
operationId: stream-dashboard
@@ -1,9 +1,18 @@
-- +goose Up
CREATE SCHEMA events;
-- A source is owned by a scope: the organisation, or one person acting in it.
-- The label is the editable name people see, unique within its scope. The
-- webhook path is the public address deliveries post to, unique across the
-- instance, and changing it leaves every stored row alone because they refer to
-- the id.
CREATE TABLE events.sources (
id uuid PRIMARY KEY,
scope text NOT NULL CHECK (scope IN ('org', 'person')),
org_id text NOT NULL,
name text NOT NULL,
person_id text,
label text NOT NULL CHECK (label <> ''),
webhook_path text NOT NULL UNIQUE CHECK (webhook_path ~ '^[a-z][a-z0-9-]{0,62}$'),
connector text NOT NULL,
token_sha256 text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
@@ -14,12 +23,13 @@ CREATE TABLE events.sources (
hmac_header text NOT NULL DEFAULT '',
hmac_prefix text NOT NULL DEFAULT '',
hmac_secret_sealed bytea NOT NULL DEFAULT '\x'::bytea,
display_name text NOT NULL DEFAULT '',
delivery_header text NOT NULL DEFAULT '',
unsigned_approved boolean NOT NULL DEFAULT false,
capture boolean NOT NULL DEFAULT true,
PRIMARY KEY (org_id, name)
CHECK ((scope = 'person') = (person_id IS NOT NULL))
);
CREATE UNIQUE INDEX sources_org_label ON events.sources (org_id, label) WHERE scope = 'org';
CREATE UNIQUE INDEX sources_person_label ON events.sources (person_id, label) WHERE scope = 'person';
-- An event type identifies one kind of event from a source by its headers and
-- payload paths. schema lists the JSON paths of the example event it was
@@ -27,19 +37,19 @@ CREATE TABLE events.sources (
CREATE TABLE events.event_types (
id uuid PRIMARY KEY,
org_id text NOT NULL,
source text NOT NULL,
source_id uuid NOT NULL REFERENCES events.sources (id),
name text NOT NULL,
rule jsonb NOT NULL,
schema jsonb NOT NULL DEFAULT '{}',
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (org_id, source, name)
UNIQUE (org_id, source_id, name)
);
CREATE TABLE events.events (
id uuid PRIMARY KEY,
org_id text NOT NULL,
source text NOT NULL,
source_id uuid REFERENCES events.sources (id) ON DELETE SET NULL,
type text NOT NULL,
source_event_id text NOT NULL,
link_key text,
@@ -58,10 +68,14 @@ CREATE TABLE events.events (
headers jsonb,
remote_addr text NOT NULL DEFAULT '',
event_type_id uuid REFERENCES events.event_types (id) ON DELETE SET NULL,
UNIQUE (org_id, source, source_event_id)
UNIQUE (org_id, source_id, source_event_id)
);
-- A schedule tick has no source, and NULL ids never conflict in the unique
-- constraint above, so each slot is made unique here.
CREATE UNIQUE INDEX events_schedule_slot ON events.events (org_id, source_event_id)
WHERE source_id IS NULL AND type = 'schedule.tick';
CREATE INDEX events_undispatched ON events.events (received_at) WHERE (dispatched_at IS NULL);
CREATE INDEX events_link ON events.events (org_id, source, link_key, received_at) WHERE (link_key IS NOT NULL);
CREATE INDEX events_link ON events.events (org_id, source_id, link_key, received_at) WHERE (link_key IS NOT NULL);
-- A mapping lists the payload paths a workflow reads from events of one event
-- type.
@@ -69,7 +83,7 @@ CREATE TABLE events.mappings (
id uuid PRIMARY KEY,
org_id text NOT NULL,
name text NOT NULL,
source_hint text NOT NULL DEFAULT '',
source_id uuid REFERENCES events.sources (id) ON DELETE SET NULL,
event_type_id uuid NOT NULL REFERENCES events.event_types (id) ON DELETE RESTRICT,
fields jsonb NOT NULL,
match_count bigint NOT NULL DEFAULT 0,
@@ -81,7 +95,7 @@ CREATE TABLE events.mappings (
CREATE TABLE events.triggers (
org_id text NOT NULL,
name text NOT NULL,
source text NOT NULL,
source_id uuid REFERENCES events.sources (id),
event_type text NOT NULL,
filter jsonb NOT NULL DEFAULT '{}',
workflow text NOT NULL,
@@ -92,7 +106,8 @@ CREATE TABLE events.triggers (
approved boolean NOT NULL DEFAULT true,
event_type_id uuid REFERENCES events.event_types (id) ON DELETE RESTRICT,
mapping_id uuid REFERENCES events.mappings (id) ON DELETE RESTRICT,
PRIMARY KEY (org_id, name)
PRIMARY KEY (org_id, name),
CHECK ((source_id IS NULL) = (schedule_every_s IS NOT NULL))
);
CREATE TABLE events.dispatches (
@@ -112,7 +127,7 @@ CREATE TABLE events.groups (
id uuid PRIMARY KEY,
org_id text NOT NULL,
key text NOT NULL,
source text NOT NULL,
source_id uuid NOT NULL REFERENCES events.sources (id) ON DELETE CASCADE,
event_type text NOT NULL,
filter jsonb NOT NULL,
count bigint NOT NULL,
@@ -6,7 +6,7 @@ CREATE TABLE drafts.drafts (
org_id text NOT NULL,
group_id uuid NOT NULL,
name text NOT NULL,
source text NOT NULL,
source_id uuid NOT NULL,
event_type text NOT NULL,
filter jsonb NOT NULL,
document text NOT NULL,
+26 -7
View File
@@ -122,17 +122,23 @@ type View struct {
// Trigger is the trigger a draft proposes.
type Trigger struct {
Source string `json:"source"`
SourceID uuid.UUID `json:"source_id"`
// Source is the source's label, empty when the source no longer exists.
Source string `json:"source,omitzero"`
EventType string `json:"event_type"`
Filter jsontext.Value `json:"filter"`
}
func (m *Module) view(ctx context.Context, d store.Draft) (View, error) {
label, err := m.sourceLabel(ctx, d.GroupID)
if err != nil {
return View{}, err
}
v := View{
ID: d.ID, GroupID: d.GroupID, Name: d.Name,
Trigger: Trigger{Source: d.Source, EventType: d.EventType, Filter: d.Filter},
Trigger: Trigger{SourceID: d.SourceID, Source: label, EventType: d.EventType, Filter: d.Filter},
Workflow: d.Document, PolicyKind: d.PolicyKind, Policy: d.Policy,
Summary: summarize(d),
Summary: summarize(d, label),
}
if d.PublishedAt.Valid {
v.PublishedAt = &d.PublishedAt.Time
@@ -159,11 +165,24 @@ var (
policyKinds = map[string]string{judgement.KindHardRules: "hard rule", judgement.KindChangeRequest: "change request rule"}
)
func summarize(d store.Draft) string {
// sourceLabel returns the label of the source of a draft's group, or "" when
// the group went with its source.
func (m *Module) sourceLabel(ctx context.Context, groupID uuid.UUID) (string, error) {
g, found, err := m.groups.Group(ctx, groupID)
if err != nil {
return "", fmt.Errorf("read group: %w", err)
}
if !found {
return "", nil
}
return g.Source, nil
}
func summarize(d store.Draft, source string) string {
var filter map[string]string
_ = json.Unmarshal(d.Filter, &filter)
var b strings.Builder
fmt.Fprintf(&b, "When %s sends %s", d.Source, d.EventType)
fmt.Fprintf(&b, "When %s sends %s", source, d.EventType)
if len(filter) > 0 {
pairs := make([]string, 0, len(filter))
for k, v := range filter {
@@ -240,7 +259,7 @@ func (m *Module) create(ctx context.Context, in *idInput) (*httpapi.Reply[View],
return nil, m.fail(ctx, "encode filter", err)
}
d, err := m.store.Create(ctx, store.Draft{
ID: uuid.New(), OrgID: m.orgID, GroupID: g.ID, Name: defaultName(g), Source: g.Source, EventType: g.EventType,
ID: uuid.New(), OrgID: m.orgID, GroupID: g.ID, Name: defaultName(g), SourceID: g.SourceID, EventType: g.EventType,
Filter: filter, Document: runs.InvestigateDocument(), PolicyKind: judgement.KindHardRules,
})
if err != nil {
@@ -417,7 +436,7 @@ func (m *Module) publish(ctx context.Context, in *idInput) (*httpapi.Reply[View]
return nil, m.fail(ctx, "read the trigger filter", err)
}
if err := m.groups.SaveTrigger(ctx, events.TriggerSpec{
Name: d.Name, Source: d.Source, EventType: d.EventType, Filter: filter, Workflow: d.Name,
Name: d.Name, SourceID: d.SourceID, EventType: d.EventType, Filter: filter, Workflow: d.Name,
}); err != nil {
return nil, m.fail(ctx, "save the trigger", err)
}
+4 -4
View File
@@ -26,7 +26,7 @@ type Draft struct {
OrgID string `db:"org_id"`
GroupID uuid.UUID `db:"group_id"`
Name string `db:"name"`
Source string `db:"source"`
SourceID uuid.UUID `db:"source_id"`
EventType string `db:"event_type"`
Filter jsontext.Value `db:"filter"`
Document string `db:"document"`
@@ -42,7 +42,7 @@ type Draft struct {
UpdatedAt time.Time `db:"updated_at"`
}
const columns = `id, org_id, group_id, name, source, event_type, filter, document, policy_kind, policy,
const columns = `id, org_id, group_id, name, source_id, event_type, filter, document, policy_kind, policy,
dry_run_id, dry_event_id, installed_version, published_at, created_at, updated_at`
// Store is the drafts module's Postgres store.
@@ -56,10 +56,10 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} }
// Create inserts a draft or returns the existing draft for the group.
func (s *Store) Create(ctx context.Context, d Draft) (Draft, error) {
_, err := s.db.ExecContext(ctx, `
INSERT INTO drafts.drafts (id, org_id, group_id, name, source, event_type, filter, document, policy_kind, policy)
INSERT INTO drafts.drafts (id, org_id, group_id, name, source_id, event_type, filter, document, policy_kind, policy)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (org_id, group_id) DO NOTHING`,
d.ID, d.OrgID, d.GroupID, d.Name, d.Source, d.EventType, d.Filter, d.Document, d.PolicyKind, d.Policy)
d.ID, d.OrgID, d.GroupID, d.Name, d.SourceID, d.EventType, d.Filter, d.Document, d.PolicyKind, d.Policy)
if err != nil {
return Draft{}, fmt.Errorf("create draft: %w", err)
}
+6 -6
View File
@@ -71,10 +71,10 @@ func TestIntakeAppliesTheDeliveryPolicyBeforeStoring(t *testing.T) {
wantStored int
wantAsked []string
}{
{name: "an allowed delivery is stored", bearer: token, policy: governance.Allowed(), deliveries: 1, want: http.StatusAccepted, wantBody: `"stored":1`, wantStored: 1, wantAsked: []string{"org-sys hook 203.0.113.9"}},
{name: "a redelivered event id is counted, not stored again", bearer: token, policy: governance.Allowed(), deliveries: 2, want: http.StatusAccepted, wantBody: `"duplicates":1`, wantStored: 1, wantAsked: []string{"org-sys hook 203.0.113.9", "org-sys hook 203.0.113.9"}},
{name: "a valid token with a denying policy", bearer: token, policy: denied, deliveries: 1, want: http.StatusForbidden, wantAsked: []string{"org-sys hook 203.0.113.9"}},
{name: "a valid token while the chain is unavailable", bearer: token, policy: governance.Unavailable(), deliveries: 1, want: http.StatusServiceUnavailable, wantAsked: []string{"org-sys hook 203.0.113.9"}},
{name: "an allowed delivery is stored", bearer: token, policy: governance.Allowed(), deliveries: 1, want: http.StatusAccepted, wantBody: `"stored":1`, wantStored: 1, wantAsked: []string{"org-sys " + hookID.String() + " 203.0.113.9"}},
{name: "a redelivered event id is counted, not stored again", bearer: token, policy: governance.Allowed(), deliveries: 2, want: http.StatusAccepted, wantBody: `"duplicates":1`, wantStored: 1, wantAsked: []string{"org-sys " + hookID.String() + " 203.0.113.9", "org-sys " + hookID.String() + " 203.0.113.9"}},
{name: "a valid token with a denying policy", bearer: token, policy: denied, deliveries: 1, want: http.StatusForbidden, wantAsked: []string{"org-sys " + hookID.String() + " 203.0.113.9"}},
{name: "a valid token while the chain is unavailable", bearer: token, policy: governance.Unavailable(), deliveries: 1, want: http.StatusServiceUnavailable, wantAsked: []string{"org-sys " + hookID.String() + " 203.0.113.9"}},
{name: "a valid token with no policy wired", bearer: token, unwired: true, deliveries: 1, want: http.StatusServiceUnavailable},
{name: "a wrong token never reaches the policy", bearer: "other", policy: governance.Allowed(), deliveries: 1, want: http.StatusUnauthorized},
}
@@ -84,7 +84,7 @@ func TestIntakeAppliesTheDeliveryPolicyBeforeStoring(t *testing.T) {
inserter := &onceInserter{stored: map[string]bool{}}
m := &Module{
orgID: "default", log: slog.New(slog.DiscardHandler), inserter: inserter, deliveries: noEcho{},
reader: fakeSources{store.Source{OrgID: "default", Name: "hook", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}},
reader: fakeSources{store.Source{ID: hookID, OrgID: "default", WebhookPath: "hook", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}},
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil
},
@@ -95,7 +95,7 @@ func TestIntakeAppliesTheDeliveryPolicyBeforeStoring(t *testing.T) {
var rec *httptest.ResponseRecorder
for range tt.deliveries {
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(`{}`))
req.SetPathValue("source", "hook")
req.SetPathValue("path", "hook")
req.RemoteAddr = "203.0.113.9:4711"
req.Header.Set("Authorization", "Bearer "+tt.bearer)
rec = httptest.NewRecorder()
+248 -111
View File
@@ -8,7 +8,9 @@ import (
"errors"
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/danielgtaylor/huma/v2"
@@ -32,11 +34,15 @@ func (m *Module) Register(api huma.API) {
Summary: "List sources", Tags: tags,
}, m.sources)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
OperationID: "put-source", Method: http.MethodPut, Path: "/api/sources/{name}",
Summary: "Add or update a source, its verification scheme and its token", Tags: tags,
}, m.putSource)
OperationID: "create-source", Method: http.MethodPost, Path: "/api/sources",
Summary: "Add a source, owned by the organisation or by the caller", Tags: tags,
}, m.createSource)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
OperationID: "put-source-key-fields", Method: http.MethodPut, Path: "/api/sources/{name}/key-fields",
OperationID: "update-source", Method: http.MethodPut, Path: "/api/sources/{id}",
Summary: "Change a source's connector, verification scheme and token", Tags: tags,
}, m.updateSource)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
OperationID: "put-source-key-fields", Method: http.MethodPut, Path: "/api/sources/{id}/key-fields",
Summary: "Set the fields a source's events are grouped by", Tags: tags,
}, m.putKeyFields)
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindTrigger), huma.Operation{
@@ -61,72 +67,119 @@ func (m *Module) Register(api huma.API) {
}, m.event)
}
type putSourceInput struct {
Name string `path:"name" doc:"Lowercase letters, digits and hyphens; the webhook URL ends in it"`
// SourceSettings are what a source's connector and verification need.
type SourceSettings struct {
Connector string `json:"connector" doc:"The connector that parses this source's events"`
// A new source without a scheme uses a bearer token, so existing
// senders keep working.
Verification string `json:"verification,omitzero" enum:"token,hmac,none" doc:"How deliveries are verified: a bearer token, an HMAC-SHA256 signature of the body, or no verification"`
HMACHeader string `json:"hmac_header,omitzero" doc:"The header that carries the signature (hmac only)"`
HMACPrefix string `json:"hmac_prefix,omitzero" doc:"Text before the hex digest in the signature header, such as sha256= (hmac only)" example:"sha256="`
HMACSecret string `json:"hmac_secret,omitzero" doc:"The shared signing secret (hmac only). Write-only: it is sealed and never returned. When none is stored or sent, one is generated and returned once"`
}
type createSourceInput struct {
Body struct {
Connector string `json:"connector" doc:"The connector that parses this source's events"`
// A new source without a scheme uses a bearer token, so existing
// senders keep working.
Verification string `json:"verification,omitzero" enum:"token,hmac,none" doc:"How deliveries are verified: a bearer token, an HMAC-SHA256 signature of the body, or no verification"`
HMACHeader string `json:"hmac_header,omitzero" doc:"The header that carries the signature (hmac only)"`
HMACPrefix string `json:"hmac_prefix,omitzero" doc:"Text before the hex digest in the signature header, such as sha256= (hmac only)" example:"sha256="`
HMACSecret string `json:"hmac_secret,omitzero" doc:"The shared signing secret (hmac only). Write-only: it is sealed and never returned. When none is stored or sent, one is generated and returned once"`
Label string `json:"label" minLength:"1" maxLength:"100" doc:"The name people see, unique among the sources of the same owner"`
WebhookPath string `json:"webhook_path,omitzero" doc:"Lowercase letters, digits and hyphens; the webhook URL ends in it. Defaults to the label"`
Scope string `json:"scope,omitzero" enum:"org,person" doc:"Who owns the source: the organisation (default) or the caller, who alone can see and use it"`
SourceSettings
}
}
type sourceCreated struct {
Source string `json:"source"`
Token string `json:"token,omitzero" doc:"Returned once for a token source; only its hash is stored"`
Secret string `json:"secret,omitzero" doc:"A signing secret generated for an HMAC source, returned once"`
URL string `json:"url" doc:"Where the sender posts its events"`
ID uuid.UUID `json:"id"`
Token string `json:"token,omitzero" doc:"Returned once for a token source; only its hash is stored"`
Secret string `json:"secret,omitzero" doc:"A signing secret generated for an HMAC source, returned once"`
URL string `json:"url" doc:"Where the sender posts its events"`
}
// putSource creates or updates a source. A save that omits verification keeps
// the stored scheme and its credentials. A token is returned only when the
// token scheme is chosen explicitly or the source is new, and only its hash is
// stored. An HMAC secret is sealed and never returned; a blank secret keeps the
// sealed one.
func (m *Module) putSource(ctx context.Context, in *putSourceInput) (*httpapi.Reply[sourceCreated], error) {
if !validName.MatchString(in.Name) || !validName.MatchString(in.Body.Connector) {
return nil, huma.Error400BadRequest("a source needs a lowercase name and a connector")
var pathChars = regexp.MustCompile(`[^a-z0-9]+`)
// pathFor derives a webhook path from a label.
func pathFor(label string) string {
path := strings.Trim(pathChars.ReplaceAllString(strings.ToLower(label), "-"), "-")
if len(path) > 63 {
path = strings.Trim(path[:63], "-")
}
existing, err := m.store.Source(ctx, m.orgID, in.Name)
if err != nil && !errors.Is(err, store.ErrNotFound) {
return nil, huma.Error500InternalServerError("couldn't read the source", err)
return path
}
// createSource adds a source. It returns a token only for the token scheme,
// and only its hash is stored. An HMAC secret is sealed and never returned,
// except one generated here.
func (m *Module) createSource(ctx context.Context, in *createSourceInput) (*httpapi.Reply[sourceCreated], error) {
body := in.Body
label := strings.TrimSpace(body.Label)
path := body.WebhookPath
if path == "" {
path = pathFor(label)
}
var stored *store.Source
if err == nil {
stored = &existing
if label == "" || !validName.MatchString(path) || !validName.MatchString(body.Connector) {
return nil, huma.Error400BadRequest("a source needs a label, a webhook path of lowercase letters, digits and hyphens, and a connector")
}
src, issued, err := m.sourceToSave(in, stored)
base := store.Source{
ID: uuid.New(), Scope: store.ScopeOrg, OrgID: m.orgID, Label: label, WebhookPath: path,
}
if body.Scope == store.ScopePerson {
base.Scope, base.PersonID = store.ScopePerson, sql.NullString{String: caller(ctx), Valid: true}
}
src, issued, err := m.sourceToSave(body.SourceSettings, base, nil)
if err != nil {
return nil, err
}
if err := m.store.UpsertSource(ctx, src); err != nil {
return nil, huma.Error500InternalServerError("couldn't save the source", err)
if err := sourceWriteError(m.store.InsertSource(ctx, src)); err != nil {
return nil, err
}
return httpapi.OK(sourceCreated{Source: in.Name, Token: issued.token, Secret: issued.secret, URL: "/hooks/" + in.Name}), nil
return httpapi.OK(sourceCreated{ID: src.ID, Token: issued.token, Secret: issued.secret, URL: "/hooks/" + src.WebhookPath}), nil
}
type updateSourceInput struct {
ID string `path:"id" format:"uuid"`
Body SourceSettings
}
// updateSource changes a source's connector and verification. A save that omits
// verification keeps the stored scheme and its credentials. A token is returned
// only when the token scheme is chosen explicitly, and only its hash is stored.
// An HMAC secret is sealed and never returned; a blank secret keeps the sealed
// one.
func (m *Module) updateSource(ctx context.Context, in *updateSourceInput) (*httpapi.Reply[sourceCreated], error) {
stored, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
if !validName.MatchString(in.Body.Connector) {
return nil, huma.Error400BadRequest("a source needs a connector")
}
src, issued, err := m.sourceToSave(in.Body, stored, &stored)
if err != nil {
return nil, err
}
if err := sourceWriteError(m.store.UpdateSource(ctx, src)); err != nil {
return nil, err
}
return httpapi.OK(sourceCreated{ID: src.ID, Token: issued.token, Secret: issued.secret, URL: "/hooks/" + src.WebhookPath}), nil
}
// issued is a credential generated for a saved source, returned once.
type issued struct{ token, secret string }
// sourceToSave builds the row to store from the request and the stored source,
// if there is one. It returns the token or secret it generated, if any.
func (m *Module) sourceToSave(in *putSourceInput, stored *store.Source) (store.Source, issued, error) {
explicit := in.Body.Verification != ""
// sourceToSave builds the row to store from the request settings, the source's
// fixed attributes in base, and the stored source if there is one. It returns
// the token or secret it generated, if any.
func (m *Module) sourceToSave(set SourceSettings, base store.Source, stored *store.Source) (store.Source, issued, error) {
explicit := set.Verification != ""
// The secret column is NOT NULL, so a source without a secret carries an
// empty value: the driver writes a nil slice as NULL.
src := store.Source{
OrgID: m.orgID, Name: in.Name, Connector: in.Body.Connector,
Verification: in.Body.Verification, HMACSecretSealed: []byte{},
}
src := base
src.Connector, src.Verification, src.HMACSecretSealed = set.Connector, set.Verification, []byte{}
switch {
case !explicit && stored != nil:
// Omitting the scheme keeps the stored one with its token or secret, so
// a save cannot downgrade a source.
src = *stored
src.Connector = in.Body.Connector
src.Connector = set.Connector
case !explicit:
src.Verification = store.Token
}
@@ -147,7 +200,7 @@ func (m *Module) sourceToSave(in *putSourceInput, stored *store.Source) (store.S
var secret string
if explicit {
var err error
if secret, err = m.setHMAC(&src, in, stored); err != nil {
if secret, err = m.setHMAC(&src, set, stored); err != nil {
return src, issued{}, err
}
}
@@ -163,9 +216,9 @@ func (m *Module) sourceToSave(in *putSourceInput, stored *store.Source) (store.S
// setHMAC applies the requested HMAC settings. A blank secret keeps the sealed
// secret a source already has, and a source that has none gets a generated one,
// which is returned so it can be shown once.
func (m *Module) setHMAC(src *store.Source, in *putSourceInput, stored *store.Source) (generated string, err error) {
src.HMACHeader, src.HMACPrefix = in.Body.HMACHeader, in.Body.HMACPrefix
secret := in.Body.HMACSecret
func (m *Module) setHMAC(src *store.Source, set SourceSettings, stored *store.Source) (generated string, err error) {
src.HMACHeader, src.HMACPrefix = set.HMACHeader, set.HMACPrefix
secret := set.HMACSecret
switch {
case secret != "":
case stored != nil && len(stored.HMACSecretSealed) > 0:
@@ -177,7 +230,7 @@ func (m *Module) setHMAC(src *store.Source, in *putSourceInput, stored *store.So
}
generated = secret
}
sealed, err := m.sealer.Seal(secretLabel(m.orgID, in.Name), []byte(secret))
sealed, err := m.sealer.Seal(secretLabel(m.orgID, src.ID), []byte(secret))
if err != nil {
return "", huma.Error500InternalServerError("couldn't seal the secret", err)
}
@@ -188,7 +241,7 @@ func (m *Module) setHMAC(src *store.Source, in *putSourceInput, stored *store.So
type putTriggerInput struct {
Name string `path:"name" doc:"Lowercase letters, digits and hyphens"`
Body struct {
Source string `json:"source,omitzero" doc:"The source whose events fire it; fixed when every is set"`
SourceID string `json:"source_id,omitzero" format:"uuid" doc:"The source whose events fire it; none when every is set"`
EventType string `json:"event_type,omitzero" doc:"The event type that fires it; fixed when every is set"`
Filter map[string]string `json:"filter,omitzero" doc:"Event fields that must match exactly"`
Workflow string `json:"workflow" doc:"The workflow each match runs"`
@@ -206,24 +259,38 @@ type triggerSaved struct {
Trigger string `json:"trigger"`
}
// parseEvery reads a schedule interval; an empty one is no schedule.
func parseEvery(raw string) (sql.NullInt64, error) {
if raw == "" {
return sql.NullInt64{}, nil
}
d, err := time.ParseDuration(raw)
if err != nil || d < minInterval || d%time.Second != 0 {
return sql.NullInt64{}, huma.Error400BadRequest("every is a whole number of seconds of at least one minute, such as 1h")
}
return sql.NullInt64{Int64: int64(d / time.Second), Valid: true}, nil
}
func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.Reply[triggerSaved], error) {
req := in.Body
var every sql.NullInt64
if req.Every != "" {
d, err := time.ParseDuration(req.Every)
if err != nil || d < minInterval || d%time.Second != 0 {
return nil, huma.Error400BadRequest("every is a whole number of seconds of at least one minute, such as 1h")
}
every = sql.NullInt64{Int64: int64(d / time.Second), Valid: true}
req.Source, req.EventType = scheduleSource, scheduleType
every, err := parseEvery(req.Every)
if err != nil {
return nil, err
}
if every.Valid {
req.SourceID, req.EventType = "", scheduleType
// Every schedule's ticks share a source and type, so the filter keeps
// this trigger to its own.
req.Filter = map[string]string{"trigger": in.Name}
}
if !validName.MatchString(in.Name) || req.Source == "" || (req.EventType == "" && req.EventTypeID == "") || req.Workflow == "" {
if !validName.MatchString(in.Name) || (req.SourceID == "" && !every.Valid) || (req.EventType == "" && req.EventTypeID == "") || req.Workflow == "" {
return nil, huma.Error400BadRequest("a trigger needs a lowercase name, a workflow, and either a source and event type or an every interval")
}
typeID, mappingID, err := m.checkTargets(ctx, req.Source, req.EventType, req.Workflow, req.EventTypeID, req.MappingID)
sourceID, err := m.triggerSource(ctx, req.SourceID)
if err != nil {
return nil, err
}
typeID, mappingID, err := m.checkTargets(ctx, sourceID, req.EventType, req.Workflow, req.EventTypeID, req.MappingID)
if err != nil {
return nil, err
}
@@ -236,7 +303,7 @@ func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.
return nil, err
}
if err := m.store.UpsertTrigger(ctx, store.Trigger{
OrgID: m.orgID, Name: in.Name, Source: req.Source, EventType: req.EventType,
OrgID: m.orgID, Name: in.Name, SourceID: sourceID, EventType: req.EventType,
Filter: filter, Workflow: req.Workflow, Enabled: !req.Disabled, Approved: approved,
EventTypeID: typeID, MappingID: mappingID, ScheduleEverySeconds: every,
}); err != nil {
@@ -245,10 +312,33 @@ func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.
return httpapi.OK(triggerSaved{Trigger: in.Name}), nil
}
// triggerSource parses the source a trigger names, if any, and refuses one the
// caller can't use.
func (m *Module) triggerSource(ctx context.Context, raw string) (uuid.NullUUID, error) {
if raw == "" {
return uuid.NullUUID{}, nil
}
refuse := func(message string) error {
return huma.Error400BadRequest(message, &huma.ErrorDetail{Location: "body.source_id", Message: message})
}
id, err := uuid.Parse(raw)
if err != nil {
return uuid.NullUUID{}, refuse("a source id is a UUID")
}
usable, err := m.canUse(ctx, id)
if err != nil {
return uuid.NullUUID{}, huma.Error500InternalServerError("couldn't read the source", err)
}
if !usable {
return uuid.NullUUID{}, refuse("no such source")
}
return uuid.NullUUID{UUID: id, Valid: true}, nil
}
// checkTargets refuses a trigger whose workflow can't be started or whose
// event type, mapping or connector event type doesn't exist.
func (m *Module) checkTargets(ctx context.Context, source, eventType, workflow, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) {
if typeID, mapID, err = m.checkBinding(ctx, source, eventTypeID, mappingID); err != nil {
func (m *Module) checkTargets(ctx context.Context, sourceID uuid.NullUUID, eventType, workflow, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) {
if typeID, mapID, err = m.checkBinding(ctx, sourceID, eventTypeID, mappingID); err != nil {
return typeID, mapID, err
}
if err := m.runs.CheckTrigger(ctx, m.orgID, workflow); err != nil {
@@ -258,7 +348,7 @@ func (m *Module) checkTargets(ctx context.Context, source, eventType, workflow,
return typeID, mapID, huma.Error500InternalServerError("couldn't check the workflow", err)
}
if eventType != "" {
err = m.checkEventType(ctx, source, eventType)
err = m.checkEventType(ctx, sourceID, eventType)
}
return typeID, mapID, err
}
@@ -282,7 +372,7 @@ func (m *Module) approvedOnSave(ctx context.Context, name string, pending bool)
// checkBinding resolves the event type and mapping a trigger binds to. The
// event type must be the source's, and the mapping the event type's.
func (m *Module) checkBinding(ctx context.Context, source, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) {
func (m *Module) checkBinding(ctx context.Context, sourceID uuid.NullUUID, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) {
refuse := func(location, message string) error {
return huma.Error400BadRequest(message, &huma.ErrorDetail{Location: location, Message: message})
}
@@ -292,7 +382,7 @@ func (m *Module) checkBinding(ctx context.Context, source, eventTypeID, mappingI
return typeID, mapID, refuse("body.event_type_id", "an event type id is a UUID")
}
t, err := m.store.EventType(ctx, m.orgID, id)
if errors.Is(err, store.ErrNotFound) || (err == nil && t.Source != source) {
if errors.Is(err, store.ErrNotFound) || (err == nil && (!sourceID.Valid || t.SourceID != sourceID.UUID)) {
return typeID, mapID, refuse("body.event_type_id", "the source has no such event type")
}
if err != nil {
@@ -319,17 +409,18 @@ func (m *Module) checkBinding(ctx context.Context, source, eventTypeID, mappingI
// checkEventType refuses a trigger on an event type that the source's
// connector doesn't declare, so the trigger can't be saved when it could never
// fire. Schedule triggers have no connector.
func (m *Module) checkEventType(ctx context.Context, source, eventType string) error {
if source == scheduleSource {
// fire, and a trigger on a source the caller can't use. Schedule triggers have
// no source.
func (m *Module) checkEventType(ctx context.Context, sourceID uuid.NullUUID, eventType string) error {
if !sourceID.Valid {
return nil
}
refuse := func(location, message string) error {
return huma.Error400BadRequest(message, &huma.ErrorDetail{Location: location, Message: message})
}
src, err := m.reader.Source(ctx, m.orgID, source)
if errors.Is(err, store.ErrNotFound) {
return refuse("body.source", fmt.Sprintf("no source named %q", source))
src, err := m.reader.Source(ctx, m.orgID, sourceID.UUID)
if errors.Is(err, store.ErrNotFound) || (err == nil && !src.VisibleTo(caller(ctx))) {
return refuse("body.source_id", "no such source")
}
if err != nil {
return huma.Error500InternalServerError("couldn't read the source", err)
@@ -348,7 +439,7 @@ func (m *Module) checkEventType(ctx context.Context, source, eventType string) e
}
type putKeyFieldsInput struct {
Name string `path:"name"`
ID string `path:"id" format:"uuid"`
Body struct {
Paths []string `json:"paths,omitzero" doc:"Paths into the event's fields; none uses the connector's default"`
}
@@ -369,7 +460,11 @@ func (m *Module) putKeyFields(ctx context.Context, in *putKeyFieldsInput) (*http
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
err = m.store.SetKeyFields(ctx, m.orgID, in.Name, raw)
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
err = m.store.SetKeyFields(ctx, m.orgID, src.ID, raw)
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("no such source")
}
@@ -390,23 +485,28 @@ type groupView struct {
}
type proposedTrigger struct {
Source string `json:"source"`
SourceID uuid.UUID `json:"source_id"`
Source string `json:"source" doc:"The source's label"`
EventType string `json:"event_type"`
Filter jsontext.Value `json:"filter"`
Workflow string `json:"workflow"`
}
func (m *Module) groups(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]groupView], error) {
groups, err := m.store.Groups(ctx, m.orgID, 200)
groups, err := m.store.Groups(ctx, m.orgID, caller(ctx), 200)
if err != nil {
m.log.ErrorContext(ctx, "list groups", "error", err)
return nil, huma.Error500InternalServerError("couldn't list groups")
}
labels, err := m.labels(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list groups", err)
}
out := make([]groupView, 0, len(groups))
for _, g := range groups {
out = append(out, groupView{
ID: g.ID, Count: g.Count, FirstSeen: g.FirstSeen, LastSeen: g.LastSeen,
Proposed: proposedTrigger{Source: g.Source, EventType: g.EventType, Filter: g.Filter},
Proposed: proposedTrigger{SourceID: g.SourceID, Source: labels[g.SourceID], EventType: g.EventType, Filter: g.Filter},
})
}
return httpapi.OK(out), nil
@@ -415,19 +515,24 @@ func (m *Module) groups(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]grou
// sourceView is a source as the API returns it. The token is returned only
// when it is created or rotated, never here.
type sourceView struct {
Name string `json:"name"`
Connector string `json:"connector"`
KeyFields []string `json:"key_fields"`
TokenSet bool `json:"token_set"`
ID uuid.UUID `json:"id"`
// Scope is org for an organisation's source and person for one only its
// owner can see and use.
Scope string `json:"scope" enum:"org,person"`
// Label is the name people see; WebhookPath ends the URL deliveries post to.
Label string `json:"label"`
WebhookPath string `json:"webhook_path"`
Connector string `json:"connector"`
KeyFields []string `json:"key_fields"`
TokenSet bool `json:"token_set"`
// Verification and the HMAC header and prefix are shown; the secret is
// only reported as set.
Verification string `json:"verification"`
HMACHeader string `json:"hmac_header,omitzero"`
HMACPrefix string `json:"hmac_prefix,omitzero"`
HMACSecretSet bool `json:"hmac_secret_set"`
// DisplayName labels the source, and DeliveryHeader names the header a
// sender repeats on every retry of one delivery.
DisplayName string `json:"display_name,omitzero"`
// DeliveryHeader names the header a sender repeats on every retry of one
// delivery.
DeliveryHeader string `json:"delivery_header,omitzero"`
// Signing is signed (HMAC), token, unsigned_pending_approval or unsigned.
Signing string `json:"signing" enum:"signed,token,unsigned_pending_approval,unsigned"`
@@ -438,7 +543,7 @@ type sourceView struct {
}
func (m *Module) sources(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]sourceView], error) {
sources, err := m.store.Sources(ctx, m.orgID)
sources, err := m.store.SourcesFor(ctx, m.orgID, caller(ctx))
if err != nil {
m.log.ErrorContext(ctx, "list sources", "error", err)
return nil, huma.Error500InternalServerError("couldn't list sources")
@@ -447,8 +552,8 @@ func (m *Module) sources(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]sou
for _, src := range sources {
view, err := viewOfSource(src)
if err != nil {
m.log.ErrorContext(ctx, "read source key fields", "source", src.Name, "error", err)
return nil, huma.Error500InternalServerError("couldn't read the key fields of " + src.Name)
m.log.ErrorContext(ctx, "read source key fields", "source", src.ID, "error", err)
return nil, huma.Error500InternalServerError("couldn't read the key fields of " + src.Label)
}
out = append(out, view)
}
@@ -457,9 +562,10 @@ func (m *Module) sources(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]sou
func viewOfSource(src store.Source) (sourceView, error) {
view := sourceView{
Name: src.Name, Connector: src.Connector, TokenSet: src.TokenSHA256 != "", KeyFields: []string{},
ID: src.ID, Scope: src.Scope, Label: src.Label, WebhookPath: src.WebhookPath,
Connector: src.Connector, TokenSet: src.TokenSHA256 != "", KeyFields: []string{},
Verification: src.Verification, HMACHeader: src.HMACHeader, HMACPrefix: src.HMACPrefix, HMACSecretSet: len(src.HMACSecretSealed) > 0,
DisplayName: src.DisplayName, DeliveryHeader: src.DeliveryHeader, Signing: signingOf(src), Capture: src.Capture,
DeliveryHeader: src.DeliveryHeader, Signing: signingOf(src), Capture: src.Capture,
}
if len(src.KeyFields) > 0 {
if err := json.Unmarshal(src.KeyFields, &view.KeyFields); err != nil {
@@ -471,8 +577,10 @@ func viewOfSource(src store.Source) (sourceView, error) {
// triggerView is a trigger as the API returns it.
type triggerView struct {
Name string `json:"name"`
Source string `json:"source"`
Name string `json:"name"`
// SourceID is empty for a scheduled trigger. Source is the source's label.
SourceID string `json:"source_id,omitempty"`
Source string `json:"source,omitempty"`
EventType string `json:"event_type"`
Filter map[string]string `json:"filter"`
Workflow string `json:"workflow"`
@@ -500,7 +608,7 @@ func statusOf(t store.Trigger) string {
// viewOfTrigger is the API's form of a stored trigger. Unsigned is set by the
// caller, which knows the sources.
func viewOfTrigger(t store.Trigger) (triggerView, error) {
view := triggerView{Name: t.Name, Source: t.Source, EventType: t.EventType, Workflow: t.Workflow, Enabled: t.Enabled, Filter: map[string]string{}, Status: statusOf(t)}
view := triggerView{Name: t.Name, EventType: t.EventType, Workflow: t.Workflow, Enabled: t.Enabled, Filter: map[string]string{}, Status: statusOf(t)}
if len(t.Filter) > 0 {
if err := json.Unmarshal(t.Filter, &view.Filter); err != nil {
return view, fmt.Errorf("filter of %s: %w", t.Name, err)
@@ -509,6 +617,9 @@ func viewOfTrigger(t store.Trigger) (triggerView, error) {
if t.ScheduleEverySeconds.Valid {
view.Every = (time.Duration(t.ScheduleEverySeconds.Int64) * time.Second).String()
}
if t.SourceID.Valid {
view.SourceID = t.SourceID.UUID.String()
}
if t.EventTypeID.Valid {
view.EventTypeID = t.EventTypeID.UUID.String()
}
@@ -524,8 +635,10 @@ func (m *Module) viewOfTrigger(ctx context.Context, t store.Trigger) (triggerVie
if err != nil {
return view, err
}
if src, err := m.store.Source(ctx, m.orgID, t.Source); err == nil {
view.Unsigned = src.Verification == store.None
if t.SourceID.Valid {
if src, err := m.store.Source(ctx, m.orgID, t.SourceID.UUID); err == nil {
view.Source, view.Unsigned = src.Label, src.Verification == store.None
}
}
return view, nil
}
@@ -536,37 +649,48 @@ func (m *Module) triggers(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]tr
m.log.ErrorContext(ctx, "list triggers", "error", err)
return nil, huma.Error500InternalServerError("couldn't list triggers")
}
sources, err := m.store.Sources(ctx, m.orgID)
sources, err := m.store.SourcesFor(ctx, m.orgID, caller(ctx))
if err != nil {
m.log.ErrorContext(ctx, "list sources", "error", err)
return nil, huma.Error500InternalServerError("couldn't list triggers")
}
unsigned := map[string]bool{}
visible := make(map[uuid.UUID]store.Source, len(sources))
for _, src := range sources {
unsigned[src.Name] = src.Verification == store.None
visible[src.ID] = src
}
out := make([]triggerView, 0, len(triggers))
for _, t := range triggers {
src, seen := visible[t.SourceID.UUID]
if t.SourceID.Valid && !seen {
continue
}
view, err := viewOfTrigger(t)
if err != nil {
m.log.ErrorContext(ctx, "read trigger", "trigger", t.Name, "error", err)
return nil, huma.Error500InternalServerError("couldn't read the filter of " + t.Name)
}
view.Unsigned = unsigned[t.Source]
view.Source, view.Unsigned = src.Label, src.Verification == store.None
out = append(out, view)
}
return httpapi.OK(out), nil
}
type recentInput struct {
Limit int `query:"limit" minimum:"1" maximum:"500" default:"50"`
Source string `query:"source"`
Type string `query:"type"`
Matched string `query:"matched" enum:"true,false" doc:"Only events a trigger did or didn't match"`
Limit int `query:"limit" minimum:"1" maximum:"500" default:"50"`
SourceID string `query:"source_id" format:"uuid"`
Type string `query:"type"`
Matched string `query:"matched" enum:"true,false" doc:"Only events a trigger did or didn't match"`
}
func (m *Module) recent(ctx context.Context, in *recentInput) (*httpapi.Reply[[]eventView], error) {
filter := store.EventFilter{Source: in.Source, Type: in.Type, Limit: in.Limit}
filter := store.EventFilter{Type: in.Type, Limit: in.Limit}
if in.SourceID != "" {
id, err := uuid.Parse(in.SourceID)
if err != nil {
return nil, huma.Error400BadRequest("a source id is a UUID")
}
filter.SourceID = uuid.NullUUID{UUID: id, Valid: true}
}
if in.Matched != "" {
matched, err := strconv.ParseBool(in.Matched)
if err != nil {
@@ -574,13 +698,17 @@ func (m *Module) recent(ctx context.Context, in *recentInput) (*httpapi.Reply[[]
}
filter.Matched = &matched
}
events, err := m.store.Recent(ctx, m.orgID, filter)
events, err := m.store.Recent(ctx, m.orgID, caller(ctx), filter)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list events", err)
}
labels, err := m.labels(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list events", err)
}
out := make([]eventView, 0, len(events))
for _, e := range events {
out = append(out, viewOf(e))
out = append(out, viewOf(e, labels))
}
return httpapi.OK(out), nil
}
@@ -618,7 +746,7 @@ func (m *Module) event(ctx context.Context, in *eventInput) (*httpapi.Reply[even
if err != nil {
return nil, huma.Error400BadRequest("an event id is a UUID")
}
e, err := m.store.Event(ctx, m.orgID, id)
e, err := m.store.Event(ctx, m.orgID, caller(ctx), id)
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("no such event")
}
@@ -631,7 +759,11 @@ func (m *Module) event(ctx context.Context, in *eventInput) (*httpapi.Reply[even
m.log.ErrorContext(ctx, "read event runs", "event", id, "error", err)
return nil, huma.Error500InternalServerError("couldn't read the runs of the event")
}
view := eventDetail{eventView: viewOf(e), Body: jsontext.Value(e.Body), Runs: make([]triggerRun, 0, len(runs))}
labels, err := m.labels(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't read the event", err)
}
view := eventDetail{eventView: viewOf(e, labels), Body: jsontext.Value(e.Body), Runs: make([]triggerRun, 0, len(runs))}
if len(view.Body) == 0 || !view.Body.IsValid() {
view.Body = jsontext.Value("null")
}
@@ -643,8 +775,10 @@ func (m *Module) event(ctx context.Context, in *eventInput) (*httpapi.Reply[even
// eventView is an event as the API returns it.
type eventView struct {
ID uuid.UUID `json:"id"`
Source string `json:"source"`
ID uuid.UUID `json:"id"`
// SourceID is empty for a schedule tick. Source is the source's label.
SourceID *uuid.UUID `json:"source_id,omitempty"`
Source string `json:"source,omitempty"`
Type string `json:"type"`
Fields jsontext.Value `json:"fields"`
LinkedTo *uuid.UUID `json:"linked_to,omitempty"`
@@ -657,12 +791,15 @@ type eventView struct {
Verification string `json:"verification,omitempty"`
}
func viewOf(e store.Event) eventView {
func viewOf(e store.Event, labels map[uuid.UUID]string) eventView {
v := eventView{
Verification: e.Verification,
ID: e.ID, Source: e.Source, Type: e.Type, Fields: e.Fields, LinkedTo: e.LinkedTo,
ID: e.ID, Source: labels[e.SourceID.UUID], Type: e.Type, Fields: e.Fields, LinkedTo: e.LinkedTo,
ReceivedAt: e.ReceivedAt, Matched: e.Matched,
}
if e.SourceID.Valid {
v.SourceID = &e.SourceID.UUID
}
if e.OccurredAt.Valid {
v.OccurredAt = &e.OccurredAt.Time
}
+82 -39
View File
@@ -53,13 +53,14 @@ func (m *Module) registerCapture(api huma.API) {
// captureView is a stored delivery as the inspector shows it.
type captureView struct {
ID uuid.UUID `json:"id"`
ReceivedAt time.Time `json:"received_at"`
Source string `json:"source"`
RemoteAddr string `json:"remote_addr,omitempty"`
ContentType string `json:"content_type,omitempty"`
Headers string `json:"headers"`
Body string `json:"body"`
ID uuid.UUID `json:"id"`
ReceivedAt time.Time `json:"received_at"`
SourceID *uuid.UUID `json:"source_id,omitempty"`
Source string `json:"source,omitempty" doc:"The source's label"`
RemoteAddr string `json:"remote_addr,omitempty"`
ContentType string `json:"content_type,omitempty"`
Headers string `json:"headers"`
Body string `json:"body"`
// Verification is how the delivery was verified: signed, token or unsigned.
Verification string `json:"verification" enum:"signed,token,unsigned,"`
// EventType is the id of the event type the delivery was identified as.
@@ -77,28 +78,35 @@ type capturesBody struct {
}
func (m *Module) captures(ctx context.Context, in *capturesInput) (*httpapi.Reply[capturesBody], error) {
rows, err := m.store.Captures(ctx, m.orgID, in.Limit)
rows, err := m.store.Captures(ctx, m.orgID, caller(ctx), in.Limit)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list captures", err)
}
sources, err := m.store.Sources(ctx, m.orgID)
sources, err := m.store.SourcesFor(ctx, m.orgID, caller(ctx))
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list sources", err)
}
labels := make(map[uuid.UUID]string, len(sources))
for _, src := range sources {
labels[src.ID] = src.Label
}
enabled := len(sources) == 0 || slices.ContainsFunc(sources, func(s store.Source) bool { return s.Capture })
out := capturesBody{Captures: make([]captureView, 0, len(rows)), Enabled: enabled}
for _, e := range rows {
out.Captures = append(out.Captures, captureOf(e))
out.Captures = append(out.Captures, captureOf(e, labels))
}
return httpapi.OK(out), nil
}
func captureOf(e store.Event) captureView {
func captureOf(e store.Event, labels map[uuid.UUID]string) captureView {
v := captureView{
ID: e.ID, ReceivedAt: e.ReceivedAt, Source: e.Source, RemoteAddr: e.RemoteAddr,
ID: e.ID, ReceivedAt: e.ReceivedAt, Source: labels[e.SourceID.UUID], RemoteAddr: e.RemoteAddr,
Headers: string(e.Headers), Body: string(e.Body), Verification: e.Verification,
}
v.ContentType = eventtype.ParseHeaders(v.Headers)["content-type"]
if e.SourceID.Valid {
v.SourceID = &e.SourceID.UUID
}
if e.EventTypeID.Valid {
v.EventType = e.EventTypeID.UUID.String()
}
@@ -123,6 +131,11 @@ func (m *Module) captureDispatches(ctx context.Context, in *idInput) (*httpapi.R
if err != nil {
return nil, huma.Error400BadRequest("a capture id is a UUID")
}
if _, err := m.store.Event(ctx, m.orgID, caller(ctx), id); errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("no such capture")
} else if err != nil {
return nil, huma.Error500InternalServerError("couldn't read the capture", err)
}
runs, err := m.store.RunsForEvent(ctx, m.orgID, id)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't read the runs of the capture", err)
@@ -136,11 +149,12 @@ func (m *Module) captureDispatches(ctx context.Context, in *idInput) (*httpapi.R
// eventTypeView is an event type as the inspector reads it.
type eventTypeView struct {
ID uuid.UUID `json:"id"`
Source string `json:"source"`
Name string `json:"name"`
Rule eventtype.Rule `json:"rule"`
Schema map[string]eventtype.ValueType `json:"schema"`
ID uuid.UUID `json:"id"`
SourceID uuid.UUID `json:"source_id"`
Source string `json:"source" doc:"The source's label"`
Name string `json:"name"`
Rule eventtype.Rule `json:"rule"`
Schema map[string]eventtype.ValueType `json:"schema"`
}
type eventTypesBody struct {
@@ -153,7 +167,11 @@ type eventTypesBody struct {
const proposalScan = 500
func (m *Module) eventTypes(ctx context.Context, _ *struct{}) (*httpapi.Reply[eventTypesBody], error) {
rows, err := m.store.EventTypes(ctx, m.orgID)
rows, err := m.store.EventTypes(ctx, m.orgID, caller(ctx))
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list event types", err)
}
labels, err := m.labels(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list event types", err)
}
@@ -163,9 +181,9 @@ func (m *Module) eventTypes(ctx context.Context, _ *struct{}) (*httpapi.Reply[ev
}
out := eventTypesBody{Enabled: true, EventTypes: make([]eventTypeView, 0, len(types))}
for i, t := range types {
out.EventTypes = append(out.EventTypes, eventTypeView{ID: rows[i].ID, Source: t.Source, Name: t.Name, Rule: t.Rule, Schema: t.Schema})
out.EventTypes = append(out.EventTypes, eventTypeView{ID: rows[i].ID, SourceID: rows[i].SourceID, Source: labels[rows[i].SourceID], Name: t.Name, Rule: t.Rule, Schema: t.Schema})
}
captured, err := m.store.Captures(ctx, m.orgID, proposalScan)
captured, err := m.store.Captures(ctx, m.orgID, caller(ctx), proposalScan)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list captures", err)
}
@@ -185,20 +203,21 @@ func unidentified(types []eventtype.EventType, captured []store.Event) []eventty
continue
}
sample := eventtype.Sample{Headers: eventtype.ParseHeaders(string(e.Headers)), Body: e.Body}
if _, ok := eventtype.Identify(types, e.Source, sample); ok {
sourceID := e.SourceID.UUID.String()
if _, ok := eventtype.Identify(types, sourceID, sample); ok {
continue
}
out = append(out, eventtype.Capture{ID: e.ID.String(), Source: e.Source, ReceivedAt: e.ReceivedAt, Sample: sample})
out = append(out, eventtype.Capture{ID: e.ID.String(), SourceID: sourceID, ReceivedAt: e.ReceivedAt, Sample: sample})
}
return out
}
type createEventTypeInput struct {
Body struct {
Source string `json:"source"`
Name string `json:"name"`
Rule *eventtype.Rule `json:"rule,omitzero" doc:"The conditions that identify the type; inferred from the example when absent"`
Example struct {
SourceID string `json:"source_id" format:"uuid"`
Name string `json:"name"`
Rule *eventtype.Rule `json:"rule,omitzero" doc:"The conditions that identify the type; inferred from the example when absent"`
Example struct {
Headers map[string]string `json:"headers,omitzero"`
Body string `json:"body,omitzero"`
} `json:"example,omitzero"`
@@ -207,17 +226,21 @@ type createEventTypeInput struct {
func (m *Module) createEventType(ctx context.Context, in *createEventTypeInput) (*httpapi.Reply[eventTypeView], error) {
req := in.Body
t := eventtype.FromExample(req.Source, req.Name, eventtype.Sample{Headers: req.Example.Headers, Body: []byte(req.Example.Body)})
t := eventtype.FromExample(req.SourceID, req.Name, eventtype.Sample{Headers: req.Example.Headers, Body: []byte(req.Example.Body)})
if req.Rule != nil {
t.Rule = *req.Rule
}
if err := t.Validate(); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
if _, err := m.store.Source(ctx, m.orgID, t.Source); errors.Is(err, store.ErrNotFound) {
return nil, huma.Error400BadRequest("no source named " + t.Source)
} else if err != nil {
sourceID, err := uuid.Parse(t.SourceID)
if err != nil {
return nil, huma.Error400BadRequest("a source id is a UUID")
}
if usable, err := m.canUse(ctx, sourceID); err != nil {
return nil, huma.Error500InternalServerError("couldn't read the source", err)
} else if !usable {
return nil, huma.Error400BadRequest("no such source")
}
if err := m.checkOverlap(ctx, t); err != nil {
return nil, err
@@ -231,21 +254,25 @@ func (m *Module) createEventType(ctx context.Context, in *createEventTypeInput)
return nil, huma.Error400BadRequest(err.Error())
}
id := uuid.New()
err = m.store.InsertEventType(ctx, store.EventType{ID: id, OrgID: m.orgID, Source: t.Source, Name: t.Name, Rule: rule, Schema: schema})
err = m.store.InsertEventType(ctx, store.EventType{ID: id, OrgID: m.orgID, SourceID: sourceID, Name: t.Name, Rule: rule, Schema: schema})
if errors.Is(err, store.ErrExists) {
return nil, huma.Error409Conflict("the source already has an event type named " + t.Name)
}
if err != nil {
return nil, huma.Error500InternalServerError("couldn't save the event type", err)
}
return httpapi.OK(eventTypeView{ID: id, Source: t.Source, Name: t.Name, Rule: t.Rule, Schema: t.Schema}), nil
return httpapi.OK(eventTypeView{ID: id, SourceID: sourceID, Name: t.Name, Rule: t.Rule, Schema: t.Schema}), nil
}
// checkOverlap refuses a type whose rule can match events another type on the
// source already matches, since an event is identified only when one type
// matches it.
func (m *Module) checkOverlap(ctx context.Context, candidate eventtype.EventType) error {
rows, err := m.store.EventTypesOf(ctx, m.orgID, candidate.Source)
sourceID, err := uuid.Parse(candidate.SourceID)
if err != nil {
return huma.Error400BadRequest("a source id is a UUID")
}
rows, err := m.store.EventTypesOf(ctx, m.orgID, sourceID)
if err != nil {
return huma.Error500InternalServerError("couldn't list event types", err)
}
@@ -283,7 +310,7 @@ func (m *Module) updateEventType(ctx context.Context, in *updateEventTypeInput)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't read the event type", err)
}
t := eventtype.EventType{ID: in.ID, Source: stored.Source, Name: in.Body.Name, Rule: in.Body.Rule}
t := eventtype.EventType{ID: in.ID, SourceID: stored.SourceID.String(), Name: in.Body.Name, Rule: in.Body.Rule}
if err := t.Validate(); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
@@ -325,7 +352,7 @@ func (m *Module) deleteEventType(ctx context.Context, in *idInput) (*struct{}, e
type mappingView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
SourceHint string `json:"source_hint"`
SourceID *uuid.UUID `json:"source_id,omitempty" doc:"The source the mapping was made for, a hint only"`
EventTypeID uuid.UUID `json:"event_type_id"`
Fields []mapping.Field `json:"fields"`
MatchCount int64 `json:"match_count"`
@@ -336,9 +363,12 @@ type mappingView struct {
func mappingOf(r store.Mapping) (mappingView, error) {
v := mappingView{
ID: r.ID, Name: r.Name, SourceHint: r.SourceHint, EventTypeID: r.EventTypeID,
ID: r.ID, Name: r.Name, EventTypeID: r.EventTypeID,
MatchCount: r.MatchCount, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
}
if r.SourceID.Valid {
v.SourceID = &r.SourceID.UUID
}
if err := json.Unmarshal(r.Fields, &v.Fields); err != nil {
return v, err
}
@@ -391,7 +421,7 @@ func (m *Module) mapping(ctx context.Context, in *idInput) (*httpapi.Reply[mappi
type mappingBody struct {
Name string `json:"name"`
SourceHint string `json:"source_hint,omitzero"`
SourceID string `json:"source_id,omitzero" format:"uuid" doc:"The source the mapping was made for, a hint only"`
EventTypeID string `json:"event_type_id" format:"uuid"`
Fields []mapping.Field `json:"fields"`
}
@@ -432,7 +462,20 @@ func (m *Module) checkedMapping(ctx context.Context, b mappingBody) (store.Mappi
if err != nil {
return store.Mapping{}, huma.Error400BadRequest(err.Error())
}
return store.Mapping{OrgID: m.orgID, Name: b.Name, SourceHint: b.SourceHint, EventTypeID: typeID, Fields: fields}, nil
row := store.Mapping{OrgID: m.orgID, Name: b.Name, EventTypeID: typeID, Fields: fields}
if b.SourceID != "" {
id, err := uuid.Parse(b.SourceID)
if err != nil {
return store.Mapping{}, huma.Error400BadRequest("a source id is a UUID")
}
if usable, err := m.canUse(ctx, id); err != nil {
return store.Mapping{}, huma.Error500InternalServerError("couldn't read the source", err)
} else if !usable {
return store.Mapping{}, huma.Error400BadRequest("no such source")
}
row.SourceID = uuid.NullUUID{UUID: id, Valid: true}
}
return row, nil
}
func (m *Module) createMapping(ctx context.Context, in *createMappingInput) (*httpapi.Reply[mappingView], error) {
@@ -515,7 +558,7 @@ func (m *Module) previewMapping(ctx context.Context, in *previewInput) (*httpapi
if err != nil {
return nil, huma.Error400BadRequest("a capture id is a UUID")
}
e, err := m.store.Event(ctx, m.orgID, id)
e, err := m.store.Event(ctx, m.orgID, caller(ctx), id)
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("no such capture")
}
+110 -50
View File
@@ -11,6 +11,7 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"golang.org/x/net/http/httpguts"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
@@ -27,13 +28,14 @@ func (m *Module) registerSourceSettings(api huma.API) {
return huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags}
}
admin := httpapi.AdminAuthorized[governance.Action, governance.ResourceKind]
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-name", http.MethodPut, "/api/sources/{name}/name", "Label a source"), m.setSourceName)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-delivery-header", http.MethodPut, "/api/sources/{name}/delivery-header", "Name the header a sender repeats when it retries a delivery"), m.setDeliveryHeader)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-capture", http.MethodPut, "/api/sources/{name}/capture", "Keep or stop keeping the headers and payloads a source receives"), m.setCapture)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-signing", http.MethodPost, "/api/sources/{name}/signing", "Require an HMAC signature, or ask to take unsigned deliveries"), m.setSigning)
httpapi.Register(api, admin(governance.ActionApprove, governance.KindSource), op("approve-source-unsigned", http.MethodPost, "/api/sources/{name}/approve-unsigned", "Accept deliveries that carry no signature"), m.approveUnsigned)
httpapi.Register(api, admin(governance.ActionReadSecret, governance.KindSecret), op("rotate-source-secret", http.MethodPost, "/api/sources/{name}/secret", "Replace a signed source's secret and return it once"), m.rotateSecret)
httpapi.Register(api, admin(governance.ActionDelete, governance.KindSource), op("delete-source", http.MethodDelete, "/api/sources/{name}", "Delete a source"), m.deleteSource)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-label", http.MethodPut, "/api/sources/{id}/label", "Rename a source"), m.setSourceLabel)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-webhook-path", http.MethodPut, "/api/sources/{id}/webhook-path", "Move the address a source receives deliveries at"), m.setWebhookPath)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-delivery-header", http.MethodPut, "/api/sources/{id}/delivery-header", "Name the header a sender repeats when it retries a delivery"), m.setDeliveryHeader)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-capture", http.MethodPut, "/api/sources/{id}/capture", "Keep or stop keeping the headers and payloads a source receives"), m.setCapture)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-signing", http.MethodPost, "/api/sources/{id}/signing", "Require an HMAC signature, or ask to take unsigned deliveries"), m.setSigning)
httpapi.Register(api, admin(governance.ActionApprove, governance.KindSource), op("approve-source-unsigned", http.MethodPost, "/api/sources/{id}/approve-unsigned", "Accept deliveries that carry no signature"), m.approveUnsigned)
httpapi.Register(api, admin(governance.ActionReadSecret, governance.KindSecret), op("rotate-source-secret", http.MethodPost, "/api/sources/{id}/secret", "Replace a signed source's secret and return it once"), m.rotateSecret)
httpapi.Register(api, admin(governance.ActionDelete, governance.KindSource), op("delete-source", http.MethodDelete, "/api/sources/{id}", "Delete a source"), m.deleteSource)
httpapi.Register(api, admin(governance.ActionApprove, governance.KindTrigger), op("approve-trigger", http.MethodPost, "/api/triggers/{name}/approve", "Arm a trigger that waits for approval"), m.approveTrigger)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindTrigger), op("pause-trigger", http.MethodPost, "/api/triggers/{name}/pause", "Stop a trigger firing"), m.pauseTrigger)
@@ -43,7 +45,16 @@ func (m *Module) registerSourceSettings(api huma.API) {
}
type sourceInput struct {
Name string `path:"name"`
ID string `path:"id" format:"uuid"`
}
// sourceID parses the id of a source in a request.
func sourceID(raw string) (uuid.UUID, error) {
id, err := uuid.Parse(raw)
if err != nil {
return uuid.Nil, huma.Error400BadRequest("a source id is a UUID")
}
return id, nil
}
// Signing states a source reports: an HMAC signature, a bearer token, or no
@@ -67,10 +78,15 @@ func signingOf(src store.Source) string {
return signingPending
}
// readSource loads a source for a settings change.
func (m *Module) readSource(ctx context.Context, name string) (store.Source, error) {
src, err := m.store.Source(ctx, m.orgID, name)
if errors.Is(err, store.ErrNotFound) {
// readSource loads a source for a request. A person's source that belongs to
// someone else reads as missing, so its existence isn't disclosed.
func (m *Module) readSource(ctx context.Context, rawID string) (store.Source, error) {
id, err := sourceID(rawID)
if err != nil {
return store.Source{}, err
}
src, err := m.reader.Source(ctx, m.orgID, id)
if errors.Is(err, store.ErrNotFound) || (err == nil && !src.VisibleTo(caller(ctx))) {
return src, huma.Error404NotFound("no such source")
}
if err != nil {
@@ -81,36 +97,64 @@ func (m *Module) readSource(ctx context.Context, name string) (store.Source, err
// sourceReply reads a source back after a change. secret is a signing secret
// issued by the change, returned once.
func (m *Module) sourceReply(ctx context.Context, name, secret string) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, name)
func (m *Module) sourceReply(ctx context.Context, id, secret string) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, id)
if err != nil {
return nil, err
}
view, err := viewOfSource(src)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't read the key fields of "+name, err)
return nil, huma.Error500InternalServerError("couldn't read the key fields of "+src.Label, err)
}
view.Secret = secret
return httpapi.OK(view), nil
}
type sourceNameInput struct {
Name string `path:"name"`
type sourceLabelInput struct {
ID string `path:"id" format:"uuid"`
Body struct {
Name string `json:"name" maxLength:"100"`
Label string `json:"label" minLength:"1" maxLength:"100" doc:"The name people see, unique among the sources of the same owner"`
}
}
func (m *Module) setSourceName(ctx context.Context, in *sourceNameInput) (*httpapi.Reply[sourceView], error) {
err := m.store.SetDisplayName(ctx, m.orgID, in.Name, strings.TrimSpace(in.Body.Name))
if err := sourceWriteError(err); err != nil {
func (m *Module) setSourceLabel(ctx context.Context, in *sourceLabelInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
return m.sourceReply(ctx, in.Name, "")
label := strings.TrimSpace(in.Body.Label)
if label == "" {
return nil, huma.Error400BadRequest("a source needs a label")
}
if err := sourceWriteError(m.store.SetLabel(ctx, m.orgID, src.ID, label)); err != nil {
return nil, err
}
return m.sourceReply(ctx, in.ID, "")
}
type webhookPathInput struct {
ID string `path:"id" format:"uuid"`
Body struct {
Path string `json:"path" doc:"Lowercase letters, digits and hyphens; the webhook URL ends in it. Senders must post to the new address."`
}
}
func (m *Module) setWebhookPath(ctx context.Context, in *webhookPathInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
if !validName.MatchString(in.Body.Path) {
return nil, huma.Error400BadRequest("a webhook path is lowercase letters, digits and hyphens")
}
if err := sourceWriteError(m.store.SetWebhookPath(ctx, m.orgID, src.ID, in.Body.Path)); err != nil {
return nil, err
}
return m.sourceReply(ctx, in.ID, "")
}
type deliveryHeaderInput struct {
Name string `path:"name"`
ID string `path:"id" format:"uuid"`
Body struct {
Header string `json:"header" doc:"A header name; empty stops de-duplicating retries by header"`
}
@@ -124,15 +168,18 @@ func (m *Module) setDeliveryHeader(ctx context.Context, in *deliveryHeaderInput)
}
header = textproto.CanonicalMIMEHeaderKey(header)
}
err := m.store.SetDeliveryHeader(ctx, m.orgID, in.Name, header)
if err := sourceWriteError(err); err != nil {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
return m.sourceReply(ctx, in.Name, "")
if err := sourceWriteError(m.store.SetDeliveryHeader(ctx, m.orgID, src.ID, header)); err != nil {
return nil, err
}
return m.sourceReply(ctx, in.ID, "")
}
type captureInput struct {
Name string `path:"name"`
ID string `path:"id" format:"uuid"`
Body struct {
Capture bool `json:"capture"`
}
@@ -142,8 +189,12 @@ type captureInput struct {
// that maps the source's payload needs the stored payload, so it blocks
// turning capture off.
func (m *Module) setCapture(ctx context.Context, in *captureInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
if !in.Body.Capture {
n, err := m.store.MappedTriggers(ctx, m.orgID, in.Name)
n, err := m.store.MappedTriggers(ctx, m.orgID, src.ID)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't check the triggers of the source", err)
}
@@ -151,22 +202,21 @@ func (m *Module) setCapture(ctx context.Context, in *captureInput) (*httpapi.Rep
return nil, huma.Error409Conflict(fmt.Sprintf("%d trigger(s) of this source read its payload through a mapping, which needs it kept", n))
}
}
err := m.store.SetCapture(ctx, m.orgID, in.Name, in.Body.Capture)
if err := sourceWriteError(err); err != nil {
if err := sourceWriteError(m.store.SetCapture(ctx, m.orgID, src.ID, in.Body.Capture)); err != nil {
return nil, err
}
return m.sourceReply(ctx, in.Name, "")
return m.sourceReply(ctx, in.ID, "")
}
type signingInput struct {
Name string `path:"name"`
ID string `path:"id" format:"uuid"`
Body struct {
Signed bool `json:"signed" doc:"True requires an HMAC signature; false asks to take deliveries without one, which a person must approve"`
}
}
func (m *Module) setSigning(ctx context.Context, in *signingInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.Name)
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
@@ -181,29 +231,30 @@ func (m *Module) setSigning(ctx context.Context, in *signingInput) (*httpapi.Rep
}
}
}
if err := sourceWriteError(m.store.SetSigning(ctx, m.orgID, in.Name, in.Body.Signed)); err != nil {
if err := sourceWriteError(m.store.SetSigning(ctx, m.orgID, src.ID, in.Body.Signed)); err != nil {
return nil, err
}
return m.sourceReply(ctx, in.Name, secret)
return m.sourceReply(ctx, in.ID, secret)
}
// approveUnsigned accepts that a source takes deliveries with no verification.
func (m *Module) approveUnsigned(ctx context.Context, in *sourceInput) (*httpapi.Reply[sourceView], error) {
approved, err := m.store.ApproveUnsigned(ctx, m.orgID, in.Name)
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
approved, err := m.store.ApproveUnsigned(ctx, m.orgID, src.ID)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't approve the source", err)
}
if !approved {
if _, err := m.readSource(ctx, in.Name); err != nil {
return nil, err
}
return nil, huma.Error409Conflict("the source isn't waiting for approval of unsigned deliveries")
}
return m.sourceReply(ctx, in.Name, "")
return m.sourceReply(ctx, in.ID, "")
}
func (m *Module) rotateSecret(ctx context.Context, in *sourceInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.Name)
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
@@ -214,7 +265,7 @@ func (m *Module) rotateSecret(ctx context.Context, in *sourceInput) (*httpapi.Re
if err != nil {
return nil, err
}
return m.sourceReply(ctx, in.Name, secret)
return m.sourceReply(ctx, in.ID, secret)
}
// issueSecret generates a signing secret, stores it sealed and returns it.
@@ -223,11 +274,11 @@ func (m *Module) issueSecret(ctx context.Context, src store.Source) (string, err
if err != nil {
return "", huma.Error500InternalServerError("couldn't generate a secret", err)
}
sealed, err := m.sealer.Seal(secretLabel(m.orgID, src.Name), []byte(secret))
sealed, err := m.sealer.Seal(secretLabel(m.orgID, src.ID), []byte(secret))
if err != nil {
return "", huma.Error500InternalServerError("couldn't seal the secret", err)
}
if err := m.store.SetSecret(ctx, m.orgID, src.Name, sealed); err != nil {
if err := m.store.SetSecret(ctx, m.orgID, src.ID, sealed); err != nil {
return "", huma.Error500InternalServerError("couldn't save the secret", err)
}
return secret, nil
@@ -248,6 +299,8 @@ func sourceWriteError(err error) error {
return nil
case errors.Is(err, store.ErrNotFound):
return huma.Error404NotFound("no such source")
case errors.Is(err, store.ErrLabelTaken), errors.Is(err, store.ErrPathTaken):
return huma.Error409Conflict(err.Error())
}
return huma.Error500InternalServerError("couldn't save the source", err)
}
@@ -255,7 +308,11 @@ func sourceWriteError(err error) error {
// deleteSource removes a source. A trigger that names it blocks the delete;
// its event types go with it, and the events it stored stay.
func (m *Module) deleteSource(ctx context.Context, in *sourceInput) (*struct{}, error) {
err := m.store.DeleteSource(ctx, m.orgID, in.Name)
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
err = m.store.DeleteSource(ctx, m.orgID, src.ID)
switch {
case errors.Is(err, store.ErrNotFound):
return nil, huma.Error404NotFound("no such source")
@@ -274,12 +331,9 @@ type triggerInput struct {
// moveTrigger changes a trigger's state when it is in one of from, and refuses
// otherwise.
func (m *Module) moveTrigger(ctx context.Context, name string, allowed func(store.Trigger) bool, refusal string, approved, enabled bool) (*httpapi.Reply[triggerView], error) {
t, err := m.store.Trigger(ctx, m.orgID, name)
if errors.Is(err, store.ErrNotFound) {
return nil, huma.Error404NotFound("no such trigger")
}
t, err := m.visibleTrigger(ctx, name)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't read the trigger", err)
return nil, err
}
if !allowed(t) {
return nil, huma.Error409Conflict(refusal)
@@ -313,6 +367,9 @@ func (m *Module) resumeTrigger(ctx context.Context, in *triggerInput) (*httpapi.
// started continue, and the dispatch records that link them to their events stay
// under the trigger's name.
func (m *Module) deleteTrigger(ctx context.Context, in *triggerInput) (*struct{}, error) {
if _, err := m.visibleTrigger(ctx, in.Name); err != nil {
return nil, err
}
err := m.store.DeleteTrigger(ctx, m.orgID, in.Name)
switch {
case errors.Is(err, store.ErrNotFound):
@@ -329,6 +386,9 @@ type triggerDispatchesInput struct {
}
func (m *Module) triggerDispatches(ctx context.Context, in *triggerDispatchesInput) (*httpapi.Reply[[]dispatchView], error) {
if _, err := m.visibleTrigger(ctx, in.Name); err != nil {
return nil, err
}
rows, err := m.store.DispatchesOf(ctx, m.orgID, in.Name, in.Limit)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list the runs of the trigger", err)
+4 -4
View File
@@ -26,7 +26,7 @@ type arrival struct {
// typeReader lists a source's event types.
type typeReader interface {
EventTypesOf(ctx context.Context, orgID, source string) ([]store.EventType, error)
EventTypesOf(ctx context.Context, orgID string, sourceID uuid.UUID) ([]store.EventType, error)
}
// credentialWords mark a header as carrying a credential or a signature, which
@@ -90,7 +90,7 @@ func (m *Module) identify(ctx context.Context, row *store.Event, src store.Sourc
if m.types == nil {
return nil
}
rows, err := m.types.EventTypesOf(ctx, row.OrgID, src.Name)
rows, err := m.types.EventTypesOf(ctx, row.OrgID, src.ID)
if err != nil {
return err
}
@@ -99,7 +99,7 @@ func (m *Module) identify(ctx context.Context, row *store.Event, src store.Sourc
return err
}
sample := eventtype.Sample{Headers: lowered(h), Body: row.Body}
if found, ok := eventtype.Identify(types, src.Name, sample); ok {
if found, ok := eventtype.Identify(types, src.ID.String(), sample); ok {
id, err := uuid.Parse(found.ID)
if err != nil {
return fmt.Errorf("event type id %q: %w", found.ID, err)
@@ -134,7 +134,7 @@ func typesOf(rows []store.EventType) ([]eventtype.EventType, error) {
}
func typeOf(r store.EventType) (eventtype.EventType, error) {
t := eventtype.EventType{ID: r.ID.String(), Source: r.Source, Name: r.Name}
t := eventtype.EventType{ID: r.ID.String(), SourceID: r.SourceID.String(), Name: r.Name}
if err := json.Unmarshal(r.Rule, &t.Rule); err != nil {
return t, fmt.Errorf("event type %q rule: %w", r.Name, err)
}
+3 -3
View File
@@ -43,11 +43,11 @@ func TestIntakeRecordsHowEachDeliveryWasVerified(t *testing.T) {
if err != nil {
t.Fatal(err)
}
sealed, err := sealer.Seal(secretLabel("org", "hook"), []byte(secret))
sealed, err := sealer.Seal(secretLabel("org", hookID), []byte(secret))
if err != nil {
t.Fatal(err)
}
base := store.Source{OrgID: "org", Name: "hook", Connector: "c", Capture: true}
base := store.Source{ID: hookID, OrgID: "org", WebhookPath: "hook", Connector: "c", Capture: true}
hmacSource := base
hmacSource.Verification, hmacSource.HMACHeader, hmacSource.HMACPrefix, hmacSource.HMACSecretSealed = store.HMAC, "X-Signature", "sha256=", sealed
tokenSource := base
@@ -83,7 +83,7 @@ func TestIntakeRecordsHowEachDeliveryWasVerified(t *testing.T) {
},
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(body))
req.SetPathValue("source", "hook")
req.SetPathValue("path", "hook")
maps.Copy(req.Header, tt.header)
req.Header.Set("Cookie", "session=not-a-real-cookie")
rec := httptest.NewRecorder()
+3 -3
View File
@@ -47,7 +47,7 @@ func TestIntakeEvaluatesThePolicyAgainstTheClientBehindTrustedProxies(t *testing
policy := &deliveryPolicy{decision: governance.Allowed()}
m := &Module{
orgID: "default", log: slog.New(slog.DiscardHandler), inserter: &onceInserter{stored: map[string]bool{}}, deliveries: noEcho{},
reader: fakeSources{store.Source{OrgID: "default", Name: "hook", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}},
reader: fakeSources{store.Source{ID: hookID, OrgID: "default", WebhookPath: "hook", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}},
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil
},
@@ -55,7 +55,7 @@ func TestIntakeEvaluatesThePolicyAgainstTheClientBehindTrustedProxies(t *testing
m.UseDeliveryPolicy(policy)
m.UseTrustedProxies(func(context.Context) ([]netip.Prefix, error) { return tt.trusted, tt.readErr })
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(`{}`))
req.SetPathValue("source", "hook")
req.SetPathValue("path", "hook")
req.RemoteAddr = tt.peer
req.Header.Set("Authorization", "Bearer "+token)
for _, h := range tt.headers {
@@ -66,7 +66,7 @@ func TestIntakeEvaluatesThePolicyAgainstTheClientBehindTrustedProxies(t *testing
if rec.Code != http.StatusAccepted {
t.Fatalf("status %d, want %d", rec.Code, http.StatusAccepted)
}
if want := "org-sys hook " + tt.want; len(policy.asked) != 1 || policy.asked[0] != want {
if want := "org-sys " + hookID.String() + " " + tt.want; len(policy.asked) != 1 || policy.asked[0] != want {
t.Fatalf("delivery policy asked %v, want %q", policy.asked, want)
}
})
+12 -5
View File
@@ -15,7 +15,10 @@ import (
// Group is a set of unmatched events that share a key, with the trigger it
// proposes.
type Group struct {
ID uuid.UUID
ID uuid.UUID
// SourceID is the source whose events the group collects, and Source its
// label.
SourceID uuid.UUID
Source string
EventType string
Filter map[string]string
@@ -34,8 +37,12 @@ func (m *Module) Group(ctx context.Context, id uuid.UUID) (Group, bool, error) {
if err := json.Unmarshal(g.Filter, &filter); err != nil {
return Group{}, false, fmt.Errorf("group %s filter: %w", id, err)
}
src, err := m.store.Source(ctx, m.orgID, g.SourceID)
if err != nil {
return Group{}, false, fmt.Errorf("group %s source: %w", id, err)
}
return Group{
ID: g.ID, Source: g.Source, EventType: g.EventType, Filter: filter,
ID: g.ID, SourceID: g.SourceID, Source: src.Label, EventType: g.EventType, Filter: filter,
Count: g.Count, FirstSeen: g.FirstSeen, LastSeen: g.LastSeen,
}, true, nil
}
@@ -70,7 +77,7 @@ func (m *Module) Replayed(ctx context.Context, eventID uuid.UUID, trigger string
// TriggerSpec is an event trigger to save.
type TriggerSpec struct {
Name string
Source string
SourceID uuid.UUID
EventType string
Filter map[string]string
Workflow string
@@ -78,7 +85,7 @@ type TriggerSpec struct {
// SaveTrigger creates or replaces an event trigger.
func (m *Module) SaveTrigger(ctx context.Context, t TriggerSpec) error {
if !validName.MatchString(t.Name) || t.Source == "" || t.EventType == "" || t.Workflow == "" {
if !validName.MatchString(t.Name) || t.SourceID == uuid.Nil || t.EventType == "" || t.Workflow == "" {
return fmt.Errorf("a trigger needs a lowercase name, a source, an event type and a workflow")
}
if err := m.runs.CheckTrigger(ctx, m.orgID, t.Workflow); err != nil {
@@ -89,7 +96,7 @@ func (m *Module) SaveTrigger(ctx context.Context, t TriggerSpec) error {
return fmt.Errorf("encode filter: %w", err)
}
return m.store.UpsertTrigger(ctx, store.Trigger{
OrgID: m.orgID, Name: t.Name, Source: t.Source, EventType: t.EventType,
OrgID: m.orgID, Name: t.Name, SourceID: uuid.NullUUID{UUID: t.SourceID, Valid: true}, EventType: t.EventType,
Filter: filter, Workflow: t.Workflow, Enabled: true, Approved: true,
})
}
+29 -23
View File
@@ -116,9 +116,11 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealer Sealer, c Con
return m
}
// sourceReader is the store method that intake uses to look up a source.
// sourceReader looks up a source by the webhook path a delivery addressed, or
// by its id for a stored event.
type sourceReader interface {
Source(ctx context.Context, orgID, name string) (store.Source, error)
SourceByPath(ctx context.Context, orgID, path string) (store.Source, error)
Source(ctx context.Context, orgID string, id uuid.UUID) (store.Source, error)
}
// eventInserter stores an event, and reports false when its source event id
@@ -134,7 +136,7 @@ func (m *Module) UseDeliveryPolicy(d governance.DeliveryAuthorizer) { m.delivery
// Routes adds the webhook intake. It stays outside the API because each
// source verifies its own deliveries.
func (m *Module) Routes(mux *http.ServeMux) {
mux.HandleFunc("POST /hooks/{source}", m.intake)
mux.HandleFunc("POST /hooks/{path}", m.intake)
}
// intake verifies a delivery, checks the source's delivery policy, parses it
@@ -169,10 +171,10 @@ type delivery struct {
// the connector for parsing. A delivery that fails verification is rejected
// with 401 before the connector sees its body, and the rejection is logged.
// An unknown source and a failed verification get the same response, so a
// caller cannot use it to discover source names.
// caller cannot use it to discover webhook paths.
func (m *Module) accept(r *http.Request) (d delivery, status int, err error) {
ctx := r.Context()
src, err := m.reader.Source(ctx, m.orgID, r.PathValue("source"))
src, err := m.reader.SourceByPath(ctx, m.orgID, r.PathValue("path"))
if errors.Is(err, store.ErrNotFound) {
return d, http.StatusUnauthorized, errUnknown
}
@@ -233,7 +235,7 @@ var (
// refuse logs why a delivery was rejected and chooses the status: 401 when
// verification failed, 503 when verification could not run.
func (m *Module) refuse(ctx context.Context, d delivery, err error) (delivery, int, error) {
m.log.WarnContext(ctx, "refused webhook delivery", "source", d.src.Name, "verification", d.src.Verification, "reason", err.Error())
m.log.WarnContext(ctx, "refused webhook delivery", "source", d.src.ID, "verification", d.src.Verification, "reason", err.Error())
if errors.Is(err, errUnverified) {
return d, http.StatusUnauthorized, errUnknown
}
@@ -263,15 +265,15 @@ func (m *Module) admit(ctx context.Context, src store.Source, addr string) (admi
}
// Delivery policies belong to the operating organisation, whatever the
// source's own org id says.
d := m.delivery.AuthorizeDelivery(ctx, governance.DefaultOrgID, src.Name, addr)
d := m.delivery.AuthorizeDelivery(ctx, governance.DefaultOrgID, src.ID.String(), addr)
switch {
case d.Allowed:
return admission{src: src}, 0, nil
case errors.Is(d.Err, governance.ErrChainUnavailable):
m.log.WarnContext(ctx, "delivery policy unavailable", "source", src.Name)
m.log.WarnContext(ctx, "delivery policy unavailable", "source", src.ID)
return admission{}, http.StatusServiceUnavailable, errDeliveryUnavailable
}
m.log.WarnContext(ctx, "refused delivery", "source", src.Name, "reason", "delivery policy", "level", d.Level, "policies", d.Policies)
m.log.WarnContext(ctx, "refused delivery", "source", src.ID, "reason", "delivery policy", "level", d.Level, "policies", d.Policies)
return admission{}, http.StatusForbidden, errDeliveryDenied
}
@@ -378,7 +380,7 @@ func (m *Module) save(ctx context.Context, adm admission, parsed []connectors.Ev
func (m *Module) Work(ctx context.Context) {
var listeners sync.WaitGroup
defer listeners.Wait()
listening := map[string]bool{}
listening := map[uuid.UUID]bool{}
nextCheck, nextTick := time.Time{}, time.Time{}
for ctx.Err() == nil {
if now := time.Now(); now.After(nextTick) {
@@ -407,7 +409,7 @@ func (m *Module) Work(ctx context.Context) {
// startListeners starts one listener for each source whose connector listens
// and has none yet. A listener lives until ctx ends.
func (m *Module) startListeners(ctx context.Context, wg *sync.WaitGroup, listening map[string]bool) {
func (m *Module) startListeners(ctx context.Context, wg *sync.WaitGroup, listening map[uuid.UUID]bool) {
sources, err := m.store.Sources(ctx, m.orgID)
if err != nil {
m.log.ErrorContext(ctx, "list sources", "error", err)
@@ -415,10 +417,10 @@ func (m *Module) startListeners(ctx context.Context, wg *sync.WaitGroup, listeni
}
for _, src := range sources {
conn, ok := m.connectors.Get(src.Connector)
if listening[src.Name] || !ok || !conn.Listens() {
if listening[src.ID] || !ok || !conn.Listens() {
continue
}
listening[src.Name] = true
listening[src.ID] = true
wg.Go(func() { m.listen(ctx, src) })
}
}
@@ -445,7 +447,7 @@ func (m *Module) listen(ctx context.Context, src store.Source) {
if ctx.Err() != nil {
return
}
m.log.WarnContext(ctx, "listening stopped", "source", src.Name, "error", err)
m.log.WarnContext(ctx, "listening stopped", "source", src.ID, "error", err)
select {
case <-ctx.Done():
case <-time.After(listenRetry):
@@ -458,7 +460,7 @@ func (m *Module) listenBatch(ctx context.Context, src store.Source, events []con
if err := m.storeListened(ctx, src, events); err != nil {
return err
}
return m.store.SetCursor(ctx, m.orgID, src.Name, next)
return m.store.SetCursor(ctx, m.orgID, src.ID, next)
}
// storeListened stores a batch streamed by a connector listener if the source's
@@ -497,7 +499,7 @@ func (m *Module) answer(ctx context.Context, e store.Event) error {
if !ok {
return nil
}
settled, err := m.answers.Settle(ctx, a.RequestID, who, e.Source, a.Approved)
settled, err := m.answers.Settle(ctx, a.RequestID, who, src.Connector, a.Approved)
if errors.Is(err, approvals.ErrUnlinked) {
m.replyUnlinked(ctx, e, src, a.ChatID)
return nil
@@ -548,14 +550,18 @@ func (m *Module) link(ctx context.Context, e store.Event) error {
// source, so a connector can only speak for its own accounts: by must name the
// source's connector.
func (m *Module) sender(ctx context.Context, e store.Event, by string) (store.Source, governance.Subject, bool) {
src, err := m.reader.Source(ctx, e.OrgID, e.Source)
if !e.SourceID.Valid {
m.log.WarnContext(ctx, "channel event from no source", "event", e.ID)
return store.Source{}, governance.Subject{}, false
}
src, err := m.reader.Source(ctx, e.OrgID, e.SourceID.UUID)
if err != nil {
m.log.WarnContext(ctx, "channel event from an unknown source", "event", e.ID, "source", e.Source, "error", err)
m.log.WarnContext(ctx, "channel event from an unknown source", "event", e.ID, "source", e.SourceID.UUID, "error", err)
return store.Source{}, governance.Subject{}, false
}
prefix, subject, found := strings.Cut(by, ":")
if !found || prefix != src.Connector || subject == "" {
m.log.WarnContext(ctx, "channel event names a sender outside its connector", "event", e.ID, "source", e.Source)
m.log.WarnContext(ctx, "channel event names a sender outside its connector", "event", e.ID, "source", e.SourceID.UUID)
return store.Source{}, governance.Subject{}, false
}
return src, governance.Subject{Issuer: src.Connector, Subject: subject}, true
@@ -604,7 +610,7 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) {
if err != nil || linked {
return false, err
}
triggers, err := store.Triggers(ctx, tx, e.OrgID, e.Source, e.Type, e.EventTypeID)
triggers, err := store.Triggers(ctx, tx, e.OrgID, e.SourceID, e.Type, e.EventTypeID)
if err != nil {
return false, err
}
@@ -696,7 +702,7 @@ func (m *Module) noteUnmatched(ctx context.Context, tx *sqlx.Tx, e store.Event)
return err
}
if created {
m.log.InfoContext(ctx, "unmatched events started a group", "source", e.Source, "type", e.Type)
m.log.InfoContext(ctx, "unmatched events started a group", "source", e.SourceID.UUID, "type", e.Type)
}
return nil
}
@@ -733,7 +739,7 @@ func (m *Module) Origin(ctx context.Context, runID uuid.UUID) (runs.Origin, bool
return runs.Origin{}, ok, err
}
return runs.Origin{
EventID: o.EventID, Source: o.Source, Type: o.Type, Fields: o.Fields,
EventID: o.EventID, SourceID: o.SourceID.UUID, Source: o.Source, Type: o.Type, Fields: o.Fields,
ReceivedAt: o.ReceivedAt, Trigger: o.Trigger, Filter: o.Filter,
}, true, nil
}
@@ -746,7 +752,7 @@ func runInput(e store.Event) jsontext.Value {
// payload under "mapped" when there are any.
func runInputWith(e store.Event, mapped map[string]any) jsontext.Value {
doc := map[string]any{"event": map[string]any{
"id": e.ID, "source": e.Source, "type": e.Type, "fields": e.Fields, "occurred_at": e.OccurredAt.Time,
"id": e.ID, "source_id": e.SourceID.UUID, "type": e.Type, "fields": e.Fields, "occurred_at": e.OccurredAt.Time,
}}
if mapped != nil {
doc["mapped"] = mapped
+4 -4
View File
@@ -24,7 +24,7 @@ var defaultKeyFields = []string{"alertname", "name", "labels", "severity", "serv
// groupKey is the identity events of one kind share: source, type and the
// values at keyFields. It also returns those values as the filter of the
// trigger the group proposes.
func groupKey(source, eventType string, fields jsontext.Value, keyFields []string) (string, map[string]string) {
func groupKey(sourceID uuid.UUID, eventType string, fields jsontext.Value, keyFields []string) (string, map[string]string) {
if len(keyFields) == 0 {
keyFields = defaultKeyFields
}
@@ -35,7 +35,7 @@ func groupKey(source, eventType string, fields jsontext.Value, keyFields []strin
}
slices.Sort(paths)
var b strings.Builder
b.WriteString(source + "\x00" + eventType)
b.WriteString(sourceID.String() + "\x00" + eventType)
for _, p := range paths {
b.WriteString("\x00" + p + "=" + filter[p])
}
@@ -59,7 +59,7 @@ func keyPaths(src store.Source) []string {
// fixed here, once, from the source's key fields.
func newRow(orgID string, src store.Source, e connectors.Event, body []byte, own bool, runID uuid.UUID) store.Event {
row := store.Event{
ID: uuid.New(), OrgID: orgID, Source: src.Name, Type: e.Type, SourceEventID: e.SourceEventID,
ID: uuid.New(), OrgID: orgID, SourceID: uuid.NullUUID{UUID: src.ID, Valid: true}, Type: e.Type, SourceEventID: e.SourceEventID,
Fields: e.Fields, Body: body, Own: own,
}
row.LinkKey.String, row.LinkKey.Valid = e.LinkKey, e.LinkKey != ""
@@ -68,7 +68,7 @@ func newRow(orgID string, src store.Source, e connectors.Event, body []byte, own
row.OriginRunID = uuid.NullUUID{UUID: runID, Valid: runID != uuid.Nil}
return row
}
key, filter := groupKey(src.Name, e.Type, e.Fields, keyPaths(src))
key, filter := groupKey(src.ID, e.Type, e.Fields, keyPaths(src))
// A map of strings always encodes.
raw, _ := json.Marshal(filter)
row.GroupKey = sql.NullString{String: key, Valid: true}
+1 -1
View File
@@ -13,7 +13,7 @@ import (
// carries a group key, so it can't become a proposal, and events differing
// only outside the key fields share one key.
func TestNewRowGrouping(t *testing.T) {
src := store.Source{Name: "alerts", KeyFields: []byte(`["alertname","labels"]`)}
src := store.Source{ID: hookID, KeyFields: []byte(`["alertname","labels"]`)}
run := uuid.New()
ev := func(fields string) connectors.Event {
return connectors.Event{Type: "alert.firing", SourceEventID: fields, Fields: []byte(fields)}
+10 -10
View File
@@ -51,11 +51,11 @@ type Rule struct {
// 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"`
ID string `json:"id"`
SourceID string `json:"source_id"`
Name string `json:"name"`
Rule Rule `json:"rule"`
Schema map[string]ValueType `json:"schema"`
}
// Validate refuses an event type that has no name or source or carries a
@@ -64,8 +64,8 @@ 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)
if strings.TrimSpace(t.SourceID) == "" {
return fmt.Errorf("%w: source id is required", ErrInvalid)
}
for _, h := range t.Rule.Headers {
if strings.TrimSpace(h.Name) == "" {
@@ -154,7 +154,7 @@ func Overlaps(a, b Rule) bool {
// 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) {
if t.SourceID != candidate.SourceID || (candidate.ID != "" && t.ID == candidate.ID) {
continue
}
if Overlaps(t.Rule, candidate.Rule) {
@@ -169,7 +169,7 @@ func CheckOverlap(existing []EventType, candidate EventType) error {
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) {
if t.SourceID == source && t.Rule.Matches(s) {
found = append(found, t)
}
}
@@ -184,7 +184,7 @@ func Identify(types []EventType, source string, s Sample) (EventType, bool) {
// 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 := EventType{SourceID: 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)) {
+6 -6
View File
@@ -10,7 +10,7 @@ import (
// Capture is one stored event as proposal grouping reads it.
type Capture struct {
ID string
Source string
SourceID string
ReceivedAt time.Time
Sample Sample
}
@@ -19,7 +19,7 @@ type Capture struct {
// 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"`
SourceID string `json:"source_id"`
Key string `json:"key"`
Schema map[string]ValueType `json:"schema"`
Headers map[string]string `json:"headers"`
@@ -38,18 +38,18 @@ func Propose(captures []Capture) []Proposal {
for _, c := range captures {
sig := Sign(c.Sample)
key := sig.Key()
id := c.Source + "\x00" + key
id := c.SourceID + "\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}
g := &Proposal{SourceID: c.SourceID, 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 {
if c := strings.Compare(a.SourceID, b.SourceID); c != 0 {
return c
}
return b.Count - a.Count
@@ -58,7 +58,7 @@ func Propose(captures []Capture) []Proposal {
for _, g := range groups {
var siblings []Signature
for _, s := range groups {
if s != g && s.Source == g.Source {
if s != g && s.SourceID == g.SourceID {
siblings = append(siblings, sigs[s])
}
}
+1 -1
View File
@@ -54,7 +54,7 @@ type Field struct {
type Mapping struct {
ID string `json:"id"`
Name string `json:"name"`
SourceHint string `json:"source_hint"`
SourceID string `json:"source_id"`
EventTypeID string `json:"event_type_id"`
Fields []Field `json:"fields"`
MatchCount int64 `json:"match_count"`
+70 -44
View File
@@ -19,6 +19,13 @@ var ErrInUse = errors.New("in use")
// ErrExists means a row with that name already exists.
var ErrExists = errors.New("already exists")
// ErrLabelTaken and ErrPathTaken mean another source of the same scope has the
// label, or another source has the webhook path.
var (
ErrLabelTaken = errors.New("a source with that label already exists")
ErrPathTaken = errors.New("a source with that webhook path already exists")
)
// Postgres reports a delete blocked by ON DELETE RESTRICT as 23001 and a
// reference to a missing row as 23503.
const (
@@ -41,16 +48,28 @@ func classify(err error) error {
return err
}
// classifySource turns a unique violation on a source's label or webhook path
// into its sentinel.
func classifySource(err error) error {
if pqErr, ok := errors.AsType[*pgconn.PgError](err); ok && pqErr.Code == uniqueViolation {
if pqErr.ConstraintName == "sources_webhook_path_key" {
return ErrPathTaken
}
return ErrLabelTaken
}
return err
}
// Captures returns the events whose source kept their headers and payload,
// newest first.
func (s *Store) Captures(ctx context.Context, orgID string, limit int) ([]Event, error) {
// newest first, for the sources the person may see.
func (s *Store) Captures(ctx context.Context, orgID, person string, limit int) ([]Event, error) {
var out []Event
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, source, type, source_event_id, fields, body, headers, remote_addr, verification,
SELECT id, org_id, source_id, type, source_event_id, fields, body, headers, remote_addr, verification,
event_type_id, received_at, occurred_at
FROM events.events
WHERE org_id = $1 AND headers IS NOT NULL
ORDER BY received_at DESC, id LIMIT $2`, orgID, limit); err != nil {
WHERE org_id = $1 AND headers IS NOT NULL AND `+visibleSource+`
ORDER BY received_at DESC, id LIMIT $3`, orgID, person, limit); err != nil {
return nil, fmt.Errorf("list captures: %w", err)
}
return out, nil
@@ -60,7 +79,7 @@ func (s *Store) Captures(ctx context.Context, orgID string, limit int) ([]Event,
type EventType struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
Source string `db:"source"`
SourceID uuid.UUID `db:"source_id"`
Name string `db:"name"`
Rule jsontext.Value `db:"rule"`
Schema jsontext.Value `db:"schema"`
@@ -68,23 +87,24 @@ type EventType struct {
UpdatedAt time.Time `db:"updated_at"`
}
// EventTypes returns the organisation's event types, by source and name.
func (s *Store) EventTypes(ctx context.Context, orgID string) ([]EventType, error) {
// EventTypes returns the event types of the sources the person may see, by
// source and name.
func (s *Store) EventTypes(ctx context.Context, orgID, person string) ([]EventType, error) {
var out []EventType
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, source, name, rule, schema, created_at, updated_at
FROM events.event_types WHERE org_id = $1 ORDER BY source, name`, orgID); err != nil {
SELECT id, org_id, source_id, name, rule, schema, created_at, updated_at
FROM events.event_types WHERE org_id = $1 AND `+visibleSource+` ORDER BY source_id, name`, orgID, person); err != nil {
return nil, fmt.Errorf("list event types: %w", err)
}
return out, nil
}
// EventTypesOf returns the event types of one source.
func (s *Store) EventTypesOf(ctx context.Context, orgID, source string) ([]EventType, error) {
func (s *Store) EventTypesOf(ctx context.Context, orgID string, sourceID uuid.UUID) ([]EventType, error) {
var out []EventType
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, source, name, rule, schema, created_at, updated_at
FROM events.event_types WHERE org_id = $1 AND source = $2 ORDER BY name`, orgID, source); err != nil {
SELECT id, org_id, source_id, name, rule, schema, created_at, updated_at
FROM events.event_types WHERE org_id = $1 AND source_id = $2 ORDER BY name`, orgID, sourceID); err != nil {
return nil, fmt.Errorf("list event types of source: %w", err)
}
return out, nil
@@ -94,7 +114,7 @@ func (s *Store) EventTypesOf(ctx context.Context, orgID, source string) ([]Event
func (s *Store) EventType(ctx context.Context, orgID string, id uuid.UUID) (EventType, error) {
var t EventType
err := s.db.GetContext(ctx, &t, `
SELECT id, org_id, source, name, rule, schema, created_at, updated_at
SELECT id, org_id, source_id, name, rule, schema, created_at, updated_at
FROM events.event_types WHERE org_id = $1 AND id = $2`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return EventType{}, ErrNotFound
@@ -108,8 +128,8 @@ func (s *Store) EventType(ctx context.Context, orgID string, id uuid.UUID) (Even
// InsertEventType stores a new event type.
func (s *Store) InsertEventType(ctx context.Context, t EventType) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO events.event_types (id, org_id, source, name, rule, schema)
VALUES (:id, :org_id, :source, :name, :rule, :schema)`, t); err != nil {
INSERT INTO events.event_types (id, org_id, source_id, name, rule, schema)
VALUES (:id, :org_id, :source_id, :name, :rule, :schema)`, t); err != nil {
return fmt.Errorf("save event type: %w", classify(err))
}
return nil
@@ -148,7 +168,7 @@ type Mapping struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
Name string `db:"name"`
SourceHint string `db:"source_hint"`
SourceID uuid.NullUUID `db:"source_id"`
EventTypeID uuid.UUID `db:"event_type_id"`
Fields jsontext.Value `db:"fields"`
MatchCount int64 `db:"match_count"`
@@ -157,7 +177,7 @@ type Mapping struct {
UpdatedAt time.Time `db:"updated_at"`
}
const mappingColumns = `id, org_id, name, source_hint, event_type_id, fields, match_count, last_matched_at, created_at, updated_at`
const mappingColumns = `id, org_id, name, source_id, event_type_id, fields, match_count, last_matched_at, created_at, updated_at`
// Mappings returns the organisation's mappings, by name.
func (s *Store) Mappings(ctx context.Context, orgID string) ([]Mapping, error) {
@@ -193,8 +213,8 @@ func MappingIn(ctx context.Context, tx *sqlx.Tx, orgID string, id uuid.UUID) (Ma
// InsertMapping stores a new mapping.
func (s *Store) InsertMapping(ctx context.Context, m Mapping) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO events.mappings (id, org_id, name, source_hint, event_type_id, fields)
VALUES (:id, :org_id, :name, :source_hint, :event_type_id, :fields)`, m); err != nil {
INSERT INTO events.mappings (id, org_id, name, source_id, event_type_id, fields)
VALUES (:id, :org_id, :name, :source_id, :event_type_id, :fields)`, m); err != nil {
return fmt.Errorf("save mapping: %w", classify(err))
}
return nil
@@ -204,7 +224,7 @@ func (s *Store) InsertMapping(ctx context.Context, m Mapping) error {
// count is kept.
func (s *Store) UpdateMapping(ctx context.Context, m Mapping) error {
res, err := s.db.NamedExecContext(ctx, `
UPDATE events.mappings SET name = :name, source_hint = :source_hint, event_type_id = :event_type_id,
UPDATE events.mappings SET name = :name, source_id = :source_id, event_type_id = :event_type_id,
fields = :fields, updated_at = now()
WHERE org_id = :org_id AND id = :id`, m)
if err != nil {
@@ -247,12 +267,12 @@ func (s *Store) SetEventType(ctx context.Context, id, typeID uuid.UUID) error {
// SetSourceColumn changes one of a source's single-value settings. column is
// always a constant of this package.
func (s *Store) setSource(ctx context.Context, orgID, name, column string, value any) error {
func (s *Store) setSource(ctx context.Context, orgID string, id uuid.UUID, column string, value any) error {
res, err := s.db.ExecContext(ctx, `
UPDATE events.sources SET `+column+` = $3, updated_at = now() WHERE org_id = $1 AND name = $2`,
orgID, name, value)
UPDATE events.sources SET `+column+` = $3, updated_at = now() WHERE org_id = $1 AND id = $2`,
orgID, id, value)
if err != nil {
return fmt.Errorf("save source: %w", err)
return fmt.Errorf("save source: %w", classifySource(err))
}
if n, err := res.RowsAffected(); err != nil || n == 0 {
return ErrNotFound
@@ -260,38 +280,44 @@ func (s *Store) setSource(ctx context.Context, orgID, name, column string, value
return nil
}
// SetDisplayName labels a source.
func (s *Store) SetDisplayName(ctx context.Context, orgID, name, display string) error {
return s.setSource(ctx, orgID, name, "display_name", display)
// SetLabel renames a source. The label is unique within the source's scope.
func (s *Store) SetLabel(ctx context.Context, orgID string, id uuid.UUID, label string) error {
return s.setSource(ctx, orgID, id, "label", label)
}
// SetWebhookPath moves the address a source receives deliveries at. Stored
// events, event types and triggers refer to the source by id and are unaffected.
func (s *Store) SetWebhookPath(ctx context.Context, orgID string, id uuid.UUID, path string) error {
return s.setSource(ctx, orgID, id, "webhook_path", path)
}
// SetDeliveryHeader names the header a sender repeats on a delivery's retries.
func (s *Store) SetDeliveryHeader(ctx context.Context, orgID, name, header string) error {
return s.setSource(ctx, orgID, name, "delivery_header", header)
func (s *Store) SetDeliveryHeader(ctx context.Context, orgID string, id uuid.UUID, header string) error {
return s.setSource(ctx, orgID, id, "delivery_header", header)
}
// SetCapture turns the keeping of a source's headers and payloads on or off.
func (s *Store) SetCapture(ctx context.Context, orgID, name string, capture bool) error {
return s.setSource(ctx, orgID, name, "capture", capture)
func (s *Store) SetCapture(ctx context.Context, orgID string, id uuid.UUID, capture bool) error {
return s.setSource(ctx, orgID, id, "capture", capture)
}
// SetSecret replaces a source's sealed signing secret.
func (s *Store) SetSecret(ctx context.Context, orgID, name string, sealed []byte) error {
return s.setSource(ctx, orgID, name, "hmac_secret_sealed", sealed)
func (s *Store) SetSecret(ctx context.Context, orgID string, id uuid.UUID, sealed []byte) error {
return s.setSource(ctx, orgID, id, "hmac_secret_sealed", sealed)
}
// SetSigning switches a source between an HMAC signature and no verification.
// Turning signing off leaves the source unapproved, so it refuses deliveries
// until a person approves it; the signature header and secret are kept so
// signing can be required again.
func (s *Store) SetSigning(ctx context.Context, orgID, name string, signed bool) error {
func (s *Store) SetSigning(ctx context.Context, orgID string, id uuid.UUID, signed bool) error {
verification := None
if signed {
verification = HMAC
}
res, err := s.db.ExecContext(ctx, `
UPDATE events.sources SET verification = $3, unsigned_approved = false, updated_at = now()
WHERE org_id = $1 AND name = $2`, orgID, name, verification)
WHERE org_id = $1 AND id = $2`, orgID, id, verification)
if err != nil {
return fmt.Errorf("save source: %w", err)
}
@@ -303,10 +329,10 @@ func (s *Store) SetSigning(ctx context.Context, orgID, name string, signed bool)
// ApproveUnsigned accepts that a source with no verification takes
// deliveries. It reports false when the source isn't waiting for approval.
func (s *Store) ApproveUnsigned(ctx context.Context, orgID, name string) (bool, error) {
func (s *Store) ApproveUnsigned(ctx context.Context, orgID string, id uuid.UUID) (bool, error) {
res, err := s.db.ExecContext(ctx, `
UPDATE events.sources SET unsigned_approved = true, updated_at = now()
WHERE org_id = $1 AND name = $2 AND verification = 'none' AND NOT unsigned_approved`, orgID, name)
WHERE org_id = $1 AND id = $2 AND verification = 'none' AND NOT unsigned_approved`, orgID, id)
if err != nil {
return false, fmt.Errorf("approve source: %w", err)
}
@@ -317,23 +343,23 @@ func (s *Store) ApproveUnsigned(ctx context.Context, orgID, name string) (bool,
// DeleteSource removes a source and its event types. A trigger or a mapping
// that still uses it blocks the delete; stored events and their dispatch
// history stay.
func (s *Store) DeleteSource(ctx context.Context, orgID, name string) error {
func (s *Store) DeleteSource(ctx context.Context, orgID string, id uuid.UUID) error {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("begin delete source: %w", err)
}
defer func() { _ = tx.Rollback() }()
var triggers int
if err := tx.GetContext(ctx, &triggers, `SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source = $2`, orgID, name); err != nil {
if err := tx.GetContext(ctx, &triggers, `SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source_id = $2`, orgID, id); err != nil {
return fmt.Errorf("check triggers of source: %w", err)
}
if triggers > 0 {
return fmt.Errorf("%w: %d trigger(s) use it", ErrInUse, triggers)
}
if _, err := tx.ExecContext(ctx, `DELETE FROM events.event_types WHERE org_id = $1 AND source = $2`, orgID, name); err != nil {
if _, err := tx.ExecContext(ctx, `DELETE FROM events.event_types WHERE org_id = $1 AND source_id = $2`, orgID, id); err != nil {
return fmt.Errorf("delete event types of source: %w", classify(err))
}
res, err := tx.ExecContext(ctx, `DELETE FROM events.sources WHERE org_id = $1 AND name = $2`, orgID, name)
res, err := tx.ExecContext(ctx, `DELETE FROM events.sources WHERE org_id = $1 AND id = $2`, orgID, id)
if err != nil {
return fmt.Errorf("delete source: %w", err)
}
@@ -348,10 +374,10 @@ func (s *Store) DeleteSource(ctx context.Context, orgID, name string) error {
// MappedTriggers counts the triggers of a source that read events with a
// mapping, which needs the stored payload.
func (s *Store) MappedTriggers(ctx context.Context, orgID, source string) (int, error) {
func (s *Store) MappedTriggers(ctx context.Context, orgID string, sourceID uuid.UUID) (int, error) {
var n int
if err := s.db.GetContext(ctx, &n, `
SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source = $2 AND mapping_id IS NOT NULL`, orgID, source); err != nil {
SELECT count(*) FROM events.triggers WHERE org_id = $1 AND source_id = $2 AND mapping_id IS NOT NULL`, orgID, sourceID); err != nil {
return 0, fmt.Errorf("count mapped triggers: %w", err)
}
return n, nil
+2 -2
View File
@@ -13,7 +13,7 @@ import (
func (s *Store) GroupByID(ctx context.Context, orgID string, id uuid.UUID) (Group, bool, error) {
var g Group
err := s.db.GetContext(ctx, &g, `
SELECT id, source, event_type, filter, count, first_seen, last_seen
SELECT id, source_id, event_type, filter, count, first_seen, last_seen
FROM events.groups WHERE org_id = $1 AND id = $2`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return Group{}, false, nil
@@ -28,7 +28,7 @@ func (s *Store) GroupByID(ctx context.Context, orgID string, id uuid.UUID) (Grou
func (s *Store) GroupEvents(ctx context.Context, orgID string, id uuid.UUID, limit int) ([]Event, error) {
var out []Event
if err := s.db.SelectContext(ctx, &out, `
SELECT e.id, e.org_id, e.source, e.type, e.source_event_id, e.link_key, e.linked_to, e.fields, e.occurred_at,
SELECT e.id, e.org_id, e.source_id, e.type, e.source_event_id, e.link_key, e.linked_to, e.fields, e.occurred_at,
e.received_at, e.matched, e.dispatched_at, e.own, e.origin_run_id, e.group_key, e.group_filter
FROM events.events e
JOIN events.groups g ON g.org_id = e.org_id AND g.key = e.group_key
+15 -14
View File
@@ -11,10 +11,10 @@ import (
)
// SetKeyFields replaces the paths a source's events are grouped by.
func (s *Store) SetKeyFields(ctx context.Context, orgID, name string, paths jsontext.Value) error {
func (s *Store) SetKeyFields(ctx context.Context, orgID string, id uuid.UUID, paths jsontext.Value) error {
res, err := s.db.ExecContext(ctx, `
UPDATE events.sources SET key_fields = $3, updated_at = now() WHERE org_id = $1 AND name = $2`,
orgID, name, paths)
UPDATE events.sources SET key_fields = $3, updated_at = now() WHERE org_id = $1 AND id = $2`,
orgID, id, paths)
if err != nil {
return fmt.Errorf("save key fields: %w", err)
}
@@ -28,7 +28,7 @@ func (s *Store) SetKeyFields(ctx context.Context, orgID, name string, paths json
// and filter are the trigger it proposes.
type Group struct {
ID uuid.UUID `db:"id"`
Source string `db:"source"`
SourceID uuid.UUID `db:"source_id"`
EventType string `db:"event_type"`
Filter jsontext.Value `db:"filter"`
Count int64 `db:"count"`
@@ -40,37 +40,38 @@ type Group struct {
// starting the group if it is the first, and reports whether it did. An event
// with no key (a schedule tick, which has none to give) is left out.
func NoteUnmatched(ctx context.Context, tx *sqlx.Tx, e Event) (bool, error) {
if !e.GroupKey.Valid {
if !e.GroupKey.Valid || !e.SourceID.Valid {
return false, nil
}
var created bool
err := tx.QueryRowxContext(ctx, `
INSERT INTO events.groups (id, org_id, key, source, event_type, filter, count, first_seen, last_seen)
INSERT INTO events.groups (id, org_id, key, source_id, event_type, filter, count, first_seen, last_seen)
VALUES ($1, $2, $3, $4, $5, $6, 1, $7, $7)
ON CONFLICT (org_id, key) DO UPDATE
SET count = events.groups.count + 1,
first_seen = LEAST(events.groups.first_seen, EXCLUDED.first_seen),
last_seen = GREATEST(events.groups.last_seen, EXCLUDED.last_seen)
RETURNING xmax = 0`,
uuid.New(), e.OrgID, e.GroupKey.String, e.Source, e.Type, e.GroupFilter, e.ReceivedAt).Scan(&created)
uuid.New(), e.OrgID, e.GroupKey.String, e.SourceID.UUID, e.Type, e.GroupFilter, e.ReceivedAt).Scan(&created)
if err != nil {
return false, fmt.Errorf("group event: %w", err)
}
return created, nil
}
// Groups returns the groups no trigger covers, newest activity first. A group
// stops being listed once a trigger exists for its source, type and filter.
func (s *Store) Groups(ctx context.Context, orgID string, limit int) ([]Group, error) {
// Groups returns the groups no trigger covers, newest activity first, for the
// sources the person may see. A group stops being listed once a trigger exists
// for its source, type and filter.
func (s *Store) Groups(ctx context.Context, orgID, person string, limit int) ([]Group, error) {
var out []Group
if err := s.db.SelectContext(ctx, &out, `
SELECT g.id, g.source, g.event_type, g.filter, g.count, g.first_seen, g.last_seen
SELECT g.id, g.source_id, g.event_type, g.filter, g.count, g.first_seen, g.last_seen
FROM events.groups g
WHERE g.org_id = $1 AND NOT EXISTS (
WHERE g.org_id = $1 AND `+visibleSource+` AND NOT EXISTS (
SELECT 1 FROM events.triggers t
WHERE t.org_id = g.org_id AND t.source = g.source AND t.event_type = g.event_type
WHERE t.org_id = g.org_id AND t.source_id = g.source_id AND t.event_type = g.event_type
AND t.filter = g.filter)
ORDER BY g.last_seen DESC LIMIT $2`, orgID, limit); err != nil {
ORDER BY g.last_seen DESC LIMIT $3`, orgID, person, limit); err != nil {
return nil, fmt.Errorf("list groups: %w", err)
}
return out, nil
+148 -72
View File
@@ -25,10 +25,26 @@ const (
None = "none"
)
// Source is a named place events come from, read by one connector.
// Scopes a source can be owned by.
const (
ScopeOrg = "org"
ScopePerson = "person"
)
// Source is a place events come from, read by one connector. It is owned by a
// scope: the organisation, or one person acting in it. Everything stored about
// it refers to ID, so the label and the webhook path can change.
type Source struct {
OrgID string `db:"org_id"`
Name string `db:"name"`
ID uuid.UUID `db:"id"`
Scope string `db:"scope"`
OrgID string `db:"org_id"`
// PersonID is the owning person of a person source, null for an
// organisation's.
PersonID sql.NullString `db:"person_id"`
// Label is the name people see, unique within the scope. WebhookPath is the
// last segment of the URL deliveries post to, unique across the instance.
Label string `db:"label"`
WebhookPath string `db:"webhook_path"`
Connector string `db:"connector"`
TokenSHA256 string `db:"token_sha256"`
// Verification is the scheme that deliveries must pass: Token, HMAC or None.
@@ -43,9 +59,8 @@ type Source struct {
Cursor string `db:"cursor"`
// KeyFields are the paths its events are grouped by; none means the default.
KeyFields jsontext.Value `db:"key_fields"`
// DisplayName labels the source for people. DeliveryHeader names the header
// a sender repeats on every retry of one delivery.
DisplayName string `db:"display_name"`
// DeliveryHeader names the header a sender repeats on every retry of one
// delivery.
DeliveryHeader string `db:"delivery_header"`
// UnsignedApproved says a person accepted that a None source does no
// verification. A None source refuses deliveries until then.
@@ -54,11 +69,19 @@ type Source struct {
Capture bool `db:"capture"`
}
// VisibleTo reports whether the person may see and use the source: an
// organisation's source belongs to every member, a person's only to that person.
func (s Source) VisibleTo(person string) bool {
return !s.PersonID.Valid || s.PersonID.String == person
}
// Event is one stored event.
type Event struct {
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
Source string `db:"source"`
ID uuid.UUID `db:"id"`
OrgID string `db:"org_id"`
// SourceID is null for a schedule tick, and for an event whose source was
// deleted.
SourceID uuid.NullUUID `db:"source_id"`
Type string `db:"type"`
SourceEventID string `db:"source_event_id"`
LinkKey sql.NullString `db:"link_key"`
@@ -101,9 +124,10 @@ const (
// Trigger starts a workflow for events of one type from one source whose
// fields match its filter.
type Trigger struct {
OrgID string `db:"org_id"`
Name string `db:"name"`
Source string `db:"source"`
OrgID string `db:"org_id"`
Name string `db:"name"`
// SourceID is null for a scheduled trigger, which has no source.
SourceID uuid.NullUUID `db:"source_id"`
EventType string `db:"event_type"`
Filter jsontext.Value `db:"filter"`
Workflow string `db:"workflow"`
@@ -129,13 +153,14 @@ type Store struct {
// New returns a store on db.
func New(db *sqlx.DB) *Store { return &Store{db: db} }
// Source returns the named source.
func (s *Store) Source(ctx context.Context, orgID, name string) (Source, error) {
const sourceColumns = `id, scope, org_id, person_id, label, webhook_path, connector, token_sha256, verification,
hmac_header, hmac_prefix, hmac_secret_sealed, cursor, key_fields, delivery_header, unsigned_approved, capture`
// Source returns one source of the organisation, whoever owns it. Callers that
// act for a person check Source.VisibleTo.
func (s *Store) Source(ctx context.Context, orgID string, id uuid.UUID) (Source, error) {
var src Source
err := s.db.GetContext(ctx, &src, `
SELECT org_id, name, connector, token_sha256, verification, hmac_header, hmac_prefix, hmac_secret_sealed, key_fields,
display_name, delivery_header, unsigned_approved, capture FROM events.sources
WHERE org_id = $1 AND name = $2`, orgID, name)
err := s.db.GetContext(ctx, &src, `SELECT `+sourceColumns+` FROM events.sources WHERE org_id = $1 AND id = $2`, orgID, id)
if errors.Is(err, sql.ErrNoRows) {
return Source{}, ErrNotFound
}
@@ -145,56 +170,97 @@ func (s *Store) Source(ctx context.Context, orgID, name string) (Source, error)
return src, nil
}
// Sources returns every source of the organisation.
// SourceByPath returns the source a webhook path addresses.
func (s *Store) SourceByPath(ctx context.Context, orgID, path string) (Source, error) {
var src Source
err := s.db.GetContext(ctx, &src, `SELECT `+sourceColumns+` FROM events.sources WHERE org_id = $1 AND webhook_path = $2`, orgID, path)
if errors.Is(err, sql.ErrNoRows) {
return Source{}, ErrNotFound
}
if err != nil {
return Source{}, fmt.Errorf("read source: %w", err)
}
return src, nil
}
// Sources returns every source of the organisation, for the work that runs on
// behalf of no person.
func (s *Store) Sources(ctx context.Context, orgID string) ([]Source, error) {
var out []Source
if err := s.db.SelectContext(ctx, &out, `SELECT `+sourceColumns+` FROM events.sources WHERE org_id = $1 ORDER BY label`, orgID); err != nil {
return nil, fmt.Errorf("list sources: %w", err)
}
return out, nil
}
// SourcesFor returns the organisation's sources the person may see: the
// organisation's own and the person's.
func (s *Store) SourcesFor(ctx context.Context, orgID, person string) ([]Source, error) {
var out []Source
if err := s.db.SelectContext(ctx, &out, `
SELECT org_id, name, connector, token_sha256, verification, hmac_header, hmac_prefix, hmac_secret_sealed, cursor, key_fields,
display_name, delivery_header, unsigned_approved, capture FROM events.sources
WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
SELECT `+sourceColumns+` FROM events.sources
WHERE org_id = $1 AND (person_id IS NULL OR person_id = $2) ORDER BY label`, orgID, person); err != nil {
return nil, fmt.Errorf("list sources: %w", err)
}
return out, nil
}
// SetCursor records where a listening source resumes.
func (s *Store) SetCursor(ctx context.Context, orgID, name, cursor string) error {
func (s *Store) SetCursor(ctx context.Context, orgID string, id uuid.UUID, cursor string) error {
if _, err := s.db.ExecContext(ctx, `
UPDATE events.sources SET cursor = $3, updated_at = now() WHERE org_id = $1 AND name = $2`,
orgID, name, cursor); err != nil {
UPDATE events.sources SET cursor = $3, updated_at = now() WHERE org_id = $1 AND id = $2`,
orgID, id, cursor); err != nil {
return fmt.Errorf("save cursor: %w", err)
}
return nil
}
// UpsertSource creates a source or replaces its connector and token.
func (s *Store) UpsertSource(ctx context.Context, src Source) error {
// InsertSource stores a new source. It returns ErrLabelTaken or ErrPathTaken
// when the label or the webhook path is in use.
func (s *Store) InsertSource(ctx context.Context, src Source) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO events.sources (org_id, name, connector, token_sha256, verification, hmac_header, hmac_prefix, hmac_secret_sealed)
VALUES (:org_id, :name, :connector, :token_sha256, :verification, :hmac_header, :hmac_prefix, :hmac_secret_sealed)
ON CONFLICT (org_id, name) DO UPDATE
SET connector = EXCLUDED.connector, token_sha256 = EXCLUDED.token_sha256,
verification = EXCLUDED.verification, hmac_header = EXCLUDED.hmac_header,
hmac_prefix = EXCLUDED.hmac_prefix, hmac_secret_sealed = EXCLUDED.hmac_secret_sealed,
unsigned_approved = EXCLUDED.verification = 'none' AND events.sources.verification = 'none'
AND events.sources.unsigned_approved,
updated_at = now()`, src); err != nil {
return fmt.Errorf("save source: %w", err)
INSERT INTO events.sources (id, scope, org_id, person_id, label, webhook_path, connector, token_sha256,
verification, hmac_header, hmac_prefix, hmac_secret_sealed)
VALUES (:id, :scope, :org_id, :person_id, :label, :webhook_path, :connector, :token_sha256,
:verification, :hmac_header, :hmac_prefix, :hmac_secret_sealed)`, src); err != nil {
return fmt.Errorf("save source: %w", classifySource(err))
}
return nil
}
// UpdateSource replaces a source's connector and verification. Verification
// that is none stays approved only if it already was and was none before, so
// only ApproveUnsigned approves an unsigned source.
func (s *Store) UpdateSource(ctx context.Context, src Source) error {
res, err := s.db.NamedExecContext(ctx, `
UPDATE events.sources
SET connector = :connector, token_sha256 = :token_sha256,
verification = :verification, hmac_header = :hmac_header,
hmac_prefix = :hmac_prefix, hmac_secret_sealed = :hmac_secret_sealed,
unsigned_approved = :verification = 'none' AND verification = 'none' AND unsigned_approved,
updated_at = now()
WHERE org_id = :org_id AND id = :id`, src)
if err != nil {
return fmt.Errorf("save source: %w", classifySource(err))
}
if n, err := res.RowsAffected(); err != nil || n == 0 {
return ErrNotFound
}
return nil
}
// Insert stores an event unless its source already delivered the same source
// event id. It reports whether the event was new.
// event id, or a schedule already stored the same slot. It reports whether the
// event was new.
func (s *Store) Insert(ctx context.Context, e Event) (bool, error) {
res, err := s.db.NamedExecContext(ctx, `
INSERT INTO events.events (id, org_id, source, type, source_event_id, link_key, fields, body, occurred_at,
INSERT INTO events.events (id, org_id, source_id, type, source_event_id, link_key, fields, body, occurred_at,
own, origin_run_id, group_key, group_filter, verification, headers, remote_addr,
event_type_id)
VALUES (:id, :org_id, :source, :type, :source_event_id, :link_key, :fields, :body, :occurred_at,
VALUES (:id, :org_id, :source_id, :type, :source_event_id, :link_key, :fields, :body, :occurred_at,
:own, :origin_run_id, :group_key, :group_filter, :verification, :headers, :remote_addr,
:event_type_id)
ON CONFLICT (org_id, source, source_event_id) DO NOTHING`, e)
ON CONFLICT DO NOTHING`, e)
if err != nil {
return false, fmt.Errorf("store event: %w", err)
}
@@ -217,7 +283,7 @@ func (s *Store) Dispatch(ctx context.Context, fn func(tx *sqlx.Tx, e Event) (mat
defer func() { _ = tx.Rollback() }()
var e Event
err = tx.GetContext(ctx, &e, `
SELECT id, org_id, source, type, source_event_id, link_key, linked_to, fields, body, occurred_at,
SELECT id, org_id, source_id, type, source_event_id, link_key, linked_to, fields, body, occurred_at,
received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter, event_type_id
FROM events.events WHERE dispatched_at IS NULL
ORDER BY received_at FOR UPDATE SKIP LOCKED LIMIT 1`)
@@ -248,14 +314,14 @@ func Link(ctx context.Context, tx *sqlx.Tx, e Event) (bool, error) {
if !e.LinkKey.Valid {
return false, nil
}
const earlier = `org_id = $2 AND source = $3 AND link_key = $4 AND id <> $1
const earlier = `org_id = $2 AND source_id = $3 AND link_key = $4 AND id <> $1
AND (received_at, id) < ($5, $1)`
res, err := tx.ExecContext(ctx, `
UPDATE events.events SET linked_to = (
SELECT id FROM events.events WHERE `+earlier+`
ORDER BY received_at, id LIMIT 1)
WHERE id = $1 AND EXISTS (SELECT 1 FROM events.events WHERE `+earlier+`)`,
e.ID, e.OrgID, e.Source, e.LinkKey.String, e.ReceivedAt)
e.ID, e.OrgID, e.SourceID, e.LinkKey.String, e.ReceivedAt)
if err != nil {
return false, fmt.Errorf("link event: %w", err)
}
@@ -273,16 +339,17 @@ func SetEventPayload(ctx context.Context, tx *sqlx.Tx, e Event) error {
}
// Triggers returns the armed triggers that fire for one source and event type,
// and for the custom type the event was identified as, if any.
func Triggers(ctx context.Context, tx *sqlx.Tx, orgID, source, eventType string, typeID uuid.NullUUID) ([]Trigger, error) {
// and for the custom type the event was identified as, if any. A schedule tick
// has no source and matches the triggers that have none.
func Triggers(ctx context.Context, tx *sqlx.Tx, orgID string, sourceID uuid.NullUUID, eventType string, typeID uuid.NullUUID) ([]Trigger, error) {
var out []Trigger
if err := tx.SelectContext(ctx, &out, `
SELECT org_id, name, source, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id
SELECT org_id, name, source_id, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id
FROM events.triggers
WHERE org_id = $1 AND source = $2 AND (event_type = $3 OR event_type = '') AND enabled AND approved
WHERE org_id = $1 AND source_id IS NOT DISTINCT FROM $2 AND (event_type = $3 OR event_type = '') AND enabled AND approved
AND (event_type_id IS NULL OR event_type_id = $4)
ORDER BY name`,
orgID, source, eventType, typeID); err != nil {
orgID, sourceID, eventType, typeID); err != nil {
return nil, fmt.Errorf("read triggers: %w", err)
}
return out, nil
@@ -328,13 +395,13 @@ func RecordNoRun(ctx context.Context, tx *sqlx.Tx, eventID uuid.UUID, trigger, o
// UpsertTrigger creates or replaces a trigger.
func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
if _, err := s.db.NamedExecContext(ctx, `
INSERT INTO events.triggers (org_id, name, source, event_type, filter, workflow, enabled, approved,
INSERT INTO events.triggers (org_id, name, source_id, event_type, filter, workflow, enabled, approved,
event_type_id, mapping_id, schedule_every_s, schedule_since)
VALUES (:org_id, :name, :source, :event_type, :filter, :workflow, :enabled, :approved,
VALUES (:org_id, :name, :source_id, :event_type, :filter, :workflow, :enabled, :approved,
:event_type_id, :mapping_id,
CAST(:schedule_every_s AS integer), CASE WHEN CAST(:schedule_every_s AS integer) IS NULL THEN NULL ELSE now() END)
ON CONFLICT (org_id, name) DO UPDATE
SET source = EXCLUDED.source, event_type = EXCLUDED.event_type, filter = EXCLUDED.filter,
SET source_id = EXCLUDED.source_id, event_type = EXCLUDED.event_type, filter = EXCLUDED.filter,
workflow = EXCLUDED.workflow, enabled = EXCLUDED.enabled, approved = EXCLUDED.approved,
event_type_id = EXCLUDED.event_type_id, mapping_id = EXCLUDED.mapping_id,
schedule_since = CASE
@@ -352,7 +419,7 @@ func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
func (s *Store) ScheduledTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
var out []Trigger
if err := s.db.SelectContext(ctx, &out, `
SELECT org_id, name, source, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id,
SELECT org_id, name, source_id, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id,
schedule_every_s, schedule_since
FROM events.triggers
WHERE org_id = $1 AND enabled AND approved AND schedule_every_s IS NOT NULL ORDER BY name`, orgID); err != nil {
@@ -364,37 +431,44 @@ func (s *Store) ScheduledTriggers(ctx context.Context, orgID string) ([]Trigger,
// EventFilter narrows the events a list returns. A zero field doesn't filter,
// and Matched distinguishes events a trigger started a run for from the rest.
type EventFilter struct {
Source string
Type string
Matched *bool
Limit int
SourceID uuid.NullUUID
Type string
Matched *bool
Limit int
}
// Recent returns an organisation's newest events that match filter.
func (s *Store) Recent(ctx context.Context, orgID string, f EventFilter) ([]Event, error) {
// visibleSource holds for a row whose source the person in $2 may see: it has
// none, or the source is the organisation's or that person's.
const visibleSource = `(source_id IS NULL OR EXISTS (
SELECT 1 FROM events.sources vs WHERE vs.id = source_id AND (vs.person_id IS NULL OR vs.person_id = $2)))`
// Recent returns the newest events of an organisation that match filter and
// come from sources the person may see.
func (s *Store) Recent(ctx context.Context, orgID, person string, f EventFilter) ([]Event, error) {
var out []Event
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, source, type, source_event_id, link_key, linked_to, fields, occurred_at,
SELECT id, org_id, source_id, type, source_event_id, link_key, linked_to, fields, occurred_at,
received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter
FROM events.events
WHERE org_id = $1
AND ($2 = '' OR source = $2)
AND ($3 = '' OR type = $3)
AND ($4::boolean IS NULL OR matched = $4)
ORDER BY received_at DESC LIMIT $5`, orgID, f.Source, f.Type, f.Matched, f.Limit); err != nil {
WHERE org_id = $1 AND `+visibleSource+`
AND ($3::uuid IS NULL OR source_id = $3)
AND ($4 = '' OR type = $4)
AND ($5::boolean IS NULL OR matched = $5)
ORDER BY received_at DESC LIMIT $6`, orgID, person, f.SourceID, f.Type, f.Matched, f.Limit); err != nil {
return nil, fmt.Errorf("list events: %w", err)
}
return out, nil
}
// Event returns one event with the payload it arrived in.
func (s *Store) Event(ctx context.Context, orgID string, id uuid.UUID) (Event, error) {
// Event returns one event with the payload it arrived in, if it comes from a
// source the person may see.
func (s *Store) Event(ctx context.Context, orgID, person string, id uuid.UUID) (Event, error) {
var e Event
err := s.db.GetContext(ctx, &e, `
SELECT id, org_id, source, type, source_event_id, link_key, linked_to, fields, body, occurred_at,
SELECT id, org_id, source_id, type, source_event_id, link_key, linked_to, fields, body, occurred_at,
received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter,
verification, headers, remote_addr, event_type_id
FROM events.events WHERE org_id = $1 AND id = $2`, orgID, id)
FROM events.events WHERE org_id = $1 AND `+visibleSource+` AND id = $3`, orgID, person, id)
if errors.Is(err, sql.ErrNoRows) {
return Event{}, ErrNotFound
}
@@ -429,7 +503,7 @@ func (s *Store) RunsForEvent(ctx context.Context, orgID string, id uuid.UUID) ([
func (s *Store) AllTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
var out []Trigger
if err := s.db.SelectContext(ctx, &out, `
SELECT org_id, name, source, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id,
SELECT org_id, name, source_id, event_type, filter, workflow, enabled, approved, event_type_id, mapping_id,
schedule_every_s, schedule_since
FROM events.triggers WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
return nil, fmt.Errorf("list triggers: %w", err)
@@ -440,6 +514,7 @@ func (s *Store) AllTriggers(ctx context.Context, orgID string) ([]Trigger, error
// Origin is the event and trigger that started a run.
type Origin struct {
EventID uuid.UUID `db:"event_id"`
SourceID uuid.NullUUID `db:"source_id"`
Source string `db:"source"`
Type string `db:"type"`
Fields jsontext.Value `db:"fields"`
@@ -452,10 +527,11 @@ type Origin struct {
func (s *Store) OriginOf(ctx context.Context, orgID string, runID uuid.UUID) (Origin, bool, error) {
var o Origin
err := s.db.GetContext(ctx, &o, `
SELECT e.id AS event_id, e.source, e.type, e.fields, e.received_at, d.trigger,
COALESCE(t.filter, '{}') AS filter
SELECT e.id AS event_id, e.source_id, COALESCE(src.label, CASE WHEN e.type = 'schedule.tick' THEN 'schedule' ELSE '' END) AS source, e.type, e.fields,
e.received_at, d.trigger, COALESCE(t.filter, '{}') AS filter
FROM events.dispatches d
JOIN events.events e ON e.id = d.event_id
LEFT JOIN events.sources src ON src.id = e.source_id
LEFT JOIN events.triggers t ON t.org_id = e.org_id AND t.name = d.trigger
WHERE e.org_id = $1 AND d.run_id = $2`, orgID, runID)
if errors.Is(err, sql.ErrNoRows) {
+1 -1
View File
@@ -35,7 +35,7 @@ func TestListenedEventsPassTheDeliveryPolicyBeforeStoring(t *testing.T) {
if !tt.unwired {
m.UseDeliveryPolicy(policy)
}
src := store.Source{OrgID: "default", Name: "tg", Connector: "telegram"}
src := store.Source{ID: hookID, OrgID: "default", WebhookPath: "tg", Connector: "telegram"}
err := m.storeListened(t.Context(), src, []connectors.Event{{Type: "message", SourceEventID: "evt-1"}})
if (err != nil) != tt.wantErr {
t.Fatalf("error = %v, want error %v", err, tt.wantErr)
+53
View File
@@ -0,0 +1,53 @@
package events
import (
"database/sql"
"errors"
"testing"
"github.com/danielgtaylor/huma/v2"
"github.com/samcharles93/archie-core/modules/events/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
// TestPersonSourceIsUsableOnlyByItsOwner guards source scopes: an
// organisation's source is visible to every member, and a person's source reads
// as missing to everyone but that person, so its existence isn't disclosed and
// no one else can bind a trigger or event type to it.
func TestPersonSourceIsUsableOnlyByItsOwner(t *testing.T) {
person := func(id string) store.Source {
return store.Source{
ID: hookID, Scope: store.ScopePerson, OrgID: "org", Label: "mine",
PersonID: sql.NullString{String: id, Valid: true},
}
}
tests := []struct {
name string
src store.Source
caller governance.IdentityID
want bool
}{
{"an organisation source, any member", store.Source{ID: hookID, Scope: store.ScopeOrg, OrgID: "org", Label: "alerts"}, "bob", true},
{"a person source, its owner", person("alice"), "alice", true},
{"a person source, another member", person("alice"), "bob", false},
{"a person source, the system caller", person("alice"), governance.SystemID, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
m := &Module{orgID: "org", reader: fakeSources{tt.src}}
ctx := governance.WithPrincipal(t.Context(), governance.Principal{IdentityID: tt.caller})
if got, err := m.canUse(ctx, hookID); err != nil || got != tt.want {
t.Fatalf("canUse = %v, %v, want %v", got, err, tt.want)
}
_, err := m.readSource(ctx, hookID.String())
var refused *huma.ErrorModel
if tt.want && err != nil {
t.Fatalf("readSource: %v", err)
}
if !tt.want && (!errors.As(err, &refused) || refused.Status != 404) {
t.Fatalf("readSource error = %v, want a 404", err)
}
})
}
}
+4 -6
View File
@@ -12,11 +12,9 @@ import (
"github.com/samcharles93/archie-core/modules/events/internal/store"
)
// The source and type of the event a schedule stores for each slot.
const (
scheduleSource = "schedule"
scheduleType = "schedule.tick"
)
// scheduleType is the type of the event a schedule stores for each slot. The
// event has no source.
const scheduleType = "schedule.tick"
// minInterval keeps a schedule from firing faster than the dispatcher can use.
const minInterval = time.Minute
@@ -63,7 +61,7 @@ func (m *Module) tick(ctx context.Context, now time.Time) error {
func tickEvent(orgID, trigger string, slot time.Time, fields jsontext.Value) store.Event {
e := store.Event{
ID: uuid.New(), OrgID: orgID, Source: scheduleSource, Type: scheduleType,
ID: uuid.New(), OrgID: orgID, Type: scheduleType,
SourceEventID: trigger + "@" + slot.UTC().Format(time.RFC3339), Fields: fields,
}
e.OccurredAt.Time, e.OccurredAt.Valid = slot, true
+65
View File
@@ -0,0 +1,65 @@
package events
import (
"context"
"errors"
"fmt"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/events/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
// caller is the person a request acts for. A source owned by a person is
// visible only to that person.
func caller(ctx context.Context) string { return governance.CallerID(ctx) }
// labels maps the id of each source the caller may see to its label.
func (m *Module) labels(ctx context.Context) (map[uuid.UUID]string, error) {
sources, err := m.store.SourcesFor(ctx, m.orgID, caller(ctx))
if err != nil {
return nil, err
}
out := make(map[uuid.UUID]string, len(sources))
for _, src := range sources {
out[src.ID] = src.Label
}
return out, nil
}
// canUse reports whether the caller may use a source: it is the organisation's
// or the caller's own. A missing source can't be used.
func (m *Module) canUse(ctx context.Context, id uuid.UUID) (bool, error) {
src, err := m.reader.Source(ctx, m.orgID, id)
if errors.Is(err, store.ErrNotFound) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("read source: %w", err)
}
return src.VisibleTo(caller(ctx)), nil
}
// visibleTrigger reads a trigger the caller may see. A trigger on someone
// else's person source reads as missing.
func (m *Module) visibleTrigger(ctx context.Context, name string) (store.Trigger, error) {
t, err := m.store.Trigger(ctx, m.orgID, name)
if errors.Is(err, store.ErrNotFound) {
return t, huma.Error404NotFound("no such trigger")
}
if err != nil {
return t, huma.Error500InternalServerError("couldn't read the trigger", err)
}
if t.SourceID.Valid {
ok, err := m.canUse(ctx, t.SourceID.UUID)
if err != nil {
return t, huma.Error500InternalServerError("couldn't read the trigger", err)
}
if !ok {
return t, huma.Error404NotFound("no such trigger")
}
}
return t, nil
}
+8 -2
View File
@@ -5,13 +5,19 @@ import (
"log/slog"
"testing"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/events/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
type connectorSource struct{ src store.Source }
func (o connectorSource) Source(context.Context, string, string) (store.Source, error) {
func (o connectorSource) Source(context.Context, string, uuid.UUID) (store.Source, error) {
return o.src, nil
}
func (o connectorSource) SourceByPath(context.Context, string, string) (store.Source, error) {
return o.src, nil
}
@@ -34,7 +40,7 @@ func TestSenderMustBelongToTheSourcesConnector(t *testing.T) {
m := &Module{reader: connectorSource{store.Source{Connector: "telegram"}}, log: slog.New(slog.DiscardHandler)}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, got, ok := m.sender(t.Context(), store.Event{Source: "chat"}, tt.by)
_, got, ok := m.sender(t.Context(), store.Event{SourceID: uuid.NullUUID{UUID: hookID, Valid: true}}, tt.by)
if ok != tt.ok || got != tt.want {
t.Fatalf("sender = %v %v, want %v %v", got, ok, tt.want, tt.ok)
}
+5 -6
View File
@@ -34,12 +34,11 @@ func TestSavedSourceSecretIsSetOnlyForHMAC(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
in := &putSourceInput{Name: "hook"}
in.Body.Connector = "c"
in.Body.Verification = tt.verify
in.Body.HMACHeader = "X-Signature"
in.Body.HMACSecret = "not-a-real-secret" //nolint:gosec // fixture secret to be sealed
src, _, err := m.sourceToSave(in, nil)
set := SourceSettings{ //nolint:gosec // fixture secret to be sealed
Connector: "c", Verification: tt.verify, HMACHeader: "X-Signature",
HMACSecret: "not-a-real-secret",
}
src, _, err := m.sourceToSave(set, store.Source{ID: hookID}, nil)
if err != nil {
t.Fatal(err)
}
+16 -9
View File
@@ -6,6 +6,7 @@ import (
"testing"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/modules/connectors"
"github.com/samcharles93/archie-core/modules/events/internal/store"
@@ -21,13 +22,19 @@ func (d declaredEvents) Capabilities(_ context.Context, connector string) (conne
return caps, ok, nil
}
var hookSource = uuid.NullUUID{UUID: hookID, Valid: true}
type oneSource struct{ connector string }
func (o oneSource) Source(_ context.Context, _, name string) (store.Source, error) {
if name != "alerts" {
func (o oneSource) Source(_ context.Context, _ string, id uuid.UUID) (store.Source, error) {
if id != hookID {
return store.Source{}, store.ErrNotFound
}
return store.Source{Name: name, Connector: o.connector}, nil
return store.Source{ID: id, Connector: o.connector}, nil
}
func (o oneSource) SourceByPath(context.Context, string, string) (store.Source, error) {
return store.Source{}, store.ErrNotFound
}
// TestSavingATriggerChecksItsEventType guards the trigger contract: a trigger
@@ -40,16 +47,16 @@ func TestSavingATriggerChecksItsEventType(t *testing.T) {
}
tests := []struct {
name string
source string
source uuid.NullUUID
connector string
eventType string
wantAt string
}{
{name: "a declared event type is accepted", source: "alerts", connector: "pager", eventType: "incident.opened"},
{name: "an undeclared event type is refused", source: "alerts", connector: "pager", eventType: "incident.closed", wantAt: "body.event_type"},
{name: "a connector that never loaded is refused", source: "alerts", connector: "other", eventType: "incident.opened", wantAt: "body.event_type"},
{name: "an unknown source is refused", source: "missing", connector: "pager", eventType: "incident.opened", wantAt: "body.source"},
{name: "a schedule is exempt", source: scheduleSource, connector: "pager", eventType: scheduleType},
{name: "a declared event type is accepted", source: hookSource, connector: "pager", eventType: "incident.opened"},
{name: "an undeclared event type is refused", source: hookSource, connector: "pager", eventType: "incident.closed", wantAt: "body.event_type"},
{name: "a connector that never loaded is refused", source: hookSource, connector: "other", eventType: "incident.opened", wantAt: "body.event_type"},
{name: "an unknown source is refused", source: uuid.NullUUID{UUID: uuid.New(), Valid: true}, connector: "pager", eventType: "incident.opened", wantAt: "body.source_id"},
{name: "a schedule is exempt", connector: "pager", eventType: scheduleType},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
+5 -3
View File
@@ -9,6 +9,8 @@ import (
"net/http"
"strings"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/httpjson"
"github.com/samcharles93/archie-core/modules/events/internal/store"
)
@@ -22,8 +24,8 @@ type Sealer interface {
// secretLabel binds a sealed secret to its source, so a value copied into
// another row doesn't open there.
func secretLabel(orgID, name string) string {
return "events.sources/" + orgID + "/" + name + "/hmac"
func secretLabel(orgID string, sourceID uuid.UUID) string {
return "events.sources/" + orgID + "/" + sourceID.String() + "/hmac"
}
// errUnverified means a delivery failed verification. Its text is safe to log:
@@ -47,7 +49,7 @@ func checkToken(src store.Source, r *http.Request) error {
// internal/infrastructure/captureintake/receiver.go (header-borne signature),
// with the header and prefix set per source.
func (m *Module) verifyHMAC(src store.Source, h http.Header, body []byte) error {
secret, err := m.sealer.Open(secretLabel(src.OrgID, src.Name), src.HMACSecretSealed)
secret, err := m.sealer.Open(secretLabel(src.OrgID, src.ID), src.HMACSecretSealed)
if err != nil {
return fmt.Errorf("open signing secret: %w", err)
}
+19 -4
View File
@@ -12,6 +12,7 @@ import (
"testing"
"filippo.io/age"
"github.com/google/uuid"
"github.com/samcharles93/archie-core/internal/platform/seal"
"github.com/samcharles93/archie-core/modules/connectors"
@@ -19,9 +20,23 @@ import (
"github.com/samcharles93/archie-core/modules/governance"
)
// hookID is the id of the source the intake tests deliver to.
var hookID = uuid.MustParse("5b0b9b1e-6f0e-4c1a-9a53-0d7c1f3a2b10")
// fakeSources serves one source by id and by webhook path.
type fakeSources struct{ src store.Source }
func (f fakeSources) Source(context.Context, string, string) (store.Source, error) {
func (f fakeSources) Source(_ context.Context, _ string, id uuid.UUID) (store.Source, error) {
if id != f.src.ID {
return store.Source{}, store.ErrNotFound
}
return f.src, nil
}
func (f fakeSources) SourceByPath(_ context.Context, _, path string) (store.Source, error) {
if path != f.src.WebhookPath {
return store.Source{}, store.ErrNotFound
}
return f.src, nil
}
@@ -45,12 +60,12 @@ func TestHMACSourceVerifiesBeforeParsing(t *testing.T) {
if err != nil {
t.Fatal(err)
}
sealed, err := sealer.Seal(secretLabel("org", "hook"), []byte(secret))
sealed, err := sealer.Seal(secretLabel("org", hookID), []byte(secret))
if err != nil {
t.Fatal(err)
}
src := store.Source{
OrgID: "org", Name: "hook", Connector: "c", Verification: store.HMAC,
ID: hookID, OrgID: "org", WebhookPath: "hook", Connector: "c", Verification: store.HMAC,
HMACHeader: "X-Signature", HMACPrefix: "sha256=", HMACSecretSealed: sealed,
}
@@ -80,7 +95,7 @@ func TestHMACSourceVerifiesBeforeParsing(t *testing.T) {
},
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(body))
req.SetPathValue("source", "hook")
req.SetPathValue("path", "hook")
if tt.header != "" {
req.Header.Set("X-Signature", tt.header)
}
+1 -1
View File
@@ -398,7 +398,7 @@ const SenderID IdentityID = "sender"
// DeliveryAuthorizer decides whether an address may deliver an event to a source.
type DeliveryAuthorizer interface {
AuthorizeDelivery(ctx context.Context, orgID OrgID, sourcePath, addr string) Decision
AuthorizeDelivery(ctx context.Context, orgID OrgID, sourceID, addr string) Decision
}
// PolicyStore persists stored Cedar policies and their instance-wide revision.
+3 -3
View File
@@ -143,9 +143,9 @@ func RecordingDelivery(a DeliveryAuthorizer, records DecisionRecorder, log *slog
return recordingDelivery{DeliveryAuthorizer: a, records: records, log: log}
}
func (r recordingDelivery) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourcePath, addr string) Decision {
d := r.DeliveryAuthorizer.AuthorizeDelivery(ctx, orgID, sourcePath, addr)
func (r recordingDelivery) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourceID, addr string) Decision {
d := r.DeliveryAuthorizer.AuthorizeDelivery(ctx, orgID, sourceID, addr)
return recordDecision(ctx, r.records, r.log, d, DecisionRecord{
Principal: SenderID, Org: orgID, Action: ActionDeliver, Kind: KindSource, ResourceID: sourcePath,
Principal: SenderID, Org: orgID, Action: ActionDeliver, Kind: KindSource, ResourceID: sourceID,
})
}
+3 -3
View File
@@ -190,14 +190,14 @@ func (e *Engine) Authorize(_ context.Context, p Principal, a Action, r Resource,
}
// AuthorizeDelivery decides whether addr may deliver an event to a source.
func (e *Engine) AuthorizeDelivery(_ context.Context, orgID OrgID, sourcePath, addr string) Decision {
func (e *Engine) AuthorizeDelivery(_ context.Context, orgID OrgID, sourceID, addr string) Decision {
if e.pending {
return Unavailable()
}
sender := Principal{IdentityID: SenderID, Org: orgID}
resource := Resource{Kind: KindSource, ID: sourcePath, Org: orgID}
resource := Resource{Kind: KindSource, ID: sourceID, Org: orgID}
levels := []*levelSet{e.instance}
if l, ok := e.objects[objectKey{orgID, KindSource, sourcePath}]; ok {
if l, ok := e.objects[objectKey{orgID, KindSource, sourceID}]; ok {
levels = append(levels, l)
}
return evaluate(levels, buildEntities(sender, resource), buildRequest(sender, ActionDeliver, resource, AccessContext{Addr: addr}))
+2 -2
View File
@@ -101,8 +101,8 @@ func (l *Live) Authorize(ctx context.Context, p Principal, a Action, r Resource,
}
// AuthorizeDelivery decides whether addr may deliver an event to a source.
func (l *Live) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourcePath, addr string) Decision {
return l.current(ctx).AuthorizeDelivery(ctx, orgID, sourcePath, addr)
func (l *Live) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourceID, addr string) Decision {
return l.current(ctx).AuthorizeDelivery(ctx, orgID, sourceID, addr)
}
// Problems reports the current engine's invalid policies.
+4 -1
View File
@@ -24,7 +24,10 @@ import (
// Origin is the event and trigger that started a run.
type Origin struct {
EventID uuid.UUID `json:"event_id"`
EventID uuid.UUID `json:"event_id"`
// SourceID is the nil UUID for a schedule tick. Source is the source's
// label.
SourceID uuid.UUID `json:"source_id"`
Source string `json:"source"`
Type string `json:"type"`
Fields jsontext.Value `json:"fields"`
+1 -1
View File
@@ -89,7 +89,7 @@ export function bindingPayload(
): TriggerInput {
const eventType = eventTypes.find((t) => t.id === draft.eventTypeId);
return {
source: eventType?.source ?? "",
source_id: eventType?.source_id ?? "",
event_type_id: draft.eventTypeId,
mapping_id: draft.mappingId || undefined,
workflow: draft.workflow,
+11 -8
View File
@@ -13,15 +13,18 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { Textarea } from "@/components/ui/textarea";
import RuleEditor from "./RuleEditor.vue";
import {
closeDraft,
draft,
eventSources,
saveDraft,
saveError,
saving,
sourceLabel,
} from "./event-type-state";
/**
@@ -54,7 +57,7 @@ function onOpenChange(open: boolean) {
<DialogHeader>
<DialogTitle>{{ title }}</DialogTitle>
<DialogDescription
>Events on {{ draft.source || "the source" }} that match no type are
>Events on {{ sourceLabel(draft.sourceId) || "the source" }} that match no type are
never dispatched.</DialogDescription
>
</DialogHeader>
@@ -62,12 +65,12 @@ function onOpenChange(open: boolean) {
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-2">
<Label for="event-type-source">Source</Label>
<Input
id="event-type-source"
v-model="draft.source"
class="font-mono"
:disabled="draft.mode !== 'paste'"
/>
<Select v-model="draft.sourceId" :disabled="draft.mode !== 'paste'">
<SelectTrigger id="event-type-source" class="w-full" aria-label="Source"><SelectValue placeholder="Source" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="s in eventSources" :key="s.id" :value="s.id">{{ s.label }}</SelectItem>
</SelectContent>
</Select>
</div>
<div class="flex flex-col gap-2">
<Label for="event-type-name">Name</Label>
@@ -108,7 +111,7 @@ function onOpenChange(open: boolean) {
<DialogFooter>
<Button variant="outline" @click="closeDraft">Cancel</Button>
<Button
:disabled="saving || !draft.name.trim() || !draft.source.trim()"
:disabled="saving || !draft.name.trim() || !draft.sourceId"
@click="saveDraft"
>
<Spinner v-if="saving" />Save</Button>
+3 -2
View File
@@ -45,6 +45,7 @@ import {
eventTypesLoading,
nameProposal,
pasteExample,
sourceLabel,
pendingDelete,
proposals,
} from "./event-type-state";
@@ -87,9 +88,9 @@ function fieldCount(schema: Record<string, string> | null | undefined): number {
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="p in proposals" :key="p.source + p.key">
<TableRow v-for="p in proposals" :key="p.source_id + p.key">
<TableCell class="font-mono">{{
p.source || "(unknown)"
sourceLabel(p.source_id) || "(unknown)"
}}</TableCell>
<TableCell class="text-right tabular-nums">{{ p.count }}</TableCell>
<TableCell class="text-right tabular-nums">{{
+17 -8
View File
@@ -1,7 +1,7 @@
import { ref } from "vue";
import { errors } from "@/copy/errors";
import { api, describeError } from "@/lib/api";
import { api, describeError, type EventSource_ } from "@/lib/api";
import { captures } from "./state";
import {
cleanRule,
@@ -37,7 +37,7 @@ type DraftMode = "proposal" | "paste" | "edit";
export interface Draft {
mode: DraftMode;
id: string | null;
source: string;
sourceId: string;
name: string;
rule: Rule;
headersText: string;
@@ -46,6 +46,14 @@ export interface Draft {
}
export const draft = ref<Draft | null>(null);
/** The sources the caller can see, for naming a proposal's or a type's source. */
export const eventSources = ref<EventSource_[]>([]);
/** The label of a source, or "" when it is unknown. */
export function sourceLabel(id: string): string {
return eventSources.value.find((s) => s.id === id)?.label ?? "";
}
export const saving = ref(false);
export const saveError = ref<string | null>(null);
@@ -53,8 +61,9 @@ let generation = 0;
export async function loadEventTypes(): Promise<void> {
const current = ++generation;
try {
const res = await api.eventTypes<EventTypesResponse>();
const [res, sources] = await Promise.all([api.eventTypes<EventTypesResponse>(), api.eventSources()]);
if (current !== generation) return;
eventSources.value = sources;
eventTypesEnabled.value = res.enabled !== false;
eventTypes.value = res.event_types || [];
proposals.value = res.proposals || [];
@@ -84,7 +93,7 @@ export function nameProposal(p: Proposal): void {
open({
mode: "proposal",
id: null,
source: p.source,
sourceId: p.source_id,
name: "",
rule: copyRule(p.rule),
headersText: "",
@@ -93,11 +102,11 @@ export function nameProposal(p: Proposal): void {
});
}
export function pasteExample(source = ""): void {
export function pasteExample(sourceId = ""): void {
open({
mode: "paste",
id: null,
source,
sourceId,
name: "",
rule: { headers: [], payload: [] },
headersText: "",
@@ -110,7 +119,7 @@ export function editEventType(t: EventType): void {
open({
mode: "edit",
id: t.id,
source: t.source,
sourceId: t.source_id,
name: t.name,
rule: copyRule(t.rule),
headersText: "",
@@ -137,7 +146,7 @@ export async function saveDraft(): Promise<void> {
const headers =
d.mode === "paste" ? parseHeaderLines(d.headersText) : d.exampleHeaders;
await api.eventTypeCreate({
source: d.source,
source_id: d.sourceId,
name: d.name,
// A pasted example's rule is inferred by the server from what was pasted.
rule: d.mode === "paste" ? undefined : cleanRule(d.rule),
+3 -1
View File
@@ -21,6 +21,8 @@ export interface Rule {
export interface EventType {
id: string;
source_id: string;
/** The source's label. */
source: string;
name: string;
rule: Rule;
@@ -28,7 +30,7 @@ export interface EventType {
}
export interface Proposal {
source: string;
source_id: string;
key: string;
schema: Record<string, string> | null;
headers: Record<string, string> | null;
+3 -3
View File
@@ -26,7 +26,7 @@ const sources = useRead(() => api.eventSources());
const { data, error, reload } = useRead(() =>
api.events({
limit: 200,
source: source.value === ALL ? undefined : source.value,
source_id: source.value === ALL ? undefined : source.value,
type: type.value.trim() || undefined,
matched: matched.value === ALL ? undefined : matched.value,
}),
@@ -45,7 +45,7 @@ const linked = computed(() => String(route.query.event ?? ""));
const time = (at?: string) => (at ? Date.parse(at) : 0);
const columns: DataTableColumn<EventRecord>[] = [
{ id: "type", label: "Type", fixed: true, width: "auto", sort: (e) => e.type },
{ id: "source", label: "Source", fixed: true, hide: "sm", width: "12rem", sort: (e) => e.source },
{ id: "source", label: "Source", fixed: true, hide: "sm", width: "12rem", sort: (e) => e.source ?? "" },
{ id: "matched", label: "Trigger", hide: "sm", width: "9rem", sort: (e) => (e.matched ? 1 : 0) },
{ id: "received", label: "Received", fixed: true, width: "7.5rem", sort: (e) => time(e.received_at) },
{ id: "occurred", label: "Occurred", hidden: true, width: "9rem", sort: (e) => time(e.occurred_at) },
@@ -61,7 +61,7 @@ const columns: DataTableColumn<EventRecord>[] = [
<SelectTrigger size="sm" aria-label="Source"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem :value="ALL">All sources</SelectItem>
<SelectItem v-for="s in sources.data.value ?? []" :key="s.name" :value="s.name">{{ s.name }}</SelectItem>
<SelectItem v-for="s in sources.data.value ?? []" :key="s.id" :value="s.id">{{ s.label }}</SelectItem>
</SelectContent>
</Select>
<Select v-model="matched">
+18 -16
View File
@@ -27,7 +27,7 @@ onMounted(() => {
});
const columns: DataTableColumn<EventSource_>[] = [
{ id: "name", label: "Source", fixed: true, sort: (s) => s.name },
{ id: "label", label: "Source", fixed: true, sort: (s) => s.label },
{ id: "connector", label: "Connector", hide: "sm", width: "12rem", sort: (s) => s.connector },
{ id: "verification", label: "Verification", hide: "sm", width: "14rem" },
{ id: "key", label: "Grouped by", hide: "md", width: "16rem" },
@@ -38,11 +38,13 @@ const columns: DataTableColumn<EventSource_>[] = [
const issued = ref<{ url: string; token?: string } | null>(null);
const busy = ref(false);
const actionError = ref("");
async function put(name: string, connector: string, verification?: SourceVerification): Promise<boolean> {
async function put(connector: string, verification?: SourceVerification, existing?: EventSource_ | null, label = ""): Promise<boolean> {
busy.value = true;
actionError.value = "";
try {
const created = await api.putEventSource(name, connector, verification);
const created = existing
? await api.updateEventSource(existing.id, connector, verification)
: await api.createEventSource({ label, connector, ...verification });
issued.value = { url: new URL(created.url, window.location.origin).toString(), token: created.token };
await reload();
return true;
@@ -56,13 +58,13 @@ async function put(name: string, connector: string, verification?: SourceVerific
const adding = ref(false);
const editing = ref<EventSource_ | null>(null);
const blank = { name: "", connector: "", verification: "token" as SourceVerification["verification"], hmac_header: "", hmac_prefix: "", hmac_secret: "" };
const blank = { label: "", connector: "", verification: "token" as SourceVerification["verification"], hmac_header: "", hmac_prefix: "", hmac_secret: "" };
const draft = ref({ ...blank });
async function add(): Promise<void> {
const { name, connector, ...verification } = draft.value;
const { label, connector, ...verification } = draft.value;
// Saving an unchanged token source must not rotate its token.
const keepsToken = editing.value?.verification === "token" && verification.verification === "token";
if (await put(name.trim(), connector, keepsToken ? undefined : verification)) {
if (await put(connector, keepsToken ? undefined : verification, editing.value, label.trim())) {
adding.value = false;
editing.value = null;
draft.value = { ...blank };
@@ -71,7 +73,7 @@ async function add(): Promise<void> {
// A blank secret keeps the stored one, so it is required only when a source
// has none yet.
const secretOptional = computed(() => editing.value?.verification === "hmac" && editing.value.hmac_secret_set);
const addDisabled = computed(() => busy.value || !draft.value.name || !draft.value.connector
const addDisabled = computed(() => busy.value || !draft.value.label || !draft.value.connector
|| (draft.value.verification === "hmac" && (!draft.value.hmac_header || (!draft.value.hmac_secret && !secretOptional.value))));
function openAdd(): void {
editing.value = null;
@@ -82,7 +84,7 @@ function openAdd(): void {
function openEdit(source: EventSource_): void {
editing.value = source;
draft.value = {
name: source.name, connector: source.connector, verification: source.verification,
label: source.label, connector: source.connector, verification: source.verification,
hmac_header: source.hmac_header ?? "", hmac_prefix: source.hmac_prefix ?? "", hmac_secret: "",
};
adding.value = true;
@@ -102,7 +104,7 @@ async function saveKeyFields(): Promise<void> {
actionError.value = "";
try {
const paths = keyFields.value.split(",").map((p) => p.trim()).filter(Boolean);
await api.putSourceKeyFields(keyFieldsOf.value.name, paths);
await api.putSourceKeyFields(keyFieldsOf.value.id, paths);
keyFieldsOf.value = null;
await reload();
} catch (cause) {
@@ -128,16 +130,16 @@ const connectorNames = computed(() => (connectors.data.value ?? []).map((c) => c
<div class="mb-2 flex justify-end">
<Button size="icon-sm" variant="ghost" aria-label="Add source" title="Add source" @click="openAdd"><Plus /></Button>
</div>
<DataTable :columns="columns" :rows="data" :row-key="(s) => s.name" storage-key="sources">
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span><span class="block text-caption text-fg-muted sm:hidden">{{ row.connector }}</span></template>
<DataTable :columns="columns" :rows="data" :row-key="(s) => s.id" storage-key="sources">
<template #cell-label="{ row }"><span class="font-medium">{{ row.label }}</span><span class="block text-caption text-fg-muted sm:hidden">{{ row.connector }}</span></template>
<template #cell-connector="{ row }">{{ row.connector }}</template>
<template #cell-verification="{ row }">{{ row.verification === "hmac" ? `HMAC (${row.hmac_header})` : row.verification === "none" ? "None" : "Bearer token" }}</template>
<template #cell-key="{ row }"><span class="font-mono text-caption">{{ (row.key_fields ?? []).join(", ") || "Connector default" }}</span></template>
<template #actions="{ row }">
<MoreMenu :label="`${row.name} actions`">
<MoreMenu :label="`${row.label} actions`">
<DropdownMenuItem @select="openEdit(row)">Edit…</DropdownMenuItem>
<DropdownMenuItem @select="editKeyFields(row)">Group by…</DropdownMenuItem>
<DropdownMenuItem v-if="row.verification === 'token'" :disabled="busy" @select="put(row.name, row.connector, { verification: 'token' })">Rotate token</DropdownMenuItem>
<DropdownMenuItem v-if="row.verification === 'token'" :disabled="busy" @select="put(row.connector, { verification: 'token' }, row)">Rotate token</DropdownMenuItem>
</MoreMenu>
</template>
<template #empty><Empty><EmptyHeader><EmptyTitle>No sources</EmptyTitle></EmptyHeader></Empty></template>
@@ -146,9 +148,9 @@ const connectorNames = computed(() => (connectors.data.value ?? []).map((c) => c
<Dialog v-model:open="adding">
<DialogContent>
<DialogHeader><DialogTitle>{{ editing ? `Edit ${editing.name}` : "Add source" }}</DialogTitle></DialogHeader>
<DialogHeader><DialogTitle>{{ editing ? `Edit ${editing.label}` : "Add source" }}</DialogTitle></DialogHeader>
<form id="add-source" class="space-y-3" @submit.prevent="add">
<Input v-model="draft.name" aria-label="Name" :disabled="!!editing" placeholder="alertmanager" pattern="[a-z0-9][a-z0-9-]*" required />
<Input v-model="draft.label" aria-label="Name" :disabled="!!editing" placeholder="Alertmanager" required />
<Select v-model="draft.connector" required>
<SelectTrigger class="w-full" aria-label="Connector"><SelectValue placeholder="Connector that parses its events" /></SelectTrigger>
<SelectContent>
@@ -177,7 +179,7 @@ const connectorNames = computed(() => (connectors.data.value ?? []).map((c) => c
<Dialog :open="!!keyFieldsOf" @update:open="(open) => { if (!open) keyFieldsOf = null; }">
<DialogContent>
<DialogHeader><DialogTitle>Group {{ keyFieldsOf?.name }} events by</DialogTitle></DialogHeader>
<DialogHeader><DialogTitle>Group {{ keyFieldsOf?.label }} events by</DialogTitle></DialogHeader>
<form id="key-fields" class="space-y-3" @submit.prevent="saveKeyFields">
<Input v-model="keyFields" aria-label="Field paths" placeholder="labels.alertname, labels.instance" />
<p class="text-caption text-fg-muted">Comma-separated field paths. Leave empty for the connector's default. Applies to events that arrive after you save.</p>
+5 -5
View File
@@ -63,14 +63,14 @@ async function save(name: string, input: TriggerInput): Promise<boolean> {
const editing = ref(false);
const isNew = ref(true);
const form = ref({ name: "", mode: "event", source: "", event_type: "", every: "", workflow: "", filter: "", disabled: false });
const form = ref({ name: "", mode: "event", source_id: "", event_type: "", every: "", workflow: "", filter: "", disabled: false });
function open(trigger?: Trigger): void {
isNew.value = !trigger;
actionError.value = "";
form.value = {
name: trigger?.name ?? "",
mode: trigger?.every ? "schedule" : "event",
source: trigger?.every ? "" : (trigger?.source ?? ""),
source_id: trigger?.every ? "" : (trigger?.source_id ?? ""),
event_type: trigger?.every ? "" : (trigger?.event_type ?? ""),
every: trigger?.every ?? "",
workflow: trigger?.workflow ?? props.workflow ?? "",
@@ -85,7 +85,7 @@ async function submit(): Promise<void> {
const input: TriggerInput =
f.mode === "schedule"
? { every: f.every.trim(), workflow: f.workflow, disabled: f.disabled }
: { source: f.source, event_type: f.event_type.trim(), filter, workflow: f.workflow, disabled: f.disabled };
: { source_id: f.source_id, event_type: f.event_type.trim(), filter, workflow: f.workflow, disabled: f.disabled };
if (await save(f.name.trim(), input)) editing.value = false;
}
</script>
@@ -129,10 +129,10 @@ async function submit(): Promise<void> {
<ToggleGroupItem value="schedule">Schedule</ToggleGroupItem>
</ToggleGroup>
<template v-if="form.mode === 'event'">
<Select v-model="form.source" required>
<Select v-model="form.source_id" required>
<SelectTrigger class="w-full" aria-label="Source"><SelectValue placeholder="Source" /></SelectTrigger>
<SelectContent>
<SelectItem v-for="s in sources.data.value ?? []" :key="s.name" :value="s.name">{{ s.name }}</SelectItem>
<SelectItem v-for="s in sources.data.value ?? []" :key="s.id" :value="s.id">{{ s.label }}</SelectItem>
</SelectContent>
</Select>
<Input v-model="form.event_type" aria-label="Event type" placeholder="Event type" required />
+1 -1
View File
@@ -5,7 +5,7 @@ import type { Trigger, TriggerInput } from "@/lib/api";
export function triggerInput(trigger: Trigger): TriggerInput {
if (trigger.every) return { every: trigger.every, workflow: trigger.workflow, disabled: !trigger.enabled };
return {
source: trigger.source,
source_id: trigger.source_id,
event_type: trigger.event_type,
filter: trigger.filter,
workflow: trigger.workflow,
+49 -30
View File
@@ -198,14 +198,16 @@ export const api = {
/** Starts the passkey confirmation that approving an irreversible action needs. */
beginApprovalConfirmation: (id: string) =>
request<ApprovalConfirmation>(`/api/approvals/${encodeURIComponent(id)}/confirmation`, { method: "POST", body: {} }),
events: (params: { limit?: number; source?: string; type?: string; matched?: string } = {}) =>
events: (params: { limit?: number; source_id?: string; type?: string; matched?: string } = {}) =>
request<EventRecord[]>("/api/events" + qs(params)),
event: (id: string) => request<EventDetail>(`/api/events/${encodeURIComponent(id)}`),
eventSources: () => request<EventSource_[]>("/api/sources"),
putEventSource: (name: string, connector: string, verification?: SourceVerification) =>
request<{ source: string; token?: string; secret?: string; url: string }>(`/api/sources/${encodeURIComponent(name)}`, { method: "PUT", body: { connector, ...verification } }),
sourceCapture: (name: string, capture: boolean) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(name)}/capture`, { method: "PUT", body: { capture } }),
createEventSource: (input: { label: string; webhook_path?: string; scope?: SourceScope; connector: string } & Partial<SourceVerification>) =>
request<SourceIssued>("/api/sources", { method: "POST", body: input }),
updateEventSource: (id: string, connector: string, verification?: SourceVerification) =>
request<SourceIssued>(`/api/sources/${encodeURIComponent(id)}`, { method: "PUT", body: { connector, ...verification } }),
sourceCapture: (id: string, capture: boolean) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/capture`, { method: "PUT", body: { capture } }),
/** The runs a trigger started, newest first. */
triggerDispatches: (name: string) =>
request<TriggerRun[]>(`/api/triggers/${encodeURIComponent(name)}/dispatches`),
@@ -221,8 +223,8 @@ export const api = {
/** The runs a stored delivery started. */
captureDispatches: (id: string) =>
request<TriggerRun[]>(`/api/captures/${encodeURIComponent(id)}/dispatches`),
putSourceKeyFields: (name: string, paths: string[]) =>
request<{ key_fields: string[] }>(`/api/sources/${encodeURIComponent(name)}/key-fields`, { method: "PUT", body: { paths } }),
putSourceKeyFields: (id: string, paths: string[]) =>
request<{ key_fields: string[] }>(`/api/sources/${encodeURIComponent(id)}/key-fields`, { method: "PUT", body: { paths } }),
triggers: () => request<Trigger[]>("/api/triggers"),
putTrigger: (name: string, trigger: TriggerInput) =>
request<{ trigger: string }>(`/api/triggers/${encodeURIComponent(name)}`, { method: "PUT", body: trigger }),
@@ -629,29 +631,25 @@ export const api = {
request<T>(`/api/bindings/${encodeURIComponent(id)}/pause`, { method: "POST" }),
bindingResume: <T = unknown>(id: string) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}/resume`, { method: "POST" }),
sources: <T = unknown>(workspace?: string) =>
request<T>("/api/sources" + qs({ workspace })),
// sourceCreate makes a source in one of the org's workspaces; an empty
// workspace is the default one.
sourceCreate: <T = unknown>(path: string, workspace = "") =>
request<T>("/api/sources", { method: "POST", body: { path, workspace } }),
sourceSigning: <T = unknown>(path: string, signed: boolean) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/signing`, {
sourceSigning: <T = unknown>(id: string, signed: boolean) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/signing`, {
method: "POST",
body: { signed },
}),
sourceApproveUnsigned: <T = unknown>(path: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/approve-unsigned`, {
sourceApproveUnsigned: <T = unknown>(id: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/approve-unsigned`, {
method: "POST",
}),
sourceName: <T = unknown>(path: string, name: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/name`, { method: "PUT", body: { name } }),
sourceDeliveryHeader: <T = unknown>(path: string, header: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/delivery-header`, { method: "PUT", body: { header } }),
sourceDelete: (path: string) =>
request<void>(`/api/sources/${encodeURIComponent(path)}`, { method: "DELETE", parse: false }),
sourceSecret: <T = unknown>(path: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/secret`, {
sourceLabel: <T = unknown>(id: string, label: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/label`, { method: "PUT", body: { label } }),
sourceWebhookPath: <T = unknown>(id: string, path: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/webhook-path`, { method: "PUT", body: { path } }),
sourceDeliveryHeader: <T = unknown>(id: string, header: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/delivery-header`, { method: "PUT", body: { header } }),
sourceDelete: (id: string) =>
request<void>(`/api/sources/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
sourceSecret: <T = unknown>(id: string) =>
request<T>(`/api/sources/${encodeURIComponent(id)}/secret`, {
method: "POST",
}),
chatSessions: () => request<ChatSessions>("/api/chat/sessions"),
@@ -928,7 +926,7 @@ export interface RunStage {
export interface RunTrail {
run: Run;
origin?: { event_id?: string; source?: string; type?: string; trigger?: string; received_at?: string };
origin?: { event_id?: string; source_id?: string; source?: string; type?: string; trigger?: string; received_at?: string };
actions?: RunAction[];
entries?: RunEntry[];
/** The document the run executes: its version, or the draft a test run tested. */
@@ -938,7 +936,10 @@ export interface RunTrail {
export interface EventRecord {
id: string;
source: string;
/** Empty for a schedule tick. */
source_id?: string;
/** The source's label. */
source?: string;
type: string;
matched: boolean;
received_at: string;
@@ -992,8 +993,24 @@ export interface SourceVerification {
hmac_secret?: string;
}
/** Who owns a source: the organisation, or the one person who can see and use it. */
export type SourceScope = "org" | "person";
/** What creating or updating a source returns; token and secret are shown once. */
export interface SourceIssued {
id: string;
token?: string;
secret?: string;
url: string;
}
export interface EventSource_ {
name: string;
id: string;
scope: SourceScope;
/** The name people see, unique within the scope. */
label: string;
/** The last segment of the URL deliveries post to. */
webhook_path: string;
connector: string;
key_fields?: string[];
token_set: boolean;
@@ -1001,7 +1018,6 @@ export interface EventSource_ {
hmac_header?: string;
hmac_prefix?: string;
hmac_secret_set: boolean;
display_name?: string;
/** The header a sender repeats on every retry of one delivery. */
delivery_header?: string;
signing: "signed" | "token" | "unsigned_pending_approval" | "unsigned";
@@ -1013,6 +1029,9 @@ export interface EventSource_ {
export interface Trigger {
name: string;
/** Empty for a scheduled trigger. */
source_id?: string;
/** The source's label. */
source?: string;
event_type?: string;
every?: string;
@@ -1027,7 +1046,7 @@ export interface Trigger {
}
export interface TriggerInput {
source?: string;
source_id?: string;
event_type?: string;
every?: string;
workflow: string;
+26 -4
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { errors } from "@/copy/errors";
import { computed } from "vue";
import { computed, onMounted } from "vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -13,7 +13,9 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { api } from "@/lib/api";
import { ago } from "@/lib/format";
import { useRead } from "@/lib/use-read";
import { eventTypeLabel } from "@/captures/event-types";
import {
captures,
@@ -29,7 +31,7 @@ import {
/**
* The mapping's own fields: the name it is saved under, the organisational
* source hint, and the captured event the payload and the preview resolve
* source, and the captured event the payload and the preview resolve
* against. The hint is a note to a human, never a matcher; bindings decide which
* events a mapping applies to.
*
@@ -42,6 +44,18 @@ import {
* item value outright. */
const NO_CAPTURE = "none";
/** The picker's value for "no source". */
const NO_SOURCE = "none";
const sources = useRead(() => api.eventSources());
onMounted(() => void sources.reload());
const sourceValue = computed(() => draft.value.sourceId || NO_SOURCE);
function onSourceChange(value: unknown): void {
draft.value.sourceId = value === NO_SOURCE ? "" : String(value);
}
const captureValue = computed(() =>
draft.value.captureId === null ? NO_CAPTURE : String(draft.value.captureId),
);
@@ -97,8 +111,16 @@ const captureHint = computed(() => {
</div>
<div class="flex flex-col gap-2">
<Label for="mapping-source-hint">Source hint (organisational only)</Label>
<Input id="mapping-source-hint" v-model="draft.sourceHint" />
<Label for="mapping-source">Source (organisational only)</Label>
<Select :model-value="sourceValue" @update:model-value="onSourceChange">
<SelectTrigger id="mapping-source" class="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="NO_SOURCE">No source</SelectItem>
<SelectItem v-for="s in sources.data.value ?? []" :key="s.id" :value="s.id">{{ s.label }}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
<div class="flex flex-col gap-2">
+5 -5
View File
@@ -34,7 +34,7 @@ export interface MappingField {
export interface Mapping {
id: number;
name: string;
source_hint?: string;
source_id?: string;
event_type_id?: string;
fields?: MappingField[];
match_count?: number;
@@ -70,7 +70,7 @@ export interface MappingDraft {
/** null until the first save. */
id: number | null;
name: string;
sourceHint: string;
sourceId: string;
/** The event type the mapping belongs to; its schema checks the fields. */
eventTypeId: string;
fields: MappingField[];
@@ -126,7 +126,7 @@ function blankDraft(): MappingDraft {
return {
id: null,
name: "",
sourceHint: "",
sourceId: "",
eventTypeId: "",
fields: [],
captureId: null,
@@ -178,7 +178,7 @@ export function startEdit(mapping: Mapping): void {
...blankDraft(),
id: mapping.id,
name: mapping.name,
sourceHint: mapping.source_hint || "",
sourceId: mapping.source_id || "",
eventTypeId: mapping.event_type_id || "",
// Copied, not aliased: the editor must not write through to the loaded list.
fields: (mapping.fields || []).map((field) => ({ ...field })),
@@ -275,7 +275,7 @@ export async function saveMapping(): Promise<void> {
const current = draft.value;
const body = {
name: current.name,
source_hint: current.sourceHint,
source_id: current.sourceId || undefined,
event_type_id: current.eventTypeId,
fields: current.fields,
};
+1 -1
View File
@@ -219,7 +219,7 @@ onMounted(load);
/>
<template v-if="draft.level === 'object'">
<Input v-model="draft.object_kind" placeholder="kind (secret, source...)" aria-label="Object kind" class="w-48" />
<Input v-model="draft.object_id" placeholder="object id" aria-label="Object id" class="w-48" />
<Input v-model="draft.object_id" placeholder="object id (a source's id)" aria-label="Object id" class="w-48" />
</template>
</div>
<Textarea
+2 -2
View File
@@ -7,7 +7,7 @@ import { sourceURL, type Source } from "./source-signing";
const props = defineProps<{ source: Source }>();
const emit = defineEmits<{ dismiss: [] }>();
const url = computed(() => sourceURL(window.location.origin, props.source.path));
const url = computed(() => sourceURL(window.location.origin, props.source.webhook_path));
const copied = ref<string | null>(null);
async function copy(value: string): Promise<void> {
await navigator.clipboard.writeText(value);
@@ -21,7 +21,7 @@ async function copy(value: string): Promise<void> {
<KeyRound />
<AlertTitle class="flex items-center justify-between gap-2 text-caption">
<span class="font-mono"
>{{ source.path }} · signing secret, shown once</span
>{{ source.label }} · signing secret, shown once</span
>
<Button
type="button"
+24 -14
View File
@@ -54,6 +54,7 @@ const {
requireSigning,
approveUnsigned,
rename,
setWebhookPath,
setDeliveryHeader,
setCapture,
remove,
@@ -64,7 +65,7 @@ const connector = ref("");
const header = ref("");
const pending = ref<Source | null>(null);
const customPath = ref("");
const label = ref("");
const copied = ref<string | null>(null);
useLiveResource(null, () => void load());
@@ -80,15 +81,15 @@ async function copy(value: string): Promise<void> {
}
async function submit(): Promise<void> {
await create(customPath.value.trim(), connector.value, header.value.trim());
await create(label.value.trim(), connector.value, header.value.trim());
if (!failure.value) {
customPath.value = "";
label.value = "";
header.value = "";
}
}
function url(source: Source): string {
return sourceURL(window.location.origin, source.path);
return sourceURL(window.location.origin, source.webhook_path);
}
</script>
@@ -99,11 +100,10 @@ function url(source: Source): string {
@submit.prevent="submit"
>
<Input
v-model="customPath"
class="w-full font-mono sm:w-48"
v-model="label"
class="w-full sm:w-48"
placeholder="Source name"
aria-label="Source name"
pattern="[a-z][a-z0-9\-]*"
required
/>
<Select v-model="connector" required>
@@ -119,7 +119,7 @@ function url(source: Source): string {
aria-label="Signature header"
required
/>
<Button type="submit" variant="outline" :disabled="busy || !customPath || !connector || !header">
<Button type="submit" variant="outline" :disabled="busy || !label || !connector || !header">
<Plus data-icon="inline-start" />
New source</Button>
</form>
@@ -146,24 +146,34 @@ function url(source: Source): string {
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="source in sources" :key="source.path">
<TableRow v-for="source in sources" :key="source.id">
<TableCell class="font-mono text-fg-muted">
<div class="flex w-64 max-w-full min-w-0 flex-col gap-1">
<Input
class="h-7 border-transparent px-1 font-sans shadow-none hover:border-input dark:bg-transparent"
:model-value="source.name ?? ''"
:model-value="source.label"
placeholder="Name this source"
:aria-label="`Name of source ${source.path}`"
:aria-label="`Name of source ${source.label}`"
:disabled="busy"
@change="rename(source, ($event.target as HTMLInputElement).value)"
/>
<Tooltip><TooltipTrigger as-child><span tabindex="0" class="truncate">{{ source.path }}</span></TooltipTrigger><TooltipContent>{{ url(source) }}</TooltipContent></Tooltip>
<Tooltip><TooltipTrigger as-child>
<Input
class="h-6 border-transparent px-1 font-mono text-caption text-fg-muted shadow-none hover:border-input md:text-caption dark:bg-transparent"
:model-value="source.webhook_path"
placeholder="Webhook path"
:aria-label="`Webhook path of source ${source.label}`"
pattern="[a-z][a-z0-9\-]*"
:disabled="busy"
@change="setWebhookPath(source, ($event.target as HTMLInputElement).value)"
/>
</TooltipTrigger><TooltipContent>{{ url(source) }}</TooltipContent></Tooltip>
<Input
class="h-6 border-transparent px-1 font-mono text-caption text-fg-muted shadow-none hover:border-input md:text-caption dark:bg-transparent"
:model-value="source.delivery_header ?? ''"
placeholder="Delivery ID header"
title="The header the sender repeats on every retry of one delivery; a retry then starts no second run"
:aria-label="`Delivery ID header of source ${source.path}`"
:aria-label="`Delivery ID header of source ${source.label}`"
:disabled="busy"
@change="setDeliveryHeader(source, ($event.target as HTMLInputElement).value)"
/>
@@ -274,7 +284,7 @@ function url(source: Source): string {
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete source?</AlertDialogTitle>
<AlertDialogDescription>Delete the source "{{ pending?.path }}"? Its webhook endpoint stops accepting deliveries.</AlertDialogDescription>
<AlertDialogDescription>Delete the source "{{ pending?.label }}"? Its webhook endpoint stops accepting deliveries.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
+9 -6
View File
@@ -7,10 +7,12 @@
import type { EventSource_ } from "@/lib/api";
export interface Source {
/** The source's name, which its webhook URL ends in. */
path: string;
/** The operator's label; the path stays the source's identity. */
name?: string;
/** The source's id, which never changes. */
id: string;
/** The name people see. */
label: string;
/** The last segment of the webhook URL; it can be changed. */
webhook_path: string;
/** The header the sender repeats on every retry of one delivery. */
delivery_header?: string;
signing?: string;
@@ -22,8 +24,9 @@ export interface Source {
export function toSource(view: EventSource_): Source {
return {
path: view.name,
name: view.display_name,
id: view.id,
label: view.label,
webhook_path: view.webhook_path,
delivery_header: view.delivery_header,
signing: view.signing,
capture: view.capture,
+16 -11
View File
@@ -59,21 +59,26 @@ export function useSources() {
load,
// A new source signs with an HMAC over the body; the server generates the
// secret and returns it once.
create: (name: string, connector: string, header: string) =>
create: (label: string, connector: string, header: string) =>
run(async () => {
const created = await api.putEventSource(name, connector, { verification: "hmac", hmac_header: header });
return { path: name, signing: "signed", capture: true, secret: created.secret };
const created = await api.createEventSource({ label, connector, verification: "hmac", hmac_header: header });
return {
id: created.id, label, webhook_path: created.url.split("/").pop() ?? "",
signing: "signed", capture: true, secret: created.secret,
};
}),
newSecret: (s: Source) => run(() => source(api.sourceSecret<EventSource_>(s.path))),
requestUnsigned: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.path, false))),
requireSigning: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.path, true))),
approveUnsigned: (s: Source) => run(() => source(api.sourceApproveUnsigned<EventSource_>(s.path))),
rename: (s: Source, name: string) => run(() => source(api.sourceName<EventSource_>(s.path, name.trim()))),
newSecret: (s: Source) => run(() => source(api.sourceSecret<EventSource_>(s.id))),
requestUnsigned: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.id, false))),
requireSigning: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.id, true))),
approveUnsigned: (s: Source) => run(() => source(api.sourceApproveUnsigned<EventSource_>(s.id))),
rename: (s: Source, label: string) => run(() => source(api.sourceLabel<EventSource_>(s.id, label.trim()))),
setWebhookPath: (s: Source, path: string) =>
run(() => source(api.sourceWebhookPath<EventSource_>(s.id, path.trim()))),
setDeliveryHeader: (s: Source, header: string) =>
run(() => source(api.sourceDeliveryHeader<EventSource_>(s.path, header.trim()))),
setCapture: (s: Source, capture: boolean) => run(() => source(api.sourceCapture(s.path, capture))),
run(() => source(api.sourceDeliveryHeader<EventSource_>(s.id, header.trim()))),
setCapture: (s: Source, capture: boolean) => run(() => source(api.sourceCapture(s.id, capture))),
// A trigger that names the source refuses the delete; the refusal shows
// as the panel's failure.
remove: (s: Source) => run(() => api.sourceDelete(s.path)),
remove: (s: Source) => run(() => api.sourceDelete(s.id)),
};
}