A source is keyed by a uuid, owned by the organisation or one person, and labelled within that scope. The webhook path is a separate unique column, so renaming either leaves stored events, event types, triggers, groups, mappings and drafts alone. Delivery policies, sealed secrets and group keys use the id.
811 lines
32 KiB
Go
811 lines
32 KiB
Go
package events
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json/jsontext"
|
|
json "encoding/json/v2"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/danielgtaylor/huma/v2"
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
|
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
|
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
|
"github.com/samcharles93/archie-core/modules/governance"
|
|
"github.com/samcharles93/archie-core/modules/runs"
|
|
)
|
|
|
|
// Register adds the events API: sources, triggers, groups of unmatched events
|
|
// and the events themselves.
|
|
func (m *Module) Register(api huma.API) {
|
|
m.registerCapture(api)
|
|
m.registerSourceSettings(api)
|
|
tags := []string{"Events"}
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindSource), huma.Operation{
|
|
OperationID: "list-sources", Method: http.MethodGet, Path: "/api/sources",
|
|
Summary: "List sources", Tags: tags,
|
|
}, m.sources)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
|
|
OperationID: "create-source", Method: http.MethodPost, Path: "/api/sources",
|
|
Summary: "Add a source, owned by the organisation or by the caller", Tags: tags,
|
|
}, m.createSource)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
|
|
OperationID: "update-source", Method: http.MethodPut, Path: "/api/sources/{id}",
|
|
Summary: "Change a source's connector, verification scheme and token", Tags: tags,
|
|
}, m.updateSource)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindSource), huma.Operation{
|
|
OperationID: "put-source-key-fields", Method: http.MethodPut, Path: "/api/sources/{id}/key-fields",
|
|
Summary: "Set the fields a source's events are grouped by", Tags: tags,
|
|
}, m.putKeyFields)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindTrigger), huma.Operation{
|
|
OperationID: "list-triggers", Method: http.MethodGet, Path: "/api/triggers",
|
|
Summary: "List triggers", Tags: tags,
|
|
}, m.triggers)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindTrigger), huma.Operation{
|
|
OperationID: "put-trigger", Method: http.MethodPut, Path: "/api/triggers/{name}",
|
|
Summary: "Add or change a trigger", Tags: tags,
|
|
}, m.putTrigger)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindEventIngest), huma.Operation{
|
|
OperationID: "list-groups", Method: http.MethodGet, Path: "/api/groups",
|
|
Summary: "List groups of unmatched events", Tags: tags,
|
|
}, m.groups)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindEventIngest), huma.Operation{
|
|
OperationID: "list-events", Method: http.MethodGet, Path: "/api/events",
|
|
Summary: "List recent events", Tags: tags,
|
|
}, m.recent)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindEventIngest), huma.Operation{
|
|
OperationID: "get-event", Method: http.MethodGet, Path: "/api/events/{id}",
|
|
Summary: "Get an event with its payload and the runs it started", Tags: tags,
|
|
}, m.event)
|
|
}
|
|
|
|
// SourceSettings are what a source's connector and verification need.
|
|
type SourceSettings struct {
|
|
Connector string `json:"connector" doc:"The connector that parses this source's events"`
|
|
// A new source without a scheme uses a bearer token, so existing
|
|
// senders keep working.
|
|
Verification string `json:"verification,omitzero" enum:"token,hmac,none" doc:"How deliveries are verified: a bearer token, an HMAC-SHA256 signature of the body, or no verification"`
|
|
HMACHeader string `json:"hmac_header,omitzero" doc:"The header that carries the signature (hmac only)"`
|
|
HMACPrefix string `json:"hmac_prefix,omitzero" doc:"Text before the hex digest in the signature header, such as sha256= (hmac only)" example:"sha256="`
|
|
HMACSecret string `json:"hmac_secret,omitzero" doc:"The shared signing secret (hmac only). Write-only: it is sealed and never returned. When none is stored or sent, one is generated and returned once"`
|
|
}
|
|
|
|
type createSourceInput struct {
|
|
Body struct {
|
|
Label string `json:"label" minLength:"1" maxLength:"100" doc:"The name people see, unique among the sources of the same owner"`
|
|
WebhookPath string `json:"webhook_path,omitzero" doc:"Lowercase letters, digits and hyphens; the webhook URL ends in it. Defaults to the label"`
|
|
Scope string `json:"scope,omitzero" enum:"org,person" doc:"Who owns the source: the organisation (default) or the caller, who alone can see and use it"`
|
|
SourceSettings
|
|
}
|
|
}
|
|
|
|
type sourceCreated struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Token string `json:"token,omitzero" doc:"Returned once for a token source; only its hash is stored"`
|
|
Secret string `json:"secret,omitzero" doc:"A signing secret generated for an HMAC source, returned once"`
|
|
URL string `json:"url" doc:"Where the sender posts its events"`
|
|
}
|
|
|
|
var pathChars = regexp.MustCompile(`[^a-z0-9]+`)
|
|
|
|
// pathFor derives a webhook path from a label.
|
|
func pathFor(label string) string {
|
|
path := strings.Trim(pathChars.ReplaceAllString(strings.ToLower(label), "-"), "-")
|
|
if len(path) > 63 {
|
|
path = strings.Trim(path[:63], "-")
|
|
}
|
|
return path
|
|
}
|
|
|
|
// createSource adds a source. It returns a token only for the token scheme,
|
|
// and only its hash is stored. An HMAC secret is sealed and never returned,
|
|
// except one generated here.
|
|
func (m *Module) createSource(ctx context.Context, in *createSourceInput) (*httpapi.Reply[sourceCreated], error) {
|
|
body := in.Body
|
|
label := strings.TrimSpace(body.Label)
|
|
path := body.WebhookPath
|
|
if path == "" {
|
|
path = pathFor(label)
|
|
}
|
|
if label == "" || !validName.MatchString(path) || !validName.MatchString(body.Connector) {
|
|
return nil, huma.Error400BadRequest("a source needs a label, a webhook path of lowercase letters, digits and hyphens, and a connector")
|
|
}
|
|
base := store.Source{
|
|
ID: uuid.New(), Scope: store.ScopeOrg, OrgID: m.orgID, Label: label, WebhookPath: path,
|
|
}
|
|
if body.Scope == store.ScopePerson {
|
|
base.Scope, base.PersonID = store.ScopePerson, sql.NullString{String: caller(ctx), Valid: true}
|
|
}
|
|
src, issued, err := m.sourceToSave(body.SourceSettings, base, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := sourceWriteError(m.store.InsertSource(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
|
|
}
|
|
|
|
type updateSourceInput struct {
|
|
ID string `path:"id" format:"uuid"`
|
|
Body SourceSettings
|
|
}
|
|
|
|
// updateSource changes a source's connector and verification. A save that omits
|
|
// verification keeps the stored scheme and its credentials. A token is returned
|
|
// only when the token scheme is chosen explicitly, and only its hash is stored.
|
|
// An HMAC secret is sealed and never returned; a blank secret keeps the sealed
|
|
// one.
|
|
func (m *Module) updateSource(ctx context.Context, in *updateSourceInput) (*httpapi.Reply[sourceCreated], error) {
|
|
stored, err := m.readSource(ctx, in.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !validName.MatchString(in.Body.Connector) {
|
|
return nil, huma.Error400BadRequest("a source needs a connector")
|
|
}
|
|
src, issued, err := m.sourceToSave(in.Body, stored, &stored)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := sourceWriteError(m.store.UpdateSource(ctx, src)); err != nil {
|
|
return nil, err
|
|
}
|
|
return httpapi.OK(sourceCreated{ID: src.ID, Token: issued.token, Secret: issued.secret, URL: "/hooks/" + src.WebhookPath}), nil
|
|
}
|
|
|
|
// issued is a credential generated for a saved source, returned once.
|
|
type issued struct{ token, secret string }
|
|
|
|
// sourceToSave builds the row to store from the request settings, the source's
|
|
// fixed attributes in base, and the stored source if there is one. It returns
|
|
// the token or secret it generated, if any.
|
|
func (m *Module) sourceToSave(set SourceSettings, base store.Source, stored *store.Source) (store.Source, issued, error) {
|
|
explicit := set.Verification != ""
|
|
// The secret column is NOT NULL, so a source without a secret carries an
|
|
// empty value: the driver writes a nil slice as NULL.
|
|
src := base
|
|
src.Connector, src.Verification, src.HMACSecretSealed = set.Connector, set.Verification, []byte{}
|
|
switch {
|
|
case !explicit && stored != nil:
|
|
// Omitting the scheme keeps the stored one with its token or secret, so
|
|
// a save cannot downgrade a source.
|
|
src = *stored
|
|
src.Connector = set.Connector
|
|
case !explicit:
|
|
src.Verification = store.Token
|
|
}
|
|
switch src.Verification {
|
|
case store.Token:
|
|
if stored != nil && !explicit {
|
|
return src, issued{}, nil
|
|
}
|
|
token, err := newToken()
|
|
if err != nil {
|
|
return src, issued{}, huma.Error500InternalServerError("couldn't generate a token", err)
|
|
}
|
|
src.TokenSHA256 = httpjson.TokenHash(token)
|
|
return src, issued{token: token}, nil
|
|
case store.None:
|
|
return src, issued{}, nil
|
|
case store.HMAC:
|
|
var secret string
|
|
if explicit {
|
|
var err error
|
|
if secret, err = m.setHMAC(&src, set, stored); err != nil {
|
|
return src, issued{}, err
|
|
}
|
|
}
|
|
if src.HMACHeader == "" || len(src.HMACSecretSealed) == 0 {
|
|
return src, issued{}, huma.Error400BadRequest("an HMAC source needs a signature header")
|
|
}
|
|
return src, issued{secret: secret}, nil
|
|
default:
|
|
return src, issued{}, huma.Error400BadRequest("verification must be token, hmac or none")
|
|
}
|
|
}
|
|
|
|
// setHMAC applies the requested HMAC settings. A blank secret keeps the sealed
|
|
// secret a source already has, and a source that has none gets a generated one,
|
|
// which is returned so it can be shown once.
|
|
func (m *Module) setHMAC(src *store.Source, set SourceSettings, stored *store.Source) (generated string, err error) {
|
|
src.HMACHeader, src.HMACPrefix = set.HMACHeader, set.HMACPrefix
|
|
secret := set.HMACSecret
|
|
switch {
|
|
case secret != "":
|
|
case stored != nil && len(stored.HMACSecretSealed) > 0:
|
|
src.HMACSecretSealed = stored.HMACSecretSealed
|
|
return "", nil
|
|
default:
|
|
if secret, err = newSecret(); err != nil {
|
|
return "", huma.Error500InternalServerError("couldn't generate a secret", err)
|
|
}
|
|
generated = secret
|
|
}
|
|
sealed, err := m.sealer.Seal(secretLabel(m.orgID, src.ID), []byte(secret))
|
|
if err != nil {
|
|
return "", huma.Error500InternalServerError("couldn't seal the secret", err)
|
|
}
|
|
src.HMACSecretSealed = sealed
|
|
return generated, nil
|
|
}
|
|
|
|
type putTriggerInput struct {
|
|
Name string `path:"name" doc:"Lowercase letters, digits and hyphens"`
|
|
Body struct {
|
|
SourceID string `json:"source_id,omitzero" format:"uuid" doc:"The source whose events fire it; none when every is set"`
|
|
EventType string `json:"event_type,omitzero" doc:"The event type that fires it; fixed when every is set"`
|
|
Filter map[string]string `json:"filter,omitzero" doc:"Event fields that must match exactly"`
|
|
Workflow string `json:"workflow" doc:"The workflow each match runs"`
|
|
Disabled bool `json:"disabled,omitzero"`
|
|
Every string `json:"every,omitzero" doc:"Fire on an interval instead of on events, such as 1h" example:"1h"`
|
|
// EventTypeID restricts the trigger to events identified as that event
|
|
// type, and MappingID reads their payload for the run.
|
|
EventTypeID string `json:"event_type_id,omitzero" format:"uuid" doc:"Fire only for events identified as this event type of the source"`
|
|
MappingID string `json:"mapping_id,omitzero" format:"uuid" doc:"A mapping of the event type that reads the payload into the run's input under mapped"`
|
|
Pending bool `json:"pending,omitzero" doc:"Save the trigger waiting for approval; it fires once a person approves it"`
|
|
}
|
|
}
|
|
|
|
type triggerSaved struct {
|
|
Trigger string `json:"trigger"`
|
|
}
|
|
|
|
// parseEvery reads a schedule interval; an empty one is no schedule.
|
|
func parseEvery(raw string) (sql.NullInt64, error) {
|
|
if raw == "" {
|
|
return sql.NullInt64{}, nil
|
|
}
|
|
d, err := time.ParseDuration(raw)
|
|
if err != nil || d < minInterval || d%time.Second != 0 {
|
|
return sql.NullInt64{}, huma.Error400BadRequest("every is a whole number of seconds of at least one minute, such as 1h")
|
|
}
|
|
return sql.NullInt64{Int64: int64(d / time.Second), Valid: true}, nil
|
|
}
|
|
|
|
func (m *Module) putTrigger(ctx context.Context, in *putTriggerInput) (*httpapi.Reply[triggerSaved], error) {
|
|
req := in.Body
|
|
every, err := parseEvery(req.Every)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if every.Valid {
|
|
req.SourceID, req.EventType = "", scheduleType
|
|
// Every schedule's ticks share a source and type, so the filter keeps
|
|
// this trigger to its own.
|
|
req.Filter = map[string]string{"trigger": in.Name}
|
|
}
|
|
if !validName.MatchString(in.Name) || (req.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")
|
|
}
|
|
sourceID, err := m.triggerSource(ctx, req.SourceID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
typeID, mappingID, err := m.checkTargets(ctx, sourceID, req.EventType, req.Workflow, req.EventTypeID, req.MappingID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
filter, err := json.Marshal(req.Filter)
|
|
if err != nil {
|
|
return nil, huma.Error400BadRequest(err.Error())
|
|
}
|
|
approved, err := m.approvedOnSave(ctx, in.Name, req.Pending)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := m.store.UpsertTrigger(ctx, store.Trigger{
|
|
OrgID: m.orgID, Name: in.Name, SourceID: sourceID, EventType: req.EventType,
|
|
Filter: filter, Workflow: req.Workflow, Enabled: !req.Disabled, Approved: approved,
|
|
EventTypeID: typeID, MappingID: mappingID, ScheduleEverySeconds: every,
|
|
}); err != nil {
|
|
return nil, huma.Error500InternalServerError("couldn't save the trigger", err)
|
|
}
|
|
return httpapi.OK(triggerSaved{Trigger: in.Name}), nil
|
|
}
|
|
|
|
// triggerSource parses the source a trigger names, if any, and refuses one the
|
|
// caller can't use.
|
|
func (m *Module) triggerSource(ctx context.Context, raw string) (uuid.NullUUID, error) {
|
|
if raw == "" {
|
|
return uuid.NullUUID{}, nil
|
|
}
|
|
refuse := func(message string) error {
|
|
return huma.Error400BadRequest(message, &huma.ErrorDetail{Location: "body.source_id", Message: message})
|
|
}
|
|
id, err := uuid.Parse(raw)
|
|
if err != nil {
|
|
return uuid.NullUUID{}, refuse("a source id is a UUID")
|
|
}
|
|
usable, err := m.canUse(ctx, id)
|
|
if err != nil {
|
|
return uuid.NullUUID{}, huma.Error500InternalServerError("couldn't read the source", err)
|
|
}
|
|
if !usable {
|
|
return uuid.NullUUID{}, refuse("no such source")
|
|
}
|
|
return uuid.NullUUID{UUID: id, Valid: true}, nil
|
|
}
|
|
|
|
// checkTargets refuses a trigger whose workflow can't be started or whose
|
|
// event type, mapping or connector event type doesn't exist.
|
|
func (m *Module) checkTargets(ctx context.Context, sourceID uuid.NullUUID, eventType, workflow, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) {
|
|
if typeID, mapID, err = m.checkBinding(ctx, sourceID, eventTypeID, mappingID); err != nil {
|
|
return typeID, mapID, err
|
|
}
|
|
if err := m.runs.CheckTrigger(ctx, m.orgID, workflow); err != nil {
|
|
if refused, ok := errors.AsType[*runs.InvalidError](err); ok {
|
|
return typeID, mapID, huma.Error400BadRequest(refused.Problems[0].Message, &huma.ErrorDetail{Location: "body.workflow", Message: refused.Problems[0].Message})
|
|
}
|
|
return typeID, mapID, huma.Error500InternalServerError("couldn't check the workflow", err)
|
|
}
|
|
if eventType != "" {
|
|
err = m.checkEventType(ctx, sourceID, eventType)
|
|
}
|
|
return typeID, mapID, err
|
|
}
|
|
|
|
// approvedOnSave decides whether a saved trigger is approved. A new trigger is
|
|
// unless it asks to wait; a saved one keeps its approval unless the change asks
|
|
// to wait for a new approval.
|
|
func (m *Module) approvedOnSave(ctx context.Context, name string, pending bool) (bool, error) {
|
|
if pending {
|
|
return false, nil
|
|
}
|
|
t, err := m.store.Trigger(ctx, m.orgID, name)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
return true, nil
|
|
}
|
|
if err != nil {
|
|
return false, huma.Error500InternalServerError("couldn't read the trigger", err)
|
|
}
|
|
return t.Approved, nil
|
|
}
|
|
|
|
// checkBinding resolves the event type and mapping a trigger binds to. The
|
|
// event type must be the source's, and the mapping the event type's.
|
|
func (m *Module) checkBinding(ctx context.Context, sourceID uuid.NullUUID, eventTypeID, mappingID string) (typeID, mapID uuid.NullUUID, err error) {
|
|
refuse := func(location, message string) error {
|
|
return huma.Error400BadRequest(message, &huma.ErrorDetail{Location: location, Message: message})
|
|
}
|
|
if eventTypeID != "" {
|
|
id, err := uuid.Parse(eventTypeID)
|
|
if err != nil {
|
|
return typeID, mapID, refuse("body.event_type_id", "an event type id is a UUID")
|
|
}
|
|
t, err := m.store.EventType(ctx, m.orgID, id)
|
|
if errors.Is(err, store.ErrNotFound) || (err == nil && (!sourceID.Valid || t.SourceID != sourceID.UUID)) {
|
|
return typeID, mapID, refuse("body.event_type_id", "the source has no such event type")
|
|
}
|
|
if err != nil {
|
|
return typeID, mapID, huma.Error500InternalServerError("couldn't read the event type", err)
|
|
}
|
|
typeID = uuid.NullUUID{UUID: id, Valid: true}
|
|
}
|
|
if mappingID != "" {
|
|
id, err := uuid.Parse(mappingID)
|
|
if err != nil {
|
|
return typeID, mapID, refuse("body.mapping_id", "a mapping id is a UUID")
|
|
}
|
|
mp, err := m.store.Mapping(ctx, m.orgID, id)
|
|
if errors.Is(err, store.ErrNotFound) || (err == nil && (!typeID.Valid || mp.EventTypeID != typeID.UUID)) {
|
|
return typeID, mapID, refuse("body.mapping_id", "the mapping must belong to the trigger's event type")
|
|
}
|
|
if err != nil {
|
|
return typeID, mapID, huma.Error500InternalServerError("couldn't read the mapping", err)
|
|
}
|
|
mapID = uuid.NullUUID{UUID: id, Valid: true}
|
|
}
|
|
return typeID, mapID, nil
|
|
}
|
|
|
|
// checkEventType refuses a trigger on an event type that the source's
|
|
// connector doesn't declare, so the trigger can't be saved when it could never
|
|
// fire, and a trigger on a source the caller can't use. Schedule triggers have
|
|
// no source.
|
|
func (m *Module) checkEventType(ctx context.Context, sourceID uuid.NullUUID, eventType string) error {
|
|
if !sourceID.Valid {
|
|
return nil
|
|
}
|
|
refuse := func(location, message string) error {
|
|
return huma.Error400BadRequest(message, &huma.ErrorDetail{Location: location, Message: message})
|
|
}
|
|
src, err := m.reader.Source(ctx, m.orgID, sourceID.UUID)
|
|
if errors.Is(err, store.ErrNotFound) || (err == nil && !src.VisibleTo(caller(ctx))) {
|
|
return refuse("body.source_id", "no such source")
|
|
}
|
|
if err != nil {
|
|
return huma.Error500InternalServerError("couldn't read the source", err)
|
|
}
|
|
caps, ok, err := m.connectors.Capabilities(ctx, src.Connector)
|
|
if err != nil {
|
|
return huma.Error500InternalServerError("couldn't read what the connector declares", err)
|
|
}
|
|
if !ok {
|
|
return refuse("body.event_type", fmt.Sprintf("connector %q isn't accepted or has never loaded, so its event types aren't known", src.Connector))
|
|
}
|
|
if _, declared := caps.Event(eventType); !declared {
|
|
return refuse("body.event_type", fmt.Sprintf("connector %q declares no event type %q", src.Connector, eventType))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type putKeyFieldsInput struct {
|
|
ID string `path:"id" format:"uuid"`
|
|
Body struct {
|
|
Paths []string `json:"paths,omitzero" doc:"Paths into the event's fields; none uses the connector's default"`
|
|
}
|
|
}
|
|
|
|
type keyFieldsSaved struct {
|
|
KeyFields []string `json:"key_fields"`
|
|
}
|
|
|
|
// putKeyFields sets the fields a source's events are grouped by. It applies to
|
|
// events that arrive after it.
|
|
func (m *Module) putKeyFields(ctx context.Context, in *putKeyFieldsInput) (*httpapi.Reply[keyFieldsSaved], error) {
|
|
paths := in.Body.Paths
|
|
if paths == nil {
|
|
paths = []string{}
|
|
}
|
|
raw, err := json.Marshal(paths)
|
|
if err != nil {
|
|
return nil, huma.Error400BadRequest(err.Error())
|
|
}
|
|
src, err := m.readSource(ctx, in.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = m.store.SetKeyFields(ctx, m.orgID, src.ID, raw)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
return nil, huma.Error404NotFound("no such source")
|
|
}
|
|
if err != nil {
|
|
return nil, huma.Error500InternalServerError("couldn't save the key fields", err)
|
|
}
|
|
return httpapi.OK(keyFieldsSaved{KeyFields: paths}), nil
|
|
}
|
|
|
|
// groupView is a group of unmatched events as the API returns it. Proposed is
|
|
// the trigger it suggests, with the workflow left for the person to choose.
|
|
type groupView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Count int64 `json:"count"`
|
|
FirstSeen time.Time `json:"first_seen"`
|
|
LastSeen time.Time `json:"last_seen"`
|
|
Proposed proposedTrigger `json:"proposed"`
|
|
}
|
|
|
|
type proposedTrigger struct {
|
|
SourceID uuid.UUID `json:"source_id"`
|
|
Source string `json:"source" doc:"The source's label"`
|
|
EventType string `json:"event_type"`
|
|
Filter jsontext.Value `json:"filter"`
|
|
Workflow string `json:"workflow"`
|
|
}
|
|
|
|
func (m *Module) groups(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]groupView], error) {
|
|
groups, err := m.store.Groups(ctx, m.orgID, caller(ctx), 200)
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "list groups", "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't list groups")
|
|
}
|
|
labels, err := m.labels(ctx)
|
|
if err != nil {
|
|
return nil, huma.Error500InternalServerError("couldn't list groups", err)
|
|
}
|
|
out := make([]groupView, 0, len(groups))
|
|
for _, g := range groups {
|
|
out = append(out, groupView{
|
|
ID: g.ID, Count: g.Count, FirstSeen: g.FirstSeen, LastSeen: g.LastSeen,
|
|
Proposed: proposedTrigger{SourceID: g.SourceID, Source: labels[g.SourceID], EventType: g.EventType, Filter: g.Filter},
|
|
})
|
|
}
|
|
return httpapi.OK(out), nil
|
|
}
|
|
|
|
// sourceView is a source as the API returns it. The token is returned only
|
|
// when it is created or rotated, never here.
|
|
type sourceView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
// Scope is org for an organisation's source and person for one only its
|
|
// owner can see and use.
|
|
Scope string `json:"scope" enum:"org,person"`
|
|
// Label is the name people see; WebhookPath ends the URL deliveries post to.
|
|
Label string `json:"label"`
|
|
WebhookPath string `json:"webhook_path"`
|
|
Connector string `json:"connector"`
|
|
KeyFields []string `json:"key_fields"`
|
|
TokenSet bool `json:"token_set"`
|
|
// Verification and the HMAC header and prefix are shown; the secret is
|
|
// only reported as set.
|
|
Verification string `json:"verification"`
|
|
HMACHeader string `json:"hmac_header,omitzero"`
|
|
HMACPrefix string `json:"hmac_prefix,omitzero"`
|
|
HMACSecretSet bool `json:"hmac_secret_set"`
|
|
// DeliveryHeader names the header a sender repeats on every retry of one
|
|
// delivery.
|
|
DeliveryHeader string `json:"delivery_header,omitzero"`
|
|
// Signing is signed (HMAC), token, unsigned_pending_approval or unsigned.
|
|
Signing string `json:"signing" enum:"signed,token,unsigned_pending_approval,unsigned"`
|
|
// Capture says the source keeps each delivery's headers and payload.
|
|
Capture bool `json:"capture"`
|
|
// Secret is a signing secret the request issued, returned once.
|
|
Secret string `json:"secret,omitzero"`
|
|
}
|
|
|
|
func (m *Module) sources(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]sourceView], error) {
|
|
sources, err := m.store.SourcesFor(ctx, m.orgID, caller(ctx))
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "list sources", "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't list sources")
|
|
}
|
|
out := make([]sourceView, 0, len(sources))
|
|
for _, src := range sources {
|
|
view, err := viewOfSource(src)
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "read source key fields", "source", src.ID, "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't read the key fields of " + src.Label)
|
|
}
|
|
out = append(out, view)
|
|
}
|
|
return httpapi.OK(out), nil
|
|
}
|
|
|
|
func viewOfSource(src store.Source) (sourceView, error) {
|
|
view := sourceView{
|
|
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,
|
|
DeliveryHeader: src.DeliveryHeader, Signing: signingOf(src), Capture: src.Capture,
|
|
}
|
|
if len(src.KeyFields) > 0 {
|
|
if err := json.Unmarshal(src.KeyFields, &view.KeyFields); err != nil {
|
|
return view, err
|
|
}
|
|
}
|
|
return view, nil
|
|
}
|
|
|
|
// triggerView is a trigger as the API returns it.
|
|
type triggerView struct {
|
|
Name string `json:"name"`
|
|
// SourceID is empty for a scheduled trigger. Source is the source's label.
|
|
SourceID string `json:"source_id,omitempty"`
|
|
Source string `json:"source,omitempty"`
|
|
EventType string `json:"event_type"`
|
|
Filter map[string]string `json:"filter"`
|
|
Workflow string `json:"workflow"`
|
|
Enabled bool `json:"enabled"`
|
|
Every string `json:"every,omitempty"`
|
|
// Status is pending_approval, armed or paused.
|
|
Status string `json:"status" enum:"pending_approval,armed,paused"`
|
|
EventTypeID string `json:"event_type_id,omitempty"`
|
|
MappingID string `json:"mapping_id,omitempty"`
|
|
// Unsigned marks a trigger whose source takes deliveries with no
|
|
// verification.
|
|
Unsigned bool `json:"unsigned"`
|
|
}
|
|
|
|
func statusOf(t store.Trigger) string {
|
|
switch {
|
|
case !t.Approved:
|
|
return "pending_approval"
|
|
case !t.Enabled:
|
|
return "paused"
|
|
}
|
|
return "armed"
|
|
}
|
|
|
|
// viewOfTrigger is the API's form of a stored trigger. Unsigned is set by the
|
|
// caller, which knows the sources.
|
|
func viewOfTrigger(t store.Trigger) (triggerView, error) {
|
|
view := triggerView{Name: t.Name, EventType: t.EventType, Workflow: t.Workflow, Enabled: t.Enabled, Filter: map[string]string{}, Status: statusOf(t)}
|
|
if len(t.Filter) > 0 {
|
|
if err := json.Unmarshal(t.Filter, &view.Filter); err != nil {
|
|
return view, fmt.Errorf("filter of %s: %w", t.Name, err)
|
|
}
|
|
}
|
|
if t.ScheduleEverySeconds.Valid {
|
|
view.Every = (time.Duration(t.ScheduleEverySeconds.Int64) * time.Second).String()
|
|
}
|
|
if t.SourceID.Valid {
|
|
view.SourceID = t.SourceID.UUID.String()
|
|
}
|
|
if t.EventTypeID.Valid {
|
|
view.EventTypeID = t.EventTypeID.UUID.String()
|
|
}
|
|
if t.MappingID.Valid {
|
|
view.MappingID = t.MappingID.UUID.String()
|
|
}
|
|
return view, nil
|
|
}
|
|
|
|
// viewOfTrigger returns a trigger with whether its source is unsigned.
|
|
func (m *Module) viewOfTrigger(ctx context.Context, t store.Trigger) (triggerView, error) {
|
|
view, err := viewOfTrigger(t)
|
|
if err != nil {
|
|
return view, err
|
|
}
|
|
if t.SourceID.Valid {
|
|
if src, err := m.store.Source(ctx, m.orgID, t.SourceID.UUID); err == nil {
|
|
view.Source, view.Unsigned = src.Label, src.Verification == store.None
|
|
}
|
|
}
|
|
return view, nil
|
|
}
|
|
|
|
func (m *Module) triggers(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]triggerView], error) {
|
|
triggers, err := m.store.AllTriggers(ctx, m.orgID)
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "list triggers", "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't list triggers")
|
|
}
|
|
sources, err := m.store.SourcesFor(ctx, m.orgID, caller(ctx))
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "list sources", "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't list triggers")
|
|
}
|
|
visible := make(map[uuid.UUID]store.Source, len(sources))
|
|
for _, src := range sources {
|
|
visible[src.ID] = src
|
|
}
|
|
out := make([]triggerView, 0, len(triggers))
|
|
for _, t := range triggers {
|
|
src, seen := visible[t.SourceID.UUID]
|
|
if t.SourceID.Valid && !seen {
|
|
continue
|
|
}
|
|
view, err := viewOfTrigger(t)
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "read trigger", "trigger", t.Name, "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't read the filter of " + t.Name)
|
|
}
|
|
view.Source, view.Unsigned = src.Label, src.Verification == store.None
|
|
out = append(out, view)
|
|
}
|
|
return httpapi.OK(out), nil
|
|
}
|
|
|
|
type recentInput struct {
|
|
Limit int `query:"limit" minimum:"1" maximum:"500" default:"50"`
|
|
SourceID string `query:"source_id" format:"uuid"`
|
|
Type string `query:"type"`
|
|
Matched string `query:"matched" enum:"true,false" doc:"Only events a trigger did or didn't match"`
|
|
}
|
|
|
|
func (m *Module) recent(ctx context.Context, in *recentInput) (*httpapi.Reply[[]eventView], error) {
|
|
filter := store.EventFilter{Type: in.Type, Limit: in.Limit}
|
|
if in.SourceID != "" {
|
|
id, err := uuid.Parse(in.SourceID)
|
|
if err != nil {
|
|
return nil, huma.Error400BadRequest("a source id is a UUID")
|
|
}
|
|
filter.SourceID = uuid.NullUUID{UUID: id, Valid: true}
|
|
}
|
|
if in.Matched != "" {
|
|
matched, err := strconv.ParseBool(in.Matched)
|
|
if err != nil {
|
|
return nil, huma.Error400BadRequest("matched is true or false")
|
|
}
|
|
filter.Matched = &matched
|
|
}
|
|
events, err := m.store.Recent(ctx, m.orgID, caller(ctx), filter)
|
|
if err != nil {
|
|
return nil, huma.Error500InternalServerError("couldn't list events", err)
|
|
}
|
|
labels, err := m.labels(ctx)
|
|
if err != nil {
|
|
return nil, huma.Error500InternalServerError("couldn't list events", err)
|
|
}
|
|
out := make([]eventView, 0, len(events))
|
|
for _, e := range events {
|
|
out = append(out, viewOf(e, labels))
|
|
}
|
|
return httpapi.OK(out), nil
|
|
}
|
|
|
|
// eventDetail is one event with the payload it arrived in and the runs it
|
|
// started.
|
|
type eventDetail struct {
|
|
eventView
|
|
Body jsontext.Value `json:"body"`
|
|
Runs []triggerRun `json:"runs"`
|
|
}
|
|
|
|
// triggerRun is the outcome of a trigger for an event: the run it started,
|
|
// or the reason no run started.
|
|
type triggerRun struct {
|
|
Trigger string `json:"trigger"`
|
|
RunID *uuid.UUID `json:"run_id,omitempty"`
|
|
Outcome string `json:"outcome" enum:"started,failed,denied,disabled"`
|
|
Reason jsontext.Value `json:"reason,omitempty"`
|
|
}
|
|
|
|
func runIDOf(id uuid.NullUUID) *uuid.UUID {
|
|
if !id.Valid {
|
|
return nil
|
|
}
|
|
return &id.UUID
|
|
}
|
|
|
|
type eventInput struct {
|
|
ID string `path:"id" format:"uuid"`
|
|
}
|
|
|
|
func (m *Module) event(ctx context.Context, in *eventInput) (*httpapi.Reply[eventDetail], error) {
|
|
id, err := uuid.Parse(in.ID)
|
|
if err != nil {
|
|
return nil, huma.Error400BadRequest("an event id is a UUID")
|
|
}
|
|
e, err := m.store.Event(ctx, m.orgID, caller(ctx), id)
|
|
if errors.Is(err, store.ErrNotFound) {
|
|
return nil, huma.Error404NotFound("no such event")
|
|
}
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "read event", "event", id, "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't read the event")
|
|
}
|
|
runs, err := m.store.RunsForEvent(ctx, m.orgID, id)
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "read event runs", "event", id, "error", err)
|
|
return nil, huma.Error500InternalServerError("couldn't read the runs of the event")
|
|
}
|
|
labels, err := m.labels(ctx)
|
|
if err != nil {
|
|
return nil, huma.Error500InternalServerError("couldn't read the event", err)
|
|
}
|
|
view := eventDetail{eventView: viewOf(e, labels), Body: jsontext.Value(e.Body), Runs: make([]triggerRun, 0, len(runs))}
|
|
if len(view.Body) == 0 || !view.Body.IsValid() {
|
|
view.Body = jsontext.Value("null")
|
|
}
|
|
for _, run := range runs {
|
|
view.Runs = append(view.Runs, triggerRun{Trigger: run.Trigger, RunID: runIDOf(run.RunID), Outcome: run.Outcome, Reason: run.Reason})
|
|
}
|
|
return httpapi.OK(view), nil
|
|
}
|
|
|
|
// eventView is an event as the API returns it.
|
|
type eventView struct {
|
|
ID uuid.UUID `json:"id"`
|
|
// SourceID is empty for a schedule tick. Source is the source's label.
|
|
SourceID *uuid.UUID `json:"source_id,omitempty"`
|
|
Source string `json:"source,omitempty"`
|
|
Type string `json:"type"`
|
|
Fields jsontext.Value `json:"fields"`
|
|
LinkedTo *uuid.UUID `json:"linked_to,omitempty"`
|
|
OccurredAt *time.Time `json:"occurred_at,omitempty"`
|
|
ReceivedAt time.Time `json:"received_at"`
|
|
Matched bool `json:"matched"`
|
|
DispatchedAt *time.Time `json:"dispatched_at,omitempty"`
|
|
// Verification is how the delivery was verified: signed, token or unsigned.
|
|
// It is empty for an event a connector streamed.
|
|
Verification string `json:"verification,omitempty"`
|
|
}
|
|
|
|
func viewOf(e store.Event, labels map[uuid.UUID]string) eventView {
|
|
v := eventView{
|
|
Verification: e.Verification,
|
|
ID: e.ID, Source: labels[e.SourceID.UUID], Type: e.Type, Fields: e.Fields, LinkedTo: e.LinkedTo,
|
|
ReceivedAt: e.ReceivedAt, Matched: e.Matched,
|
|
}
|
|
if e.SourceID.Valid {
|
|
v.SourceID = &e.SourceID.UUID
|
|
}
|
|
if e.OccurredAt.Valid {
|
|
v.OccurredAt = &e.OccurredAt.Time
|
|
}
|
|
if e.DispatchedAt.Valid {
|
|
v.DispatchedAt = &e.DispatchedAt.Time
|
|
}
|
|
return v
|
|
}
|