package proposals import ( "context" "encoding/json/jsontext" json "encoding/json/v2" "errors" "fmt" "regexp" "slices" "strings" "github.com/google/uuid" "github.com/samcharles93/archie-core/modules/events" "github.com/samcharles93/archie-core/modules/judgement" "github.com/samcharles93/archie-core/modules/proposals/internal/store" "github.com/samcharles93/archie-core/modules/runs" ) // replayable limits dry runs and the events a published trigger runs for to // the group's most recently received events. const replayable = 50 // triggerChange is the change of a trigger proposal: the trigger, the workflow // it starts and the policy added with them, for the group of unmatched events // that prompted it. type triggerChange struct { GroupID uuid.UUID `json:"group_id"` Name string `json:"name"` SourceID uuid.UUID `json:"source_id"` // SourceLabel is the source's label when the proposal was made, kept for // display after the source is renamed. SourceLabel string `json:"source_label,omitempty"` EventType string `json:"event_type"` Filter map[string]string `json:"filter"` // Workflow is the workflow document the trigger starts. Workflow string `json:"workflow"` PolicyKind string `json:"policy_kind"` // Policy is Cedar policy text added to the set in force when the proposal is // approved. Policy string `json:"policy"` DryRunID *uuid.UUID `json:"dry_run_id"` DryEventID *uuid.UUID `json:"dry_event_id"` // InstalledVersion is the workflow version installed when the proposal was // approved. InstalledVersion *int `json:"installed_version"` } func readTrigger(p store.Proposal) (triggerChange, error) { var c triggerChange if err := json.Unmarshal(p.Change, &c); err != nil { return triggerChange{}, fmt.Errorf("read the trigger of proposal %s: %w", p.ID, err) } return c, nil } var ( policyID = regexp.MustCompile(`@id\("([^"]+)"\)`) nameChars = regexp.MustCompile(`[^a-z0-9]+`) validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`) policyKinds = map[string]string{judgement.KindHardRules: "hard rule", judgement.KindChangeRequest: "change request rule"} ) // summarize describes in plain language what approving the trigger proposal // does. func (c triggerChange) summarize() string { var b strings.Builder source := c.SourceLabel if source == "" { source = c.SourceID.String() } fmt.Fprintf(&b, "When %s sends %s", source, c.EventType) if len(c.Filter) > 0 { pairs := make([]string, 0, len(c.Filter)) for k, v := range c.Filter { pairs = append(pairs, k+"="+v) } slices.Sort(pairs) b.WriteString(" matching " + strings.Join(pairs, ", ")) } fmt.Fprintf(&b, ", Archie runs %q.", c.Name) doc, err := runs.ParseDocument(c.Workflow) if err != nil { b.WriteString(" The workflow is not valid.") } for _, line := range doc.Describe() { b.WriteString(" " + line + ".") } if strings.TrimSpace(c.Policy) != "" { ids := policyID.FindAllStringSubmatch(c.Policy, -1) names := make([]string, 0, len(ids)) for _, id := range ids { names = append(names, id[1]) } fmt.Fprintf(&b, " It adds %s policies", policyKinds[c.PolicyKind]) if len(names) > 0 { b.WriteString(": " + strings.Join(names, ", ")) } b.WriteString(".") } return b.String() } // needs is who must approve the proposal: a policy change needs a person with // authority over policies, and anything else needs the owner. func (c triggerChange) needs() string { if strings.TrimSpace(c.Policy) != "" { return NeedsAuthority } return NeedsOwner } // defaultName uses part of the group ID to distinguish groups with the same // source and event type. func defaultName(g events.Group) string { slug := strings.Trim(nameChars.ReplaceAllString(strings.ToLower(g.Source+"-"+g.EventType), "-"), "-") if len(slug) > 50 { slug = strings.Trim(slug[:50], "-") } return slug + "-" + g.ID.String()[:6] } // check validates the parts of a trigger proposal an approval installs. func (m *Module) check(ctx context.Context, name, document, policyKind, policy string) error { if !validName.MatchString(name) { return &runs.InvalidError{Problems: []runs.Problem{{Path: "name", Message: "lowercase letters, digits and hyphens, starting with a letter"}}} } return m.checkWorkflowPolicy(ctx, document, policyKind, policy) } func (m *Module) checkWorkflowPolicy(ctx context.Context, document, policyKind, policy string) error { if _, err := runs.ParseDocument(document); err != nil { return err } return m.checkPolicy(ctx, policyKind, policy) } func (m *Module) checkPolicy(ctx context.Context, policyKind, policy string) error { if _, ok := policyKinds[policyKind]; !ok { return &runs.InvalidError{Problems: []runs.Problem{{Path: "policy_kind", Message: "hard_rules or change_request"}}} } if strings.TrimSpace(policy) == "" { return nil } return m.policies.Check(ctx, policyKind, policy) } // proposeTrigger proposes the trigger and workflow for a group of unmatched // events. A group that already has a live proposal returns it, so edits are // not replaced with the default investigation workflow. func (m *Module) proposeTrigger(ctx context.Context, g events.Group) (store.Proposal, error) { existing, err := m.store.ByGroup(ctx, m.orgID, g.ID) if err == nil { return existing, nil } if !errors.Is(err, store.ErrNotFound) { return store.Proposal{}, err } stored, err := m.groups.GroupEvents(ctx, g.ID, replayable) if err != nil { return store.Proposal{}, fmt.Errorf("read the group's events: %w", err) } change := triggerChange{ GroupID: g.ID, Name: defaultName(g), SourceID: g.SourceID, SourceLabel: g.Source, EventType: g.EventType, Filter: g.Filter, Workflow: runs.InvestigateDocument(), PolicyKind: judgement.KindHardRules, } raw, err := json.Marshal(change) if err != nil { return store.Proposal{}, fmt.Errorf("encode the trigger: %w", err) } evidence := map[string]any{"group": map[string]any{ "source_id": g.SourceID, "event_type": g.EventType, "filter": g.Filter, "count": g.Count, "first_seen": g.FirstSeen, "last_seen": g.LastSeen, }} prompted := make([]uuid.UUID, 0, len(stored)) for _, e := range stored { prompted = append(prompted, e.ID) } if len(stored) > 0 { evidence["sample"] = stored[0].Input } evidenceRaw, err := json.Marshal(evidence) if err != nil { return store.Proposal{}, fmt.Errorf("encode the evidence: %w", err) } promptedRaw, err := json.Marshal(prompted) if err != nil { return store.Proposal{}, fmt.Errorf("encode the prompting events: %w", err) } p := store.Proposal{ ID: uuid.New(), OrgID: m.orgID, Kind: KindTrigger, Needs: change.needs(), Title: "Handle " + g.EventType + " from " + g.Source, Summary: change.summarize(), Evidence: evidenceRaw, Change: raw, TargetKind: "event_group", TargetID: g.ID.String(), PromptedBy: promptedRaw, ProposedByID: callerID(ctx), } created, err := m.store.Create(ctx, p, nil) if err != nil { return store.Proposal{}, err } if !created { return m.store.ByGroup(ctx, m.orgID, g.ID) } return m.store.ByID(ctx, m.orgID, p.ID) } // edit changes a pending trigger proposal's name, workflow and policy, and // clears its dry run because that run no longer represents the proposal. func (m *Module) edit(ctx context.Context, p store.Proposal, name, workflow, policyKind, policy string) error { c, err := readTrigger(p) if err != nil { return err } c.Name, c.Workflow, c.PolicyKind, c.Policy = name, workflow, policyKind, policy patch := map[string]any{ "name": name, "workflow": workflow, "policy_kind": policyKind, "policy": policy, "dry_run_id": nil, "dry_event_id": nil, } if err := m.store.Patch(ctx, m.orgID, p.ID, patch, c.needs()); err != nil { return err } return m.store.Retitle(ctx, m.orgID, p.ID, p.Title, c.summarize()) } // pick expects events in newest-first order so a missing ID selects the newest. func pick(stored []events.Stored, id uuid.UUID) (events.Stored, bool) { for _, e := range stored { if id == uuid.Nil || e.ID == id { return e, true } } return events.Stored{}, false } // dryRun tests a trigger proposal's workflow and policy against a stored event // of its group. A zero eventID replays the most recently received event. func (m *Module) dryRun(ctx context.Context, p store.Proposal, eventID uuid.UUID) error { c, err := readTrigger(p) if err != nil { return err } if err := m.check(ctx, c.Name, c.Workflow, c.PolicyKind, c.Policy); err != nil { return err } stored, err := m.groups.GroupEvents(ctx, c.GroupID, replayable) if err != nil { return fmt.Errorf("read the group's events: %w", err) } event, found := pick(stored, eventID) if !found { return errNoEvent } runID, err := m.workflows.StartDry(ctx, runs.DryRequest{ OrgID: m.orgID, Name: c.Name, Document: c.Workflow, PolicyKind: c.PolicyKind, Policy: c.Policy, Input: event.Input, }) if err != nil { return fmt.Errorf("start the dry run: %w", err) } if err := m.groups.Replayed(ctx, event.ID, c.Name, runID); err != nil { return fmt.Errorf("record the replay: %w", err) } return m.store.Patch(ctx, m.orgID, p.ID, map[string]any{"dry_run_id": runID, "dry_event_id": event.ID}, c.needs()) } var errNoEvent = errors.New("the group has no stored event to replay") // publishTrigger installs the policy and workflow before saving the trigger so // the trigger cannot fire before both are available, then runs the trigger for // the events that prompted it. Every step is idempotent, so a retry after a // crash repeats none of the effects. func (m *Module) publishTrigger(ctx context.Context, p store.Proposal) error { c, err := readTrigger(p) if err != nil { return err } by := p.AnsweredByID.String if strings.TrimSpace(c.Policy) != "" { if _, err := m.policies.Append(ctx, c.PolicyKind, c.Policy, by); err != nil { return fmt.Errorf("add the policy: %w", err) } } workflow, version, err := m.workflows.Install(ctx, m.orgID, c.Name, c.Workflow, by) if err != nil { return fmt.Errorf("install the workflow: %w", err) } if err := m.store.PatchApproved(ctx, m.orgID, p.ID, map[string]any{"installed_version": version}); err != nil { return err } if err := m.groups.SaveTrigger(ctx, events.TriggerSpec{ Name: c.Name, SourceID: c.SourceID, EventType: c.EventType, Filter: c.Filter, WorkflowID: workflow, }); err != nil { return fmt.Errorf("save the trigger: %w", err) } return m.runPrompting(ctx, p, c, workflow) } // runPrompting starts the new trigger's workflow for each stored event that // prompted the proposal, keyed so a retry starts none twice. func (m *Module) runPrompting(ctx context.Context, p store.Proposal, c triggerChange, workflow uuid.UUID) error { var prompted []uuid.UUID if err := json.Unmarshal(p.PromptedBy, &prompted); err != nil { return fmt.Errorf("read the prompting events: %w", err) } if len(prompted) == 0 { return nil } stored, err := m.groups.GroupEvents(ctx, c.GroupID, replayable) if err != nil { return fmt.Errorf("read the group's events: %w", err) } ctx = workloadContext(ctx) for _, e := range stored { if !slices.Contains(prompted, e.ID) { continue } runID, err := m.workflows.Start(ctx, runs.StartRequest{ OrgID: m.orgID, WorkflowID: workflow, Key: "proposal:" + p.ID.String() + ":" + e.ID.String(), Input: e.Input, }) switch { case err == nil: case unavailable(err): return fmt.Errorf("start the workflow for event %s: %w", e.ID, err) default: m.log.WarnContext(ctx, "the published trigger could not run for an event that prompted it", "proposal", p.ID, "event", e.ID, "error", err) continue } if err := m.groups.Replayed(ctx, e.ID, c.Name, runID); err != nil { return fmt.Errorf("record the run for event %s: %w", e.ID, err) } } return nil } // evidenceOf encodes v as proposal evidence. func evidenceOf(v any) (jsontext.Value, error) { raw, err := json.Marshal(v) if err != nil { return nil, fmt.Errorf("encode the evidence: %w", err) } return raw, nil }