diff --git a/deployments/archie/compose.yml b/deployments/archie/compose.yml index 2be697b3e..e479f8eec 100644 --- a/deployments/archie/compose.yml +++ b/deployments/archie/compose.yml @@ -26,6 +26,7 @@ services: volumes: - ./bin/archie:/archie/archie:ro - ./config.toml:/archie/config.toml:ro + - ./extensions:/archie/extensions:ro ports: - "${ARCHIE_BIND:?}:8080" networks: [internal] diff --git a/deployments/archie/deploy.sh b/deployments/archie/deploy.sh index 86806b1a6..5706f56d9 100755 --- a/deployments/archie/deploy.sh +++ b/deployments/archie/deploy.sh @@ -14,7 +14,7 @@ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -C "$repo" -trimpath \ -ldflags "-X github.com/samcharles93/archie-core/internal/buildinfo.Version=$version" \ -o "$here/.build/archie" ./cmd/archie -ssh "$target" "mkdir -p $dir/bin $dir/initdb" +ssh "$target" "mkdir -p $dir/bin $dir/initdb $dir/extensions" scp -q "$here/compose.yml" "$target:$dir/compose.yml" scp -q "$here/initdb/01-roles.sh" "$target:$dir/initdb/01-roles.sh" scp -q "$here/.build/archie" "$target:$dir/bin/archie.new" @@ -41,6 +41,15 @@ owner_url = "postgres://archie_owner:${ARCHIE_OWNER_PASSWORD}@archie-db:5432/arc CONFIG chown 65532:65532 config.toml fi +# The admin token guards /api/. Only its hash goes in the config, as a +# top-level key, so it must come before the [database] table. +if ! grep -q '^admin_token_sha256' config.toml; then + umask 077 + openssl rand -hex 32 | tr -d '\n' > admin-token + hash=$(sha256sum admin-token | cut -d' ' -f1) + sed -i "1i admin_token_sha256 = \"$hash\"" config.toml + chown 65532:65532 config.toml +fi docker compose up -d --remove-orphans docker compose restart archie REMOTE diff --git a/internal/app/archie/config.go b/internal/app/archie/config.go index ccaa6825b..cf2dd2ff3 100644 --- a/internal/app/archie/config.go +++ b/internal/app/archie/config.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "path/filepath" + "regexp" "github.com/BurntSushi/toml" ) @@ -14,6 +15,9 @@ import ( type Config struct { Listen string `toml:"listen"` Database DatabaseConfig `toml:"database"` + // AdminTokenSHA256 is the hex SHA-256 of the bootstrap admin token that + // guards /api/ until identities exist. The token itself is never stored. + AdminTokenSHA256 string `toml:"admin_token_sha256"` } // DatabaseConfig holds the two connection URLs. The owner runs migrations at @@ -23,6 +27,8 @@ type DatabaseConfig struct { OwnerURL string `toml:"owner_url"` } +var adminHash = regexp.MustCompile(`^[0-9a-f]{64}$`) + // DefaultConfigPath is ${XDG_CONFIG_HOME:-~/.config}/archie/config.toml. func DefaultConfigPath() string { dir, err := os.UserConfigDir() @@ -57,6 +63,9 @@ func (c Config) validate() error { if c.Database.OwnerURL == "" { errs = append(errs, errors.New("database.owner_url is required")) } + if !adminHash.MatchString(c.AdminTokenSHA256) { + errs = append(errs, errors.New("admin_token_sha256 must be a hex SHA-256")) + } if c.Database.URL != "" && c.Database.URL == c.Database.OwnerURL { errs = append(errs, errors.New("database.url and database.owner_url must name different roles")) } diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index 537beced8..2864a78d8 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -12,11 +12,15 @@ import ( "net/http" "os" "strconv" + "sync" "time" "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/platform/health" + "github.com/samcharles93/archie-core/internal/platform/httpjson" "github.com/samcharles93/archie-core/internal/platform/pg" + "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/events" "github.com/samcharles93/archie-core/modules/runs" ) @@ -42,26 +46,40 @@ func Run(ctx context.Context, configPath string) error { checks := health.NewRegistry() checks.Register("database", db.PingContext) - - engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()}) - ctx, stop := context.WithCancel(ctx) - defer stop() - working := make(chan struct{}) - go func() { - defer close(working) - engine.Work(ctx) - }() - + guard := func(h http.Handler) http.Handler { return httpjson.Admin(cfg.AdminTokenSHA256, h) } mux := http.NewServeMux() checks.Routes(mux) + + engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()}) + + conns := connectors.NewModule(db, log.With("module", "connectors"), orgID) + defer conns.Close() + if err := conns.Start(ctx); err != nil { + return err + } + checks.Register("connectors", conns.Ready) + conns.Routes(mux, guard) + + hear := events.NewModule(db, log.With("module", "events"), orgID, conns, engine) + hear.Routes(mux, guard) + + ctx, stop := context.WithCancel(ctx) + defer stop() + var workers sync.WaitGroup + workers.Go(func() { engine.Work(ctx) }) + workers.Go(func() { hear.Work(ctx) }) + err = serve(ctx, log, cfg.Listen, mux) stop() - <-working + workers.Wait() return err } +// orgID is the one organisation until hosting is multi-tenant. +const orgID = "default" + // schemas are the module schemas the runtime role is granted DML on. -var schemas = []string{"runs"} +var schemas = []string{"runs", "connectors", "events"} // owner names this process in run leases. func owner() string { diff --git a/internal/platform/httpjson/httpjson.go b/internal/platform/httpjson/httpjson.go new file mode 100644 index 000000000..f634ccd4d --- /dev/null +++ b/internal/platform/httpjson/httpjson.go @@ -0,0 +1,86 @@ +// Package httpjson reads and writes the JSON bodies of the binary's HTTP API, +// and guards the admin routes with the bootstrap admin token. +package httpjson + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" +) + +// maxBody bounds a request body the API reads. +const maxBody = 1 << 20 + +// Write encodes v as the response body with status. +func Write(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +// Error writes {"error": msg} with status. +func Error(w http.ResponseWriter, status int, msg string) { + Write(w, status, map[string]string{"error": msg}) +} + +// Read decodes a bounded request body into v, refusing unknown fields. +func Read(r *http.Request, v any) error { + dec := json.NewDecoder(io.LimitReader(r.Body, maxBody)) + dec.DisallowUnknownFields() + if err := dec.Decode(v); err != nil { + return fmt.Errorf("read request body: %w", err) + } + return nil +} + +// Body reads a bounded raw request body. +func Body(r *http.Request) ([]byte, error) { + body, err := io.ReadAll(io.LimitReader(r.Body, maxBody+1)) + if err != nil { + return nil, fmt.Errorf("read request body: %w", err) + } + if len(body) > maxBody { + return nil, errors.New("request body too large") + } + return body, nil +} + +// Bearer returns the request's bearer token, or "". +func Bearer(r *http.Request) string { + token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if !ok { + return "" + } + return strings.TrimSpace(token) +} + +// TokenHash is the hex SHA-256 of a token, the only form tokens are stored in. +func TokenHash(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +// TokenMatches compares a presented token with a stored hash in constant time. +func TokenMatches(token, hash string) bool { + if token == "" || hash == "" { + return false + } + return subtle.ConstantTimeCompare([]byte(TokenHash(token)), []byte(hash)) == 1 +} + +// Admin guards next with the bootstrap admin token, held only as its hash. +func Admin(hash string, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !TokenMatches(Bearer(r), hash) { + Error(w, http.StatusUnauthorized, "admin token required") + return + } + next.ServeHTTP(w, r) + }) +} diff --git a/internal/platform/httpjson/httpjson_test.go b/internal/platform/httpjson/httpjson_test.go new file mode 100644 index 000000000..67bc8b45a --- /dev/null +++ b/internal/platform/httpjson/httpjson_test.go @@ -0,0 +1,40 @@ +package httpjson + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +// TestAdminGuardsWithTheTokenHash guards the bootstrap admin boundary: only a +// bearer token whose hash matches the configured one reaches the handler, and +// an empty configured hash locks everyone out rather than letting everyone in. +func TestAdminGuardsWithTheTokenHash(t *testing.T) { + const token = "a-plainly-fake-admin-token" //nolint:gosec // test fixture, not a credential + tests := []struct { + name string + hash string + header string + want int + }{ + {name: "matching token", hash: TokenHash(token), header: "Bearer " + token, want: http.StatusOK}, + {name: "wrong token", hash: TokenHash(token), header: "Bearer other", want: http.StatusUnauthorized}, + {name: "no token", hash: TokenHash(token), header: "", want: http.StatusUnauthorized}, + {name: "not a bearer token", hash: TokenHash(token), header: "Basic " + token, want: http.StatusUnauthorized}, + {name: "no configured hash locks everyone out", hash: "", header: "Bearer ", want: http.StatusUnauthorized}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + h := Admin(tt.hash, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/events", nil) + if tt.header != "" { + req.Header.Set("Authorization", tt.header) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != tt.want { + t.Fatalf("status = %d, want %d", rec.Code, tt.want) + } + }) + } +} diff --git a/internal/platform/pg/migrations/00002_connectors_events.sql b/internal/platform/pg/migrations/00002_connectors_events.sql new file mode 100644 index 000000000..986b09dc6 --- /dev/null +++ b/internal/platform/pg/migrations/00002_connectors_events.sql @@ -0,0 +1,70 @@ +-- +goose Up +CREATE SCHEMA connectors; + +CREATE TABLE connectors.accepted ( + org_id text NOT NULL, + name text NOT NULL, + path text NOT NULL, + sha256 text NOT NULL, + egress jsonb NOT NULL DEFAULT '[]', + env jsonb NOT NULL DEFAULT '[]', + settings jsonb NOT NULL DEFAULT '{}', + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (org_id, name) +); + +CREATE SCHEMA events; + +CREATE TABLE events.sources ( + org_id text NOT NULL, + name text NOT NULL, + connector text NOT NULL, + token_sha256 text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (org_id, name) +); + +CREATE TABLE events.events ( + id uuid PRIMARY KEY, + org_id text NOT NULL, + source text NOT NULL, + type text NOT NULL, + source_event_id text NOT NULL, + link_key text, + linked_to uuid REFERENCES events.events (id), + fields jsonb NOT NULL, + occurred_at timestamptz, + received_at timestamptz NOT NULL DEFAULT now(), + dispatched_at timestamptz, + matched boolean NOT NULL DEFAULT false, + -- Dedupe is this constraint: a re-delivery conflicts instead of racing. + UNIQUE (org_id, source, source_event_id) +); + +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 TABLE events.triggers ( + org_id text NOT NULL, + name text NOT NULL, + source text NOT NULL, + event_type text NOT NULL, + filter jsonb NOT NULL DEFAULT '{}', + workflow text NOT NULL, + enabled boolean NOT NULL DEFAULT true, + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (org_id, name) +); + +CREATE TABLE events.dispatches ( + event_id uuid NOT NULL REFERENCES events.events (id), + trigger text NOT NULL, + run_id uuid NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (event_id, trigger) +); + +-- +goose Down +DROP SCHEMA events CASCADE; +DROP SCHEMA connectors CASCADE; diff --git a/modules/connectors/internal/store/store.go b/modules/connectors/internal/store/store.go new file mode 100644 index 000000000..2c02b5b02 --- /dev/null +++ b/modules/connectors/internal/store/store.go @@ -0,0 +1,86 @@ +// Package store holds the connectors module's SQL: the accepted connector +// specs the host starts at boot. +package store + +import ( + "context" + "database/sql/driver" + "encoding/json" + "errors" + "fmt" + + "github.com/jmoiron/sqlx" +) + +// Accepted is one connector an operator accepted, with the authority it +// declared. +type Accepted struct { + OrgID string `db:"org_id"` + Name string `db:"name"` + Path string `db:"path"` + SHA256 string `db:"sha256"` + Egress Strings `db:"egress"` + Env Strings `db:"env"` + Settings json.RawMessage `db:"settings"` +} + +// Store is the connectors module's Postgres store. +type Store struct { + db *sqlx.DB +} + +// New returns a store on db. +func New(db *sqlx.DB) *Store { return &Store{db: db} } + +// List returns an organisation's accepted connectors. +func (s *Store) List(ctx context.Context, orgID string) ([]Accepted, error) { + var out []Accepted + if err := s.db.SelectContext(ctx, &out, ` + SELECT org_id, name, path, sha256, egress, env, settings + FROM connectors.accepted WHERE org_id = $1 ORDER BY name`, orgID); err != nil { + return nil, fmt.Errorf("list connectors: %w", err) + } + return out, nil +} + +// Upsert records an accepted connector, replacing an earlier acceptance. +func (s *Store) Upsert(ctx context.Context, a Accepted) error { + if _, err := s.db.NamedExecContext(ctx, ` + INSERT INTO connectors.accepted (org_id, name, path, sha256, egress, env, settings) + VALUES (:org_id, :name, :path, :sha256, :egress, :env, :settings) + ON CONFLICT (org_id, name) DO UPDATE + SET path = EXCLUDED.path, sha256 = EXCLUDED.sha256, egress = EXCLUDED.egress, + env = EXCLUDED.env, settings = EXCLUDED.settings, updated_at = now()`, a); err != nil { + return fmt.Errorf("accept connector: %w", err) + } + return nil +} + +// Strings is a string list stored as a JSON array. Value has a value receiver +// so database/sql finds it on a struct field; Scan needs a pointer. +type Strings []string //nolint:recvcheck // database/sql's Valuer and Scanner idiom + +// Value encodes the list as JSON. +func (s Strings) Value() (driver.Value, error) { + if s == nil { + return []byte("[]"), nil + } + return json.Marshal([]string(s)) +} + +// Scan decodes a JSON array. +func (s *Strings) Scan(src any) error { + var raw []byte + switch v := src.(type) { + case []byte: + raw = v + case string: + raw = []byte(v) + case nil: + *s = nil + return nil + default: + return errors.New("strings: unsupported column type") + } + return json.Unmarshal(raw, (*[]string)(s)) +} diff --git a/modules/connectors/module.go b/modules/connectors/module.go new file mode 100644 index 000000000..b0e259225 --- /dev/null +++ b/modules/connectors/module.go @@ -0,0 +1,164 @@ +package connectors + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "regexp" + "sort" + "strings" + "sync" + + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/modules/connectors/internal/store" +) + +// validName is the shape of a connector name: it appears in logs and URLs. +var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`) + +// Module runs an organisation's accepted connectors and serves their +// administration. +type Module struct { + orgID string + host *Host + store *store.Store + log *slog.Logger + + mu sync.RWMutex + running map[string]*Connector + failed map[string]string +} + +// NewModule returns the connectors module for orgID. +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module { + return &Module{ + orgID: orgID, host: NewHost(log), store: store.New(db), log: log, + running: map[string]*Connector{}, failed: map[string]string{}, + } +} + +// Start launches every accepted connector. A connector that fails to start is +// reported by Ready and logged; the others still run. +func (m *Module) Start(ctx context.Context) error { + accepted, err := m.store.List(ctx, m.orgID) + if err != nil { + return err + } + for _, a := range accepted { + // A failure is recorded for Ready and logged; the rest still start. + _ = m.launch(ctx, a) + } + return nil +} + +// Get returns the running connector named name. +func (m *Module) Get(name string) (*Connector, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + c, ok := m.running[name] + return c, ok +} + +// Ready reports connectors that failed to start or whose process has exited. +func (m *Module) Ready(context.Context) error { + m.mu.RLock() + defer m.mu.RUnlock() + var problems []string + for name, reason := range m.failed { + problems = append(problems, name+": "+reason) + } + for name := range m.running { + if !m.host.Alive(name) { + problems = append(problems, name+": process exited") + } + } + if len(problems) == 0 { + return nil + } + sort.Strings(problems) + return errors.New(strings.Join(problems, "; ")) +} + +// Close stops every connector. +func (m *Module) Close() { m.host.Close() } + +// Routes adds the admin routes, each wrapped in guard. +func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) { + mux.Handle("PUT /api/connectors/{name}", guard(http.HandlerFunc(m.accept))) +} + +type acceptRequest struct { + Path string `json:"path"` + SHA256 string `json:"sha256"` + Egress []string `json:"egress"` + Env []string `json:"env"` + Settings map[string]string `json:"settings"` +} + +func (m *Module) accept(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + var req acceptRequest + if err := httpjson.Read(r, &req); err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + if !validName.MatchString(name) || req.Path == "" || req.SHA256 == "" { + httpjson.Error(w, http.StatusBadRequest, "a connector needs a lowercase name, a path and a sha256") + return + } + settings, err := json.Marshal(req.Settings) + if err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + a := store.Accepted{ + OrgID: m.orgID, Name: name, Path: req.Path, SHA256: req.SHA256, + Egress: req.Egress, Env: req.Env, Settings: settings, + } + if err := m.store.Upsert(r.Context(), a); err != nil { + httpjson.Error(w, http.StatusInternalServerError, err.Error()) + return + } + if err := m.launch(context.WithoutCancel(r.Context()), a); err != nil { + httpjson.Error(w, http.StatusUnprocessableEntity, err.Error()) + return + } + httpjson.Write(w, http.StatusOK, map[string]string{"name": name, "state": "running"}) +} + +// launch starts or restarts one accepted connector and records the outcome. +func (m *Module) launch(ctx context.Context, a store.Accepted) error { + var settings map[string]string + if len(a.Settings) > 0 { + if err := json.Unmarshal(a.Settings, &settings); err != nil { + return m.fail(ctx, a.Name, fmt.Errorf("settings: %w", err)) + } + } + c, err := m.host.Start(ctx, Spec{ + Name: a.Name, Path: a.Path, SHA256: a.SHA256, + Env: a.Env, Egress: a.Egress, Settings: settings, + }) + if err != nil { + return m.fail(ctx, a.Name, err) + } + m.mu.Lock() + m.running[a.Name] = c + delete(m.failed, a.Name) + m.mu.Unlock() + m.log.InfoContext(ctx, "connector started", "connector", a.Name) + return nil +} + +func (m *Module) fail(ctx context.Context, name string, err error) error { + m.mu.Lock() + delete(m.running, name) + m.failed[name] = err.Error() + m.mu.Unlock() + m.log.ErrorContext(ctx, "connector failed to start", "connector", name, "error", err) + return err +} diff --git a/modules/events/events.go b/modules/events/events.go new file mode 100644 index 000000000..a844c0287 --- /dev/null +++ b/modules/events/events.go @@ -0,0 +1,271 @@ +// Package events is how Archie hears: sources deliver payloads, a connector +// turns each verified payload into typed events, and every event is stored +// before it is acknowledged. A dispatcher then claims each new event, links a +// resolve to what it resolves, and starts a run for every trigger it matches. +package events + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "regexp" + "strconv" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/internal/platform/httpjson" + "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/events/internal/match" + "github.com/samcharles93/archie-core/modules/events/internal/store" + "github.com/samcharles93/archie-core/modules/runs" +) + +var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`) + +// Connectors finds the running connector a source reads with. +type Connectors interface { + Get(name string) (*connectors.Connector, bool) +} + +// Runs starts runs for matched triggers. +type Runs interface { + Start(ctx context.Context, req runs.StartRequest) (uuid.UUID, error) +} + +// Module hears events for one organisation. +type Module struct { + orgID string + store *store.Store + connectors Connectors + runs Runs + log *slog.Logger + poll time.Duration +} + +// NewModule returns the events module for orgID. +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, c Connectors, r Runs) *Module { + return &Module{orgID: orgID, store: store.New(db), connectors: c, runs: r, log: log, poll: time.Second} +} + +// Routes adds the webhook intake and the guarded admin routes. +func (m *Module) Routes(mux *http.ServeMux, guard func(http.Handler) http.Handler) { + mux.HandleFunc("POST /hooks/{source}", m.intake) + mux.Handle("PUT /api/sources/{name}", guard(http.HandlerFunc(m.putSource))) + mux.Handle("PUT /api/triggers/{name}", guard(http.HandlerFunc(m.putTrigger))) + mux.Handle("GET /api/events", guard(http.HandlerFunc(m.recent))) +} + +// intake verifies the source's token before reading the body, has the +// source's connector parse it, and stores each event before answering. A +// re-delivered event is a constraint conflict, counted as a duplicate. +func (m *Module) intake(w http.ResponseWriter, r *http.Request) { + src, err := m.store.Source(r.Context(), m.orgID, r.PathValue("source")) + if errors.Is(err, store.ErrNotFound) || (err == nil && !httpjson.TokenMatches(httpjson.Bearer(r), src.TokenSHA256)) { + // Unknown source and wrong token answer alike, so neither is probed. + httpjson.Error(w, http.StatusUnauthorized, "unknown source or wrong token") + return + } + if err != nil { + httpjson.Error(w, http.StatusServiceUnavailable, "events store unavailable") + return + } + conn, ok := m.connectors.Get(src.Connector) + if !ok { + httpjson.Error(w, http.StatusServiceUnavailable, "connector "+src.Connector+" isn't running") + return + } + body, err := httpjson.Body(r) + if err != nil { + httpjson.Error(w, http.StatusRequestEntityTooLarge, err.Error()) + return + } + parsed, err := conn.Parse(r.Context(), body, map[string]string{"Content-Type": r.Header.Get("Content-Type")}) + if err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + stored, duplicates, err := m.save(r.Context(), src.Name, parsed) + if err != nil { + httpjson.Error(w, http.StatusServiceUnavailable, err.Error()) + return + } + httpjson.Write(w, http.StatusAccepted, map[string]int{"stored": stored, "duplicates": duplicates}) +} + +func (m *Module) save(ctx context.Context, source string, parsed []connectors.Event) (stored, duplicates int, err error) { + for _, e := range parsed { + row := store.Event{ + ID: uuid.New(), OrgID: m.orgID, Source: source, Type: e.Type, SourceEventID: e.SourceEventID, + Fields: e.Fields, + } + row.LinkKey.String, row.LinkKey.Valid = e.LinkKey, e.LinkKey != "" + row.OccurredAt.Time, row.OccurredAt.Valid = e.OccurredAt, !e.OccurredAt.IsZero() + isNew, err := m.store.Insert(ctx, row) + if err != nil { + return stored, duplicates, err + } + if isNew { + stored++ + } else { + duplicates++ + } + } + return stored, duplicates, nil +} + +// Work dispatches stored events until ctx ends. +func (m *Module) Work(ctx context.Context) { + for ctx.Err() == nil { + found, err := m.store.Dispatch(ctx, m.dispatch) + if err != nil { + m.log.ErrorContext(ctx, "dispatch event", "error", err) + } + if found && err == nil { + continue + } + select { + case <-ctx.Done(): + case <-time.After(m.poll): + } + } +} + +// dispatch links a resolve to the event it resolves and starts no work for +// it. Any other event starts one run per matching trigger, keyed so a retried +// dispatch never starts a second run. +func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) { + ctx := context.Background() + linked, err := store.Link(ctx, tx, e) + if err != nil || linked { + return false, err + } + triggers, err := store.Triggers(ctx, tx, e.OrgID, e.Source, e.Type) + if err != nil { + return false, err + } + matched := false + for _, t := range triggers { + var filter map[string]string + if err := json.Unmarshal(t.Filter, &filter); err != nil { + return false, fmt.Errorf("trigger %q filter: %w", t.Name, err) + } + if !match.Fields(e.Fields, filter) { + continue + } + runID, err := m.runs.Start(ctx, runs.StartRequest{ + OrgID: e.OrgID, Workflow: t.Workflow, Key: e.ID.String() + ":" + t.Name, Input: runInput(e), + }) + if err != nil { + return false, fmt.Errorf("start run for trigger %q: %w", t.Name, err) + } + if err := store.RecordDispatch(ctx, tx, e.ID, t.Name, runID); err != nil { + return false, err + } + m.log.InfoContext(ctx, "trigger started run", "event", e.ID, "trigger", t.Name, "run", runID) + matched = true + } + return matched, nil +} + +func runInput(e store.Event) json.RawMessage { + input, err := json.Marshal(map[string]any{"event": map[string]any{ + "id": e.ID, "source": e.Source, "type": e.Type, "fields": e.Fields, "occurred_at": e.OccurredAt.Time, + }}) + if err != nil { + return json.RawMessage("null") + } + return input +} + +type sourceRequest struct { + Connector string `json:"connector"` +} + +// putSource creates a source or rotates its token. The token is returned once +// and stored only as its hash. +func (m *Module) putSource(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + var req sourceRequest + if err := httpjson.Read(r, &req); err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + if !validName.MatchString(name) || !validName.MatchString(req.Connector) { + httpjson.Error(w, http.StatusBadRequest, "a source needs a lowercase name and a connector") + return + } + token, err := newToken() + if err != nil { + httpjson.Error(w, http.StatusInternalServerError, err.Error()) + return + } + if err := m.store.UpsertSource(r.Context(), store.Source{ + OrgID: m.orgID, Name: name, Connector: req.Connector, TokenSHA256: httpjson.TokenHash(token), + }); err != nil { + httpjson.Error(w, http.StatusInternalServerError, err.Error()) + return + } + httpjson.Write(w, http.StatusOK, map[string]string{"source": name, "token": token, "url": "/hooks/" + name}) +} + +type triggerRequest struct { + Source string `json:"source"` + EventType string `json:"event_type"` + Filter map[string]string `json:"filter"` + Workflow string `json:"workflow"` + Disabled bool `json:"disabled"` +} + +func (m *Module) putTrigger(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + var req triggerRequest + if err := httpjson.Read(r, &req); err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + if !validName.MatchString(name) || req.Source == "" || req.EventType == "" || req.Workflow == "" { + httpjson.Error(w, http.StatusBadRequest, "a trigger needs a lowercase name, a source, an event type and a workflow") + return + } + filter, err := json.Marshal(req.Filter) + if err != nil { + httpjson.Error(w, http.StatusBadRequest, err.Error()) + return + } + if err := m.store.UpsertTrigger(r.Context(), store.Trigger{ + OrgID: m.orgID, Name: name, Source: req.Source, EventType: req.EventType, + Filter: filter, Workflow: req.Workflow, Enabled: !req.Disabled, + }); err != nil { + httpjson.Error(w, http.StatusInternalServerError, err.Error()) + return + } + httpjson.Write(w, http.StatusOK, map[string]string{"trigger": name}) +} + +func (m *Module) recent(w http.ResponseWriter, r *http.Request) { + limit := 50 + if n, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && n > 0 && n <= 500 { + limit = n + } + events, err := m.store.Recent(r.Context(), m.orgID, limit) + if err != nil { + httpjson.Error(w, http.StatusInternalServerError, err.Error()) + return + } + httpjson.Write(w, http.StatusOK, events) +} + +func newToken() (string, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", fmt.Errorf("generate token: %w", err) + } + return hex.EncodeToString(b), nil +} diff --git a/modules/events/internal/match/match.go b/modules/events/internal/match/match.go new file mode 100644 index 000000000..27a1941d4 --- /dev/null +++ b/modules/events/internal/match/match.go @@ -0,0 +1,46 @@ +// Package match decides whether an event's fields satisfy a trigger's filter. +package match + +import ( + "encoding/json" + "fmt" + "strings" +) + +// Fields reports whether every filter entry equals the event field at its +// dotted path ("labels.alertname"). An empty filter matches every event. +func Fields(fields json.RawMessage, filter map[string]string) bool { + if len(filter) == 0 { + return true + } + var doc any + if err := json.Unmarshal(fields, &doc); err != nil { + return false + } + for path, want := range filter { + got, ok := lookup(doc, strings.Split(path, ".")) + if !ok || got != want { + return false + } + } + return true +} + +func lookup(doc any, path []string) (string, bool) { + for _, key := range path { + obj, ok := doc.(map[string]any) + if !ok { + return "", false + } + if doc, ok = obj[key]; !ok { + return "", false + } + } + switch v := doc.(type) { + case string: + return v, true + case float64, bool: + return fmt.Sprint(v), true + } + return "", false +} diff --git a/modules/events/internal/store/store.go b/modules/events/internal/store/store.go new file mode 100644 index 000000000..7c5f73d60 --- /dev/null +++ b/modules/events/internal/store/store.go @@ -0,0 +1,212 @@ +// Package store holds the events module's SQL: sources, the events table that +// is Archie's one stream, triggers and the record of which run each trigger +// started. +package store + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" +) + +// ErrNotFound means the named row doesn't exist. +var ErrNotFound = errors.New("not found") + +// Source is a named place events come from, read by one connector. +type Source struct { + OrgID string `db:"org_id"` + Name string `db:"name"` + Connector string `db:"connector"` + TokenSHA256 string `db:"token_sha256"` +} + +// Event is one stored event. +type Event struct { + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + Source string `db:"source"` + Type string `db:"type"` + SourceEventID string `db:"source_event_id"` + LinkKey sql.NullString `db:"link_key"` + LinkedTo *uuid.UUID `db:"linked_to"` + Fields json.RawMessage `db:"fields"` + OccurredAt sql.NullTime `db:"occurred_at"` + ReceivedAt time.Time `db:"received_at"` + Matched bool `db:"matched"` + DispatchedAt sql.NullTime `db:"dispatched_at"` +} + +// Trigger starts a workflow for events of one type from one source whose +// fields match its filter. +type Trigger struct { + OrgID string `db:"org_id"` + Name string `db:"name"` + Source string `db:"source"` + EventType string `db:"event_type"` + Filter json.RawMessage `db:"filter"` + Workflow string `db:"workflow"` + Enabled bool `db:"enabled"` +} + +// Store is the events module's Postgres store. +type Store struct { + db *sqlx.DB +} + +// New returns a store on db. +func New(db *sqlx.DB) *Store { return &Store{db: db} } + +// Source returns the named source. +func (s *Store) Source(ctx context.Context, orgID, name string) (Source, error) { + var src Source + err := s.db.GetContext(ctx, &src, ` + SELECT org_id, name, connector, token_sha256 FROM events.sources + WHERE org_id = $1 AND name = $2`, orgID, name) + if errors.Is(err, sql.ErrNoRows) { + return Source{}, ErrNotFound + } + if err != nil { + return Source{}, fmt.Errorf("read source: %w", err) + } + return src, nil +} + +// UpsertSource creates a source or replaces its connector and token. +func (s *Store) UpsertSource(ctx context.Context, src Source) error { + if _, err := s.db.NamedExecContext(ctx, ` + INSERT INTO events.sources (org_id, name, connector, token_sha256) + VALUES (:org_id, :name, :connector, :token_sha256) + ON CONFLICT (org_id, name) DO UPDATE + SET connector = EXCLUDED.connector, token_sha256 = EXCLUDED.token_sha256, updated_at = now()`, src); err != nil { + return fmt.Errorf("save source: %w", err) + } + return nil +} + +// Insert stores an event unless its source already delivered the same source +// event id. It reports whether the event was new. +func (s *Store) Insert(ctx context.Context, e Event) (bool, error) { + res, err := s.db.NamedExecContext(ctx, ` + INSERT INTO events.events (id, org_id, source, type, source_event_id, link_key, fields, occurred_at) + VALUES (:id, :org_id, :source, :type, :source_event_id, :link_key, :fields, :occurred_at) + ON CONFLICT (org_id, source, source_event_id) DO NOTHING`, e) + if err != nil { + return false, fmt.Errorf("store event: %w", err) + } + n, err := res.RowsAffected() + if err != nil { + return false, fmt.Errorf("store event: %w", err) + } + return n == 1, nil +} + +// Dispatch claims the oldest undispatched event and hands it to fn inside one +// transaction. fn's matched result and the dispatched mark commit together, +// so an event is dispatched once even with several workers. It reports +// whether there was an event to dispatch. +func (s *Store) Dispatch(ctx context.Context, fn func(tx *sqlx.Tx, e Event) (matched bool, err error)) (bool, error) { + tx, err := s.db.BeginTxx(ctx, nil) + if err != nil { + return false, fmt.Errorf("begin dispatch: %w", err) + } + defer func() { _ = tx.Rollback() }() + var e Event + err = tx.GetContext(ctx, &e, ` + SELECT id, org_id, source, type, source_event_id, link_key, linked_to, fields, occurred_at, + received_at, matched, dispatched_at + FROM events.events WHERE dispatched_at IS NULL + ORDER BY received_at FOR UPDATE SKIP LOCKED LIMIT 1`) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("claim event: %w", err) + } + matched, err := fn(tx, e) + if err != nil { + return true, err + } + if _, err := tx.ExecContext(ctx, ` + UPDATE events.events SET dispatched_at = now(), matched = $2 WHERE id = $1`, e.ID, matched); err != nil { + return true, fmt.Errorf("mark dispatched: %w", err) + } + if err := tx.Commit(); err != nil { + return true, fmt.Errorf("commit dispatch: %w", err) + } + return true, nil +} + +// Link points e at the earliest event its source delivered before it with the +// same link key, and reports whether it found one. Only an earlier event +// counts: a firing alert must not link to the resolve that follows it. +func Link(ctx context.Context, tx *sqlx.Tx, e Event) (bool, error) { + if !e.LinkKey.Valid { + return false, nil + } + const earlier = `org_id = $2 AND source = $3 AND link_key = $4 AND id <> $1 + AND (received_at, id) < ($5, $1)` + res, err := tx.ExecContext(ctx, ` + UPDATE events.events SET linked_to = ( + SELECT id FROM events.events WHERE `+earlier+` + ORDER BY received_at, id LIMIT 1) + WHERE id = $1 AND EXISTS (SELECT 1 FROM events.events WHERE `+earlier+`)`, + e.ID, e.OrgID, e.Source, e.LinkKey.String, e.ReceivedAt) + if err != nil { + return false, fmt.Errorf("link event: %w", err) + } + n, err := res.RowsAffected() + return n == 1, err +} + +// Triggers returns the enabled triggers for one source and event type. +func Triggers(ctx context.Context, tx *sqlx.Tx, orgID, source, eventType string) ([]Trigger, error) { + var out []Trigger + if err := tx.SelectContext(ctx, &out, ` + SELECT org_id, name, source, event_type, filter, workflow, enabled FROM events.triggers + WHERE org_id = $1 AND source = $2 AND event_type = $3 AND enabled ORDER BY name`, + orgID, source, eventType); err != nil { + return nil, fmt.Errorf("read triggers: %w", err) + } + return out, nil +} + +// RecordDispatch notes that trigger started run for an event. +func RecordDispatch(ctx context.Context, tx *sqlx.Tx, eventID uuid.UUID, trigger string, runID uuid.UUID) error { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO events.dispatches (event_id, trigger, run_id) VALUES ($1, $2, $3) + ON CONFLICT (event_id, trigger) DO NOTHING`, eventID, trigger, runID); err != nil { + return fmt.Errorf("record dispatch: %w", err) + } + return nil +} + +// UpsertTrigger creates or replaces a trigger. +func (s *Store) UpsertTrigger(ctx context.Context, t Trigger) error { + if _, err := s.db.NamedExecContext(ctx, ` + INSERT INTO events.triggers (org_id, name, source, event_type, filter, workflow, enabled) + VALUES (:org_id, :name, :source, :event_type, :filter, :workflow, :enabled) + ON CONFLICT (org_id, name) DO UPDATE + SET source = EXCLUDED.source, event_type = EXCLUDED.event_type, filter = EXCLUDED.filter, + workflow = EXCLUDED.workflow, enabled = EXCLUDED.enabled, updated_at = now()`, t); err != nil { + return fmt.Errorf("save trigger: %w", err) + } + return nil +} + +// Recent returns an organisation's newest events. +func (s *Store) Recent(ctx context.Context, orgID string, limit int) ([]Event, error) { + var out []Event + if err := s.db.SelectContext(ctx, &out, ` + SELECT id, org_id, source, type, source_event_id, link_key, linked_to, fields, occurred_at, + received_at, matched, dispatched_at + FROM events.events WHERE org_id = $1 ORDER BY received_at DESC LIMIT $2`, orgID, limit); err != nil { + return nil, fmt.Errorf("list events: %w", err) + } + return out, nil +}