diff --git a/api/openapi.yaml b/api/openapi.yaml index 27566cae8..1c4b00f62 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -107,6 +107,12 @@ components: - decision_id - requested_at type: object + ApproveInputBody: + additionalProperties: false + properties: + assertion: + $ref: "#/components/schemas/ApprovalsAssertion" + type: object AuditjsonPayload: additionalProperties: false properties: @@ -1172,10 +1178,11 @@ components: rule: $ref: "#/components/schemas/EventtypeRule" description: The conditions that identify the type; inferred from the example when absent - source: + source_id: + format: uuid type: string required: - - source + - source_id - name type: object CreateInstallationInputBody: @@ -1198,6 +1205,48 @@ components: - package - scope type: object + CreateSourceInputBody: + additionalProperties: false + properties: + connector: + description: The connector that parses this source's events + type: string + hmac_header: + description: The header that carries the signature (hmac only) + type: string + hmac_prefix: + description: Text before the hex digest in the signature header, such as sha256= (hmac only) + examples: + - sha256= + type: string + hmac_secret: + description: "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: string + label: + description: The name people see, unique among the sources of the same owner + maxLength: 100 + minLength: 1 + type: string + scope: + description: "Who owns the source: the organisation (default) or the caller, who alone can see and use it" + enum: + - org + - person + type: string + verification: + description: "How deliveries are verified: a bearer token, an HMAC-SHA256 signature of the body, or no verification" + enum: + - token + - hmac + - none + type: string + webhook_path: + description: Lowercase letters, digits and hyphens; the webhook URL ends in it. Defaults to the label + type: string + required: + - label + - connector + type: object CreateTokenInputBody: additionalProperties: false properties: @@ -1310,57 +1359,6 @@ components: required: - disabled type: object - DraftsTrigger: - additionalProperties: false - properties: - event_type: - type: string - filter: {} - source: - type: string - required: - - source - - event_type - - filter - type: object - DraftsView: - additionalProperties: false - properties: - dry_event_id: - type: string - dry_run: - $ref: "#/components/schemas/RunsDryReport" - group_id: - type: string - id: - type: string - name: - type: string - policy: - type: string - policy_kind: - type: string - published_at: - format: date-time - type: - - string - - "null" - summary: - type: string - trigger: - $ref: "#/components/schemas/DraftsTrigger" - workflow: - type: string - required: - - id - - group_id - - name - - trigger - - workflow - - policy_kind - - policy - - summary - type: object DryRunInputBody: additionalProperties: false properties: @@ -1374,7 +1372,7 @@ components: name: type: string policy: - description: Cedar policy text added when the draft is published + description: Cedar policy text added when the proposal is approved type: string policy_kind: enum: @@ -1460,6 +1458,9 @@ components: remote_addr: type: string source: + description: The source's label + type: string + source_id: type: string verification: enum: @@ -1471,7 +1472,6 @@ components: required: - id - received_at - - source - headers - body - verification @@ -1543,9 +1543,13 @@ components: type: string type: object source: + description: The source's label + type: string + source_id: type: string required: - id + - source_id - source - name - rule @@ -1594,13 +1598,14 @@ components: type: string source: type: string + source_id: + type: string type: type: string verification: type: string required: - id - - source - type - fields - received_at @@ -1655,7 +1660,9 @@ components: - "null" name: type: string - source_hint: + source_id: + description: The source the mapping was made for, a hint only + format: uuid type: string required: - name @@ -1686,7 +1693,8 @@ components: type: integer name: type: string - source_hint: + source_id: + description: The source the mapping was made for, a hint only type: string updated_at: format: date-time @@ -1694,7 +1702,6 @@ components: required: - id - name - - source_hint - event_type_id - fields - match_count @@ -1724,10 +1731,14 @@ components: type: string filter: {} source: + description: The source's label + type: string + source_id: type: string workflow: type: string required: + - source_id - source - event_type - filter @@ -1744,11 +1755,11 @@ components: EventsSourceCreated: additionalProperties: false properties: + id: + type: string secret: description: A signing secret generated for an HMAC source, returned once type: string - source: - type: string token: description: Returned once for a token source; only its hash is stored type: string @@ -1756,9 +1767,36 @@ components: description: Where the sender posts its events type: string required: - - source + - id - url type: object + EventsSourceSettings: + additionalProperties: false + properties: + connector: + description: The connector that parses this source's events + type: string + hmac_header: + description: The header that carries the signature (hmac only) + type: string + hmac_prefix: + description: Text before the hex digest in the signature header, such as sha256= (hmac only) + examples: + - sha256= + type: string + hmac_secret: + description: "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: string + verification: + description: "How deliveries are verified: a bearer token, an HMAC-SHA256 signature of the body, or no verification" + enum: + - token + - hmac + - none + type: string + required: + - connector + type: object EventsSourceView: additionalProperties: false properties: @@ -1768,21 +1806,26 @@ components: type: string delivery_header: type: string - display_name: - type: string hmac_header: type: string hmac_prefix: type: string hmac_secret_set: type: boolean + id: + type: string key_fields: items: type: string type: - array - "null" - name: + label: + type: string + scope: + enum: + - org + - person type: string secret: type: string @@ -1797,8 +1840,13 @@ components: type: boolean verification: type: string + webhook_path: + type: string required: - - name + - id + - scope + - label + - webhook_path - connector - key_fields - token_set @@ -1855,6 +1903,8 @@ components: type: string source: type: string + source_id: + type: string status: enum: - pending_approval @@ -1867,7 +1917,6 @@ components: type: string required: - name - - source - event_type - filter - workflow @@ -1919,10 +1968,10 @@ components: additionalProperties: type: string type: object - source: + source_id: type: string required: - - source + - source_id - key - schema - headers @@ -2754,6 +2803,18 @@ components: required: - workspaces type: object + Item: + additionalProperties: false + properties: + action: + type: string + connector: + type: string + input: {} + required: + - connector + - action + type: object JudgementAction: additionalProperties: false properties: @@ -3391,6 +3452,221 @@ components: - capture_id - fields type: object + ProposalsActionView: + additionalProperties: false + properties: + action: + type: string + connector: + type: string + decision_id: + type: string + input: {} + level: + type: string + outcome: + type: string + reason: + type: string + refused_by: + type: string + seq: + format: int64 + type: integer + settled_at: + format: date-time + type: + - string + - "null" + state: + enum: + - pending + - ran + - failed + - unknown + - refused + - skipped + type: string + target_id: + type: string + target_kind: + type: string + verdicts: + items: + $ref: "#/components/schemas/JudgementVerdict" + type: + - array + - "null" + required: + - seq + - connector + - action + - target_kind + - target_id + - input + - decision_id + - state + type: object + ProposalsTrigger: + additionalProperties: false + properties: + dry_event_id: + type: string + dry_run: + $ref: "#/components/schemas/RunsDryReport" + event_type: + type: string + filter: {} + group_id: + type: string + installed_version: + format: int64 + type: + - integer + - "null" + name: + type: string + policy: + type: string + policy_kind: + enum: + - hard_rules + - change_request + type: string + source_id: + type: string + workflow: + type: string + required: + - group_id + - name + - source_id + - event_type + - filter + - workflow + - policy_kind + - policy + type: object + ProposalsView: + additionalProperties: false + properties: + actions: + items: + $ref: "#/components/schemas/ProposalsActionView" + type: + - array + - "null" + answer_reason: + type: string + answered_at: + format: date-time + type: + - string + - "null" + answered_by_id: + type: string + change: {} + created_at: + format: date-time + type: string + evidence: {} + id: + type: string + kind: + enum: + - root_cause_fix + - trigger + - workflow_change + - ceiling_raise + - policy_change + type: string + needs: + enum: + - owner + - authority + type: string + prompted_by: + items: + type: string + type: + - array + - "null" + proposed_by_id: + type: string + published_at: + format: date-time + type: + - string + - "null" + run_id: + type: string + state: + enum: + - pending + - approved + - rejected + - published + - superseded + - withdrawn + type: string + summary: + type: string + target_id: + type: string + target_kind: + type: string + title: + type: string + trigger: + $ref: "#/components/schemas/ProposalsTrigger" + required: + - id + - kind + - state + - needs + - title + - summary + - evidence + - target_kind + - actions + - prompted_by + - proposed_by_id + - created_at + type: object + ProposeInputBody: + additionalProperties: false + properties: + actions: + description: The actions to take once approved, judged now and shown with the proposal + items: + $ref: "#/components/schemas/Item" + type: + - array + - "null" + change: + description: "What approving writes: {cause} for a root-cause fix, {name, workflow} for a workflow change, {policy_kind, policy} for a policy change" + evidence: {} + kind: + enum: + - root_cause_fix + - workflow_change + - policy_change + type: string + summary: + type: string + target_id: + type: string + target_kind: + type: string + title: + type: string + required: + - kind + - title + - summary + - change + - target_kind + type: object PutDraftInputBody: additionalProperties: false properties: @@ -3417,33 +3693,6 @@ components: - array - "null" type: object - PutSourceInputBody: - additionalProperties: false - properties: - connector: - description: The connector that parses this source's events - type: string - hmac_header: - description: The header that carries the signature (hmac only) - type: string - hmac_prefix: - description: Text before the hex digest in the signature header, such as sha256= (hmac only) - examples: - - sha256= - type: string - hmac_secret: - description: "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: string - verification: - description: "How deliveries are verified: a bearer token, an HMAC-SHA256 signature of the body, or no verification" - enum: - - token - - hmac - - none - type: string - required: - - connector - type: object PutTriggerInputBody: additionalProperties: false properties: @@ -3473,8 +3722,9 @@ components: pending: description: Save the trigger waiting for approval; it fires once a person approves it type: boolean - source: - description: The source whose events fire it; fixed when every is set + source_id: + description: The source whose events fire it; none when every is set + format: uuid type: string workflow: description: The workflow each match runs @@ -3518,6 +3768,15 @@ components: required: - code type: object + RejectInputBody: + additionalProperties: false + properties: + reason: + description: Why the proposal is turned down; it is kept with the proposal + type: string + required: + - reason + type: object RenameInputBody: additionalProperties: false properties: @@ -3741,12 +4000,15 @@ components: type: string source: type: string + source_id: + type: string trigger: type: string type: type: string required: - event_id + - source_id - source - type - fields @@ -4259,14 +4521,16 @@ components: required: - signed type: object - SourceNameInputBody: + SourceLabelInputBody: additionalProperties: false properties: - name: + label: + description: The name people see, unique among the sources of the same owner maxLength: 100 + minLength: 1 type: string required: - - name + - label type: object SystemAdminToken: additionalProperties: false @@ -4443,6 +4707,15 @@ components: - completion_tokens - total_tokens type: object + WebhookPathInputBody: + additionalProperties: false + properties: + path: + description: Lowercase letters, digits and hyphens; the webhook URL ends in it. Senders must post to the new address. + type: string + required: + - path + type: object securitySchemes: bearer: description: A personal API token, or the bootstrap admin token @@ -5894,143 +6167,6 @@ paths: summary: Store a credential sealed at a scope and restart what uses it tags: - Credentials - /api/drafts: - get: - operationId: list-drafts - responses: - "200": - content: - application/json: - schema: - items: - $ref: "#/components/schemas/DraftsView" - type: - - array - - "null" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: List drafts - tags: - - Drafts - /api/drafts/{id}: - get: - operationId: get-draft - parameters: - - in: path - name: id - required: true - schema: - format: uuid - type: string - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/DraftsView" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Get a draft - tags: - - Drafts - put: - operationId: edit-draft - parameters: - - in: path - name: id - required: true - schema: - format: uuid - type: string - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/EditInputBody" - required: true - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/DraftsView" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Change a draft's name, workflow and policy - tags: - - Drafts - /api/drafts/{id}/dry-run: - post: - operationId: dry-run-draft - parameters: - - in: path - name: id - required: true - schema: - format: uuid - type: string - requestBody: - content: - application/json: - schema: - $ref: "#/components/schemas/DryRunInputBody" - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/DraftsView" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Replay a stored event against the draft workflow and policy in a dry run - tags: - - Drafts - /api/drafts/{id}/publish: - post: - operationId: publish-draft - parameters: - - in: path - name: id - required: true - schema: - format: uuid - type: string - responses: - "200": - content: - application/json: - schema: - $ref: "#/components/schemas/DraftsView" - description: OK - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Install the draft's workflow, policy and trigger - tags: - - Drafts /api/event-types: get: operationId: list-event-types @@ -6142,8 +6278,9 @@ paths: type: integer - explode: false in: query - name: source + name: source_id schema: + format: uuid type: string - explode: false in: query @@ -6589,9 +6726,9 @@ paths: summary: List groups of unmatched events tags: - Events - /api/groups/{id}/draft: + /api/groups/{id}/proposal: post: - operationId: draft-group + operationId: propose-for-group parameters: - in: path name: id @@ -6604,7 +6741,7 @@ paths: content: application/json: schema: - $ref: "#/components/schemas/DraftsView" + $ref: "#/components/schemas/ProposalsView" description: OK default: content: @@ -6612,9 +6749,9 @@ paths: schema: $ref: "#/components/schemas/ErrorModel" description: Error - summary: Draft a trigger and workflow for a group of unmatched events + summary: Propose a trigger and workflow for a group of unmatched events tags: - - Drafts + - Proposals /api/guards: get: operationId: list-guards @@ -7946,6 +8083,245 @@ paths: summary: Replace the hard rules with a new version tags: - Controls + /api/proposals: + get: + operationId: list-proposals + parameters: + - description: Only proposals in this state + explode: false + in: query + name: state + schema: + description: Only proposals in this state + enum: + - pending + - approved + - rejected + - published + - superseded + - withdrawn + type: string + responses: + "200": + content: + application/json: + schema: + items: + $ref: "#/components/schemas/ProposalsView" + type: + - array + - "null" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List proposals + tags: + - Proposals + post: + operationId: propose + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ProposeInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ProposalsView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Propose a change, judging the actions it will take + tags: + - Proposals + /api/proposals/{id}: + get: + operationId: get-proposal + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ProposalsView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Get a proposal + tags: + - Proposals + put: + operationId: edit-proposal + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/EditInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ProposalsView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Change a trigger proposal's name, workflow and policy + tags: + - Proposals + /api/proposals/{id}/approve: + post: + operationId: approve-proposal + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/ApproveInputBody" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ProposalsView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Approve a proposal and its actions as the signed-in person, which applies it + tags: + - Proposals + /api/proposals/{id}/confirmation: + post: + operationId: begin-proposal-confirmation + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ApprovalsConfirmation" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Start the passkey confirmation that approving an irreversible action needs + tags: + - Proposals + /api/proposals/{id}/dry-run: + post: + operationId: dry-run-proposal + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/DryRunInputBody" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ProposalsView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Replay a stored event against a trigger proposal's workflow and policy in a dry run + tags: + - Proposals + /api/proposals/{id}/reject: + post: + operationId: reject-proposal + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RejectInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ProposalsView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Reject a proposal and record why + tags: + - Proposals /api/runs: get: operationId: list-runs @@ -8526,42 +8902,13 @@ paths: summary: List sources tags: - Events - /api/sources/{name}: - delete: - operationId: delete-source - parameters: - - in: path - name: name - required: true - schema: - type: string - responses: - "204": - description: No Content - default: - content: - application/problem+json: - schema: - $ref: "#/components/schemas/ErrorModel" - description: Error - summary: Delete a source - tags: - - Events - put: - operationId: put-source - parameters: - - description: Lowercase letters, digits and hyphens; the webhook URL ends in it - in: path - name: name - required: true - schema: - description: Lowercase letters, digits and hyphens; the webhook URL ends in it - type: string + post: + operationId: create-source requestBody: content: application/json: schema: - $ref: "#/components/schemas/PutSourceInputBody" + $ref: "#/components/schemas/CreateSourceInputBody" required: true responses: "200": @@ -8576,17 +8923,71 @@ paths: schema: $ref: "#/components/schemas/ErrorModel" description: Error - summary: Add or update a source, its verification scheme and its token + summary: Add a source, owned by the organisation or by the caller tags: - Events - /api/sources/{name}/approve-unsigned: + /api/sources/{id}: + delete: + operationId: delete-source + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + responses: + "204": + description: No Content + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Delete a source + tags: + - Events + put: + operationId: update-source + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/EventsSourceSettings" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/EventsSourceCreated" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Change a source's connector, verification scheme and token + tags: + - Events + /api/sources/{id}/approve-unsigned: post: operationId: approve-source-unsigned parameters: - in: path - name: name + name: id required: true schema: + format: uuid type: string responses: "200": @@ -8604,14 +9005,15 @@ paths: summary: Accept deliveries that carry no signature tags: - Events - /api/sources/{name}/capture: + /api/sources/{id}/capture: put: operationId: set-source-capture parameters: - in: path - name: name + name: id required: true schema: + format: uuid type: string requestBody: content: @@ -8635,14 +9037,15 @@ paths: summary: Keep or stop keeping the headers and payloads a source receives tags: - Events - /api/sources/{name}/delivery-header: + /api/sources/{id}/delivery-header: put: operationId: set-source-delivery-header parameters: - in: path - name: name + name: id required: true schema: + format: uuid type: string requestBody: content: @@ -8666,14 +9069,15 @@ paths: summary: Name the header a sender repeats when it retries a delivery tags: - Events - /api/sources/{name}/key-fields: + /api/sources/{id}/key-fields: put: operationId: put-source-key-fields parameters: - in: path - name: name + name: id required: true schema: + format: uuid type: string requestBody: content: @@ -8697,20 +9101,21 @@ paths: summary: Set the fields a source's events are grouped by tags: - Events - /api/sources/{name}/name: + /api/sources/{id}/label: put: - operationId: set-source-name + operationId: set-source-label parameters: - in: path - name: name + name: id required: true schema: + format: uuid type: string requestBody: content: application/json: schema: - $ref: "#/components/schemas/SourceNameInputBody" + $ref: "#/components/schemas/SourceLabelInputBody" required: true responses: "200": @@ -8725,17 +9130,18 @@ paths: schema: $ref: "#/components/schemas/ErrorModel" description: Error - summary: Label a source + summary: Rename a source tags: - Events - /api/sources/{name}/secret: + /api/sources/{id}/secret: post: operationId: rotate-source-secret parameters: - in: path - name: name + name: id required: true schema: + format: uuid type: string responses: "200": @@ -8753,14 +9159,15 @@ paths: summary: Replace a signed source's secret and return it once tags: - Events - /api/sources/{name}/signing: + /api/sources/{id}/signing: post: operationId: set-source-signing parameters: - in: path - name: name + name: id required: true schema: + format: uuid type: string requestBody: content: @@ -8784,6 +9191,38 @@ paths: summary: Require an HMAC signature, or ask to take unsigned deliveries tags: - Events + /api/sources/{id}/webhook-path: + put: + operationId: set-source-webhook-path + parameters: + - in: path + name: id + required: true + schema: + format: uuid + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/WebhookPathInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/EventsSourceView" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Move the address a source receives deliveries at + tags: + - Events /api/stream: get: operationId: stream-dashboard diff --git a/internal/app/archie/api.go b/internal/app/archie/api.go index 7754473a1..a5e60af8c 100644 --- a/internal/app/archie/api.go +++ b/internal/app/archie/api.go @@ -13,11 +13,11 @@ import ( "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/dashboard" "github.com/samcharles93/archie-core/modules/deliveries" - "github.com/samcharles93/archie-core/modules/drafts" "github.com/samcharles93/archie-core/modules/events" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" "github.com/samcharles93/archie-core/modules/memory" + "github.com/samcharles93/archie-core/modules/proposals" "github.com/samcharles93/archie-core/modules/runs" "github.com/samcharles93/archie-core/modules/system" ) @@ -35,7 +35,7 @@ type apiModules struct { judge *judgement.Module engine *runs.Engine chat *chat.Module - drafts *drafts.Module + proposals *proposals.Module notes *memory.Module live *hub.Hub } @@ -54,7 +54,7 @@ func (m apiModules) register(api huma.API) { m.hear.Register(api) m.judge.Register(api) m.engine.Register(api, orgID, m.hear, m.judge, m.allow) - m.drafts.Register(api) + m.proposals.Register(api) m.chat.Register(api) // The memory routes are served once the root wires the module, which it // does after the modules that read it are built. @@ -82,7 +82,7 @@ func emptyAPI(auth httpapi.Authenticator, authz httpapi.Authorizer) (*http.Serve settings: settings, conns: &connectors.Module{}, system: &system.Module{}, tell: &deliveries.Module{}, allow: &approvals.Module{}, actionTypes: &judgement.ActionTypes{}, policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{}, - engine: &runs.Engine{}, chat: &chat.Module{}, drafts: &drafts.Module{}, + engine: &runs.Engine{}, chat: &chat.Module{}, proposals: &proposals.Module{}, notes: &memory.Module{}, live: hub.New(), }.register(api) return mux, api diff --git a/internal/app/archie/operations.go b/internal/app/archie/operations.go index a5d7eb2a6..f16514bdc 100644 --- a/internal/app/archie/operations.go +++ b/internal/app/archie/operations.go @@ -16,6 +16,7 @@ import ( "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" "github.com/samcharles93/archie-core/modules/memory" + "github.com/samcharles93/archie-core/modules/proposals" "github.com/samcharles93/archie-core/modules/runs" ) @@ -39,6 +40,7 @@ type operations struct { judge *judgement.Module allow *approvals.Module remember *memory.Module + proposed *proposals.Module // completeRecord finishes the record of a committed deletion whose entry could // not be written. completeRecord func(context.Context) (int, error) @@ -66,7 +68,7 @@ func (o *operations) Start(ctx context.Context) error { // from the request. o.engine.Use(runs.Deps{ Settings: o.settings, Toolbox: o.conns, Judge: o.judge, Approver: o.allow, - Notifier: o.tell, Messenger: o.tell, Memory: o.remember, Capabilities: o.conns, + Proposals: o.proposed, Notifier: o.tell, Messenger: o.tell, Memory: o.remember, Capabilities: o.conns, Access: checked, }) if err := installStarter(ctx, o.engine); err != nil { @@ -92,6 +94,7 @@ func (o *operations) Start(ctx context.Context) error { // each source's delivery policy from it. o.settings.UseAuthorizer(checked) o.allow.UseAuthorizer(checked) + o.proposed.UseAuthorizer(checked) o.tell.UseAccess(checked) o.hear.UseDeliveryPolicy(governance.RecordingDelivery(access, o.settings, o.log.With("module", "governance"))) o.hear.UseTrustedProxies(o.settings.TrustedProxies) @@ -99,7 +102,7 @@ func (o *operations) Start(ctx context.Context) error { People: o.settings, Access: checked, Settings: o.settings, Toolbox: o.conns, Judge: o.judge, Approver: o.allow, Memory: o.remember, Runs: o.engine, Notifier: o.tell, }) - for _, loop := range []func(context.Context){o.engine.Work, o.hear.Work, o.tell.Work, o.talk.Work, o.retryDeletionRecord} { + for _, loop := range []func(context.Context){o.engine.Work, o.hear.Work, o.tell.Work, o.proposed.Work, o.talk.Work, o.retryDeletionRecord} { o.workers.Go(func() { loop(ctx) }) } return nil @@ -144,6 +147,9 @@ func installStarter(ctx context.Context, engine *runs.Engine) error { if _, err := engine.Install(ctx, orgID, "investigate", runs.InvestigateDocument(), string(governance.SystemID)); err != nil { return fmt.Errorf("install the investigate workflow: %w", err) } + if _, err := engine.Install(ctx, orgID, runs.ProposalWorkflow, runs.ProposalDocument(), string(governance.SystemID)); err != nil { + return fmt.Errorf("install the proposal workflow: %w", err) + } return nil } diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index 4a159e4aa..3dea49eed 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -32,11 +32,11 @@ import ( "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/dashboard" "github.com/samcharles93/archie-core/modules/deliveries" - "github.com/samcharles93/archie-core/modules/drafts" "github.com/samcharles93/archie-core/modules/events" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" "github.com/samcharles93/archie-core/modules/memory" + "github.com/samcharles93/archie-core/modules/proposals" "github.com/samcharles93/archie-core/modules/runs" "github.com/samcharles93/archie-core/modules/system" "github.com/samcharles93/archie-core/ui" @@ -210,10 +210,15 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary } return nil }) + proposed := proposals.NewModule(db, log.With("module", "proposals"), orgID, hear, engine, policies, judge) + // A cause that keeps recurring becomes a root-cause proposal. + remember.UseProposals(proposed) + // Approving an action that can't be undone needs a fresh passkey assertion. + proposed.UseConfirmer(settings) sys.UseHealth(healthSources(checks, conns, engine, allow)) apiModules{ settings: settings, conns: conns, system: sys, tell: tell, allow: allow, actionTypes: actionTypes, policies: policies, - hear: hear, judge: judge, engine: engine, chat: talk, drafts: drafts.NewModule(db, log.With("module", "drafts"), orgID, hear, engine, policies), + hear: hear, judge: judge, engine: engine, chat: talk, proposals: proposed, notes: remember, live: live, }.register(api) dashboard.Routes(mux, ui.DistDirFS) @@ -223,7 +228,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary db: db, conns: conns, gate: g, served: serveSurface(checks, g), settings: settings, ops: &operations{ log: log, checks: checks, settings: settings, conns: conns, engine: engine, hear: hear, - tell: tell, talk: talk, judge: judge, allow: allow, remember: remember, + tell: tell, talk: talk, judge: judge, allow: allow, remember: remember, proposed: proposed, completeRecord: func(ctx context.Context) (int, error) { return memory.Reconcile(ctx, db, cfg.StateDir) }, @@ -273,7 +278,7 @@ func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, actio const orgID = "default" // schemas are the module schemas the runtime role is granted DML on. -var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory", "drafts", "chat"} +var schemas = []string{"runs", "connectors", "events", "governance", "deliveries", "judgement", "approvals", "memory", "alerts", "proposals", "chat"} // owner names this process in run leases. func owner() string { diff --git a/internal/platform/pg/migrations/00008_drafts.sql b/internal/platform/pg/migrations/00008_drafts.sql deleted file mode 100644 index 7893ee4c9..000000000 --- a/internal/platform/pg/migrations/00008_drafts.sql +++ /dev/null @@ -1,26 +0,0 @@ --- +goose Up -CREATE SCHEMA drafts; - -CREATE TABLE drafts.drafts ( - id uuid PRIMARY KEY, - org_id text NOT NULL, - group_id uuid NOT NULL, - name text NOT NULL, - source_id uuid NOT NULL, - event_type text NOT NULL, - filter jsonb NOT NULL, - document text NOT NULL, - policy_kind text NOT NULL CHECK (policy_kind IN ('hard_rules', 'change_request')), - policy text NOT NULL, - dry_run_id uuid, - dry_event_id uuid, - installed_version integer, - published_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - UNIQUE (org_id, group_id), - UNIQUE (org_id, name) -); - --- +goose Down -DROP SCHEMA drafts CASCADE; diff --git a/internal/platform/pg/migrations/00010_memory.sql b/internal/platform/pg/migrations/00010_memory.sql index 93771f7a7..8ebe958e2 100644 --- a/internal/platform/pg/migrations/00010_memory.sql +++ b/internal/platform/pg/migrations/00010_memory.sql @@ -19,20 +19,6 @@ CREATE TABLE memory.incidents ( ); CREATE INDEX incidents_by_target ON memory.incidents (org_id, target_kind, target_id, at DESC); --- A proposal asks for a root-cause fix when the same cause recurs on a target. --- There is at most one per target and cause. -CREATE TABLE memory.proposals ( - id uuid PRIMARY KEY, - org_id text NOT NULL, - target_kind text NOT NULL, - target_id text NOT NULL, - cause text NOT NULL, - incidents integer NOT NULL, - body text NOT NULL, - created_at timestamptz NOT NULL DEFAULT now(), - UNIQUE (org_id, target_kind, target_id, cause) -); - -- A note is one item of Archie's memory. class is its kind: working context for -- one chat session, episodic history or enterprise retrieval in a collection, -- or a durable fact. diff --git a/internal/platform/pg/migrations/00012_proposals.sql b/internal/platform/pg/migrations/00012_proposals.sql index b201a2f80..1469d80d7 100644 --- a/internal/platform/pg/migrations/00012_proposals.sql +++ b/internal/platform/pg/migrations/00012_proposals.sql @@ -8,7 +8,7 @@ CREATE SCHEMA proposals; -- change needs a person with authority, and any other change needs the owner. -- A rejection keeps its reason so the next proposal can take it into account. -- prompted_by lists the events that led to it, which a published trigger runs --- for. +-- for. run_id is the run that takes the proposal's actions once it is approved. CREATE TABLE proposals.proposals ( id uuid PRIMARY KEY, org_id text NOT NULL, @@ -24,6 +24,7 @@ CREATE TABLE proposals.proposals ( base_version integer, prompted_by uuid[] NOT NULL DEFAULT '{}', origin_run_id uuid, + run_id uuid, proposed_by_id text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), answered_by_id text, @@ -36,13 +37,30 @@ CREATE TABLE proposals.proposals ( ); CREATE INDEX proposals_by_state ON proposals.proposals (org_id, state, created_at DESC); CREATE INDEX proposals_by_target ON proposals.proposals (org_id, target_kind, target_id, created_at DESC); +CREATE INDEX proposals_unfinished ON proposals.proposals (org_id, answered_at) WHERE state = 'approved'; + +-- A recurring cause on a target has at most one open root-cause proposal. +CREATE UNIQUE INDEX proposals_one_open_root_cause ON proposals.proposals (org_id, target_kind, target_id, (change ->> 'cause')) + WHERE kind = 'root_cause_fix' AND state IN ('pending', 'approved'); + +-- A group of unmatched events has at most one live trigger proposal, and an +-- open one holds its workflow name, so two proposals never publish the same +-- workflow. +CREATE UNIQUE INDEX proposals_one_trigger_per_group ON proposals.proposals (org_id, (change ->> 'group_id')) + WHERE kind = 'trigger' AND state IN ('pending', 'approved', 'published'); +CREATE UNIQUE INDEX proposals_one_trigger_per_name ON proposals.proposals (org_id, (change ->> 'name')) + WHERE kind = 'trigger' AND state IN ('pending', 'approved'); -- The actions a proposal will take when it is approved, in order. Each is -- judged when the proposal is made and shown with it, and approving the --- proposal approves them. digest binds the approval to the exact action. +-- proposal approves them. digest binds the approval to the exact action. The +-- run that takes the actions settles each one: ran, failed, unknown (started +-- and not confirmed, never repeated), refused (judged again and no longer +-- allowed) or skipped (an earlier action did not run). CREATE TABLE proposals.actions ( proposal_id uuid NOT NULL REFERENCES proposals.proposals (id) ON DELETE CASCADE, seq integer NOT NULL, + connector text NOT NULL, installation_id uuid NOT NULL, action text NOT NULL, target_kind text NOT NULL, @@ -50,6 +68,10 @@ CREATE TABLE proposals.actions ( input jsonb NOT NULL, digest text NOT NULL, decision_id uuid NOT NULL, + state text NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'ran', 'failed', 'unknown', 'refused', 'skipped')), + outcome text NOT NULL DEFAULT '', + settled_at timestamptz, + CHECK ((state = 'pending') = (settled_at IS NULL)), PRIMARY KEY (proposal_id, seq) ); diff --git a/modules/approvals/dashboard.go b/modules/approvals/dashboard.go index 430a4d83d..540dff886 100644 --- a/modules/approvals/dashboard.go +++ b/modules/approvals/dashboard.go @@ -253,3 +253,7 @@ func (m *Module) beginConfirmation(ctx context.Context, in *confirmationInput) ( } return httpapi.OK(Confirmation{Token: ceremony.Token, Options: jsontext.Value(ceremony.Options)}), nil } + +// Irreversible reports whether approving the action needs a fresh passkey +// assertion, as a held action does. +func Irreversible(a judgement.Action) bool { return irreversible(a) } diff --git a/modules/drafts/drafts.go b/modules/drafts/drafts.go deleted file mode 100644 index f4a543fe2..000000000 --- a/modules/drafts/drafts.go +++ /dev/null @@ -1,479 +0,0 @@ -// Package drafts manages proposed triggers, workflows and policies for groups -// of unmatched events. Drafts can be tested by replaying a stored event in a -// dry run before the trigger is enabled. -package drafts - -import ( - "context" - "encoding/json/jsontext" - json "encoding/json/v2" - "errors" - "fmt" - "log/slog" - "net/http" - "regexp" - "slices" - "strings" - "time" - - "github.com/danielgtaylor/huma/v2" - "github.com/google/uuid" - "github.com/jmoiron/sqlx" - - "github.com/samcharles93/archie-core/internal/platform/httpapi" - "github.com/samcharles93/archie-core/modules/drafts/internal/store" - "github.com/samcharles93/archie-core/modules/events" - "github.com/samcharles93/archie-core/modules/governance" - "github.com/samcharles93/archie-core/modules/judgement" - "github.com/samcharles93/archie-core/modules/runs" -) - -// replayable limits dry runs to the group's most recently received events. -const replayable = 50 - -// Groups provides unmatched event groups, replay tracking and trigger storage. -type Groups interface { - Group(ctx context.Context, id uuid.UUID) (events.Group, bool, error) - GroupEvents(ctx context.Context, id uuid.UUID, limit int) ([]events.Stored, error) - Replayed(ctx context.Context, eventID uuid.UUID, trigger string, runID uuid.UUID) error - SaveTrigger(ctx context.Context, t events.TriggerSpec) error -} - -// Workflows installs workflow documents and manages dry runs. -type Workflows interface { - Install(ctx context.Context, orgID, name, body, by string) (int, error) - Has(ctx context.Context, orgID, name string) (bool, error) - StartDry(ctx context.Context, req runs.DryRequest) (uuid.UUID, error) - DryReport(ctx context.Context, orgID string, id uuid.UUID) (runs.DryReport, bool, error) -} - -// Policies validates a draft's policy against the current policy set and -// adds it when the draft is published. -type Policies interface { - Check(ctx context.Context, kind, extra string) error - Append(ctx context.Context, kind, extra, by string) (judgement.PolicySetView, error) -} - -// Module holds one organisation's drafts. -type Module struct { - orgID string - store *store.Store - groups Groups - workflows Workflows - policies Policies - log *slog.Logger -} - -// NewModule returns the drafts module for orgID. -func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, g Groups, w Workflows, p Policies) *Module { - return &Module{orgID: orgID, store: store.New(db), groups: g, workflows: w, policies: p, log: log} -} - -// Register adds the draft API. -func (m *Module) Register(api huma.API) { - tags := []string{"Drafts"} - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindDraft), huma.Operation{ - OperationID: "list-drafts", Method: http.MethodGet, Path: "/api/drafts", - Summary: "List drafts", Tags: tags, - }, m.list) - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindDraft), huma.Operation{ - OperationID: "draft-group", Method: http.MethodPost, Path: "/api/groups/{id}/draft", - Summary: "Draft a trigger and workflow for a group of unmatched events", Tags: tags, - }, m.create) - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRead, governance.KindDraft), huma.Operation{ - OperationID: "get-draft", Method: http.MethodGet, Path: "/api/drafts/{id}", - Summary: "Get a draft", Tags: tags, - }, m.get) - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindDraft), huma.Operation{ - OperationID: "edit-draft", Method: http.MethodPut, Path: "/api/drafts/{id}", - Summary: "Change a draft's name, workflow and policy", Tags: tags, - }, m.edit) - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRun, governance.KindWorkflow), huma.Operation{ - OperationID: "dry-run-draft", Method: http.MethodPost, Path: "/api/drafts/{id}/dry-run", - Summary: "Replay a stored event against the draft workflow and policy in a dry run", Tags: tags, - }, m.dryRun) - httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindWorkflow), huma.Operation{ - OperationID: "publish-draft", Method: http.MethodPost, Path: "/api/drafts/{id}/publish", - Summary: "Install the draft's workflow, policy and trigger", Tags: tags, - }, m.publish) -} - -type idInput struct { - ID string `path:"id" format:"uuid"` -} - -// View is the API representation of a draft. -type View struct { - ID uuid.UUID `json:"id"` - GroupID uuid.UUID `json:"group_id"` - Name string `json:"name"` - Trigger Trigger `json:"trigger"` - // Workflow is the workflow document the trigger would start. - Workflow string `json:"workflow"` - PolicyKind string `json:"policy_kind"` - // Policy is Cedar policy text added to the set in force when published. - Policy string `json:"policy"` - Summary string `json:"summary"` - // DryRun reports the latest dry run since the draft was last edited. - DryRun *runs.DryReport `json:"dry_run,omitzero"` - DryEventID *uuid.UUID `json:"dry_event_id,omitzero"` - PublishedAt *time.Time `json:"published_at,omitzero"` -} - -// Trigger is the trigger a draft proposes. -type Trigger struct { - SourceID uuid.UUID `json:"source_id"` - // Source is the source's label, empty when the source no longer exists. - Source string `json:"source,omitzero"` - EventType string `json:"event_type"` - Filter jsontext.Value `json:"filter"` -} - -func (m *Module) view(ctx context.Context, d store.Draft) (View, error) { - label, err := m.sourceLabel(ctx, d.GroupID) - if err != nil { - return View{}, err - } - v := View{ - ID: d.ID, GroupID: d.GroupID, Name: d.Name, - Trigger: Trigger{SourceID: d.SourceID, Source: label, EventType: d.EventType, Filter: d.Filter}, - Workflow: d.Document, PolicyKind: d.PolicyKind, Policy: d.Policy, - Summary: summarize(d, label), - } - if d.PublishedAt.Valid { - v.PublishedAt = &d.PublishedAt.Time - } - if d.DryEventID.Valid { - v.DryEventID = &d.DryEventID.UUID - } - if d.DryRunID.Valid { - rep, ok, err := m.workflows.DryReport(ctx, m.orgID, d.DryRunID.UUID) - if err != nil { - return View{}, fmt.Errorf("read dry run: %w", err) - } - if ok { - v.DryRun = &rep - } - } - return v, 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"} -) - -// sourceLabel returns the label of the source of a draft's group, or "" when -// the group went with its source. -func (m *Module) sourceLabel(ctx context.Context, groupID uuid.UUID) (string, error) { - g, found, err := m.groups.Group(ctx, groupID) - if err != nil { - return "", fmt.Errorf("read group: %w", err) - } - if !found { - return "", nil - } - return g.Source, nil -} - -func summarize(d store.Draft, source string) string { - var filter map[string]string - _ = json.Unmarshal(d.Filter, &filter) - var b strings.Builder - fmt.Fprintf(&b, "When %s sends %s", source, d.EventType) - if len(filter) > 0 { - pairs := make([]string, 0, len(filter)) - for k, v := range filter { - pairs = append(pairs, k+"="+v) - } - slices.Sort(pairs) - b.WriteString(" matching " + strings.Join(pairs, ", ")) - } - fmt.Fprintf(&b, ", Archie runs %q.", d.Name) - doc, err := runs.ParseDocument(d.Document) - if err != nil { - b.WriteString(" The workflow is not valid.") - } - for _, line := range doc.Describe() { - b.WriteString(" " + line + ".") - } - if strings.TrimSpace(d.Policy) != "" { - ids := policyID.FindAllStringSubmatch(d.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[d.PolicyKind]) - if len(names) > 0 { - b.WriteString(": " + strings.Join(names, ", ")) - } - b.WriteString(".") - } - return b.String() -} - -// 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] -} - -func (m *Module) list(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]View], error) { - rows, err := m.store.List(ctx, m.orgID) - if err != nil { - return nil, m.fail(ctx, "list drafts", err) - } - out := make([]View, 0, len(rows)) - for _, d := range rows { - v, err := m.view(ctx, d) - if err != nil { - return nil, m.fail(ctx, "read draft", err) - } - out = append(out, v) - } - return httpapi.OK(out), nil -} - -// create reuses an existing group draft rather than replacing any edits -// with the default investigation workflow. -func (m *Module) create(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) { - id, err := uuid.Parse(in.ID) - if err != nil { - return nil, huma.Error400BadRequest("ID must be a UUID") - } - g, found, err := m.groups.Group(ctx, id) - switch { - case err != nil: - return nil, m.fail(ctx, "read group", err) - case !found: - return nil, huma.Error404NotFound("no such group") - } - filter, err := json.Marshal(g.Filter) - if err != nil { - return nil, m.fail(ctx, "encode filter", err) - } - d, err := m.store.Create(ctx, store.Draft{ - ID: uuid.New(), OrgID: m.orgID, GroupID: g.ID, Name: defaultName(g), SourceID: g.SourceID, EventType: g.EventType, - Filter: filter, Document: runs.InvestigateDocument(), PolicyKind: judgement.KindHardRules, - }) - if err != nil { - return nil, m.fail(ctx, "create draft", err) - } - return m.respond(ctx, d) -} - -func (m *Module) get(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) { - d, err := m.draft(ctx, in.ID) - if err != nil { - return nil, err - } - return m.respond(ctx, d) -} - -type editInput struct { - ID string `path:"id" format:"uuid"` - Body struct { - Name string `json:"name"` - Workflow string `json:"workflow" doc:"The workflow document"` - PolicyKind string `json:"policy_kind" enum:"hard_rules,change_request"` - Policy string `json:"policy,omitzero" doc:"Cedar policy text added when the draft is published"` - } -} - -func (m *Module) edit(ctx context.Context, in *editInput) (*httpapi.Reply[View], error) { - d, err := m.draft(ctx, in.ID) - if err != nil { - return nil, err - } - if d.PublishedAt.Valid { - return nil, huma.Error409Conflict("a published draft can't be edited") - } - req := in.Body - if err := m.check(ctx, req.Name, req.Workflow, req.PolicyKind, req.Policy); err != nil { - return nil, invalid(err) - } - switch err := m.store.Edit(ctx, m.orgID, d.ID, req.Name, req.Workflow, req.PolicyKind, req.Policy); { - case errors.Is(err, store.ErrTaken): - return nil, huma.Error409Conflict("another draft has that name") - case err != nil: - return nil, m.fail(ctx, "edit draft", err) - } - d, err = m.store.ByID(ctx, m.orgID, d.ID) - if err != nil { - return nil, m.fail(ctx, "read draft", err) - } - return m.respond(ctx, d) -} - -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"}}} - } - if _, err := runs.ParseDocument(document); err != nil { - return err - } - 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) -} - -func invalid(err error) error { - var problem *runs.InvalidError - switch { - case errors.As(err, &problem): - return runs.Problems(problem) - case errors.Is(err, judgement.ErrInvalidPolicy): - return huma.Error400BadRequest(err.Error(), &huma.ErrorDetail{Location: "policy", Message: err.Error()}) - default: - return huma.Error500InternalServerError("couldn't check the draft") - } -} - -type dryRunInput struct { - ID string `path:"id" format:"uuid"` - Body *struct { - EventID uuid.UUID `json:"event_id,omitzero" doc:"The stored event to replay; the newest by default"` - } -} - -// dryRun tests the draft workflow and policy against a stored event. If the -// caller omits the event ID, it replays the most recently received event. -func (m *Module) dryRun(ctx context.Context, in *dryRunInput) (*httpapi.Reply[View], error) { - d, err := m.draft(ctx, in.ID) - if err != nil { - return nil, err - } - var eventID uuid.UUID - if in.Body != nil { - eventID = in.Body.EventID - } - if err := m.check(ctx, d.Name, d.Document, d.PolicyKind, d.Policy); err != nil { - return nil, invalid(err) - } - stored, err := m.groups.GroupEvents(ctx, d.GroupID, replayable) - if err != nil { - return nil, m.fail(ctx, "read the group's events", err) - } - event, found := pick(stored, eventID) - if !found { - return nil, huma.Error409Conflict("the group has no stored event to replay") - } - runID, err := m.workflows.StartDry(ctx, runs.DryRequest{ - OrgID: m.orgID, Workflow: d.Name, Document: d.Document, PolicyKind: d.PolicyKind, Policy: d.Policy, Input: event.Input, - }) - if err != nil { - return nil, m.fail(ctx, "start the dry run", err) - } - if err := m.groups.Replayed(ctx, event.ID, d.Name, runID); err != nil { - return nil, m.fail(ctx, "record the replay", err) - } - if err := m.store.SetDryRun(ctx, m.orgID, d.ID, runID, event.ID); err != nil { - return nil, m.fail(ctx, "record the dry run", err) - } - d, err = m.store.ByID(ctx, m.orgID, d.ID) - if err != nil { - return nil, m.fail(ctx, "read draft", err) - } - return m.respond(ctx, d) -} - -// 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 -} - -// publish installs the policy and workflow before saving the trigger so the -// trigger cannot fire before both are available. A recorded workflow version -// lets a retry skip the name-conflict check. The retry still calls the policy -// and workflow installers, which avoid duplicating unchanged content. -func (m *Module) publish(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) { - d, err := m.draft(ctx, in.ID) - if err != nil { - return nil, err - } - if err := m.check(ctx, d.Name, d.Document, d.PolicyKind, d.Policy); err != nil { - return nil, invalid(err) - } - if !d.InstalledVersion.Valid { - taken, err := m.workflows.Has(ctx, m.orgID, d.Name) - if err != nil { - return nil, m.fail(ctx, "check the workflow name", err) - } - if taken { - return nil, huma.Error409Conflict("a workflow named " + d.Name + " already exists; rename the draft") - } - } - by := governance.CallerID(ctx) - if strings.TrimSpace(d.Policy) != "" { - if _, err := m.policies.Append(ctx, d.PolicyKind, d.Policy, by); err != nil { - return nil, m.fail(ctx, "add the policy", err) - } - } - version, err := m.workflows.Install(ctx, m.orgID, d.Name, d.Document, by) - if err != nil { - return nil, m.fail(ctx, "install the workflow", err) - } - if err := m.store.MarkInstalled(ctx, m.orgID, d.ID, version); err != nil { - return nil, m.fail(ctx, "record the workflow version", err) - } - var filter map[string]string - if err := json.Unmarshal(d.Filter, &filter); err != nil { - return nil, m.fail(ctx, "read the trigger filter", err) - } - if err := m.groups.SaveTrigger(ctx, events.TriggerSpec{ - Name: d.Name, SourceID: d.SourceID, EventType: d.EventType, Filter: filter, Workflow: d.Name, - }); err != nil { - return nil, m.fail(ctx, "save the trigger", err) - } - if err := m.store.MarkPublished(ctx, m.orgID, d.ID); err != nil { - return nil, m.fail(ctx, "mark the draft published", err) - } - d, err = m.store.ByID(ctx, m.orgID, d.ID) - if err != nil { - return nil, m.fail(ctx, "read draft", err) - } - return m.respond(ctx, d) -} - -func (m *Module) draft(ctx context.Context, rawID string) (store.Draft, error) { - id, err := uuid.Parse(rawID) - if err != nil { - return store.Draft{}, huma.Error400BadRequest("ID must be a UUID") - } - d, err := m.store.ByID(ctx, m.orgID, id) - switch { - case errors.Is(err, store.ErrNotFound): - return store.Draft{}, huma.Error404NotFound("no such draft") - case err != nil: - return store.Draft{}, m.fail(ctx, "read draft", err) - } - return d, nil -} - -func (m *Module) respond(ctx context.Context, d store.Draft) (*httpapi.Reply[View], error) { - v, err := m.view(ctx, d) - if err != nil { - return nil, m.fail(ctx, "read draft", err) - } - return httpapi.OK(v), nil -} - -func (m *Module) fail(ctx context.Context, what string, err error) error { - m.log.ErrorContext(ctx, what, "error", err) - return huma.Error500InternalServerError("couldn't " + what) -} diff --git a/modules/drafts/internal/store/store.go b/modules/drafts/internal/store/store.go deleted file mode 100644 index d6bb5eb32..000000000 --- a/modules/drafts/internal/store/store.go +++ /dev/null @@ -1,154 +0,0 @@ -// Package store holds the drafts module's SQL. -package store - -import ( - "context" - "database/sql" - "encoding/json/jsontext" - "errors" - "fmt" - "time" - - "github.com/google/uuid" - "github.com/jackc/pgx/v5/pgconn" - "github.com/jmoiron/sqlx" -) - -// ErrNotFound means no such draft. -var ErrNotFound = errors.New("no such draft") - -// ErrTaken indicates that another draft already uses the name. -var ErrTaken = errors.New("name already used by another draft") - -// Draft is one stored draft. -type Draft struct { - ID uuid.UUID `db:"id"` - OrgID string `db:"org_id"` - GroupID uuid.UUID `db:"group_id"` - Name string `db:"name"` - SourceID uuid.UUID `db:"source_id"` - EventType string `db:"event_type"` - Filter jsontext.Value `db:"filter"` - Document string `db:"document"` - PolicyKind string `db:"policy_kind"` - Policy string `db:"policy"` - DryRunID uuid.NullUUID `db:"dry_run_id"` - DryEventID uuid.NullUUID `db:"dry_event_id"` - // InstalledVersion is recorded before the trigger is saved so a retry - // can distinguish an earlier installation from a workflow name conflict. - InstalledVersion sql.NullInt32 `db:"installed_version"` - PublishedAt sql.NullTime `db:"published_at"` - CreatedAt time.Time `db:"created_at"` - UpdatedAt time.Time `db:"updated_at"` -} - -const columns = `id, org_id, group_id, name, source_id, event_type, filter, document, policy_kind, policy, - dry_run_id, dry_event_id, installed_version, published_at, created_at, updated_at` - -// Store is the drafts 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} } - -// Create inserts a draft or returns the existing draft for the group. -func (s *Store) Create(ctx context.Context, d Draft) (Draft, error) { - _, err := s.db.ExecContext(ctx, ` - INSERT INTO drafts.drafts (id, org_id, group_id, name, source_id, event_type, filter, document, policy_kind, policy) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) - ON CONFLICT (org_id, group_id) DO NOTHING`, - d.ID, d.OrgID, d.GroupID, d.Name, d.SourceID, d.EventType, d.Filter, d.Document, d.PolicyKind, d.Policy) - if err != nil { - return Draft{}, fmt.Errorf("create draft: %w", err) - } - return s.ByGroup(ctx, d.OrgID, d.GroupID) -} - -// ByGroup returns a group's draft. -func (s *Store) ByGroup(ctx context.Context, orgID string, groupID uuid.UUID) (Draft, error) { - return s.one(ctx, `WHERE org_id = $1 AND group_id = $2`, orgID, groupID) -} - -// ByID returns one draft. -func (s *Store) ByID(ctx context.Context, orgID string, id uuid.UUID) (Draft, error) { - return s.one(ctx, `WHERE org_id = $1 AND id = $2`, orgID, id) -} - -func (s *Store) one(ctx context.Context, where string, args ...any) (Draft, error) { - var d Draft - err := s.db.GetContext(ctx, &d, `SELECT `+columns+` FROM drafts.drafts `+where, args...) - if errors.Is(err, sql.ErrNoRows) { - return Draft{}, ErrNotFound - } - if err != nil { - return Draft{}, fmt.Errorf("read draft: %w", err) - } - return d, nil -} - -// List returns an organisation's drafts, newest first. -func (s *Store) List(ctx context.Context, orgID string) ([]Draft, error) { - var out []Draft - if err := s.db.SelectContext(ctx, &out, ` - SELECT `+columns+` FROM drafts.drafts WHERE org_id = $1 ORDER BY created_at DESC LIMIT 200`, orgID); err != nil { - return nil, fmt.Errorf("list drafts: %w", err) - } - return out, nil -} - -// Edit updates an unpublished draft and clears its dry-run references because -// the previous run no longer represents the current draft. -func (s *Store) Edit(ctx context.Context, orgID string, id uuid.UUID, name, document, policyKind, policy string) error { - res, err := s.db.ExecContext(ctx, ` - UPDATE drafts.drafts - SET name = $3, document = $4, policy_kind = $5, policy = $6, - dry_run_id = NULL, dry_event_id = NULL, updated_at = now() - WHERE org_id = $1 AND id = $2 AND published_at IS NULL`, orgID, id, name, document, policyKind, policy) - if err != nil { - if isUnique(err) { - return ErrTaken - } - return fmt.Errorf("edit draft: %w", err) - } - if n, _ := res.RowsAffected(); n == 0 { - return ErrNotFound - } - return nil -} - -// SetDryRun records the latest dry run and the event it replayed. -func (s *Store) SetDryRun(ctx context.Context, orgID string, id, runID, eventID uuid.UUID) error { - if _, err := s.db.ExecContext(ctx, ` - UPDATE drafts.drafts SET dry_run_id = $3, dry_event_id = $4, updated_at = now() - WHERE org_id = $1 AND id = $2`, orgID, id, runID, eventID); err != nil { - return fmt.Errorf("record dry run: %w", err) - } - return nil -} - -// MarkInstalled records the workflow version installed during publication. -func (s *Store) MarkInstalled(ctx context.Context, orgID string, id uuid.UUID, version int) error { - if _, err := s.db.ExecContext(ctx, ` - UPDATE drafts.drafts SET installed_version = $3, updated_at = now() WHERE org_id = $1 AND id = $2`, - orgID, id, version); err != nil { - return fmt.Errorf("record installed version: %w", err) - } - return nil -} - -// MarkPublished records the publication time without overwriting it on retry. -func (s *Store) MarkPublished(ctx context.Context, orgID string, id uuid.UUID) error { - if _, err := s.db.ExecContext(ctx, ` - UPDATE drafts.drafts SET published_at = COALESCE(published_at, now()), updated_at = now() - WHERE org_id = $1 AND id = $2`, orgID, id); err != nil { - return fmt.Errorf("mark draft published: %w", err) - } - return nil -} - -func isUnique(err error) bool { - var pgerr *pgconn.PgError - return errors.As(err, &pgerr) && pgerr.Code == "23505" -} diff --git a/modules/governance/access.go b/modules/governance/access.go index 75130c7da..e99884e52 100644 --- a/modules/governance/access.go +++ b/modules/governance/access.go @@ -101,7 +101,7 @@ const ( KindRun ResourceKind = "run" KindApproval ResourceKind = "approval" KindActionType ResourceKind = "action_type" - KindDraft ResourceKind = "draft" + KindProposal ResourceKind = "proposal" KindDelivery ResourceKind = "delivery" KindIncident ResourceKind = "incident" KindMemory ResourceKind = "memory" diff --git a/modules/memory/internal/store/store.go b/modules/memory/internal/store/store.go index 9b7b08275..31df01be7 100644 --- a/modules/memory/internal/store/store.go +++ b/modules/memory/internal/store/store.go @@ -1,4 +1,4 @@ -// Package store persists incident history and proposals for root-cause fixes. +// Package store persists incident history. package store import ( @@ -23,16 +23,6 @@ type Incident struct { At time.Time `db:"at"` } -// Proposal is a request to fix a recurring cause on a target. -type Proposal struct { - ID uuid.UUID `db:"id"` - TargetKind string `db:"target_kind"` - TargetID string `db:"target_id"` - Cause string `db:"cause"` - Incidents int `db:"incidents"` - Body string `db:"body"` -} - // Store is the memory module's Postgres store. type Store struct { db *sqlx.DB @@ -91,18 +81,3 @@ func (s *Store) ByTarget(ctx context.Context, orgID, kind, id string, limit int) } return out, nil } - -// Propose stores one proposal per organisation, target and cause. If one -// already exists, it updates the incident count and returns the original text. -func (s *Store) Propose(ctx context.Context, orgID string, p Proposal) (Proposal, error) { - var out Proposal - if err := s.db.GetContext(ctx, &out, ` - INSERT INTO memory.proposals (id, org_id, target_kind, target_id, cause, incidents, body) - VALUES ($1, $2, $3, $4, $5, $6, $7) - ON CONFLICT (org_id, target_kind, target_id, cause) DO UPDATE SET incidents = EXCLUDED.incidents - RETURNING id, target_kind, target_id, cause, incidents, body`, - p.ID, orgID, p.TargetKind, p.TargetID, p.Cause, p.Incidents, p.Body); err != nil { - return Proposal{}, fmt.Errorf("record proposal: %w", err) - } - return out, nil -} diff --git a/modules/memory/memory.go b/modules/memory/memory.go index 320e3bfd7..96b71e80b 100644 --- a/modules/memory/memory.go +++ b/modules/memory/memory.go @@ -84,7 +84,24 @@ type ledger interface { SetActions(ctx context.Context, orgID string, runID uuid.UUID, actions []byte) error Incident(ctx context.Context, orgID string, runID uuid.UUID) (store.Incident, bool, error) ByTarget(ctx context.Context, orgID, kind, id string, limit int) ([]store.Incident, error) - Propose(ctx context.Context, orgID string, p store.Proposal) (store.Proposal, error) +} + +// FixRequest asks for a root-cause fix to a cause that keeps recurring on a +// target. +type FixRequest struct { + // RunID is the run whose incident reached the threshold. + RunID uuid.UUID + Target Target + Cause string + Incidents int + // Summary says what recurred and what was already tried. + Summary string +} + +// Proposer takes a request for a root-cause fix and keeps at most one open for +// a cause on a target. +type Proposer interface { + ProposeRootCause(ctx context.Context, req FixRequest) error } // Module manages incident history and proposals for one organisation, and the @@ -93,6 +110,7 @@ type Module struct { orgID string log *slog.Logger ledger ledger + fixes Proposer notes noteStore shared sharedStore deleted DeletionLog @@ -112,6 +130,9 @@ func NewModule(db *sqlx.DB, orgID string, log *slog.Logger, deleted DeletionLog) return &Module{orgID: orgID, log: log, ledger: s, notes: s, shared: s, deleted: deleted} } +// UseProposals sends the root-cause fixes the module requests to p. +func (m *Module) UseProposals(p Proposer) { m.fixes = p } + var unsafeCause = regexp.MustCompile(`[^a-z0-9]+`) // Cause normalises labels for comparison: "Disk pressure" and "disk-pressure" @@ -186,14 +207,17 @@ func (m *Module) Finish(ctx context.Context, runID uuid.UUID, actions []Action, if review.Repeats < threshold { return review, nil } - proposal, err := m.ledger.Propose(ctx, m.orgID, store.Proposal{ - ID: uuid.New(), TargetKind: current.TargetKind, TargetID: current.TargetID, Cause: current.Cause, - Incidents: review.Repeats, Body: proposalBody(current, same), + review.Proposal = proposalBody(current, same) + if m.fixes == nil { + return Review{}, errors.New("root-cause fixes are not wired") + } + err = m.fixes.ProposeRootCause(ctx, FixRequest{ + RunID: runID, Target: Target{Kind: current.TargetKind, ID: current.TargetID}, Cause: current.Cause, + Incidents: review.Repeats, Summary: review.Proposal, }) if err != nil { - return Review{}, err + return Review{}, fmt.Errorf("propose a root-cause fix: %w", err) } - review.Proposal = proposal.Body return review, nil } diff --git a/modules/memory/memory_test.go b/modules/memory/memory_test.go index d0284c816..b5de9f360 100644 --- a/modules/memory/memory_test.go +++ b/modules/memory/memory_test.go @@ -10,10 +10,17 @@ import ( "github.com/samcharles93/archie-core/modules/memory/internal/store" ) -// fakeLedger holds one target's incidents, newest first, and the proposals made. +// fakeLedger holds one target's incidents, newest first. type fakeLedger struct { - rows []store.Incident - proposals []store.Proposal + rows []store.Incident +} + +// fakeProposer counts the root-cause fixes requested. +type fakeProposer struct{ requests []FixRequest } + +func (f *fakeProposer) ProposeRootCause(_ context.Context, req FixRequest) error { + f.requests = append(f.requests, req) + return nil } func (f *fakeLedger) Upsert(context.Context, string, store.Incident) error { return nil } @@ -33,11 +40,6 @@ func (f *fakeLedger) ByTarget(context.Context, string, string, string, int) ([]s return f.rows, nil } -func (f *fakeLedger) Propose(_ context.Context, _ string, p store.Proposal) (store.Proposal, error) { - f.proposals = append(f.proposals, p) - return p, nil -} - // TestFinishProposesOnRecurrence checks that only incidents with the same // cause count towards the configured threshold, even if an action was denied. func TestFinishProposesOnRecurrence(t *testing.T) { @@ -65,13 +67,14 @@ func TestFinishProposesOnRecurrence(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ledger := &fakeLedger{rows: tt.rows} - m := &Module{orgID: "org", ledger: ledger} + fixes := &fakeProposer{} + m := &Module{orgID: "org", ledger: ledger, fixes: fixes} review, err := m.Finish(t.Context(), run, []Action{{Action: "restart", Target: "host:web-1", State: "denied"}}, tt.threshold) if err != nil { t.Fatal(err) } - if got := review.Proposal != ""; got != tt.want || (len(ledger.proposals) == 1) != tt.want { - t.Fatalf("proposal = %q, recorded %d; want proposal %v", review.Proposal, len(ledger.proposals), tt.want) + if got := review.Proposal != ""; got != tt.want || (len(fixes.requests) == 1) != tt.want { + t.Fatalf("proposal = %q, requested %d; want proposal %v", review.Proposal, len(fixes.requests), tt.want) } }) } diff --git a/modules/proposals/api.go b/modules/proposals/api.go new file mode 100644 index 000000000..0046eff9d --- /dev/null +++ b/modules/proposals/api.go @@ -0,0 +1,487 @@ +package proposals + +import ( + "context" + "encoding/json/jsontext" + "errors" + "net/http" + "time" + + "github.com/danielgtaylor/huma/v2" + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/modules/approvals" + "github.com/samcharles93/archie-core/modules/governance" + "github.com/samcharles93/archie-core/modules/judgement" + "github.com/samcharles93/archie-core/modules/proposals/internal/store" + "github.com/samcharles93/archie-core/modules/runs" +) + +// Register adds the proposals API. +func (m *Module) Register(api huma.API) { + tags := []string{"Proposals"} + httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindProposal), huma.Operation{ + OperationID: "list-proposals", Method: http.MethodGet, Path: "/api/proposals", + Summary: "List proposals", Tags: tags, + }, m.list) + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindProposal), huma.Operation{ + OperationID: "propose", Method: http.MethodPost, Path: "/api/proposals", + Summary: "Propose a change, judging the actions it will take", Tags: tags, + }, m.propose) + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindProposal), huma.Operation{ + OperationID: "propose-for-group", Method: http.MethodPost, Path: "/api/groups/{id}/proposal", + Summary: "Propose a trigger and workflow for a group of unmatched events", Tags: tags, + }, m.proposeForGroup) + httpapi.Register(api, httpapi.Authorized(governance.ActionRead, governance.KindProposal), huma.Operation{ + OperationID: "get-proposal", Method: http.MethodGet, Path: "/api/proposals/{id}", + Summary: "Get a proposal", Tags: tags, + }, m.getProposal) + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindProposal), huma.Operation{ + OperationID: "edit-proposal", Method: http.MethodPut, Path: "/api/proposals/{id}", + Summary: "Change a trigger proposal's name, workflow and policy", Tags: tags, + }, m.editProposal) + httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionRun, governance.KindWorkflow), huma.Operation{ + OperationID: "dry-run-proposal", Method: http.MethodPost, Path: "/api/proposals/{id}/dry-run", + Summary: "Replay a stored event against a trigger proposal's workflow and policy in a dry run", Tags: tags, + }, m.dryRunProposal) + httpapi.Register(api, httpapi.Authorized(governance.ActionApprove, governance.KindProposal), huma.Operation{ + OperationID: "approve-proposal", Method: http.MethodPost, Path: "/api/proposals/{id}/approve", + Summary: "Approve a proposal and its actions as the signed-in person, which applies it", Tags: tags, + }, m.approve) + httpapi.Register(api, httpapi.Authorized(governance.ActionApprove, governance.KindProposal), huma.Operation{ + OperationID: "begin-proposal-confirmation", Method: http.MethodPost, Path: "/api/proposals/{id}/confirmation", + Summary: "Start the passkey confirmation that approving an irreversible action needs", Tags: tags, + }, m.beginConfirmation) + httpapi.Register(api, httpapi.Authorized(governance.ActionApprove, governance.KindProposal), huma.Operation{ + OperationID: "reject-proposal", Method: http.MethodPost, Path: "/api/proposals/{id}/reject", + Summary: "Reject a proposal and record why", Tags: tags, + }, m.reject) +} + +// View is the API representation of a proposal. +type View struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind" enum:"root_cause_fix,trigger,workflow_change,ceiling_raise,policy_change"` + State string `json:"state" enum:"pending,approved,rejected,published,superseded,withdrawn"` + // Needs is who must approve: the owner, or a person with authority over + // policies. + Needs string `json:"needs" enum:"owner,authority"` + Title string `json:"title"` + Summary string `json:"summary"` + Evidence jsontext.Value `json:"evidence"` + // Change is what approving the proposal writes. A trigger proposal reports + // it as Trigger instead. + Change jsontext.Value `json:"change,omitzero"` + Trigger *Trigger `json:"trigger,omitzero"` + TargetKind string `json:"target_kind"` + TargetID string `json:"target_id,omitzero"` + // Actions are the actions the proposal takes once approved, in order, each + // with the judgement shown when it was proposed. + Actions []ActionView `json:"actions"` + PromptedBy []uuid.UUID `json:"prompted_by"` + RunID *uuid.UUID `json:"run_id,omitzero"` + ProposedByID string `json:"proposed_by_id"` + CreatedAt time.Time `json:"created_at"` + // AnsweredByID is the answering account's identity ID. + AnsweredByID string `json:"answered_by_id,omitzero"` + AnsweredAt *time.Time `json:"answered_at,omitzero"` + AnswerReason string `json:"answer_reason,omitzero"` + PublishedAt *time.Time `json:"published_at,omitzero"` +} + +// Trigger is the trigger a trigger proposal adds. +type Trigger struct { + GroupID uuid.UUID `json:"group_id"` + Name string `json:"name"` + SourceID uuid.UUID `json:"source_id"` + EventType string `json:"event_type"` + Filter jsontext.Value `json:"filter"` + // Workflow is the workflow document the trigger would start. + Workflow string `json:"workflow"` + PolicyKind string `json:"policy_kind" enum:"hard_rules,change_request"` + // Policy is Cedar policy text added to the set in force when approved. + Policy string `json:"policy"` + // DryRun reports the latest dry run since the proposal was last edited. + DryRun *runs.DryReport `json:"dry_run,omitzero"` + DryEventID *uuid.UUID `json:"dry_event_id,omitzero"` + InstalledVersion *int `json:"installed_version,omitzero"` +} + +// ActionView is a proposed action and the judgement it was shown with. +type ActionView struct { + Seq int `json:"seq"` + Connector string `json:"connector"` + Action string `json:"action"` + TargetKind string `json:"target_kind"` + TargetID string `json:"target_id"` + Input jsontext.Value `json:"input"` + DecisionID uuid.UUID `json:"decision_id"` + // Level is how far judgement lets the action run. + Level string `json:"level,omitzero"` + Reason string `json:"reason,omitzero"` + RefusedBy string `json:"refused_by,omitzero"` + Verdicts []judgement.Verdict `json:"verdicts,omitzero"` + // State is how the action ended once the proposal was approved: pending + // until its run takes it. + State string `json:"state" enum:"pending,ran,failed,unknown,refused,skipped"` + Outcome string `json:"outcome,omitzero"` + SettledAt *time.Time `json:"settled_at,omitzero"` +} + +func (m *Module) get(ctx context.Context, id uuid.UUID) (View, error) { + p, actions, decisions, err := m.load(ctx, id) + if err != nil { + return View{}, err + } + return m.view(ctx, p, actions, decisions) +} + +func (m *Module) view(ctx context.Context, p store.Proposal, actions []store.Action, decisions []judgement.Decision) (View, error) { + v := View{ + ID: p.ID, Kind: p.Kind, State: p.State, Needs: p.Needs, Title: p.Title, Summary: p.Summary, + Evidence: p.Evidence, TargetKind: p.TargetKind, TargetID: p.TargetID, PromptedBy: []uuid.UUID{}, + ProposedByID: p.ProposedByID, CreatedAt: p.CreatedAt, AnswerReason: p.AnswerReason, + Actions: make([]ActionView, 0, len(actions)), + } + if err := unmarshalIDs(p.PromptedBy, &v.PromptedBy); err != nil { + return View{}, err + } + if p.RunID.Valid { + v.RunID = &p.RunID.UUID + } + if p.AnsweredByID.Valid { + v.AnsweredByID = p.AnsweredByID.String + } + if p.AnsweredAt.Valid { + v.AnsweredAt = &p.AnsweredAt.Time + } + if p.PublishedAt.Valid { + v.PublishedAt = &p.PublishedAt.Time + } + if p.Kind == KindTrigger { + t, err := m.triggerView(ctx, p) + if err != nil { + return View{}, err + } + v.Trigger = &t + } else { + v.Change = p.Change + } + byID := make(map[uuid.UUID]judgement.Decision, len(decisions)) + for _, d := range decisions { + byID[d.ID] = d + } + for _, a := range actions { + av := ActionView{ + Seq: a.Seq, Connector: a.Connector, Action: a.Action, TargetKind: a.TargetKind, TargetID: a.TargetID, + Input: a.Input, DecisionID: a.DecisionID, State: a.State, Outcome: a.Outcome, + } + if a.SettledAt.Valid { + av.SettledAt = &a.SettledAt.Time + } + if d, ok := byID[a.DecisionID]; ok { + av.Level, av.Reason, av.RefusedBy, av.Verdicts = d.Level.String(), d.Reason, d.RefusedBy, d.Verdicts + } + v.Actions = append(v.Actions, av) + } + return v, nil +} + +func (m *Module) triggerView(ctx context.Context, p store.Proposal) (Trigger, error) { + c, err := readTrigger(p) + if err != nil { + return Trigger{}, err + } + filter, err := evidenceOf(c.Filter) + if err != nil { + return Trigger{}, err + } + t := Trigger{ + GroupID: c.GroupID, Name: c.Name, SourceID: c.SourceID, EventType: c.EventType, Filter: filter, + Workflow: c.Workflow, PolicyKind: c.PolicyKind, Policy: c.Policy, DryEventID: c.DryEventID, + InstalledVersion: c.InstalledVersion, + } + if c.DryRunID != nil { + rep, ok, err := m.workflows.DryReport(ctx, m.orgID, *c.DryRunID) + if err != nil { + return Trigger{}, errors.Join(errors.New("read dry run"), err) + } + if ok { + t.DryRun = &rep + } + } + return t, nil +} + +type idInput struct { + ID string `path:"id" format:"uuid"` +} + +type listInput struct { + State string `query:"state" enum:"pending,approved,rejected,published,superseded,withdrawn" doc:"Only proposals in this state"` +} + +func (m *Module) list(ctx context.Context, in *listInput) (*httpapi.Reply[[]View], error) { + rows, err := m.store.List(ctx, m.orgID, in.State) + if err != nil { + return nil, m.fail(ctx, "list proposals", err) + } + out := make([]View, 0, len(rows)) + for _, p := range rows { + actions, err := m.store.Actions(ctx, p.ID) + if err != nil { + return nil, m.fail(ctx, "read proposal", err) + } + v, err := m.view(ctx, p, actions, nil) + if err != nil { + return nil, m.fail(ctx, "read proposal", err) + } + out = append(out, v) + } + return httpapi.OK(out), nil +} + +type proposeInput struct { + Body struct { + Kind string `json:"kind" enum:"root_cause_fix,workflow_change,policy_change"` + Title string `json:"title"` + Summary string `json:"summary"` + Evidence jsontext.Value `json:"evidence,omitzero"` + Change jsontext.Value `json:"change" doc:"What approving writes: {cause} for a root-cause fix, {name, workflow} for a workflow change, {policy_kind, policy} for a policy change"` + TargetKind string `json:"target_kind"` + TargetID string `json:"target_id,omitzero"` + Actions []struct { + Connector string `json:"connector"` + Action string `json:"action"` + Input jsontext.Value `json:"input,omitzero"` + } `json:"actions,omitzero" doc:"The actions to take once approved, judged now and shown with the proposal"` + } +} + +func (m *Module) propose(ctx context.Context, in *proposeInput) (*httpapi.Reply[View], error) { + b := in.Body + n := NewProposal{ + Kind: b.Kind, Title: b.Title, Summary: b.Summary, Evidence: b.Evidence, Change: b.Change, + TargetKind: b.TargetKind, TargetID: b.TargetID, + } + for _, a := range b.Actions { + n.Actions = append(n.Actions, NewAction{Connector: a.Connector, Action: a.Action, Input: a.Input}) + } + v, err := m.Propose(ctx, n) + if err != nil { + return nil, m.problem(ctx, "propose", err) + } + return httpapi.OK(v), nil +} + +func (m *Module) proposeForGroup(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) { + id, err := uuid.Parse(in.ID) + if err != nil { + return nil, huma.Error400BadRequest("ID must be a UUID") + } + g, found, err := m.groups.Group(ctx, id) + switch { + case err != nil: + return nil, m.fail(ctx, "read group", err) + case !found: + return nil, huma.Error404NotFound("no such group") + } + p, err := m.proposeTrigger(ctx, g) + if err != nil { + return nil, m.problem(ctx, "propose a trigger", err) + } + return m.respond(ctx, p.ID) +} + +func (m *Module) getProposal(ctx context.Context, in *idInput) (*httpapi.Reply[View], error) { + id, err := parseID(in.ID) + if err != nil { + return nil, err + } + return m.respond(ctx, id) +} + +type editInput struct { + ID string `path:"id" format:"uuid"` + Body struct { + Name string `json:"name"` + Workflow string `json:"workflow" doc:"The workflow document"` + PolicyKind string `json:"policy_kind" enum:"hard_rules,change_request"` + Policy string `json:"policy,omitzero" doc:"Cedar policy text added when the proposal is approved"` + } +} + +func (m *Module) editProposal(ctx context.Context, in *editInput) (*httpapi.Reply[View], error) { + p, err := m.pendingTrigger(ctx, in.ID) + if err != nil { + return nil, err + } + req := in.Body + if err := m.check(ctx, req.Name, req.Workflow, req.PolicyKind, req.Policy); err != nil { + return nil, invalid(err) + } + if err := m.edit(ctx, p, req.Name, req.Workflow, req.PolicyKind, req.Policy); err != nil { + return nil, m.problem(ctx, "edit proposal", err) + } + return m.respond(ctx, p.ID) +} + +type dryRunInput struct { + ID string `path:"id" format:"uuid"` + Body *struct { + EventID uuid.UUID `json:"event_id,omitzero" doc:"The stored event to replay; the newest by default"` + } +} + +func (m *Module) dryRunProposal(ctx context.Context, in *dryRunInput) (*httpapi.Reply[View], error) { + p, err := m.pendingTrigger(ctx, in.ID) + if err != nil { + return nil, err + } + var eventID uuid.UUID + if in.Body != nil { + eventID = in.Body.EventID + } + if err := m.dryRun(ctx, p, eventID); err != nil { + return nil, m.problem(ctx, "dry run", err) + } + return m.respond(ctx, p.ID) +} + +type approveInput struct { + ID string `path:"id" format:"uuid"` + Body *struct { + // Assertion is the passkey assertion that approving an action that + // can't be undone needs. + Assertion *approvals.Assertion `json:"assertion,omitzero"` + } +} + +func (m *Module) approve(ctx context.Context, in *approveInput) (*httpapi.Reply[View], error) { + id, err := parseID(in.ID) + if err != nil { + return nil, err + } + var assertion *approvals.Assertion + if in.Body != nil { + assertion = in.Body.Assertion + } + v, err := m.Approve(ctx, id, assertion) + if err != nil { + return nil, m.problem(ctx, "approve", err) + } + return httpapi.OK(v), nil +} + +func (m *Module) beginConfirmation(ctx context.Context, in *idInput) (*httpapi.Reply[approvals.Confirmation], error) { + id, err := parseID(in.ID) + if err != nil { + return nil, err + } + ceremony, err := m.Confirmation(ctx, id) + switch { + case errors.Is(err, governance.ErrNoPasskey): + return nil, huma.Error409Conflict("Add a passkey to your account to approve this proposal.") + case err != nil: + return nil, m.problem(ctx, "start the confirmation", err) + } + return httpapi.OK(approvals.Confirmation{Token: ceremony.Token, Options: jsontext.Value(ceremony.Options)}), nil +} + +type rejectInput struct { + ID string `path:"id" format:"uuid"` + Body struct { + Reason string `json:"reason" doc:"Why the proposal is turned down; it is kept with the proposal"` + } +} + +func (m *Module) reject(ctx context.Context, in *rejectInput) (*httpapi.Reply[View], error) { + id, err := parseID(in.ID) + if err != nil { + return nil, err + } + v, err := m.Reject(ctx, id, in.Body.Reason) + if err != nil { + return nil, m.problem(ctx, "reject", err) + } + return httpapi.OK(v), nil +} + +func parseID(raw string) (uuid.UUID, error) { + id, err := uuid.Parse(raw) + if err != nil { + return uuid.Nil, huma.Error400BadRequest("ID must be a UUID") + } + return id, nil +} + +// pendingTrigger returns a trigger proposal that can still be edited. +func (m *Module) pendingTrigger(ctx context.Context, rawID string) (store.Proposal, error) { + id, err := parseID(rawID) + if err != nil { + return store.Proposal{}, err + } + p, err := m.store.ByID(ctx, m.orgID, id) + switch { + case errors.Is(err, store.ErrNotFound): + return store.Proposal{}, huma.Error404NotFound("no such proposal") + case err != nil: + return store.Proposal{}, m.fail(ctx, "read proposal", err) + case p.Kind != KindTrigger: + return store.Proposal{}, huma.Error409Conflict("only a trigger proposal has a workflow to edit or test") + case p.State != StatePending: + return store.Proposal{}, huma.Error409Conflict("a proposal that was answered can't be changed") + } + return p, nil +} + +func (m *Module) respond(ctx context.Context, id uuid.UUID) (*httpapi.Reply[View], error) { + v, err := m.get(ctx, id) + if err != nil { + return nil, m.problem(ctx, "read proposal", err) + } + return httpapi.OK(v), nil +} + +func invalid(err error) error { + var problem *runs.InvalidError + switch { + case errors.As(err, &problem): + return runs.Problems(problem) + case errors.Is(err, judgement.ErrInvalidPolicy): + return huma.Error400BadRequest(err.Error(), &huma.ErrorDetail{Location: "policy", Message: err.Error()}) + default: + return huma.Error500InternalServerError("couldn't check the proposal") + } +} + +// problem turns an error into the response for the person who caused it, and +// logs the ones that are the server's own. +func (m *Module) problem(ctx context.Context, what string, err error) error { + var invalidDoc *runs.InvalidError + switch { + case errors.Is(err, ErrNotFound): + return huma.Error404NotFound("no such proposal") + case errors.Is(err, ErrAnswered), errors.Is(err, ErrNotBound), errors.Is(err, errNoEvent): + return huma.Error409Conflict(err.Error()) + case errors.Is(err, ErrTaken): + return huma.Error409Conflict(err.Error()) + case errors.Is(err, approvals.ErrNeedsFreshAuthentication): + return huma.NewError(http.StatusPreconditionRequired, err.Error()) + case errors.Is(err, ErrNotSignedIn), errors.Is(err, ErrNotApprover), errors.Is(err, approvals.ErrFreshAuthenticationFailed): + return huma.Error403Forbidden(err.Error()) + case errors.Is(err, ErrNoConfirmation): + return huma.Error409Conflict(err.Error()) + case errors.Is(err, ErrReasonRequired), errors.Is(err, ErrInvalid), errors.Is(err, ErrRefused): + return huma.Error422UnprocessableEntity(err.Error()) + case errors.As(err, &invalidDoc), errors.Is(err, judgement.ErrInvalidPolicy): + return invalid(err) + } + return m.fail(ctx, what, err) +} + +func (m *Module) fail(ctx context.Context, what string, err error) error { + m.log.ErrorContext(ctx, what, "error", err) + return huma.Error500InternalServerError("couldn't " + what) +} diff --git a/modules/proposals/binding.go b/modules/proposals/binding.go new file mode 100644 index 000000000..0f6788475 --- /dev/null +++ b/modules/proposals/binding.go @@ -0,0 +1,50 @@ +package proposals + +import ( + "errors" + "fmt" + + "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/judgement" + "github.com/samcharles93/archie-core/modules/proposals/internal/store" + "github.com/samcharles93/archie-core/modules/runs" +) + +// ErrNotBound means an approved proposal's action is not the action that was +// judged and shown to the person who approved. +var ErrNotBound = errors.New("the action is not the one that was approved") + +// bind returns what an approved proposal allows its actions to run as. An +// approval covers an action only when the action stored with the proposal is +// the one its decision judged: same decision, and an input that still hashes to +// the digest both carry. An action that was changed after it was shown, or +// whose decision refuses it, gets no approval, and so none of the proposal's +// actions run. +func bind(p store.Proposal, actions []store.Action, decisions []judgement.Decision) ([]runs.ApprovedAction, error) { + if p.State != StateApproved || !p.AnsweredAt.Valid || !p.AnsweredByID.Valid { + return nil, fmt.Errorf("%w: the proposal is %s", ErrNotBound, p.State) + } + byID := make(map[string]judgement.Decision, len(decisions)) + for _, d := range decisions { + byID[d.ID.String()] = d + } + out := make([]runs.ApprovedAction, 0, len(actions)) + for _, a := range actions { + d, ok := byID[a.DecisionID.String()] + switch { + case !ok: + return nil, fmt.Errorf("%w: action %d has no judgement", ErrNotBound, a.Seq) + case d.Level == judgement.Never: + return nil, fmt.Errorf("%w: action %d is refused: %s", ErrNotBound, a.Seq, d.Reason) + case connectors.Digest(a.Action, a.Input) != a.Digest, d.Action.Digest != a.Digest: + return nil, fmt.Errorf("%w: action %d changed after it was judged", ErrNotBound, a.Seq) + } + out = append(out, runs.ApprovedAction{ + Seq: a.Seq, Decision: d, + Approval: judgement.Approval{ + DecisionID: d.ID, Digest: a.Digest, By: p.AnsweredByID.String, ByID: p.AnsweredByID.String, At: p.AnsweredAt.Time, + }, + }) + } + return out, nil +} diff --git a/modules/proposals/binding_test.go b/modules/proposals/binding_test.go new file mode 100644 index 000000000..7aef668ef --- /dev/null +++ b/modules/proposals/binding_test.go @@ -0,0 +1,98 @@ +package proposals + +import ( + "database/sql" + "encoding/json/jsontext" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/judgement" + "github.com/samcharles93/archie-core/modules/proposals/internal/store" +) + +// TestBindApprovesExactlyTheJudgedActions guards the security seam that +// approving a proposal approves only the actions that were judged and shown: an +// action changed after it was judged, one whose judgement is missing or +// refuses it, or a proposal nobody approved must never yield an approval. +func TestBindApprovesExactlyTheJudgedActions(t *testing.T) { + input := jsontext.Value(`{"path":"/tmp/runner"}`) + digest := connectors.Digest("clear", input) + decision := func(level judgement.Level, digest string) judgement.Decision { + return judgement.Decision{ID: uuid.New(), Level: level, Action: judgement.Action{Name: "clear", Digest: digest, Input: input}} + } + approved := store.Proposal{ + State: StateApproved, AnsweredByID: sql.NullString{String: "person-1", Valid: true}, + AnsweredAt: sql.NullTime{Time: time.Date(2026, 11, 24, 0, 0, 0, 0, time.UTC), Valid: true}, + } + action := func(d judgement.Decision, in jsontext.Value, digest string) store.Action { + return store.Action{Seq: 0, Action: "clear", Input: in, Digest: digest, DecisionID: d.ID} + } + + good := decision(judgement.ProposeAndWait, digest) + other := decision(judgement.ProposeAndWait, digest) + refused := decision(judgement.Never, digest) + tests := []struct { + name string + proposal store.Proposal + actions []store.Action + decisions []judgement.Decision + wantErr bool + }{ + {"an action as judged is approved", approved, []store.Action{action(good, input, digest)}, []judgement.Decision{good}, false}, + { + "an input changed after judging is not approved", approved, + []store.Action{action(good, jsontext.Value(`{"path":"/"}`), digest)}, + []judgement.Decision{good}, + true, + }, + { + "a digest that is not the judged one is not approved", approved, + []store.Action{action(good, input, "forged")}, + []judgement.Decision{good}, + true, + }, + { + "an action judged under another decision is not approved", approved, + []store.Action{action(other, input, digest)}, + []judgement.Decision{good}, + true, + }, + { + "an action judgement refuses is not approved", approved, + []store.Action{action(refused, input, digest)}, + []judgement.Decision{refused}, + true, + }, + { + "a proposal nobody approved gives no approval", + store.Proposal{State: StatePending}, + []store.Action{action(good, input, digest)}, + []judgement.Decision{good}, + true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := bind(tt.proposal, tt.actions, tt.decisions) + if tt.wantErr { + if !errors.Is(err, ErrNotBound) { + t.Fatalf("err = %v, want ErrNotBound", err) + } + return + } + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].Approval.DecisionID != good.ID || got[0].Approval.Digest != digest || got[0].Approval.ByID != "person-1" { + t.Fatalf("approval = %+v, want one covering decision %s with digest %s by person-1", got, good.ID, digest) + } + if !got[0].Approval.Covers(got[0].Decision) { + t.Fatal("the approval does not cover its own decision") + } + }) + } +} diff --git a/modules/proposals/internal/store/store.go b/modules/proposals/internal/store/store.go new file mode 100644 index 000000000..8d8ccefdd --- /dev/null +++ b/modules/proposals/internal/store/store.go @@ -0,0 +1,297 @@ +// Package store holds the proposals module's SQL. +package store + +import ( + "context" + "database/sql" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jmoiron/sqlx" +) + +var ( + // ErrNotFound means no such proposal. + ErrNotFound = errors.New("no such proposal") + // ErrAnswered means the proposal was not waiting for an answer. + ErrAnswered = errors.New("the proposal is not waiting for an answer") + // ErrTaken means another proposal already holds the trigger name. + ErrTaken = errors.New("name already used by another proposal") +) + +// Proposal is one stored proposal. +type Proposal struct { + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + Kind string `db:"kind"` + State string `db:"state"` + Needs string `db:"needs"` + Title string `db:"title"` + Summary string `db:"summary"` + Evidence jsontext.Value `db:"evidence"` + Change jsontext.Value `db:"change"` + TargetKind string `db:"target_kind"` + TargetID string `db:"target_id"` + BaseVersion sql.NullInt32 `db:"base_version"` + // PromptedBy is a JSON array of the events that led to the proposal. + PromptedBy jsontext.Value `db:"prompted_by"` + OriginRunID uuid.NullUUID `db:"origin_run_id"` + RunID uuid.NullUUID `db:"run_id"` + ProposedByID string `db:"proposed_by_id"` + CreatedAt time.Time `db:"created_at"` + AnsweredByID sql.NullString `db:"answered_by_id"` + AnsweredAt sql.NullTime `db:"answered_at"` + AnswerReason string `db:"answer_reason"` + PublishedAt sql.NullTime `db:"published_at"` +} + +// Action is one action a proposal will take. +type Action struct { + ProposalID uuid.UUID `db:"proposal_id"` + Seq int `db:"seq"` + Connector string `db:"connector"` + InstallationID uuid.UUID `db:"installation_id"` + Action string `db:"action"` + TargetKind string `db:"target_kind"` + TargetID string `db:"target_id"` + Input jsontext.Value `db:"input"` + Digest string `db:"digest"` + DecisionID uuid.UUID `db:"decision_id"` + State string `db:"state"` + Outcome string `db:"outcome"` + SettledAt sql.NullTime `db:"settled_at"` +} + +const proposalColumns = `id, org_id, kind, state, needs, title, summary, evidence, change, target_kind, target_id, + base_version, to_jsonb(prompted_by) AS prompted_by, origin_run_id, run_id, proposed_by_id, created_at, + answered_by_id, answered_at, answer_reason, published_at` + +const actionColumns = `proposal_id, seq, connector, installation_id, action, target_kind, target_id, input, digest, + decision_id, state, outcome, settled_at` + +// Store is the proposals 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} } + +// Create inserts a proposal with its actions. It reports false, and inserts +// nothing, when a unique index already holds an equivalent open proposal. +func (s *Store) Create(ctx context.Context, p Proposal, actions []Action) (bool, error) { + tx, err := s.db.BeginTxx(ctx, nil) + if err != nil { + return false, fmt.Errorf("begin: %w", err) + } + defer func() { _ = tx.Rollback() }() + res, err := tx.ExecContext(ctx, ` + INSERT INTO proposals.proposals (id, org_id, kind, state, needs, title, summary, evidence, change, + target_kind, target_id, base_version, prompted_by, origin_run_id, proposed_by_id) + VALUES ($1, $2, $3, 'pending', $4, $5, $6, $7, $8, $9, $10, $11, + ARRAY(SELECT jsonb_array_elements_text($12::jsonb)::uuid), $13, $14) + ON CONFLICT DO NOTHING`, + p.ID, p.OrgID, p.Kind, p.Needs, p.Title, p.Summary, p.Evidence, p.Change, + p.TargetKind, p.TargetID, p.BaseVersion, string(p.PromptedBy), p.OriginRunID, p.ProposedByID) + if err != nil { + return false, fmt.Errorf("create proposal: %w", err) + } + if n, _ := res.RowsAffected(); n == 0 { + return false, nil + } + for _, a := range actions { + if _, err := tx.ExecContext(ctx, ` + INSERT INTO proposals.actions (proposal_id, seq, connector, installation_id, action, target_kind, target_id, + input, digest, decision_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, + p.ID, a.Seq, a.Connector, a.InstallationID, a.Action, a.TargetKind, a.TargetID, a.Input, a.Digest, a.DecisionID); err != nil { + return false, fmt.Errorf("create proposal action: %w", err) + } + } + if err := tx.Commit(); err != nil { + return false, fmt.Errorf("commit proposal: %w", err) + } + return true, nil +} + +// ByID returns one proposal. +func (s *Store) ByID(ctx context.Context, orgID string, id uuid.UUID) (Proposal, error) { + return s.one(ctx, `WHERE org_id = $1 AND id = $2`, orgID, id) +} + +// ByGroup returns the live trigger proposal for a group of unmatched events. +func (s *Store) ByGroup(ctx context.Context, orgID string, groupID uuid.UUID) (Proposal, error) { + return s.one(ctx, `WHERE org_id = $1 AND kind = 'trigger' AND change ->> 'group_id' = $2 + AND state IN ('pending', 'approved', 'published')`, orgID, groupID.String()) +} + +// OpenRootCause returns the open root-cause proposal for a cause on a target. +func (s *Store) OpenRootCause(ctx context.Context, orgID, targetKind, targetID, cause string) (Proposal, error) { + return s.one(ctx, `WHERE org_id = $1 AND kind = 'root_cause_fix' AND target_kind = $2 AND target_id = $3 + AND change ->> 'cause' = $4 AND state IN ('pending', 'approved')`, orgID, targetKind, targetID, cause) +} + +func (s *Store) one(ctx context.Context, where string, args ...any) (Proposal, error) { + var p Proposal + err := s.db.GetContext(ctx, &p, `SELECT `+proposalColumns+` FROM proposals.proposals `+where, args...) + if errors.Is(err, sql.ErrNoRows) { + return Proposal{}, ErrNotFound + } + if err != nil { + return Proposal{}, fmt.Errorf("read proposal: %w", err) + } + return p, nil +} + +// List returns an organisation's proposals, newest first. An empty state lists +// every state. +func (s *Store) List(ctx context.Context, orgID, state string) ([]Proposal, error) { + var out []Proposal + if err := s.db.SelectContext(ctx, &out, ` + SELECT `+proposalColumns+` FROM proposals.proposals + WHERE org_id = $1 AND ($2 = '' OR state = $2) ORDER BY created_at DESC LIMIT 200`, orgID, state); err != nil { + return nil, fmt.Errorf("list proposals: %w", err) + } + return out, nil +} + +// Unfinished returns approved proposals whose change is not yet applied, oldest +// answer first. +func (s *Store) Unfinished(ctx context.Context, orgID string, limit int) ([]Proposal, error) { + var out []Proposal + if err := s.db.SelectContext(ctx, &out, ` + SELECT `+proposalColumns+` FROM proposals.proposals + WHERE org_id = $1 AND state = 'approved' ORDER BY answered_at LIMIT $2`, orgID, limit); err != nil { + return nil, fmt.Errorf("list approved proposals: %w", err) + } + return out, nil +} + +// Actions returns a proposal's actions in order. +func (s *Store) Actions(ctx context.Context, id uuid.UUID) ([]Action, error) { + var out []Action + if err := s.db.SelectContext(ctx, &out, ` + SELECT `+actionColumns+` FROM proposals.actions WHERE proposal_id = $1 ORDER BY seq`, id); err != nil { + return nil, fmt.Errorf("list proposal actions: %w", err) + } + return out, nil +} + +// Patch merges fields into the change of a pending proposal and sets who it +// needs. A null value clears a field. +func (s *Store) Patch(ctx context.Context, orgID string, id uuid.UUID, patch map[string]any, needs string) error { + raw, err := json.Marshal(patch) + if err != nil { + return fmt.Errorf("encode change: %w", err) + } + res, err := s.db.ExecContext(ctx, ` + UPDATE proposals.proposals SET change = change || $3::jsonb, needs = $4 + WHERE org_id = $1 AND id = $2 AND state = 'pending'`, orgID, id, string(raw), needs) + return affected(res, err, "edit proposal") +} + +// PatchApproved merges fields into the change of a proposal that is being +// applied, to record progress that a retry skips. +func (s *Store) PatchApproved(ctx context.Context, orgID string, id uuid.UUID, patch map[string]any) error { + raw, err := json.Marshal(patch) + if err != nil { + return fmt.Errorf("encode change: %w", err) + } + res, err := s.db.ExecContext(ctx, ` + UPDATE proposals.proposals SET change = change || $3::jsonb + WHERE org_id = $1 AND id = $2 AND state = 'approved'`, orgID, id, string(raw)) + return affected(res, err, "record proposal progress") +} + +// Retitle replaces a pending proposal's title and summary. +func (s *Store) Retitle(ctx context.Context, orgID string, id uuid.UUID, title, summary string) error { + res, err := s.db.ExecContext(ctx, ` + UPDATE proposals.proposals SET title = $3, summary = $4 WHERE org_id = $1 AND id = $2 AND state = 'pending'`, + orgID, id, title, summary) + return affected(res, err, "retitle proposal") +} + +// Refresh replaces the evidence and summary of a pending proposal. +func (s *Store) Refresh(ctx context.Context, orgID string, id uuid.UUID, summary string, evidence jsontext.Value) error { + res, err := s.db.ExecContext(ctx, ` + UPDATE proposals.proposals SET summary = $3, evidence = $4 WHERE org_id = $1 AND id = $2 AND state = 'pending'`, + orgID, id, summary, evidence) + return affected(res, err, "refresh proposal") +} + +// Answer settles a pending proposal as approved or rejected by one account. It +// returns ErrAnswered when the proposal was no longer waiting, so two answers +// never both succeed. +func (s *Store) Answer(ctx context.Context, orgID string, id uuid.UUID, state, byID, reason string) (Proposal, error) { + var out Proposal + err := s.db.GetContext(ctx, &out, ` + UPDATE proposals.proposals + SET state = $3, answered_by_id = $4, answered_at = now(), answer_reason = $5 + WHERE org_id = $1 AND id = $2 AND state = 'pending' + RETURNING `+proposalColumns, orgID, id, state, byID, reason) + if errors.Is(err, sql.ErrNoRows) { + return Proposal{}, ErrAnswered + } + if err != nil { + return Proposal{}, fmt.Errorf("answer proposal: %w", err) + } + return out, nil +} + +// SetRun records the run that takes an approved proposal's actions. It keeps +// the first run recorded. +func (s *Store) SetRun(ctx context.Context, orgID string, id, runID uuid.UUID) error { + if _, err := s.db.ExecContext(ctx, ` + UPDATE proposals.proposals SET run_id = COALESCE(run_id, $3) WHERE org_id = $1 AND id = $2`, orgID, id, runID); err != nil { + return fmt.Errorf("record proposal run: %w", err) + } + return nil +} + +// SettleAction records how an action ended. An action that already settled +// keeps its outcome. +func (s *Store) SettleAction(ctx context.Context, id uuid.UUID, seq int, state, outcome string) error { + if _, err := s.db.ExecContext(ctx, ` + UPDATE proposals.actions SET state = $3, outcome = $4, settled_at = now() + WHERE proposal_id = $1 AND seq = $2 AND state = 'pending'`, id, seq, state, outcome); err != nil { + return fmt.Errorf("settle proposal action: %w", err) + } + return nil +} + +// Publish marks an approved proposal published once none of its actions is +// still pending. It reports whether the proposal is published. +func (s *Store) Publish(ctx context.Context, orgID string, id uuid.UUID) (bool, error) { + res, err := s.db.ExecContext(ctx, ` + UPDATE proposals.proposals p SET state = 'published', published_at = now() + WHERE p.org_id = $1 AND p.id = $2 AND p.state = 'approved' + AND NOT EXISTS (SELECT 1 FROM proposals.actions a WHERE a.proposal_id = p.id AND a.state = 'pending')`, orgID, id) + if err != nil { + return false, fmt.Errorf("publish proposal: %w", err) + } + n, _ := res.RowsAffected() + return n > 0, nil +} + +func affected(res sql.Result, err error, what string) error { + if err != nil { + if isUnique(err) { + return ErrTaken + } + return fmt.Errorf("%s: %w", what, err) + } + if n, _ := res.RowsAffected(); n == 0 { + return ErrNotFound + } + return nil +} + +func isUnique(err error) bool { + var pgerr *pgconn.PgError + return errors.As(err, &pgerr) && pgerr.Code == "23505" +} diff --git a/modules/proposals/proposals.go b/modules/proposals/proposals.go new file mode 100644 index 000000000..364bf1e2e --- /dev/null +++ b/modules/proposals/proposals.go @@ -0,0 +1,655 @@ +// Package proposals holds the changes Archie proposes, with their evidence: a +// root-cause fix, a trigger and workflow for unmatched events, a workflow or +// policy change. A proposal can list the actions it will take. They are judged +// when it is proposed and shown with it, and approving the proposal approves +// exactly those actions, which a run then takes once. A policy change needs a +// person with authority over policies, and any other change needs the owner. +// A rejection keeps its reason. +package proposals + +import ( + "context" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "fmt" + "log/slog" + "strings" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/modules/approvals" + "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/events" + "github.com/samcharles93/archie-core/modules/governance" + "github.com/samcharles93/archie-core/modules/judgement" + "github.com/samcharles93/archie-core/modules/memory" + "github.com/samcharles93/archie-core/modules/proposals/internal/store" + "github.com/samcharles93/archie-core/modules/runs" +) + +// The kinds of proposal. +const ( + KindRootCauseFix = "root_cause_fix" + KindTrigger = "trigger" + KindWorkflowChange = "workflow_change" + KindPolicyChange = "policy_change" +) + +// The states of a proposal. An approved proposal is applied and then +// published; a rejected one stays as the record of why. +const ( + StatePending = "pending" + StateApproved = "approved" + StateRejected = "rejected" + StatePublished = "published" +) + +// Who must approve a proposal. +const ( + NeedsOwner = "owner" + NeedsAuthority = "authority" +) + +var ( + // ErrNotSignedIn means the answer came from no signed-in person: the + // bootstrap admin token is not a person who may approve. + ErrNotSignedIn = errors.New("only a signed-in person can answer a proposal") + // ErrNotApprover means the person may not answer this proposal. + ErrNotApprover = errors.New("you may not answer this proposal") + // ErrAnswered means the proposal is not waiting for an answer. + ErrAnswered = store.ErrAnswered + // ErrNotFound means no such proposal. + ErrNotFound = store.ErrNotFound + // ErrTaken means a workflow or another proposal already uses the name. + ErrTaken = store.ErrTaken + // ErrRefused means judgement refuses one of the proposed actions. + ErrRefused = errors.New("judgement refuses a proposed action") + // ErrInvalid means the proposal is not one that can be made. + ErrInvalid = errors.New("invalid proposal") + // ErrNoConfirmation means the proposal needs no passkey confirmation, or the + // instance can't give one. + ErrNoConfirmation = errors.New("that proposal can't be confirmed with a passkey") + // ErrReasonRequired means a rejection did not say why. + ErrReasonRequired = errors.New("a rejection needs a reason") +) + +// workInterval is how often approved proposals that are not yet applied are +// picked up again. +const workInterval = 5 * time.Second + +// Groups provides unmatched event groups, replay tracking and trigger storage. +type Groups interface { + Group(ctx context.Context, id uuid.UUID) (events.Group, bool, error) + GroupEvents(ctx context.Context, id uuid.UUID, limit int) ([]events.Stored, error) + Replayed(ctx context.Context, eventID uuid.UUID, trigger string, runID uuid.UUID) error + SaveTrigger(ctx context.Context, t events.TriggerSpec) error +} + +// Workflows installs workflow documents, starts runs and manages dry runs. +type Workflows interface { + Install(ctx context.Context, orgID, name, body, by string) (int, error) + Has(ctx context.Context, orgID, name string) (bool, error) + Start(ctx context.Context, req runs.StartRequest) (uuid.UUID, error) + StartDry(ctx context.Context, req runs.DryRequest) (uuid.UUID, error) + DryReport(ctx context.Context, orgID string, id uuid.UUID) (runs.DryReport, bool, error) +} + +// Policies validates a policy against the current policy set and adds it when +// its proposal is approved. +type Policies interface { + Check(ctx context.Context, kind, extra string) error + Append(ctx context.Context, kind, extra, by string) (judgement.PolicySetView, error) +} + +// Judge judges a proposed action and returns the decisions recorded for a +// proposal. +type Judge interface { + Assess(ctx context.Context, req judgement.Request) (judgement.Decision, error) + ForRun(ctx context.Context, runID uuid.UUID) ([]judgement.Decision, error) +} + +// Module holds one organisation's proposals. +type Module struct { + orgID string + store *store.Store + groups Groups + workflows Workflows + policies Policies + judge Judge + authz governance.Authorizer + confirm approvals.Confirmer + log *slog.Logger +} + +// NewModule returns the proposals module for orgID. +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, g Groups, w Workflows, p Policies, j Judge) *Module { + return &Module{orgID: orgID, store: store.New(db), groups: g, workflows: w, policies: p, judge: j, log: log} +} + +// UseAuthorizer attaches the access policies an answer is judged against. +// Until one is attached, no answer is accepted. +func (m *Module) UseAuthorizer(a governance.Authorizer) { m.authz = a } + +// UseConfirmer configures the passkey check behind approving a proposal whose +// actions can't be undone. Without one, such a proposal can't be approved. +func (m *Module) UseConfirmer(c approvals.Confirmer) { m.confirm = c } + +// confirmationSubject ties a passkey ceremony to one proposal. +func confirmationSubject(id uuid.UUID) string { return "proposal:" + id.String() } + +// irreversible reports whether any of the proposal's actions can't be undone. +func irreversible(decisions []judgement.Decision) bool { + for _, d := range decisions { + if approvals.Irreversible(d.Action) { + return true + } + } + return false +} + +// confirmed checks the passkey assertion approving an irreversible action +// needs. +func (m *Module) confirmed(ctx context.Context, id uuid.UUID, a *approvals.Assertion) error { + if m.confirm == nil || a == nil || a.Token == "" || len(a.Credential) == 0 { + return approvals.ErrNeedsFreshAuthentication + } + err := m.confirm.Confirm(ctx, a.Token, a.Credential, confirmationSubject(id)) + switch { + case errors.Is(err, governance.ErrCredentialRejected): + return approvals.ErrFreshAuthenticationFailed + case err != nil: + return fmt.Errorf("check passkey confirmation: %w", err) + } + return nil +} + +// NewProposal is a change to propose and the actions it will take. +type NewProposal struct { + Kind string + Title string + Summary string + Evidence jsontext.Value + // Change is what approving the proposal writes: for a workflow change the + // name and workflow, for a policy change the policy kind and policy, for a + // root-cause fix the cause. + Change jsontext.Value + TargetKind string + TargetID string + PromptedBy []uuid.UUID + // OriginRunID is the run that produced the proposal, if one did. + OriginRunID uuid.UUID + ProposedByID string + Actions []NewAction +} + +// NewAction is an action a proposal will take once it is approved. +type NewAction struct { + Connector string + Action string + Input jsontext.Value +} + +// Propose records a proposal after judging each of its actions. The proposal +// is shown with the decisions, and approving it approves those actions and no +// others. A proposal for a cause that already has an open root-cause proposal +// refreshes that one instead. +func (m *Module) Propose(ctx context.Context, n NewProposal) (View, error) { + change, needs, err := m.checkProposal(ctx, n) + if err != nil { + return View{}, err + } + id := uuid.New() + actions := make([]store.Action, 0, len(n.Actions)) + for i, a := range n.Actions { + stored, err := m.judged(ctx, id, i, a) + if err != nil { + return View{}, err + } + actions = append(actions, stored) + } + promptedBy, err := json.Marshal(append([]uuid.UUID{}, n.PromptedBy...)) + if err != nil { + return View{}, fmt.Errorf("encode the prompting events: %w", err) + } + if n.ProposedByID == "" { + n.ProposedByID = callerID(ctx) + } + evidence := n.Evidence + if len(evidence) == 0 { + evidence = jsontext.Value(`{}`) + } + p := store.Proposal{ + ID: id, OrgID: m.orgID, Kind: n.Kind, Needs: needs, Title: n.Title, Summary: n.Summary, + Evidence: evidence, Change: change, TargetKind: n.TargetKind, TargetID: n.TargetID, + PromptedBy: promptedBy, OriginRunID: uuid.NullUUID{UUID: n.OriginRunID, Valid: n.OriginRunID != uuid.Nil}, + ProposedByID: n.ProposedByID, + } + created, err := m.store.Create(ctx, p, actions) + if err != nil { + return View{}, err + } + if !created { + return m.refreshOpen(ctx, p) + } + return m.get(ctx, id) +} + +// refreshOpen updates the open root-cause proposal that kept p out with the +// newer evidence, and returns it. +func (m *Module) refreshOpen(ctx context.Context, p store.Proposal) (View, error) { + if p.Kind != KindRootCauseFix { + return View{}, fmt.Errorf("%w: an equivalent proposal is already open", ErrTaken) + } + var c struct { + Cause string `json:"cause"` + } + if err := json.Unmarshal(p.Change, &c); err != nil { + return View{}, fmt.Errorf("read the cause: %w", err) + } + open, err := m.store.OpenRootCause(ctx, m.orgID, p.TargetKind, p.TargetID, c.Cause) + if err != nil { + return View{}, err + } + if open.State == StatePending { + if err := m.store.Refresh(ctx, m.orgID, open.ID, p.Summary, p.Evidence); err != nil && !errors.Is(err, ErrNotFound) { + return View{}, err + } + } + return m.get(ctx, open.ID) +} + +// checkProposal validates a new proposal and returns its change and who it +// needs. +func (m *Module) checkProposal(ctx context.Context, n NewProposal) (jsontext.Value, string, error) { + if strings.TrimSpace(n.Title) == "" || strings.TrimSpace(n.Summary) == "" { + return nil, "", fmt.Errorf("%w: a title and a summary are required", ErrInvalid) + } + change := n.Change + if len(change) == 0 { + change = jsontext.Value(`{}`) + } + switch n.Kind { + case KindRootCauseFix: + var c struct { + Cause string `json:"cause"` + } + if err := json.Unmarshal(change, &c); err != nil || c.Cause == "" { + return nil, "", fmt.Errorf("%w: a root-cause fix names its cause", ErrInvalid) + } + return change, NeedsOwner, nil + case KindWorkflowChange: + var c struct { + Name string `json:"name"` + Workflow string `json:"workflow"` + } + if err := json.Unmarshal(change, &c); err != nil { + return nil, "", fmt.Errorf("%w: %w", ErrInvalid, err) + } + if !validName.MatchString(c.Name) { + return nil, "", fmt.Errorf("%w: name is lowercase letters, digits and hyphens, starting with a letter", ErrInvalid) + } + if _, err := runs.ParseDocument(c.Workflow); err != nil { + return nil, "", err + } + return change, NeedsOwner, nil + case KindPolicyChange: + var c struct { + PolicyKind string `json:"policy_kind"` + Policy string `json:"policy"` + } + if err := json.Unmarshal(change, &c); err != nil { + return nil, "", fmt.Errorf("%w: %w", ErrInvalid, err) + } + if strings.TrimSpace(c.Policy) == "" { + return nil, "", fmt.Errorf("%w: a policy change carries the policy", ErrInvalid) + } + if err := m.checkPolicy(ctx, c.PolicyKind, c.Policy); err != nil { + return nil, "", err + } + return change, NeedsAuthority, nil + } + return nil, "", fmt.Errorf("%w: %q is not a kind that can be proposed here", ErrInvalid, n.Kind) +} + +// judged judges one proposed action. The decision is recorded against the +// proposal, so the same decision is shown and later approved. +func (m *Module) judged(ctx context.Context, proposal uuid.UUID, seq int, a NewAction) (store.Action, error) { + input := connectors.Canonical(a.Input) + if len(input) == 0 { + input = jsontext.Value(`{}`) + } + d, err := m.judge.Assess(ctx, judgement.Request{ + RunID: proposal, Key: fmt.Sprintf("proposal:%s:%d", proposal, seq), Connector: a.Connector, Action: a.Action, + Input: input, Workflow: runs.ProposalWorkflow, + }) + if err != nil { + return store.Action{}, fmt.Errorf("judge action %d: %w", seq, err) + } + if d.Level == judgement.Never { + return store.Action{}, fmt.Errorf("%w: %s %s: %s", ErrRefused, a.Connector, a.Action, d.Reason) + } + return store.Action{ + ProposalID: proposal, Seq: seq, Connector: a.Connector, InstallationID: d.Action.Installation.ID, Action: a.Action, + TargetKind: d.Action.Target.Kind, TargetID: d.Action.Target.ID, + Input: input, Digest: d.Action.Digest, DecisionID: d.ID, + }, nil +} + +// ProposeRootCause proposes a root-cause fix for a cause that keeps recurring +// on a target. There is at most one open proposal per target and cause. +func (m *Module) ProposeRootCause(ctx context.Context, req memory.FixRequest) error { + evidence, err := evidenceOf(map[string]any{"cause": req.Cause, "incidents": req.Incidents}) + if err != nil { + return err + } + change, err := json.Marshal(map[string]string{"cause": req.Cause}) + if err != nil { + return fmt.Errorf("encode the change: %w", err) + } + _, err = m.Propose(ctx, NewProposal{ + Kind: KindRootCauseFix, + Title: fmt.Sprintf("Fix the recurring %s on %s %s", req.Cause, req.Target.Kind, req.Target.ID), + Summary: req.Summary, Evidence: evidence, Change: change, + TargetKind: req.Target.Kind, TargetID: req.Target.ID, + OriginRunID: req.RunID, ProposedByID: string(governance.SystemID), + }) + return err +} + +// Approve records the signed-in person's approval of a proposal and applies +// it. Approving a proposal approves its actions, each only as it was judged. +// The approval is durable once it returns, even if applying it fails: the work +// loop finishes an approved proposal. +func (m *Module) Approve(ctx context.Context, id uuid.UUID, assertion *approvals.Assertion) (View, error) { + p, actions, decisions, err := m.load(ctx, id) + if err != nil { + return View{}, err + } + if p.State != StatePending { + return View{}, ErrAnswered + } + who, err := m.mayAnswer(ctx, p, decisions) + if err != nil { + return View{}, err + } + if err := m.readyToApprove(ctx, p, actions, decisions, who); err != nil { + return View{}, err + } + if irreversible(decisions) { + if err := m.confirmed(ctx, id, assertion); err != nil { + return View{}, err + } + } + approved, err := m.store.Answer(ctx, m.orgID, id, StateApproved, who, "") + if err != nil { + return View{}, err + } + if err := m.apply(ctx, approved); err != nil { + m.log.ErrorContext(ctx, "apply approved proposal", "proposal", id, "error", err) + } + return m.get(ctx, id) +} + +// readyToApprove refuses an approval that could not be applied: a trigger +// whose workflow name is taken or whose parts are invalid, or an action that +// would not be bound to the approval. +func (m *Module) readyToApprove(ctx context.Context, p store.Proposal, actions []store.Action, decisions []judgement.Decision, who string) error { + if p.Kind == KindTrigger { + 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 + } + taken, err := m.workflows.Has(ctx, m.orgID, c.Name) + if err != nil { + return fmt.Errorf("check the workflow name: %w", err) + } + if taken { + return fmt.Errorf("%w: a workflow named %s already exists; rename the proposal", ErrTaken, c.Name) + } + } + trial := p + trial.State = StateApproved + trial.AnsweredByID.String, trial.AnsweredByID.Valid = who, true + trial.AnsweredAt.Time, trial.AnsweredAt.Valid = time.Now(), true + _, err := bind(trial, actions, decisions) + return err +} + +// Confirmation starts the passkey ceremony approving a proposal with an +// irreversible action needs. +func (m *Module) Confirmation(ctx context.Context, id uuid.UUID) (governance.PasskeyCeremony, error) { + p, _, decisions, err := m.load(ctx, id) + if err != nil { + return governance.PasskeyCeremony{}, err + } + if _, err := m.mayAnswer(ctx, p, decisions); err != nil { + return governance.PasskeyCeremony{}, err + } + if !irreversible(decisions) || m.confirm == nil { + return governance.PasskeyCeremony{}, ErrNoConfirmation + } + return m.confirm.BeginConfirmation(ctx, confirmationSubject(id)) +} + +// Reject records why the signed-in person turned a proposal down. +func (m *Module) Reject(ctx context.Context, id uuid.UUID, reason string) (View, error) { + reason = strings.TrimSpace(reason) + if reason == "" { + return View{}, ErrReasonRequired + } + p, _, decisions, err := m.load(ctx, id) + if err != nil { + return View{}, err + } + who, err := m.mayAnswer(ctx, p, decisions) + if err != nil { + return View{}, err + } + if _, err := m.store.Answer(ctx, m.orgID, id, StateRejected, who, reason); err != nil { + return View{}, err + } + return m.get(ctx, id) +} + +// mayAnswer returns the identity ID of the signed-in person when their access +// lets them answer p: approving needs the approve action on the proposal, +// owned by whoever answers for its target, and a proposal that needs authority +// also needs the policy-management action. +func (m *Module) mayAnswer(ctx context.Context, p store.Proposal, decisions []judgement.Decision) (string, error) { + person, ok := governance.PrincipalFromContext(ctx) + if !ok || person.IdentityID == governance.SystemID || person.Kind != governance.KindUser { + return "", ErrNotSignedIn + } + if m.authz == nil { + return "", ErrNotApprover + } + actions := []governance.Action{governance.ActionApprove} + if p.Needs == NeedsAuthority { + actions = append(actions, governance.ActionManagePolicies) + } + res := governance.Resource{ + Kind: governance.KindProposal, ID: p.ID.String(), Org: governance.DefaultOrgID, + Owner: governance.IdentityID(ownerOf(decisions)), State: p.State, + } + for _, a := range actions { + d := m.authz.Authorize(ctx, person, a, res, governance.AccessContext{}) + if d.Err != nil { + return "", fmt.Errorf("check access: %w", d.Err) + } + if !d.Allowed { + return "", ErrNotApprover + } + } + return string(person.IdentityID), nil +} + +// ownerOf is the person who answers for the target of the first action that +// has one. +func ownerOf(decisions []judgement.Decision) string { + for _, d := range decisions { + if owner := d.Owner(); owner != "" { + return owner + } + } + return "" +} + +// apply carries out an approved proposal and publishes it once its actions have +// settled. Every step is idempotent, so a retry never repeats an effect. +func (m *Module) apply(ctx context.Context, p store.Proposal) error { + var err error + switch p.Kind { + case KindTrigger: + err = m.publishTrigger(ctx, p) + case KindWorkflowChange: + err = m.publishWorkflow(ctx, p) + case KindPolicyChange: + err = m.publishPolicy(ctx, p) + } + if err != nil { + return err + } + actions, err := m.store.Actions(ctx, p.ID) + if err != nil { + return err + } + if len(actions) > 0 { + runID, err := m.workflows.Start(workloadContext(ctx), runs.StartRequest{ + OrgID: m.orgID, Workflow: runs.ProposalWorkflow, Key: "proposal:" + p.ID.String(), + Input: jsontext.Value(`{"proposal_id":"` + p.ID.String() + `"}`), + }) + if err != nil { + return fmt.Errorf("start the run for the actions: %w", err) + } + if err := m.store.SetRun(ctx, m.orgID, p.ID, runID); err != nil { + return err + } + } + _, err = m.store.Publish(ctx, m.orgID, p.ID) + return err +} + +func (m *Module) publishWorkflow(ctx context.Context, p store.Proposal) error { + var c struct { + Name string `json:"name"` + Workflow string `json:"workflow"` + } + if err := json.Unmarshal(p.Change, &c); err != nil { + return fmt.Errorf("read the workflow change: %w", err) + } + if _, err := m.workflows.Install(ctx, m.orgID, c.Name, c.Workflow, p.AnsweredByID.String); err != nil { + return fmt.Errorf("install the workflow: %w", err) + } + return nil +} + +func (m *Module) publishPolicy(ctx context.Context, p store.Proposal) error { + var c struct { + PolicyKind string `json:"policy_kind"` + Policy string `json:"policy"` + } + if err := json.Unmarshal(p.Change, &c); err != nil { + return fmt.Errorf("read the policy change: %w", err) + } + if _, err := m.policies.Append(ctx, c.PolicyKind, c.Policy, p.AnsweredByID.String); err != nil { + return fmt.Errorf("add the policy: %w", err) + } + return nil +} + +// Work finishes approved proposals that were not applied, such as after a +// restart, until ctx ends. +func (m *Module) Work(ctx context.Context) { + ticker := time.NewTicker(workInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + m.finish(ctx) + } + } +} + +func (m *Module) finish(ctx context.Context) { + open, err := m.store.Unfinished(ctx, m.orgID, 20) + if err != nil { + m.log.ErrorContext(ctx, "list approved proposals", "error", err) + return + } + for _, p := range open { + if err := m.apply(ctx, p); err != nil { + m.log.ErrorContext(ctx, "apply approved proposal", "proposal", p.ID, "error", err) + } + } +} + +// ApprovedActions returns the actions of an approved proposal, each with the +// approval that covers exactly that action. +func (m *Module) ApprovedActions(ctx context.Context, proposalID uuid.UUID) ([]runs.ApprovedAction, error) { + p, actions, decisions, err := m.load(ctx, proposalID) + if err != nil { + return nil, err + } + return bind(p, actions, decisions) +} + +// SettleAction records how one action of a proposal ended, and publishes the +// proposal when every action has. +func (m *Module) SettleAction(ctx context.Context, proposalID uuid.UUID, seq int, state, outcome string) error { + if err := m.store.SettleAction(ctx, proposalID, seq, state, outcome); err != nil { + return err + } + _, err := m.store.Publish(ctx, m.orgID, proposalID) + return err +} + +// load reads a proposal, its actions and the decisions that judged them. +func (m *Module) load(ctx context.Context, id uuid.UUID) (store.Proposal, []store.Action, []judgement.Decision, error) { + p, err := m.store.ByID(ctx, m.orgID, id) + if err != nil { + return store.Proposal{}, nil, nil, err + } + actions, err := m.store.Actions(ctx, id) + if err != nil { + return store.Proposal{}, nil, nil, err + } + var decisions []judgement.Decision + if len(actions) > 0 { + decisions, err = m.judge.ForRun(ctx, id) + if err != nil { + return store.Proposal{}, nil, nil, fmt.Errorf("read the judgements: %w", err) + } + } + return p, actions, decisions, nil +} + +func callerID(ctx context.Context) string { return governance.CallerID(ctx) } + +// workloadContext acts as the workload principal, as queued work does, so a +// run start is decided by the same policy chain as any other background start. +func workloadContext(ctx context.Context) context.Context { + return governance.WithPrincipal(ctx, governance.WorkloadPrincipal(governance.DefaultOrgID)) +} + +// unavailable reports an error that a retry may clear, as opposed to a refusal. +func unavailable(err error) bool { + return errors.Is(err, governance.ErrChainUnavailable) || errors.Is(err, context.Canceled) +} + +func unmarshalIDs(raw jsontext.Value, dst *[]uuid.UUID) error { + if len(raw) == 0 { + return nil + } + if err := json.Unmarshal(raw, dst); err != nil { + return fmt.Errorf("read the prompting events: %w", err) + } + return nil +} diff --git a/modules/proposals/trigger.go b/modules/proposals/trigger.go new file mode 100644 index 000000000..213c684c2 --- /dev/null +++ b/modules/proposals/trigger.go @@ -0,0 +1,342 @@ +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, Workflow: 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) + } + } + 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, Workflow: c.Name, + }); err != nil { + return fmt.Errorf("save the trigger: %w", err) + } + return m.runPrompting(ctx, p, c) +} + +// 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) 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, Workflow: c.Name, 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 +} diff --git a/modules/runs/interpreter.go b/modules/runs/interpreter.go index e8482eeda..fff7c113b 100644 --- a/modules/runs/interpreter.go +++ b/modules/runs/interpreter.go @@ -95,10 +95,13 @@ func stepBudget(ctx context.Context, settings Settings) (agentloop.Budget, error // the connectors and tools an agent may call, judgement, approvals, delivery // and memory. type Deps struct { - Settings Settings - Toolbox Toolbox - Judge Judge - Approver Approver + Settings Settings + Toolbox Toolbox + Judge Judge + Approver Approver + // Proposals provides the actions of an approved proposal to the workflow + // that runs them. + Proposals Proposals Notifier Notifier Messenger Messenger Memory Memory @@ -665,7 +668,8 @@ func settleOne(rc *Context, judge Judge, ask Approver, settings Settings, d judg }); err != nil { return out, err } - out.Result, out.Error, out.Unknown = runJudged(rc, judge, d, &answer) + approval := answer.Approval(d) + out.Result, out.Error, out.Unknown = runJudged(rc, judge, d, &approval) } out.State = approvals.StateApproved return out, nil @@ -711,7 +715,7 @@ func askThroughPath(rc *Context, ask Approver, settings Settings, d judgement.De // runJudged runs the action judged as d, on approval when there is one, and // returns what came of it. The action's own failure is part of what the answer // led to, and its step has recorded it, so the investigation still reports. -func runJudged(rc *Context, judge Judge, d judgement.Decision, approval *approvals.Answer) (result, failure string, unknown bool) { +func runJudged(rc *Context, judge Judge, d judgement.Decision, approval *judgement.Approval) (result, failure string, unknown bool) { var runErr error if approval == nil { result, runErr = runUnattended(rc, judge, d) @@ -820,12 +824,12 @@ func runUnattended(rc *Context, judge Judge, d judgement.Decision) (string, erro // runApproved runs the action a person approved, once. judgement runs only the // action that was judged, whatever input comes with it. -func runApproved(rc *Context, judge Judge, d judgement.Decision, answer approvals.Answer) (string, error) { +func runApproved(rc *Context, judge Judge, d judgement.Decision, approval judgement.Approval) (string, error) { return rc.Step("run:"+d.Key, func(ctx context.Context, key string) (string, error) { if err := begun(ctx, rc, key); err != nil { return "", err } - out, err := judge.ExecuteApproved(ctx, d, answer.Approval(d), d.Action.Input, key) + out, err := judge.ExecuteApproved(ctx, d, approval, d.Action.Input, key) return out, unknownOutcome(err) }) } diff --git a/modules/runs/proposal.go b/modules/runs/proposal.go new file mode 100644 index 000000000..28748cec7 --- /dev/null +++ b/modules/runs/proposal.go @@ -0,0 +1,146 @@ +package runs + +import ( + "context" + "errors" + "fmt" + + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/modules/judgement" +) + +// ProposalWorkflow is the workflow that takes the actions of an approved +// proposal. Its input is the proposal's id. +const ProposalWorkflow = "run-proposal" + +// proposalDocument runs an approved proposal's actions in order. +const proposalDocument = `inputs: + proposal_id: + type: string + required: true +repository: none +steps: + - id: actions + type: proposal.actions +` + +// ProposalDocument defines the workflow that ships with the binary to run an +// approved proposal's actions. +func ProposalDocument() string { return proposalDocument } + +// The states an action of a proposal settles as. +const ( + ActionRan = "ran" + ActionFailed = "failed" + ActionUnknown = "unknown" + ActionRefused = "refused" + ActionSkipped = "skipped" +) + +// ApprovedAction is one action of an approved proposal: the decision it was +// judged under when proposed, and the approval the proposal's answer gave it. +type ApprovedAction struct { + Seq int + Decision judgement.Decision + Approval judgement.Approval +} + +// Proposals provides the actions of an approved proposal and records how each +// one settled. +type Proposals interface { + // ApprovedActions returns the proposal's actions in order, only while the + // proposal is approved and each approval covers exactly its action. + ApprovedActions(ctx context.Context, proposalID uuid.UUID) ([]ApprovedAction, error) + // SettleAction records how one action ended. Settling it again changes + // nothing. + SettleAction(ctx context.Context, proposalID uuid.UUID, seq int, state, outcome string) error +} + +type proposalActions struct{} + +func (proposalActions) valid() error { return nil } + +func (proposalActions) describe() string { + return "Runs the actions of an approved proposal in order, each judged again first, and stops at the first that does not run" +} + +// runProposalActions takes a proposal's actions one at a time. Each is judged +// again and runs only if that judgement still allows what the approval +// covered. An action that does not run stops the rest, which settle as +// skipped. Every settlement is its own step, so a resumed run repeats none. +func runProposalActions(d Deps, rc *Context, p *progress, _ string, _ proposalActions) (StepResult, error) { + if d.Proposals == nil { + return StepResult{}, errors.New("proposals are not available") + } + id, err := uuid.Parse(fmt.Sprint(p.inputs["proposal_id"])) + if err != nil { + return StepResult{}, fmt.Errorf("proposal_id is not a proposal id: %w", err) + } + actions, err := rc.Step("proposal-actions", func(ctx context.Context, _ string) ([]ApprovedAction, error) { + return d.Proposals.ApprovedActions(ctx, id) + }) + if err != nil { + return StepResult{}, err + } + stopped, ran := false, 0 + for _, a := range actions { + state, outcome := ActionSkipped, "an earlier action did not run" + if !stopped { + out, err := takeProposed(rc, d.Judge, a) + if err != nil { + return StepResult{}, err + } + p.outcomes = append(p.outcomes, out) + state, outcome = settlement(out) + stopped = state != ActionRan + } + if state == ActionRan { + ran++ + } + if _, err := rc.Step(fmt.Sprintf("settle:%d", a.Seq), func(ctx context.Context, _ string) (bool, error) { + return true, d.Proposals.SettleAction(ctx, id, a.Seq, state, outcome) + }); err != nil { + return StepResult{}, err + } + } + return StepResult{Summary: fmt.Sprintf("%d of %d actions ran", ran, len(actions))}, nil +} + +// takeProposed judges one approved action again and runs it if the approval +// still holds, as for an approval given during a run. +func takeProposed(rc *Context, judge Judge, a ApprovedAction) (approvalOutcome, error) { + d := a.Decision + out := approvalOutcome{ + Action: d.Action.Connector + " " + d.Action.Name, Target: d.Action.Target.Kind + ":" + d.Action.Target.ID, + State: "approved", digest: d.Action.Digest, By: a.Approval.By, + } + fresh, err := rc.Step(fmt.Sprintf("judge-again:%d", a.Seq), func(ctx context.Context, key string) (judgement.Decision, error) { + return judge.Assess(ctx, rc.request(key, d.Action.Connector, d.Action.Name, d.Action.Input)) + }) + if err != nil { + return out, err + } + switch next, why := afterApproval(d, fresh); next { + case refuseAction, reaskPerson: + out.State, out.Error = ActionRefused, why + case runFresh: + out.Result, out.Error, out.Unknown = runJudged(rc, judge, fresh, nil) + default: + out.Result, out.Error, out.Unknown = runJudged(rc, judge, d, &a.Approval) + } + return out, nil +} + +// settlement is the state and text an action's outcome settles as. +func settlement(o approvalOutcome) (state, text string) { + switch { + case o.State == ActionRefused: + return ActionRefused, o.Error + case o.Unknown: + return ActionUnknown, o.Error + case o.Error != "": + return ActionFailed, o.Error + } + return ActionRan, o.Result +} diff --git a/modules/runs/started_test.go b/modules/runs/started_test.go index 8900b4cc5..0e88e5fbc 100644 --- a/modules/runs/started_test.go +++ b/modules/runs/started_test.go @@ -79,7 +79,7 @@ func TestActionStartedBeforeItsResultIsNeverRunAgain(t *testing.T) { var err error if tt.approved { d := judgement.Decision{Key: "k", Level: judgement.ProposeAndWait, Action: judgement.Action{Connector: "ops", Name: "restart"}} - _, err = runApproved(rc, judge, d, approvals.Answer{Approved: true}) + _, err = runApproved(rc, judge, d, approvals.Answer{Approved: true}.Approval(d)) } else { ctx := core.WithIdempotencyKey(t.Context(), agentKey) _, err = call(ctx, stubBox{}, judge, rc, decl, jsontext.Value(`{}`)) diff --git a/modules/runs/vocabulary.go b/modules/runs/vocabulary.go index 0752a3934..cc734f5c4 100644 --- a/modules/runs/vocabulary.go +++ b/modules/runs/vocabulary.go @@ -29,6 +29,7 @@ const ( typeHandoff = "workflow.handoff" typeApprove = "workflow.approve" typeMessage = "message.send" + typeProposal = "proposal.actions" ) // StepType defines a workflow step's settings and implementation. @@ -98,6 +99,7 @@ var stepTypes = vocabulary( define(typeHandoff, "Hand off", handoffSettings.valid, handoffSettings.describe, runHandoff), define(typeApprove, "Approval", approveSettings.valid, approveSettings.describe, runApprove), define(typeMessage, "Send message", messageSettings.valid, messageSettings.describe, runMessage), + define(typeProposal, "Run a proposal's actions", proposalActions.valid, proposalActions.describe, runProposalActions), ) func vocabulary(types ...StepType) map[string]StepType { diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index d16b70c8e..d7ab57596 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -192,6 +192,22 @@ export const api = { request(`/api/runs/${encodeURIComponent(id)}/retry`, { method: "POST", body: from ? { from } : {} }), /** Asks a run that has not ended to stop, along with the runs it called. */ cancelRun: (id: string) => request(`/api/runs/${encodeURIComponent(id)}/cancel`, { method: "POST", body: {} }), + proposals: (state?: ProposalState) => request("/api/proposals" + qs({ state })), + proposal: (id: string) => request(`/api/proposals/${encodeURIComponent(id)}`), + /** Approves a proposal and the actions it lists; the server applies it. */ + approveProposal: (id: string, assertion?: ApprovalAssertion) => + request(`/api/proposals/${encodeURIComponent(id)}/approve`, { method: "POST", body: { assertion } }), + rejectProposal: (id: string, reason: string) => + request(`/api/proposals/${encodeURIComponent(id)}/reject`, { method: "POST", body: { reason } }), + /** Starts the passkey confirmation that approving an irreversible action needs. */ + beginProposalConfirmation: (id: string) => + request(`/api/proposals/${encodeURIComponent(id)}/confirmation`, { method: "POST", body: {} }), + /** Replays a stored event, the newest by default, against a trigger proposal. */ + dryRunProposal: (id: string, eventId?: string) => + request(`/api/proposals/${encodeURIComponent(id)}/dry-run`, { method: "POST", body: eventId ? { event_id: eventId } : {} }), + /** Proposes a trigger and workflow for a group of unmatched events. */ + proposeForGroup: (groupId: string) => + request(`/api/groups/${encodeURIComponent(groupId)}/proposal`, { method: "POST", body: {} }), approvals: () => request("/api/approvals"), answerApproval: (id: string, approved: boolean, assertion?: ApprovalAssertion) => request(`/api/approvals/${encodeURIComponent(id)}/answer`, { method: "POST", body: { approved, assertion } }), @@ -853,6 +869,64 @@ export interface Bootstrap { sealing_identity_set: boolean; } +export type ProposalState = "pending" | "approved" | "rejected" | "published" | "superseded" | "withdrawn"; + +export interface ProposalAction { + seq: number; + connector: string; + action: string; + target_kind: string; + target_id: string; + input: unknown; + decision_id: string; + /** How far judgement lets the action run, as shown when it was proposed. */ + level?: string; + reason?: string; + refused_by?: string; + verdicts?: { guard: string; ceiling: string; findings?: { text: string }[]; failed?: string }[]; + state: "pending" | "ran" | "failed" | "unknown" | "refused" | "skipped"; + outcome?: string; + settled_at?: string; +} + +export interface ProposalTrigger { + group_id: string; + name: string; + source_id: string; + event_type: string; + filter: Record; + workflow: string; + policy_kind: "hard_rules" | "change_request"; + policy: string; + dry_run?: { run_id: string; state: string; error?: string; findings?: string; actions: { action: string; target: string; level: string; outcome: string; why?: string }[] }; + dry_event_id?: string; + installed_version?: number; +} + +export interface Proposal { + id: string; + kind: "root_cause_fix" | "trigger" | "workflow_change" | "ceiling_raise" | "policy_change"; + state: ProposalState; + /** Who must approve: the owner, or a person with authority over policies. */ + needs: "owner" | "authority"; + title: string; + summary: string; + evidence: unknown; + change?: unknown; + trigger?: ProposalTrigger; + target_kind: string; + target_id?: string; + actions: ProposalAction[]; + prompted_by: string[]; + run_id?: string; + proposed_by_id: string; + created_at: string; + answered_by_id?: string; + answered_at?: string; + answer_reason?: string; + published_at?: string; +} + export interface ApprovalConfirmation { token: string; options: { publicKey: Record }; diff --git a/ui/src/proposals/ProposalPage.vue b/ui/src/proposals/ProposalPage.vue new file mode 100644 index 000000000..92aa74eda --- /dev/null +++ b/ui/src/proposals/ProposalPage.vue @@ -0,0 +1,167 @@ + + +