# Conflicts: # api/openapi.yaml # modules/events/events.go
This commit is contained in:
53 files changed
+1195
-581
No files matched your search
@@ -1,9 +1,18 @@
|
|||||||
-- +goose Up
|
-- +goose Up
|
||||||
CREATE SCHEMA events;
|
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 (
|
CREATE TABLE events.sources (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
scope text NOT NULL CHECK (scope IN ('org', 'person')),
|
||||||
org_id text NOT NULL,
|
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,
|
connector text NOT NULL,
|
||||||
token_sha256 text NOT NULL,
|
token_sha256 text NOT NULL,
|
||||||
created_at timestamptz NOT NULL DEFAULT now(),
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
@@ -14,12 +23,13 @@ CREATE TABLE events.sources (
|
|||||||
hmac_header text NOT NULL DEFAULT '',
|
hmac_header text NOT NULL DEFAULT '',
|
||||||
hmac_prefix text NOT NULL DEFAULT '',
|
hmac_prefix text NOT NULL DEFAULT '',
|
||||||
hmac_secret_sealed bytea NOT NULL DEFAULT '\x'::bytea,
|
hmac_secret_sealed bytea NOT NULL DEFAULT '\x'::bytea,
|
||||||
display_name text NOT NULL DEFAULT '',
|
|
||||||
delivery_header text NOT NULL DEFAULT '',
|
delivery_header text NOT NULL DEFAULT '',
|
||||||
unsigned_approved boolean NOT NULL DEFAULT false,
|
unsigned_approved boolean NOT NULL DEFAULT false,
|
||||||
capture boolean NOT NULL DEFAULT true,
|
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
|
-- 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
|
-- 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 (
|
CREATE TABLE events.event_types (
|
||||||
id uuid PRIMARY KEY,
|
id uuid PRIMARY KEY,
|
||||||
org_id text NOT NULL,
|
org_id text NOT NULL,
|
||||||
source text NOT NULL,
|
source_id uuid NOT NULL REFERENCES events.sources (id),
|
||||||
name text NOT NULL,
|
name text NOT NULL,
|
||||||
rule jsonb NOT NULL,
|
rule jsonb NOT NULL,
|
||||||
schema jsonb NOT NULL DEFAULT '{}',
|
schema jsonb NOT NULL DEFAULT '{}',
|
||||||
created_at timestamptz NOT NULL DEFAULT now(),
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
updated_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 (
|
CREATE TABLE events.events (
|
||||||
id uuid PRIMARY KEY,
|
id uuid PRIMARY KEY,
|
||||||
org_id text NOT NULL,
|
org_id text NOT NULL,
|
||||||
source text NOT NULL,
|
source_id uuid REFERENCES events.sources (id) ON DELETE SET NULL,
|
||||||
type text NOT NULL,
|
type text NOT NULL,
|
||||||
source_event_id text NOT NULL,
|
source_event_id text NOT NULL,
|
||||||
link_key text,
|
link_key text,
|
||||||
@@ -58,10 +68,14 @@ CREATE TABLE events.events (
|
|||||||
headers jsonb,
|
headers jsonb,
|
||||||
remote_addr text NOT NULL DEFAULT '',
|
remote_addr text NOT NULL DEFAULT '',
|
||||||
event_type_id uuid REFERENCES events.event_types (id) ON DELETE SET NULL,
|
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_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
|
-- A mapping lists the payload paths a workflow reads from events of one event
|
||||||
-- type.
|
-- type.
|
||||||
@@ -69,7 +83,7 @@ CREATE TABLE events.mappings (
|
|||||||
id uuid PRIMARY KEY,
|
id uuid PRIMARY KEY,
|
||||||
org_id text NOT NULL,
|
org_id text NOT NULL,
|
||||||
name 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,
|
event_type_id uuid NOT NULL REFERENCES events.event_types (id) ON DELETE RESTRICT,
|
||||||
fields jsonb NOT NULL,
|
fields jsonb NOT NULL,
|
||||||
match_count bigint NOT NULL DEFAULT 0,
|
match_count bigint NOT NULL DEFAULT 0,
|
||||||
@@ -81,7 +95,7 @@ CREATE TABLE events.mappings (
|
|||||||
CREATE TABLE events.triggers (
|
CREATE TABLE events.triggers (
|
||||||
org_id text NOT NULL,
|
org_id text NOT NULL,
|
||||||
name text NOT NULL,
|
name text NOT NULL,
|
||||||
source text NOT NULL,
|
source_id uuid REFERENCES events.sources (id),
|
||||||
event_type text NOT NULL,
|
event_type text NOT NULL,
|
||||||
filter jsonb NOT NULL DEFAULT '{}',
|
filter jsonb NOT NULL DEFAULT '{}',
|
||||||
workflow text NOT NULL,
|
workflow text NOT NULL,
|
||||||
@@ -92,7 +106,8 @@ CREATE TABLE events.triggers (
|
|||||||
approved boolean NOT NULL DEFAULT true,
|
approved boolean NOT NULL DEFAULT true,
|
||||||
event_type_id uuid REFERENCES events.event_types (id) ON DELETE RESTRICT,
|
event_type_id uuid REFERENCES events.event_types (id) ON DELETE RESTRICT,
|
||||||
mapping_id uuid REFERENCES events.mappings (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 (
|
CREATE TABLE events.dispatches (
|
||||||
@@ -112,7 +127,7 @@ CREATE TABLE events.groups (
|
|||||||
id uuid PRIMARY KEY,
|
id uuid PRIMARY KEY,
|
||||||
org_id text NOT NULL,
|
org_id text NOT NULL,
|
||||||
key 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,
|
event_type text NOT NULL,
|
||||||
filter jsonb NOT NULL,
|
filter jsonb NOT NULL,
|
||||||
count bigint NOT NULL,
|
count bigint NOT NULL,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ CREATE TABLE drafts.drafts (
|
|||||||
org_id text NOT NULL,
|
org_id text NOT NULL,
|
||||||
group_id uuid NOT NULL,
|
group_id uuid NOT NULL,
|
||||||
name text NOT NULL,
|
name text NOT NULL,
|
||||||
source text NOT NULL,
|
source_id uuid NOT NULL,
|
||||||
event_type text NOT NULL,
|
event_type text NOT NULL,
|
||||||
filter jsonb NOT NULL,
|
filter jsonb NOT NULL,
|
||||||
document text NOT NULL,
|
document text NOT NULL,
|
||||||
|
|||||||
@@ -122,17 +122,23 @@ type View struct {
|
|||||||
|
|
||||||
// Trigger is the trigger a draft proposes.
|
// Trigger is the trigger a draft proposes.
|
||||||
type Trigger struct {
|
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"`
|
EventType string `json:"event_type"`
|
||||||
Filter jsontext.Value `json:"filter"`
|
Filter jsontext.Value `json:"filter"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Module) view(ctx context.Context, d store.Draft) (View, error) {
|
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{
|
v := View{
|
||||||
ID: d.ID, GroupID: d.GroupID, Name: d.Name,
|
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,
|
Workflow: d.Document, PolicyKind: d.PolicyKind, Policy: d.Policy,
|
||||||
Summary: summarize(d),
|
Summary: summarize(d, label),
|
||||||
}
|
}
|
||||||
if d.PublishedAt.Valid {
|
if d.PublishedAt.Valid {
|
||||||
v.PublishedAt = &d.PublishedAt.Time
|
v.PublishedAt = &d.PublishedAt.Time
|
||||||
@@ -159,11 +165,24 @@ var (
|
|||||||
policyKinds = map[string]string{judgement.KindHardRules: "hard rule", judgement.KindChangeRequest: "change request rule"}
|
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
|
var filter map[string]string
|
||||||
_ = json.Unmarshal(d.Filter, &filter)
|
_ = json.Unmarshal(d.Filter, &filter)
|
||||||
var b strings.Builder
|
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 {
|
if len(filter) > 0 {
|
||||||
pairs := make([]string, 0, len(filter))
|
pairs := make([]string, 0, len(filter))
|
||||||
for k, v := range 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)
|
return nil, m.fail(ctx, "encode filter", err)
|
||||||
}
|
}
|
||||||
d, err := m.store.Create(ctx, store.Draft{
|
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,
|
Filter: filter, Document: runs.InvestigateDocument(), PolicyKind: judgement.KindHardRules,
|
||||||
})
|
})
|
||||||
if err != nil {
|
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)
|
return nil, m.fail(ctx, "read the trigger filter", err)
|
||||||
}
|
}
|
||||||
if err := m.groups.SaveTrigger(ctx, events.TriggerSpec{
|
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 {
|
}); err != nil {
|
||||||
return nil, m.fail(ctx, "save the trigger", err)
|
return nil, m.fail(ctx, "save the trigger", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ type Draft struct {
|
|||||||
OrgID string `db:"org_id"`
|
OrgID string `db:"org_id"`
|
||||||
GroupID uuid.UUID `db:"group_id"`
|
GroupID uuid.UUID `db:"group_id"`
|
||||||
Name string `db:"name"`
|
Name string `db:"name"`
|
||||||
Source string `db:"source"`
|
SourceID uuid.UUID `db:"source_id"`
|
||||||
EventType string `db:"event_type"`
|
EventType string `db:"event_type"`
|
||||||
Filter jsontext.Value `db:"filter"`
|
Filter jsontext.Value `db:"filter"`
|
||||||
Document string `db:"document"`
|
Document string `db:"document"`
|
||||||
@@ -42,7 +42,7 @@ type Draft struct {
|
|||||||
UpdatedAt time.Time `db:"updated_at"`
|
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`
|
dry_run_id, dry_event_id, installed_version, published_at, created_at, updated_at`
|
||||||
|
|
||||||
// Store is the drafts module's Postgres store.
|
// 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.
|
// Create inserts a draft or returns the existing draft for the group.
|
||||||
func (s *Store) Create(ctx context.Context, d Draft) (Draft, error) {
|
func (s *Store) Create(ctx context.Context, d Draft) (Draft, error) {
|
||||||
_, err := s.db.ExecContext(ctx, `
|
_, 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)
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||||
ON CONFLICT (org_id, group_id) DO NOTHING`,
|
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 {
|
if err != nil {
|
||||||
return Draft{}, fmt.Errorf("create draft: %w", err)
|
return Draft{}, fmt.Errorf("create draft: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,10 +71,10 @@ func TestIntakeAppliesTheDeliveryPolicyBeforeStoring(t *testing.T) {
|
|||||||
wantStored int
|
wantStored int
|
||||||
wantAsked []string
|
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: "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 hook 203.0.113.9", "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 " + 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 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 " + 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 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 " + 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 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},
|
{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{}}
|
inserter := &onceInserter{stored: map[string]bool{}}
|
||||||
m := &Module{
|
m := &Module{
|
||||||
orgID: "default", log: slog.New(slog.DiscardHandler), inserter: inserter, deliveries: noEcho{},
|
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) {
|
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
|
||||||
return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil
|
return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil
|
||||||
},
|
},
|
||||||
@@ -95,7 +95,7 @@ func TestIntakeAppliesTheDeliveryPolicyBeforeStoring(t *testing.T) {
|
|||||||
var rec *httptest.ResponseRecorder
|
var rec *httptest.ResponseRecorder
|
||||||
for range tt.deliveries {
|
for range tt.deliveries {
|
||||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(`{}`))
|
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.RemoteAddr = "203.0.113.9:4711"
|
||||||
req.Header.Set("Authorization", "Bearer "+tt.bearer)
|
req.Header.Set("Authorization", "Bearer "+tt.bearer)
|
||||||
rec = httptest.NewRecorder()
|
rec = httptest.NewRecorder()
|
||||||
|
|||||||
+248
-111
@@ -8,7 +8,9 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
@@ -32,11 +34,15 @@ func (m *Module) Register(api huma.API) {
|
|||||||
Summary: "List sources", Tags: tags,
|
Summary: "List sources", Tags: tags,
|
||||||
}, m.sources)
|
}, m.sources)
|
||||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
|
||||||
OperationID: "put-source", Method: http.MethodPut, Path: "/api/sources/{name}",
|
OperationID: "create-source", Method: http.MethodPost, Path: "/api/sources",
|
||||||
Summary: "Add or update a source, its verification scheme and its token", Tags: tags,
|
Summary: "Add a source, owned by the organisation or by the caller", Tags: tags,
|
||||||
}, m.putSource)
|
}, m.createSource)
|
||||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
|
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,
|
Summary: "Set the fields a source's events are grouped by", Tags: tags,
|
||||||
}, m.putKeyFields)
|
}, m.putKeyFields)
|
||||||
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindTrigger), huma.Operation{
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindTrigger), huma.Operation{
|
||||||
@@ -61,72 +67,119 @@ func (m *Module) Register(api huma.API) {
|
|||||||
}, m.event)
|
}, m.event)
|
||||||
}
|
}
|
||||||
|
|
||||||
type putSourceInput struct {
|
// SourceSettings are what a source's connector and verification need.
|
||||||
Name string `path:"name" doc:"Lowercase letters, digits and hyphens; the webhook URL ends in it"`
|
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 {
|
Body struct {
|
||||||
Connector string `json:"connector" doc:"The connector that parses this source's events"`
|
Label string `json:"label" minLength:"1" maxLength:"100" doc:"The name people see, unique among the sources of the same owner"`
|
||||||
// A new source without a scheme uses a bearer token, so existing
|
WebhookPath string `json:"webhook_path,omitzero" doc:"Lowercase letters, digits and hyphens; the webhook URL ends in it. Defaults to the label"`
|
||||||
// senders keep working.
|
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"`
|
||||||
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"`
|
SourceSettings
|
||||||
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 sourceCreated struct {
|
type sourceCreated struct {
|
||||||
Source string `json:"source"`
|
ID uuid.UUID `json:"id"`
|
||||||
Token string `json:"token,omitzero" doc:"Returned once for a token source; only its hash is stored"`
|
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"`
|
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"`
|
URL string `json:"url" doc:"Where the sender posts its events"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// putSource creates or updates a source. A save that omits verification keeps
|
var pathChars = regexp.MustCompile(`[^a-z0-9]+`)
|
||||||
// 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
|
// pathFor derives a webhook path from a label.
|
||||||
// stored. An HMAC secret is sealed and never returned; a blank secret keeps the
|
func pathFor(label string) string {
|
||||||
// sealed one.
|
path := strings.Trim(pathChars.ReplaceAllString(strings.ToLower(label), "-"), "-")
|
||||||
func (m *Module) putSource(ctx context.Context, in *putSourceInput) (*httpapi.Reply[sourceCreated], error) {
|
if len(path) > 63 {
|
||||||
if !validName.MatchString(in.Name) || !validName.MatchString(in.Body.Connector) {
|
path = strings.Trim(path[:63], "-")
|
||||||
return nil, huma.Error400BadRequest("a source needs a lowercase name and a connector")
|
|
||||||
}
|
}
|
||||||
existing, err := m.store.Source(ctx, m.orgID, in.Name)
|
return path
|
||||||
if err != nil && !errors.Is(err, store.ErrNotFound) {
|
}
|
||||||
return nil, huma.Error500InternalServerError("couldn't read the source", err)
|
|
||||||
|
// 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 label == "" || !validName.MatchString(path) || !validName.MatchString(body.Connector) {
|
||||||
if err == nil {
|
return nil, huma.Error400BadRequest("a source needs a label, a webhook path of lowercase letters, digits and hyphens, and a connector")
|
||||||
stored = &existing
|
|
||||||
}
|
}
|
||||||
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if err := m.store.UpsertSource(ctx, src); err != nil {
|
if err := sourceWriteError(m.store.InsertSource(ctx, src)); err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't save the source", err)
|
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.
|
// issued is a credential generated for a saved source, returned once.
|
||||||
type issued struct{ token, secret string }
|
type issued struct{ token, secret string }
|
||||||
|
|
||||||
// sourceToSave builds the row to store from the request and the stored source,
|
// sourceToSave builds the row to store from the request settings, the source's
|
||||||
// if there is one. It returns the token or secret it generated, if any.
|
// fixed attributes in base, and the stored source if there is one. It returns
|
||||||
func (m *Module) sourceToSave(in *putSourceInput, stored *store.Source) (store.Source, issued, error) {
|
// the token or secret it generated, if any.
|
||||||
explicit := in.Body.Verification != ""
|
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
|
// The secret column is NOT NULL, so a source without a secret carries an
|
||||||
// empty value: the driver writes a nil slice as NULL.
|
// empty value: the driver writes a nil slice as NULL.
|
||||||
src := store.Source{
|
src := base
|
||||||
OrgID: m.orgID, Name: in.Name, Connector: in.Body.Connector,
|
src.Connector, src.Verification, src.HMACSecretSealed = set.Connector, set.Verification, []byte{}
|
||||||
Verification: in.Body.Verification, HMACSecretSealed: []byte{},
|
|
||||||
}
|
|
||||||
switch {
|
switch {
|
||||||
case !explicit && stored != nil:
|
case !explicit && stored != nil:
|
||||||
// Omitting the scheme keeps the stored one with its token or secret, so
|
// Omitting the scheme keeps the stored one with its token or secret, so
|
||||||
// a save cannot downgrade a source.
|
// a save cannot downgrade a source.
|
||||||
src = *stored
|
src = *stored
|
||||||
src.Connector = in.Body.Connector
|
src.Connector = set.Connector
|
||||||
case !explicit:
|
case !explicit:
|
||||||
src.Verification = store.Token
|
src.Verification = store.Token
|
||||||
}
|
}
|
||||||
@@ -147,7 +200,7 @@ func (m *Module) sourceToSave(in *putSourceInput, stored *store.Source) (store.S
|
|||||||
var secret string
|
var secret string
|
||||||
if explicit {
|
if explicit {
|
||||||
var err error
|
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
|
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
|
// 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,
|
// secret a source already has, and a source that has none gets a generated one,
|
||||||
// which is returned so it can be shown once.
|
// 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) {
|
func (m *Module) setHMAC(src *store.Source, set SourceSettings, stored *store.Source) (generated string, err error) {
|
||||||
src.HMACHeader, src.HMACPrefix = in.Body.HMACHeader, in.Body.HMACPrefix
|
src.HMACHeader, src.HMACPrefix = set.HMACHeader, set.HMACPrefix
|
||||||
secret := in.Body.HMACSecret
|
secret := set.HMACSecret
|
||||||
switch {
|
switch {
|
||||||
case secret != "":
|
case secret != "":
|
||||||
case stored != nil && len(stored.HMACSecretSealed) > 0:
|
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
|
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 {
|
if err != nil {
|
||||||
return "", huma.Error500InternalServerError("couldn't seal the secret", err)
|
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 {
|
type putTriggerInput struct {
|
||||||
Name string `path:"name" doc:"Lowercase letters, digits and hyphens"`
|
Name string `path:"name" doc:"Lowercase letters, digits and hyphens"`
|
||||||
Body struct {
|
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"`
|
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"`
|
Filter map[string]string `json:"filter,omitzero" doc:"Event fields that must match exactly"`
|
||||||
Workflow string `json:"workflow" doc:"The workflow each match runs"`
|
Workflow string `json:"workflow" doc:"The workflow each match runs"`
|
||||||
@@ -206,24 +259,38 @@ type triggerSaved struct {
|
|||||||
Trigger string `json:"trigger"`
|
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) {
|
func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.Reply[triggerSaved], error) {
|
||||||
req := in.Body
|
req := in.Body
|
||||||
var every sql.NullInt64
|
every, err := parseEvery(req.Every)
|
||||||
if req.Every != "" {
|
if err != nil {
|
||||||
d, err := time.ParseDuration(req.Every)
|
return nil, err
|
||||||
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")
|
if every.Valid {
|
||||||
}
|
req.SourceID, req.EventType = "", scheduleType
|
||||||
every = sql.NullInt64{Int64: int64(d / time.Second), Valid: true}
|
|
||||||
req.Source, req.EventType = scheduleSource, scheduleType
|
|
||||||
// Every schedule's ticks share a source and type, so the filter keeps
|
// Every schedule's ticks share a source and type, so the filter keeps
|
||||||
// this trigger to its own.
|
// this trigger to its own.
|
||||||
req.Filter = map[string]string{"trigger": in.Name}
|
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")
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -236,7 +303,7 @@ func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if err := m.store.UpsertTrigger(ctx, store.Trigger{
|
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,
|
Filter: filter, Workflow: req.Workflow, Enabled: !req.Disabled, Approved: approved,
|
||||||
EventTypeID: typeID, MappingID: mappingID, ScheduleEverySeconds: every,
|
EventTypeID: typeID, MappingID: mappingID, ScheduleEverySeconds: every,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
@@ -245,10 +312,33 @@ func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.
|
|||||||
return httpapi.OK(triggerSaved{Trigger: in.Name}), nil
|
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
|
// checkTargets refuses a trigger whose workflow can't be started or whose
|
||||||
// event type, mapping or connector event type doesn't exist.
|
// 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) {
|
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, source, eventTypeID, mappingID); err != nil {
|
if typeID, mapID, err = m.checkBinding(ctx, sourceID, eventTypeID, mappingID); err != nil {
|
||||||
return typeID, mapID, err
|
return typeID, mapID, err
|
||||||
}
|
}
|
||||||
if err := m.runs.CheckTrigger(ctx, m.orgID, workflow); err != nil {
|
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)
|
return typeID, mapID, huma.Error500InternalServerError("couldn't check the workflow", err)
|
||||||
}
|
}
|
||||||
if eventType != "" {
|
if eventType != "" {
|
||||||
err = m.checkEventType(ctx, source, eventType)
|
err = m.checkEventType(ctx, sourceID, eventType)
|
||||||
}
|
}
|
||||||
return typeID, mapID, err
|
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
|
// 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.
|
// 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 {
|
refuse := func(location, message string) error {
|
||||||
return huma.Error400BadRequest(message, &huma.ErrorDetail{Location: location, Message: message})
|
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")
|
return typeID, mapID, refuse("body.event_type_id", "an event type id is a UUID")
|
||||||
}
|
}
|
||||||
t, err := m.store.EventType(ctx, m.orgID, id)
|
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")
|
return typeID, mapID, refuse("body.event_type_id", "the source has no such event type")
|
||||||
}
|
}
|
||||||
if err != nil {
|
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
|
// 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
|
// connector doesn't declare, so the trigger can't be saved when it could never
|
||||||
// fire. Schedule triggers have no connector.
|
// fire, and a trigger on a source the caller can't use. Schedule triggers have
|
||||||
func (m *Module) checkEventType(ctx context.Context, source, eventType string) error {
|
// no source.
|
||||||
if source == scheduleSource {
|
func (m *Module) checkEventType(ctx context.Context, sourceID uuid.NullUUID, eventType string) error {
|
||||||
|
if !sourceID.Valid {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
refuse := func(location, message string) error {
|
refuse := func(location, message string) error {
|
||||||
return huma.Error400BadRequest(message, &huma.ErrorDetail{Location: location, Message: message})
|
return huma.Error400BadRequest(message, &huma.ErrorDetail{Location: location, Message: message})
|
||||||
}
|
}
|
||||||
src, err := m.reader.Source(ctx, m.orgID, source)
|
src, err := m.reader.Source(ctx, m.orgID, sourceID.UUID)
|
||||||
if errors.Is(err, store.ErrNotFound) {
|
if errors.Is(err, store.ErrNotFound) || (err == nil && !src.VisibleTo(caller(ctx))) {
|
||||||
return refuse("body.source", fmt.Sprintf("no source named %q", source))
|
return refuse("body.source_id", "no such source")
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return huma.Error500InternalServerError("couldn't read the source", err)
|
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 {
|
type putKeyFieldsInput struct {
|
||||||
Name string `path:"name"`
|
ID string `path:"id" format:"uuid"`
|
||||||
Body struct {
|
Body struct {
|
||||||
Paths []string `json:"paths,omitzero" doc:"Paths into the event's fields; none uses the connector's default"`
|
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 {
|
if err != nil {
|
||||||
return nil, huma.Error400BadRequest(err.Error())
|
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) {
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
return nil, huma.Error404NotFound("no such source")
|
return nil, huma.Error404NotFound("no such source")
|
||||||
}
|
}
|
||||||
@@ -390,23 +485,28 @@ type groupView struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type proposedTrigger 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"`
|
EventType string `json:"event_type"`
|
||||||
Filter jsontext.Value `json:"filter"`
|
Filter jsontext.Value `json:"filter"`
|
||||||
Workflow string `json:"workflow"`
|
Workflow string `json:"workflow"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Module) groups(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]groupView], error) {
|
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 {
|
if err != nil {
|
||||||
m.log.ErrorContext(ctx, "list groups", "error", err)
|
m.log.ErrorContext(ctx, "list groups", "error", err)
|
||||||
return nil, huma.Error500InternalServerError("couldn't list groups")
|
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))
|
out := make([]groupView, 0, len(groups))
|
||||||
for _, g := range groups {
|
for _, g := range groups {
|
||||||
out = append(out, groupView{
|
out = append(out, groupView{
|
||||||
ID: g.ID, Count: g.Count, FirstSeen: g.FirstSeen, LastSeen: g.LastSeen,
|
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
|
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
|
// sourceView is a source as the API returns it. The token is returned only
|
||||||
// when it is created or rotated, never here.
|
// when it is created or rotated, never here.
|
||||||
type sourceView struct {
|
type sourceView struct {
|
||||||
Name string `json:"name"`
|
ID uuid.UUID `json:"id"`
|
||||||
Connector string `json:"connector"`
|
// Scope is org for an organisation's source and person for one only its
|
||||||
KeyFields []string `json:"key_fields"`
|
// owner can see and use.
|
||||||
TokenSet bool `json:"token_set"`
|
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
|
// Verification and the HMAC header and prefix are shown; the secret is
|
||||||
// only reported as set.
|
// only reported as set.
|
||||||
Verification string `json:"verification"`
|
Verification string `json:"verification"`
|
||||||
HMACHeader string `json:"hmac_header,omitzero"`
|
HMACHeader string `json:"hmac_header,omitzero"`
|
||||||
HMACPrefix string `json:"hmac_prefix,omitzero"`
|
HMACPrefix string `json:"hmac_prefix,omitzero"`
|
||||||
HMACSecretSet bool `json:"hmac_secret_set"`
|
HMACSecretSet bool `json:"hmac_secret_set"`
|
||||||
// DisplayName labels the source, and DeliveryHeader names the header a
|
// DeliveryHeader names the header a sender repeats on every retry of one
|
||||||
// sender repeats on every retry of one delivery.
|
// delivery.
|
||||||
DisplayName string `json:"display_name,omitzero"`
|
|
||||||
DeliveryHeader string `json:"delivery_header,omitzero"`
|
DeliveryHeader string `json:"delivery_header,omitzero"`
|
||||||
// Signing is signed (HMAC), token, unsigned_pending_approval or unsigned.
|
// Signing is signed (HMAC), token, unsigned_pending_approval or unsigned.
|
||||||
Signing string `json:"signing" enum:"signed,token,unsigned_pending_approval,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) {
|
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 {
|
if err != nil {
|
||||||
m.log.ErrorContext(ctx, "list sources", "error", err)
|
m.log.ErrorContext(ctx, "list sources", "error", err)
|
||||||
return nil, huma.Error500InternalServerError("couldn't list sources")
|
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 {
|
for _, src := range sources {
|
||||||
view, err := viewOfSource(src)
|
view, err := viewOfSource(src)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
m.log.ErrorContext(ctx, "read source key fields", "source", src.Name, "error", err)
|
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.Name)
|
return nil, huma.Error500InternalServerError("couldn't read the key fields of " + src.Label)
|
||||||
}
|
}
|
||||||
out = append(out, view)
|
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) {
|
func viewOfSource(src store.Source) (sourceView, error) {
|
||||||
view := sourceView{
|
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,
|
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 len(src.KeyFields) > 0 {
|
||||||
if err := json.Unmarshal(src.KeyFields, &view.KeyFields); err != nil {
|
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.
|
// triggerView is a trigger as the API returns it.
|
||||||
type triggerView struct {
|
type triggerView struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Source string `json:"source"`
|
// 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"`
|
EventType string `json:"event_type"`
|
||||||
Filter map[string]string `json:"filter"`
|
Filter map[string]string `json:"filter"`
|
||||||
Workflow string `json:"workflow"`
|
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
|
// viewOfTrigger is the API's form of a stored trigger. Unsigned is set by the
|
||||||
// caller, which knows the sources.
|
// caller, which knows the sources.
|
||||||
func viewOfTrigger(t store.Trigger) (triggerView, error) {
|
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 len(t.Filter) > 0 {
|
||||||
if err := json.Unmarshal(t.Filter, &view.Filter); err != nil {
|
if err := json.Unmarshal(t.Filter, &view.Filter); err != nil {
|
||||||
return view, fmt.Errorf("filter of %s: %w", t.Name, err)
|
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 {
|
if t.ScheduleEverySeconds.Valid {
|
||||||
view.Every = (time.Duration(t.ScheduleEverySeconds.Int64) * time.Second).String()
|
view.Every = (time.Duration(t.ScheduleEverySeconds.Int64) * time.Second).String()
|
||||||
}
|
}
|
||||||
|
if t.SourceID.Valid {
|
||||||
|
view.SourceID = t.SourceID.UUID.String()
|
||||||
|
}
|
||||||
if t.EventTypeID.Valid {
|
if t.EventTypeID.Valid {
|
||||||
view.EventTypeID = t.EventTypeID.UUID.String()
|
view.EventTypeID = t.EventTypeID.UUID.String()
|
||||||
}
|
}
|
||||||
@@ -524,8 +635,10 @@ func (m *Module) viewOfTrigger(ctx context.Context, t store.Trigger) (triggerVie
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return view, err
|
return view, err
|
||||||
}
|
}
|
||||||
if src, err := m.store.Source(ctx, m.orgID, t.Source); err == nil {
|
if t.SourceID.Valid {
|
||||||
view.Unsigned = src.Verification == store.None
|
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
|
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)
|
m.log.ErrorContext(ctx, "list triggers", "error", err)
|
||||||
return nil, huma.Error500InternalServerError("couldn't list triggers")
|
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 {
|
if err != nil {
|
||||||
m.log.ErrorContext(ctx, "list sources", "error", err)
|
m.log.ErrorContext(ctx, "list sources", "error", err)
|
||||||
return nil, huma.Error500InternalServerError("couldn't list triggers")
|
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 {
|
for _, src := range sources {
|
||||||
unsigned[src.Name] = src.Verification == store.None
|
visible[src.ID] = src
|
||||||
}
|
}
|
||||||
out := make([]triggerView, 0, len(triggers))
|
out := make([]triggerView, 0, len(triggers))
|
||||||
for _, t := range triggers {
|
for _, t := range triggers {
|
||||||
|
src, seen := visible[t.SourceID.UUID]
|
||||||
|
if t.SourceID.Valid && !seen {
|
||||||
|
continue
|
||||||
|
}
|
||||||
view, err := viewOfTrigger(t)
|
view, err := viewOfTrigger(t)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
m.log.ErrorContext(ctx, "read trigger", "trigger", t.Name, "error", err)
|
m.log.ErrorContext(ctx, "read trigger", "trigger", t.Name, "error", err)
|
||||||
return nil, huma.Error500InternalServerError("couldn't read the filter of " + t.Name)
|
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)
|
out = append(out, view)
|
||||||
}
|
}
|
||||||
return httpapi.OK(out), nil
|
return httpapi.OK(out), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type recentInput struct {
|
type recentInput struct {
|
||||||
Limit int `query:"limit" minimum:"1" maximum:"500" default:"50"`
|
Limit int `query:"limit" minimum:"1" maximum:"500" default:"50"`
|
||||||
Source string `query:"source"`
|
SourceID string `query:"source_id" format:"uuid"`
|
||||||
Type string `query:"type"`
|
Type string `query:"type"`
|
||||||
Matched string `query:"matched" enum:"true,false" doc:"Only events a trigger did or didn't match"`
|
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) {
|
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 != "" {
|
if in.Matched != "" {
|
||||||
matched, err := strconv.ParseBool(in.Matched)
|
matched, err := strconv.ParseBool(in.Matched)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -574,13 +698,17 @@ func (m *Module) recent(ctx context.Context, in *recentInput) (*httpapi.Reply[[]
|
|||||||
}
|
}
|
||||||
filter.Matched = &matched
|
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 {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't list events", err)
|
return nil, huma.Error500InternalServerError("couldn't list events", err)
|
||||||
}
|
}
|
||||||
out := make([]eventView, 0, len(events))
|
out := make([]eventView, 0, len(events))
|
||||||
for _, e := range events {
|
for _, e := range events {
|
||||||
out = append(out, viewOf(e))
|
out = append(out, viewOf(e, labels))
|
||||||
}
|
}
|
||||||
return httpapi.OK(out), nil
|
return httpapi.OK(out), nil
|
||||||
}
|
}
|
||||||
@@ -618,7 +746,7 @@ func (m *Module) event(ctx context.Context, in *eventInput) (*httpapi.Reply[even
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error400BadRequest("an event id is a UUID")
|
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) {
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
return nil, huma.Error404NotFound("no such event")
|
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)
|
m.log.ErrorContext(ctx, "read event runs", "event", id, "error", err)
|
||||||
return nil, huma.Error500InternalServerError("couldn't read the runs of the event")
|
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() {
|
if len(view.Body) == 0 || !view.Body.IsValid() {
|
||||||
view.Body = jsontext.Value("null")
|
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.
|
// eventView is an event as the API returns it.
|
||||||
type eventView struct {
|
type eventView struct {
|
||||||
ID uuid.UUID `json:"id"`
|
ID uuid.UUID `json:"id"`
|
||||||
Source string `json:"source"`
|
// 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"`
|
Type string `json:"type"`
|
||||||
Fields jsontext.Value `json:"fields"`
|
Fields jsontext.Value `json:"fields"`
|
||||||
LinkedTo *uuid.UUID `json:"linked_to,omitempty"`
|
LinkedTo *uuid.UUID `json:"linked_to,omitempty"`
|
||||||
@@ -657,12 +791,15 @@ type eventView struct {
|
|||||||
Verification string `json:"verification,omitempty"`
|
Verification string `json:"verification,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func viewOf(e store.Event) eventView {
|
func viewOf(e store.Event, labels map[uuid.UUID]string) eventView {
|
||||||
v := eventView{
|
v := eventView{
|
||||||
Verification: e.Verification,
|
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,
|
ReceivedAt: e.ReceivedAt, Matched: e.Matched,
|
||||||
}
|
}
|
||||||
|
if e.SourceID.Valid {
|
||||||
|
v.SourceID = &e.SourceID.UUID
|
||||||
|
}
|
||||||
if e.OccurredAt.Valid {
|
if e.OccurredAt.Valid {
|
||||||
v.OccurredAt = &e.OccurredAt.Time
|
v.OccurredAt = &e.OccurredAt.Time
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,13 +53,14 @@ func (m *Module) registerCapture(api huma.API) {
|
|||||||
|
|
||||||
// captureView is a stored delivery as the inspector shows it.
|
// captureView is a stored delivery as the inspector shows it.
|
||||||
type captureView struct {
|
type captureView struct {
|
||||||
ID uuid.UUID `json:"id"`
|
ID uuid.UUID `json:"id"`
|
||||||
ReceivedAt time.Time `json:"received_at"`
|
ReceivedAt time.Time `json:"received_at"`
|
||||||
Source string `json:"source"`
|
SourceID *uuid.UUID `json:"source_id,omitempty"`
|
||||||
RemoteAddr string `json:"remote_addr,omitempty"`
|
Source string `json:"source,omitempty" doc:"The source's label"`
|
||||||
ContentType string `json:"content_type,omitempty"`
|
RemoteAddr string `json:"remote_addr,omitempty"`
|
||||||
Headers string `json:"headers"`
|
ContentType string `json:"content_type,omitempty"`
|
||||||
Body string `json:"body"`
|
Headers string `json:"headers"`
|
||||||
|
Body string `json:"body"`
|
||||||
// Verification is how the delivery was verified: signed, token or unsigned.
|
// Verification is how the delivery was verified: signed, token or unsigned.
|
||||||
Verification string `json:"verification" enum:"signed,token,unsigned,"`
|
Verification string `json:"verification" enum:"signed,token,unsigned,"`
|
||||||
// EventType is the id of the event type the delivery was identified as.
|
// 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) {
|
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 {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't list captures", err)
|
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 {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't list sources", err)
|
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 })
|
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}
|
out := capturesBody{Captures: make([]captureView, 0, len(rows)), Enabled: enabled}
|
||||||
for _, e := range rows {
|
for _, e := range rows {
|
||||||
out.Captures = append(out.Captures, captureOf(e))
|
out.Captures = append(out.Captures, captureOf(e, labels))
|
||||||
}
|
}
|
||||||
return httpapi.OK(out), nil
|
return httpapi.OK(out), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func captureOf(e store.Event) captureView {
|
func captureOf(e store.Event, labels map[uuid.UUID]string) captureView {
|
||||||
v := 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,
|
Headers: string(e.Headers), Body: string(e.Body), Verification: e.Verification,
|
||||||
}
|
}
|
||||||
v.ContentType = eventtype.ParseHeaders(v.Headers)["content-type"]
|
v.ContentType = eventtype.ParseHeaders(v.Headers)["content-type"]
|
||||||
|
if e.SourceID.Valid {
|
||||||
|
v.SourceID = &e.SourceID.UUID
|
||||||
|
}
|
||||||
if e.EventTypeID.Valid {
|
if e.EventTypeID.Valid {
|
||||||
v.EventType = e.EventTypeID.UUID.String()
|
v.EventType = e.EventTypeID.UUID.String()
|
||||||
}
|
}
|
||||||
@@ -123,6 +131,11 @@ func (m *Module) captureDispatches(ctx context.Context, in *idInput) (*httpapi.R
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error400BadRequest("a capture id is a UUID")
|
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)
|
runs, err := m.store.RunsForEvent(ctx, m.orgID, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't read the runs of the capture", err)
|
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.
|
// eventTypeView is an event type as the inspector reads it.
|
||||||
type eventTypeView struct {
|
type eventTypeView struct {
|
||||||
ID uuid.UUID `json:"id"`
|
ID uuid.UUID `json:"id"`
|
||||||
Source string `json:"source"`
|
SourceID uuid.UUID `json:"source_id"`
|
||||||
Name string `json:"name"`
|
Source string `json:"source" doc:"The source's label"`
|
||||||
Rule eventtype.Rule `json:"rule"`
|
Name string `json:"name"`
|
||||||
Schema map[string]eventtype.ValueType `json:"schema"`
|
Rule eventtype.Rule `json:"rule"`
|
||||||
|
Schema map[string]eventtype.ValueType `json:"schema"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type eventTypesBody struct {
|
type eventTypesBody struct {
|
||||||
@@ -153,7 +167,11 @@ type eventTypesBody struct {
|
|||||||
const proposalScan = 500
|
const proposalScan = 500
|
||||||
|
|
||||||
func (m *Module) eventTypes(ctx context.Context, _ *struct{}) (*httpapi.Reply[eventTypesBody], error) {
|
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 {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't list event types", err)
|
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))}
|
out := eventTypesBody{Enabled: true, EventTypes: make([]eventTypeView, 0, len(types))}
|
||||||
for i, t := range 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 {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't list captures", err)
|
return nil, huma.Error500InternalServerError("couldn't list captures", err)
|
||||||
}
|
}
|
||||||
@@ -185,20 +203,21 @@ func unidentified(types []eventtype.EventType, captured []store.Event) []eventty
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
sample := eventtype.Sample{Headers: eventtype.ParseHeaders(string(e.Headers)), Body: e.Body}
|
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
|
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
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
type createEventTypeInput struct {
|
type createEventTypeInput struct {
|
||||||
Body struct {
|
Body struct {
|
||||||
Source string `json:"source"`
|
SourceID string `json:"source_id" format:"uuid"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Rule *eventtype.Rule `json:"rule,omitzero" doc:"The conditions that identify the type; inferred from the example when absent"`
|
Rule *eventtype.Rule `json:"rule,omitzero" doc:"The conditions that identify the type; inferred from the example when absent"`
|
||||||
Example struct {
|
Example struct {
|
||||||
Headers map[string]string `json:"headers,omitzero"`
|
Headers map[string]string `json:"headers,omitzero"`
|
||||||
Body string `json:"body,omitzero"`
|
Body string `json:"body,omitzero"`
|
||||||
} `json:"example,omitzero"`
|
} `json:"example,omitzero"`
|
||||||
@@ -207,17 +226,21 @@ type createEventTypeInput struct {
|
|||||||
|
|
||||||
func (m *Module) createEventType(ctx context.Context, in *createEventTypeInput) (*httpapi.Reply[eventTypeView], error) {
|
func (m *Module) createEventType(ctx context.Context, in *createEventTypeInput) (*httpapi.Reply[eventTypeView], error) {
|
||||||
req := in.Body
|
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 {
|
if req.Rule != nil {
|
||||||
t.Rule = *req.Rule
|
t.Rule = *req.Rule
|
||||||
}
|
}
|
||||||
if err := t.Validate(); err != nil {
|
if err := t.Validate(); err != nil {
|
||||||
return nil, huma.Error400BadRequest(err.Error())
|
return nil, huma.Error400BadRequest(err.Error())
|
||||||
}
|
}
|
||||||
if _, err := m.store.Source(ctx, m.orgID, t.Source); errors.Is(err, store.ErrNotFound) {
|
sourceID, err := uuid.Parse(t.SourceID)
|
||||||
return nil, huma.Error400BadRequest("no source named " + t.Source)
|
if err != nil {
|
||||||
} else 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)
|
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 {
|
if err := m.checkOverlap(ctx, t); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -231,21 +254,25 @@ func (m *Module) createEventType(ctx context.Context, in *createEventTypeInput)
|
|||||||
return nil, huma.Error400BadRequest(err.Error())
|
return nil, huma.Error400BadRequest(err.Error())
|
||||||
}
|
}
|
||||||
id := uuid.New()
|
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) {
|
if errors.Is(err, store.ErrExists) {
|
||||||
return nil, huma.Error409Conflict("the source already has an event type named " + t.Name)
|
return nil, huma.Error409Conflict("the source already has an event type named " + t.Name)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't save the event type", err)
|
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
|
// 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
|
// source already matches, since an event is identified only when one type
|
||||||
// matches it.
|
// matches it.
|
||||||
func (m *Module) checkOverlap(ctx context.Context, candidate eventtype.EventType) error {
|
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 {
|
if err != nil {
|
||||||
return huma.Error500InternalServerError("couldn't list event types", err)
|
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 {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't read the event type", err)
|
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 {
|
if err := t.Validate(); err != nil {
|
||||||
return nil, huma.Error400BadRequest(err.Error())
|
return nil, huma.Error400BadRequest(err.Error())
|
||||||
}
|
}
|
||||||
@@ -325,7 +352,7 @@ func (m *Module) deleteEventType(ctx context.Context, in *idInput) (*struct{}, e
|
|||||||
type mappingView struct {
|
type mappingView struct {
|
||||||
ID uuid.UUID `json:"id"`
|
ID uuid.UUID `json:"id"`
|
||||||
Name string `json:"name"`
|
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"`
|
EventTypeID uuid.UUID `json:"event_type_id"`
|
||||||
Fields []mapping.Field `json:"fields"`
|
Fields []mapping.Field `json:"fields"`
|
||||||
MatchCount int64 `json:"match_count"`
|
MatchCount int64 `json:"match_count"`
|
||||||
@@ -336,9 +363,12 @@ type mappingView struct {
|
|||||||
|
|
||||||
func mappingOf(r store.Mapping) (mappingView, error) {
|
func mappingOf(r store.Mapping) (mappingView, error) {
|
||||||
v := mappingView{
|
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,
|
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 {
|
if err := json.Unmarshal(r.Fields, &v.Fields); err != nil {
|
||||||
return v, err
|
return v, err
|
||||||
}
|
}
|
||||||
@@ -391,7 +421,7 @@ func (m *Module) mapping(ctx context.Context, in *idInput) (*httpapi.Reply[mappi
|
|||||||
|
|
||||||
type mappingBody struct {
|
type mappingBody struct {
|
||||||
Name string `json:"name"`
|
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"`
|
EventTypeID string `json:"event_type_id" format:"uuid"`
|
||||||
Fields []mapping.Field `json:"fields"`
|
Fields []mapping.Field `json:"fields"`
|
||||||
}
|
}
|
||||||
@@ -432,7 +462,20 @@ func (m *Module) checkedMapping(ctx context.Context, b mappingBody) (store.Mappi
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return store.Mapping{}, huma.Error400BadRequest(err.Error())
|
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) {
|
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 {
|
if err != nil {
|
||||||
return nil, huma.Error400BadRequest("a capture id is a UUID")
|
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) {
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
return nil, huma.Error404NotFound("no such capture")
|
return nil, huma.Error404NotFound("no such capture")
|
||||||
}
|
}
|
||||||
|
|||||||
+110
-50
@@ -11,6 +11,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
|
"github.com/google/uuid"
|
||||||
"golang.org/x/net/http/httpguts"
|
"golang.org/x/net/http/httpguts"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
"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}
|
return huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags}
|
||||||
}
|
}
|
||||||
admin := httpapi.AdminAuthorized[governance.Action, governance.ResourceKind]
|
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-label", http.MethodPut, "/api/sources/{id}/label", "Rename a source"), m.setSourceLabel)
|
||||||
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-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-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-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-signing", http.MethodPost, "/api/sources/{name}/signing", "Require an HMAC signature, or ask to take unsigned deliveries"), m.setSigning)
|
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.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.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.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.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.ActionDelete, governance.KindSource), op("delete-source", http.MethodDelete, "/api/sources/{name}", "Delete a source"), m.deleteSource)
|
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.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)
|
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 {
|
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
|
// 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
|
return signingPending
|
||||||
}
|
}
|
||||||
|
|
||||||
// readSource loads a source for a settings change.
|
// readSource loads a source for a request. A person's source that belongs to
|
||||||
func (m *Module) readSource(ctx context.Context, name string) (store.Source, error) {
|
// someone else reads as missing, so its existence isn't disclosed.
|
||||||
src, err := m.store.Source(ctx, m.orgID, name)
|
func (m *Module) readSource(ctx context.Context, rawID string) (store.Source, error) {
|
||||||
if errors.Is(err, store.ErrNotFound) {
|
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")
|
return src, huma.Error404NotFound("no such source")
|
||||||
}
|
}
|
||||||
if err != nil {
|
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
|
// sourceReply reads a source back after a change. secret is a signing secret
|
||||||
// issued by the change, returned once.
|
// issued by the change, returned once.
|
||||||
func (m *Module) sourceReply(ctx context.Context, name, secret string) (*httpapi.Reply[sourceView], error) {
|
func (m *Module) sourceReply(ctx context.Context, id, secret string) (*httpapi.Reply[sourceView], error) {
|
||||||
src, err := m.readSource(ctx, name)
|
src, err := m.readSource(ctx, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
view, err := viewOfSource(src)
|
view, err := viewOfSource(src)
|
||||||
if err != nil {
|
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
|
view.Secret = secret
|
||||||
return httpapi.OK(view), nil
|
return httpapi.OK(view), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type sourceNameInput struct {
|
type sourceLabelInput struct {
|
||||||
Name string `path:"name"`
|
ID string `path:"id" format:"uuid"`
|
||||||
Body struct {
|
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) {
|
func (m *Module) setSourceLabel(ctx context.Context, in *sourceLabelInput) (*httpapi.Reply[sourceView], error) {
|
||||||
err := m.store.SetDisplayName(ctx, m.orgID, in.Name, strings.TrimSpace(in.Body.Name))
|
src, err := m.readSource(ctx, in.ID)
|
||||||
if err := sourceWriteError(err); err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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 {
|
type deliveryHeaderInput struct {
|
||||||
Name string `path:"name"`
|
ID string `path:"id" format:"uuid"`
|
||||||
Body struct {
|
Body struct {
|
||||||
Header string `json:"header" doc:"A header name; empty stops de-duplicating retries by header"`
|
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)
|
header = textproto.CanonicalMIMEHeaderKey(header)
|
||||||
}
|
}
|
||||||
err := m.store.SetDeliveryHeader(ctx, m.orgID, in.Name, header)
|
src, err := m.readSource(ctx, in.ID)
|
||||||
if err := sourceWriteError(err); err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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 {
|
type captureInput struct {
|
||||||
Name string `path:"name"`
|
ID string `path:"id" format:"uuid"`
|
||||||
Body struct {
|
Body struct {
|
||||||
Capture bool `json:"capture"`
|
Capture bool `json:"capture"`
|
||||||
}
|
}
|
||||||
@@ -142,8 +189,12 @@ type captureInput struct {
|
|||||||
// that maps the source's payload needs the stored payload, so it blocks
|
// that maps the source's payload needs the stored payload, so it blocks
|
||||||
// turning capture off.
|
// turning capture off.
|
||||||
func (m *Module) setCapture(ctx context.Context, in *captureInput) (*httpapi.Reply[sourceView], error) {
|
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 {
|
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 {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't check the triggers of the source", err)
|
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))
|
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(m.store.SetCapture(ctx, m.orgID, src.ID, in.Body.Capture)); err != nil {
|
||||||
if err := sourceWriteError(err); err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return m.sourceReply(ctx, in.Name, "")
|
return m.sourceReply(ctx, in.ID, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
type signingInput struct {
|
type signingInput struct {
|
||||||
Name string `path:"name"`
|
ID string `path:"id" format:"uuid"`
|
||||||
Body struct {
|
Body struct {
|
||||||
Signed bool `json:"signed" doc:"True requires an HMAC signature; false asks to take deliveries without one, which a person must approve"`
|
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) {
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
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 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.
|
// approveUnsigned accepts that a source takes deliveries with no verification.
|
||||||
func (m *Module) approveUnsigned(ctx context.Context, in *sourceInput) (*httpapi.Reply[sourceView], error) {
|
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 {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't approve the source", err)
|
return nil, huma.Error500InternalServerError("couldn't approve the source", err)
|
||||||
}
|
}
|
||||||
if !approved {
|
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 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) {
|
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -214,7 +265,7 @@ func (m *Module) rotateSecret(ctx context.Context, in *sourceInput) (*httpapi.Re
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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.
|
// 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 {
|
if err != nil {
|
||||||
return "", huma.Error500InternalServerError("couldn't generate a secret", err)
|
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 {
|
if err != nil {
|
||||||
return "", huma.Error500InternalServerError("couldn't seal the secret", err)
|
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 "", huma.Error500InternalServerError("couldn't save the secret", err)
|
||||||
}
|
}
|
||||||
return secret, nil
|
return secret, nil
|
||||||
@@ -248,6 +299,8 @@ func sourceWriteError(err error) error {
|
|||||||
return nil
|
return nil
|
||||||
case errors.Is(err, store.ErrNotFound):
|
case errors.Is(err, store.ErrNotFound):
|
||||||
return huma.Error404NotFound("no such source")
|
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)
|
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;
|
// deleteSource removes a source. A trigger that names it blocks the delete;
|
||||||
// its event types go with it, and the events it stored stay.
|
// its event types go with it, and the events it stored stay.
|
||||||
func (m *Module) deleteSource(ctx context.Context, in *sourceInput) (*struct{}, error) {
|
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 {
|
switch {
|
||||||
case errors.Is(err, store.ErrNotFound):
|
case errors.Is(err, store.ErrNotFound):
|
||||||
return nil, huma.Error404NotFound("no such source")
|
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
|
// moveTrigger changes a trigger's state when it is in one of from, and refuses
|
||||||
// otherwise.
|
// otherwise.
|
||||||
func (m *Module) moveTrigger(ctx context.Context, name string, allowed func(store.Trigger) bool, refusal string, approved, enabled bool) (*httpapi.Reply[triggerView], error) {
|
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)
|
t, err := m.visibleTrigger(ctx, name)
|
||||||
if errors.Is(err, store.ErrNotFound) {
|
|
||||||
return nil, huma.Error404NotFound("no such trigger")
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't read the trigger", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
if !allowed(t) {
|
if !allowed(t) {
|
||||||
return nil, huma.Error409Conflict(refusal)
|
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
|
// started continue, and the dispatch records that link them to their events stay
|
||||||
// under the trigger's name.
|
// under the trigger's name.
|
||||||
func (m *Module) deleteTrigger(ctx context.Context, in *triggerInput) (*struct{}, error) {
|
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)
|
err := m.store.DeleteTrigger(ctx, m.orgID, in.Name)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, store.ErrNotFound):
|
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) {
|
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)
|
rows, err := m.store.DispatchesOf(ctx, m.orgID, in.Name, in.Limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, huma.Error500InternalServerError("couldn't list the runs of the trigger", err)
|
return nil, huma.Error500InternalServerError("couldn't list the runs of the trigger", err)
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ type arrival struct {
|
|||||||
|
|
||||||
// typeReader lists a source's event types.
|
// typeReader lists a source's event types.
|
||||||
type typeReader interface {
|
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
|
// 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 {
|
if m.types == nil {
|
||||||
return 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 {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -99,7 +99,7 @@ func (m *Module) identify(ctx context.Context, row *store.Event, src store.Sourc
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
sample := eventtype.Sample{Headers: lowered(h), Body: row.Body}
|
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)
|
id, err := uuid.Parse(found.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("event type id %q: %w", found.ID, err)
|
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) {
|
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 {
|
if err := json.Unmarshal(r.Rule, &t.Rule); err != nil {
|
||||||
return t, fmt.Errorf("event type %q rule: %w", r.Name, err)
|
return t, fmt.Errorf("event type %q rule: %w", r.Name, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,11 +43,11 @@ func TestIntakeRecordsHowEachDeliveryWasVerified(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
sealed, err := sealer.Seal(secretLabel("org", "hook"), []byte(secret))
|
sealed, err := sealer.Seal(secretLabel("org", hookID), []byte(secret))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
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 := base
|
||||||
hmacSource.Verification, hmacSource.HMACHeader, hmacSource.HMACPrefix, hmacSource.HMACSecretSealed = store.HMAC, "X-Signature", "sha256=", sealed
|
hmacSource.Verification, hmacSource.HMACHeader, hmacSource.HMACPrefix, hmacSource.HMACSecretSealed = store.HMAC, "X-Signature", "sha256=", sealed
|
||||||
tokenSource := base
|
tokenSource := base
|
||||||
@@ -83,7 +83,7 @@ func TestIntakeRecordsHowEachDeliveryWasVerified(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(body))
|
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)
|
maps.Copy(req.Header, tt.header)
|
||||||
req.Header.Set("Cookie", "session=not-a-real-cookie")
|
req.Header.Set("Cookie", "session=not-a-real-cookie")
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ func TestIntakeEvaluatesThePolicyAgainstTheClientBehindTrustedProxies(t *testing
|
|||||||
policy := &deliveryPolicy{decision: governance.Allowed()}
|
policy := &deliveryPolicy{decision: governance.Allowed()}
|
||||||
m := &Module{
|
m := &Module{
|
||||||
orgID: "default", log: slog.New(slog.DiscardHandler), inserter: &onceInserter{stored: map[string]bool{}}, deliveries: noEcho{},
|
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) {
|
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
|
||||||
return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil
|
return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil
|
||||||
},
|
},
|
||||||
@@ -55,7 +55,7 @@ func TestIntakeEvaluatesThePolicyAgainstTheClientBehindTrustedProxies(t *testing
|
|||||||
m.UseDeliveryPolicy(policy)
|
m.UseDeliveryPolicy(policy)
|
||||||
m.UseTrustedProxies(func(context.Context) ([]netip.Prefix, error) { return tt.trusted, tt.readErr })
|
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 := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(`{}`))
|
||||||
req.SetPathValue("source", "hook")
|
req.SetPathValue("path", "hook")
|
||||||
req.RemoteAddr = tt.peer
|
req.RemoteAddr = tt.peer
|
||||||
req.Header.Set("Authorization", "Bearer "+token)
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
for _, h := range tt.headers {
|
for _, h := range tt.headers {
|
||||||
@@ -66,7 +66,7 @@ func TestIntakeEvaluatesThePolicyAgainstTheClientBehindTrustedProxies(t *testing
|
|||||||
if rec.Code != http.StatusAccepted {
|
if rec.Code != http.StatusAccepted {
|
||||||
t.Fatalf("status %d, want %d", 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)
|
t.Fatalf("delivery policy asked %v, want %q", policy.asked, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -15,7 +15,10 @@ import (
|
|||||||
// Group is a set of unmatched events that share a key, with the trigger it
|
// Group is a set of unmatched events that share a key, with the trigger it
|
||||||
// proposes.
|
// proposes.
|
||||||
type Group struct {
|
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
|
Source string
|
||||||
EventType string
|
EventType string
|
||||||
Filter map[string]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 {
|
if err := json.Unmarshal(g.Filter, &filter); err != nil {
|
||||||
return Group{}, false, fmt.Errorf("group %s filter: %w", id, err)
|
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{
|
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,
|
Count: g.Count, FirstSeen: g.FirstSeen, LastSeen: g.LastSeen,
|
||||||
}, true, nil
|
}, 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.
|
// TriggerSpec is an event trigger to save.
|
||||||
type TriggerSpec struct {
|
type TriggerSpec struct {
|
||||||
Name string
|
Name string
|
||||||
Source string
|
SourceID uuid.UUID
|
||||||
EventType string
|
EventType string
|
||||||
Filter map[string]string
|
Filter map[string]string
|
||||||
Workflow string
|
Workflow string
|
||||||
@@ -78,7 +85,7 @@ type TriggerSpec struct {
|
|||||||
|
|
||||||
// SaveTrigger creates or replaces an event trigger.
|
// SaveTrigger creates or replaces an event trigger.
|
||||||
func (m *Module) SaveTrigger(ctx context.Context, t TriggerSpec) error {
|
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")
|
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 {
|
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 fmt.Errorf("encode filter: %w", err)
|
||||||
}
|
}
|
||||||
return m.store.UpsertTrigger(ctx, store.Trigger{
|
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,
|
Filter: filter, Workflow: t.Workflow, Enabled: true, Approved: true,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
+29
-23
@@ -116,9 +116,11 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealer Sealer, c Con
|
|||||||
return m
|
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 {
|
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
|
// 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
|
// Routes adds the webhook intake. It stays outside the API because each
|
||||||
// source verifies its own deliveries.
|
// source verifies its own deliveries.
|
||||||
func (m *Module) Routes(mux *http.ServeMux) {
|
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
|
// 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
|
// the connector for parsing. A delivery that fails verification is rejected
|
||||||
// with 401 before the connector sees its body, and the rejection is logged.
|
// 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
|
// 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) {
|
func (m *Module) accept(r *http.Request) (d delivery, status int, err error) {
|
||||||
ctx := r.Context()
|
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) {
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
return d, http.StatusUnauthorized, errUnknown
|
return d, http.StatusUnauthorized, errUnknown
|
||||||
}
|
}
|
||||||
@@ -233,7 +235,7 @@ var (
|
|||||||
// refuse logs why a delivery was rejected and chooses the status: 401 when
|
// refuse logs why a delivery was rejected and chooses the status: 401 when
|
||||||
// verification failed, 503 when verification could not run.
|
// verification failed, 503 when verification could not run.
|
||||||
func (m *Module) refuse(ctx context.Context, d delivery, err error) (delivery, int, error) {
|
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) {
|
if errors.Is(err, errUnverified) {
|
||||||
return d, http.StatusUnauthorized, errUnknown
|
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
|
// Delivery policies belong to the operating organisation, whatever the
|
||||||
// source's own org id says.
|
// 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 {
|
switch {
|
||||||
case d.Allowed:
|
case d.Allowed:
|
||||||
return admission{src: src}, 0, nil
|
return admission{src: src}, 0, nil
|
||||||
case errors.Is(d.Err, governance.ErrChainUnavailable):
|
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
|
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
|
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) {
|
func (m *Module) Work(ctx context.Context) {
|
||||||
var listeners sync.WaitGroup
|
var listeners sync.WaitGroup
|
||||||
defer listeners.Wait()
|
defer listeners.Wait()
|
||||||
listening := map[string]bool{}
|
listening := map[uuid.UUID]bool{}
|
||||||
nextCheck, nextTick := time.Time{}, time.Time{}
|
nextCheck, nextTick := time.Time{}, time.Time{}
|
||||||
for ctx.Err() == nil {
|
for ctx.Err() == nil {
|
||||||
if now := time.Now(); now.After(nextTick) {
|
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
|
// startListeners starts one listener for each source whose connector listens
|
||||||
// and has none yet. A listener lives until ctx ends.
|
// 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)
|
sources, err := m.store.Sources(ctx, m.orgID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
m.log.ErrorContext(ctx, "list sources", "error", err)
|
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 {
|
for _, src := range sources {
|
||||||
conn, ok := m.connectors.Get(ctx, src.Connector)
|
conn, ok := m.connectors.Get(ctx, src.Connector)
|
||||||
if listening[src.Name] || !ok || !conn.Listens() {
|
if listening[src.ID] || !ok || !conn.Listens() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
listening[src.Name] = true
|
listening[src.ID] = true
|
||||||
wg.Go(func() { m.listen(ctx, src) })
|
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 {
|
if ctx.Err() != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
m.log.WarnContext(ctx, "listening stopped", "source", src.Name, "error", err)
|
m.log.WarnContext(ctx, "listening stopped", "source", src.ID, "error", err)
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
case <-time.After(listenRetry):
|
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 {
|
if err := m.storeListened(ctx, src, events); err != nil {
|
||||||
return err
|
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
|
// 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 {
|
if !ok {
|
||||||
return nil
|
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) {
|
if errors.Is(err, approvals.ErrUnlinked) {
|
||||||
m.replyUnlinked(ctx, e, src, a.ChatID)
|
m.replyUnlinked(ctx, e, src, a.ChatID)
|
||||||
return nil
|
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, so a connector can only speak for its own accounts: by must name the
|
||||||
// source's connector.
|
// source's connector.
|
||||||
func (m *Module) sender(ctx context.Context, e store.Event, by string) (store.Source, governance.Subject, bool) {
|
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 {
|
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
|
return store.Source{}, governance.Subject{}, false
|
||||||
}
|
}
|
||||||
prefix, subject, found := strings.Cut(by, ":")
|
prefix, subject, found := strings.Cut(by, ":")
|
||||||
if !found || prefix != src.Connector || subject == "" {
|
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 store.Source{}, governance.Subject{}, false
|
||||||
}
|
}
|
||||||
return src, governance.Subject{Issuer: src.Connector, Subject: subject}, true
|
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 {
|
if err != nil || linked {
|
||||||
return false, err
|
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 {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
@@ -696,7 +702,7 @@ func (m *Module) noteUnmatched(ctx context.Context, tx *sqlx.Tx, e store.Event)
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if created {
|
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
|
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{}, ok, err
|
||||||
}
|
}
|
||||||
return runs.Origin{
|
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,
|
ReceivedAt: o.ReceivedAt, Trigger: o.Trigger, Filter: o.Filter,
|
||||||
}, true, nil
|
}, true, nil
|
||||||
}
|
}
|
||||||
@@ -746,7 +752,7 @@ func runInput(e store.Event) jsontext.Value {
|
|||||||
// payload under "mapped" when there are any.
|
// payload under "mapped" when there are any.
|
||||||
func runInputWith(e store.Event, mapped map[string]any) jsontext.Value {
|
func runInputWith(e store.Event, mapped map[string]any) jsontext.Value {
|
||||||
doc := map[string]any{"event": map[string]any{
|
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 {
|
if mapped != nil {
|
||||||
doc["mapped"] = mapped
|
doc["mapped"] = mapped
|
||||||
|
|||||||
@@ -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
|
// 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
|
// values at keyFields. It also returns those values as the filter of the
|
||||||
// trigger the group proposes.
|
// 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 {
|
if len(keyFields) == 0 {
|
||||||
keyFields = defaultKeyFields
|
keyFields = defaultKeyFields
|
||||||
}
|
}
|
||||||
@@ -35,7 +35,7 @@ func groupKey(source, eventType string, fields jsontext.Value, keyFields []strin
|
|||||||
}
|
}
|
||||||
slices.Sort(paths)
|
slices.Sort(paths)
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
b.WriteString(source + "\x00" + eventType)
|
b.WriteString(sourceID.String() + "\x00" + eventType)
|
||||||
for _, p := range paths {
|
for _, p := range paths {
|
||||||
b.WriteString("\x00" + p + "=" + filter[p])
|
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.
|
// 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 {
|
func newRow(orgID string, src store.Source, e connectors.Event, body []byte, own bool, runID uuid.UUID) store.Event {
|
||||||
row := 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,
|
Fields: e.Fields, Body: body, Own: own,
|
||||||
}
|
}
|
||||||
row.LinkKey.String, row.LinkKey.Valid = e.LinkKey, e.LinkKey != ""
|
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}
|
row.OriginRunID = uuid.NullUUID{UUID: runID, Valid: runID != uuid.Nil}
|
||||||
return row
|
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.
|
// A map of strings always encodes.
|
||||||
raw, _ := json.Marshal(filter)
|
raw, _ := json.Marshal(filter)
|
||||||
row.GroupKey = sql.NullString{String: key, Valid: true}
|
row.GroupKey = sql.NullString{String: key, Valid: true}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import (
|
|||||||
// carries a group key, so it can't become a proposal, and events differing
|
// carries a group key, so it can't become a proposal, and events differing
|
||||||
// only outside the key fields share one key.
|
// only outside the key fields share one key.
|
||||||
func TestNewRowGrouping(t *testing.T) {
|
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()
|
run := uuid.New()
|
||||||
ev := func(fields string) connectors.Event {
|
ev := func(fields string) connectors.Event {
|
||||||
return connectors.Event{Type: "alert.firing", SourceEventID: fields, Fields: []byte(fields)}
|
return connectors.Event{Type: "alert.firing", SourceEventID: fields, Fields: []byte(fields)}
|
||||||
|
|||||||
@@ -51,11 +51,11 @@ type Rule struct {
|
|||||||
// EventType is a named kind of event from one source. Schema is the inferred
|
// 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.
|
// structure (path to type) of the payload it was created from.
|
||||||
type EventType struct {
|
type EventType struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Source string `json:"source"`
|
SourceID string `json:"source_id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Rule Rule `json:"rule"`
|
Rule Rule `json:"rule"`
|
||||||
Schema map[string]ValueType `json:"schema"`
|
Schema map[string]ValueType `json:"schema"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate refuses an event type that has no name or source or carries a
|
// 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) == "" {
|
if strings.TrimSpace(t.Name) == "" {
|
||||||
return fmt.Errorf("%w: name is required", ErrInvalid)
|
return fmt.Errorf("%w: name is required", ErrInvalid)
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(t.Source) == "" {
|
if strings.TrimSpace(t.SourceID) == "" {
|
||||||
return fmt.Errorf("%w: source is required", ErrInvalid)
|
return fmt.Errorf("%w: source id is required", ErrInvalid)
|
||||||
}
|
}
|
||||||
for _, h := range t.Rule.Headers {
|
for _, h := range t.Rule.Headers {
|
||||||
if strings.TrimSpace(h.Name) == "" {
|
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.
|
// same source. A type is not compared with itself, so an update passes.
|
||||||
func CheckOverlap(existing []EventType, candidate EventType) error {
|
func CheckOverlap(existing []EventType, candidate EventType) error {
|
||||||
for _, t := range existing {
|
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
|
continue
|
||||||
}
|
}
|
||||||
if Overlaps(t.Rule, candidate.Rule) {
|
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) {
|
func Identify(types []EventType, source string, s Sample) (EventType, bool) {
|
||||||
var found []EventType
|
var found []EventType
|
||||||
for _, t := range types {
|
for _, t := range types {
|
||||||
if t.Source == source && t.Rule.Matches(s) {
|
if t.SourceID == source && t.Rule.Matches(s) {
|
||||||
found = append(found, t)
|
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.
|
// when it has none, the presence of each top-level payload key.
|
||||||
func FromExample(source, name string, s Sample) EventType {
|
func FromExample(source, name string, s Sample) EventType {
|
||||||
sig := Sign(s)
|
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)
|
t.Rule.Headers = headerConditions(sig.Headers)
|
||||||
if len(t.Rule.Headers) == 0 {
|
if len(t.Rule.Headers) == 0 {
|
||||||
for _, path := range slices.Sorted(maps.Keys(sig.Paths)) {
|
for _, path := range slices.Sorted(maps.Keys(sig.Paths)) {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
// Capture is one stored event as proposal grouping reads it.
|
// Capture is one stored event as proposal grouping reads it.
|
||||||
type Capture struct {
|
type Capture struct {
|
||||||
ID string
|
ID string
|
||||||
Source string
|
SourceID string
|
||||||
ReceivedAt time.Time
|
ReceivedAt time.Time
|
||||||
Sample Sample
|
Sample Sample
|
||||||
}
|
}
|
||||||
@@ -19,7 +19,7 @@ type Capture struct {
|
|||||||
// to the operator as an event type to name. Rule is the set of
|
// 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.
|
// discriminators that separates the group from its siblings on the source.
|
||||||
type Proposal struct {
|
type Proposal struct {
|
||||||
Source string `json:"source"`
|
SourceID string `json:"source_id"`
|
||||||
Key string `json:"key"`
|
Key string `json:"key"`
|
||||||
Schema map[string]ValueType `json:"schema"`
|
Schema map[string]ValueType `json:"schema"`
|
||||||
Headers map[string]string `json:"headers"`
|
Headers map[string]string `json:"headers"`
|
||||||
@@ -38,18 +38,18 @@ func Propose(captures []Capture) []Proposal {
|
|||||||
for _, c := range captures {
|
for _, c := range captures {
|
||||||
sig := Sign(c.Sample)
|
sig := Sign(c.Sample)
|
||||||
key := sig.Key()
|
key := sig.Key()
|
||||||
id := c.Source + "\x00" + key
|
id := c.SourceID + "\x00" + key
|
||||||
if g, ok := index[id]; ok {
|
if g, ok := index[id]; ok {
|
||||||
g.Count++
|
g.Count++
|
||||||
continue
|
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
|
index[id] = g
|
||||||
sigs[g] = sig
|
sigs[g] = sig
|
||||||
groups = append(groups, g)
|
groups = append(groups, g)
|
||||||
}
|
}
|
||||||
slices.SortStableFunc(groups, func(a, b *Proposal) int {
|
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 c
|
||||||
}
|
}
|
||||||
return b.Count - a.Count
|
return b.Count - a.Count
|
||||||
@@ -58,7 +58,7 @@ func Propose(captures []Capture) []Proposal {
|
|||||||
for _, g := range groups {
|
for _, g := range groups {
|
||||||
var siblings []Signature
|
var siblings []Signature
|
||||||
for _, s := range groups {
|
for _, s := range groups {
|
||||||
if s != g && s.Source == g.Source {
|
if s != g && s.SourceID == g.SourceID {
|
||||||
siblings = append(siblings, sigs[s])
|
siblings = append(siblings, sigs[s])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ type Field struct {
|
|||||||
type Mapping struct {
|
type Mapping struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
SourceHint string `json:"source_hint"`
|
SourceID string `json:"source_id"`
|
||||||
EventTypeID string `json:"event_type_id"`
|
EventTypeID string `json:"event_type_id"`
|
||||||
Fields []Field `json:"fields"`
|
Fields []Field `json:"fields"`
|
||||||
MatchCount int64 `json:"match_count"`
|
MatchCount int64 `json:"match_count"`
|
||||||
|
|||||||
@@ -19,6 +19,13 @@ var ErrInUse = errors.New("in use")
|
|||||||
// ErrExists means a row with that name already exists.
|
// ErrExists means a row with that name already exists.
|
||||||
var ErrExists = errors.New("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
|
// Postgres reports a delete blocked by ON DELETE RESTRICT as 23001 and a
|
||||||
// reference to a missing row as 23503.
|
// reference to a missing row as 23503.
|
||||||
const (
|
const (
|
||||||
@@ -41,16 +48,28 @@ func classify(err error) error {
|
|||||||
return err
|
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,
|
// Captures returns the events whose source kept their headers and payload,
|
||||||
// newest first.
|
// newest first, for the sources the person may see.
|
||||||
func (s *Store) Captures(ctx context.Context, orgID string, limit int) ([]Event, error) {
|
func (s *Store) Captures(ctx context.Context, orgID, person string, limit int) ([]Event, error) {
|
||||||
var out []Event
|
var out []Event
|
||||||
if err := s.db.SelectContext(ctx, &out, `
|
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
|
event_type_id, received_at, occurred_at
|
||||||
FROM events.events
|
FROM events.events
|
||||||
WHERE org_id = $1 AND headers IS NOT NULL
|
WHERE org_id = $1 AND headers IS NOT NULL AND `+visibleSource+`
|
||||||
ORDER BY received_at DESC, id LIMIT $2`, orgID, limit); err != nil {
|
ORDER BY received_at DESC, id LIMIT $3`, orgID, person, limit); err != nil {
|
||||||
return nil, fmt.Errorf("list captures: %w", err)
|
return nil, fmt.Errorf("list captures: %w", err)
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
@@ -60,7 +79,7 @@ func (s *Store) Captures(ctx context.Context, orgID string, limit int) ([]Event,
|
|||||||
type EventType struct {
|
type EventType struct {
|
||||||
ID uuid.UUID `db:"id"`
|
ID uuid.UUID `db:"id"`
|
||||||
OrgID string `db:"org_id"`
|
OrgID string `db:"org_id"`
|
||||||
Source string `db:"source"`
|
SourceID uuid.UUID `db:"source_id"`
|
||||||
Name string `db:"name"`
|
Name string `db:"name"`
|
||||||
Rule jsontext.Value `db:"rule"`
|
Rule jsontext.Value `db:"rule"`
|
||||||
Schema jsontext.Value `db:"schema"`
|
Schema jsontext.Value `db:"schema"`
|
||||||
@@ -68,23 +87,24 @@ type EventType struct {
|
|||||||
UpdatedAt time.Time `db:"updated_at"`
|
UpdatedAt time.Time `db:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// EventTypes returns the organisation's event types, by source and name.
|
// EventTypes returns the event types of the sources the person may see, by
|
||||||
func (s *Store) EventTypes(ctx context.Context, orgID string) ([]EventType, error) {
|
// source and name.
|
||||||
|
func (s *Store) EventTypes(ctx context.Context, orgID, person string) ([]EventType, error) {
|
||||||
var out []EventType
|
var out []EventType
|
||||||
if err := s.db.SelectContext(ctx, &out, `
|
if err := s.db.SelectContext(ctx, &out, `
|
||||||
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 ORDER BY source, name`, orgID); err != nil {
|
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 nil, fmt.Errorf("list event types: %w", err)
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// EventTypesOf returns the event types of one source.
|
// 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
|
var out []EventType
|
||||||
if err := s.db.SelectContext(ctx, &out, `
|
if err := s.db.SelectContext(ctx, &out, `
|
||||||
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 source = $2 ORDER BY name`, orgID, source); err != nil {
|
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 nil, fmt.Errorf("list event types of source: %w", err)
|
||||||
}
|
}
|
||||||
return out, nil
|
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) {
|
func (s *Store) EventType(ctx context.Context, orgID string, id uuid.UUID) (EventType, error) {
|
||||||
var t EventType
|
var t EventType
|
||||||
err := s.db.GetContext(ctx, &t, `
|
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)
|
FROM events.event_types WHERE org_id = $1 AND id = $2`, orgID, id)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return EventType{}, ErrNotFound
|
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.
|
// InsertEventType stores a new event type.
|
||||||
func (s *Store) InsertEventType(ctx context.Context, t EventType) error {
|
func (s *Store) InsertEventType(ctx context.Context, t EventType) error {
|
||||||
if _, err := s.db.NamedExecContext(ctx, `
|
if _, err := s.db.NamedExecContext(ctx, `
|
||||||
INSERT INTO events.event_types (id, org_id, source, name, rule, schema)
|
INSERT INTO events.event_types (id, org_id, source_id, name, rule, schema)
|
||||||
VALUES (:id, :org_id, :source, :name, :rule, :schema)`, t); err != nil {
|
VALUES (:id, :org_id, :source_id, :name, :rule, :schema)`, t); err != nil {
|
||||||
return fmt.Errorf("save event type: %w", classify(err))
|
return fmt.Errorf("save event type: %w", classify(err))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -148,7 +168,7 @@ type Mapping struct {
|
|||||||
ID uuid.UUID `db:"id"`
|
ID uuid.UUID `db:"id"`
|
||||||
OrgID string `db:"org_id"`
|
OrgID string `db:"org_id"`
|
||||||
Name string `db:"name"`
|
Name string `db:"name"`
|
||||||
SourceHint string `db:"source_hint"`
|
SourceID uuid.NullUUID `db:"source_id"`
|
||||||
EventTypeID uuid.UUID `db:"event_type_id"`
|
EventTypeID uuid.UUID `db:"event_type_id"`
|
||||||
Fields jsontext.Value `db:"fields"`
|
Fields jsontext.Value `db:"fields"`
|
||||||
MatchCount int64 `db:"match_count"`
|
MatchCount int64 `db:"match_count"`
|
||||||
@@ -157,7 +177,7 @@ type Mapping struct {
|
|||||||
UpdatedAt time.Time `db:"updated_at"`
|
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.
|
// Mappings returns the organisation's mappings, by name.
|
||||||
func (s *Store) Mappings(ctx context.Context, orgID string) ([]Mapping, error) {
|
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.
|
// InsertMapping stores a new mapping.
|
||||||
func (s *Store) InsertMapping(ctx context.Context, m Mapping) error {
|
func (s *Store) InsertMapping(ctx context.Context, m Mapping) error {
|
||||||
if _, err := s.db.NamedExecContext(ctx, `
|
if _, err := s.db.NamedExecContext(ctx, `
|
||||||
INSERT INTO events.mappings (id, org_id, name, source_hint, event_type_id, fields)
|
INSERT INTO events.mappings (id, org_id, name, source_id, event_type_id, fields)
|
||||||
VALUES (:id, :org_id, :name, :source_hint, :event_type_id, :fields)`, m); err != nil {
|
VALUES (:id, :org_id, :name, :source_id, :event_type_id, :fields)`, m); err != nil {
|
||||||
return fmt.Errorf("save mapping: %w", classify(err))
|
return fmt.Errorf("save mapping: %w", classify(err))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -204,7 +224,7 @@ func (s *Store) InsertMapping(ctx context.Context, m Mapping) error {
|
|||||||
// count is kept.
|
// count is kept.
|
||||||
func (s *Store) UpdateMapping(ctx context.Context, m Mapping) error {
|
func (s *Store) UpdateMapping(ctx context.Context, m Mapping) error {
|
||||||
res, err := s.db.NamedExecContext(ctx, `
|
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()
|
fields = :fields, updated_at = now()
|
||||||
WHERE org_id = :org_id AND id = :id`, m)
|
WHERE org_id = :org_id AND id = :id`, m)
|
||||||
if err != nil {
|
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
|
// SetSourceColumn changes one of a source's single-value settings. column is
|
||||||
// always a constant of this package.
|
// 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, `
|
res, err := s.db.ExecContext(ctx, `
|
||||||
UPDATE events.sources SET `+column+` = $3, updated_at = now() WHERE org_id = $1 AND name = $2`,
|
UPDATE events.sources SET `+column+` = $3, updated_at = now() WHERE org_id = $1 AND id = $2`,
|
||||||
orgID, name, value)
|
orgID, id, value)
|
||||||
if err != nil {
|
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 {
|
if n, err := res.RowsAffected(); err != nil || n == 0 {
|
||||||
return ErrNotFound
|
return ErrNotFound
|
||||||
@@ -260,38 +280,44 @@ func (s *Store) setSource(ctx context.Context, orgID, name, column string, value
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetDisplayName labels a source.
|
// SetLabel renames a source. The label is unique within the source's scope.
|
||||||
func (s *Store) SetDisplayName(ctx context.Context, orgID, name, display string) error {
|
func (s *Store) SetLabel(ctx context.Context, orgID string, id uuid.UUID, label string) error {
|
||||||
return s.setSource(ctx, orgID, name, "display_name", display)
|
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.
|
// SetDeliveryHeader names the header a sender repeats on a delivery's retries.
|
||||||
func (s *Store) SetDeliveryHeader(ctx context.Context, orgID, name, header string) error {
|
func (s *Store) SetDeliveryHeader(ctx context.Context, orgID string, id uuid.UUID, header string) error {
|
||||||
return s.setSource(ctx, orgID, name, "delivery_header", header)
|
return s.setSource(ctx, orgID, id, "delivery_header", header)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetCapture turns the keeping of a source's headers and payloads on or off.
|
// 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 {
|
func (s *Store) SetCapture(ctx context.Context, orgID string, id uuid.UUID, capture bool) error {
|
||||||
return s.setSource(ctx, orgID, name, "capture", capture)
|
return s.setSource(ctx, orgID, id, "capture", capture)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetSecret replaces a source's sealed signing secret.
|
// SetSecret replaces a source's sealed signing secret.
|
||||||
func (s *Store) SetSecret(ctx context.Context, orgID, name string, sealed []byte) error {
|
func (s *Store) SetSecret(ctx context.Context, orgID string, id uuid.UUID, sealed []byte) error {
|
||||||
return s.setSource(ctx, orgID, name, "hmac_secret_sealed", sealed)
|
return s.setSource(ctx, orgID, id, "hmac_secret_sealed", sealed)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetSigning switches a source between an HMAC signature and no verification.
|
// SetSigning switches a source between an HMAC signature and no verification.
|
||||||
// Turning signing off leaves the source unapproved, so it refuses deliveries
|
// Turning signing off leaves the source unapproved, so it refuses deliveries
|
||||||
// until a person approves it; the signature header and secret are kept so
|
// until a person approves it; the signature header and secret are kept so
|
||||||
// signing can be required again.
|
// 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
|
verification := None
|
||||||
if signed {
|
if signed {
|
||||||
verification = HMAC
|
verification = HMAC
|
||||||
}
|
}
|
||||||
res, err := s.db.ExecContext(ctx, `
|
res, err := s.db.ExecContext(ctx, `
|
||||||
UPDATE events.sources SET verification = $3, unsigned_approved = false, updated_at = now()
|
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 {
|
if err != nil {
|
||||||
return fmt.Errorf("save source: %w", err)
|
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
|
// ApproveUnsigned accepts that a source with no verification takes
|
||||||
// deliveries. It reports false when the source isn't waiting for approval.
|
// 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, `
|
res, err := s.db.ExecContext(ctx, `
|
||||||
UPDATE events.sources SET unsigned_approved = true, updated_at = now()
|
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 {
|
if err != nil {
|
||||||
return false, fmt.Errorf("approve source: %w", err)
|
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
|
// 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
|
// that still uses it blocks the delete; stored events and their dispatch
|
||||||
// history stay.
|
// 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)
|
tx, err := s.db.BeginTxx(ctx, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("begin delete source: %w", err)
|
return fmt.Errorf("begin delete source: %w", err)
|
||||||
}
|
}
|
||||||
defer func() { _ = tx.Rollback() }()
|
defer func() { _ = tx.Rollback() }()
|
||||||
var triggers int
|
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)
|
return fmt.Errorf("check triggers of source: %w", err)
|
||||||
}
|
}
|
||||||
if triggers > 0 {
|
if triggers > 0 {
|
||||||
return fmt.Errorf("%w: %d trigger(s) use it", ErrInUse, triggers)
|
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))
|
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 {
|
if err != nil {
|
||||||
return fmt.Errorf("delete source: %w", err)
|
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
|
// MappedTriggers counts the triggers of a source that read events with a
|
||||||
// mapping, which needs the stored payload.
|
// 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
|
var n int
|
||||||
if err := s.db.GetContext(ctx, &n, `
|
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 0, fmt.Errorf("count mapped triggers: %w", err)
|
||||||
}
|
}
|
||||||
return n, nil
|
return n, nil
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import (
|
|||||||
func (s *Store) GroupByID(ctx context.Context, orgID string, id uuid.UUID) (Group, bool, error) {
|
func (s *Store) GroupByID(ctx context.Context, orgID string, id uuid.UUID) (Group, bool, error) {
|
||||||
var g Group
|
var g Group
|
||||||
err := s.db.GetContext(ctx, &g, `
|
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)
|
FROM events.groups WHERE org_id = $1 AND id = $2`, orgID, id)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return Group{}, false, nil
|
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) {
|
func (s *Store) GroupEvents(ctx context.Context, orgID string, id uuid.UUID, limit int) ([]Event, error) {
|
||||||
var out []Event
|
var out []Event
|
||||||
if err := s.db.SelectContext(ctx, &out, `
|
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
|
e.received_at, e.matched, e.dispatched_at, e.own, e.origin_run_id, e.group_key, e.group_filter
|
||||||
FROM events.events e
|
FROM events.events e
|
||||||
JOIN events.groups g ON g.org_id = e.org_id AND g.key = e.group_key
|
JOIN events.groups g ON g.org_id = e.org_id AND g.key = e.group_key
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// SetKeyFields replaces the paths a source's events are grouped by.
|
// 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, `
|
res, err := s.db.ExecContext(ctx, `
|
||||||
UPDATE events.sources SET key_fields = $3, updated_at = now() WHERE org_id = $1 AND name = $2`,
|
UPDATE events.sources SET key_fields = $3, updated_at = now() WHERE org_id = $1 AND id = $2`,
|
||||||
orgID, name, paths)
|
orgID, id, paths)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("save key fields: %w", err)
|
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.
|
// and filter are the trigger it proposes.
|
||||||
type Group struct {
|
type Group struct {
|
||||||
ID uuid.UUID `db:"id"`
|
ID uuid.UUID `db:"id"`
|
||||||
Source string `db:"source"`
|
SourceID uuid.UUID `db:"source_id"`
|
||||||
EventType string `db:"event_type"`
|
EventType string `db:"event_type"`
|
||||||
Filter jsontext.Value `db:"filter"`
|
Filter jsontext.Value `db:"filter"`
|
||||||
Count int64 `db:"count"`
|
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
|
// 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.
|
// 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) {
|
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
|
return false, nil
|
||||||
}
|
}
|
||||||
var created bool
|
var created bool
|
||||||
err := tx.QueryRowxContext(ctx, `
|
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)
|
VALUES ($1, $2, $3, $4, $5, $6, 1, $7, $7)
|
||||||
ON CONFLICT (org_id, key) DO UPDATE
|
ON CONFLICT (org_id, key) DO UPDATE
|
||||||
SET count = events.groups.count + 1,
|
SET count = events.groups.count + 1,
|
||||||
first_seen = LEAST(events.groups.first_seen, EXCLUDED.first_seen),
|
first_seen = LEAST(events.groups.first_seen, EXCLUDED.first_seen),
|
||||||
last_seen = GREATEST(events.groups.last_seen, EXCLUDED.last_seen)
|
last_seen = GREATEST(events.groups.last_seen, EXCLUDED.last_seen)
|
||||||
RETURNING xmax = 0`,
|
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 {
|
if err != nil {
|
||||||
return false, fmt.Errorf("group event: %w", err)
|
return false, fmt.Errorf("group event: %w", err)
|
||||||
}
|
}
|
||||||
return created, nil
|
return created, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Groups returns the groups no trigger covers, newest activity first. A group
|
// Groups returns the groups no trigger covers, newest activity first, for the
|
||||||
// stops being listed once a trigger exists for its source, type and filter.
|
// sources the person may see. A group stops being listed once a trigger exists
|
||||||
func (s *Store) Groups(ctx context.Context, orgID string, limit int) ([]Group, error) {
|
// for its source, type and filter.
|
||||||
|
func (s *Store) Groups(ctx context.Context, orgID, person string, limit int) ([]Group, error) {
|
||||||
var out []Group
|
var out []Group
|
||||||
if err := s.db.SelectContext(ctx, &out, `
|
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
|
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
|
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)
|
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 nil, fmt.Errorf("list groups: %w", err)
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
|
|||||||
@@ -25,10 +25,26 @@ const (
|
|||||||
None = "none"
|
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 {
|
type Source struct {
|
||||||
OrgID string `db:"org_id"`
|
ID uuid.UUID `db:"id"`
|
||||||
Name string `db:"name"`
|
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"`
|
Connector string `db:"connector"`
|
||||||
TokenSHA256 string `db:"token_sha256"`
|
TokenSHA256 string `db:"token_sha256"`
|
||||||
// Verification is the scheme that deliveries must pass: Token, HMAC or None.
|
// Verification is the scheme that deliveries must pass: Token, HMAC or None.
|
||||||
@@ -43,9 +59,8 @@ type Source struct {
|
|||||||
Cursor string `db:"cursor"`
|
Cursor string `db:"cursor"`
|
||||||
// KeyFields are the paths its events are grouped by; none means the default.
|
// KeyFields are the paths its events are grouped by; none means the default.
|
||||||
KeyFields jsontext.Value `db:"key_fields"`
|
KeyFields jsontext.Value `db:"key_fields"`
|
||||||
// DisplayName labels the source for people. DeliveryHeader names the header
|
// DeliveryHeader names the header a sender repeats on every retry of one
|
||||||
// a sender repeats on every retry of one delivery.
|
// delivery.
|
||||||
DisplayName string `db:"display_name"`
|
|
||||||
DeliveryHeader string `db:"delivery_header"`
|
DeliveryHeader string `db:"delivery_header"`
|
||||||
// UnsignedApproved says a person accepted that a None source does no
|
// UnsignedApproved says a person accepted that a None source does no
|
||||||
// verification. A None source refuses deliveries until then.
|
// verification. A None source refuses deliveries until then.
|
||||||
@@ -54,11 +69,19 @@ type Source struct {
|
|||||||
Capture bool `db:"capture"`
|
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.
|
// Event is one stored event.
|
||||||
type Event struct {
|
type Event struct {
|
||||||
ID uuid.UUID `db:"id"`
|
ID uuid.UUID `db:"id"`
|
||||||
OrgID string `db:"org_id"`
|
OrgID string `db:"org_id"`
|
||||||
Source string `db:"source"`
|
// 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"`
|
Type string `db:"type"`
|
||||||
SourceEventID string `db:"source_event_id"`
|
SourceEventID string `db:"source_event_id"`
|
||||||
LinkKey sql.NullString `db:"link_key"`
|
LinkKey sql.NullString `db:"link_key"`
|
||||||
@@ -101,9 +124,10 @@ const (
|
|||||||
// Trigger starts a workflow for events of one type from one source whose
|
// Trigger starts a workflow for events of one type from one source whose
|
||||||
// fields match its filter.
|
// fields match its filter.
|
||||||
type Trigger struct {
|
type Trigger struct {
|
||||||
OrgID string `db:"org_id"`
|
OrgID string `db:"org_id"`
|
||||||
Name string `db:"name"`
|
Name string `db:"name"`
|
||||||
Source string `db:"source"`
|
// SourceID is null for a scheduled trigger, which has no source.
|
||||||
|
SourceID uuid.NullUUID `db:"source_id"`
|
||||||
EventType string `db:"event_type"`
|
EventType string `db:"event_type"`
|
||||||
Filter jsontext.Value `db:"filter"`
|
Filter jsontext.Value `db:"filter"`
|
||||||
Workflow string `db:"workflow"`
|
Workflow string `db:"workflow"`
|
||||||
@@ -129,13 +153,14 @@ type Store struct {
|
|||||||
// New returns a store on db.
|
// New returns a store on db.
|
||||||
func New(db *sqlx.DB) *Store { return &Store{db: db} }
|
func New(db *sqlx.DB) *Store { return &Store{db: db} }
|
||||||
|
|
||||||
// Source returns the named source.
|
const sourceColumns = `id, scope, org_id, person_id, label, webhook_path, connector, token_sha256, verification,
|
||||||
func (s *Store) Source(ctx context.Context, orgID, name string) (Source, error) {
|
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
|
var src Source
|
||||||
err := s.db.GetContext(ctx, &src, `
|
err := s.db.GetContext(ctx, &src, `SELECT `+sourceColumns+` FROM events.sources WHERE org_id = $1 AND id = $2`, orgID, id)
|
||||||
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)
|
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return Source{}, ErrNotFound
|
return Source{}, ErrNotFound
|
||||||
}
|
}
|
||||||
@@ -145,56 +170,97 @@ func (s *Store) Source(ctx context.Context, orgID, name string) (Source, error)
|
|||||||
return src, nil
|
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) {
|
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
|
var out []Source
|
||||||
if err := s.db.SelectContext(ctx, &out, `
|
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,
|
SELECT `+sourceColumns+` FROM events.sources
|
||||||
display_name, delivery_header, unsigned_approved, capture FROM events.sources
|
WHERE org_id = $1 AND (person_id IS NULL OR person_id = $2) ORDER BY label`, orgID, person); err != nil {
|
||||||
WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
|
||||||
return nil, fmt.Errorf("list sources: %w", err)
|
return nil, fmt.Errorf("list sources: %w", err)
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetCursor records where a listening source resumes.
|
// 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, `
|
if _, err := s.db.ExecContext(ctx, `
|
||||||
UPDATE events.sources SET cursor = $3, updated_at = now() WHERE org_id = $1 AND name = $2`,
|
UPDATE events.sources SET cursor = $3, updated_at = now() WHERE org_id = $1 AND id = $2`,
|
||||||
orgID, name, cursor); err != nil {
|
orgID, id, cursor); err != nil {
|
||||||
return fmt.Errorf("save cursor: %w", err)
|
return fmt.Errorf("save cursor: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpsertSource creates a source or replaces its connector and token.
|
// InsertSource stores a new source. It returns ErrLabelTaken or ErrPathTaken
|
||||||
func (s *Store) UpsertSource(ctx context.Context, src Source) error {
|
// 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, `
|
if _, err := s.db.NamedExecContext(ctx, `
|
||||||
INSERT INTO events.sources (org_id, name, connector, token_sha256, verification, hmac_header, hmac_prefix, hmac_secret_sealed)
|
INSERT INTO events.sources (id, scope, org_id, person_id, label, webhook_path, connector, token_sha256,
|
||||||
VALUES (:org_id, :name, :connector, :token_sha256, :verification, :hmac_header, :hmac_prefix, :hmac_secret_sealed)
|
verification, hmac_header, hmac_prefix, hmac_secret_sealed)
|
||||||
ON CONFLICT (org_id, name) DO UPDATE
|
VALUES (:id, :scope, :org_id, :person_id, :label, :webhook_path, :connector, :token_sha256,
|
||||||
SET connector = EXCLUDED.connector, token_sha256 = EXCLUDED.token_sha256,
|
:verification, :hmac_header, :hmac_prefix, :hmac_secret_sealed)`, src); err != nil {
|
||||||
verification = EXCLUDED.verification, hmac_header = EXCLUDED.hmac_header,
|
return fmt.Errorf("save source: %w", classifySource(err))
|
||||||
hmac_prefix = EXCLUDED.hmac_prefix, hmac_secret_sealed = EXCLUDED.hmac_secret_sealed,
|
}
|
||||||
unsigned_approved = EXCLUDED.verification = 'none' AND events.sources.verification = 'none'
|
return nil
|
||||||
AND events.sources.unsigned_approved,
|
}
|
||||||
updated_at = now()`, src); err != nil {
|
|
||||||
return fmt.Errorf("save source: %w", err)
|
// 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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Insert stores an event unless its source already delivered the same source
|
// 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) {
|
func (s *Store) Insert(ctx context.Context, e Event) (bool, error) {
|
||||||
res, err := s.db.NamedExecContext(ctx, `
|
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,
|
own, origin_run_id, group_key, group_filter, verification, headers, remote_addr,
|
||||||
event_type_id)
|
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,
|
:own, :origin_run_id, :group_key, :group_filter, :verification, :headers, :remote_addr,
|
||||||
:event_type_id)
|
:event_type_id)
|
||||||
ON CONFLICT (org_id, source, source_event_id) DO NOTHING`, e)
|
ON CONFLICT DO NOTHING`, e)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, fmt.Errorf("store event: %w", err)
|
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() }()
|
defer func() { _ = tx.Rollback() }()
|
||||||
var e Event
|
var e Event
|
||||||
err = tx.GetContext(ctx, &e, `
|
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
|
received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter, event_type_id
|
||||||
FROM events.events WHERE dispatched_at IS NULL
|
FROM events.events WHERE dispatched_at IS NULL
|
||||||
ORDER BY received_at FOR UPDATE SKIP LOCKED LIMIT 1`)
|
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 {
|
if !e.LinkKey.Valid {
|
||||||
return false, nil
|
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)`
|
AND (received_at, id) < ($5, $1)`
|
||||||
res, err := tx.ExecContext(ctx, `
|
res, err := tx.ExecContext(ctx, `
|
||||||
UPDATE events.events SET linked_to = (
|
UPDATE events.events SET linked_to = (
|
||||||
SELECT id FROM events.events WHERE `+earlier+`
|
SELECT id FROM events.events WHERE `+earlier+`
|
||||||
ORDER BY received_at, id LIMIT 1)
|
ORDER BY received_at, id LIMIT 1)
|
||||||
WHERE id = $1 AND EXISTS (SELECT 1 FROM events.events WHERE `+earlier+`)`,
|
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 {
|
if err != nil {
|
||||||
return false, fmt.Errorf("link event: %w", err)
|
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,
|
// 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.
|
// and for the custom type the event was identified as, if any. A schedule tick
|
||||||
func Triggers(ctx context.Context, tx *sqlx.Tx, orgID, source, eventType string, typeID uuid.NullUUID) ([]Trigger, error) {
|
// 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
|
var out []Trigger
|
||||||
if err := tx.SelectContext(ctx, &out, `
|
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
|
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)
|
AND (event_type_id IS NULL OR event_type_id = $4)
|
||||||
ORDER BY name`,
|
ORDER BY name`,
|
||||||
orgID, source, eventType, typeID); err != nil {
|
orgID, sourceID, eventType, typeID); err != nil {
|
||||||
return nil, fmt.Errorf("read triggers: %w", err)
|
return nil, fmt.Errorf("read triggers: %w", err)
|
||||||
}
|
}
|
||||||
return out, nil
|
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.
|
// UpsertTrigger creates or replaces a trigger.
|
||||||
func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
|
func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error {
|
||||||
if _, err := s.db.NamedExecContext(ctx, `
|
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)
|
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,
|
: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)
|
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
|
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,
|
workflow = EXCLUDED.workflow, enabled = EXCLUDED.enabled, approved = EXCLUDED.approved,
|
||||||
event_type_id = EXCLUDED.event_type_id, mapping_id = EXCLUDED.mapping_id,
|
event_type_id = EXCLUDED.event_type_id, mapping_id = EXCLUDED.mapping_id,
|
||||||
schedule_since = CASE
|
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) {
|
func (s *Store) ScheduledTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
|
||||||
var out []Trigger
|
var out []Trigger
|
||||||
if err := s.db.SelectContext(ctx, &out, `
|
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
|
schedule_every_s, schedule_since
|
||||||
FROM events.triggers
|
FROM events.triggers
|
||||||
WHERE org_id = $1 AND enabled AND approved AND schedule_every_s IS NOT NULL ORDER BY name`, orgID); err != nil {
|
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,
|
// 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.
|
// and Matched distinguishes events a trigger started a run for from the rest.
|
||||||
type EventFilter struct {
|
type EventFilter struct {
|
||||||
Source string
|
SourceID uuid.NullUUID
|
||||||
Type string
|
Type string
|
||||||
Matched *bool
|
Matched *bool
|
||||||
Limit int
|
Limit int
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recent returns an organisation's newest events that match filter.
|
// visibleSource holds for a row whose source the person in $2 may see: it has
|
||||||
func (s *Store) Recent(ctx context.Context, orgID string, f EventFilter) ([]Event, error) {
|
// 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
|
var out []Event
|
||||||
if err := s.db.SelectContext(ctx, &out, `
|
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
|
received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter
|
||||||
FROM events.events
|
FROM events.events
|
||||||
WHERE org_id = $1
|
WHERE org_id = $1 AND `+visibleSource+`
|
||||||
AND ($2 = '' OR source = $2)
|
AND ($3::uuid IS NULL OR source_id = $3)
|
||||||
AND ($3 = '' OR type = $3)
|
AND ($4 = '' OR type = $4)
|
||||||
AND ($4::boolean IS NULL OR matched = $4)
|
AND ($5::boolean IS NULL OR matched = $5)
|
||||||
ORDER BY received_at DESC LIMIT $5`, orgID, f.Source, f.Type, f.Matched, f.Limit); err != nil {
|
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 nil, fmt.Errorf("list events: %w", err)
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Event returns one event with the payload it arrived in.
|
// Event returns one event with the payload it arrived in, if it comes from a
|
||||||
func (s *Store) Event(ctx context.Context, orgID string, id uuid.UUID) (Event, error) {
|
// source the person may see.
|
||||||
|
func (s *Store) Event(ctx context.Context, orgID, person string, id uuid.UUID) (Event, error) {
|
||||||
var e Event
|
var e Event
|
||||||
err := s.db.GetContext(ctx, &e, `
|
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,
|
received_at, matched, dispatched_at, own, origin_run_id, group_key, group_filter,
|
||||||
verification, headers, remote_addr, event_type_id
|
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) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return Event{}, ErrNotFound
|
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) {
|
func (s *Store) AllTriggers(ctx context.Context, orgID string) ([]Trigger, error) {
|
||||||
var out []Trigger
|
var out []Trigger
|
||||||
if err := s.db.SelectContext(ctx, &out, `
|
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
|
schedule_every_s, schedule_since
|
||||||
FROM events.triggers WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
FROM events.triggers WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
||||||
return nil, fmt.Errorf("list triggers: %w", err)
|
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.
|
// Origin is the event and trigger that started a run.
|
||||||
type Origin struct {
|
type Origin struct {
|
||||||
EventID uuid.UUID `db:"event_id"`
|
EventID uuid.UUID `db:"event_id"`
|
||||||
|
SourceID uuid.NullUUID `db:"source_id"`
|
||||||
Source string `db:"source"`
|
Source string `db:"source"`
|
||||||
Type string `db:"type"`
|
Type string `db:"type"`
|
||||||
Fields jsontext.Value `db:"fields"`
|
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) {
|
func (s *Store) OriginOf(ctx context.Context, orgID string, runID uuid.UUID) (Origin, bool, error) {
|
||||||
var o Origin
|
var o Origin
|
||||||
err := s.db.GetContext(ctx, &o, `
|
err := s.db.GetContext(ctx, &o, `
|
||||||
SELECT e.id AS event_id, e.source, e.type, e.fields, e.received_at, d.trigger,
|
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,
|
||||||
COALESCE(t.filter, '{}') AS filter
|
e.received_at, d.trigger, COALESCE(t.filter, '{}') AS filter
|
||||||
FROM events.dispatches d
|
FROM events.dispatches d
|
||||||
JOIN events.events e ON e.id = d.event_id
|
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
|
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)
|
WHERE e.org_id = $1 AND d.run_id = $2`, orgID, runID)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ func TestListenedEventsPassTheDeliveryPolicyBeforeStoring(t *testing.T) {
|
|||||||
if !tt.unwired {
|
if !tt.unwired {
|
||||||
m.UseDeliveryPolicy(policy)
|
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"}})
|
err := m.storeListened(t.Context(), src, []connectors.Event{{Type: "message", SourceEventID: "evt-1"}})
|
||||||
if (err != nil) != tt.wantErr {
|
if (err != nil) != tt.wantErr {
|
||||||
t.Fatalf("error = %v, want error %v", err, tt.wantErr)
|
t.Fatalf("error = %v, want error %v", err, tt.wantErr)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,11 +12,9 @@ import (
|
|||||||
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
// The source and type of the event a schedule stores for each slot.
|
// scheduleType is the type of the event a schedule stores for each slot. The
|
||||||
const (
|
// event has no source.
|
||||||
scheduleSource = "schedule"
|
const scheduleType = "schedule.tick"
|
||||||
scheduleType = "schedule.tick"
|
|
||||||
)
|
|
||||||
|
|
||||||
// minInterval keeps a schedule from firing faster than the dispatcher can use.
|
// minInterval keeps a schedule from firing faster than the dispatcher can use.
|
||||||
const minInterval = time.Minute
|
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 {
|
func tickEvent(orgID, trigger string, slot time.Time, fields jsontext.Value) store.Event {
|
||||||
e := 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,
|
SourceEventID: trigger + "@" + slot.UTC().Format(time.RFC3339), Fields: fields,
|
||||||
}
|
}
|
||||||
e.OccurredAt.Time, e.OccurredAt.Valid = slot, true
|
e.OccurredAt.Time, e.OccurredAt.Valid = slot, true
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -5,13 +5,19 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
||||||
"github.com/samcharles93/archie-core/modules/governance"
|
"github.com/samcharles93/archie-core/modules/governance"
|
||||||
)
|
)
|
||||||
|
|
||||||
type connectorSource struct{ src store.Source }
|
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
|
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)}
|
m := &Module{reader: connectorSource{store.Source{Connector: "telegram"}}, log: slog.New(slog.DiscardHandler)}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
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 {
|
if ok != tt.ok || got != tt.want {
|
||||||
t.Fatalf("sender = %v %v, want %v %v", got, ok, tt.want, tt.ok)
|
t.Fatalf("sender = %v %v, want %v %v", got, ok, tt.want, tt.ok)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,12 +34,11 @@ func TestSavedSourceSecretIsSetOnlyForHMAC(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
in := &putSourceInput{Name: "hook"}
|
set := SourceSettings{ //nolint:gosec // fixture secret to be sealed
|
||||||
in.Body.Connector = "c"
|
Connector: "c", Verification: tt.verify, HMACHeader: "X-Signature",
|
||||||
in.Body.Verification = tt.verify
|
HMACSecret: "not-a-real-secret",
|
||||||
in.Body.HMACHeader = "X-Signature"
|
}
|
||||||
in.Body.HMACSecret = "not-a-real-secret" //nolint:gosec // fixture secret to be sealed
|
src, _, err := m.sourceToSave(set, store.Source{ID: hookID}, nil)
|
||||||
src, _, err := m.sourceToSave(in, nil)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/modules/connectors"
|
"github.com/samcharles93/archie-core/modules/connectors"
|
||||||
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
"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
|
return caps, ok, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var hookSource = uuid.NullUUID{UUID: hookID, Valid: true}
|
||||||
|
|
||||||
type oneSource struct{ connector string }
|
type oneSource struct{ connector string }
|
||||||
|
|
||||||
func (o oneSource) Source(_ context.Context, _, name string) (store.Source, error) {
|
func (o oneSource) Source(_ context.Context, _ string, id uuid.UUID) (store.Source, error) {
|
||||||
if name != "alerts" {
|
if id != hookID {
|
||||||
return store.Source{}, store.ErrNotFound
|
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
|
// TestSavingATriggerChecksItsEventType guards the trigger contract: a trigger
|
||||||
@@ -40,16 +47,16 @@ func TestSavingATriggerChecksItsEventType(t *testing.T) {
|
|||||||
}
|
}
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
source string
|
source uuid.NullUUID
|
||||||
connector string
|
connector string
|
||||||
eventType string
|
eventType string
|
||||||
wantAt string
|
wantAt string
|
||||||
}{
|
}{
|
||||||
{name: "a declared event type is accepted", source: "alerts", connector: "pager", eventType: "incident.opened"},
|
{name: "a declared event type is accepted", source: hookSource, connector: "pager", eventType: "incident.opened"},
|
||||||
{name: "an undeclared event type is refused", source: "alerts", connector: "pager", eventType: "incident.closed", wantAt: "body.event_type"},
|
{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: "alerts", connector: "other", eventType: "incident.opened", 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: "missing", connector: "pager", eventType: "incident.opened", wantAt: "body.source"},
|
{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", source: scheduleSource, connector: "pager", eventType: scheduleType},
|
{name: "a schedule is exempt", connector: "pager", eventType: scheduleType},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||||
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
"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
|
// secretLabel binds a sealed secret to its source, so a value copied into
|
||||||
// another row doesn't open there.
|
// another row doesn't open there.
|
||||||
func secretLabel(orgID, name string) string {
|
func secretLabel(orgID string, sourceID uuid.UUID) string {
|
||||||
return "events.sources/" + orgID + "/" + name + "/hmac"
|
return "events.sources/" + orgID + "/" + sourceID.String() + "/hmac"
|
||||||
}
|
}
|
||||||
|
|
||||||
// errUnverified means a delivery failed verification. Its text is safe to log:
|
// 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),
|
// internal/infrastructure/captureintake/receiver.go (header-borne signature),
|
||||||
// with the header and prefix set per source.
|
// with the header and prefix set per source.
|
||||||
func (m *Module) verifyHMAC(src store.Source, h http.Header, body []byte) error {
|
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 {
|
if err != nil {
|
||||||
return fmt.Errorf("open signing secret: %w", err)
|
return fmt.Errorf("open signing secret: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"filippo.io/age"
|
"filippo.io/age"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||||
"github.com/samcharles93/archie-core/modules/connectors"
|
"github.com/samcharles93/archie-core/modules/connectors"
|
||||||
@@ -19,9 +20,23 @@ import (
|
|||||||
"github.com/samcharles93/archie-core/modules/governance"
|
"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 }
|
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
|
return f.src, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,12 +60,12 @@ func TestHMACSourceVerifiesBeforeParsing(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
sealed, err := sealer.Seal(secretLabel("org", "hook"), []byte(secret))
|
sealed, err := sealer.Seal(secretLabel("org", hookID), []byte(secret))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
src := store.Source{
|
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,
|
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 := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(body))
|
||||||
req.SetPathValue("source", "hook")
|
req.SetPathValue("path", "hook")
|
||||||
if tt.header != "" {
|
if tt.header != "" {
|
||||||
req.Header.Set("X-Signature", tt.header)
|
req.Header.Set("X-Signature", tt.header)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -398,7 +398,7 @@ const SenderID IdentityID = "sender"
|
|||||||
|
|
||||||
// DeliveryAuthorizer decides whether an address may deliver an event to a source.
|
// DeliveryAuthorizer decides whether an address may deliver an event to a source.
|
||||||
type DeliveryAuthorizer interface {
|
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.
|
// PolicyStore persists stored Cedar policies and their instance-wide revision.
|
||||||
|
|||||||
@@ -143,9 +143,9 @@ func RecordingDelivery(a DeliveryAuthorizer, records DecisionRecorder, log *slog
|
|||||||
return recordingDelivery{DeliveryAuthorizer: a, records: records, log: log}
|
return recordingDelivery{DeliveryAuthorizer: a, records: records, log: log}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r recordingDelivery) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourcePath, addr string) Decision {
|
func (r recordingDelivery) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourceID, addr string) Decision {
|
||||||
d := r.DeliveryAuthorizer.AuthorizeDelivery(ctx, orgID, sourcePath, addr)
|
d := r.DeliveryAuthorizer.AuthorizeDelivery(ctx, orgID, sourceID, addr)
|
||||||
return recordDecision(ctx, r.records, r.log, d, DecisionRecord{
|
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,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -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.
|
// 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 {
|
if e.pending {
|
||||||
return Unavailable()
|
return Unavailable()
|
||||||
}
|
}
|
||||||
sender := Principal{IdentityID: SenderID, Org: orgID}
|
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}
|
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)
|
levels = append(levels, l)
|
||||||
}
|
}
|
||||||
return evaluate(levels, buildEntities(sender, resource), buildRequest(sender, ActionDeliver, resource, AccessContext{Addr: addr}))
|
return evaluate(levels, buildEntities(sender, resource), buildRequest(sender, ActionDeliver, resource, AccessContext{Addr: addr}))
|
||||||
|
|||||||
@@ -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.
|
// AuthorizeDelivery decides whether addr may deliver an event to a source.
|
||||||
func (l *Live) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourcePath, addr string) Decision {
|
func (l *Live) AuthorizeDelivery(ctx context.Context, orgID OrgID, sourceID, addr string) Decision {
|
||||||
return l.current(ctx).AuthorizeDelivery(ctx, orgID, sourcePath, addr)
|
return l.current(ctx).AuthorizeDelivery(ctx, orgID, sourceID, addr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Problems reports the current engine's invalid policies.
|
// Problems reports the current engine's invalid policies.
|
||||||
|
|||||||
@@ -24,7 +24,10 @@ import (
|
|||||||
|
|
||||||
// Origin is the event and trigger that started a run.
|
// Origin is the event and trigger that started a run.
|
||||||
type Origin struct {
|
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"`
|
Source string `json:"source"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Fields jsontext.Value `json:"fields"`
|
Fields jsontext.Value `json:"fields"`
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ export function bindingPayload(
|
|||||||
): TriggerInput {
|
): TriggerInput {
|
||||||
const eventType = eventTypes.find((t) => t.id === draft.eventTypeId);
|
const eventType = eventTypes.find((t) => t.id === draft.eventTypeId);
|
||||||
return {
|
return {
|
||||||
source: eventType?.source ?? "",
|
source_id: eventType?.source_id ?? "",
|
||||||
event_type_id: draft.eventTypeId,
|
event_type_id: draft.eventTypeId,
|
||||||
mapping_id: draft.mappingId || undefined,
|
mapping_id: draft.mappingId || undefined,
|
||||||
workflow: draft.workflow,
|
workflow: draft.workflow,
|
||||||
|
|||||||
@@ -13,15 +13,18 @@ import {
|
|||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import RuleEditor from "./RuleEditor.vue";
|
import RuleEditor from "./RuleEditor.vue";
|
||||||
import {
|
import {
|
||||||
closeDraft,
|
closeDraft,
|
||||||
draft,
|
draft,
|
||||||
|
eventSources,
|
||||||
saveDraft,
|
saveDraft,
|
||||||
saveError,
|
saveError,
|
||||||
saving,
|
saving,
|
||||||
|
sourceLabel,
|
||||||
} from "./event-type-state";
|
} from "./event-type-state";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -54,7 +57,7 @@ function onOpenChange(open: boolean) {
|
|||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>{{ title }}</DialogTitle>
|
<DialogTitle>{{ title }}</DialogTitle>
|
||||||
<DialogDescription
|
<DialogDescription
|
||||||
>Events on {{ draft.source || "the source" }} that match no type are
|
>Events on {{ sourceLabel(draft.sourceId) || "the source" }} that match no type are
|
||||||
never dispatched.</DialogDescription
|
never dispatched.</DialogDescription
|
||||||
>
|
>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
@@ -62,12 +65,12 @@ function onOpenChange(open: boolean) {
|
|||||||
<div class="flex flex-col gap-4">
|
<div class="flex flex-col gap-4">
|
||||||
<div class="flex flex-col gap-2">
|
<div class="flex flex-col gap-2">
|
||||||
<Label for="event-type-source">Source</Label>
|
<Label for="event-type-source">Source</Label>
|
||||||
<Input
|
<Select v-model="draft.sourceId" :disabled="draft.mode !== 'paste'">
|
||||||
id="event-type-source"
|
<SelectTrigger id="event-type-source" class="w-full" aria-label="Source"><SelectValue placeholder="Source" /></SelectTrigger>
|
||||||
v-model="draft.source"
|
<SelectContent>
|
||||||
class="font-mono"
|
<SelectItem v-for="s in eventSources" :key="s.id" :value="s.id">{{ s.label }}</SelectItem>
|
||||||
:disabled="draft.mode !== 'paste'"
|
</SelectContent>
|
||||||
/>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col gap-2">
|
<div class="flex flex-col gap-2">
|
||||||
<Label for="event-type-name">Name</Label>
|
<Label for="event-type-name">Name</Label>
|
||||||
@@ -108,7 +111,7 @@ function onOpenChange(open: boolean) {
|
|||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" @click="closeDraft">Cancel</Button>
|
<Button variant="outline" @click="closeDraft">Cancel</Button>
|
||||||
<Button
|
<Button
|
||||||
:disabled="saving || !draft.name.trim() || !draft.source.trim()"
|
:disabled="saving || !draft.name.trim() || !draft.sourceId"
|
||||||
@click="saveDraft"
|
@click="saveDraft"
|
||||||
>
|
>
|
||||||
<Spinner v-if="saving" />Save</Button>
|
<Spinner v-if="saving" />Save</Button>
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ import {
|
|||||||
eventTypesLoading,
|
eventTypesLoading,
|
||||||
nameProposal,
|
nameProposal,
|
||||||
pasteExample,
|
pasteExample,
|
||||||
|
sourceLabel,
|
||||||
pendingDelete,
|
pendingDelete,
|
||||||
proposals,
|
proposals,
|
||||||
} from "./event-type-state";
|
} from "./event-type-state";
|
||||||
@@ -87,9 +88,9 @@ function fieldCount(schema: Record<string, string> | null | undefined): number {
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
<TableRow v-for="p in proposals" :key="p.source + p.key">
|
<TableRow v-for="p in proposals" :key="p.source_id + p.key">
|
||||||
<TableCell class="font-mono">{{
|
<TableCell class="font-mono">{{
|
||||||
p.source || "(unknown)"
|
sourceLabel(p.source_id) || "(unknown)"
|
||||||
}}</TableCell>
|
}}</TableCell>
|
||||||
<TableCell class="text-right tabular-nums">{{ p.count }}</TableCell>
|
<TableCell class="text-right tabular-nums">{{ p.count }}</TableCell>
|
||||||
<TableCell class="text-right tabular-nums">{{
|
<TableCell class="text-right tabular-nums">{{
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ref } from "vue";
|
import { ref } from "vue";
|
||||||
|
|
||||||
import { errors } from "@/copy/errors";
|
import { errors } from "@/copy/errors";
|
||||||
import { api, describeError } from "@/lib/api";
|
import { api, describeError, type EventSource_ } from "@/lib/api";
|
||||||
import { captures } from "./state";
|
import { captures } from "./state";
|
||||||
import {
|
import {
|
||||||
cleanRule,
|
cleanRule,
|
||||||
@@ -37,7 +37,7 @@ type DraftMode = "proposal" | "paste" | "edit";
|
|||||||
export interface Draft {
|
export interface Draft {
|
||||||
mode: DraftMode;
|
mode: DraftMode;
|
||||||
id: string | null;
|
id: string | null;
|
||||||
source: string;
|
sourceId: string;
|
||||||
name: string;
|
name: string;
|
||||||
rule: Rule;
|
rule: Rule;
|
||||||
headersText: string;
|
headersText: string;
|
||||||
@@ -46,6 +46,14 @@ export interface Draft {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const draft = ref<Draft | null>(null);
|
export const draft = ref<Draft | null>(null);
|
||||||
|
|
||||||
|
/** The sources the caller can see, for naming a proposal's or a type's source. */
|
||||||
|
export const eventSources = ref<EventSource_[]>([]);
|
||||||
|
|
||||||
|
/** The label of a source, or "" when it is unknown. */
|
||||||
|
export function sourceLabel(id: string): string {
|
||||||
|
return eventSources.value.find((s) => s.id === id)?.label ?? "";
|
||||||
|
}
|
||||||
export const saving = ref(false);
|
export const saving = ref(false);
|
||||||
export const saveError = ref<string | null>(null);
|
export const saveError = ref<string | null>(null);
|
||||||
|
|
||||||
@@ -53,8 +61,9 @@ let generation = 0;
|
|||||||
export async function loadEventTypes(): Promise<void> {
|
export async function loadEventTypes(): Promise<void> {
|
||||||
const current = ++generation;
|
const current = ++generation;
|
||||||
try {
|
try {
|
||||||
const res = await api.eventTypes<EventTypesResponse>();
|
const [res, sources] = await Promise.all([api.eventTypes<EventTypesResponse>(), api.eventSources()]);
|
||||||
if (current !== generation) return;
|
if (current !== generation) return;
|
||||||
|
eventSources.value = sources;
|
||||||
eventTypesEnabled.value = res.enabled !== false;
|
eventTypesEnabled.value = res.enabled !== false;
|
||||||
eventTypes.value = res.event_types || [];
|
eventTypes.value = res.event_types || [];
|
||||||
proposals.value = res.proposals || [];
|
proposals.value = res.proposals || [];
|
||||||
@@ -84,7 +93,7 @@ export function nameProposal(p: Proposal): void {
|
|||||||
open({
|
open({
|
||||||
mode: "proposal",
|
mode: "proposal",
|
||||||
id: null,
|
id: null,
|
||||||
source: p.source,
|
sourceId: p.source_id,
|
||||||
name: "",
|
name: "",
|
||||||
rule: copyRule(p.rule),
|
rule: copyRule(p.rule),
|
||||||
headersText: "",
|
headersText: "",
|
||||||
@@ -93,11 +102,11 @@ export function nameProposal(p: Proposal): void {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function pasteExample(source = ""): void {
|
export function pasteExample(sourceId = ""): void {
|
||||||
open({
|
open({
|
||||||
mode: "paste",
|
mode: "paste",
|
||||||
id: null,
|
id: null,
|
||||||
source,
|
sourceId,
|
||||||
name: "",
|
name: "",
|
||||||
rule: { headers: [], payload: [] },
|
rule: { headers: [], payload: [] },
|
||||||
headersText: "",
|
headersText: "",
|
||||||
@@ -110,7 +119,7 @@ export function editEventType(t: EventType): void {
|
|||||||
open({
|
open({
|
||||||
mode: "edit",
|
mode: "edit",
|
||||||
id: t.id,
|
id: t.id,
|
||||||
source: t.source,
|
sourceId: t.source_id,
|
||||||
name: t.name,
|
name: t.name,
|
||||||
rule: copyRule(t.rule),
|
rule: copyRule(t.rule),
|
||||||
headersText: "",
|
headersText: "",
|
||||||
@@ -137,7 +146,7 @@ export async function saveDraft(): Promise<void> {
|
|||||||
const headers =
|
const headers =
|
||||||
d.mode === "paste" ? parseHeaderLines(d.headersText) : d.exampleHeaders;
|
d.mode === "paste" ? parseHeaderLines(d.headersText) : d.exampleHeaders;
|
||||||
await api.eventTypeCreate({
|
await api.eventTypeCreate({
|
||||||
source: d.source,
|
source_id: d.sourceId,
|
||||||
name: d.name,
|
name: d.name,
|
||||||
// A pasted example's rule is inferred by the server from what was pasted.
|
// A pasted example's rule is inferred by the server from what was pasted.
|
||||||
rule: d.mode === "paste" ? undefined : cleanRule(d.rule),
|
rule: d.mode === "paste" ? undefined : cleanRule(d.rule),
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ export interface Rule {
|
|||||||
|
|
||||||
export interface EventType {
|
export interface EventType {
|
||||||
id: string;
|
id: string;
|
||||||
|
source_id: string;
|
||||||
|
/** The source's label. */
|
||||||
source: string;
|
source: string;
|
||||||
name: string;
|
name: string;
|
||||||
rule: Rule;
|
rule: Rule;
|
||||||
@@ -28,7 +30,7 @@ export interface EventType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface Proposal {
|
export interface Proposal {
|
||||||
source: string;
|
source_id: string;
|
||||||
key: string;
|
key: string;
|
||||||
schema: Record<string, string> | null;
|
schema: Record<string, string> | null;
|
||||||
headers: Record<string, string> | null;
|
headers: Record<string, string> | null;
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ const sources = useRead(() => api.eventSources());
|
|||||||
const { data, error, reload } = useRead(() =>
|
const { data, error, reload } = useRead(() =>
|
||||||
api.events({
|
api.events({
|
||||||
limit: 200,
|
limit: 200,
|
||||||
source: source.value === ALL ? undefined : source.value,
|
source_id: source.value === ALL ? undefined : source.value,
|
||||||
type: type.value.trim() || undefined,
|
type: type.value.trim() || undefined,
|
||||||
matched: matched.value === ALL ? undefined : matched.value,
|
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 time = (at?: string) => (at ? Date.parse(at) : 0);
|
||||||
const columns: DataTableColumn<EventRecord>[] = [
|
const columns: DataTableColumn<EventRecord>[] = [
|
||||||
{ id: "type", label: "Type", fixed: true, width: "auto", sort: (e) => e.type },
|
{ 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: "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: "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) },
|
{ id: "occurred", label: "Occurred", hidden: true, width: "9rem", sort: (e) => time(e.occurred_at) },
|
||||||
@@ -61,7 +61,7 @@ const columns: DataTableColumn<EventRecord>[] = [
|
|||||||
<SelectTrigger size="sm" aria-label="Source"><SelectValue /></SelectTrigger>
|
<SelectTrigger size="sm" aria-label="Source"><SelectValue /></SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem :value="ALL">All sources</SelectItem>
|
<SelectItem :value="ALL">All sources</SelectItem>
|
||||||
<SelectItem v-for="s in sources.data.value ?? []" :key="s.name" :value="s.name">{{ s.name }}</SelectItem>
|
<SelectItem v-for="s in sources.data.value ?? []" :key="s.id" :value="s.id">{{ s.label }}</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
<Select v-model="matched">
|
<Select v-model="matched">
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ onMounted(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const columns: DataTableColumn<EventSource_>[] = [
|
const columns: DataTableColumn<EventSource_>[] = [
|
||||||
{ id: "name", label: "Source", fixed: true, sort: (s) => s.name },
|
{ id: "label", label: "Source", fixed: true, sort: (s) => s.label },
|
||||||
{ id: "connector", label: "Connector", hide: "sm", width: "12rem", sort: (s) => s.connector },
|
{ id: "connector", label: "Connector", hide: "sm", width: "12rem", sort: (s) => s.connector },
|
||||||
{ id: "verification", label: "Verification", hide: "sm", width: "14rem" },
|
{ id: "verification", label: "Verification", hide: "sm", width: "14rem" },
|
||||||
{ id: "key", label: "Grouped by", hide: "md", width: "16rem" },
|
{ id: "key", label: "Grouped by", hide: "md", width: "16rem" },
|
||||||
@@ -38,11 +38,13 @@ const columns: DataTableColumn<EventSource_>[] = [
|
|||||||
const issued = ref<{ url: string; token?: string } | null>(null);
|
const issued = ref<{ url: string; token?: string } | null>(null);
|
||||||
const busy = ref(false);
|
const busy = ref(false);
|
||||||
const actionError = ref("");
|
const actionError = ref("");
|
||||||
async function put(name: string, connector: string, verification?: SourceVerification): Promise<boolean> {
|
async function put(connector: string, verification?: SourceVerification, existing?: EventSource_ | null, label = ""): Promise<boolean> {
|
||||||
busy.value = true;
|
busy.value = true;
|
||||||
actionError.value = "";
|
actionError.value = "";
|
||||||
try {
|
try {
|
||||||
const created = await api.putEventSource(name, connector, verification);
|
const created = existing
|
||||||
|
? await api.updateEventSource(existing.id, connector, verification)
|
||||||
|
: await api.createEventSource({ label, connector, ...verification });
|
||||||
issued.value = { url: new URL(created.url, window.location.origin).toString(), token: created.token };
|
issued.value = { url: new URL(created.url, window.location.origin).toString(), token: created.token };
|
||||||
await reload();
|
await reload();
|
||||||
return true;
|
return true;
|
||||||
@@ -56,13 +58,13 @@ async function put(name: string, connector: string, verification?: SourceVerific
|
|||||||
|
|
||||||
const adding = ref(false);
|
const adding = ref(false);
|
||||||
const editing = ref<EventSource_ | null>(null);
|
const editing = ref<EventSource_ | null>(null);
|
||||||
const blank = { name: "", connector: "", verification: "token" as SourceVerification["verification"], hmac_header: "", hmac_prefix: "", hmac_secret: "" };
|
const blank = { label: "", connector: "", verification: "token" as SourceVerification["verification"], hmac_header: "", hmac_prefix: "", hmac_secret: "" };
|
||||||
const draft = ref({ ...blank });
|
const draft = ref({ ...blank });
|
||||||
async function add(): Promise<void> {
|
async function add(): Promise<void> {
|
||||||
const { name, connector, ...verification } = draft.value;
|
const { label, connector, ...verification } = draft.value;
|
||||||
// Saving an unchanged token source must not rotate its token.
|
// Saving an unchanged token source must not rotate its token.
|
||||||
const keepsToken = editing.value?.verification === "token" && verification.verification === "token";
|
const keepsToken = editing.value?.verification === "token" && verification.verification === "token";
|
||||||
if (await put(name.trim(), connector, keepsToken ? undefined : verification)) {
|
if (await put(connector, keepsToken ? undefined : verification, editing.value, label.trim())) {
|
||||||
adding.value = false;
|
adding.value = false;
|
||||||
editing.value = null;
|
editing.value = null;
|
||||||
draft.value = { ...blank };
|
draft.value = { ...blank };
|
||||||
@@ -71,7 +73,7 @@ async function add(): Promise<void> {
|
|||||||
// A blank secret keeps the stored one, so it is required only when a source
|
// A blank secret keeps the stored one, so it is required only when a source
|
||||||
// has none yet.
|
// has none yet.
|
||||||
const secretOptional = computed(() => editing.value?.verification === "hmac" && editing.value.hmac_secret_set);
|
const secretOptional = computed(() => editing.value?.verification === "hmac" && editing.value.hmac_secret_set);
|
||||||
const addDisabled = computed(() => busy.value || !draft.value.name || !draft.value.connector
|
const addDisabled = computed(() => busy.value || !draft.value.label || !draft.value.connector
|
||||||
|| (draft.value.verification === "hmac" && (!draft.value.hmac_header || (!draft.value.hmac_secret && !secretOptional.value))));
|
|| (draft.value.verification === "hmac" && (!draft.value.hmac_header || (!draft.value.hmac_secret && !secretOptional.value))));
|
||||||
function openAdd(): void {
|
function openAdd(): void {
|
||||||
editing.value = null;
|
editing.value = null;
|
||||||
@@ -82,7 +84,7 @@ function openAdd(): void {
|
|||||||
function openEdit(source: EventSource_): void {
|
function openEdit(source: EventSource_): void {
|
||||||
editing.value = source;
|
editing.value = source;
|
||||||
draft.value = {
|
draft.value = {
|
||||||
name: source.name, connector: source.connector, verification: source.verification,
|
label: source.label, connector: source.connector, verification: source.verification,
|
||||||
hmac_header: source.hmac_header ?? "", hmac_prefix: source.hmac_prefix ?? "", hmac_secret: "",
|
hmac_header: source.hmac_header ?? "", hmac_prefix: source.hmac_prefix ?? "", hmac_secret: "",
|
||||||
};
|
};
|
||||||
adding.value = true;
|
adding.value = true;
|
||||||
@@ -102,7 +104,7 @@ async function saveKeyFields(): Promise<void> {
|
|||||||
actionError.value = "";
|
actionError.value = "";
|
||||||
try {
|
try {
|
||||||
const paths = keyFields.value.split(",").map((p) => p.trim()).filter(Boolean);
|
const paths = keyFields.value.split(",").map((p) => p.trim()).filter(Boolean);
|
||||||
await api.putSourceKeyFields(keyFieldsOf.value.name, paths);
|
await api.putSourceKeyFields(keyFieldsOf.value.id, paths);
|
||||||
keyFieldsOf.value = null;
|
keyFieldsOf.value = null;
|
||||||
await reload();
|
await reload();
|
||||||
} catch (cause) {
|
} catch (cause) {
|
||||||
@@ -128,16 +130,16 @@ const connectorNames = computed(() => (connectors.data.value ?? []).map((c) => c
|
|||||||
<div class="mb-2 flex justify-end">
|
<div class="mb-2 flex justify-end">
|
||||||
<Button size="icon-sm" variant="ghost" aria-label="Add source" title="Add source" @click="openAdd"><Plus /></Button>
|
<Button size="icon-sm" variant="ghost" aria-label="Add source" title="Add source" @click="openAdd"><Plus /></Button>
|
||||||
</div>
|
</div>
|
||||||
<DataTable :columns="columns" :rows="data" :row-key="(s) => s.name" storage-key="sources">
|
<DataTable :columns="columns" :rows="data" :row-key="(s) => s.id" storage-key="sources">
|
||||||
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span><span class="block text-caption text-fg-muted sm:hidden">{{ row.connector }}</span></template>
|
<template #cell-label="{ row }"><span class="font-medium">{{ row.label }}</span><span class="block text-caption text-fg-muted sm:hidden">{{ row.connector }}</span></template>
|
||||||
<template #cell-connector="{ row }">{{ row.connector }}</template>
|
<template #cell-connector="{ row }">{{ row.connector }}</template>
|
||||||
<template #cell-verification="{ row }">{{ row.verification === "hmac" ? `HMAC (${row.hmac_header})` : row.verification === "none" ? "None" : "Bearer token" }}</template>
|
<template #cell-verification="{ row }">{{ row.verification === "hmac" ? `HMAC (${row.hmac_header})` : row.verification === "none" ? "None" : "Bearer token" }}</template>
|
||||||
<template #cell-key="{ row }"><span class="font-mono text-caption">{{ (row.key_fields ?? []).join(", ") || "Connector default" }}</span></template>
|
<template #cell-key="{ row }"><span class="font-mono text-caption">{{ (row.key_fields ?? []).join(", ") || "Connector default" }}</span></template>
|
||||||
<template #actions="{ row }">
|
<template #actions="{ row }">
|
||||||
<MoreMenu :label="`${row.name} actions`">
|
<MoreMenu :label="`${row.label} actions`">
|
||||||
<DropdownMenuItem @select="openEdit(row)">Edit…</DropdownMenuItem>
|
<DropdownMenuItem @select="openEdit(row)">Edit…</DropdownMenuItem>
|
||||||
<DropdownMenuItem @select="editKeyFields(row)">Group by…</DropdownMenuItem>
|
<DropdownMenuItem @select="editKeyFields(row)">Group by…</DropdownMenuItem>
|
||||||
<DropdownMenuItem v-if="row.verification === 'token'" :disabled="busy" @select="put(row.name, row.connector, { verification: 'token' })">Rotate token</DropdownMenuItem>
|
<DropdownMenuItem v-if="row.verification === 'token'" :disabled="busy" @select="put(row.connector, { verification: 'token' }, row)">Rotate token</DropdownMenuItem>
|
||||||
</MoreMenu>
|
</MoreMenu>
|
||||||
</template>
|
</template>
|
||||||
<template #empty><Empty><EmptyHeader><EmptyTitle>No sources</EmptyTitle></EmptyHeader></Empty></template>
|
<template #empty><Empty><EmptyHeader><EmptyTitle>No sources</EmptyTitle></EmptyHeader></Empty></template>
|
||||||
@@ -146,9 +148,9 @@ const connectorNames = computed(() => (connectors.data.value ?? []).map((c) => c
|
|||||||
|
|
||||||
<Dialog v-model:open="adding">
|
<Dialog v-model:open="adding">
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogHeader><DialogTitle>{{ editing ? `Edit ${editing.name}` : "Add source" }}</DialogTitle></DialogHeader>
|
<DialogHeader><DialogTitle>{{ editing ? `Edit ${editing.label}` : "Add source" }}</DialogTitle></DialogHeader>
|
||||||
<form id="add-source" class="space-y-3" @submit.prevent="add">
|
<form id="add-source" class="space-y-3" @submit.prevent="add">
|
||||||
<Input v-model="draft.name" aria-label="Name" :disabled="!!editing" placeholder="alertmanager" pattern="[a-z0-9][a-z0-9-]*" required />
|
<Input v-model="draft.label" aria-label="Name" :disabled="!!editing" placeholder="Alertmanager" required />
|
||||||
<Select v-model="draft.connector" required>
|
<Select v-model="draft.connector" required>
|
||||||
<SelectTrigger class="w-full" aria-label="Connector"><SelectValue placeholder="Connector that parses its events" /></SelectTrigger>
|
<SelectTrigger class="w-full" aria-label="Connector"><SelectValue placeholder="Connector that parses its events" /></SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
@@ -177,7 +179,7 @@ const connectorNames = computed(() => (connectors.data.value ?? []).map((c) => c
|
|||||||
|
|
||||||
<Dialog :open="!!keyFieldsOf" @update:open="(open) => { if (!open) keyFieldsOf = null; }">
|
<Dialog :open="!!keyFieldsOf" @update:open="(open) => { if (!open) keyFieldsOf = null; }">
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogHeader><DialogTitle>Group {{ keyFieldsOf?.name }} events by</DialogTitle></DialogHeader>
|
<DialogHeader><DialogTitle>Group {{ keyFieldsOf?.label }} events by</DialogTitle></DialogHeader>
|
||||||
<form id="key-fields" class="space-y-3" @submit.prevent="saveKeyFields">
|
<form id="key-fields" class="space-y-3" @submit.prevent="saveKeyFields">
|
||||||
<Input v-model="keyFields" aria-label="Field paths" placeholder="labels.alertname, labels.instance" />
|
<Input v-model="keyFields" aria-label="Field paths" placeholder="labels.alertname, labels.instance" />
|
||||||
<p class="text-caption text-fg-muted">Comma-separated field paths. Leave empty for the connector's default. Applies to events that arrive after you save.</p>
|
<p class="text-caption text-fg-muted">Comma-separated field paths. Leave empty for the connector's default. Applies to events that arrive after you save.</p>
|
||||||
|
|||||||
@@ -63,14 +63,14 @@ async function save(name: string, input: TriggerInput): Promise<boolean> {
|
|||||||
|
|
||||||
const editing = ref(false);
|
const editing = ref(false);
|
||||||
const isNew = ref(true);
|
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 {
|
function open(trigger?: Trigger): void {
|
||||||
isNew.value = !trigger;
|
isNew.value = !trigger;
|
||||||
actionError.value = "";
|
actionError.value = "";
|
||||||
form.value = {
|
form.value = {
|
||||||
name: trigger?.name ?? "",
|
name: trigger?.name ?? "",
|
||||||
mode: trigger?.every ? "schedule" : "event",
|
mode: trigger?.every ? "schedule" : "event",
|
||||||
source: trigger?.every ? "" : (trigger?.source ?? ""),
|
source_id: trigger?.every ? "" : (trigger?.source_id ?? ""),
|
||||||
event_type: trigger?.every ? "" : (trigger?.event_type ?? ""),
|
event_type: trigger?.every ? "" : (trigger?.event_type ?? ""),
|
||||||
every: trigger?.every ?? "",
|
every: trigger?.every ?? "",
|
||||||
workflow: trigger?.workflow ?? props.workflow ?? "",
|
workflow: trigger?.workflow ?? props.workflow ?? "",
|
||||||
@@ -85,7 +85,7 @@ async function submit(): Promise<void> {
|
|||||||
const input: TriggerInput =
|
const input: TriggerInput =
|
||||||
f.mode === "schedule"
|
f.mode === "schedule"
|
||||||
? { every: f.every.trim(), workflow: f.workflow, disabled: f.disabled }
|
? { 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;
|
if (await save(f.name.trim(), input)) editing.value = false;
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -129,10 +129,10 @@ async function submit(): Promise<void> {
|
|||||||
<ToggleGroupItem value="schedule">Schedule</ToggleGroupItem>
|
<ToggleGroupItem value="schedule">Schedule</ToggleGroupItem>
|
||||||
</ToggleGroup>
|
</ToggleGroup>
|
||||||
<template v-if="form.mode === 'event'">
|
<template v-if="form.mode === 'event'">
|
||||||
<Select v-model="form.source" required>
|
<Select v-model="form.source_id" required>
|
||||||
<SelectTrigger class="w-full" aria-label="Source"><SelectValue placeholder="Source" /></SelectTrigger>
|
<SelectTrigger class="w-full" aria-label="Source"><SelectValue placeholder="Source" /></SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem v-for="s in sources.data.value ?? []" :key="s.name" :value="s.name">{{ s.name }}</SelectItem>
|
<SelectItem v-for="s in sources.data.value ?? []" :key="s.id" :value="s.id">{{ s.label }}</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
<Input v-model="form.event_type" aria-label="Event type" placeholder="Event type" required />
|
<Input v-model="form.event_type" aria-label="Event type" placeholder="Event type" required />
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import type { Trigger, TriggerInput } from "@/lib/api";
|
|||||||
export function triggerInput(trigger: Trigger): TriggerInput {
|
export function triggerInput(trigger: Trigger): TriggerInput {
|
||||||
if (trigger.every) return { every: trigger.every, workflow: trigger.workflow, disabled: !trigger.enabled };
|
if (trigger.every) return { every: trigger.every, workflow: trigger.workflow, disabled: !trigger.enabled };
|
||||||
return {
|
return {
|
||||||
source: trigger.source,
|
source_id: trigger.source_id,
|
||||||
event_type: trigger.event_type,
|
event_type: trigger.event_type,
|
||||||
filter: trigger.filter,
|
filter: trigger.filter,
|
||||||
workflow: trigger.workflow,
|
workflow: trigger.workflow,
|
||||||
|
|||||||
+49
-30
@@ -198,14 +198,16 @@ export const api = {
|
|||||||
/** Starts the passkey confirmation that approving an irreversible action needs. */
|
/** Starts the passkey confirmation that approving an irreversible action needs. */
|
||||||
beginApprovalConfirmation: (id: string) =>
|
beginApprovalConfirmation: (id: string) =>
|
||||||
request<ApprovalConfirmation>(`/api/approvals/${encodeURIComponent(id)}/confirmation`, { method: "POST", body: {} }),
|
request<ApprovalConfirmation>(`/api/approvals/${encodeURIComponent(id)}/confirmation`, { method: "POST", body: {} }),
|
||||||
events: (params: { limit?: number; source?: string; type?: string; matched?: string } = {}) =>
|
events: (params: { limit?: number; source_id?: string; type?: string; matched?: string } = {}) =>
|
||||||
request<EventRecord[]>("/api/events" + qs(params)),
|
request<EventRecord[]>("/api/events" + qs(params)),
|
||||||
event: (id: string) => request<EventDetail>(`/api/events/${encodeURIComponent(id)}`),
|
event: (id: string) => request<EventDetail>(`/api/events/${encodeURIComponent(id)}`),
|
||||||
eventSources: () => request<EventSource_[]>("/api/sources"),
|
eventSources: () => request<EventSource_[]>("/api/sources"),
|
||||||
putEventSource: (name: string, connector: string, verification?: SourceVerification) =>
|
createEventSource: (input: { label: string; webhook_path?: string; scope?: SourceScope; connector: string } & Partial<SourceVerification>) =>
|
||||||
request<{ source: string; token?: string; secret?: string; url: string }>(`/api/sources/${encodeURIComponent(name)}`, { method: "PUT", body: { connector, ...verification } }),
|
request<SourceIssued>("/api/sources", { method: "POST", body: input }),
|
||||||
sourceCapture: (name: string, capture: boolean) =>
|
updateEventSource: (id: string, connector: string, verification?: SourceVerification) =>
|
||||||
request<EventSource_>(`/api/sources/${encodeURIComponent(name)}/capture`, { method: "PUT", body: { capture } }),
|
request<SourceIssued>(`/api/sources/${encodeURIComponent(id)}`, { method: "PUT", body: { connector, ...verification } }),
|
||||||
|
sourceCapture: (id: string, capture: boolean) =>
|
||||||
|
request<EventSource_>(`/api/sources/${encodeURIComponent(id)}/capture`, { method: "PUT", body: { capture } }),
|
||||||
/** The runs a trigger started, newest first. */
|
/** The runs a trigger started, newest first. */
|
||||||
triggerDispatches: (name: string) =>
|
triggerDispatches: (name: string) =>
|
||||||
request<TriggerRun[]>(`/api/triggers/${encodeURIComponent(name)}/dispatches`),
|
request<TriggerRun[]>(`/api/triggers/${encodeURIComponent(name)}/dispatches`),
|
||||||
@@ -221,8 +223,8 @@ export const api = {
|
|||||||
/** The runs a stored delivery started. */
|
/** The runs a stored delivery started. */
|
||||||
captureDispatches: (id: string) =>
|
captureDispatches: (id: string) =>
|
||||||
request<TriggerRun[]>(`/api/captures/${encodeURIComponent(id)}/dispatches`),
|
request<TriggerRun[]>(`/api/captures/${encodeURIComponent(id)}/dispatches`),
|
||||||
putSourceKeyFields: (name: string, paths: string[]) =>
|
putSourceKeyFields: (id: string, paths: string[]) =>
|
||||||
request<{ key_fields: string[] }>(`/api/sources/${encodeURIComponent(name)}/key-fields`, { method: "PUT", body: { paths } }),
|
request<{ key_fields: string[] }>(`/api/sources/${encodeURIComponent(id)}/key-fields`, { method: "PUT", body: { paths } }),
|
||||||
triggers: () => request<Trigger[]>("/api/triggers"),
|
triggers: () => request<Trigger[]>("/api/triggers"),
|
||||||
putTrigger: (name: string, trigger: TriggerInput) =>
|
putTrigger: (name: string, trigger: TriggerInput) =>
|
||||||
request<{ trigger: string }>(`/api/triggers/${encodeURIComponent(name)}`, { method: "PUT", body: trigger }),
|
request<{ trigger: string }>(`/api/triggers/${encodeURIComponent(name)}`, { method: "PUT", body: trigger }),
|
||||||
@@ -638,29 +640,25 @@ export const api = {
|
|||||||
request<T>(`/api/bindings/${encodeURIComponent(id)}/pause`, { method: "POST" }),
|
request<T>(`/api/bindings/${encodeURIComponent(id)}/pause`, { method: "POST" }),
|
||||||
bindingResume: <T = unknown>(id: string) =>
|
bindingResume: <T = unknown>(id: string) =>
|
||||||
request<T>(`/api/bindings/${encodeURIComponent(id)}/resume`, { method: "POST" }),
|
request<T>(`/api/bindings/${encodeURIComponent(id)}/resume`, { method: "POST" }),
|
||||||
sources: <T = unknown>(workspace?: string) =>
|
sourceSigning: <T = unknown>(id: string, signed: boolean) =>
|
||||||
request<T>("/api/sources" + qs({ workspace })),
|
request<T>(`/api/sources/${encodeURIComponent(id)}/signing`, {
|
||||||
// sourceCreate makes a source in one of the org's workspaces; an empty
|
|
||||||
// workspace is the default one.
|
|
||||||
sourceCreate: <T = unknown>(path: string, workspace = "") =>
|
|
||||||
request<T>("/api/sources", { method: "POST", body: { path, workspace } }),
|
|
||||||
sourceSigning: <T = unknown>(path: string, signed: boolean) =>
|
|
||||||
request<T>(`/api/sources/${encodeURIComponent(path)}/signing`, {
|
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: { signed },
|
body: { signed },
|
||||||
}),
|
}),
|
||||||
sourceApproveUnsigned: <T = unknown>(path: string) =>
|
sourceApproveUnsigned: <T = unknown>(id: string) =>
|
||||||
request<T>(`/api/sources/${encodeURIComponent(path)}/approve-unsigned`, {
|
request<T>(`/api/sources/${encodeURIComponent(id)}/approve-unsigned`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
}),
|
}),
|
||||||
sourceName: <T = unknown>(path: string, name: string) =>
|
sourceLabel: <T = unknown>(id: string, label: string) =>
|
||||||
request<T>(`/api/sources/${encodeURIComponent(path)}/name`, { method: "PUT", body: { name } }),
|
request<T>(`/api/sources/${encodeURIComponent(id)}/label`, { method: "PUT", body: { label } }),
|
||||||
sourceDeliveryHeader: <T = unknown>(path: string, header: string) =>
|
sourceWebhookPath: <T = unknown>(id: string, path: string) =>
|
||||||
request<T>(`/api/sources/${encodeURIComponent(path)}/delivery-header`, { method: "PUT", body: { header } }),
|
request<T>(`/api/sources/${encodeURIComponent(id)}/webhook-path`, { method: "PUT", body: { path } }),
|
||||||
sourceDelete: (path: string) =>
|
sourceDeliveryHeader: <T = unknown>(id: string, header: string) =>
|
||||||
request<void>(`/api/sources/${encodeURIComponent(path)}`, { method: "DELETE", parse: false }),
|
request<T>(`/api/sources/${encodeURIComponent(id)}/delivery-header`, { method: "PUT", body: { header } }),
|
||||||
sourceSecret: <T = unknown>(path: string) =>
|
sourceDelete: (id: string) =>
|
||||||
request<T>(`/api/sources/${encodeURIComponent(path)}/secret`, {
|
request<void>(`/api/sources/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
|
||||||
|
sourceSecret: <T = unknown>(id: string) =>
|
||||||
|
request<T>(`/api/sources/${encodeURIComponent(id)}/secret`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
}),
|
}),
|
||||||
chatSessions: () => request<ChatSessions>("/api/chat/sessions"),
|
chatSessions: () => request<ChatSessions>("/api/chat/sessions"),
|
||||||
@@ -937,7 +935,7 @@ export interface RunStage {
|
|||||||
|
|
||||||
export interface RunTrail {
|
export interface RunTrail {
|
||||||
run: Run;
|
run: Run;
|
||||||
origin?: { event_id?: string; source?: string; type?: string; trigger?: string; received_at?: string };
|
origin?: { event_id?: string; source_id?: string; source?: string; type?: string; trigger?: string; received_at?: string };
|
||||||
actions?: RunAction[];
|
actions?: RunAction[];
|
||||||
entries?: RunEntry[];
|
entries?: RunEntry[];
|
||||||
/** The document the run executes: its version, or the draft a test run tested. */
|
/** The document the run executes: its version, or the draft a test run tested. */
|
||||||
@@ -947,7 +945,10 @@ export interface RunTrail {
|
|||||||
|
|
||||||
export interface EventRecord {
|
export interface EventRecord {
|
||||||
id: string;
|
id: string;
|
||||||
source: string;
|
/** Empty for a schedule tick. */
|
||||||
|
source_id?: string;
|
||||||
|
/** The source's label. */
|
||||||
|
source?: string;
|
||||||
type: string;
|
type: string;
|
||||||
matched: boolean;
|
matched: boolean;
|
||||||
received_at: string;
|
received_at: string;
|
||||||
@@ -1001,8 +1002,24 @@ export interface SourceVerification {
|
|||||||
hmac_secret?: string;
|
hmac_secret?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Who owns a source: the organisation, or the one person who can see and use it. */
|
||||||
|
export type SourceScope = "org" | "person";
|
||||||
|
|
||||||
|
/** What creating or updating a source returns; token and secret are shown once. */
|
||||||
|
export interface SourceIssued {
|
||||||
|
id: string;
|
||||||
|
token?: string;
|
||||||
|
secret?: string;
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface EventSource_ {
|
export interface EventSource_ {
|
||||||
name: string;
|
id: string;
|
||||||
|
scope: SourceScope;
|
||||||
|
/** The name people see, unique within the scope. */
|
||||||
|
label: string;
|
||||||
|
/** The last segment of the URL deliveries post to. */
|
||||||
|
webhook_path: string;
|
||||||
connector: string;
|
connector: string;
|
||||||
key_fields?: string[];
|
key_fields?: string[];
|
||||||
token_set: boolean;
|
token_set: boolean;
|
||||||
@@ -1010,7 +1027,6 @@ export interface EventSource_ {
|
|||||||
hmac_header?: string;
|
hmac_header?: string;
|
||||||
hmac_prefix?: string;
|
hmac_prefix?: string;
|
||||||
hmac_secret_set: boolean;
|
hmac_secret_set: boolean;
|
||||||
display_name?: string;
|
|
||||||
/** The header a sender repeats on every retry of one delivery. */
|
/** The header a sender repeats on every retry of one delivery. */
|
||||||
delivery_header?: string;
|
delivery_header?: string;
|
||||||
signing: "signed" | "token" | "unsigned_pending_approval" | "unsigned";
|
signing: "signed" | "token" | "unsigned_pending_approval" | "unsigned";
|
||||||
@@ -1022,6 +1038,9 @@ export interface EventSource_ {
|
|||||||
|
|
||||||
export interface Trigger {
|
export interface Trigger {
|
||||||
name: string;
|
name: string;
|
||||||
|
/** Empty for a scheduled trigger. */
|
||||||
|
source_id?: string;
|
||||||
|
/** The source's label. */
|
||||||
source?: string;
|
source?: string;
|
||||||
event_type?: string;
|
event_type?: string;
|
||||||
every?: string;
|
every?: string;
|
||||||
@@ -1036,7 +1055,7 @@ export interface Trigger {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface TriggerInput {
|
export interface TriggerInput {
|
||||||
source?: string;
|
source_id?: string;
|
||||||
event_type?: string;
|
event_type?: string;
|
||||||
every?: string;
|
every?: string;
|
||||||
workflow: string;
|
workflow: string;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { errors } from "@/copy/errors";
|
import { errors } from "@/copy/errors";
|
||||||
import { computed } from "vue";
|
import { computed, onMounted } from "vue";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -13,7 +13,9 @@ import {
|
|||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
import { ago } from "@/lib/format";
|
import { ago } from "@/lib/format";
|
||||||
|
import { useRead } from "@/lib/use-read";
|
||||||
import { eventTypeLabel } from "@/captures/event-types";
|
import { eventTypeLabel } from "@/captures/event-types";
|
||||||
import {
|
import {
|
||||||
captures,
|
captures,
|
||||||
@@ -29,7 +31,7 @@ import {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The mapping's own fields: the name it is saved under, the organisational
|
* The mapping's own fields: the name it is saved under, the organisational
|
||||||
* source hint, and the captured event the payload and the preview resolve
|
* source, and the captured event the payload and the preview resolve
|
||||||
* against. The hint is a note to a human, never a matcher; bindings decide which
|
* against. The hint is a note to a human, never a matcher; bindings decide which
|
||||||
* events a mapping applies to.
|
* events a mapping applies to.
|
||||||
*
|
*
|
||||||
@@ -42,6 +44,18 @@ import {
|
|||||||
* item value outright. */
|
* item value outright. */
|
||||||
const NO_CAPTURE = "none";
|
const NO_CAPTURE = "none";
|
||||||
|
|
||||||
|
/** The picker's value for "no source". */
|
||||||
|
const NO_SOURCE = "none";
|
||||||
|
|
||||||
|
const sources = useRead(() => api.eventSources());
|
||||||
|
onMounted(() => void sources.reload());
|
||||||
|
|
||||||
|
const sourceValue = computed(() => draft.value.sourceId || NO_SOURCE);
|
||||||
|
|
||||||
|
function onSourceChange(value: unknown): void {
|
||||||
|
draft.value.sourceId = value === NO_SOURCE ? "" : String(value);
|
||||||
|
}
|
||||||
|
|
||||||
const captureValue = computed(() =>
|
const captureValue = computed(() =>
|
||||||
draft.value.captureId === null ? NO_CAPTURE : String(draft.value.captureId),
|
draft.value.captureId === null ? NO_CAPTURE : String(draft.value.captureId),
|
||||||
);
|
);
|
||||||
@@ -97,8 +111,16 @@ const captureHint = computed(() => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex flex-col gap-2">
|
<div class="flex flex-col gap-2">
|
||||||
<Label for="mapping-source-hint">Source hint (organisational only)</Label>
|
<Label for="mapping-source">Source (organisational only)</Label>
|
||||||
<Input id="mapping-source-hint" v-model="draft.sourceHint" />
|
<Select :model-value="sourceValue" @update:model-value="onSourceChange">
|
||||||
|
<SelectTrigger id="mapping-source" class="w-full"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectGroup>
|
||||||
|
<SelectItem :value="NO_SOURCE">No source</SelectItem>
|
||||||
|
<SelectItem v-for="s in sources.data.value ?? []" :key="s.id" :value="s.id">{{ s.label }}</SelectItem>
|
||||||
|
</SelectGroup>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex flex-col gap-2">
|
<div class="flex flex-col gap-2">
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ export interface MappingField {
|
|||||||
export interface Mapping {
|
export interface Mapping {
|
||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
source_hint?: string;
|
source_id?: string;
|
||||||
event_type_id?: string;
|
event_type_id?: string;
|
||||||
fields?: MappingField[];
|
fields?: MappingField[];
|
||||||
match_count?: number;
|
match_count?: number;
|
||||||
@@ -70,7 +70,7 @@ export interface MappingDraft {
|
|||||||
/** null until the first save. */
|
/** null until the first save. */
|
||||||
id: number | null;
|
id: number | null;
|
||||||
name: string;
|
name: string;
|
||||||
sourceHint: string;
|
sourceId: string;
|
||||||
/** The event type the mapping belongs to; its schema checks the fields. */
|
/** The event type the mapping belongs to; its schema checks the fields. */
|
||||||
eventTypeId: string;
|
eventTypeId: string;
|
||||||
fields: MappingField[];
|
fields: MappingField[];
|
||||||
@@ -126,7 +126,7 @@ function blankDraft(): MappingDraft {
|
|||||||
return {
|
return {
|
||||||
id: null,
|
id: null,
|
||||||
name: "",
|
name: "",
|
||||||
sourceHint: "",
|
sourceId: "",
|
||||||
eventTypeId: "",
|
eventTypeId: "",
|
||||||
fields: [],
|
fields: [],
|
||||||
captureId: null,
|
captureId: null,
|
||||||
@@ -178,7 +178,7 @@ export function startEdit(mapping: Mapping): void {
|
|||||||
...blankDraft(),
|
...blankDraft(),
|
||||||
id: mapping.id,
|
id: mapping.id,
|
||||||
name: mapping.name,
|
name: mapping.name,
|
||||||
sourceHint: mapping.source_hint || "",
|
sourceId: mapping.source_id || "",
|
||||||
eventTypeId: mapping.event_type_id || "",
|
eventTypeId: mapping.event_type_id || "",
|
||||||
// Copied, not aliased: the editor must not write through to the loaded list.
|
// Copied, not aliased: the editor must not write through to the loaded list.
|
||||||
fields: (mapping.fields || []).map((field) => ({ ...field })),
|
fields: (mapping.fields || []).map((field) => ({ ...field })),
|
||||||
@@ -275,7 +275,7 @@ export async function saveMapping(): Promise<void> {
|
|||||||
const current = draft.value;
|
const current = draft.value;
|
||||||
const body = {
|
const body = {
|
||||||
name: current.name,
|
name: current.name,
|
||||||
source_hint: current.sourceHint,
|
source_id: current.sourceId || undefined,
|
||||||
event_type_id: current.eventTypeId,
|
event_type_id: current.eventTypeId,
|
||||||
fields: current.fields,
|
fields: current.fields,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -219,7 +219,7 @@ onMounted(load);
|
|||||||
/>
|
/>
|
||||||
<template v-if="draft.level === 'object'">
|
<template v-if="draft.level === 'object'">
|
||||||
<Input v-model="draft.object_kind" placeholder="kind (secret, source...)" aria-label="Object kind" class="w-48" />
|
<Input v-model="draft.object_kind" placeholder="kind (secret, source...)" aria-label="Object kind" class="w-48" />
|
||||||
<Input v-model="draft.object_id" placeholder="object id" aria-label="Object id" class="w-48" />
|
<Input v-model="draft.object_id" placeholder="object id (a source's id)" aria-label="Object id" class="w-48" />
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
<Textarea
|
<Textarea
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { sourceURL, type Source } from "./source-signing";
|
|||||||
|
|
||||||
const props = defineProps<{ source: Source }>();
|
const props = defineProps<{ source: Source }>();
|
||||||
const emit = defineEmits<{ dismiss: [] }>();
|
const emit = defineEmits<{ dismiss: [] }>();
|
||||||
const url = computed(() => sourceURL(window.location.origin, props.source.path));
|
const url = computed(() => sourceURL(window.location.origin, props.source.webhook_path));
|
||||||
const copied = ref<string | null>(null);
|
const copied = ref<string | null>(null);
|
||||||
async function copy(value: string): Promise<void> {
|
async function copy(value: string): Promise<void> {
|
||||||
await navigator.clipboard.writeText(value);
|
await navigator.clipboard.writeText(value);
|
||||||
@@ -21,7 +21,7 @@ async function copy(value: string): Promise<void> {
|
|||||||
<KeyRound />
|
<KeyRound />
|
||||||
<AlertTitle class="flex items-center justify-between gap-2 text-caption">
|
<AlertTitle class="flex items-center justify-between gap-2 text-caption">
|
||||||
<span class="font-mono"
|
<span class="font-mono"
|
||||||
>{{ source.path }} · signing secret, shown once</span
|
>{{ source.label }} · signing secret, shown once</span
|
||||||
>
|
>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ const {
|
|||||||
requireSigning,
|
requireSigning,
|
||||||
approveUnsigned,
|
approveUnsigned,
|
||||||
rename,
|
rename,
|
||||||
|
setWebhookPath,
|
||||||
setDeliveryHeader,
|
setDeliveryHeader,
|
||||||
setCapture,
|
setCapture,
|
||||||
remove,
|
remove,
|
||||||
@@ -64,7 +65,7 @@ const connector = ref("");
|
|||||||
const header = ref("");
|
const header = ref("");
|
||||||
const pending = ref<Source | null>(null);
|
const pending = ref<Source | null>(null);
|
||||||
|
|
||||||
const customPath = ref("");
|
const label = ref("");
|
||||||
const copied = ref<string | null>(null);
|
const copied = ref<string | null>(null);
|
||||||
|
|
||||||
useLiveResource(null, () => void load());
|
useLiveResource(null, () => void load());
|
||||||
@@ -80,15 +81,15 @@ async function copy(value: string): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function submit(): Promise<void> {
|
async function submit(): Promise<void> {
|
||||||
await create(customPath.value.trim(), connector.value, header.value.trim());
|
await create(label.value.trim(), connector.value, header.value.trim());
|
||||||
if (!failure.value) {
|
if (!failure.value) {
|
||||||
customPath.value = "";
|
label.value = "";
|
||||||
header.value = "";
|
header.value = "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function url(source: Source): string {
|
function url(source: Source): string {
|
||||||
return sourceURL(window.location.origin, source.path);
|
return sourceURL(window.location.origin, source.webhook_path);
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -99,11 +100,10 @@ function url(source: Source): string {
|
|||||||
@submit.prevent="submit"
|
@submit.prevent="submit"
|
||||||
>
|
>
|
||||||
<Input
|
<Input
|
||||||
v-model="customPath"
|
v-model="label"
|
||||||
class="w-full font-mono sm:w-48"
|
class="w-full sm:w-48"
|
||||||
placeholder="Source name"
|
placeholder="Source name"
|
||||||
aria-label="Source name"
|
aria-label="Source name"
|
||||||
pattern="[a-z][a-z0-9\-]*"
|
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<Select v-model="connector" required>
|
<Select v-model="connector" required>
|
||||||
@@ -119,7 +119,7 @@ function url(source: Source): string {
|
|||||||
aria-label="Signature header"
|
aria-label="Signature header"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<Button type="submit" variant="outline" :disabled="busy || !customPath || !connector || !header">
|
<Button type="submit" variant="outline" :disabled="busy || !label || !connector || !header">
|
||||||
<Plus data-icon="inline-start" />
|
<Plus data-icon="inline-start" />
|
||||||
New source</Button>
|
New source</Button>
|
||||||
</form>
|
</form>
|
||||||
@@ -146,24 +146,34 @@ function url(source: Source): string {
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
<TableRow v-for="source in sources" :key="source.path">
|
<TableRow v-for="source in sources" :key="source.id">
|
||||||
<TableCell class="font-mono text-fg-muted">
|
<TableCell class="font-mono text-fg-muted">
|
||||||
<div class="flex w-64 max-w-full min-w-0 flex-col gap-1">
|
<div class="flex w-64 max-w-full min-w-0 flex-col gap-1">
|
||||||
<Input
|
<Input
|
||||||
class="h-7 border-transparent px-1 font-sans shadow-none hover:border-input dark:bg-transparent"
|
class="h-7 border-transparent px-1 font-sans shadow-none hover:border-input dark:bg-transparent"
|
||||||
:model-value="source.name ?? ''"
|
:model-value="source.label"
|
||||||
placeholder="Name this source"
|
placeholder="Name this source"
|
||||||
:aria-label="`Name of source ${source.path}`"
|
:aria-label="`Name of source ${source.label}`"
|
||||||
:disabled="busy"
|
:disabled="busy"
|
||||||
@change="rename(source, ($event.target as HTMLInputElement).value)"
|
@change="rename(source, ($event.target as HTMLInputElement).value)"
|
||||||
/>
|
/>
|
||||||
<Tooltip><TooltipTrigger as-child><span tabindex="0" class="truncate">{{ source.path }}</span></TooltipTrigger><TooltipContent>{{ url(source) }}</TooltipContent></Tooltip>
|
<Tooltip><TooltipTrigger as-child>
|
||||||
|
<Input
|
||||||
|
class="h-6 border-transparent px-1 font-mono text-caption text-fg-muted shadow-none hover:border-input md:text-caption dark:bg-transparent"
|
||||||
|
:model-value="source.webhook_path"
|
||||||
|
placeholder="Webhook path"
|
||||||
|
:aria-label="`Webhook path of source ${source.label}`"
|
||||||
|
pattern="[a-z][a-z0-9\-]*"
|
||||||
|
:disabled="busy"
|
||||||
|
@change="setWebhookPath(source, ($event.target as HTMLInputElement).value)"
|
||||||
|
/>
|
||||||
|
</TooltipTrigger><TooltipContent>{{ url(source) }}</TooltipContent></Tooltip>
|
||||||
<Input
|
<Input
|
||||||
class="h-6 border-transparent px-1 font-mono text-caption text-fg-muted shadow-none hover:border-input md:text-caption dark:bg-transparent"
|
class="h-6 border-transparent px-1 font-mono text-caption text-fg-muted shadow-none hover:border-input md:text-caption dark:bg-transparent"
|
||||||
:model-value="source.delivery_header ?? ''"
|
:model-value="source.delivery_header ?? ''"
|
||||||
placeholder="Delivery ID header"
|
placeholder="Delivery ID header"
|
||||||
title="The header the sender repeats on every retry of one delivery; a retry then starts no second run"
|
title="The header the sender repeats on every retry of one delivery; a retry then starts no second run"
|
||||||
:aria-label="`Delivery ID header of source ${source.path}`"
|
:aria-label="`Delivery ID header of source ${source.label}`"
|
||||||
:disabled="busy"
|
:disabled="busy"
|
||||||
@change="setDeliveryHeader(source, ($event.target as HTMLInputElement).value)"
|
@change="setDeliveryHeader(source, ($event.target as HTMLInputElement).value)"
|
||||||
/>
|
/>
|
||||||
@@ -274,7 +284,7 @@ function url(source: Source): string {
|
|||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>Delete source?</AlertDialogTitle>
|
<AlertDialogTitle>Delete source?</AlertDialogTitle>
|
||||||
<AlertDialogDescription>Delete the source "{{ pending?.path }}"? Its webhook endpoint stops accepting deliveries.</AlertDialogDescription>
|
<AlertDialogDescription>Delete the source "{{ pending?.label }}"? Its webhook endpoint stops accepting deliveries.</AlertDialogDescription>
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
<AlertDialogFooter>
|
||||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||||
|
|||||||
@@ -7,10 +7,12 @@
|
|||||||
import type { EventSource_ } from "@/lib/api";
|
import type { EventSource_ } from "@/lib/api";
|
||||||
|
|
||||||
export interface Source {
|
export interface Source {
|
||||||
/** The source's name, which its webhook URL ends in. */
|
/** The source's id, which never changes. */
|
||||||
path: string;
|
id: string;
|
||||||
/** The operator's label; the path stays the source's identity. */
|
/** The name people see. */
|
||||||
name?: string;
|
label: string;
|
||||||
|
/** The last segment of the webhook URL; it can be changed. */
|
||||||
|
webhook_path: string;
|
||||||
/** The header the sender repeats on every retry of one delivery. */
|
/** The header the sender repeats on every retry of one delivery. */
|
||||||
delivery_header?: string;
|
delivery_header?: string;
|
||||||
signing?: string;
|
signing?: string;
|
||||||
@@ -22,8 +24,9 @@ export interface Source {
|
|||||||
|
|
||||||
export function toSource(view: EventSource_): Source {
|
export function toSource(view: EventSource_): Source {
|
||||||
return {
|
return {
|
||||||
path: view.name,
|
id: view.id,
|
||||||
name: view.display_name,
|
label: view.label,
|
||||||
|
webhook_path: view.webhook_path,
|
||||||
delivery_header: view.delivery_header,
|
delivery_header: view.delivery_header,
|
||||||
signing: view.signing,
|
signing: view.signing,
|
||||||
capture: view.capture,
|
capture: view.capture,
|
||||||
|
|||||||
@@ -59,21 +59,26 @@ export function useSources() {
|
|||||||
load,
|
load,
|
||||||
// A new source signs with an HMAC over the body; the server generates the
|
// A new source signs with an HMAC over the body; the server generates the
|
||||||
// secret and returns it once.
|
// secret and returns it once.
|
||||||
create: (name: string, connector: string, header: string) =>
|
create: (label: string, connector: string, header: string) =>
|
||||||
run(async () => {
|
run(async () => {
|
||||||
const created = await api.putEventSource(name, connector, { verification: "hmac", hmac_header: header });
|
const created = await api.createEventSource({ label, connector, verification: "hmac", hmac_header: header });
|
||||||
return { path: name, signing: "signed", capture: true, secret: created.secret };
|
return {
|
||||||
|
id: created.id, label, webhook_path: created.url.split("/").pop() ?? "",
|
||||||
|
signing: "signed", capture: true, secret: created.secret,
|
||||||
|
};
|
||||||
}),
|
}),
|
||||||
newSecret: (s: Source) => run(() => source(api.sourceSecret<EventSource_>(s.path))),
|
newSecret: (s: Source) => run(() => source(api.sourceSecret<EventSource_>(s.id))),
|
||||||
requestUnsigned: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.path, false))),
|
requestUnsigned: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.id, false))),
|
||||||
requireSigning: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.path, true))),
|
requireSigning: (s: Source) => run(() => source(api.sourceSigning<EventSource_>(s.id, true))),
|
||||||
approveUnsigned: (s: Source) => run(() => source(api.sourceApproveUnsigned<EventSource_>(s.path))),
|
approveUnsigned: (s: Source) => run(() => source(api.sourceApproveUnsigned<EventSource_>(s.id))),
|
||||||
rename: (s: Source, name: string) => run(() => source(api.sourceName<EventSource_>(s.path, name.trim()))),
|
rename: (s: Source, label: string) => run(() => source(api.sourceLabel<EventSource_>(s.id, label.trim()))),
|
||||||
|
setWebhookPath: (s: Source, path: string) =>
|
||||||
|
run(() => source(api.sourceWebhookPath<EventSource_>(s.id, path.trim()))),
|
||||||
setDeliveryHeader: (s: Source, header: string) =>
|
setDeliveryHeader: (s: Source, header: string) =>
|
||||||
run(() => source(api.sourceDeliveryHeader<EventSource_>(s.path, header.trim()))),
|
run(() => source(api.sourceDeliveryHeader<EventSource_>(s.id, header.trim()))),
|
||||||
setCapture: (s: Source, capture: boolean) => run(() => source(api.sourceCapture(s.path, capture))),
|
setCapture: (s: Source, capture: boolean) => run(() => source(api.sourceCapture(s.id, capture))),
|
||||||
// A trigger that names the source refuses the delete; the refusal shows
|
// A trigger that names the source refuses the delete; the refusal shows
|
||||||
// as the panel's failure.
|
// as the panel's failure.
|
||||||
remove: (s: Source) => run(() => api.sourceDelete(s.path)),
|
remove: (s: Source) => run(() => api.sourceDelete(s.id)),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user