Files
archie/modules/events/api_sources.go
T

404 lines
16 KiB
Go

package events
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"net/http"
"net/textproto"
"strings"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
"golang.org/x/net/http/httpguts"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
"github.com/samcharles93/archie-core/modules/events/internal/store"
"github.com/samcharles93/archie-core/modules/governance"
)
// registerSourceSettings adds the operations that change one setting of a
// source, and the trigger lifecycle. Approving an unsigned source or a
// trigger has its own grant, so a role that may edit them cannot also approve.
func (m *Module) registerSourceSettings(api huma.API) {
tags := []string{"Events"}
op := func(id, method, path, summary string) huma.Operation {
return huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags}
}
admin := httpapi.AdminAuthorized[governance.Action, governance.ResourceKind]
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-label", http.MethodPut, "/api/sources/{id}/label", "Rename a source"), m.setSourceLabel)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-webhook-path", http.MethodPut, "/api/sources/{id}/webhook-path", "Move the address a source receives deliveries at"), m.setWebhookPath)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-delivery-header", http.MethodPut, "/api/sources/{id}/delivery-header", "Name the header a sender repeats when it retries a delivery"), m.setDeliveryHeader)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-capture", http.MethodPut, "/api/sources/{id}/capture", "Keep or stop keeping the headers and payloads a source receives"), m.setCapture)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-signing", http.MethodPost, "/api/sources/{id}/signing", "Require an HMAC signature, or ask to take unsigned deliveries"), m.setSigning)
httpapi.Register(api, admin(governance.ActionApprove, governance.KindSource), op("approve-source-unsigned", http.MethodPost, "/api/sources/{id}/approve-unsigned", "Accept deliveries that carry no signature"), m.approveUnsigned)
httpapi.Register(api, admin(governance.ActionReadSecret, governance.KindSecret), op("rotate-source-secret", http.MethodPost, "/api/sources/{id}/secret", "Replace a signed source's secret and return it once"), m.rotateSecret)
httpapi.Register(api, admin(governance.ActionDelete, governance.KindSource), op("delete-source", http.MethodDelete, "/api/sources/{id}", "Delete a source"), m.deleteSource)
httpapi.Register(api, admin(governance.ActionApprove, governance.KindTrigger), op("approve-trigger", http.MethodPost, "/api/triggers/{id}/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/{id}/pause", "Stop a trigger firing"), m.pauseTrigger)
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindTrigger), op("resume-trigger", http.MethodPost, "/api/triggers/{id}/resume", "Return a paused trigger to waiting for approval"), m.resumeTrigger)
httpapi.Register(api, admin(governance.ActionDelete, governance.KindTrigger), op("delete-trigger", http.MethodDelete, "/api/triggers/{id}", "Delete a trigger"), m.deleteTrigger)
httpapi.Register(api, admin(governance.ActionRead, governance.KindTrigger), op("list-trigger-dispatches", http.MethodGet, "/api/triggers/{id}/dispatches", "List the dispatches of a trigger"), m.triggerDispatches)
}
type sourceInput struct {
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
// verification, which waits for approval before it takes deliveries.
const (
signingSigned = "signed"
signingToken = "token"
signingPending = "unsigned_pending_approval"
signingUnsigned = "unsigned"
)
func signingOf(src store.Source) string {
switch {
case src.Verification == store.HMAC:
return signingSigned
case src.Verification == store.Token:
return signingToken
case src.UnsignedApproved:
return signingUnsigned
}
return signingPending
}
// readSource loads a source for a request. A person's source that belongs to
// someone else reads as missing, so its existence isn't disclosed.
func (m *Module) readSource(ctx context.Context, rawID string) (store.Source, error) {
id, err := sourceID(rawID)
if err != nil {
return store.Source{}, err
}
src, err := m.reader.Source(ctx, m.orgID, id)
if errors.Is(err, store.ErrNotFound) || (err == nil && !src.VisibleTo(caller(ctx))) {
return src, huma.Error404NotFound("no such source")
}
if err != nil {
return src, huma.Error500InternalServerError("couldn't read the source", err)
}
return src, nil
}
// sourceReply reads a source back after a change. secret is a signing secret
// issued by the change, returned once.
func (m *Module) sourceReply(ctx context.Context, id, secret string) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, id)
if err != nil {
return nil, err
}
view, err := viewOfSource(src)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't read the key fields of "+src.Label, err)
}
view.Secret = secret
return httpapi.OK(view), nil
}
type sourceLabelInput struct {
ID string `path:"id" format:"uuid"`
Body struct {
Label string `json:"label" minLength:"1" maxLength:"100" doc:"The name people see, unique among the sources of the same owner"`
}
}
func (m *Module) setSourceLabel(ctx context.Context, in *sourceLabelInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
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 {
ID string `path:"id" format:"uuid"`
Body struct {
Header string `json:"header" doc:"A header name; empty stops de-duplicating retries by header"`
}
}
func (m *Module) setDeliveryHeader(ctx context.Context, in *deliveryHeaderInput) (*httpapi.Reply[sourceView], error) {
header := strings.TrimSpace(in.Body.Header)
if header != "" {
if len(header) > 128 || !httpguts.ValidHeaderFieldName(header) {
return nil, huma.Error400BadRequest("the delivery header must be an HTTP header name")
}
header = textproto.CanonicalMIMEHeaderKey(header)
}
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
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 {
ID string `path:"id" format:"uuid"`
Body struct {
Capture bool `json:"capture"`
}
}
// setCapture turns the keeping of a source's payloads on or off. A trigger
// that maps the source's payload needs the stored payload, so it blocks
// turning capture off.
func (m *Module) setCapture(ctx context.Context, in *captureInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
if !in.Body.Capture {
n, err := m.store.MappedTriggers(ctx, m.orgID, src.ID)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't check the triggers of the source", err)
}
if n > 0 {
return nil, huma.Error409Conflict(fmt.Sprintf("%d trigger(s) of this source read its payload through a mapping, which needs it kept", n))
}
}
if err := sourceWriteError(m.store.SetCapture(ctx, m.orgID, src.ID, in.Body.Capture)); err != nil {
return nil, err
}
return m.sourceReply(ctx, in.ID, "")
}
type signingInput struct {
ID string `path:"id" format:"uuid"`
Body struct {
Signed bool `json:"signed" doc:"True requires an HMAC signature; false asks to take deliveries without one, which a person must approve"`
}
}
func (m *Module) setSigning(ctx context.Context, in *signingInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
secret := ""
if in.Body.Signed {
if src.HMACHeader == "" {
return nil, huma.Error409Conflict("set the signature header first: edit the source and choose HMAC signature")
}
if len(src.HMACSecretSealed) == 0 {
if secret, err = m.issueSecret(ctx, src); err != nil {
return nil, err
}
}
}
if err := sourceWriteError(m.store.SetSigning(ctx, m.orgID, src.ID, in.Body.Signed)); err != nil {
return nil, err
}
return m.sourceReply(ctx, in.ID, secret)
}
// approveUnsigned accepts that a source takes deliveries with no verification.
func (m *Module) approveUnsigned(ctx context.Context, in *sourceInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
approved, err := m.store.ApproveUnsigned(ctx, m.orgID, src.ID)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't approve the source", err)
}
if !approved {
return nil, huma.Error409Conflict("the source isn't waiting for approval of unsigned deliveries")
}
return m.sourceReply(ctx, in.ID, "")
}
func (m *Module) rotateSecret(ctx context.Context, in *sourceInput) (*httpapi.Reply[sourceView], error) {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
if src.HMACHeader == "" {
return nil, huma.Error409Conflict("only a source with an HMAC signature header has a secret")
}
secret, err := m.issueSecret(ctx, src)
if err != nil {
return nil, err
}
return m.sourceReply(ctx, in.ID, secret)
}
// issueSecret generates a signing secret, stores it sealed and returns it.
func (m *Module) issueSecret(ctx context.Context, src store.Source) (string, error) {
secret, err := newSecret()
if err != nil {
return "", huma.Error500InternalServerError("couldn't generate a secret", err)
}
sealed, err := m.sealer.Seal(secretLabel(m.orgID, src.ID), []byte(secret))
if err != nil {
return "", huma.Error500InternalServerError("couldn't seal the secret", err)
}
if err := m.store.SetSecret(ctx, m.orgID, src.ID, sealed); err != nil {
return "", huma.Error500InternalServerError("couldn't save the secret", err)
}
return secret, nil
}
// newSecret returns a 256-bit signing secret in hex.
func newSecret() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generate secret: %w", err)
}
return hex.EncodeToString(b), nil
}
func sourceWriteError(err error) error {
switch {
case err == nil:
return nil
case errors.Is(err, store.ErrNotFound):
return huma.Error404NotFound("no such source")
case errors.Is(err, store.ErrLabelTaken), errors.Is(err, store.ErrPathTaken):
return huma.Error409Conflict(err.Error())
}
return huma.Error500InternalServerError("couldn't save the source", err)
}
// deleteSource removes a source. A trigger that names it blocks the delete;
// its event types go with it, and the events it stored stay.
func (m *Module) deleteSource(ctx context.Context, in *sourceInput) (*struct{}, error) {
src, err := m.readSource(ctx, in.ID)
if err != nil {
return nil, err
}
err = m.store.DeleteSource(ctx, m.orgID, src.ID)
switch {
case errors.Is(err, store.ErrNotFound):
return nil, huma.Error404NotFound("no such source")
case errors.Is(err, store.ErrInUse):
return nil, huma.Error409Conflict("the source is still in use: " + err.Error())
case err != nil:
return nil, huma.Error500InternalServerError("couldn't delete the source", err)
}
return nil, nil
}
type triggerInput struct {
ID string `path:"id" format:"uuid"`
}
// moveTrigger changes a trigger's state when it is in one of from, and refuses
// otherwise.
func (m *Module) moveTrigger(ctx context.Context, id string, allowed func(store.Trigger) bool, refusal string, approved, enabled bool) (*httpapi.Reply[triggerView], error) {
t, err := m.visibleTrigger(ctx, id)
if err != nil {
return nil, err
}
if !allowed(t) {
return nil, huma.Error409Conflict(refusal)
}
if _, err := m.store.SetTriggerState(ctx, m.orgID, t.ID, approved, enabled); err != nil {
return nil, huma.Error500InternalServerError("couldn't save the trigger", err)
}
t.Approved, t.Enabled = approved, enabled
view, err := m.viewOfTrigger(ctx, t)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't read the trigger", err)
}
return httpapi.OK(view), nil
}
func (m *Module) approveTrigger(ctx context.Context, in *triggerInput) (*httpapi.Reply[triggerView], error) {
return m.moveTrigger(ctx, in.ID, func(t store.Trigger) bool { return !t.Approved }, "the trigger isn't waiting for approval", true, true)
}
func (m *Module) pauseTrigger(ctx context.Context, in *triggerInput) (*httpapi.Reply[triggerView], error) {
return m.moveTrigger(ctx, in.ID, func(t store.Trigger) bool { return t.Approved && t.Enabled }, "only an armed trigger can be paused", true, false)
}
// resumeTrigger returns a paused trigger to waiting for approval, so a person
// approves it again before it fires.
func (m *Module) resumeTrigger(ctx context.Context, in *triggerInput) (*httpapi.Reply[triggerView], error) {
return m.moveTrigger(ctx, in.ID, func(t store.Trigger) bool { return t.Approved && !t.Enabled }, "only a paused trigger can be resumed", false, true)
}
// deleteTrigger removes a trigger. It cascades to nothing: the runs it already
// started continue, and the dispatch records that link them to their events
// still name the trigger. Its name is free for a new trigger.
func (m *Module) deleteTrigger(ctx context.Context, in *triggerInput) (*struct{}, error) {
t, err := m.visibleTrigger(ctx, in.ID)
if err != nil {
return nil, err
}
err = m.store.DeleteTrigger(ctx, m.orgID, t.ID)
switch {
case errors.Is(err, store.ErrNotFound):
return nil, huma.Error404NotFound("no such trigger")
case err != nil:
return nil, huma.Error500InternalServerError("couldn't delete the trigger", err)
}
return nil, nil
}
type triggerDispatchesInput struct {
ID string `path:"id" format:"uuid"`
Limit int `query:"limit" minimum:"1" maximum:"200" default:"50"`
}
func (m *Module) triggerDispatches(ctx context.Context, in *triggerDispatchesInput) (*httpapi.Reply[[]dispatchView], error) {
t, err := m.visibleTrigger(ctx, in.ID)
if err != nil {
return nil, err
}
rows, err := m.store.DispatchesOf(ctx, m.orgID, t.ID, in.Limit)
if err != nil {
return nil, huma.Error500InternalServerError("couldn't list the runs of the trigger", err)
}
out := make([]dispatchView, 0, len(rows))
for _, r := range rows {
out = append(out, dispatchView{EventID: r.EventID, RunID: runIDOf(r.RunID), Outcome: r.Outcome, Reason: r.Reason, TriggerID: t.ID, Trigger: t.Name, CreatedAt: r.CreatedAt})
}
return httpapi.OK(out), nil
}