diff --git a/api/openapi.yaml b/api/openapi.yaml index d8d9bb3ce..64c574a64 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -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 diff --git a/internal/platform/pg/migrations/00003_events.sql b/internal/platform/pg/migrations/00003_events.sql index df5b1af8d..a2d65af7a 100644 --- a/internal/platform/pg/migrations/00003_events.sql +++ b/internal/platform/pg/migrations/00003_events.sql @@ -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, diff --git a/internal/platform/pg/migrations/00008_drafts.sql b/internal/platform/pg/migrations/00008_drafts.sql index e99791f21..7893ee4c9 100644 --- a/internal/platform/pg/migrations/00008_drafts.sql +++ b/internal/platform/pg/migrations/00008_drafts.sql @@ -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, diff --git a/modules/drafts/drafts.go b/modules/drafts/drafts.go index b60720441..f4a543fe2 100644 --- a/modules/drafts/drafts.go +++ b/modules/drafts/drafts.go @@ -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) } diff --git a/modules/drafts/internal/store/store.go b/modules/drafts/internal/store/store.go index d0c3df3c5..d6bb5eb32 100644 --- a/modules/drafts/internal/store/store.go +++ b/modules/drafts/internal/store/store.go @@ -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) } diff --git a/modules/events/access_test.go b/modules/events/access_test.go index 793e822aa..3c99074bc 100644 --- a/modules/events/access_test.go +++ b/modules/events/access_test.go @@ -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() diff --git a/modules/events/api.go b/modules/events/api.go index 4860dc63f..61057cb1c 100644 --- a/modules/events/api.go +++ b/modules/events/api.go @@ -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 } diff --git a/modules/events/api_capture.go b/modules/events/api_capture.go index 215257af5..05ce7a768 100644 --- a/modules/events/api_capture.go +++ b/modules/events/api_capture.go @@ -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") } diff --git a/modules/events/api_sources.go b/modules/events/api_sources.go index ec4f8ac5c..5b9051d6e 100644 --- a/modules/events/api_sources.go +++ b/modules/events/api_sources.go @@ -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) diff --git a/modules/events/capture.go b/modules/events/capture.go index 0de76c7db..db2befb91 100644 --- a/modules/events/capture.go +++ b/modules/events/capture.go @@ -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) } diff --git a/modules/events/capture_test.go b/modules/events/capture_test.go index 57db3ecb2..246495e54 100644 --- a/modules/events/capture_test.go +++ b/modules/events/capture_test.go @@ -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() diff --git a/modules/events/clientaddr_test.go b/modules/events/clientaddr_test.go index 094aec426..b453d65da 100644 --- a/modules/events/clientaddr_test.go +++ b/modules/events/clientaddr_test.go @@ -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) } }) diff --git a/modules/events/drafting.go b/modules/events/drafting.go index b63386a68..be78c958e 100644 --- a/modules/events/drafting.go +++ b/modules/events/drafting.go @@ -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, }) } diff --git a/modules/events/events.go b/modules/events/events.go index 4b5bf21db..19828f0f9 100644 --- a/modules/events/events.go +++ b/modules/events/events.go @@ -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 diff --git a/modules/events/grouping.go b/modules/events/grouping.go index 865cca7fe..74df52079 100644 --- a/modules/events/grouping.go +++ b/modules/events/grouping.go @@ -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} diff --git a/modules/events/grouping_test.go b/modules/events/grouping_test.go index f48e615f7..1a1ec91c7 100644 --- a/modules/events/grouping_test.go +++ b/modules/events/grouping_test.go @@ -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)} diff --git a/modules/events/internal/eventtype/eventtype.go b/modules/events/internal/eventtype/eventtype.go index b5ecb18e0..ae7de867d 100644 --- a/modules/events/internal/eventtype/eventtype.go +++ b/modules/events/internal/eventtype/eventtype.go @@ -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)) { diff --git a/modules/events/internal/eventtype/propose.go b/modules/events/internal/eventtype/propose.go index 4153fecf4..c7ebf56ac 100644 --- a/modules/events/internal/eventtype/propose.go +++ b/modules/events/internal/eventtype/propose.go @@ -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]) } } diff --git a/modules/events/internal/mapping/mapping.go b/modules/events/internal/mapping/mapping.go index d4725508e..b77cd3873 100644 --- a/modules/events/internal/mapping/mapping.go +++ b/modules/events/internal/mapping/mapping.go @@ -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"` diff --git a/modules/events/internal/store/capture.go b/modules/events/internal/store/capture.go index 1db2db2db..b89ea27b0 100644 --- a/modules/events/internal/store/capture.go +++ b/modules/events/internal/store/capture.go @@ -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 diff --git a/modules/events/internal/store/drafting.go b/modules/events/internal/store/drafting.go index b197663c4..7b22e03e4 100644 --- a/modules/events/internal/store/drafting.go +++ b/modules/events/internal/store/drafting.go @@ -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 diff --git a/modules/events/internal/store/groups.go b/modules/events/internal/store/groups.go index bf17ba97e..2965c5c25 100644 --- a/modules/events/internal/store/groups.go +++ b/modules/events/internal/store/groups.go @@ -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 diff --git a/modules/events/internal/store/store.go b/modules/events/internal/store/store.go index 5c3d73f42..ae352c0b2 100644 --- a/modules/events/internal/store/store.go +++ b/modules/events/internal/store/store.go @@ -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) { diff --git a/modules/events/listen_test.go b/modules/events/listen_test.go index 755276282..2c81ecff0 100644 --- a/modules/events/listen_test.go +++ b/modules/events/listen_test.go @@ -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) diff --git a/modules/events/person_source_test.go b/modules/events/person_source_test.go new file mode 100644 index 000000000..faa2e19cc --- /dev/null +++ b/modules/events/person_source_test.go @@ -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) + } + }) + } +} diff --git a/modules/events/schedule.go b/modules/events/schedule.go index 1df8c2cc9..3d2e1c6c4 100644 --- a/modules/events/schedule.go +++ b/modules/events/schedule.go @@ -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 diff --git a/modules/events/scope.go b/modules/events/scope.go new file mode 100644 index 000000000..a6c401f57 --- /dev/null +++ b/modules/events/scope.go @@ -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 +} diff --git a/modules/events/sender_test.go b/modules/events/sender_test.go index e91eb51cd..e2c8fb20d 100644 --- a/modules/events/sender_test.go +++ b/modules/events/sender_test.go @@ -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) } diff --git a/modules/events/source_save_test.go b/modules/events/source_save_test.go index bf4e1d829..4b3fe4915 100644 --- a/modules/events/source_save_test.go +++ b/modules/events/source_save_test.go @@ -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) } diff --git a/modules/events/trigger_test.go b/modules/events/trigger_test.go index 95c301757..652ed2fdf 100644 --- a/modules/events/trigger_test.go +++ b/modules/events/trigger_test.go @@ -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) { diff --git a/modules/events/verify.go b/modules/events/verify.go index 74249ab0c..b1842a2dc 100644 --- a/modules/events/verify.go +++ b/modules/events/verify.go @@ -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) } diff --git a/modules/events/verify_test.go b/modules/events/verify_test.go index 527338c6a..b6c7fea45 100644 --- a/modules/events/verify_test.go +++ b/modules/events/verify_test.go @@ -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) } diff --git a/modules/governance/access.go b/modules/governance/access.go index ee888e273..75130c7da 100644 --- a/modules/governance/access.go +++ b/modules/governance/access.go @@ -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. diff --git a/modules/governance/enforce.go b/modules/governance/enforce.go index 7d4cf16b7..5c621bb25 100644 --- a/modules/governance/enforce.go +++ b/modules/governance/enforce.go @@ -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, }) } diff --git a/modules/governance/engine.go b/modules/governance/engine.go index 045ea89b1..f1b65be41 100644 --- a/modules/governance/engine.go +++ b/modules/governance/engine.go @@ -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})) diff --git a/modules/governance/live.go b/modules/governance/live.go index e9a3e25e6..76483243c 100644 --- a/modules/governance/live.go +++ b/modules/governance/live.go @@ -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. diff --git a/modules/runs/trail.go b/modules/runs/trail.go index c5c3d3861..2dafbd3fd 100644 --- a/modules/runs/trail.go +++ b/modules/runs/trail.go @@ -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"` diff --git a/ui/src/bindings/binding-trigger.ts b/ui/src/bindings/binding-trigger.ts index b40efb821..e54d8faaf 100644 --- a/ui/src/bindings/binding-trigger.ts +++ b/ui/src/bindings/binding-trigger.ts @@ -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, diff --git a/ui/src/captures/EventTypeDialog.vue b/ui/src/captures/EventTypeDialog.vue index dc3a2c202..de3e89a92 100644 --- a/ui/src/captures/EventTypeDialog.vue +++ b/ui/src/captures/EventTypeDialog.vue @@ -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) { {{ title }} 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. @@ -62,12 +65,12 @@ function onOpenChange(open: boolean) {
- +
@@ -108,7 +111,7 @@ function onOpenChange(open: boolean) { diff --git a/ui/src/captures/EventTypesCard.vue b/ui/src/captures/EventTypesCard.vue index 81a19cace..ef1132647 100644 --- a/ui/src/captures/EventTypesCard.vue +++ b/ui/src/captures/EventTypesCard.vue @@ -45,6 +45,7 @@ import { eventTypesLoading, nameProposal, pasteExample, + sourceLabel, pendingDelete, proposals, } from "./event-type-state"; @@ -87,9 +88,9 @@ function fieldCount(schema: Record | null | undefined): number { - + {{ - p.source || "(unknown)" + sourceLabel(p.source_id) || "(unknown)" }} {{ p.count }} {{ diff --git a/ui/src/captures/event-type-state.ts b/ui/src/captures/event-type-state.ts index b2f9d8114..1e5fffebd 100644 --- a/ui/src/captures/event-type-state.ts +++ b/ui/src/captures/event-type-state.ts @@ -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(null); + +/** The sources the caller can see, for naming a proposal's or a type's source. */ +export const eventSources = ref([]); + +/** 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(null); @@ -53,8 +61,9 @@ let generation = 0; export async function loadEventTypes(): Promise { const current = ++generation; try { - const res = await api.eventTypes(); + const [res, sources] = await Promise.all([api.eventTypes(), 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 { 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), diff --git a/ui/src/captures/event-types.ts b/ui/src/captures/event-types.ts index 926454388..6e6a26b81 100644 --- a/ui/src/captures/event-types.ts +++ b/ui/src/captures/event-types.ts @@ -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 | null; headers: Record | null; diff --git a/ui/src/events/EventList.vue b/ui/src/events/EventList.vue index 316bc2582..d868bd1d3 100644 --- a/ui/src/events/EventList.vue +++ b/ui/src/events/EventList.vue @@ -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[] = [ { 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[] = [ All sources - {{ s.name }} + {{ s.label }} +

Comma-separated field paths. Leave empty for the connector's default. Applies to events that arrive after you save.

diff --git a/ui/src/events/TriggerList.vue b/ui/src/events/TriggerList.vue index 7587b665c..e163f0a29 100644 --- a/ui/src/events/TriggerList.vue +++ b/ui/src/events/TriggerList.vue @@ -63,14 +63,14 @@ async function save(name: string, input: TriggerInput): Promise { 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 { 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; } @@ -129,10 +129,10 @@ async function submit(): Promise { Schedule