diff --git a/docs/effectors/README.md b/docs/effectors/README.md new file mode 100644 index 00000000..2f898066 --- /dev/null +++ b/docs/effectors/README.md @@ -0,0 +1,89 @@ +# Effectors + +Status: **draft for discussion**. Nothing here is implemented. + +CCF today only observes: agents collect evidence, the API turns it into posture, and +people read dashboards. Effectors add the other direction. When something in CCF reaches a +state a user cares about, CCF **acts** through effector plugins: it notifies someone, +blocks a change, or remediates, depending on the plugins installed. + +The smallest useful loop needs no SSP at all: + +```mermaid +flowchart LR + AG["Agent
collects evidence"] -->|"evidence: not-satisfied"| API["CCF API
rule matches"] + API -->|"effect.apply"| EF["Effector
plugin fixes it"] + EF -->|"changes"| SYS["GitHub / AWS / Slack"] + SYS -.->|"next collection"| AG + AG -->|"evidence: satisfied"| API + API -->|"effect.clear"| EF +``` + +## Documents + +Read them in this order. Each one ends with its own open questions. + +| Document | Covers | Read it if you're... | +| --- | --- | --- | +| [User interface](user-interface.md) | What users do through the API: register effectors, create rules, pick targets, see what happened, decide on exceptions | designing the UI or the rule model | +| [Triggers](triggers.md) | Trigger sources (evidence, risk, workflow, SSP, catalog) and their subject schemas, CEL conditions, state vs event rules, how the API evaluates them | working on the API's rule engine | +| [Events and states](events-and-states.md) | Every state rules can test and every event they can react to, per source, and how the API computes each | checking what a rule can react to | +| [Wire interface](wire-interface.md) | The API ↔ agent protocol for effectors: registration, webhooks, effect document, callbacks, delivery guarantees | building the API side or the agent's effector support | +| [Effector interface](effector-interface.md) | Effectors as agents: the `effector` block, effector plugins and actions, remote config, validation, the plugin gRPC contract | operating an effector or writing a plugin | +| [Plugin runtime](plugin-runtime.md) | How the agent runs effector plugins: processes, listener, gRPC messages, status flow, timeouts, ordering, retries | implementing the agent side or a plugin | +| [Example plugins](plugins.md) | Illustrative plugins and how a plugin maps onto the contract. Plugins themselves are out of scope | writing a plugin | +| [Security](security.md) | Trust boundaries, identity, signing, credentials, who may create which rules | reviewing the design | +| [Operations](operations.md) | Failure modes, observability, HA, phasing, how this relates to notifications | planning the rollout | + +## Glossary + +| Term | Meaning | +| --- | --- | +| **Rule** | *When* something holds or happens, *do* these actions. Top-level resource; not owned by an SSP. | +| **Trigger** | The *when* of a rule: a **source** (evidence, risk, workflow, SSP, catalog) and either a CEL **condition** over its subjects (`when`) or **event types** with an optional CEL filter (`on`, `if`). | +| **State rule** | Its trigger is a condition that holds or doesn't ("evidence is failing"). Its effects turn on and off. | +| **Event rule** | Its trigger is something that happens ("a catalog control changed"). Each occurrence produces a one-off effect. | +| **Rule action** | The *do* of a rule: which **effector**, which of its **effector actions**, which target, and an optional delay. No config. | +| **Target** | What an action acts on, as an identity `scheme:value` (`github-repo:github.com/acme/repo-1`, `slack-channel:#platform`). Fixed in the rule, or computed by a CEL expression from whatever triggered it. | +| **Effect** | The live record of one rule action on one target: desired state, generation, the subjects that caused it, and what the effector reports back. | +| **Effector** | A CCF **agent** running effector plugins, in the customer's environment. It receives effects and runs its effector actions. The same agent can also run collector plugins. | +| **Effector plugin** | An agent plugin with `type: effector` that declares and performs one or more effect types against one provider. go-plugin over gRPC, distributed like collector plugins. | +| **Effector action** | A named thing an effector can do, defined by its operator in the effector's config: plugin, effect type (a label the plugin declares, such as `notify` or `block`), allowed targets, and config. Registered with the API without the config. | + +## Big picture + +```mermaid +flowchart TB + subgraph Sources["Trigger sources (API)"] + E["Evidence status"] + R["Risk status"] + W["Workflow status"] + S["SSP status"] + C["Catalog changes"] + end + Sources --> DE["Domain events"] + DE --> RE["Rule engine"] + RU["Rules + actions
(user interface)"] --> RE + RE --> FX[("Effects")] + FX --> DL["Webhook delivery
(wire interface)"] + DL --> EF["Agent + effector plugins
(effector interface)"] + EF -->|"status, observations"| FX + EF --> EXT["External systems"] +``` + +## Design principles + +1. **The API decides, effectors act.** Effectors hold no rules and no policies. They make + a provider reflect the effect they were given. +2. **Desired state, not commands.** Effects are level-triggered documents with a + generation number. Missed deliveries and restarts converge on their own. +3. **Credentials stay with the customer.** The API never holds Slack, GitHub or AWS + credentials for effects. +4. **The operator has the last word.** An effector only runs the effector actions its + operator defined, with the config they wrote. Rules pick an action and a target, nothing + more. +5. **Effectors are agents.** An effector is the agent with effector plugins: identity, + keys, heartbeats, remote configuration and the plugin model come from the agent. +6. **One rule action, one effector.** Each rule action names the effector that receives its + effects. Effectors never compete for rules, and an effect is never sent to two agents. + Delivery is at least once; agents drop a generation they've already received. diff --git a/docs/effectors/effector-interface.md b/docs/effectors/effector-interface.md new file mode 100644 index 00000000..07dca01f --- /dev/null +++ b/docs/effectors/effector-interface.md @@ -0,0 +1,542 @@ +# Effector interface + +An **effector is not a separate program**. It's the CCF **agent** running one or more +**effector plugins**, next to (or instead of) its collector plugins. The agent already +has what an effector needs: API authentication, plugin download and verification, remote +configuration, heartbeats and instance IDs. This document covers what the agent adds to act as +an effector: configuration, effector actions, validation, and the plugin contract. The +protocol with the API is in [wire interface](wire-interface.md). + +```mermaid +flowchart TB + subgraph Agent["ccf-agent"] + subgraph Shared["Shared (exists today)"] + CFG["Config file + remote config overlay"] + PL["Plugin loader
OCI sources, trusted_sources"] + AUTH["API client + auth"] + HB["Heartbeat, config report,
instance ID, state dir"] + end + subgraph Collect["Collector plugins (exists today)"] + SCH["Scheduler"] --> CP["collector plugins"] + end + subgraph Effect["Effector plugins (new)"] + RX["Webhook receiver
signature, dedupe,
action + target check"] + MEM["In-memory effects
(from the API)"] + WK["Worker + reconciler"] + XR["External ingress
/ext/{plugin}/…"] + EP["effector plugins"] + end + end + RX --> MEM --> WK --> EP + XR --> EP + PL --> CP + PL --> EP + CP -- "ApiHelper" --> AUTH + EP -- "EffectorHelper only" --> AUTH +``` + +One agent can run collector plugins, effector plugins, or both. A plugin's `type` says which. + +## Configuration + +Effector settings use the agent's existing configuration file and conventions: snake_case +keys, `CCF_` environment variables, `${env:NAME}` placeholders for secrets in plugin config, +and `remote_config` for what an API overlay may change. Today placeholders are resolved only in +`plugins.*.config`; they'd be resolved in `plugins.*.actions.*.config` too, with the same +rules. Three things are new: + +- `plugins..type`: `collector` (the default, so existing configs don't change) or + `effector`. +- `plugins..actions`: the effector actions an effector plugin offers. +- A top-level `effector` block: the webhook listener and defaults. It's only needed when at + least one effector plugin is enabled. + +```yaml +daemon: true +api: + url: https://ccf.acme.com + auth: # or CCF_API_AUTH_CLIENT_ID / CCF_API_AUTH_CLIENT_SECRET + client_id: 6f1c… + client_secret: … + +effector: + listen: 0.0.0.0:8443 + public_url: https://agent-platform.acme.internal # base URL; must equal the one an admin set in the API + tls: # optional: omit when TLS is terminated in front of the agent + cert: /tls/tls.crt + key: /tls/tls.key + stale_after: 15m # no successful API contact for this long → on_stale applies + defaults: # for every effector plugin and action, unless overridden below + on_stale: keep # keep | fail-open | fail-closed + reconcile_interval: 10m + targets_refresh: 15m + +plugins: + github-settings: # a collector plugin: unchanged from today + source: ghcr.io/compliance-framework/plugin-github-settings:1.2.0 + schedule: "0 * * * *" + policies: [ghcr.io/compliance-framework/plugin-github-settings-policies:1.0.0] + config: + token: ${env:GITHUB_TOKEN} + + slack: + type: effector + source: ghcr.io/compliance-framework/effector-slack:1.0.0 + reconcile_interval: 5m # overrides effector.defaults for this plugin + config: # plugin config: credentials and connection + bot_token: ${env:SLACK_BOT_TOKEN} + actions: + notify-platform: + description: Short alert to platform channels + effect: notify + targets: + include: ["slack-channel:#platform", "slack-channel:#platform-*"] + exclude: ["slack-channel:#platform-exec"] + on_clear: resolve + publish_targets: true + config: # action config: how to perform it + template: short + notify-person: + description: Detailed direct message + effect: notify + targets: + include: ["slack-user:*"] + config: + template: detailed + + github-checks: + type: effector + source: ghcr.io/compliance-framework/effector-github-checks:1.0.0 + config: + app_id: "123456" + private_key: ${env:GITHUB_APP_KEY} + webhook_secret: ${env:GITHUB_WEBHOOK_SECRET} + actions: + block-prs: + description: Required check that fails while the rule is active + effect: block + targets: + include: ["github-repo:github.com/acme/*"] + on_clear: revert + on_stale: fail-open # overrides effector.defaults.on_stale for this action + config: + check_name: CCF compliance + +remote_config: # unchanged: local only + mode: report + trusted_sources: ["ghcr.io/compliance-framework/*"] + allow_local_sources: false +``` + +### The `effector` block + +| Field | Required | Meaning | +| --- | --- | --- | +| `listen` | Yes | Address the webhook receiver binds to | +| `public_url` | Yes | The agent's **base URL** as the API reaches it. The agent serves `/v1/webhook` (deliveries), `/ext/{plugin}/…` (provider webhooks), `/healthz` and `/readyz` under it. It must equal the base URL an admin set for this agent in the API, after normalisation (`409` on registration otherwise), so a leaked key can't redirect deliveries. Must be `https`, unless the API runs with `CCF_EFFECTOR_ALLOW_INSECURE_WEBHOOKS=true` (local development) | +| `tls` | **No** | Certificate and key for the listener. Omit it when TLS is terminated in front of the agent (ingress, load balancer, service mesh): `public_url` still has to be `https`, but the agent itself listens in plain HTTP | +| `stale_after` | No (`15m`) | How long without successful API contact before `on_stale` applies | +| `defaults` | No | Defaults for plugins and actions (below) | + +### Defaults and overrides + +Settings in `effector.defaults` can be overridden by a plugin or an action. The most specific +one wins: + +| Setting | `effector.defaults` | `plugins.

` | `plugins.

.actions.` | Default | +| --- | --- | --- | --- | --- | +| `on_stale` | yes | yes | yes | `keep` | +| `reconcile_interval` | yes | yes | — | `10m` | +| `targets_refresh` | yes | yes | yes | `15m` | +| `on_clear` | — | — | yes | the default the plugin declares for that effect | + +`reconcile_interval` is per plugin because `Reconcile` works on all of a plugin's effects at +once. + +### Plugin fields + +| Field | Collector | Effector | +| --- | --- | --- | +| `type` | `collector` (default) | `effector` | +| `source`, `enabled`, `protocol_version`, `config`, `labels` | as today | as today | +| `schedule`, `policies`, `policy_data`, `policy_behavior` | as today | not allowed: effector plugins are driven by effects, not schedules, and don't evaluate policies | +| `actions` | not allowed | required (at least one) | +| `reconcile_interval`, `targets_refresh`, `on_stale` | not allowed | optional overrides | +| `apply_timeout`, `reconcile_timeout`, `max_concurrency` | not allowed | optional ([plugin runtime](plugin-runtime.md#timeouts)) | + +The plugin's `type` must match what the binary implements. Collector plugins only serve the +`Runner` service (`Configure`, `Eval`, `Init`), so there's no `Describe` to ask them. Instead +the agent dispenses the go-plugin service that `type` names (`runner` for collectors, +`effector` for effectors), and a binary that doesn't serve it fails to start. An effector binary +then answers `Describe()`. + +## Effector actions + +An effector action is a named, operator-defined use of an effector plugin, under +`plugins.

.actions.`: + +| Field | Meaning | +| --- | --- | +| name (key) | Unique **within the agent**, across all its plugins. Rules refer to it together with the agent's name | +| `description` | Shown in the rule builder | +| `effect` | Which of the plugin's effect types the action performs. See [Effect types](#effect-types) | +| `targets.include` | Patterns of targets this action may act on: `scheme:pattern`, for example `github-repo:github.com/acme/*`. The scheme must be one the plugin declares | +| `targets.exclude` | Optional patterns removed from `include` | +| `rule_kinds` | Optional: narrow to `state` or `event`. Defaults to what the plugin supports for that effect | +| `on_clear`, `on_stale`, `targets_refresh` | Overrides ([above](#defaults-and-overrides)) | +| `publish_targets` | Optional, default `false`. Publish the targets the plugin can list, for the rule builder's dropdown ([below](#published-targets)) | +| `config` | Action config, passed to the plugin with every effect for this action | + +### Effect types + +Effect types are **declared by plugins**, not a list owned by CCF. An effect type is a short +label (a lowercase slug such as `notify`, `block`, `remediate-apply`, `dispatch`) plus the +properties the API actually needs, all in the plugin's manifest: + +| Declared per effect | Used for | +| --- | --- | +| `effect` | A label: shown in the rule builder, usable as a filter. The API attaches no meaning to it | +| `rule_kinds` | Which rules can use it: `state`, `event` or both. A plugin that can't undo what it does (for example applying a fix) declares `state` only if it wants the next collection to confirm it | +| `default_on_clear` | What clearing means for it: `revert`, `resolve` or `none`. An action can override it with `on_clear` | + +The API validates rules against those registered properties only: a rule kind the action +didn't register is rejected, and `on_clear` must be one of `revert`, `resolve`, `none`. It +doesn't know or check any particular label. A new kind of effect, such as `dispatch` for +handing results to another system, is just a plugin declaring it: no CCF change. + +The labels in this design (`notify`, `block`, `remediate`) are conventions used by the example +plugins, not a closed list. + +### Targets: an allowlist + +`targets` is an **allowlist**, so anything not matched is denied. `include` lists what's +allowed, and `exclude` takes patterns back out of it ("every repo in `acme` except +`acme/prod-*`"). There's no way to allow something that isn't in `include`. + +The patterns are enforced twice: the API rejects or skips targets that don't match, and the +agent checks every delivery again before it reaches a plugin (`403` otherwise). So a +compromised or misconfigured API can't make an agent act outside what its operator wrote. + +### Target pattern grammar + +Both sides must match the same way, or the API accepts a target the agent then refuses. So the +grammar is defined once and implemented once, in a public package both import (for example +`pkg/effector/targets` in the API module, which the agent already depends on). + +| Part | Rule | +| --- | --- | +| Identity | `scheme:value`. The first `:` separates them; the value may contain more `:` | +| Scheme | `[a-z][a-z0-9-]*`, matched exactly. Patterns can't use wildcards in the scheme | +| Value | Any non-empty string of printable characters. It must also match the scheme's `value-pattern` (an RE2 regular expression, anchored) | +| Pattern | `scheme:glob`. The glob is matched against the **whole** value, case-sensitively | +| `*` | Any sequence of characters, except `/` | +| `**` | Any sequence of characters, including `/` | +| `?` | One character, except `/` | +| `\` | Escapes the next character (`\*` is a literal `*`) | + +Examples: + +| Pattern | Matches | Doesn't match | +| --- | --- | --- | +| `github-repo:github.com/acme/*` | `github.com/acme/repo-1` | `github.com/acme/team/repo-1`, `github.com/ACME/repo-1` | +| `github-repo:github.com/acme/**` | `github.com/acme/team/repo-1` | `github.com/other/repo-1` | +| `slack-channel:#platform-*` | `#platform-alerts` | `#platform` | +| `slack-user:*` | any value of the `slack-user` scheme | anything in another scheme | + +An identity is allowed when it matches at least one `include` pattern and no `exclude` +pattern. + +### Two kinds of config + +| | Plugin config (`plugins.

.config`) | Action config (`plugins.

.actions..config`) | +| --- | --- | --- | +| Holds | Credentials, endpoints, accounts | How to perform one action: template, check name, settings baseline | +| How many | One per plugin | One per action; many actions share a plugin | +| Validated by | The plugin's `Configure`, at startup | The plugin's `ValidateAction`, at startup | +| Reported to the API | With the agent's config report (`remote_config.mode` other than `off`), masked as today | Same | + +How a plugin organizes accounts (one, or several in its config) is up to the plugin. The +agent only needs it to accept its config, perform its actions and list its targets. + +## Remote configuration + +Effector settings follow the agent's remote configuration rules: an overlay from the API +changes them only within what `remote_config` allows, and the agent classifies each change. + +Today an operator can set `remote_config.mode: apply_all`, which applies **unsafe** changes +too. If widening an effector were only unsafe, an `apply_all` agent would let the API add +actions or targets, and "the API can't make an agent act outside what its operator wrote" +would be false. So anything that widens what an effector can do is **forbidden**: rejected in +every mode, like changes to `api`. Proposed classification: + +| Change | Class | +| --- | --- | +| `effector.*` | **forbidden**, like `api` and `remote_config`: it controls a network listener | +| Adding a plugin with `type: effector`, or changing any plugin's `type` | **forbidden** | +| Adding an action; adding an `include` pattern; removing an `exclude` pattern; changing `effect` | **forbidden** (widens what the agent can do) | +| `publish_targets: true` | **forbidden** (sends more data to the API) | +| `on_clear`, `on_stale` | **unsafe** | +| Removing an action; removing an `include` pattern; adding an `exclude` pattern; `publish_targets: false`; disabling an effector plugin | safe (narrows what the agent can do) | +| `description`, `targets_refresh`, `reconcile_interval` | safe | +| An action's `config` key | Safe only if it matches the new `overridable_action_config_flags` list; unsafe otherwise | + +**Action config overrides get their own list.** Existing `overridable_config_flags` patterns +are matched with `path.Match`, where `*` also matches dots +(`pkg/agentconfig/remoteconfig.go`). If action config keys were matched against that list, an +existing `"*"` or `"slack:*"` entry would silently make every action's config overridable. A +separate list, `remote_config.overridable_action_config_flags`, with entries +`::` matched segment by segment, keeps that opt-in explicit. Existing +lists don't change meaning. + +So whatever `mode` an operator picks, an overlay can only make an effector do less, or tune +config keys the operator listed by name. + +`trusted_sources` and `allow_local_sources` apply to effector plugin sources exactly as to +collector plugins. + +## State + +The agent keeps **no effector state of its own**. The API is the only store: + +- The effects an agent owns, and what each plugin last reported for them (status and + `refs`, such as a Slack message ID or check run IDs), live in the API. Every effect + document the agent receives carries the last applied status and refs back. +- The agent holds the current effects **in memory**. On startup, and on every resync, it + fetches them from the API (`GET /api/agent/effects`). +- Webhook deduplication (`webhook-id`) is in memory, for the 5-minute signature window. +- The agent's existing state directory (instance ID, remote config cache) is unchanged and + isn't used for effects. + +Until its first successful fetch after a start, an agent ignores provider events +(`HandleExternal`) for effects it doesn't know yet. The first `Reconcile` afterwards catches +up. If a local store is ever needed, it goes under a namespaced key +(`effector.store.local.path`, `effector.store.postgres`, …), and the API stays the source of +truth. + +### Multiple instances + +**v1 supports one replica per agent with effector plugins.** Deliveries go to one URL, and +that agent holds the effects in memory; nothing keeps several pods' memory in sync. Running +more than one replica of such an agent isn't supported in v1: a delivery would reach one pod +and the others would keep acting on older state. + +Multiple replicas come with leader election in v2 (below). With one active pod at a time, +the protocol doesn't need a change feed, an "as of" digest or per-pod retries, so v1 doesn't +build them. + +### Later (v2): leader election + +Parked for after v1, as an **agent-wide** feature rather than an effector one. The agreed +shape: + +- An opt-in, local-only agent setting (forbidden in overlays, like `api`), for example + `ha.mode: all-active | leader`, defaulting to `all-active` so existing agents don't change. +- In `leader` mode, instances hold a lease in the CCF API, renewed periodically. Writes + (evidence, effect status) carry the lease epoch, and the API rejects stale ones (fencing). + Only the leader runs collector schedules and effector plugins, and only it reports Ready, + so a Service routes webhooks to it. This also stops two pods from sending the same evidence. +- Agents with effector plugins would then require `leader` mode. An agent that needs + per-host collection (a DaemonSet with `local-ssh`) and effectors becomes two agents. +- With one active pod, effectors work as in v1: the leader holds the effects, and a new + leader starts with a full fetch. + +## Published targets + +If a plugin can enumerate targets (`supports_listing` on a target scheme), an action with +`publish_targets: true` publishes them to the API: + +1. On startup and every `targets_refresh`, the agent calls the plugin's `ListTargets` for each + scheme of the action. +2. It keeps only identities allowed by the action's `targets` (`include` minus `exclude`), up + to a cap (default 5,000 per action), and marks the list `truncated` beyond it. +3. It sends the list with `PUT /api/agent/instances/{instanceId}/targets` + ([wire interface](wire-interface.md#published-targets)). + +Publishing is off by default because it sends provider names (channels, repositories) to the +API. A target missing from the list can still be used: the list helps the rule builder; it +isn't a check. + +## Validation + +```mermaid +flowchart TD + A["1. Agent startup / overlay apply"] --> A1["Config file schema, plugin types"] + A1 --> A2["Fetch plugins, verify trusted_sources and digests"] + A2 --> A3["Dispense the service plugins.p.type names;
Describe() for effectors"] + A3 --> A4["Configure(): plugin config valid"] + A4 --> A5["For each action: effect declared by the plugin,
target schemes declared by the plugin,
ValidateAction(config) passes, name unique in the agent"] + A5 -->|"failure at startup: exit non-zero
failure on overlay: revision rejected, report sent"| X1["Not applied"] + A5 --> B["2. Registration (API)"] + B --> B1["Well-formed effects and rule kinds,
valid patterns and value formats"] + B1 -->|"422"| X2["Agent logs and retries with backoff"] + B1 --> C["3. Rule saved (API)"] + C --> C1["Agent and action exist, target allowed,
effect fits the rule kind, author can read the source"] + C1 -->|"422 / 403"| X3["Rule admin fixes the rule"] + C1 --> D["4. Delivery (agent)"] + D --> D1["Signature, timestamp, webhook-id,
action exists, target allowed, generation"] + D1 -->|"401/403/409"| X4["Rejected, reported"] + D1 --> OK["Plugin Apply / Clear with the action's config"] +``` + +An overlay that fails step 1 is rejected like any other invalid overlay: the running +configuration stays, and the rejection is reported with a reason. A new +`ccf-agent validate --config agent.yaml` subcommand would run step 1 without starting +anything, for CI. + +## Plugin contract + +Effector plugins use the same mechanism as collector plugins: hashicorp go-plugin over gRPC, +with the agent serving helper services to the plugin through the go-plugin broker. Collector +plugins get `ApiHelper` today. **Effector plugins get only an `EffectorHelper`**, never the +`ApiHelper`. + +The services are summarized here. The full messages, how status flows back, timeouts, +concurrency, retries, and how the agent runs plugins and its listener are in +[plugin runtime](plugin-runtime.md). + +```proto +syntax = "proto3"; +package ccf.effector.v1; + +service Effector { + // What the plugin can do. Called once at startup; also tells the agent this is an effector. + rpc Describe(DescribeRequest) returns (Manifest); + + // Plugin config (credentials, connection). Validate and connect. + rpc Configure(ConfigureRequest) returns (ConfigureResponse); + + // Validate one action's config. Called at startup and on overlay apply, for every action. + rpc ValidateAction(ValidateActionRequest) returns (ValidateActionResponse); + + // Make the provider reflect an active (or occurred) effect. The request carries the effect + // document (transition, last applied status and refs) and the action's config. + // Idempotent per generation. + rpc Apply(ApplyRequest) returns (ApplyResponse); + + // Revert or resolve an inactive effect, following the action's on_clear. Idempotent. + rpc Clear(ClearRequest) returns (ClearResponse); + + // Converge on all of this plugin's effects. Called after a fetch and every reconcile_interval. + rpc Reconcile(ReconcileRequest) returns (ReconcileResponse); + + // An inbound provider webhook routed by the agent (/ext/{plugin}/...). + rpc HandleExternal(ExternalRequest) returns (ExternalResponse); + + // Optional: list identities of a scheme, for published targets. + rpc ListTargets(ListTargetsRequest) returns (stream ListedTarget); +} + +// Served by the agent to effector plugins only. Effector plugins never get ApiHelper +// (CreateEvidence, UpsertRiskTemplates, UpsertSubjectTemplates). +service EffectorHelper { + rpc ListEffects(ListEffectsRequest) returns (ListEffectsResponse); // from the agent's memory + rpc ReportStatus(ReportStatusRequest) returns (ReportStatusResponse); // status + refs, stored in the API + rpc Observe(ObserveRequest) returns (ObserveResponse); + rpc GetContext(GetContextRequest) returns (GetContextResponse); // proxies the API context route +} + +message Manifest { + string name = 1; + string version = 2; + repeated Capability capabilities = 3; + bytes plugin_config_schema = 4; // JSON Schema, for docs and `validate` + repeated string external_routes = 5; // e.g. "github" → /ext/github-checks/github +} + +message Capability { + string effect = 1; // plugin-declared label, e.g. notify, block, remediate-apply + string default_on_clear = 2; // revert | resolve | none + repeated string rule_kinds = 3; // state | event + repeated TargetScheme target_schemes = 4; + bytes action_config_schema = 5; // JSON Schema, for docs and `validate` + bool supports_exceptions = 6; + repeated ObservationType observations = 7; +} + +message TargetScheme { + string name = 1; // e.g. github-repo, slack-channel + string value_pattern = 2; // RE2 regular expression the value must match + string description = 3; + string example = 4; + bool supports_listing = 5; +} + +message ObservationType { + string type = 1; // plugin's own label + string kind = 2; // exception-request | dismissed | notice +} + +message ListedTarget { + string value = 1; + string label = 2; +} +``` + +### No evidence from effectors + +Effector plugins **can't produce evidence**, by design. Collector plugins observe a system and +report evidence; effector plugins act on it. If an effector could report evidence, it could +report on the results of its own actions, and the chain from observation to rule to effect +would no longer be one-directional. + +The agent enforces this: an effector plugin runs in the effector context, which serves only +`EffectorHelper`. It has no `ApiHelper`, so no `CreateEvidence`, `UpsertRiskTemplates` or +`UpsertSubjectTemplates`. A binary declared as `type: effector` that asks for `ApiHelper` +gets nothing. Whether an action worked is shown by the next collection. What an effector +sees that a person should know about (a bypass, a rejected fix) goes back as an observation. + +### Rules for plugin authors + +- `Apply`, `Clear` and `Reconcile` must be **idempotent**. The agent may call them again for + the same generation after a restart or a retry. +- Keep provider state (message IDs, check run IDs, PR numbers) in the `refs` of + `ReportStatus`. They're stored in the API and come back with the effect; there's no local + storage. +- Report `links` for people (the message, the pull request, the settings page), and use + `waiting` once the result is in a person's hands, so the effect view can show what's + pending and since when ([status](wire-interface.md#status)). +- Handle every transition `Apply` can receive, including `repeated` (the rule asked to act + again: a reminder, a re-assert, a retry) and `finished` (no more repeats; the condition + still holds, so this isn't a clear). +- Validate a target's existence in the provider at `Apply`, and report `failed` with a clear + message. Format checks already happened in the API and the agent. +- Never decide policy: report an observation and let the API decide. +- Answer `HandleExternal` from `ListEffects` (the agent's memory), not by calling the API. + +### Lifecycle + +| Situation | Agent does | +| --- | --- | +| Startup | Load config, start plugins, `Describe`, `Configure`, `ValidateAction`, register effector actions, fetch effects, `Reconcile` | +| Delivery | Check, update the effect in memory, queue `Apply` or `Clear` | +| Plugin crash | Restart it with backoff, replay the current effect for each of its effects | +| Resync | Fetch all effects again from the API, replace memory, `Reconcile` per plugin | +| No API contact past `stale_after` | Apply each action's `on_stale`: `keep` changes nothing, `fail-open` clears state effects (for example unblocks), `fail-closed` leaves blocks and blocks targets with no known effect | +| Overlay applied | Re-register. A rule action turns `degraded` once no fresh instance of the agent registers its action | +| Shutdown | Stop accepting webhooks (`503`), let in-flight calls finish | + +## Decisions + +1. **Agent, not a separate binary.** Effectors are the agent with effector plugins + (`plugins.

.type: effector`). Authentication, remote configuration, plugin loading and + config reporting come from the agent. +2. **Remote configuration** extends to effector settings, with the classification above. +3. **Action config visibility** comes from the agent's config report (masked), as for + plugin config today. +4. **No local store.** The API stores effects and plugin refs; the agent keeps them in memory. +5. **Accounts** are the plugin's business. +6. **Plugin types** are `collector` (default) and `effector`. +7. **No evidence from effectors.** Effector plugins get no `ApiHelper` + ([above](#no-evidence-from-effectors)). +8. **One replica in v1.** Multiple replicas come with agent-wide leader election in v2 + ([above](#multiple-instances)). v1 builds no change feed or other multi-pod machinery. +9. **Remote config classification** as proposed, with widening changes forbidden in every + mode; to be revisited after trying it. +10. **Effect types are plugin-declared.** No fixed list in the API; it validates rules only + against each action's registered rule kinds and `on_clear`. +11. **Target patterns** follow one grammar, implemented in one public package + ([above](#target-pattern-grammar)). + +## Open questions + +None at the moment. diff --git a/docs/effectors/events-and-states.md b/docs/effectors/events-and-states.md new file mode 100644 index 00000000..309d28bf --- /dev/null +++ b/docs/effectors/events-and-states.md @@ -0,0 +1,244 @@ +# Events and states reference + +Every state a rule can test and every event a rule can react to, with **how the API +computes it** and where in the code it comes from. [Triggers](triggers.md) explains how +rules use them; this document is the list. + +Status: **proposal**. Phase 1 needs only the evidence source; the other sources come in +phase 2 ([phasing](operations.md#phasing)). Items marked *later* aren't needed in either. + +## Summary + +| Source | States (for `when`) | Events (for `on`) | +| --- | --- | --- | +| `evidence` | `status` | `evidence.stream-started`, `evidence.status-changed` | +| `risk` | `status`, `score`, `review_deadline` | `risk.created`, `risk.status-changed`, `risk.accepted`, `risk.reviewed`, `risk.score-changed`, `risk.deleted`; *later*: link events | +| `workflow-execution` | `status` | `workflow.execution.status-changed` | +| `workflow-step` | `status`, `assignee` | `workflow.step.status-changed`, `workflow.step.assigned`, `workflow.step.reassigned` | +| `ssp` | `controls[].posture`, `controls[].implementation_status`, `posture_counts` | `ssp.control.posture-changed`, `ssp.changed` | +| `catalog` | `active` (no state rules) | `catalog.created`, `catalog.deleted`, `catalog.activated`, `catalog.deactivated`, `catalog.control.added`, `catalog.control.changed`, `catalog.control.removed` | + +## How producers emit + +Every event below is written by its **producer**, in the same transaction as the change, +into the outbox ([pipeline](triggers.md#pipeline)). Two producers aren't sources of their own: filter +changes write `filter.changed` so rules that use `matches_filter` re-evaluate +([filters](triggers.md#filters)), and the SSP recompute job writes the derived SSP events. Each producer also writes a +`.subject-changed` notice, which is what makes state rules re-evaluate. Producers +are the places in the code where the change already happens; the table under each source +names them. + +Every event document has these fields, plus the source-specific ones: + +| Field | Type | Meaning | +| --- | --- | --- | +| `type` | string | For example `risk.status-changed` | +| `occurred_at` | timestamp | When the change was committed | +| `actor` | `{kind: user \| agent \| effector \| system, id?}` | Who caused it, when known | +| `subject_id` | string | The subject the event is about | + +`from`/`to` events are only emitted when the value actually changed. Writing the same +status again emits nothing. + +## `evidence` + +**Subject:** an evidence stream (all evidence with the same stream UUID), represented by its +latest evidence, the one with the greatest `end`. + +### States + +| Field | Values | Computed from | +| --- | --- | --- | +| `status` | `satisfied`, `not-satisfied` | `Status.Data().State` (OSCAL objective status) of the stream's latest evidence | +| `expires` | timestamp, optional | The latest evidence's `expires` | +| `end` | timestamp | The latest evidence's `end`. `now - subject.end` is how long since the stream last reported | + +There's no stored "stale" state: rules compare `expires` or `end` with `now`, and the timer +mechanism re-evaluates them ([timers](triggers.md#timers)). + +### Events + +| Event | Emitted when | How it's computed | Event fields | +| --- | --- | --- | --- | +| `evidence.stream-started` | The first evidence of a stream is stored | Ingest finds no previous evidence for the stream UUID | `status` | +| `evidence.status-changed` | A stream's latest status differs from the previous latest | Ingest reads the stream's current latest status before inserting. If the new evidence becomes the latest (greater `end`) and its status differs, emit | `from`, `to` | + +Evidence that arrives late (an `end` older than the current latest) doesn't change the +latest, so it emits nothing. + +**Producers:** single ingest (`POST /api/evidence`) and the batch ingest worker +(`internal/service/worker/evidence_batch_worker.go`). A batch emits at most one event per +stream: the first `from` and the last `to`, and nothing if they're equal. Every ingest also +writes `evidence.subject-changed` for each stream it touched, since `end` changes on every run +([when a subject counts as changed](triggers.md#when-a-subject-counts-as-changed)). + +## `risk` + +**Subject:** a risk. + +### States + +| Field | Values | Computed from | +| --- | --- | --- | +| `status` | `open`, `investigating`, `mitigating-planned`, `mitigating-implemented`, `risk-accepted`, `remediated`, `closed` | `Risk.Status` (`internal/service/relational/risks/models.go`) | +| `likelihood`, `impact` | risk level, optional | `Risk.Likelihood`, `Risk.Impact` | +| `score` | int, optional | `NumericalRiskScore` (`risks/scores.go`): likelihood rank × impact rank, 1–25. Absent when either is unset | +| `review_deadline` | timestamp, optional | `Risk.ReviewDeadline` | + +### Events + +Risks already keep an event log, the `risk_events` table. Most rule events correspond to a +`risk_events` type, and are written to the outbox **next to** that row, by the same code. The +writers of `risk_events` today are `RiskService.logRiskEvent` and `logRiskEventWithSnapshot`, +the leverage drift handlers (`emitLeverageDriftRiskEvent`), and the risk-evidence worker +(`internal/service/worker/risk_evidence_worker.go`). All of them have to write the outbox row +too; a shared helper keeps that in one place. + +`risk.deleted` is the exception: deleting a risk writes a score snapshot but no `risk_events` +row, and the risk's event rows are deleted with it. `RiskService.Delete` writes +`risk.deleted` to the outbox itself, with the risk's last subject document, before the rows go. + +| Event | Corresponding `risk_events` type | Event fields | +| --- | --- | --- | +| `risk.created` | `created` | `status` | +| `risk.status-changed` | `status_changed` | `from`, `to` | +| `risk.accepted` | `accepted` | `accepted_until?`, `justification?` | +| `risk.reviewed` | `reviewed` | `next_review_deadline?` | +| `risk.score-changed` | `score_updated`, `score_reassessed` | `from`, `to` | +| `risk.deleted` | none (written by `RiskService.Delete`) | — (`subject` is the risk as it was) | +| *later* `risk.linked`, `risk.unlinked` | `evidence_linked`, `control_linked`, `component_linked`, `subject_linked`, `threat_linked` and their `*_unlinked` | `kind` (evidence, control, …), `id` | + +`last_seen`, `remediation_created` and `threat_updated` aren't exposed in v1. + +## `workflow-execution` and `workflow-step` + +**Subjects:** a workflow execution; a step execution (which also carries its execution's +fields as `subject.execution`). + +### States + +| Source | Field | Values | Computed from | +| --- | --- | --- | --- | +| `workflow-execution` | `status` | `pending`, `in_progress`, `overdue`, `completed`, `failed`, `cancelled` | `WorkflowExecution.Status` | +| `workflow-step` | `status` | `pending`, `blocked`, `in_progress`, `overdue`, `completed`, `failed`, `skipped`, `cancelled` | `StepExecution.Status`. `cancelled` is set when the execution is cancelled (`Manager.CancelExecution`) | +| `workflow-step` | `assignee` | `{kind: user \| group \| email, id?, email?, slack_user_id?}` | The step's assignment; `slack_user_id` from the user's linked Slack account | + +`overdue` is already a stored status, set by the overdue checker (`internal/workflow/overdue.go`), +so rules don't need to compute it. + +### Events + +| Event | Emitted when | Event fields | +| --- | --- | --- | +| `workflow.execution.status-changed` | An execution's status changes | `from`, `to` | +| `workflow.step.status-changed` | A step's status changes | `from`, `to`, `reason?` (for `failed`) | +| `workflow.step.assigned` | A step gets its first assignee | `assignee` | +| `workflow.step.reassigned` | A step's assignee changes | `from`, `to` | + +**Producers:** status changes go through `WorkflowExecutionService.UpdateStatus` and +`StepExecutionService.UpdateStatus`, and the helpers that use them (`Start`, `Complete`, +`Fail`, `Block`, `Unblock`), plus `BulkFailWithTx`, cancellation (`Manager.CancelExecution`, +which also cancels steps) and the overdue checker. Assignment goes +through `StepExecutionService.AssignTo` and `ReassignWithTx`. Emitting in those few methods +covers every path. + +## `ssp` + +**Subject:** an SSP. Its control fields are **derived**: no single write changes them, so a +derived job computes them ([cascades](triggers.md#cascades)). + +### States + +| Field | Values | Computed from | +| --- | --- | --- | +| `controls[]` | one entry per control in the SSP's profiles | The SSP's profiles, resolved (an SSP can import several) | +| `controls[].posture` | `satisfied`, `not-satisfied`, `inherited`, `not-applicable`, `planned`, `attention` | The lineage posture ladder (constants in `internal/api/handler/lineage.go`), minus `out-of-scope`, since controls outside the profiles aren't listed: decisive evidence wins (`not-satisfied` over `satisfied`); otherwise the implementation status decides (`not-applicable`, `planned`, or `attention` when nothing explains the gap). `inherited` when a leveraged authorization covers it | +| `controls[].implementation_status` | OSCAL implementation status, when uniform across the control's components | The same input the lineage view uses | +| `posture_counts` | `map(string, int)`, keyed by posture | Counts over `controls`. Always has every posture as a key (0 when none), so expressions can index it safely. Rules compute ratios themselves, for example `posture_counts["satisfied"] * 100 / size(subject.controls)` | + +The ladder has to move from the lineage handler into a service, so the HTTP view and the +derived job use one definition. + +### Events + +| Event | Emitted when | How it's computed | Event fields | +| --- | --- | --- | --- | +| `ssp.control.posture-changed` | One control's posture changed | `ssp.recompute` compares each control's new posture with the stored projection | `control_id`, `catalog_id`, `from`, `to` | +| `ssp.changed` | Any field of the SSP's subject document changed | `ssp.recompute` compares the new document with the stored projection | `changed_fields` (top-level field names) | + +**Producer:** the `ssp.recompute` job. It runs for an SSP when anything its posture depends +on changes: evidence matching the SSP's scope or filters, its risks, its implemented +requirements, its profile, control links, leveraged authorizations. It stores the projection +it computed, so the next run can diff against it. + +## `catalog` + +**Subject:** a catalog. A catalog has no failing or passing state, so it only supports event +rules. + +### States + +| Field | Values | Computed from | +| --- | --- | --- | +| `active` | bool | `Catalog.Active` | + +### Events + +| Event | Emitted when | Event fields | +| --- | --- | --- | +| `catalog.created` | A catalog is created or imported for the first time | — | +| `catalog.deleted` | A catalog is deleted | — | +| `catalog.activated`, `catalog.deactivated` | `active` changes | — | +| `catalog.control.added` | A control ID exists after the change and didn't before | `control` | +| `catalog.control.changed` | A control ID exists before and after, and its content differs | `control`, `changed_fields` | +| `catalog.control.removed` | A control ID existed before and doesn't after | `control` (as it was) | + +`control` is `{id, title, group_id?, parent_id?, used_by_ssps: list(string)}`. + +**How control changes are computed.** Catalog writes can touch one control +(`POST`/`PUT /api/oscal/catalogs/{id}/controls/...`) or the whole catalog +(`PUT /api/oscal/catalogs/{id}`, `oscal import` from the CLI). All of them go through one +**diff** in the same transaction: + +```mermaid +flowchart LR + B["Load the catalog's controls
before the write"] --> W["Apply the write"] + W --> A["Load the controls after"] + A --> D{"Match by control ID"} + D -->|"only after"| AD["catalog.control.added"] + D -->|"only before"| RM["catalog.control.removed"] + D -->|"both, canonical form differs"| CH["catalog.control.changed
changed_fields"] + D -->|"both, same"| NO["nothing"] +``` + +- Controls are compared in a **canonical form**: OSCAL JSON with sorted keys and without + fields that change on every save (internal IDs, timestamps). +- `changed_fields` lists the top-level OSCAL control fields that differ: `title`, `class`, + `params`, `props`, `links`, `parts`, `controls` (sub-controls), plus `group` when the control + moved. +- A renamed control ID is a `removed` plus an `added`: the ID is the only identity a control + has. +- `used_by_ssps` is computed when the event is emitted: SSPs whose resolved profiles include + the control. + +Replacing a large catalog can emit thousands of `catalog.control.*` events, and v1 has no +event batching: an event rule fires once per control. Rules should narrow with `if` (for +example only controls used by an SSP). + +**Producers:** the catalog write handlers (`internal/api/handler/oscal/catalogs.go`: catalog, +group and control create, update, delete and activation) and the `oscal import` command. + +## Decisions + +1. **Catalog versions** in phase 2: `catalog.control.changed` compares stored revisions. +2. **`control` and `profile` sources** in phase 2 ([triggers](triggers.md#phase-2-control-and-profile)). + +## Open questions + +1. **Late evidence.** Should evidence with an older `end` than the current latest ever + change the stream's state (for example when the latest was recorded by mistake)? +2. **Risk link events.** Are `risk.linked` / `risk.unlinked` needed in v1? +3. **SSP recompute scope.** Recomputing an SSP's posture on every matching evidence change + could be expensive for large SSPs. Debounce per SSP (for example at most once a minute)? +4. **Catalog canonical form.** Which fields are volatile and excluded from the diff? This + needs a look at what catalog updates rewrite today. diff --git a/docs/effectors/operations.md b/docs/effectors/operations.md new file mode 100644 index 00000000..001519fb --- /dev/null +++ b/docs/effectors/operations.md @@ -0,0 +1,132 @@ +# Operations + +Running effectors in production: what fails and how, what to watch, how this relates to the +existing notification system, and the order to build it in. + +## Failure modes + +| Failure | What happens | Visible as | +| --- | --- | --- | +| Effector unreachable | Deliveries retry for 24h. Whatever was applied last stays in place: a block stays, a cleared effect stays cleared | Effect `applied: unknown`; instance `stale`, then `offline`; admins notified | +| Effector loses the API | After `stale-after`, each action's `on-stale` applies: `keep`, `fail-open` (clear state effects) or `fail-closed` | Host logs and metrics; the API sees missed heartbeats | +| Missed or reordered webhooks | Each webhook carries the whole document, older generations are dropped, heartbeat digests trigger resync | Digest mismatch count | +| Plugin crash | The agent restarts it and replays the current effect document for each of its effects | Plugin restart count | +| Provider rejects a call (rate limit, permission) | Plugin reports `failed`; the agent retries with backoff | Effect `failed` with the provider's message | +| Effector action removed (config change) | Rule actions using it become `degraded`; effects are kept and redelivered when the action returns or the rule action is pointed at another effector | Rule shows a degraded action | +| Rule flaps | Rate limit per rule and target; any effect that flaps stops being redelivered | Rule paused for that target; admins notified | +| A human rejects a plugin's result in the provider | Effect `dismissed`, not retried | Decision queue item | +| API down | Nothing new is evaluated or delivered; agents keep the last state in memory and answer provider events from it | API health | + +## What to watch + +**API:** + +- Effects by state and by applied status, per rule and per effector. +- Desired vs applied lag: time between a generation being created and reported `applied`. +- Delivery attempts, failures and retries pending, per effector. +- Outbox depth and dispatch lag (time from a domain event to its effects). +- Rules paused by rate limiting; flapping effects. +- Effects in `waiting` and for how long (remediations stuck on a review). + +**Agent** (Prometheus metrics, for its effector side): + +- Deliveries received, rejected (by reason: signature, unknown action, target mismatch, stale generation). +- Plugin calls by plugin, method and result; latency. +- Effects held in memory per plugin; time since the last successful fetch from the API. + +The UI shows desired vs applied per effect. That's the first place to look when someone asks +"why is this still blocked?". + +## High availability + +v1 supports **one replica** per agent with effector plugins. The agent keeps no effector +state of its own, so a restart only needs a fetch and a `Reconcile`. More replicas come with +leader election in v2; v1 builds no multi-pod machinery (no change feed). See +[multiple instances](effector-interface.md#multiple-instances). + +For regions or separate failure domains, run several agents with the same effector actions; +each rule action names the agent it uses. + +Agent-wide leader election (a lease held in the CCF API, with fencing) is a v2 goal. It would +also stop several collector pods from sending the same evidence. See +[effector interface](effector-interface.md#later-v2-leader-election). + +## Deployment + +- No new deployable: effectors are agents. The agent's Helm chart gets **opt-in** values for + the `effector` block, effector plugins and the listener's Service/Ingress. Nothing changes + for an existing install until they're turned on. +- Customers who want credentials kept away from the API cluster run the agent in their own + environment, as they already do for collection. +- A new `ccf-agent validate` subcommand in CI catches config errors before deployment. + +## Retention + +| Data | Kept | +| --- | --- | +| Rules, rule actions, and each effect's **current** state (generation, desired state, last applied status and refs) | As long as the rule action and the effect exist | +| Effect **history** (past generations and transitions), **deliveries** (webhook attempts) and decided **observations** | **24 hours**, then pruned by a periodic River job | + +The effect views show the last 24 hours of history and deliveries. That's enough to debug +"why is this still blocked?"; it isn't a long-term audit log. + +## Relationship to notifications + +| | Notifications (existing) | Rules with a `notify` action (new) | +| --- | --- | --- | +| Triggered by | Workflow and system events: task assigned, digests, workflow execution failed, POA&M due | A rule on evidence, risk, workflow, SSP or catalog state or events | +| Configured by | Each user (subscriptions) and admins (system destinations) | Rule admins | +| Delivered by | The API (email, Slack) | An effector plugin | +| Resolves when fixed | No | Yes, for state rules | + +They coexist, and **nothing migrates**. Existing notifications stay exactly as they are. +Effectors only add new, rule-driven notifications. + +## Phasing + +```mermaid +flowchart LR + P1["Phase 1
Evidence source, end to end"] --> P2["Phase 2
More sources
(mostly API)"] + P2 --> P3["Phase 3
More effect types
(mostly plugins)"] +``` + +| Phase | API | Agent and plugins | Delivers | +| --- | --- | --- | --- | +| 1 | Outbox; CEL environment and validation; the **evidence** source; rules and effects routes and their permissions; registration (with instance rows), verification, delivery, and the heartbeat response; effector actions; preview; retention | `type: effector` plugins as long-lived processes, `effector` block and listener (webhooks, health, readiness, metrics), config validation and remote config classification, plugin contract; the **Slack** plugin (`notify`) to prove it, and the effector plugin template | Evidence rules, end to end. The "evidence failed → Slack" request | +| 2 | **Risk**, **workflow** (`workflow-execution`, `workflow-step`), **SSP**, **catalog** (with stored versions), **control** and **profile** sources: subject documents, producers, events, and as many derived and aggregate fields as possible | — | Rules on every source | +| 3 | What new effect types need from the API: observations, decisions and exceptions; the context route; published targets | Plugins for more effect types (for example `block`, `remediate-propose`, `remediate-apply`); external ingress (`HandleExternal`) and `ListTargets` in the agent | More effect types | + +Each phase includes the UI (rule builder, effect views) in the `ui` repository. + +## Implementation map + +Following the repository's conventions (`AGENTS.md`): + +| Change | Where | +| --- | --- | +| New models: `AgentEffector` (per agent: admin-set base URL, verification status), `AgentEffectorInstance` (per instance: registered actions, revision), `EffectorAction`, `Rule`, `RuleAction`, `Effect`, `EffectHistory`, `EffectDelivery`, `EffectObservation`, `DomainEvent` | `internal/service/relational/…`, added to both AutoMigrate lists (`internal/service/migrator.go`, `internal/tests/migrate.go`) | +| New authz resources and actions: `rule` (`read`, `create`, `update`, `delete`), `effect` (`decide`); agent effector routes reuse `agent:sync` | `internal/authz/pdp.go`, `internal/authz/manifest.yaml`, Cedar policies only | +| Effector routes under `/api/agent/` with the existing agent JWT middleware (strict, like config sync) | `internal/api/handler/api.go` | +| Routes (with swag annotations, then `make swag`) | `internal/api/handler/rules.go`, `effects.go`, `effector.go`, registered in `api.go` | +| CEL environment per source (declared subject and event types, member functions), served by `GET /api/rules/sources`; new dependency `cel-go` | `internal/service/rules/` | +| River jobs: `domain-events.dispatch`, `rules.evaluate`, `rules.sweep`, `effects.deliver`, `effects.prune` (24-hour retention), `ssp.recompute` | `internal/service/worker/` | +| Producers writing domain events | evidence ingest, risk service, workflow services, catalog handlers | +| Shared config model: `effector` block, plugin `type`, `actions`, and their remote config classification | `pkg/agentconfig` (public: the agent imports it; backwards compatible, rc tag, then bump the agent) | +| Delivery signing key settings `CCF_EFFECTOR_SIGNING_KEY` and `CCF_EFFECTOR_SIGNING_KEY_NEXT` (one key pair for the API), and `CCF_EFFECTOR_ALLOW_INSECURE_WEBHOOKS` for local development | `internal/config/`, listed in `.env.example` | +| Heartbeat: an `effector` block in the request and a response body (today it answers `201` with none) | `internal/api/handler/heartbeat.go` | +| Go client for the effector routes, and a new heartbeat method that returns the response (the existing `Create` keeps discarding it) | `sdk/` (public, so backwards compatible) | +| Effector registration upserts `AgentInstance` rows, and fails at the instance cap instead of skipping | `internal/service/relational/agentcfg/` | +| Target pattern grammar, shared with the agent | a new public package, for example `pkg/effector/targets` | +| Agent: plugin `type`, effector plugin runtime ([plugin runtime](plugin-runtime.md)), listener and metrics, registration, `validate` subcommand | `compliance-framework/agent`, separate PR after the API's rc | + +## Decisions + +1. **Retention:** effect history, deliveries and decided observations are kept 24 hours. +2. **Helm:** effector settings in the agent chart are opt-in. +3. **Notifications:** nothing migrates; effectors only add new notifications. +4. **Phases:** evidence first, end to end; then the other sources (mostly API); then more + effect types (mostly plugins). + +## Open questions + +None at the moment. diff --git a/docs/effectors/plugin-runtime.md b/docs/effectors/plugin-runtime.md new file mode 100644 index 00000000..efdf1f6d --- /dev/null +++ b/docs/effectors/plugin-runtime.md @@ -0,0 +1,246 @@ +# Plugin runtime + +How the agent runs effector plugins: their processes, the HTTP listener, the gRPC messages, +how results flow back, timeouts, ordering and retries. [Effector interface](effector-interface.md) +covers configuration and the overall contract; this document is what an agent implementation +and a plugin template need to agree on. + +## What the agent has to add + +The agent runs collector plugins differently from what effectors need: + +| | Collector plugins today | Effector plugins | +| --- | --- | --- | +| Process | Started for one scheduled run and torn down after it (`getRunnerInstance` + `defer cleanupRunner` in `cmd/agent.go`) | **Long-lived**: started at boot, kept running, restarted if they crash | +| Triggered by | The scheduler | Deliveries from the API, provider webhooks, reconcile timers | +| Network | Outbound calls only; no listener | An HTTP **listener** for deliveries, provider webhooks, health and metrics | +| Helper | `ApiHelper` | `EffectorHelper` only | +| Agent mode | Daemon or one-shot | **Daemon only.** An agent with `daemon: false` and an enabled effector plugin refuses to start | + +## Processes + +- One plugin process per enabled effector plugin entry, started when the agent starts (or + when an overlay enables it), dispensed as the `effector` go-plugin service. +- The agent supervises it: a crash or a failed go-plugin ping restarts it with backoff + (1s doubling up to 1m). After a restart the agent runs `Configure` and `ValidateAction` + again, then replays the current effect for each of the plugin's effects (`Apply` or + `Clear`), then `Reconcile`. +- While a plugin is down, deliveries for its actions are answered `503`, so the API retries + them. + +## The listener + +The `effector` block's `listen` address serves, under the agent's base URL: + +| Path | Purpose | +| --- | --- | +| `POST /v1/webhook` | Deliveries from the API. Checked (signature, timestamp, `webhook-id`, action, target, generation), then queued; answered `202` | +| `POST /ext/{plugin}/{route}` | Provider webhooks, passed to the plugin's `HandleExternal` for routes it declared | +| `GET /healthz` | `200` while the agent process is up | +| `GET /readyz` | `200` once the agent has registered, its URL is verified, every plugin is configured, and the first fetch of effects has completed. `503` before that and during shutdown | +| `GET /metrics` | Prometheus metrics (below). New for the agent, which exports none today | + +Metrics: deliveries received and rejected (by reason), plugin calls by plugin, method and +result, call latency, effects held per plugin, time since the last successful API contact, +plugin restarts. + +## Messages + +```proto +syntax = "proto3"; +package ccf.effector.v1; + +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; + +service Effector { + rpc Describe(DescribeRequest) returns (Manifest); + rpc Configure(ConfigureRequest) returns (ConfigureResponse); + rpc ValidateAction(ValidateActionRequest) returns (ValidateActionResponse); + rpc Apply(EffectRequest) returns (Result); + rpc Clear(EffectRequest) returns (Result); + rpc Reconcile(ReconcileRequest) returns (ReconcileResponse); + rpc HandleExternal(ExternalRequest) returns (ExternalResponse); + rpc ListTargets(ListTargetsRequest) returns (stream ListedTarget); +} + +service EffectorHelper { + rpc ListEffects(ListEffectsRequest) returns (ListEffectsResponse); + rpc ReportStatus(ReportStatusRequest) returns (ReportStatusResponse); + rpc Observe(ObserveRequest) returns (ObserveResponse); + rpc GetContext(GetContextRequest) returns (GetContextResponse); +} + +message DescribeRequest {} +// Manifest, Capability, TargetScheme, ObservationType, ListedTarget: see effector-interface.md. + +message ConfigureRequest { + google.protobuf.Struct config = 1; // plugins.

.config, placeholders resolved + uint32 helper_broker_id = 2; // go-plugin broker ID of EffectorHelper +} +message ConfigureResponse {} // errors are gRPC InvalidArgument with a message + +message ValidateActionRequest { + string action = 1; + string effect = 2; + google.protobuf.Struct config = 3; // plugins.

.actions..config +} +message ValidateActionResponse { + repeated string errors = 1; // empty means valid +} + +message EffectRequest { + string action = 1; // the effector action + google.protobuf.Struct action_config = 2; + bytes effect_document = 3; // the effect document from the API, as JSON +} + +message Result { + string status = 1; // in-progress | waiting | applied | failed | dismissed + string message = 2; + repeated Link links = 3; + google.protobuf.Struct refs = 4; +} + +message Link { + string rel = 1; + string href = 2; + string title = 3; +} + +message ReconcileRequest { + repeated EffectRequest effects = 1; // every effect this plugin's actions hold +} +message ReconcileResponse { + repeated ReconcileOutcome outcomes = 1; +} +message ReconcileOutcome { + string effect_id = 1; + Result result = 2; // only for effects whose state the plugin changed +} + +message ExternalRequest { + string route = 1; // declared in Manifest.external_routes + map headers = 2; + bytes body = 3; +} +message ExternalResponse { + int32 http_status = 1; + bytes body = 2; +} + +message ListTargetsRequest { + string scheme = 1; +} + +message ListEffectsRequest { + string action = 1; // optional filter + string target = 2; // optional filter (identity) +} +message ListEffectsResponse { + repeated EffectRequest effects = 1; +} + +message ReportStatusRequest { + string effect_id = 1; + uint64 generation = 2; + Result result = 3; +} +message ReportStatusResponse {} + +message ObserveRequest { + string effect_id = 1; + uint64 generation = 2; + string type = 3; + string ref = 4; + string summary = 5; + google.protobuf.Struct data = 6; +} +message ObserveResponse {} + +message GetContextRequest { + string effect_id = 1; + string page_token = 2; +} +message GetContextResponse { + bytes context = 1; // the API's context response, as JSON + string next_page_token = 2; +} +``` + +## How results flow back + +- `Apply` and `Clear` **return** a `Result`. The agent sends it to the API as that + generation's status (`PUT /api/agent/effects/{id}/status`). +- Work that outlives the call (a pull request awaiting review) returns `in-progress` or + `waiting`, and later calls `EffectorHelper.ReportStatus` for the same generation as things + change (`waiting`, `applied`, `dismissed`). The agent forwards each one. +- `Reconcile` returns outcomes only for effects whose state it changed; the agent forwards + those too. +- A report for an older generation than the agent holds is dropped by the agent. +- The API merges `refs` key by key and keeps them across reports and generations; `null` + removes a key ([status](wire-interface.md#status)). A plugin that keeps one provider + object per subject (one Slack message per stream) can key its refs by subject ID. + +## Timeouts + +| Call | Default | Override | +| --- | --- | --- | +| `Configure`, `ValidateAction` | 30s | — | +| `Apply`, `Clear` | 60s | `plugins.

.apply_timeout` | +| `Reconcile` | 10m | `plugins.

.reconcile_timeout` | +| `HandleExternal` | 10s | — (providers expect a quick answer) | + +A call that times out counts as a `failed` result with the message `timeout`. + +## Concurrency and ordering + +- **Per effect, one call at a time.** The agent never runs two calls for the same effect + concurrently. +- **Newest generation wins.** If a newer generation arrives while an older one is queued, the + older one is dropped. If one arrives while an older one is running, it runs next. +- **Across effects, in parallel**, up to `plugins.

.max_concurrency` (default 4) calls per + plugin. +- `Reconcile` doesn't run while calls for the same plugin are in flight, and vice versa. + +## Retries + +- A `failed` result from `Apply` or `Clear` is retried by the agent with exponential backoff + (30s, doubling, up to 1h between tries), for the same generation, until it succeeds or a + newer generation replaces it. Each failure is reported, so the effect view shows it. +- `Reconcile` also retries failed effects whenever it runs. + +## Startup + +1. Start and configure every effector plugin (`Describe`, `Configure`, `ValidateAction`). +2. Register (`PUT /api/agent/instances/{instanceId}/effector`). +3. Fetch every effect (`GET /api/agent/effects`, all pages) into memory. +4. For each effect whose `applied.generation` is missing or older than its `generation`, call + `Apply` (active, finished, occurred) or `Clear` (inactive). +5. Run `Reconcile` per plugin. +6. Report ready (`/readyz`). + +Deliveries that arrive before step 6 are accepted and queued; they're processed after step 4. + +## Configuration changes + +The `effector` block can't change at runtime (it's forbidden in overlays), so the listener +keeps running through any applied configuration change. For each plugin whose source, config +or actions changed: + +1. Stop starting new calls for it; queue its deliveries. +2. Let in-flight calls finish, up to their timeout. +3. Restart the plugin if its source or config changed; otherwise only re-run `ValidateAction`. +4. Re-register, so the API sees the new action set. +5. Resume: process the queue, then `Reconcile`. + +Effects in memory are kept throughout. Plugins that didn't change aren't touched. + +## Shutdown + +Stop accepting deliveries (`503`, `/readyz` fails), let in-flight calls finish up to their +timeout, then stop the plugins. + +## Open questions + +None at the moment. diff --git a/docs/effectors/plugins.md b/docs/effectors/plugins.md new file mode 100644 index 00000000..ff53a07a --- /dev/null +++ b/docs/effectors/plugins.md @@ -0,0 +1,57 @@ +# Example plugins + +Plugins aren't part of this design. The design only defines the contract they implement +([effector interface](effector-interface.md#plugin-contract)) and the effect types they map +to. The plugins below are **illustrations** of how real use cases map onto that contract. +They get built when a phase needs them, starting with Slack in phase 1 +([decisions](#decisions)). Each then has its own design covering its provider permissions, +behaviour, safety and hosting. That's the plugin's responsibility, not the effector's. + +| Example plugin | Effect | Rule kinds | Target schemes | What an effector action using it might do | +| --- | --- | --- | --- | --- | +| `slack` | `notify` | state, event | `slack-channel`, `slack-user` | Post a message when an effect activates, edit it to resolved when it clears | +| `github-checks` | `block` | state | `github-repo` | Fail a required status check on open pull requests while the effect is active | +| `github-settings` | `remediate-apply` | state | `github-repo` | Re-apply a settings baseline to the repository | +| `iac-llm` | `remediate-propose` | state, event | any | Propose a fix as a pull request (designed separately) | + +## How a plugin maps onto the contract + +Whatever the provider, a plugin answers the same questions: + +| Question | Where it's answered | +| --- | --- | +| Which effect types does it declare, with which rule kinds, default `on_clear` and target schemes? | `Describe()` → `Manifest.capabilities` | +| What credentials does it need? | Plugin config, validated by `Configure()` | +| What can an operator tune per effector action? | Action config, validated by `ValidateAction()` | +| What does "active" look like in the provider? | `Apply()` | +| What does a repeat look like (the rule's `repeat` elapsed)? | `Apply()` with transition `repeated` | +| What do its target identities look like? | `Manifest.capabilities[].target_schemes`: name, value format, example | +| Can it list targets for a dropdown? | `ListTargets()`, for schemes with `supports_listing` | +| What does "cleared" look like (revert, resolve, nothing)? | `Clear()`, following the action's `on-clear` | +| How does it converge after missed deliveries? | `Reconcile()` | +| Does it react to provider events between deliveries? | `HandleExternal()` and its external routes | +| What does it report back for a human to decide? | Observations, declared per capability ([wire interface](wire-interface.md#observations)) | + +For example, a state `notify` plugin usually keeps the provider's message ID in refs so +`Apply` can edit rather than repost, and `Clear` can mark the message resolved. If it posts +one message per subject, it keys those IDs by subject and uses `trigger.changes` to know which +message to post, edit or resolve. A state +`block` plugin has to treat any target in its action's `targets` that has **no effect** as +inactive (for example posting a passing check), because the agent only holds active effects +and clears that haven't been applied yet +([what the agent holds](wire-interface.md#what-the-agent-holds)). A `remediate` plugin usually does nothing on `Clear`: a +fix isn't undone when the trigger stops holding. + +## Decisions + +1. **Plugins ship with the phases that need them.** Each phase builds the plugins it needs to + be proven end to end. Phase 1 starts with the **Slack** plugin (`notify`). Phase 3 adds + plugins for `block` and `remediate`. The other examples stay examples until a phase needs + them, and each gets its own design then. +2. **An effector plugin template.** A starter repository like `plugin-template`, for example + `effector-template`, with the `Effector` gRPC service stubbed, `Describe` and + `ValidateAction` wired, and a sample action. One repository per plugin, as for collectors. + +## Open questions + +None at the moment. diff --git a/docs/effectors/security.md b/docs/effectors/security.md new file mode 100644 index 00000000..d8ab7173 --- /dev/null +++ b/docs/effectors/security.md @@ -0,0 +1,136 @@ +# Security + +Effectors let CCF change other systems, so the design has to hold up when one part is +compromised or misconfigured. This document collects the security decisions spread across +the other documents and adds the threat model. + +## Trust boundaries + +```mermaid +flowchart LR + subgraph U["Users"] + RA["Rule admin"] + AP["Approver"] + end + subgraph C["CCF API (hosted or self-hosted)"] + R["Rules"] + E["Effects"] + K["Delivery signing key"] + end + subgraph X["Customer environment"] + H["Agent
effector actions"] + P["Plugins
provider credentials"] + end + S["Slack / GitHub / AWS"] + + RA -->|"JWT + Cedar"| R + AP -->|"JWT + Cedar"| E + E -->|"signed webhooks"| H + H -->|"agent JWT"| E + H --> P + P -->|"provider credentials"| S +``` + +| Boundary | Control | +| --- | --- | +| User → API | Rule permissions (`rule:*`), plus type-level read permission on the rule's whole source for whoever creates or edits it ([user interface](user-interface.md#permissions)) | +| API → effector | Ed25519-signed webhooks, timestamp window, replay protection | +| Agent → API | Agent JWT (existing token exchange); effector routes limited to the agent's own effects | +| Agent → plugin | Effector actions: the agent checks the action and target on every delivery, and supplies the config itself | +| Plugin → provider | Credentials that never leave the effector, scoped by the operator | + +## Threats + +| If this is compromised… | …the attacker can | …but not | +| --- | --- | --- | +| A user account with `rule:create` | Create or edit rules using registered effector actions, over sources that user can read in full | Act on or leak subjects the user can't read, change how an action behaves, or act on targets outside an action's patterns | +| The API (code or admin) | Send effects for registered effector actions | Make an effector run anything but its declared actions, on other targets, with other config; or read provider credentials | +| The API database only | Read rules and effects | Forge deliveries: the signing key isn't in the database | +| An agent key | Register a fake instance, read that agent's effects and their context, report false status | Redirect deliveries: the webhook URL is set by an admin, not by registrations | +| An agent host | Use its provider credentials, within what the operator granted them | Affect other agents | +| An effector plugin | What the agent exposes to effector plugins (`EffectorHelper`) | Receive deliveries for actions that don't use it, or create evidence | + +## Identity + +- An effector is an agent with effector plugins. It uses the agent's `AgentServiceAccountKey`, + with expiry, revocation and auth events. +- Effector routes accept agent JWTs only, and the effects routes only for instances that + registered effector actions. An agent only sees its own effects. +- **Effector plugins can't produce evidence.** Collectors observe and effectors act; evidence + only ever comes from observation, so the chain from a system's state to an evidence record + to a rule to an effect is never circular. The agent enforces it by not giving effector + plugins the `ApiHelper` (see [effector interface](effector-interface.md#no-evidence-from-effectors)). + What an effector sees that matters (a bypass, a dismissed fix) goes back as an observation, + for a person to decide on. +- Remote configuration can't open the effector listener or change it (`effector.*` is + forbidden in overlays, like `api` and `remote_config`), and it can't widen what an effector + does: adding actions or targets is forbidden in every `remote_config.mode`, `apply_all` + included ([effector interface](effector-interface.md#remote-configuration)). + +## Delivery signing + +- Ed25519 (Standard Webhooks `v1a`). The private key comes from the API's configuration, a + key file named by a new `CCF_EFFECTOR_SIGNING_KEY` variable (like `CCF_JWT_PRIVATE_KEY`), + never from the database. +- Effectors reject: bad signatures, timestamps more than 5 minutes off, repeated + `webhook-id`s, and generations lower than or equal to one they've already received. +- One key pair for the whole API, not one per agent. Agents only receive public keys, by + `kid`. Rotation: configure the next key as `CCF_EFFECTOR_SIGNING_KEY_NEXT`, which agents + learn through heartbeat responses; then promote it + ([wire interface](wire-interface.md#headers-and-signing)). + +## Effector actions as the allowlist + +The effector actions in an effector's config are the most important control: an effector +only does what its actions declare, only on targets matching their patterns, with config the +operator wrote. The API can pick an action and a target, nothing else. Details are in +[effector interface](effector-interface.md#effector-actions). Recommendations: + +- Keep the targets of actions that block or change systems narrow, not `*`. +- Give each plugin a provider credential limited to the same scope as the actions that use + it. + +## Out of scope: plugins + +What a plugin does inside a provider, which provider permissions it needs, what it runs and +where, and how it protects itself against hostile input (for example evidence text passed +to a model) are the plugin's responsibility. Each plugin that ships covers them in its own +design. This design only guarantees what reaches a plugin: a verified delivery, for a +declared effector action, on an allowed target, with the operator's config. + +## Data sent to effectors + +- Effect documents include subject titles, links and target identities. Subject documents + for people include **emails and linked Slack user IDs** (risk owners, workflow assignees, + SSP contacts). The customer runs + the effector, but it's still data leaving the API: document it, and allow redaction per + rule. +- The context route returns policy output and control text for the effect's subjects only, + with size limits. + +## Data sent to the API by effectors + +- Registration, status, observations: what the plugin chooses to report. +- **Published targets** (channel names, repository names) only for actions with + `publish-targets: true`. Off by default. + +## Audit trail + +- Every effect generation, delivery attempt, status report, observation and decision is + stored with timestamps and actors, for **24 hours** ([retention](operations.md#retention)). + Each effect's current state is kept as long as the effect exists. +- Rule changes are versioned, with who changed what. +- What plugins change in providers is linked from the effect's refs. Whether a change worked + is shown by the next collection, not by the effector. + +## Decisions + +1. **Signing key storage:** the delivery signing key comes from the API's configuration + (`CCF_EFFECTOR_SIGNING_KEY`, plus `CCF_EFFECTOR_SIGNING_KEY_NEXT` while rotating, key + files like the JWT keys), not a KMS. One key pair for the whole API. +2. **No second approval:** a rule is enabled when an authorized rule admin saves it, whatever + its actions do. + +## Open questions + +None at the moment. diff --git a/docs/effectors/triggers.md b/docs/effectors/triggers.md new file mode 100644 index 00000000..ea51b737 --- /dev/null +++ b/docs/effectors/triggers.md @@ -0,0 +1,434 @@ +# Triggers + +How the API decides that a rule's actions should run. The rule document users write is in +[user interface](user-interface.md); what gets sent to effectors is in +[wire interface](wire-interface.md). + +## Principle: the API exposes data, rules decide + +The API has no use-case-specific rule options. Each **source** exposes a typed **subject** +document, and event sources also expose typed **event** documents. Rules filter them with **CEL** expressions. A new use +case needs, at most, a new field on a subject or event, which every rule can then use. It +never needs a new rule option. + +```yaml +trigger: + source: catalog + on: [catalog.control.changed] + if: > + subject.id == "3f1d6c2a-…" && # the NIST 800-53 catalog (IDs are UUIDs) + size(event.control.used_by_ssps) > 0 # only controls an SSP uses +``` + +## Two kinds of rule + +| | State rule | Event rule | +| --- | --- | --- | +| Written as | `when: ` over `subject` | `on: [event types]` and optional `if: ` over `subject` and `event` | +| Question | "Is this true right now?" | "Did this just happen?" | +| Effect lifecycle | `inactive` → `pending` → `active` → `inactive`, repeatedly | `occurred`, once per occurrence | +| Undo | Yes: the effector action's `on-clear` | No | +| Re-evaluated | Whenever a subject of the source changes, and on timers | Never | +| Created with existing data | Evaluated against every current subject immediately | Starts from now; no backfill | + +```mermaid +stateDiagram-v2 + direction LR + state "State rule effect" as S { + [*] --> inactive + inactive --> pending: a subject matches + pending --> inactive: no subject matches any more + pending --> active: a subject entered (matched for for + delay) + active --> active: a subject entered or left, exceptions changed, or repeat elapsed + active --> finished: max_repeats reached + finished --> active: a new subject entered (repeat count reset) + finished --> inactive: no subject matches + active --> inactive: no subject matches + } + state "Event rule effect" as E { + [*] --> occurred: event type matches and if holds + occurred --> [*]: delivered and applied + } +``` + +Every change to a state effect (on, off, or a change in the subjects that caused it) +increments its **generation**. `pending` is internal to the API and is never delivered. + +## The expression language + +Conditions and targets are [CEL](https://cel.dev) expressions, evaluated with `cel-go`. + +| Why CEL | | +| --- | --- | +| Type-checked | Each source declares its subject and event types. A typo (`subject.staus`) is a `422` when the rule is saved, not a silent "never matches" | +| Bounded | Not Turing-complete; cel-go estimates cost statically and enforces a limit at runtime. A rule can't hang the engine | +| Partial evaluation | The engine can tell which subjects depend on `now` and schedule them, instead of sweeping everything (see [Timers](#timers)) | +| Known | Same language as Kubernetes admission policies and Google APIs. The UI can still offer forms that write CEL | + +Variables available to expressions: + +| Variable | Type | In | +| --- | --- | --- | +| `subject` | The source's subject type | `when`, `if`, target expressions | +| `event` | The event type of the matched event | `if`, target expressions of event rules | +| `now` | `timestamp` | everywhere | + +Functions: the CEL standard library, plus the `strings`, `lists` and `math` extensions. +Sources can add **member functions** for data that's too expensive to put in every subject +document (for example `subject.matches_filter(id)` on evidence). They're part of the +source's schema like fields are. + +Field names in expressions are snake_case (`used_by_ssps`), because CEL identifiers can't +contain `-`. The same fields are kebab-case when they appear in JSON (`used-by-ssps`). + +### Validation on save + +Errors at evaluation time (a missing map key, for example) are handled separately: they count +as no match and are kept visible on the rule +([user interface](user-interface.md#when-an-expression-fails)). + +1. Compile and type-check against the source's declared types. `when` and `if` must return + `bool`; target expressions must return `string` or `list(string)`. +2. Estimate the cost. Over the limit → `422` with the estimate. +3. `on` lists only event types the source declares. + +Errors come back with the expression, line and column. + +## Subject documents + +`subject` is **not** a database model like `relational.Evidence` or `SystemSecurityPlan`. It's +a **subject document**: a read-only projection, defined per source, that's part of the +rules contract. + +| | GORM model | Subject document | +| --- | --- | --- | +| Shape | Whatever the database needs; changes with migrations | Declared per source as CEL types; versioned; additive changes only | +| Relations | Lazy or preloaded associations, any depth, polymorphic | Only the relations the schema lists, as **flat summaries** (`{id, title, labels}`), never the related object itself | +| Size | Unbounded (an SSP's full OSCAL tree) | Only the declared fields. Lists are **complete** for evaluation (an SSP's `controls` has every control), so `size()` and `exists()` are exact. Effect documents carry the same, uncapped | +| Built | By the ORM, per query | By the source's **document builder**, once per change, then evaluated by every rule of that source | + +What that means in practice: + +- **One subject = one thing the engine evaluates on its own.** For `evidence` it's one + stream; for `ssp` one SSP; for `catalog` one catalog. +- **No implicit loading.** If a field isn't in the schema, an expression can't reach it, + and nothing is loaded "just in case". A rule can't walk from a catalog into all its + controls and their SSPs. +- **No polymorphism in expressions.** Every field has one declared type. Mixed relations (for + example OSCAL subjects of different types) use one common shape with a `type` field. +- **Expensive data is precomputed or explicit.** Derived fields (an SSP's control posture) + come from projections that their own jobs keep up to date ([Cascades](#cascades)). Lookups + that are too costly to put in every document are member functions with a declared cost + (`subject.matches_filter(id)`). + +- **Deleted subjects.** For a `*.deleted` event, `subject` is the document as it was just + before the deletion. The producer builds it inside the deleting transaction, because the + rows are gone afterwards. + +### When a subject counts as changed + +A subject **changes** when any field of its document changes. For evidence that includes +`end`, so every collection run changes its stream. Every change re-evaluates the source's +state rules for that subject, so rules over any field (`end`, `expires`, `labels`) stay +correct. + +Re-evaluating isn't the same as delivering. An effect gets a new generation (`updated`) only +when **which subjects match** it changes, or its exceptions change, not when other fields of +a matching subject change. An hourly collection of a still-failing stream re-evaluates the rule +and delivers nothing. The effect document's subject snapshots refresh with the next delivery. + +### Filters + +`subject.matches_filter(id)` is evaluated live against the filter's current definition. There's +no cache to go stale. Filter membership can change without any evidence write (someone edits +the filter, or a scope-following filter is rewritten when its SSP's scope changes), so a filter +change is a producer too: it writes `filter.changed`, and the engine re-evaluates every rule +whose expressions reference that filter ID, over the streams the filter matches before or after +the change. Rules that build the filter ID dynamically can't be tracked this way, so the +validator only accepts a literal ID in `matches_filter`. + +### Rules over all controls + +So for "a rule over all controls of a catalog": the `catalog` source can't express it, +because its subject is the catalog. Rules that need one evaluation per control need a source +whose subject is a control (`control`, with fields such as `catalog_id`, `used_by_ssps`). That +would be a new source, not a bigger catalog document. See open questions. + +## Sources + +The tables below are **illustrative**. The authoritative schema is served by +`GET /api/rules/sources` (CEL type declarations plus a description per field), so the UI and +validation always use the same definition. Adding a field is a non-breaking change. + +### `evidence` + +Subject: an evidence **stream** (all evidence sharing a stream UUID), as of its latest evidence. + +| Field | Type | Notes | +| --- | --- | --- | +| `id`, `title` | string | | +| `status` | string | OSCAL objective status of the latest evidence | +| `labels` | map(string, string) | | +| `start`, `end` | timestamp | Of the latest evidence | +| `expires` | timestamp, optional | | +| `subjects` | list(Subject) | `{id, type, title, props: list({name, ns?, value}), links: list({href, rel?})}`. No identity field: targets are built from these, see [user interface](user-interface.md#targets) | +| `components` | list(Component) | `{id, title, labels: map(string, string)}`. A component's identity in CCF is its set of identity labels | +| `matches_filter(id)` | bool | The stream's latest evidence matches the saved filter, evaluated live ([Filters](#filters)). `id` must be a literal | + +Events: `evidence.stream-started`, `evidence.status-changed` (`event.from`, `event.to`). All events and states, and how each is computed: [events and states](events-and-states.md#evidence). + +### `risk` + +| Field | Type | Notes | +| --- | --- | --- | +| `id`, `title`, `status` | string | `open`, `investigating`, `mitigating-planned`, `mitigating-implemented`, `risk-accepted`, `remediated`, `closed` | +| `likelihood`, `impact` | string, optional | Risk levels | +| `score` | int, optional | `likelihood × impact` ranks (1–25), absent when either is unset | +| `ssp` | `{id, title}` | | +| `template_id` | string, optional | | +| `labels` | map(string, string) | | +| `review_deadline` | timestamp, optional | | +| `owners` | list(Party) | `{kind: user \| group, id, email?, slack_user_id?}`. `slack_user_id` comes from the user's linked Slack account | +| `components`, `subjects` | lists | As on evidence | +| `controls` | list(`{catalog_id, control_id}`) | | + +Events: `risk.created`, `risk.status-changed` (`event.from`, `event.to`), `risk.accepted`, +`risk.reviewed`, `risk.score-changed`, `risk.deleted`. +All events and states, and how each is computed: [events and states](events-and-states.md#risk). + +### `workflow-execution` and `workflow-step` + +| Source | Subject fields | +| --- | --- | +| `workflow-execution` | `id`, `definition {id, name}`, `ssp {id, title}?`, `status` (`pending`, `in_progress`, `overdue`, `completed`, `failed`, `cancelled`), `started_at`, `due_at?` | +| `workflow-step` | `id`, `name`, `status` (`pending`, `blocked`, `in_progress`, `overdue`, `completed`, `failed`, `skipped`, `cancelled`), `due_at?`, `assignee {kind: user \| group \| email, id?, email?, slack_user_id?}`, `execution` (the execution's fields) | + +Events: `workflow.execution.status-changed`, `workflow.step.status-changed`, +`workflow.step.assigned`, `workflow.step.reassigned`. All events and states, and how each is computed: [events and states](events-and-states.md#workflow-execution-and-workflow-step). + +### `ssp` + +| Field | Type | Notes | +| --- | --- | --- | +| `id`, `title` | string | | +| `labels` | map(string, string) | | +| `components` | list(Component) | As on evidence | +| `contacts` | list(`{role, email, slack_user_id?}`) | Parties with responsible roles | +| `controls` | list(`{catalog_id, control_id, posture, implementation_status}`) | Every control in the SSP's profiles (an SSP can have several). `posture` from the lineage posture ladder: `satisfied`, `not-satisfied`, `inherited`, `not-applicable`, `planned`, `attention`. Controls outside the profiles aren't listed, so `out-of-scope` never appears. Computed by a derived job, see [Cascades](#cascades) | +| `posture_counts` | map(string, int) | Controls per posture | + +Events: `ssp.control.posture-changed` (`event.control_id`, `event.from`, `event.to`), +`ssp.changed` (`event.changed_fields`). All events and states, and how each is computed: [events and states](events-and-states.md#ssp). + +### `catalog` + +| Field | Type | +| --- | --- | +| `id`, `title` | string | +| `active` | bool | + +Events, with `event.control = {id, title, group_id?, parent_id?, used_by_ssps: list(string)}` +where relevant: `catalog.created`, `catalog.deleted`, `catalog.activated`, +`catalog.deactivated`, `catalog.control.added`, `catalog.control.changed` +(`event.changed_fields`), `catalog.control.removed`. How control changes are computed (a +diff by control ID on every catalog write): [events and states](events-and-states.md#catalog). + +A catalog has no state worth a state rule, so it only supports event rules. Per-control +events still carry the control (`event.control`), so "react when any used control changes" +works without loading the catalog's controls. + +Catalogs get **versions** in phase 2: each imported or edited revision is stored, so +`event.changed_fields` comes from comparing two stored revisions and an effect can link to +what changed. + +### Phase 2: `control` and `profile` + +Two more sources come in phase 2, detailed then: + +| Source | Subject | Why | +| --- | --- | --- | +| `control` | One control of a catalog: `catalog_id`, `control_id`, `title`, `class`, `used_by_ssps`, and its posture in each SSP that uses it | State rules that run once per control ("any control not satisfied in more than two SSPs"), which the `catalog` source can't express | +| `profile` | One profile: its imported catalogs, selected controls, the SSPs that use it, and aggregates over them | Alerts on a baseline as a whole, and profile changes as events | + +### Derived fields + +**Phase 1 has no derived fields.** The evidence source only exposes what's stored with the +evidence (plus `matches_filter`). In phase 2, the `ssp`, `risk`, `catalog`, `control` and +`profile` sources get **as many derived and aggregate fields as possible**, because they're +what people want to alert on: SSP control posture and posture counts, an SSP's or profile's +total open risk score, how many SSPs use a control, how many of a profile's controls are +satisfied. Each is computed by its own derived job ([cascades](#cascades)). + +## Pipeline + +```mermaid +flowchart LR + subgraph TX["Same DB transaction as the change"] + P["Producer
(ingest, risk service,
workflow, catalog handler)"] --> O[("domain_events
outbox")] + end + O --> D["dispatch job
(River)"] + D --> M["Rules for this source"] + M -->|"state rule"| SE["Evaluate when
for the changed subject,
regroup by target"] + M -->|"event rule"| EV["Evaluate if,
create occurrence effects"] + SE --> DIFF["Diff effects:
changed → generation + 1"] + DIFF --> DL["effects.deliver"] + EV --> DL + TM["Timers
for, delay, now-dependent subjects,
exception expiry"] --> SE +``` + +1. **Producers write a domain event in the same transaction** as the change (an outbox + table). Two kinds: `.subject-changed` (a subject's document changed, with its ID) + for state rules, and the source's typed events for event rules. A crash can't lose an + event or deliver one for a rolled-back change. Producers don't know about rules. +2. A **dispatch job** reads the outbox and loads the rules for that source. +3. **State rules** evaluate `when` for the changed subject only, then evaluate the target + expression and regroup subjects by target. An effect is (rule action, target), so a + change to one subject can activate, update or clear the effect of the target it maps to. +4. **Event rules** evaluate `if` and the target expression, then create one effect per + (rule action, target, occurrence), in state `occurred`. +5. Changed effects get generation + 1 and a delivery job. + +Rules are never evaluated in the request that made the change. Batch evidence ingest writes +one `subject-changed` row per stream it touched, not one per evidence item. + +### Timers + +Some conditions change without any write: anything comparing to `now`, a `for` period, an +action's `delay`, an exception's expiry. + +- `for`, `delay`, `repeat` and exception expiry have known times, so the engine schedules a + River job at that time (`ScheduledAt`). +- For `now` in expressions, the engine evaluates `when` with `now` as an **unknown** (cel-go + partial evaluation). Subjects whose result doesn't depend on `now` need no timer. For the + others, the engine adds them to a time-dependent set that a sweep re-evaluates (default + every minute). Only those subjects are swept, not the whole source. + +### Cascades + +Some subject fields are derived: an SSP's `controls[].posture` depends on evidence, risks and +control links. A **derived job** recomputes them and writes `ssp.subject-changed` (and +`ssp.changed`) into the same outbox: + +```mermaid +flowchart LR + EV["evidence.subject-changed"] --> R1["evidence rules"] + EV --> SSPJ["ssp.recompute
(SSPs whose scope matches)"] + RK["risk.subject-changed"] --> SSPJ + CL["control link or implementation edited"] --> SSPJ + SSPJ --> SS["ssp.subject-changed"] --> R2["ssp rules"] +``` + +A cascade is one level deep by construction: effects never write domain events directly. + +### Loops + +Effectors never produce evidence ([effector interface](effector-interface.md#no-evidence-from-effectors)), +so a rule can't feed itself directly. The remaining loop is the intended one: a remediation +changes the system, and the next collection observes it. When that misbehaves (a fix that +doesn't stick, a condition that flaps), two guards apply: + +- Each rule has a rate limit on effect activations per target (default: 10 per hour). Over + the limit, the rule is paused for that target and admins are notified. +- An effect that goes active → inactive → active more than N times in a window is marked + `flapping` and stops being redelivered until someone looks. + +## Grouping and deduplication + +An effect is delivered when its generation changes, and only then. Being active doesn't +cause deliveries; transitions do: + +| Transition | Happens when | Delivered | +| --- | --- | --- | +| `activated` | The first subject **entered**: it matched for `for`, plus the rule action's `delay` | Once | +| `updated` | A subject entered or left, or the exceptions changed, while active | Once per change. A subject entering resets the repeat count | +| `repeated` | The rule action's `repeat` interval passed since the last entry or repeat | Once per interval, up to `max_repeats` | +| `finished` | `max_repeats` was reached; the condition still holds | Once | +| `redelivered` | An admin asked to apply it again | Once per request | +| `cleared` | No subject holds any more | Once | +| `disabled` | The rule was disabled | Once (as `effect.clear`) | + +A rule whose condition keeps holding produces one `activated` delivery, plus one `repeated` +delivery per interval if it has `repeat`. It never produces a second `activated` while the +effect is active. The effector drops any generation it has already applied, so retries and +duplicate webhooks don't repeat the action either. + +- **State rules:** one effect per (rule action, target). The effect lists every subject + that has entered it for that target, and clears only when none match. Each subject is + timed on its own: it **enters** once it has matched for `for` plus the action's `delay`, + and **leaves** when it stops matching. Deliveries say which subjects entered and left, so + a plugin can act per subject ([user interface](user-interface.md#targets)). +- **Repeat count:** one per effect, counted from the last entry. A subject entering resets it + to 0; repeats aren't counted per subject. +- **Event rules:** one effect per (rule action, target, occurrence). Batching occurrences + into one effect isn't in v1; it can be added later if one-per-occurrence turns out too + noisy. +- **Ordering:** each effect's generations are strictly increasing; nothing is promised + across effects. + +## Performance + +- Expressions are compiled once when the rule is saved and cached per rule. +- Only the changed subject is evaluated, not the whole source. Backfill on rule creation + streams through the source's subjects in a background job. +- Expensive data is behind member functions (`matches_filter`) or derived fields computed + by their own jobs (SSP posture), so expressions only pay for what they use. The cost + estimate accounts for them. +- Dispatch is debounced per (rule, subject): bursts for the same subject fold into one + evaluation. +- `POST /api/rules/preview` reports how many subjects match and how long evaluation took. + +## Alternatives considered + +**Typed selectors per source.** Instead of CEL, each source gets a namespaced, typed +selector block: + +```yaml +select: + catalog: + catalog-ids: [nist-800-53-r5] + only-used: true + # or + ssp: + ssp-ids: [repo-1-ssp] + controls-failing: [SA-11, SI-2] +``` + +| | Typed selectors | CEL | +| --- | --- | --- | +| UI | Forms map 1:1 to fields | Needs an expression editor, or forms that generate CEL | +| Expressiveness | Only what someone added a field for | Any condition over the exposed data | +| API surface per use case | A new field per need (`only-used`, `review-overdue`, …) | None; at most a new data field | +| Indexing | Easy to index fixed fields | Needs care: only the changed subject is evaluated, so less of a problem | + +If typed selectors were chosen, every field must sit under its source's namespace +(`select.catalog.*`, `select.ssp.*`) so the shape stays uniform and validation is per +source. CEL is recommended because it removes per-use-case API surface entirely, which is +the point of this section. + +**Rego.** CCF already runs Rego (OPA) for policies and playback. It could express these +conditions too, but it's heavier for one-line boolean filters, harder to type-check against +a declared schema, and mixing rule conditions with compliance policies would blur what a +policy is. + +## Decisions + +1. **Outbox.** Producers write domain events to a `domain_events` table in their own + transaction. Enqueuing River jobs directly isn't an option: River's `InsertTx` needs a pgx + transaction, which isn't reachable from inside a GORM transaction (see the note in + `internal/service/relational/evidence/service.go`). +2. **CEL**, with `cel-go` as a new dependency. +3. **CEL field naming.** Expressions use snake_case, JSON stays kebab-case. +4. **Catalog versions** in phase 2. +5. **`control` and `profile` sources** in phase 2. +6. **Derived fields.** None in phase 1. In phase 2, as many as possible for SSPs, risks, + catalogs, controls and profiles. +7. **Evidence events.** `evidence.status-changed` (and `evidence.stream-started`) only. An + event per collection run would be too noisy. +8. **Workflow sources aren't designed around notifications.** Workflows already notify + people, so the workflow sources were added for acting on other systems: triggering an + external process when an execution completes, or sending its results somewhere. Nothing + stops a rule from notifying with them, for example people who aren't CCF users. + +## Open questions + +None at the moment. diff --git a/docs/effectors/user-interface.md b/docs/effectors/user-interface.md new file mode 100644 index 00000000..8976a47a --- /dev/null +++ b/docs/effectors/user-interface.md @@ -0,0 +1,735 @@ +# User interface + +What people do through the API: set up agents as effectors, write rules, see what the rules did, +and decide on exceptions. The UI is a client of these routes. The protocol between the API +and effectors is in [wire interface](wire-interface.md); how the API evaluates triggers is in +[triggers](triggers.md). + +Throughout, an **effector** is a CCF agent that runs effector plugins. Rules name it by its +agent name. + +## Rules don't belong to SSPs + +A rule is a top-level resource. An SSP is **one of five things a rule can watch**, not the +container every rule lives in. The simplest rule has nothing to do with SSPs: + +> *When* evidence about branch protection is failing, have the `platform-github` effector +> *apply the branch baseline* to the repository the evidence is about. + +```mermaid +flowchart LR + subgraph Rule + direction LR + T["Trigger
source + CEL condition,
or event types + CEL filter"] --> A1["Action
effector platform-github
action apply-branch-baseline
target: the evidence's repo"] + T --> A2["Action
effector platform-notify
action notify-platform
target: #platform"] + end +``` + +## Who does what + +| Role | Does | Permission (Cedar) | +| --- | --- | --- | +| Admin | Creates and deletes agents and their keys, sets an agent's webhook URL, sees the effector actions agents offer and their health | `admin:manage` for changes (as agent create, update, delete and keys are guarded today), `agent:read` to view | +| Agent operator | Decides what an agent can do as an effector: its effector plugins and **effector actions**, in the agent's config (file, or a remote overlay the agent accepts) | Access to the agent's deployment, or `agent:configure` for overlays | +| Rule admin | Creates, edits, disables and deletes rules. Rules are an admin activity with their own permissions | `rule:create`, `rule:update`, `rule:delete`, **plus** permission on the subjects the rule watches (see [Permissions](#permissions)) | +| Approver | Decides on observations that effectors report, such as exception requests | `effect:decide` | +| Viewer | Sees rules, effects, deliveries | `rule:read` | + +## Turning an agent into an effector + +An effector is a CCF **agent** that runs effector plugins +([effector interface](effector-interface.md)). There's nothing separate to register: the +admin creates an agent and its key as today, **sets the URL the API should deliver to**, and +the agent's operator adds effector plugins and their actions to its config. An agent can run +collector plugins too. + +```mermaid +sequenceDiagram + autonumber + actor Admin + participant API as CCF API + participant AG as Agent + + Admin->>API: POST /api/admin/agents {name: platform-github} + Admin->>API: POST /api/admin/agents/{id}/keys + API-->>Admin: client_id, client_secret (shown once) + Admin->>API: PUT /api/admin/agents/{id}/effector {webhook-url} + Admin->>AG: Deploy with key + config (effector plugins, credentials, effector actions) + API->>AG: effector.verify (to the URL) + AG->>API: Registers its instance and effector actions (wire interface) + Admin->>API: GET /api/admin/agents/{id}/effector + API-->>Admin: instances, webhook status, effector actions +``` + +What the admin sees for an agent's effector side: + +| Field | Example | +| --- | --- | +| Agent | `platform-github` (`5d0c…`; rules store the ID) | +| Webhook | `https://agent-platform.acme.internal/v1/webhook`: `not-set` · `pending-verify` · `ready` · `failing` (deliveries failing) | +| Instances | `3c9e…` (v1.9.0, fresh, last seen 12s ago). Fresh or stale by the API's existing `InstanceStaleAfter` | +| Effector actions | `apply-branch-baseline` (`remediate-apply` on `github.com/acme/*`), `block-prs` (`block` on `github.com/acme/*`) | +| Used by | 14 rule actions in 9 rules (2 degraded) | +| Deliveries | 99.8% delivered in 24h, 3 pending | + +Effector actions can't be added or edited from the rule pages. They come from the agent's +configuration ([effector interface](effector-interface.md#effector-actions)): its file, or a +remote configuration overlay within what the agent's `remote_config` allows. The rule +builder shows them read-only. + +**Rules store the agent's ID.** Agent names aren't unique (the `ccf_agents.name` column has +no unique index, and agents are soft-deleted), so a rule can't rely on a name. A rule may give +`effector.agent` as a name on input; the API resolves it to the ID if exactly one active agent +has that name (`422` if none or several) and stores the ID. Responses show both. Renaming an +agent therefore doesn't affect its rules. + +**Deleting an agent deletes every rule that uses it.** Before deleting, the API lists those +rules and the admin has to confirm: + +1. `DELETE /api/admin/agents/{id}` on an agent used by rules answers `409` with the rules + that will be deleted. +2. `DELETE /api/admin/agents/{id}?confirm=delete-rules` deletes the agent and those rules. + A deleted rule's effects on *other* agents are cleared first (they get `effect.clear` + with transition `removed`). The deleted agent's own effects are dropped: it can no longer + be reached or trusted. + +## Anatomy of a rule + +A rule has a **trigger** (when) and one or more **actions** (do). Rules come in two kinds: +a **state rule** uses `when:` and its effects turn on and off; an **event rule** uses `on:` +and each occurrence fires once. Conditions and targets are [CEL](https://cel.dev) +expressions over the source's subject and event documents. There are no use-case-specific +rule options ([triggers](triggers.md#principle-the-api-exposes-data-rules-decide)). Shown as +YAML for readability; the API takes JSON with the same (kebab-case) keys. + +**State rule** (`when`): + +```yaml +name: Repos keep branch protection +description: Re-apply the baseline when branch protection evidence fails +enabled: true + +trigger: + source: evidence # evidence | risk | workflow-execution | workflow-step | ssp | catalog + when: > # CEL → bool, over `subject` + subject.matches_filter("7c1e…") && + subject.status == "not-satisfied" + for: 30m # must hold this long first + +actions: + - effector: + agent: platform-github # the agent whose effector actions run this + action: apply-branch-baseline # which of its effector actions it runs + target: + expr: > # CEL → string or list(string), per matching subject + "github-repo:github.com/" + subject.labels["organization"] + "/" + subject.labels["repository"] + + - effector: + agent: platform-notify + action: notify-platform + target: + identity: slack-channel:#platform # a fixed target +``` + +**Event rule** (`on`): + +```yaml +name: Propose policy updates when NIST controls change +enabled: true + +trigger: + source: catalog + on: # event types; each occurrence fires the actions once + - catalog.control.changed + - catalog.control.removed + if: > # optional CEL → bool, over `subject` and `event` + subject.id == "3f1d6c2a-…" && # the NIST 800-53 catalog; IDs are UUIDs + size(event.control.used_by_ssps) > 0 + +actions: + - effector: + agent: platform-github + action: propose-policy-update # an action that proposes a change + target: + identity: github-repo:github.com/acme/policies + + - effector: + agent: platform-notify + action: notify-grc + target: + identity: slack-channel:#grc +``` + +### Trigger + +| Field | Meaning | +| --- | --- | +| `source` | Which kind of subject the rule watches: `evidence`, `risk`, `workflow-execution`, `workflow-step`, `ssp`, `catalog` | +| `when` | **State rule**: CEL returning `bool` over `subject`. Effects turn on while it holds and off when it stops | +| `on` | **Event rule**: one or more event types the source declares | +| `if` | Event rules only, optional: CEL returning `bool` over `subject` and `event` | +| `for` | State rules only: how long `when` must hold for **a subject** before that subject counts. Each subject is timed on its own, so one flapping stream doesn't disturb the others. Absorbs flapping | + +A rule has either `when` or `on`, never both. + +**What `subject` is.** It's the source's **subject document**, not a database model: with +`source: evidence` it's one evidence stream as the evidence source defines it; with +`source: ssp` it's one SSP. It contains exactly the fields its schema declares. Related +objects appear only as flat, size-limited summaries, and nothing else is loaded. A rule +can't walk from a catalog into all its controls, because the catalog's subject doesn't +contain them; per-control rules would need a source whose subject is a control +([subject documents](triggers.md#subject-documents)). The schemas are served by +`GET /api/rules/sources`; [triggers](triggers.md#sources) has the full list. + +Some conditions, written out: + +| Intent | Source | Expression | +| --- | --- | --- | +| Evidence failing for one team | `evidence` | `when: subject.labels["team"] == "payments" && subject.status == "not-satisfied"` | +| Evidence past its expiry | `evidence` | `when: has(subject.expires) && subject.expires < now` | +| High risks past review | `risk` | `when: has(subject.score) && subject.score >= 15 && subject.status in ["open", "investigating"] && has(subject.review_deadline) && subject.review_deadline < now` | +| A workflow execution completed | `workflow-execution` | `on: [workflow.execution.status-changed]`, `if: event.to == "completed"` | +| Named controls failing on an SSP | `ssp` | `when: subject.controls.exists(c, c.control_id in ["SA-11", "SI-2"] && c.posture == "not-satisfied")` | +| Under 80% of controls satisfied | `ssp` | `when: subject.posture_counts["satisfied"] * 100 < 80 * size(subject.controls)` | +| A risk was accepted | `risk` | `on: [risk.accepted]`, `if: has(subject.score) && subject.score >= 10` | + +### Actions + +A rule action names **one effector** and **one of that effector's actions**, plus a target: + +| Field | Meaning | +| --- | --- | +| `id` | Assigned by the API when the action is created, and never changes. Effects are keyed by it ([below](#rule-actions-are-resources)) | +| `effector.agent` | The agent (with effector plugins) that receives this action's effects: its ID, or a name that exactly one active agent has. Stored as the ID. Required | +| `effector.action` | The effector action to run. It must be one that agent registered. Required | +| `target` | What to act on. See [Targets](#targets). Must be within the targets the effector action allows | +| `delay` | State rules only: how long a subject must have counted (after `for`) before it counts for this action too. Per subject and target, like `for`. Gives escalation: notify now, block after 7 days | +| `repeat` | State rules only, optional: while the effect stays active, deliver it again at this interval (`24h`). The plugin decides what a repeat means: a reminder message, re-asserting a block, retrying a fix | +| `max_repeats` | Optional, with `repeat`: stop repeating after this many repeats. The effect becomes `finished` ([below](#how-often-an-action-fires)) | + +There's **no plugin configuration in the rule**. Everything about *how* to act (which +plugin, its settings, whether to revert on clear) belongs to the effector action, defined +in the agent's config by its operator. Everything about *when* and *how often* (`for`, +`delay`, `repeat`) belongs to the rule. A rule says *when*, *how often*, *which effector +action* and *on what*. + +### How often an action fires + +An effect is sent to the effector when it **changes**, not because it's active. Once `for` +has elapsed, the effect is `activated` and delivered once. It isn't delivered again while it +stays active unless: + +| What happens | Transition | Delivered | +| --- | --- | --- | +| The subjects or exceptions behind it change | `updated` | Once per change | +| `repeat` elapses | `repeated` | Once per interval, up to `max_repeats` | +| `max_repeats` is reached | `finished` | Once | +| `when` stops holding | `cleared` | Once | +| An admin redelivers it | `redelivered` | Once per request | + +Every delivery carries a new generation, and the effector drops generations it has already +applied, so retries and duplicate webhooks can't fire an action twice. If the condition +clears and holds again later, that's a new activation (after `for` again). + +So "notify, and notify again every 24h until fixed" is one rule action with `repeat: 24h`, +not a second action. + +**Finished, not cleared.** With `max_repeats: 10`, after the tenth repeat the effect becomes +`finished`: the condition still holds, but the rule stops acting on it. That covers subjects +that never change again, for example evidence from a stream that stopped reporting. A +finished effect: + +- gets one `finished` delivery, so the plugin can say so (for example "no more reminders") + instead of resolving anything; +- stays `finished` while the same subjects keep matching; +- **triggers again on a new condition**: if a new subject enters it, it's active again, with + its repeat count back to 0; +- clears as usual if nothing matches any more (a block is still lifted when the problem is + fixed). + +No source has to define when its subjects are "alive", so this works the same for evidence, +risks, workflows and every other source. + +**One repeat count per effect, reset by a new match.** Repeats count from the last time a +subject entered the effect. When a new subject enters, the count goes back to 0. The old +match's remaining repeats are discarded; they aren't kept alongside a new sequence. For +example, with `max_repeats: 10`: two repeats have run for stream A, then stream B also +matches for Alice. The effect is `updated`, the count restarts, and up to 10 more repeats +follow, each covering A and B. It's never 10 repeats for B plus the 8 left for A. + +"Notify now, block after a week" is two rule actions, the second with `delay: 7d`. + +Timing lives in the rule rather than in the effector action because it's the same for every +plugin, the API is what keeps time, and it shows in the effect's history. The effector action +only says what an activation, update, repeat or clear looks like in its provider. + +### Rule actions are resources + +A rule's actions are **resources of their own**, with stable IDs, under the rule: + +| Route | Does | +| --- | --- | +| `POST /api/rules/{id}/actions` | Add an action; the API assigns its ID | +| `GET`, `PUT`, `DELETE /api/rules/{id}/actions/{actionId}` | Read, change or remove one action | + +`GET /api/rules/{id}` still returns the actions inline, for reading. Because effects are keyed +by (action ID, target), what happens to them on an edit is well defined: + +| Edit | Effects | +| --- | --- | +| The rule's name or description | Nothing | +| The rule's trigger (`when`, `on`, `if`, `for`) | The rule is re-evaluated; effects are diffed by (action ID, target). Unchanged effects keep their state and generation, so nothing is resolved and re-posted | +| An action's target, `delay`, `repeat` or `max_repeats` | That action is re-evaluated and its effects diffed the same way | +| An action's agent or effector action | Its effects are cleared on the old agent (transition `removed`), and the action is evaluated from scratch on the new one | +| Deleting an action | Its effects are cleared (`removed`) | + +### Effector actions: where the "how" lives + +An effector action is a named, operator-defined thing an agent can do with one of its +effector plugins. It's **not** created from the rule pages: it's part of the agent's +configuration, under the plugin, next to the plugin credentials +([effector interface](effector-interface.md#effector-actions) has the full format). For +example: + +```yaml +# agent config, on the agent host (see effector interface for the full format) +plugins: + github-settings-fixer: + type: effector + source: ghcr.io/acme/effector-github-settings:1.0.0 + config: { … } # plugin config: credentials + actions: + apply-branch-baseline: + description: Re-apply Acme's branch protection baseline + effect: remediate-apply # a label the plugin declares + targets: + include: ["github-repo:github.com/acme/*"] + config: { … } # action config: plugin-specific, validated at startup + + slack: + type: effector + source: ghcr.io/acme/effector-slack:1.0.0 + config: { … } + actions: + notify-platform: + description: Short alert to platform channels + effect: notify + targets: + include: ["slack-channel:#platform", "slack-channel:#platform-*"] + config: { template: short } +``` + +Where each field comes from: + +| Field | Written by | Allowed values come from | +| --- | --- | --- | +| `plugins.

` (`type: effector`) | The operator | Effector plugins loaded by this agent | +| `effect` | The operator | One of the effect types the plugin's manifest (`Describe()`) declares; the agent refuses the config otherwise | +| `targets.include`, `targets.exclude` | The operator | An allowlist of patterns over the target schemes the plugin declares | +| `config` | The operator | The plugin's config schema, checked by `ValidateAction()` | + +The effector registers its actions with the API: name, description, effect type, +allowed targets (with each scheme's value format), and the rule kinds it supports. **The config itself never leaves the +effector.** The API stores the action's name and properties and shows them read-only in the +rule builder. + +This answers both "where does the config come from" and "how is it validated": + +| Concern | Answer | +| --- | --- | +| Who writes the config | The agent's operator, who also holds the provider credentials and knows the provider | +| Where it's validated | By the plugin, when the agent starts or applies an overlay (`ccf-agent validate` in CI). An invalid action stops the agent from starting, or the overlay is rejected, so invalid config can't reach a rule | +| What the API validates | That the agent exists and registered the named action, that the target is within the action's targets, and that the action registered the rule's kind (state or event) | +| Changing the "how" | Change the agent's config (file or overlay). Every rule using that action picks it up | + +The trade-off: a rule admin can't tweak an action per rule (a different Slack template for +one rule). They pick another effector action, or ask the operator to add one. + +### One action, one effector, one webhook + +Effectors don't subscribe to rules or compete for them. **The API delivers each rule +action's effects only to the effector that action names.** With five effectors running: + +```mermaid +flowchart LR + R["Rule: repos keep branch protection"] + R --> A1["Action 1
platform-github / apply-branch-baseline"] + R --> A2["Action 2
platform-notify / notify-platform"] + A1 -->|"effects for action 1 only"| E1["platform-github"] + A2 -->|"effects for action 2 only"| E2["platform-notify"] + E3["eu-github"] + E4["security-aws"] + E5["sandbox"] +``` + +- `eu-github` gets nothing, even if it also registered an `apply-branch-baseline` action. + Action names are per effector. +- One effect = one (rule action, target) = one effector = one webhook stream. The same + effect is never sent to two effectors. +- An effector with several instances receives each delivery once, at its registered URL + ([operations](operations.md#high-availability)). +- To act on two effectors (Slack in two workspaces), add two rule actions. + +If the named effector is offline, or re-registers without the action, the rule action turns +`degraded` and nothing else picks it up. An admin can edit the rule to point the action at another +effector that registered a compatible action. + +### Which effector actions fit which rules + +Each effector action registers the rule kinds it supports, `state`, `event` or both, as its +plugin declares them for that effect ([effect types](effector-interface.md#effect-types)). A +rule can only use actions that registered its kind. The API has no built-in table of effect +types. For example, a plugin's `block` effect would register `state` only, since in an event +rule nothing would ever unblock it. + +## Targets + +A target is an **identity**: `scheme:value`, for example `github-repo:github.com/acme/repo-1` +or `slack-channel:#platform`. A rule action's `target` has exactly one of: + +| Field | Meaning | +| --- | --- | +| `identity` | A fixed identity | +| `expr` | CEL returning `string` or `list(string)`, evaluated for each matching subject with the same variables as the trigger (`subject`, `event`, `now`) | + +```yaml +# Fixed +target: { identity: slack-channel:#platform } + +# Built from the evidence's labels +target: + expr: '"github-repo:github.com/" + subject.labels["organization"] + "/" + subject.labels["repository"]' + +# Built from the evidence's components (a component's identity in CCF is its identity labels) +target: + expr: > + subject.components + .filter(c, "repository" in c.labels) + .map(c, "github-repo:github.com/acme/" + c.labels["repository"]) + +# People: a risk's owners, by their linked Slack account +target: + expr: subject.owners.filter(o, has(o.slack_user_id)).map(o, "slack-user:" + o.slack_user_id) +``` + +Derived targets are what make SSP-free rules work: "fix *the repo this evidence is about*". +Nothing about targets is source-specific: the expression reads whatever the source's subject +exposes. + +**Mapping is the rule admin's job.** CCF stores no `scheme:value` identities: evidence +subjects have IDs, types, titles, props and links, and a component's identity is a set of +labels. Even if it stored one, it couldn't assume it's what a given plugin expects. The rule +admin builds the target the effector action needs from labels, props or other subject fields, +including any transformation, in the target expression. The scheme's published format +([below](#who-validates-a-target)) tells them what that is, and the API checks the result +against it. + +### Picking a fixed target + +For a fixed `identity`, the rule builder offers a **dropdown** when it can, and free text +otherwise: + +- **Published targets.** An effector action can publish the targets its plugin can list + (the Slack channels the bot is in, the repositories the GitHub App can see), filtered by + the action's `targets` patterns. The effector refreshes the list periodically. Publishing + is opt-in per action, because it sends the names to the API + ([effector interface](effector-interface.md#published-targets)). +- **Free text**, always allowed, checked against the scheme's format. A target that isn't + in the published list yet (a channel created a minute ago) still works. + +`GET /api/effector-actions/{agent}/{action}/targets?q=` serves the dropdown from what the +API has stored, so it works while the agent is offline. Each entry has an `identity` and a +`label` (for example the channel's display name). + +### Who validates a target + +Producing the right format is the rule admin's job, but they don't have to guess it: the +plugin publishes it. Each +target **scheme** a plugin supports comes with a value format (a regular expression), a +description and an example, and the effector registers them with each action. If a plugin +identified channels by number, its scheme would say so (`^[0-9]+$`, "numeric channel ID", +example `slack-channel-id:4211`), and the rule builder shows that next to the target field. + +| Check | Where | When | On failure | +| --- | --- | --- | --- | +| `scheme:value` syntax | API | Rule save (fixed identity), each evaluation (expressions) | `422`, or the target is skipped with a warning on the effect | +| Value matches the scheme's format | API, using the format the effector registered | Same | Same | +| Identity matches the effector action's `targets` patterns | API | Same | Same | +| Same checks again | Agent | Each delivery | `403`, reported | +| The target exists and is usable (the channel exists, the bot is in it) | Plugin | Apply | Status `failed` with the plugin's message, shown on the effect | + +Only the last check needs the provider, so it's the only one a rule admin finds out about +after saving. `POST /api/rules/preview` shows each resolved target with the format checks +applied. + +**Fan-out and grouping:** a rule produces **one effect per (rule action, target)**. If three +failing evidence streams all resolve to `github-repo:github.com/acme/repo-1`, the effect for +that repo lists all three as its subjects, and it clears when the last of them passes. A block +stays in place until all three are fixed, and a fix runs once for the repo. + +**Subjects are still handled one by one.** Inside an effect, each subject has its own timing +(`for`, `delay`) and its own entry and exit, and every delivery says which subjects entered or +left. A plugin can therefore act per subject when that makes sense for its provider. For +example, a Slack plugin can post **one message per stream**: when Alice's stream A and stream B +both fail, the effect for `slack-user:…alice` lists both, and the plugin keeps two messages, +each edited or resolved on its own as A or B changes. How a plugin uses this is up to the +plugin; the effect only guarantees the per-subject information. + +For event rules, each occurrence gets its own effect: one effect per (rule action, target, +occurrence). + +## When an expression fails + +An expression can fail at evaluation time even though it type-checked: a label the subject +doesn't have (`subject.labels["owner"]`), a division by zero, a list index out of range. + +- **A failing `when` or `if` counts as no match** for that subject. It never activates an + effect, and if it fails on a subject that was matching, that subject stops matching. +- **A failing target expression produces no target** for that subject, so no effect is + created for it. +- **Every failure is counted and kept visible**, per rule and per rule action: the subject, + the expression, the error and when it last happened. The rule view shows them, and + `POST /api/rules/preview` shows them for the current subjects, so a rule that silently + matches nothing, or loses a DM because a label is missing, is visible. +- The validator **warns** about unguarded map lookups when the rule is saved, and suggests a + guard (`"owner" in subject.labels && …`). + +## Examples + +**The feature request: evidence failed → Slack.** + +```yaml +trigger: + source: evidence + when: subject.labels["team"] == "payments" && subject.status == "not-satisfied" + for: 15m +actions: + - effector: { agent: platform-notify, action: notify-payments } + target: { identity: slack-channel:#payments-alerts } +``` + +**SSP posture blocks changes to one of its components.** + +```yaml +trigger: + source: ssp + when: > + subject.id == "9a4e01b7-…" && # the Repo-1 SSP + subject.controls.exists(c, c.control_id in ["SA-11", "SI-2"] && c.posture == "not-satisfied") +actions: + - effector: { agent: platform-notify, action: notify-owners } + target: { expr: 'subject.contacts.filter(c, has(c.slack_user_id)).map(c, "slack-user:" + c.slack_user_id)' } + - effector: { agent: platform-github, action: block-prs } + target: { identity: github-repo:github.com/acme/repo-1 } + delay: 24h +``` + +**Risk: high risks past their review deadline notify their owners, and again every day until +they're reviewed.** + +```yaml +trigger: + source: risk + when: > + has(subject.score) && subject.score >= 15 && + subject.status in ["open", "investigating"] && + has(subject.review_deadline) && subject.review_deadline < now +actions: + - effector: { agent: platform-notify, action: notify-owners } + target: { expr: 'subject.owners.filter(o, has(o.slack_user_id)).map(o, "slack-user:" + o.slack_user_id)' } + repeat: 24h + max_repeats: 10 +``` + +**Workflow: when a quarterly access review completes, hand its results to another system.** +Workflows already notify CCF users, so this is the kind of use the workflow sources were added +for. Notifying is still possible, for example people outside CCF. + +```yaml +trigger: + source: workflow-execution + on: [workflow.execution.status-changed] + if: subject.definition.name == "quarterly-access-review" && event.to == "completed" +actions: + - effector: { agent: grc-bridge, action: send-review-results } # e.g. a plugin-declared `dispatch` effect + target: { identity: grc-system:access-reviews } +``` + +**Risk event: tell GRC whenever a risk is accepted.** + +```yaml +trigger: + source: risk + on: [risk.accepted] + if: has(subject.score) && subject.score >= 10 +actions: + - effector: { agent: platform-notify, action: notify-grc } + target: { identity: slack-channel:#grc } +``` + +## Creating a rule + +The rule builder is data-driven: it asks the API what triggers exist and which effector +actions can be used, instead of hard-coding them. + +```mermaid +flowchart TD + S1["GET /api/rules/sources
per source: subject and event types
(CEL declarations), event names"] --> S2["User writes when, or on + if
(editor with completion, or forms that write CEL)"] + S2 --> S3["GET /api/effector-actions?kind=state&target-scheme=github-repo
(effector, action) pairs that fit this rule"] + S3 --> S4["User picks effector + action for each rule action,
then a fixed identity or a target expression"] + S4 --> S5["POST /api/rules/preview"] + S5 --> S6{"Preview OK?
matches now, resolved targets,
effector ready"} + S6 -- "no: 422 with reasons" --> S4 + S6 -- yes --> S7["POST /api/rules"] + S7 --> S8["Effects created (inactive);
rule evaluated immediately"] +``` + +`POST /api/rules/preview` evaluates the rule without saving it and returns: + +- the subjects that match **now** (for example 4 failing evidence streams); +- the targets those resolve to, per rule action (for example + `github-repo:github.com/acme/repo-1`, `github-repo:github.com/acme/repo-7`), and any that + fall outside the effector action's targets; +- expression cost estimates, and how long evaluation took; +- each named effector's status; +- warnings, such as target expressions that returned nothing for some subjects. + +Validation on save (`422` with field errors): + +| Check | Example error | +| --- | --- | +| Expressions compile and type-check against the source's declared types | `when` line 1, col 9: undefined field `staus` | +| `when` and `if` return `bool`; target expressions return `string` or `list(string)` | target expression returns `map`, expected `list(string)` | +| Expression cost is under the limit | Estimated cost 1.2M exceeds 100k | +| The source supports the rule kind and event types | `catalog` has no state (`when`) rules; `ssp` has no event `ssp.deleted` | +| The agent exists and registered the named action | No agent named `platform-gihub` | +| It registered the named action | `platform-notify` has no action `apply-branch-baseline` | +| The action registered the rule's kind | `block-prs` only registered `state` rules | +| A fixed `identity` matches its scheme's format | `slack-channel-id:general` must match `^[0-9]+$` (numeric channel ID) | +| A fixed `identity` is within the action's targets | `slack-channel:#random` isn't allowed by `notify-platform` | +| `delay` and `repeat` are only used on state rules | `repeat` needs a state rule | +| `max_repeats` is only used with `repeat` | `max_repeats` needs `repeat` | +| Map lookups in expressions are guarded (a warning, not an error) | `subject.labels["owner"]` fails on streams without the label: use `"owner" in subject.labels` first | +| The user saving can read the whole source | `403`: no type-level read permission on `risk` | + +An effector that's offline when the rule is saved isn't an error: the rule is saved with +the action `degraded`, and a warning. + +## Seeing what happened + +| View | Shows | +| --- | --- | +| Rule | State per target: inactive, pending (inside `for`), active. When each turned on. | +| Effect | Desired generation vs applied generation, applied status (`in-progress`, `waiting`, `applied`, `failed`, `dismissed`, `unknown`) and for how long, the links the plugin reported (the message, the pull request, the settings page), the subjects that caused it | +| Deliveries | Each webhook attempt in the last 24 hours: generation, event, response, retries | +| History | Every generation with its transition and reason, for the last 24 hours ([retention](operations.md#retention)) | + +Actions: **redeliver** an effect, **resync** an effector, **disable** a rule. + +**Disabling a rule clears its effects.** Every active effect gets `effect.clear` with +transition `disabled`, so blocks are lifted and notifications resolved, and every effect of +the rule is shown as `disabled`. The rule isn't evaluated while disabled. Enabling it +evaluates it again from scratch: effects whose condition holds activate again (after `for`). + +## Exceptions and decisions + +Effectors report things the API should decide on, called *observations*. Plugins name +them however they like; the API handles them by **kind** +([wire interface](wire-interface.md#observations)). They appear in a decision queue: + +| Kind | Decisions | +| --- | --- | +| `exception-request` | Accept → an exception on the effect for the requested `ref`, with an expiry and optionally a link to a risk or POA&M item. Reject → nothing changes | +| `dismissed` (a human rejected the plugin's result in the provider) | Acknowledge, or open a risk | +| `notice` | Acknowledge, or open a risk | + +An accepted exception changes the effect, so the effector gets a new generation. What an +exception means in the provider is up to the plugin. Effectors never decide exceptions +themselves. + +## Permissions + +Rules are an admin activity with their own resource and permissions (`rule:read`, +`rule:create`, `rule:update`, `rule:delete`). They aren't scoped to an SSP or label set. + +On top of that, **whoever saves a rule must be able to read its whole source**: + +| Check | When | Otherwise | +| --- | --- | --- | +| The user saving can read **every** subject of the rule's source: a type-level `read` on the source's authz resource (table below), not a check on individual subjects | Every create and every update, against the user making that change | `403`: the change is rejected | + +| Source | Authz resource (`internal/authz/manifest.yaml`) | +| --- | --- | +| `evidence` | `evidence` | +| `risk` | `risk` | +| `workflow-execution` | `workflow-execution` | +| `workflow-step` | `step-execution` | +| `ssp` | `ssp` | +| `catalog` | `catalog` | + +Rules have **no owner**. They run as the system, and nobody's permissions are attached to +them at evaluation time. The save check is what keeps that safe: a rule can only be created or +changed by someone who could read everything it can match, so it never sees more than its +last editor could. + +This is also why there's no owner to inherit from. If A creates a rule and B edits it, B is +checked as B. If B can't read the whole source, B's change is rejected, even if it only +touches the description. B can never borrow A's view by editing A's rule. + +The rule records `created-by`, `created-at`, `updated-by` and `updated-at`, and every change +is in its history. That's for audit only; it doesn't affect what the rule sees. + +## Routes + +User routes take a user JWT. + +| Route | Purpose | +| --- | --- | +| `POST /api/admin/agents`, `.../keys` | Create an agent and its keys (existing routes) | +| `DELETE /api/admin/agents/{id}?confirm=delete-rules` | Delete an agent and the rules that use it. Without `confirm`, `409` lists those rules | +| `PUT /api/admin/agents/{id}/effector` | Set the agent's webhook URL (`https`); starts verification | +| `GET /api/admin/agents/{id}/effector` | An agent's effector side: instances, webhook status, effector actions, rule actions using them | +| `POST /api/admin/agents/{id}/effector/resync` | Ask the agent to resync all its effects | +| `GET /api/effector-actions` | Registered effector actions across agents; filter by `agent`, `kind`, `effect`, `target-scheme` | +| `GET /api/effector-actions/{agent}/{action}/targets?q=` | Targets for the dropdown: published by the agent, plus matching components | +| `GET /api/rules/sources` | The trigger catalogue: per source, the CEL type declarations of its subject and events, with a description per field | +| `POST /api/rules/preview` | Dry run | +| `GET`, `POST /api/rules`; `GET`, `PUT`, `DELETE /api/rules/{id}` | Rules. `GET` includes the actions; `PUT` changes the rule's own fields only | +| `POST /api/rules/{id}/actions`; `GET`, `PUT`, `DELETE /api/rules/{id}/actions/{actionId}` | Rule actions, with stable IDs ([rule actions are resources](#rule-actions-are-resources)) | +| `PUT /api/rules/{id}/enabled` | Enable or disable. Disabling clears the rule's effects | +| `GET /api/rules/{id}/effects` | Effects of a rule | +| `GET /api/effects/{id}`, `.../history`, `.../deliveries` | One effect | +| `POST /api/effects/{id}/redeliver` | Apply again: creates a new generation with transition `redelivered` and the same content, so the agent doesn't drop it as already applied | +| `GET /api/observations?decision=pending` | Decision queue | +| `POST /api/observations/{id}/decision` | Accept or reject | + +## Decisions + +Questions raised while writing this document, and how they were answered. + +1. **Target mapping.** CCF can't assume an identity it holds is what a plugin expects. Rule + admins map subject data to the target format, transforming it in the target expression + if needed. Subject templates aren't required to declare identities. +2. **Writing CEL.** Start with an expression editor with completion from + `GET /api/rules/sources`, and experiment from there. No condition forms for now. +3. **Per-rule parameters.** None. Two rules that need different behaviour use two effector + actions. +4. **Agent references.** Rules store the agent's ID, because agent names aren't unique in + the code. That makes the earlier "renaming is forbidden" rule unnecessary: renaming no + longer affects rules. Deleting an agent warns, then deletes every rule that uses it. +5. **Permissions and ownership.** Rules are an admin activity with their own + permissions, not scoped to SSPs or labels. Whoever creates or edits a rule must be able to + read its whole source, or the change is rejected. Rules have no owner: they run as the + system, and `created-by` / `updated-by` are kept for audit only. +6. **Actions are resources.** Rule actions have stable IDs and their own routes, so editing a + rule or an action never resets effects that didn't change. (This replaces an earlier + decision to edit actions only inline in the rule document.) +7. **Event batching.** Not in v1: one effect per occurrence. Batching can come later if + needed. +8. **Disabling.** Clears the rule's effects and shows them as `disabled`. +9. **People as targets.** Subject documents expose people's linked Slack user IDs + (`slack_user_id`) next to their email. + +## Open questions + +None at the moment. Remaining details can be settled during implementation. diff --git a/docs/effectors/wire-interface.md b/docs/effectors/wire-interface.md new file mode 100644 index 00000000..6db454e0 --- /dev/null +++ b/docs/effectors/wire-interface.md @@ -0,0 +1,511 @@ +# Wire interface + +The protocol between the API and effectors, in both directions. An effector is a CCF agent +running effector plugins, so this is what the **agent** implements; plugins never see it (they +see the [effector interface](effector-interface.md)). + +```mermaid +flowchart LR + API["CCF API"] -->|"webhooks: effector.verify,
effect.apply, effect.clear"| EF["Agent (effector plugins)"] + EF -->|"REST: token, registration, heartbeat,
effects list, status, observations, context"| API +``` + +- **API → agent:** signed webhooks that tell the agent something changed. Each carries a + whole document, so no follow-up call is needed. +- **Agent → API:** REST calls with the agent's JWT, to register, report and pull. They sit + under `/api/agent/`, next to the agent's existing routes (heartbeat, config sync). + +All bodies are JSON with kebab-case keys. Every request in both directions carries +`ccf-effector-protocol: 1`. + +## Authentication + +Effectors are agents, so they use the agent token they already have. The exchange is unchanged: + +```http +POST /api/auth/agent/token +content-type: application/x-www-form-urlencoded + +client_id=…&client_secret=… +``` + +The JWT identifies the agent. Effector routes accept agent JWTs only (never a user token or +an anonymous caller, even with public agent endpoints on). The effects routes additionally +require the instance to have registered effector actions. An agent only sees and reports on +effects for its own actions. + +## Registration + +```mermaid +sequenceDiagram + autonumber + actor Admin + participant API as CCF API + participant EF as Agent + + Admin->>API: PUT /api/admin/agents/{id}/effector {base-url} + Note over API: status = pending-verify (no instance yet) + Note over EF: Agent starts, already authenticated
(existing agent token) + EF->>API: PUT /api/agent/instances/{instanceId}/effector + API->>API: base URL matches? upsert the instance, store its actions + API-->>EF: 200 {revision, delivery_keys} + API->>EF: effector.verify {challenge} (to base-url + /v1/webhook) + EF-->>API: 200 {challenge} + API->>API: agent effector status = ready + EF->>API: GET /api/agent/effects (all pages) + loop every heartbeat interval + EF->>API: POST /api/agent/heartbeat (effector block) + API-->>EF: 201 {effector: {resync?, delivery_keys}} + end +``` + +v1 assumes **one replica** per agent with effector plugins +([multiple instances](effector-interface.md#multiple-instances)). + +### The base URL belongs to the agent, and the admin sets it + +The address deliveries go to is a property of the **agent**, set by an admin, not by whichever +instance registers first or last. It's a **base URL**; the agent serves fixed paths under it: + +| Path | Used for | +| --- | --- | +| `{base-url}/v1/webhook` | Deliveries from the API (`effector.verify`, `effect.apply`, `effect.clear`) | +| `{base-url}/ext/{plugin}/…` | Provider webhooks routed to a plugin | +| `{base-url}/healthz`, `{base-url}/readyz` | Health and readiness ([plugin runtime](plugin-runtime.md#the-listener)) | + +- `PUT /api/admin/agents/{id}/effector` with `{"base-url": "https://…"}` sets it (`https` + only, unless the API runs with `CCF_EFFECTOR_ALLOW_INSECURE_WEBHOOKS=true`). The admin can + set it before any agent is deployed. Changing it resets the agent to `pending-verify`. +- An instance registration carries its `public_url` as `base-url`. The two are compared after + normalisation: scheme and host lowercased, default port (`:443`, `:80`) removed, trailing + slash removed, no query or fragment allowed. A different URL, or none set by the admin yet, + gets `409`. The instance's actions are stored anyway (so the admin sees them), but nothing + is delivered until the URL is set and verified. + +So a leaked agent key can register a fake instance, but it can't redirect deliveries: only an +admin can change where they go. + +### `effector.verify` + +Verification is **per agent**, and needs a running agent to answer it. The API sends a +challenge to `{base-url}/v1/webhook` when an instance registers with a matching URL while the +agent is `pending-verify` (the URL was just set or changed, or a new signing key came into +use). Until it's answered, the API retries with backoff after each later registration or +heartbeat. The agent is already authenticated by then: it uses its existing agent token, so +there's no extra login step for effectors. + +```json +{ "type": "effector.verify", "agent-id": "5d0c…", "challenge": "q8Xc…" } +``` + +The agent answers `200 {"challenge": "q8Xc…"}`. Until it does, the agent's effector status is +`pending-verify` and nothing is delivered. Instance health is separate and unchanged: an +instance is fresh or stale by the API's existing `InstanceStaleAfter` setting. + +### `PUT /api/agent/instances/{instanceId}/effector` + +`instanceId` is the agent's existing instance ID. An instance registers when it starts with at +least one effector plugin enabled, and again after every applied configuration change. +Registration is idempotent: the same body returns the same revision. + +Registration **upserts the instance's `AgentInstance` row**. Today that row is only created by +heartbeats that carry a `config_digest`, which an agent with `remote_config.mode: off` never +sends (`internal/service/relational/agentcfg/service.go`). An effector must have an instance +row whatever its remote config mode. At the per-agent instance cap, registration fails with +`409` and a reason, instead of silently not creating the row as heartbeats do today. + +```json +{ + "version": "1.9.0", + "base-url": "https://agent-platform.acme.internal", + "plugins": [ + { "name": "github-checks", "version": "1.0.0", "digest": "sha256:9f2c…" }, + { "name": "slack", "version": "1.0.0", "digest": "sha256:41ab…" } + ], + "actions": [ + { + "name": "block-prs", + "description": "Required check that fails while the rule is active", + "plugin": "github-checks", + "effect": "block", + "rule-kinds": ["state"], + "targets": { "include": ["github-repo:github.com/acme/*"], "exclude": [] }, + "target-schemes": [ + { + "name": "github-repo", + "value-pattern": "^github\\.com/[^/]+/[^/]+$", + "description": "Repository as host/owner/name", + "example": "github.com/acme/repo-1" + } + ], + "on-clear": "revert", + "publish-targets": false, + "supports-exceptions": true, + "observations": [{ "type": "change-claims-remediation", "kind": "exception-request" }] + }, + { + "name": "notify-platform", + "description": "Short alert to platform channels", + "plugin": "slack", + "effect": "notify", + "rule-kinds": ["state", "event"], + "targets": { "include": ["slack-channel:#platform", "slack-channel:#platform-*"], "exclude": ["slack-channel:#platform-exec"] }, + "target-schemes": [ + { "name": "slack-channel", "value-pattern": "^#[a-z0-9_-]+$", "description": "Channel name", "example": "#platform" } + ], + "on-clear": "resolve", + "publish-targets": true, + "supports-exceptions": false, + "observations": [] + } + ] +} +``` + +`actions` are the effector actions from the agent's config +([effector interface](effector-interface.md#effector-actions)), already validated by their +plugins. Their `config` is never sent here: the API only learns what an action is and where it +may act (the agent's config report, when enabled, carries the masked config separately). +Target patterns follow the [target pattern grammar](effector-interface.md#target-pattern-grammar). + +| Response | Meaning | +| --- | --- | +| `200` | `{revision, delivery_keys: [{kid, alg: "Ed25519", public_key, status: current \| next}]}` | +| `400` | Malformed body | +| `409` | `base-url` differs from the agent's, the admin hasn't set one yet, or the agent is at its instance cap | +| `422` | A malformed effect label, an empty or unknown rule kind (only `state`, `event`), an `on-clear` other than `revert`, `resolve`, `none`, a duplicate action name, a malformed target pattern, a target pattern using a scheme not in `target-schemes`, an invalid `value-pattern` | +| `403` | The agent is disabled | + +### The agent's actions + +The agent's actions are the ones its fresh instance last registered. A rule action is +`degraded` when no fresh instance of the agent registers its action. A delivery that reaches +an agent without the action gets `410`, and the rule action turns `degraded`. + +### Heartbeat + +The existing `POST /api/agent/heartbeat` gets an `effector` block in its request, and, for the +first time, a response body. Both use the heartbeat's existing conventions (snake_case, the +instance ID as a UUID). The block is only honored on heartbeats authenticated with an agent +JWT; an anonymous heartbeat (public agent endpoints on) never carries effector state. + +```json +{ + "effector": { + "registration_revision": 3, + "held_digest": "sha256:…" + } +} +``` + +- `held_digest` is a hash over the sorted (effect ID, generation) pairs the agent holds in + memory, that is, what it **received**, not what it applied. Failed, in-progress or dismissed + effects still match, so the digest settles. The API compares it with its current desired + set for the agent. +- The response, `201` with a body for agents that send an `effector` block, says whether to + resync and carries the signing keys: + `{"effector": {"resync": true, "delivery_keys": [...]}}`. On `resync: true` the agent + fetches every effect again. + +Today the heartbeat handler answers `201` with no body (`internal/api/handler/heartbeat.go`), +and the SDK's `Create` discards the response (`sdk/heartbeat.go`). The response body is +additive. The SDK gets a new method that returns it, leaving `Create` unchanged for older +agents. + +An admin's "resync" sets the flag for the agent's next heartbeat. + +### What the agent holds + +`GET /api/agent/effects` returns **effects**, not rules, and not a log of events. Each effect +is the current desired state of one rule action on one target: the agent doesn't need the +rules, only what they currently want done. What caused each effect is inside it: + +- `trigger.subjects`: the subjects that currently make it hold (for example the failing + evidence streams), each with the document the rule saw. +- `trigger.event`: for an event rule, the event that fired it. +- `transition` and `generation`: the latest change, not every change. + +It isn't a job queue: a state effect that changed three times while an agent was down comes +back once, at its latest generation. Event effects are the closest thing to jobs (one per +occurrence, held until the agent reports a final status). The full history of every effect +(every generation, delivery and status) stays in the API, for people to read. + +The set an agent holds, and that `GET /api/agent/effects` returns, is bounded: + +| Effect | Held while | +| --- | --- | +| State effect, active | It's active | +| State effect, finished | Until the agent reports the `finished` delivery as applied. Then it's dropped; the API still keeps it until it clears | +| State effect, inactive | Until the agent reports its `cleared` (or `disabled`, `removed`) as applied. Then it's dropped from the set | +| Event effect (`occurred`) | Until the agent reports a final status (`applied`, `failed`, `dismissed`). Then it's dropped | + +A target with no effect is **inactive**. Plugins must treat it that way (for example, a +blocking plugin posts a passing check on a target it has no effect for), so the set doesn't +grow with every target that was ever matched. History stays in the API. + +## Webhooks (API → effector) + +| Event | Sent when | Body | +| --- | --- | --- | +| `effector.verify` | The admin set or changed the agent's URL, or a new signing key came into use | challenge | +| `effect.apply` | A state effect turned active, changed while active, reached its `repeat` interval, ran out of repeats (`finished`), or was redelivered; an event effect occurred | effect document | +| `effect.clear` | A state effect turned inactive, its rule was disabled, or its action or rule was deleted | effect document | + +There's no resync webhook: resyncs are asked for in the heartbeat response. + +### Headers and signing + +[Standard Webhooks](https://www.standardwebhooks.com/) with asymmetric signatures: + +```http +POST https://agent-platform.acme.internal/v1/webhook +webhook-id: dlv_01JDX7K9Q2 +webhook-timestamp: 1764500000 +webhook-signature: v1a,MEUCIQD… +ccf-effector-protocol: 1 +content-type: application/json +``` + +- `v1a` is Ed25519 over `{webhook-id}.{webhook-timestamp}.{body}`. +- **One key pair for the whole API**, not one per agent. The private key is a file named by + `CCF_EFFECTOR_SIGNING_KEY`. Agents only ever receive public keys, in registration and + heartbeat responses (`delivery_keys`), each identified by `kid` (a hash of the public key). +- **Rotation:** the operator configures the next key as `CCF_EFFECTOR_SIGNING_KEY_NEXT`. The + API then publishes it as `next` while still signing with the current one, so every agent + learns it within a heartbeat. When the operator promotes it (it becomes + `CCF_EFFECTOR_SIGNING_KEY`), the API signs with it, re-verifies each agent's URL, and keeps + publishing the old public key as accepted for an overlap period. +- The agent rejects timestamps more than 5 minutes off, and `webhook-id`s it has seen. + +### The effect document + +```json +{ + "type": "effect.apply", + "effect": { + "id": "eff_7f3c", + "generation": 42, + "transition": "activated", + "state": "active", + "active-since": "2026-11-30T09:12:00Z", + "rule": { "id": "rul_19a2", "name": "Repos keep branch protection", "kind": "state" }, + "action": { + "rule-action-id": "act_55d1", + "effector-action": "apply-branch-baseline", + "effect": "remediate-apply" + }, + "target": { + "identity": "github-repo:github.com/acme/repo-1", + "scheme": "github-repo", + "value": "github.com/acme/repo-1" + }, + "trigger": { + "source": "evidence", + "subjects": [ + { + "id": "4d1a…", + "title": "Branch protection on main", + "matched-since": "2026-11-30T08:40:00Z", + "entered-at": "2026-11-30T09:12:00Z", + "url": "https://ccf.acme/evidence/4d1a…", + "document": { "status": "not-satisfied", "labels": { "team": "platform" } } + } + ], + "changes": { "entered": ["4d1a…"], "left": [] }, + "event": null + }, + "exceptions": [], + "applied": { + "generation": 41, + "status": "applied", + "links": [{ "rel": "settings", "href": "https://github.com/acme/repo-1/settings/branches", "title": "Branch protection" }], + "refs": { "changed-fields": ["required-reviews"] } + }, + "links": { "ui": "https://ccf.acme/rules/rul_19a2/effects/eff_7f3c" } + } +} +``` + +| Field | Notes | +| --- | --- | +| `transition` | `activated`, `updated`, `repeated` (the rule action's `repeat` elapsed; `repeat-count` says which), `finished` (`max_repeats` reached; no more repeats until the condition changes), `redelivered` (an admin asked to apply it again), `cleared`, `disabled` (the rule was disabled), `removed` (action, rule or agent deleted), `occurred` (event rule) | +| `state` | `active`, `finished`, `inactive`, `occurred` | +| `trigger.subjects` | What caused this effect, for this target, now. For state rules, every subject that has entered it. Each has its `id`, `matched-since` (when it started matching), `entered-at` (when it counted, after `for` and `delay`), and `document`, the subject document the rule's expressions were evaluated against (the source's schema, kebab-case) | +| `trigger.changes` | State rules: the subject IDs that `entered` or `left` with this generation. Lets a plugin act per subject (edit one message, resolve another) | +| `trigger.event` | Event rules only: `{type, occurred-at, document}`, where `document` is the event document the rule's `if` saw | +| `exceptions` | Accepted exceptions: `{kind, ref, expires, risk-id?, poam-id?}` | +| `applied` | What the agent last reported for this effect: generation, status, `links` and `refs`. The API is the only store of plugin state, so this is how a plugin gets its refs (a message ID, a check run ID) back after a restart | +| `target` | `identity` as the rule produced it, split into `scheme` and `value` | +| `action.effector-action` | The effector action to run. The effector looks up its plugin and config locally; neither is in the document | + +The document is self-contained so the effector can act without calling back. A plugin that +needs more detail than the document carries calls the context route. + +The API **builds the document when it sends it**, not when the generation is created, so +`applied` always carries the latest status, links and refs the agent reported, even for a +generation created before that report arrived. + +### Responses and retries + +| Effector response | API does | +| --- | --- | +| `2xx` | Delivered. The result comes later through the status route | +| `409` | The effector already has a higher generation for this effect: delivered, nothing to do | +| `410` | The agent doesn't have the effector action: the rule action turns `degraded` | +| `401`, `403` | Signature rejected, or the target doesn't match the action's targets: recorded, admins notified, no retries | +| `429`, `5xx`, timeout (10s) | Retry with exponential backoff and jitter for up to 24h | + +- The agent applies at most one generation per effect at a time, and drops a generation + older than one it already holds, so the newest always wins + ([plugin runtime](plugin-runtime.md#concurrency-and-ordering)). +- At least once: the same generation may arrive twice. The effector deduplicates by + `webhook-id` and generation. +- When retries run out, the effect's applied status becomes `unknown`, and the heartbeat + digest triggers a resync once the agent is back. +- **Redeliver** (an admin action) doesn't resend the same generation, which the agent would + drop as already applied. It creates a new generation with transition `redelivered` and the + same content, so the plugin applies it again. + +## Effector → API + +All routes take the agent's JWT. An agent only sees and reports on effects it owns. + +| Route | Purpose | +| --- | --- | +| `PUT /api/agent/instances/{instanceId}/effector` | Register ([above](#registration)) | +| `POST /api/agent/heartbeat` | Heartbeat ([above](#heartbeat)) | +| `GET /api/agent/effects?plugin=&state=&cursor=` | Page through owned effects, any state. Same document as webhooks | +| `PUT /api/agent/instances/{instanceId}/targets` | Publish listed targets for actions with `publish-targets` ([below](#published-targets)) | +| `GET /api/agent/effects/{effectId}` | One effect, current generation | +| `PUT /api/agent/effects/{effectId}/status` | Report applied state | +| `POST /api/agent/effects/{effectId}/observations` | Report something for a human or the API to decide | +| `GET /api/agent/effects/{effectId}/context` | Extra detail for the effect's subjects | + +### Status + +```json +{ + "generation": 42, + "status": "waiting", + "message": "Pull request opened; waiting for review and merge", + "links": [ + { "rel": "pull-request", "href": "https://github.com/acme/infra/pull/91", "title": "Fix bucket encryption (acme/infra#91)" }, + { "rel": "repository", "href": "https://github.com/acme/infra", "title": "acme/infra" } + ], + "refs": { "pr-number": 91 }, + "observed-at": "2026-11-30T09:12:04Z" +} +``` + +| `status` | Meaning | +| --- | --- | +| `in-progress` | The plugin is still working on it (writing a change, calling the provider) | +| `waiting` | The plugin is done; the result now waits for a person in the provider (a pull request to review and merge, a change to approve, a ticket to pick up). The effect stays active until the trigger stops holding, for example when the next collection sees the merged change applied | +| `applied` | The provider reflects this generation | +| `failed` | Couldn't apply. `message` says why; the agent retries according to its own policy | +| `dismissed` | A human rejected the result in the provider (closed the pull request). Not retried | + +A plugin can move an effect from `in-progress` to `waiting` to `applied` (or `dismissed`) within +one generation. What each report does to the stored values: + +| Field | On each report | +| --- | --- | +| `status`, `message` | Replaced | +| `refs` | **Merged key by key**: keys in the report overwrite stored ones, keys it doesn't mention are kept, and a key set to `null` is removed. A report without `refs` keeps them all, so a later `in-progress` doesn't wipe a stored message ID | +| `links` | Replaced when the report has `links`; kept when it doesn't | + +Refs and links survive across generations too, until the plugin changes them. + +**`links`** are for people: where to see what the plugin did. Each has a `rel` (a short kind, +such as `message`, `pull-request`, `repository`, `settings`, `ticket`), an `href` and a +`title`. The effect view shows them as clickable links, without CCF knowing anything about the +plugin. They're kept with the effect and sent back in its `applied` block, like `refs`. +**`refs`** stay for the plugin's own state (IDs it needs later) and aren't shown as links. +`href` must be `https`; other schemes are rejected (`422`). + +`409` if `generation` is lower than one already reported. `404` if the effector doesn't own +the effect. + +### Published targets + +For effector actions with `publish-targets: true` +([effector interface](effector-interface.md#published-targets)). The body replaces what the +API stored for those actions: + +```json +{ + "listed-at": "2026-11-30T09:00:00Z", + "actions": [ + { + "name": "notify-platform", + "truncated": false, + "targets": [ + { "identity": "slack-channel:#platform", "label": "platform (412 members)" }, + { "identity": "slack-channel:#platform-alerts", "label": "platform-alerts (38 members)" } + ] + } + ] +} +``` + +`422` if an action isn't registered, doesn't have `publish-targets`, or lists an identity +outside its `targets` patterns. `413` above the size limit. + +### Observations + +An observation is something the plugin saw that a person should decide on. The API only +understands its **kind**. The **type** is the plugin's own label, shown to people. + +| `kind` | Meaning | Possible decisions | +| --- | --- | --- | +| `exception-request` | The plugin asks for an exception for `ref` (an identifier in the provider) | Accept (adds an exception to the effect, with an expiry), reject | +| `dismissed` | A human rejected the plugin's result in the provider | Acknowledge, open a risk | +| `notice` | Something worth recording, nothing to change | Acknowledge, open a risk | + +```json +{ + "kind": "exception-request", + "type": "change-claims-remediation", + "generation": 42, + "ref": "acme/repo-1#91", + "summary": "Change says it remediates POAM-123", + "data": { "claims": ["poam:2b7e…"] }, + "observed-at": "2026-11-30T10:01:00Z" +} +``` + +Effector actions declare the observation types they may send, with their kind, at +registration. Unknown types get `422`. Decisions are made by people in the API +([user interface](user-interface.md#exceptions-and-decisions)). An accepted +`exception-request` adds `{ref, expires, …}` to the effect's `exceptions`, and a new +generation is delivered. What the plugin does with an exception is up to the plugin. + +### Context + +`GET /api/agent/effects/{effectId}/context` returns, for the effect's **current +subjects only**: the evidence (including the policy output and the input digest), the +controls linked to it with their statement text, and any linked risks or POA&M items. It's +paginated, with a size limit per subject. An effector can't use it to read anything outside +its own effects. + +## Versioning + +- `ccf-effector-protocol: 1` on every request in both directions. Additive changes (new + fields, new event types) keep version 1. Effectors must ignore unknown fields and answer + `422` to unknown event types. +- A breaking change gets version 2. The API keeps sending version 1 to effectors that + registered with it. + +## Decisions + +1. **Webhooks only.** No pull mode for deliveries: the API has to reach the agent's URL. +2. **No document size cap** for now. Effect documents carry every current subject; revisit if + sizes become a problem in practice. +3. **Own signing key.** Deliveries are signed with a dedicated Ed25519 key pair, one for the + whole API, not the API's JWT signing key and not one per agent. +4. **One replica in v1.** No change feed, no "as of a token" digest, no retryable `410`; + multiple instances wait for leader election in v2. + +## Open questions + +None at the moment.