diff --git a/cmd/dashboards/import.go b/cmd/dashboards/import.go index 8b0084ce..a89c4d8c 100644 --- a/cmd/dashboards/import.go +++ b/cmd/dashboards/import.go @@ -13,7 +13,6 @@ import ( "github.com/spf13/cobra" "go.uber.org/zap" "gorm.io/datatypes" - "gorm.io/gorm/clause" ) func newDashboardsImportCMD() *cobra.Command { @@ -89,7 +88,8 @@ func importDashboards(cmd *cobra.Command, args []string) { rec.Filter = datatypes.NewJSONType(lf) } - if err := db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&rec).Error; err != nil { + // An operator-run import may overwrite a filter by ID, but never its badge settings. + if err := db.Clauses(relational.FilterImportUpsert()).Create(&rec).Error; err != nil { sugar.Fatalf("failed to create filter '%s': %v", in.Name, err) } diff --git a/docs/authz-oss-cedar.md b/docs/authz-oss-cedar.md index 8f5e4ada..95cfa28a 100644 --- a/docs/authz-oss-cedar.md +++ b/docs/authz-oss-cedar.md @@ -13,7 +13,7 @@ class). Attribute-rich (ABAC/ReBAC) policy is an Enterprise / bring-your-own-PDP | Driver | What it is | | --------- | ---------------------------------------------------------------------- | -| `builtin` | **Default.** Pre-authz rules: authenticated = allowed, admin via SSO groups. The `agent` resource (agent reads and remote configuration) also requires the admin check for users; agent service accounts may only register, ingest and sync. | +| `builtin` | **Default.** Pre-authz rules: authenticated = allowed, admin via SSO groups. The `agent` resource (agent reads and remote configuration) also requires the admin check for users; agent service accounts may only register, ingest and sync. `filter:publish` (a saved filter's public badge, see [filter-badges.md](filter-badges.md)) also requires the admin check. | | `cedar` | Embedded Cedar RBAC against the bundled role policies (this document). | | `authzen` | Delegate every decision to a remote AuthZen-compliant PDP (bring your own). | @@ -34,7 +34,7 @@ Four fixed global roles plus the agent service role (the manifest lists every ro | Role | Grants | | ------------- | ---------------------------------------------------------------------------- | | `admin` | Everything (all resources, all actions). | -| `contributor` | Author content (OSCAL docs, risk/poam register, workflows, dashboards, evidence); read everything; no admin. | +| `contributor` | Author content (OSCAL docs, risk/poam register, workflows, dashboards, evidence); read everything; no admin. Cannot publish filter badges (`filter:publish`). | | `auditor` | Read everything; record evidence; maintain the risk/poam register. | | `viewer` | Read everything; no writes. | | `agent` | Service accounts: ingest evidence/heartbeats, register, sync their remote configuration. | diff --git a/docs/docs.go b/docs/docs.go index 6b0eb173..8fd77f08 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -5775,7 +5775,7 @@ const docTemplate = `{ } }, "post": { - "description": "Creates a new filter.", + "description": "Creates a new filter. Setting a non-default badge needs the filter:publish\npermission (403 without it); a slug another filter holds is a 409.", "consumes": [ "application/json" ], @@ -5810,6 +5810,18 @@ const docTemplate = `{ "$ref": "#/definitions/api.Error" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, "422": { "description": "Unprocessable Entity", "schema": { @@ -5916,7 +5928,7 @@ const docTemplate = `{ } }, "put": { - "description": "Updates an existing filter.", + "description": "Updates an existing filter. Changing its badge, or the predicate, SSP or\nscope following of a filter whose badge is published, needs the\nfilter:publish permission (403 without it); a slug another filter holds\nis a 409. Omitting badge keeps the current settings.", "consumes": [ "application/json" ], @@ -5958,12 +5970,24 @@ const docTemplate = `{ "$ref": "#/definitions/api.Error" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/api.Error" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -6012,6 +6036,71 @@ const docTemplate = `{ } } }, + "/filters/{id}/badge.svg": { + "get": { + "description": "Renders the SVG badge of a saved filter by ID, whether or not it is published.\nRequires filter read and the evidence read authorization of\n/evidence/compliance-by-filter/{id}. Takes no query parameters.", + "produces": [ + "image/svg+xml", + "application/json" + ], + "tags": [ + "Filters" + ], + "summary": "Preview a filter's badge", + "parameters": [ + { + "type": "string", + "description": "Filter ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "SVG badge", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + }, + "security": [ + { + "OAuth2Password": [] + } + ] + } + }, "/filters/{id}/responsibilities": { "post": { "description": "Associates this filter with an upstream responsibility the given downstream\nSSP inherits (BCH-1339's filter_responsibilities), so the responsibility's\nposture is computed live from the filter's evidence. When controlId is given,\nthe filter is also linked to that control (so control-level compliance\nsurfaces include it) with provenance recorded: detaching removes the control\nlink only if this attach created it.", @@ -30954,6 +31043,54 @@ const docTemplate = `{ ] } }, + "/public/badges/{file}": { + "get": { + "description": "Renders the SVG badge published under a slug. Anonymous: no token is needed.\nOnly the badge label and aggregate state (passing, failing, unknown or no\nevidence) are disclosed. Unknown, invalid and unpublished slugs all return the\nsame 404. Takes no query parameters.", + "produces": [ + "image/svg+xml", + "application/json" + ], + "tags": [ + "Filters" + ], + "summary": "Get a published filter badge", + "parameters": [ + { + "type": "string", + "description": "Badge slug followed by .svg, e.g. payments-service.svg", + "name": "file", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "SVG badge", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + } + } + }, "/risks": { "get": { "description": "Lists risk register entries with filtering, sorting, and pagination.", @@ -37540,6 +37677,14 @@ const docTemplate = `{ "handler.FilterWithAssociations": { "type": "object", "properties": { + "badge": { + "description": "Badge is never imported or copied: imports, clones and generated filters start\nunpublished.", + "allOf": [ + { + "$ref": "#/definitions/relational.FilterBadge" + } + ] + }, "components": { "type": "array", "items": { @@ -41394,6 +41539,15 @@ const docTemplate = `{ "name" ], "properties": { + "badge": { + "description": "Badge changes the filter's public badge (docs/filter-badges.md) and needs the\nfilter:publish permission unless it leaves the settings unchanged. Omitted keeps the\ncurrent settings (POST: unpublished defaults); null resets them to the defaults.", + "allOf": [ + { + "$ref": "#/definitions/handler.filterBadgeRequest" + } + ], + "x-nullable": true + }, "components": { "type": "array", "items": { @@ -41657,6 +41811,26 @@ const docTemplate = `{ } } }, + "handler.filterBadgeRequest": { + "type": "object", + "properties": { + "enabled": { + "description": "Enabled publishes the badge at /api/public/badges/{slug}.svg; it requires a slug.", + "type": "boolean" + }, + "label": { + "description": "Label is the badge's left-hand text: 1-64 characters after trimming, no control\ncharacters.", + "type": "string", + "example": "compliance" + }, + "slug": { + "description": "Slug is the public identifier: lowercase letters, digits and single hyphens, at\nmost 63 characters, unique across filters. null clears it and unpublishes.", + "type": "string", + "x-nullable": true, + "example": "payments-production" + } + } + }, "handler.filteredSearchRequest": { "type": "object", "required": [ @@ -50737,6 +50911,14 @@ const docTemplate = `{ "relational.Filter": { "type": "object", "properties": { + "badge": { + "description": "Badge is never imported or copied: imports, clones and generated filters start\nunpublished.", + "allOf": [ + { + "$ref": "#/definitions/relational.FilterBadge" + } + ] + }, "components": { "type": "array", "items": { @@ -50775,6 +50957,22 @@ const docTemplate = `{ } } }, + "relational.FilterBadge": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "label": { + "description": "Label is the plain-text left-hand side of the badge.", + "type": "string" + }, + "slug": { + "description": "Slug is the public identifier in /api/public/badges/{slug}.svg. Absent is NULL, never \"\".", + "type": "string" + } + } + }, "relational.FilterResponsibility": { "type": "object", "properties": { diff --git a/docs/filter-badges.md b/docs/filter-badges.md new file mode 100644 index 00000000..8b32899e --- /dev/null +++ b/docs/filter-badges.md @@ -0,0 +1,374 @@ +# Saved evidence filter badges: API specification + +Status: implemented. The model, the `filter:publish` action, the preview route +(`GET /api/filters/{id}/badge.svg`) and the public route +(`GET /api/public/badges/{slug}.svg`) are in place; the renderer lives in +`internal/badge`. + +## Purpose and scope + +Let an administrator explicitly publish a saved evidence filter's aggregate +compliance state as an API-rendered SVG that can be embedded in a README. +Publishing is an opt-in setting on the saved filter, not an anonymous endpoint +that accepts arbitrary evidence labels or filter expressions. + +With this feature, the public badge route is the only supported anonymous view +of a filter's aggregate. The JSON `compliance-by-filter` endpoint is not intended +for anonymous use; its current anonymous access under builtin with public agent +endpoints enabled is expected to go away. Do not build integrations on it. + +Saved filters are inexpensive and already support SSP scope, scope-following, +and control/component associations. Reuse those objects rather than introducing +a parallel badge-query model. + +The API owns lookup, aggregation, SVG rendering, and cache headers. No +shields.io integration, external badge service, worker, or additional runtime is +required. Neither badge endpoint returns individual evidence. + +## Existing implementation to reuse + +- [Filter routes and request handling](../internal/api/handler/filter.go): + `POST /api/filters`, `PUT /api/filters/:id`, and authenticated filter reads. +- [Filter model](../internal/service/relational/filters.go): the persisted + predicate, SSP binding, scope-following base, and associations. +- [ComplianceByFilter](../internal/api/handler/evidence.go): + `GET /api/evidence/compliance-by-filter/:id` loads a saved filter and calls + `GetStatusCountsByFilters(filter.Filter.Data())`. +- [Evidence service](../internal/service/relational/evidence/service.go): + `GetStatusCountsByFilters` uses the latest-evidence query, applies the saved + predicate, and groups counts by `status->>'state'`. +- [Authorization manifest](../internal/authz/manifest.yaml) and + [builtin driver](../internal/authz/builtin.go): contributors have filter + create/update rights under Cedar; builtin currently permits ordinary filter + actions for every authenticated caller. Neither is sufficient authority to + publish data. + +## Filter settings and persistence + +Add a nested `badge` object to filter create/update requests and authenticated +filter responses. For example, these are the new fields within an otherwise +valid filter request: + +```json +{ + "badge": { + "enabled": true, + "label": "compliance", + "slug": "payments-service" + } +} +``` + +| Field | Contract | +| --- | --- | +| `enabled` | Boolean; defaults to `false` on creation and for existing filters. | +| `label` | Plain-text left-hand badge label; defaults to `compliance`. Trim surrounding whitespace; require 1–64 Unicode code points and reject control characters. | +| `slug` | Nullable public identifier. Required when enabled; `null` clears it and disables publication. | + +Slug rules: + +- Require 1–63 ASCII characters matching + `^[a-z0-9]+(?:-[a-z0-9]+)*$`: lowercase words separated by single hyphens. + Reject invalid input rather than silently lowercasing or rewriting it. +- Slugs are human-readable, not secrets or authorization credentials. They + must not contain confidential identifiers. +- Enforce uniqueness across all filters, including disabled ones, with a + partial unique index on non-null `badge_slug`. +- Store absent slugs as SQL `NULL`, never an empty string. Reject `""`. +- Changing or clearing a slug removes the old public mapping in the same + transaction. There are no aliases or redirects. + +Suggested columns on `filters` are `badge_enabled` (non-null, default false), +`badge_label` (non-null, default `compliance`), and nullable `badge_slug`. +Keep storage columns out of the flat JSON shape; expose only `badge`. +Add a database check that an enabled badge has a non-null slug. + +### Write semantics and compatibility + +- `POST /api/filters` without `badge` creates an unpublished filter. +- `PUT /api/filters/:id` without `badge` preserves all existing badge settings, + so older clients do not accidentally publish or unpublish. +- Within a supplied `badge` object, omitted fields retain their current values + on update and use their defaults on creation. +- An explicit `badge: null` resets settings to disabled, label `compliance`, + and no slug. An explicit `slug: null` disables publication while retaining + the label. Reject `enabled: true` combined with `slug: null`. +- `enabled: false` alone disables publication but retains the slug reservation + and label. Re-enabling the same retained slug intentionally restores its + existing embeds. +- A new slug can be reserved while disabled, allowing preview and review before + publication. Never enable implicitly just because a slug is present. +- Settings, any affected filter fields, and slug reservations are committed + atomically after validation and authorization. A rejected request must not + partially change associations or publication state. +- Imports, clones, and automatically generated filters start unpublished with + no slug; they must not copy publication settings from another filter. + +Return the existing JSON response envelopes and create/update success codes. +Use `400` for invalid settings, `403` for missing publish authority, and `409` +for a conflicting slug. Map database uniqueness violations to the same `409` +as pre-validation, including concurrent requests. + +### Revocation and slug reuse + +Disabling, clearing/changing the slug, or deleting the filter makes subsequent +origin requests to the old public URL return `404`. Changing a slug never +redirects an existing embed to its replacement. + +A slug is reserved only while a filter holds it, published or not. Changing or +clearing the slug, or deleting its filter, frees it; a later claim by any filter +is allowed. Disabling without clearing retains the slug. The partial unique +index on `filters.badge_slug` protects these reservations; no tombstone table +is needed. + +Revocation removes the current mapping, not the URL forever. If a freed slug is +later claimed and enabled, existing embeds of that URL display the new holder's +aggregate. There are still no redirects or aliases. + +This is origin revocation, not erasure: the API cannot retract previously +downloaded SVGs, screenshots, or copies cached by external image proxies. + +## Publishing permission + +Introduce action `publish` on resource `filter` (`filter:publish`): + +- Add its action constant to [pdp.go](../internal/authz/pdp.go), declare it on + `filter` in the manifest, and keep manifest/export/permission-discovery + contracts consistent. +- Cedar's default admin role receives it through its existing wildcard grant. + Do not add it to contributor, auditor, viewer, or agent roles. +- Add an explicit builtin rule delegating `filter:publish` to the existing + user-admin check. Do not let it fall through to builtin's ordinary + authenticated-request allow. Keep single and batch evaluation consistent. +- AuthZEN/custom policy operators must explicitly grant the new action. + +The existing create/update permission remains required. Additionally require +`filter:publish` whenever a request changes badge settings, including reserving +or changing a slug, enabling, disabling, clearing, or changing the label. +An identical settings round trip is not a publication change. + +Because changing a published filter's selection changes what is disclosed, +also require publish authority for changes made through the filter routes to +its effective predicate, SSP binding, or scope-following configuration while it +is enabled. This prevents a caller with only filter update rights from +broadening a published filter through those routes. Reject the entire +unauthorized write before any mutation. +Unrelated metadata/association edits retain existing authorization unless they +change the evidence selection. + +A published badge is a live view: new evidence and SSP scope updates affect it +without another publication request. Editing an SSP's scope never requires +`filter:publish`; it retains its existing SSP authorization, and a scope-following +badge reflects scope changes as part of its live view. This behavior must be +made clear at publication time. Filter deletion retains its existing delete +permission and revokes the badge. + +Enforce conditional publish checks through the existing PDP/PEP mechanisms, +not hard-coded role names in handlers. For every publication-sensitive write +through the filter routes, the publication-state read, authorization decision, +and write must form one atomic decision. Serialize competing writes (for +example, lock the filter row before checking and hold the lock until commit), +or use a versioned conditional write and roll back the entire transaction on +conflict (`409`). All competing filter-route writers, including enabling a +badge, must follow the same concurrency protocol. +When updating a filter, acquire the scope locks of its current SSP and of the +requested SSP, in a fixed order, before the filter row lock, matching scope +edits, and hold them through authorization and commit. Locking only the +requested SSP would let a scope edit on the SSP the filter leaves rewrite it +with the old scope after the update commits. If the row's SSP changed between +choosing the locks and locking the row, retry, and return `409` once retries +are exhausted. + +An import that finds no row must insert without overwriting on conflict. If +another transaction creates the ID first, repeat the locked lookup and +selection-dependent publish check before updating it. + +A predicate write authorized only while disabled must not commit after another +transaction enables the badge: it must fail without mutation. Evaluate +authorization before side effects against the state protected by that protocol, +not an earlier unlocked read. Slug claims/releases and affected associations +belong to the same transaction, with the unique index arbitrating concurrent +slug claims. This atomicity requirement does not add publish checks to SSP +scope edits. Publication checks must fail closed if the PDP is unavailable, +even if ordinary authorization is configured fail-open. + +## SVG endpoints + +| Route | Authentication and authorization | Behavior | +| --- | --- | --- | +| `GET /api/filters/:id/badge.svg` | User JWT, `filter:read`, and the same `evidence:read` authorization as `GET /api/evidence/compliance-by-filter/:id` | Preview by filter UUID, whether published or not and without requiring a slug. | +| `GET /api/public/badges/{slug}.svg` | Anonymous; no user or agent token required | Render only when the slug resolves to an existing filter with `badge.enabled = true`. | + +The public URL shape is `/api/public/badges/{slug}.svg`. In Echo, register +`/api/public/badges/:file`, require the captured `file` to end in the literal +`.svg` suffix, strip that suffix, and validate the remaining slug. Return the +generic public `404` for a missing suffix or invalid slug. Do not register +`:slug.svg`: Echo treats the entire `slug.svg` as the parameter name and does +not enforce that suffix. + +Register preview in the existing authenticated filter group with both the +filter-read and evidence-read guards. Use the same evidence authorization +semantics as the JSON compliance endpoint; `filter:read` alone must not disclose +evidence-derived state, even for an enabled badge. + +Register public badges in a separate, deliberately anonymous group in +[RegisterHandlers](../internal/api/handler/api.go). Do not attach optional agent +authentication, an evidence-read guard, or an anonymous `filter:read` grant. +The narrowly scoped publication lookup is the public access gate. + +Public badges are available regardless of +`StrictDisablePublicAgentEndpoints`. This flag controls existing agent-facing +exposure, not explicitly published filter badges. Do not broaden access to +filter JSON, evidence, artifacts, or other routes. + +No query parameter may override the predicate, SSP scope, label, slug, or +aggregation. Reject unsupported query parameters with `400`. + +### Responses and errors + +- Success: `200`, `Content-Type: image/svg+xml; charset=utf-8`, raw SVG bytes, + not a JSON response envelope. +- Preview: `400` for a malformed UUID; existing JWT behavior for unauthenticated + requests; `403` if either read permission is denied; `404` for an unknown filter. +- Public: `404` for a missing `.svg` suffix, invalid/unknown slug, or a slug with + no enabled holder (including after clearing, disabling, or deletion), with + the same generic response shape for each case. A freed slug may be reclaimed + and published as described above. +- Database/aggregation/rendering failures: log internally and return a generic + `500` using the API error helper. Never render a green badge or pretend that + a failure means no evidence. +- Error responses use standard API JSON errors, not SVG, and are not cached. + +## Aggregation and rendering + +Both endpoints share one lookup/aggregate/render path after their different +access checks. Reuse `GetStatusCountsByFilters` directly; do not make an HTTP +request to the JSON compliance endpoint or duplicate its query logic. + +Per render, perform the necessary saved-filter/publication lookup and one +grouped evidence query. Do not load individual evidence, iterate over evidence +in application code, or add one query per status. Preserve existing +latest-stream, deduplication, and effective-filter semantics, including saved +scope-following predicates. Do not infer additional evidence constraints from +control/component associations or SSP metadata that the existing endpoint +does not apply. + +The SVG shows the configured label and one aggregate state: + +| Aggregate counts | Display text | Color | +| --- | --- | --- | +| No matching evidence | `no evidence` | Gray | +| Any `not-satisfied` evidence | `failing` | Red | +| Nonempty result, all evidence `satisfied` | `passing` | Green | +| Otherwise, including unknown/empty states | `unknown` | Gray | + +Failure takes precedence over unknown states. Do not silently drop unfamiliar +states or treat them as satisfied. This is a rollup of recorded evidence, not +an attestation, certification, or guarantee of freshness. Do not introduce a +different expiry rule from the existing compliance aggregation. + +V1 publishes only the label and aggregate state, not counts, percentages, +evidence IDs, titles, labels, props, timestamps, filter UUIDs/predicates, SSP +details, control/component identifiers, or links to authenticated resources. +Keep SVG metadata and accessible text limited to the same disclosure. + +Use a small deterministic SVG template with bounded dimensions and escaped +text in every insertion context. Include readable text and an accessible +label/title so color is not the sole signal. No scripts, event handlers, +`foreignObject`, external images/fonts, remote URLs, or embedded credentials. +Set `X-Content-Type-Options: nosniff` and a restrictive SVG-compatible CSP +(`default-src 'none'; style-src 'unsafe-inline'; sandbox`). + +## Caching and revocation boundary + +Set cache policy in the API, not in an external badge service: + +- Authenticated preview: `Cache-Control: private, no-store`. +- Public SVG: `Cache-Control: public, no-cache, max-age=0, must-revalidate`. + This permits storage but requires origin revalidation before reuse; do not + add `stale-while-revalidate` or `stale-if-error`. +- All error responses: `Cache-Control: no-store`. + +V1 need not implement ETags. If conditional responses are added, check the +current publication mapping before considering `304`, and compute validators +from the current rendered representation. An old validator must never bypass +revocation. + +Origin requests begun after a revocation transaction commits must observe it. +Already in-flight responses and external caches are outside that guarantee. +Do not add an in-process publication/result cache: independent caches across API +replicas could continue serving a revoked mapping after commit. Each origin +request must check the current mapping. +GitHub's image proxy may cache independently; document that no cache header can +guarantee immediate removal from an already-rendered GitHub README. + +## Embedding and deployment + +```markdown +![Compliance](https://api.example.com/api/public/badges/payments-service.svg) +``` + +Only the public slug URL is suitable for anonymous embeds; never embed an +access token or the authenticated preview URL. + +Badges render only where the API is reachable. On github.com, GitHub's image +fetcher must be able to reach the public route over the internet, normally +over HTTPS. A private-network-only API will not render there. Operators may +expose only this path through their ingress without exposing authenticated +API data. Publishing a badge does not configure DNS, TLS, firewall, or ingress. + +No CORS change is needed for an ordinary Markdown/image embed. The API currently +has no HTTP rate limiting. Operators must rate-limit `/api/public/badges/` at +the ingress before exposing it: each render performs an aggregate query, and +the revalidation policy can send every proxy hit back to the origin. Do not +assume an existing API limiter or add an in-process result cache as a substitute. + +## Implementation and verification checklist + +1. Add model fields, defaults, validation, the partial unique index, and + migrations in the production and test migrators. + Existing filters must all migrate unpublished. +2. Extend filter requests/responses and conditional publish authorization; + preserve existing clients and ensure imports/automatic filters stay private. +3. Add `filter:publish` to the vocabulary and enforce the builtin/Cedar/remote + policy behavior described above. +4. Add the authenticated preview and independent public route, shared aggregate + renderer, safe SVG template, and response headers. +5. Add handler annotations and run `make swag`; do not hand-edit generated + Swagger files. +6. Add focused tests covering: + - Defaults, omitted/null settings, label/slug validation, duplicate slugs, + concurrent claims, and transactional rollback. + - Publish allowed for admin, denied for ordinary contributors, and not + implied by builtin filter update; single/batch permission parity and + fail-closed publication during PDP failure. + - Unauthorized changes to a published predicate/scope, unchanged settings + round trips, and compatibility with older request bodies; an SSP scope + edit without `filter:publish` still updates a scope-following badge. + - Concurrent predicate changes and badge enablement: an update authorized + only while disabled must not commit after publication. Include slug + claims/releases and verify conflicts leave no partial mutations. + - Preview before publication and after disabling; user JWT enforcement, + success with both read permissions, and `403` when either one is missing; + public success with no token under both values of the strict-agent flag. + - `404` after disable, rename, clear, or deletion until a freed slug is + reclaimed and enabled; reuse by the same or another filter succeeds, + while disabled filters retain their slugs. No redirect, alias, or + conditional-cache bypass. + - Public filename routing: valid `.svg` URLs work; missing suffixes, + invalid slugs, and unsupported query parameters are rejected as specified. + - Parity with the existing compliance query for latest evidence, overlapping + matches, and effective SSP-following filters; one grouped evidence query. + - Passing, failing, mixed, empty, and unknown states; database failures; + XML escaping, bounded SVG output, forbidden-content absence, and headers. + - No individual evidence or filter details in SVG text, metadata, or errors; + no regressions in existing filter/evidence access. +7. Run targeted unit/integration tests and lint. Integration tests require + Docker; compile integration-tagged code when shared helpers change. + Before deployment, verify ingress rate limiting on the public badge path + and revocation visibility across API replicas. + +UI controls and permission hints can consume this contract in a separate UI +change. They must explain that enabling a badge publishes a live aggregate and +that the label/slug are public. API authorization must remain sufficient even +without those UI controls. diff --git a/docs/swagger.json b/docs/swagger.json index 9b005b7f..8ae0a69e 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -5769,7 +5769,7 @@ } }, "post": { - "description": "Creates a new filter.", + "description": "Creates a new filter. Setting a non-default badge needs the filter:publish\npermission (403 without it); a slug another filter holds is a 409.", "consumes": [ "application/json" ], @@ -5804,6 +5804,18 @@ "$ref": "#/definitions/api.Error" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, "422": { "description": "Unprocessable Entity", "schema": { @@ -5910,7 +5922,7 @@ } }, "put": { - "description": "Updates an existing filter.", + "description": "Updates an existing filter. Changing its badge, or the predicate, SSP or\nscope following of a filter whose badge is published, needs the\nfilter:publish permission (403 without it); a slug another filter holds\nis a 409. Omitting badge keeps the current settings.", "consumes": [ "application/json" ], @@ -5952,12 +5964,24 @@ "$ref": "#/definitions/api.Error" } }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/api.Error" } }, + "409": { + "description": "Conflict", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, "500": { "description": "Internal Server Error", "schema": { @@ -6006,6 +6030,71 @@ } } }, + "/filters/{id}/badge.svg": { + "get": { + "description": "Renders the SVG badge of a saved filter by ID, whether or not it is published.\nRequires filter read and the evidence read authorization of\n/evidence/compliance-by-filter/{id}. Takes no query parameters.", + "produces": [ + "image/svg+xml", + "application/json" + ], + "tags": [ + "Filters" + ], + "summary": "Preview a filter's badge", + "parameters": [ + { + "type": "string", + "description": "Filter ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "SVG badge", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "403": { + "description": "Forbidden", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + }, + "security": [ + { + "OAuth2Password": [] + } + ] + } + }, "/filters/{id}/responsibilities": { "post": { "description": "Associates this filter with an upstream responsibility the given downstream\nSSP inherits (BCH-1339's filter_responsibilities), so the responsibility's\nposture is computed live from the filter's evidence. When controlId is given,\nthe filter is also linked to that control (so control-level compliance\nsurfaces include it) with provenance recorded: detaching removes the control\nlink only if this attach created it.", @@ -30948,6 +31037,54 @@ ] } }, + "/public/badges/{file}": { + "get": { + "description": "Renders the SVG badge published under a slug. Anonymous: no token is needed.\nOnly the badge label and aggregate state (passing, failing, unknown or no\nevidence) are disclosed. Unknown, invalid and unpublished slugs all return the\nsame 404. Takes no query parameters.", + "produces": [ + "image/svg+xml", + "application/json" + ], + "tags": [ + "Filters" + ], + "summary": "Get a published filter badge", + "parameters": [ + { + "type": "string", + "description": "Badge slug followed by .svg, e.g. payments-service.svg", + "name": "file", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "SVG badge", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + } + } + }, "/risks": { "get": { "description": "Lists risk register entries with filtering, sorting, and pagination.", @@ -37534,6 +37671,14 @@ "handler.FilterWithAssociations": { "type": "object", "properties": { + "badge": { + "description": "Badge is never imported or copied: imports, clones and generated filters start\nunpublished.", + "allOf": [ + { + "$ref": "#/definitions/relational.FilterBadge" + } + ] + }, "components": { "type": "array", "items": { @@ -41388,6 +41533,15 @@ "name" ], "properties": { + "badge": { + "description": "Badge changes the filter's public badge (docs/filter-badges.md) and needs the\nfilter:publish permission unless it leaves the settings unchanged. Omitted keeps the\ncurrent settings (POST: unpublished defaults); null resets them to the defaults.", + "allOf": [ + { + "$ref": "#/definitions/handler.filterBadgeRequest" + } + ], + "x-nullable": true + }, "components": { "type": "array", "items": { @@ -41651,6 +41805,26 @@ } } }, + "handler.filterBadgeRequest": { + "type": "object", + "properties": { + "enabled": { + "description": "Enabled publishes the badge at /api/public/badges/{slug}.svg; it requires a slug.", + "type": "boolean" + }, + "label": { + "description": "Label is the badge's left-hand text: 1-64 characters after trimming, no control\ncharacters.", + "type": "string", + "example": "compliance" + }, + "slug": { + "description": "Slug is the public identifier: lowercase letters, digits and single hyphens, at\nmost 63 characters, unique across filters. null clears it and unpublishes.", + "type": "string", + "x-nullable": true, + "example": "payments-production" + } + } + }, "handler.filteredSearchRequest": { "type": "object", "required": [ @@ -50731,6 +50905,14 @@ "relational.Filter": { "type": "object", "properties": { + "badge": { + "description": "Badge is never imported or copied: imports, clones and generated filters start\nunpublished.", + "allOf": [ + { + "$ref": "#/definitions/relational.FilterBadge" + } + ] + }, "components": { "type": "array", "items": { @@ -50769,6 +50951,22 @@ } } }, + "relational.FilterBadge": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "label": { + "description": "Label is the plain-text left-hand side of the badge.", + "type": "string" + }, + "slug": { + "description": "Slug is the public identifier in /api/public/badges/{slug}.svg. Absent is NULL, never \"\".", + "type": "string" + } + } + }, "relational.FilterResponsibility": { "type": "object", "properties": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 98ea21a3..d2ea86f9 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -871,6 +871,12 @@ definitions: type: object handler.FilterWithAssociations: properties: + badge: + allOf: + - $ref: '#/definitions/relational.FilterBadge' + description: |- + Badge is never imported or copied: imports, clones and generated filters start + unpublished. components: items: $ref: '#/definitions/oscalTypes_1_1_3.SystemComponent' @@ -3299,6 +3305,14 @@ definitions: type: object handler.createFilterRequest: properties: + badge: + allOf: + - $ref: '#/definitions/handler.filterBadgeRequest' + description: |- + Badge changes the filter's public badge (docs/filter-badges.md) and needs the + filter:publish permission unless it leaves the settings unchanged. Omitted keeps the + current settings (POST: unpublished defaults); null resets them to the defaults. + x-nullable: true components: items: type: string @@ -3487,6 +3501,26 @@ definitions: poam-item-id: type: string type: object + handler.filterBadgeRequest: + properties: + enabled: + description: Enabled publishes the badge at /api/public/badges/{slug}.svg; + it requires a slug. + type: boolean + label: + description: |- + Label is the badge's left-hand text: 1-64 characters after trimming, no control + characters. + example: compliance + type: string + slug: + description: |- + Slug is the public identifier: lowercase letters, digits and single hyphens, at + most 63 characters, unique across filters. null clears it and unpublishes. + example: payments-production + type: string + x-nullable: true + type: object handler.filteredSearchRequest: properties: filter: @@ -9581,6 +9615,12 @@ definitions: type: object relational.Filter: properties: + badge: + allOf: + - $ref: '#/definitions/relational.FilterBadge' + description: |- + Badge is never imported or copied: imports, clones and generated filters start + unpublished. components: items: $ref: '#/definitions/relational.SystemComponent' @@ -9609,6 +9649,18 @@ definitions: sspId: type: string type: object + relational.FilterBadge: + properties: + enabled: + type: boolean + label: + description: Label is the plain-text left-hand side of the badge. + type: string + slug: + description: Slug is the public identifier in /api/public/badges/{slug}.svg. + Absent is NULL, never "". + type: string + type: object relational.FilterResponsibility: properties: controlId: @@ -17206,7 +17258,9 @@ paths: post: consumes: - application/json - description: Creates a new filter. + description: |- + Creates a new filter. Setting a non-default badge needs the filter:publish + permission (403 without it); a slug another filter holds is a 409. parameters: - description: Filter to add in: body @@ -17225,6 +17279,14 @@ paths: description: Bad Request schema: $ref: '#/definitions/api.Error' + "403": + description: Forbidden + schema: + $ref: '#/definitions/api.Error' + "409": + description: Conflict + schema: + $ref: '#/definitions/api.Error' "422": description: Unprocessable Entity schema: @@ -17296,7 +17358,11 @@ paths: put: consumes: - application/json - description: Updates an existing filter. + description: |- + Updates an existing filter. Changing its badge, or the predicate, SSP or + scope following of a filter whose badge is published, needs the + filter:publish permission (403 without it); a slug another filter holds + is a 409. Omitting badge keeps the current settings. parameters: - description: Filter ID in: path @@ -17320,10 +17386,18 @@ paths: description: Bad Request schema: $ref: '#/definitions/api.Error' + "403": + description: Forbidden + schema: + $ref: '#/definitions/api.Error' "404": description: Not Found schema: $ref: '#/definitions/api.Error' + "409": + description: Conflict + schema: + $ref: '#/definitions/api.Error' "500": description: Internal Server Error schema: @@ -17331,6 +17405,51 @@ paths: summary: Update a filter tags: - Filters + /filters/{id}/badge.svg: + get: + description: |- + Renders the SVG badge of a saved filter by ID, whether or not it is published. + Requires filter read and the evidence read authorization of + /evidence/compliance-by-filter/{id}. Takes no query parameters. + parameters: + - description: Filter ID + in: path + name: id + required: true + type: string + produces: + - image/svg+xml + - application/json + responses: + "200": + description: SVG badge + schema: + type: string + "400": + description: Bad Request + schema: + $ref: '#/definitions/api.Error' + "401": + description: Unauthorized + schema: + $ref: '#/definitions/api.Error' + "403": + description: Forbidden + schema: + $ref: '#/definitions/api.Error' + "404": + description: Not Found + schema: + $ref: '#/definitions/api.Error' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/api.Error' + security: + - OAuth2Password: [] + summary: Preview a filter's badge + tags: + - Filters /filters/{id}/responsibilities: post: consumes: @@ -33953,6 +34072,42 @@ paths: summary: Delete a risk link tags: - POAM Items + /public/badges/{file}: + get: + description: |- + Renders the SVG badge published under a slug. Anonymous: no token is needed. + Only the badge label and aggregate state (passing, failing, unknown or no + evidence) are disclosed. Unknown, invalid and unpublished slugs all return the + same 404. Takes no query parameters. + parameters: + - description: Badge slug followed by .svg, e.g. payments-service.svg + in: path + name: file + required: true + type: string + produces: + - image/svg+xml + - application/json + responses: + "200": + description: SVG badge + schema: + type: string + "400": + description: Bad Request + schema: + $ref: '#/definitions/api.Error' + "404": + description: Not Found + schema: + $ref: '#/definitions/api.Error' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/api.Error' + summary: Get a published filter badge + tags: + - Filters /risks: get: description: Lists risk register entries with filtering, sorting, and pagination. diff --git a/internal/api/handler/api.go b/internal/api/handler/api.go index 1e98f9fa..34526299 100644 --- a/internal/api/handler/api.go +++ b/internal/api/handler/api.go @@ -86,10 +86,18 @@ func RegisterHandlers(server *api.Server, logger *zap.SugaredLogger, db *gorm.DB meGroup.Use(middleware.JWTMiddleware(config.JWTPublicKey)) permissionsHandler.Register(meGroup, pep.For(authz.ResourceUser)) - filterHandler := NewFilterHandler(logger, db) + filterHandler := NewFilterHandler(logger, db).WithPDP(pdp).WithEvidenceService(services.EvidenceService) filterGroup := server.API().Group("/filters") + // Before authentication, so a badge request's 401 is uncacheable too. + filterGroup.Use(filterBadgeErrorNoStore) filterGroup.Use(middleware.JWTMiddleware(config.JWTPublicKey)) filterHandler.Register(filterGroup, pep.For(authz.ResourceFilter)) + // The preview discloses evidence-derived state, so it also needs evidence read. + filterHandler.RegisterBadgePreview(filterGroup, pep.For(authz.ResourceFilter), pep.For(authz.ResourceEvidence)) + // Published badges are deliberately anonymous, whatever StrictDisablePublicAgentEndpoints + // says: publication (filter:publish) is the access gate. Keep this group free of auth + // middleware and of every other route. + filterHandler.RegisterPublicBadges(server.API().Group("/public/badges")) // Policies & Procedures + Compliance Lineage. controlLinkHandler := NewControlLinkHandler(logger, db) diff --git a/internal/api/handler/filter.go b/internal/api/handler/filter.go index 807963a6..4b3500d5 100644 --- a/internal/api/handler/filter.go +++ b/internal/api/handler/filter.go @@ -1,15 +1,19 @@ package handler import ( + "bytes" "errors" "fmt" "net/http" + "slices" "strings" "github.com/compliance-framework/api/internal/api" "github.com/compliance-framework/api/internal/api/middleware" + "github.com/compliance-framework/api/internal/authz" "github.com/compliance-framework/api/internal/converters/labelfilter" "github.com/compliance-framework/api/internal/service/relational" + evidencesvc "github.com/compliance-framework/api/internal/service/relational/evidence" "github.com/compliance-framework/api/internal/service/relational/sspscope" oscalTypes_1_1_3 "github.com/defenseunicorns/go-oscal/src/types/oscal-1-1-3" "github.com/google/uuid" @@ -22,8 +26,10 @@ import ( // FilterHandler handles CRUD operations for filters. type FilterHandler struct { - db *gorm.DB - sugar *zap.SugaredLogger + db *gorm.DB + sugar *zap.SugaredLogger + pdp authz.PDP + evidenceService *evidencesvc.EvidenceService } func NewFilterHandler(sugar *zap.SugaredLogger, db *gorm.DB) *FilterHandler { @@ -33,6 +39,18 @@ func NewFilterHandler(sugar *zap.SugaredLogger, db *gorm.DB) *FilterHandler { } } +// WithPDP sets the PDP that decides filter:publish. Without one, badge changes are denied. +func (h *FilterHandler) WithPDP(pdp authz.PDP) *FilterHandler { + h.pdp = pdp + return h +} + +// WithEvidenceService sets the service badges aggregate evidence through. +func (h *FilterHandler) WithEvidenceService(svc *evidencesvc.EvidenceService) *FilterHandler { + h.evidenceService = svc + return h +} + // Register registers the filter endpoints. func (h *FilterHandler) Register(api *echo.Group, guard middleware.ResourceGuard) { api.GET("", h.List, guard.Read()) @@ -194,13 +212,16 @@ func (h *FilterHandler) List(ctx *echo.Context) error { // Create godoc // // @Summary Create a new filter -// @Description Creates a new filter. +// @Description Creates a new filter. Setting a non-default badge needs the filter:publish +// @Description permission (403 without it); a slug another filter holds is a 409. // @Tags Filters // @Accept json // @Produce json // @Param filter body createFilterRequest true "Filter to add" // @Success 201 {object} GenericDataResponse[relational.Filter] // @Failure 400 {object} api.Error +// @Failure 403 {object} api.Error +// @Failure 409 {object} api.Error // @Failure 422 {object} api.Error // @Failure 500 {object} api.Error // @Router /filters [post] @@ -225,11 +246,22 @@ func (h *FilterHandler) Create(ctx *echo.Context) error { ) } + badgeSettings, err := resolveFilterBadge(relational.DefaultFilterBadge(), req.Badge, req.badgeSet) + if err != nil { + return ctx.JSON(http.StatusBadRequest, api.NewError(err)) + } + if !badgeEqual(badgeSettings, relational.DefaultFilterBadge()) { + if err := h.authorizePublish(ctx, ""); err != nil { + return h.filterWriteError(ctx, err) + } + } + filter := relational.Filter{ Name: req.Name, SSPID: req.SSPID, Filter: datatypes.NewJSONType(req.Filter), Origin: relational.FilterOriginManual, + Badge: badgeSettings, } follow := req.FollowSSPScope != nil && *req.FollowSSPScope @@ -269,6 +301,9 @@ func (h *FilterHandler) Create(ctx *echo.Context) error { return err } } + if err := checkBadgeSlugAvailable(tx, nil, filter.Badge.Slug); err != nil { + return err + } return tx.Create(&filter).Error }); err != nil { return h.filterWriteError(ctx, err) @@ -280,7 +315,10 @@ func (h *FilterHandler) Create(ctx *echo.Context) error { // Update godoc // // @Summary Update a filter -// @Description Updates an existing filter. +// @Description Updates an existing filter. Changing its badge, or the predicate, SSP or +// @Description scope following of a filter whose badge is published, needs the +// @Description filter:publish permission (403 without it); a slug another filter holds +// @Description is a 409. Omitting badge keeps the current settings. // @Tags Filters // @Accept json // @Produce json @@ -288,7 +326,9 @@ func (h *FilterHandler) Create(ctx *echo.Context) error { // @Param filter body createFilterRequest true "Filter to update" // @Success 200 {object} GenericDataResponse[relational.Filter] // @Failure 400 {object} api.Error +// @Failure 403 {object} api.Error // @Failure 404 {object} api.Error +// @Failure 409 {object} api.Error // @Failure 500 {object} api.Error // @Router /filters/{id} [put] func (h *FilterHandler) Update(ctx *echo.Context) error { @@ -307,38 +347,6 @@ func (h *FilterHandler) Update(ctx *echo.Context) error { return ctx.JSON(http.StatusBadRequest, api.Validator(err)) } - var filter relational.Filter - if err := h.db.First(&filter, "id = ?", id).Error; err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return ctx.JSON(http.StatusNotFound, api.NewError(err)) - } - return ctx.JSON(http.StatusInternalServerError, api.NewError(err)) - } - - filter.Name = req.Name - // PUT is full replacement: omitted or null sspId intentionally clears the SSP binding. - filter.SSPID = req.SSPID - // followSspScope: true follows (filter is the new base), false stops following and - // keeps the current effective filter, omitted keeps the filter's current state. - following := filter.ScopeBase != nil - follow := following - if req.FollowSSPScope != nil { - follow = *req.FollowSSPScope - } - if !following || follow { - filter.Filter = datatypes.NewJSONType(req.Filter) - } - filter.ScopeBase = nil - - // Note: nil and empty slices are semantically different here. - // If one of controls / components is present but empty, that - // means clear the existing controls / components, whereas a nil - // slice means we should ignore it entirely. Now consider, an - // existing filter with controls, and a request to update it where - // controls is nil but components is populated. This should be - // invalid, as the expected update would be to ignore the controls - // and update the components, resulting in a filter with both. - // The request contains one or more of both Controls and Components if (req.Controls != nil && len(*req.Controls) > 0) && (req.Components != nil && len(*req.Components) > 0) { return ctx.JSON(http.StatusBadRequest, api.NewError( @@ -348,80 +356,191 @@ func (h *FilterHandler) Update(ctx *echo.Context) error { ) } - // The request contains one or more Controls, with a nil slice for Components - if (req.Controls != nil && len(*req.Controls) > 0) && (req.Components == nil) && len(filter.Components) > 0 { - return ctx.JSON(http.StatusBadRequest, api.NewError( - fmt.Errorf( - "cannot link Controls to a Filter with associated Components."+ + // The row is locked for the whole read-authorize-write, so the publish decision is + // made against the badge state the write commits over, and a failed check or + // conflict leaves nothing changed. + var filter relational.Filter + update := func(tx *gorm.DB) error { + seenSSP, err := lockFilterScopes(tx, id, req.SSPID) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return &filterHTTPError{status: http.StatusNotFound, err: err} + } + return err + } + if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&filter, "id = ?", id).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return &filterHTTPError{status: http.StatusNotFound, err: err} + } + return err + } + if !sameSSP(seenSSP, filter.SSPID) { + return errFilterSSPMoved + } + before, err := selectionOf(&filter) + if err != nil { + return err + } + currentBadge := filter.Badge + + filter.Name = req.Name + // PUT is full replacement: omitted or null sspId intentionally clears the SSP binding. + filter.SSPID = req.SSPID + // followSspScope: true follows (filter is the new base), false stops following and + // keeps the current effective filter, omitted keeps the filter's current state. + following := filter.ScopeBase != nil + follow := following + if req.FollowSSPScope != nil { + follow = *req.FollowSSPScope + } + if !following || follow { + filter.Filter = datatypes.NewJSONType(req.Filter) + } + filter.ScopeBase = nil + + // Note: nil and empty slices are semantically different here. + // If one of controls / components is present but empty, that + // means clear the existing controls / components, whereas a nil + // slice means we should ignore it entirely. Now consider, an + // existing filter with controls, and a request to update it where + // controls is nil but components is populated. This should be + // invalid, as the expected update would be to ignore the controls + // and update the components, resulting in a filter with both. + + // The request contains one or more Controls, with a nil slice for Components + if (req.Controls != nil && len(*req.Controls) > 0) && (req.Components == nil) && len(filter.Components) > 0 { + return badRequest(fmt.Errorf( + "cannot link Controls to a Filter with associated Components." + "To remove existing Component associations, send an empty list for the Components field", - )), - ) - } + )) + } - // The request contains a nil slice for Controls, with one or more Components - if (req.Controls == nil) && (req.Components != nil && len(*req.Components) > 0) && len(filter.Controls) > 0 { - return ctx.JSON(http.StatusBadRequest, api.NewError( - fmt.Errorf( - "cannot link Components to a Filter with associated Controls."+ + // The request contains a nil slice for Controls, with one or more Components + if (req.Controls == nil) && (req.Components != nil && len(*req.Components) > 0) && len(filter.Controls) > 0 { + return badRequest(fmt.Errorf( + "cannot link Components to a Filter with associated Controls." + "To remove existing Control associations, send an empty list for the Controls field", - )), - ) - } - - // Update controls if provided - if req.Controls != nil { - // Clear existing controls association - if err := h.db.Model(&filter).Association("Controls").Clear(); err != nil { - return ctx.JSON(http.StatusInternalServerError, api.NewError(err)) + )) } - // Add new controls - for _, controlId := range *req.Controls { - searchDB := h.db.Session(&gorm.Session{}) - control := relational.Control{} - err := searchDB.First(&control, "id = ?", controlId).Error - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return ctx.JSON(http.StatusNotFound, api.NewError(err)) + + var controls []relational.Control + if req.Controls != nil { + for _, controlId := range *req.Controls { + control := relational.Control{} + if err := tx.Session(&gorm.Session{}).First(&control, "id = ?", controlId).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return &filterHTTPError{status: http.StatusNotFound, err: err} + } + return err } - return ctx.JSON(http.StatusInternalServerError, api.NewError(err)) + controls = append(controls, control) } - filter.Controls = append(filter.Controls, control) - } - } - - if req.Components != nil { - if err := h.db.Model(&filter).Association("Components").Clear(); err != nil { - return ctx.JSON(http.StatusInternalServerError, api.NewError(err)) } - for _, componentId := range *req.Components { - searchDB := h.db.Session(&gorm.Session{}) - component := relational.SystemComponent{} - err := searchDB.First(&component, "id = ?", componentId).Error - if err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return ctx.JSON(http.StatusNotFound, api.NewError(err)) + var components []relational.SystemComponent + if req.Components != nil { + for _, componentId := range *req.Components { + component := relational.SystemComponent{} + if err := tx.Session(&gorm.Session{}).First(&component, "id = ?", componentId).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return &filterHTTPError{status: http.StatusNotFound, err: err} + } + return err } - return ctx.JSON(http.StatusInternalServerError, api.NewError(err)) + components = append(components, component) } - filter.Components = append(filter.Components, component) } - } - if err := h.db.Transaction(func(tx *gorm.DB) error { + badgeSettings, err := resolveFilterBadge(currentBadge, req.Badge, req.badgeSet) + if err != nil { + return badRequest(err) + } + filter.Badge = badgeSettings + if follow { if err := followSSPScope(tx, &filter, req.Filter); err != nil { return err } } + + after, err := selectionOf(&filter) + if err != nil { + return err + } + if !badgeEqual(currentBadge, badgeSettings) || (currentBadge.Enabled && before != after) { + if err := h.authorizePublish(ctx, id.String()); err != nil { + return err + } + } + if err := checkBadgeSlugAvailable(tx, &id, filter.Badge.Slug); err != nil { + return err + } + + // Clearing resets the struct's association field, so assign the new ones after. + if req.Controls != nil { + if err := tx.Model(&filter).Association("Controls").Clear(); err != nil { + return err + } + filter.Controls = controls + } + if req.Components != nil { + if err := tx.Model(&filter).Association("Components").Clear(); err != nil { + return err + } + filter.Components = components + } return tx.Save(&filter).Error - }); err != nil { + } + for attempt := 1; ; attempt++ { + filter = relational.Filter{} + err = h.db.Transaction(update) + if !errors.Is(err, errFilterSSPMoved) || attempt == filterUpdateAttempts { + break + } + } + if err != nil { return h.filterWriteError(ctx, err) } return ctx.JSON(http.StatusOK, GenericDataResponse[relational.Filter]{Data: filter}) } +// filterUpdateAttempts bounds Update's retries when the filter's SSP changes under it. +const filterUpdateAttempts = 3 + +// errFilterSSPMoved means the filter's SSP changed between the unlocked read that chose +// the scope locks and the row lock, so those locks do not cover it. +var errFilterSSPMoved = errors.New("filter SSP changed concurrently; retry the update") + +// lockFilterScopes takes the scope locks of the filter's current SSP and the requested +// one, in a fixed order and before the filter row lock, as scope edits do. A scope edit +// on the SSP a filter leaves could otherwise rewrite it with that SSP's scope after the +// update. It returns the SSP it read, which the caller checks against the locked row. +func lockFilterScopes(tx *gorm.DB, id uuid.UUID, requested *uuid.UUID) (*uuid.UUID, error) { + var current relational.Filter + if err := tx.Select("id", "ssp_id").First(¤t, "id = ?", id).Error; err != nil { + return nil, err + } + var ssps []uuid.UUID + if current.SSPID != nil { + ssps = append(ssps, *current.SSPID) + } + if requested != nil && !sameSSP(current.SSPID, requested) { + ssps = append(ssps, *requested) + } + slices.SortFunc(ssps, func(a, b uuid.UUID) int { return bytes.Compare(a[:], b[:]) }) + for _, sspID := range ssps { + if err := sspscope.LockSSP(tx, sspID); err != nil { + return nil, err + } + } + return current.SSPID, nil +} + +func sameSSP(a, b *uuid.UUID) bool { + return (a == nil) == (b == nil) && (a == nil || *a == *b) +} + // Delete godoc // // @Summary Delete a filter @@ -863,9 +982,19 @@ func followSSPScope(tx *gorm.DB, filter *relational.Filter, base labelfilter.Fil } func (h *FilterHandler) filterWriteError(ctx *echo.Context, err error) error { + var httpErr *filterHTTPError switch { + case errors.As(err, &httpErr): + return ctx.JSON(httpErr.status, api.NewError(httpErr.err)) case errors.Is(err, errFollowNeedsSSP), errors.Is(err, sspscope.ErrScopeEmpty), errors.Is(err, sspscope.ErrSSPNotFound): return ctx.JSON(http.StatusBadRequest, api.NewError(err)) - } - return ctx.JSON(http.StatusInternalServerError, api.NewError(err)) + case errors.Is(err, errPublishForbidden): + return ctx.JSON(http.StatusForbidden, api.NewError(errPublishForbidden)) + case errors.Is(err, errBadgeSlugTaken), isBadgeSlugConflict(err): + return ctx.JSON(http.StatusConflict, api.NewError(errBadgeSlugTaken)) + case errors.Is(err, errFilterSSPMoved): + return ctx.JSON(http.StatusConflict, api.NewError(errFilterSSPMoved)) + } + h.sugar.Errorw("Failed to write filter", "error", err) + return ctx.JSON(http.StatusInternalServerError, api.InternalServerError()) } diff --git a/internal/api/handler/filter_badge.go b/internal/api/handler/filter_badge.go new file mode 100644 index 00000000..657a2028 --- /dev/null +++ b/internal/api/handler/filter_badge.go @@ -0,0 +1,352 @@ +package handler + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "regexp" + "strings" + "unicode" + "unicode/utf8" + + "github.com/compliance-framework/api/internal/api" + "github.com/compliance-framework/api/internal/api/middleware" + "github.com/compliance-framework/api/internal/authz" + "github.com/compliance-framework/api/internal/badge" + "github.com/compliance-framework/api/internal/service/relational" + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/labstack/echo/v5" + "gorm.io/gorm" +) + +const ( + maxBadgeSlugLen = 63 + + badgeContentType = "image/svg+xml; charset=utf-8" + badgeContentSecurity = "default-src 'none'; style-src 'unsafe-inline'; sandbox" + badgePreviewCacheControl = "private, no-store" + badgePublicCacheControl = "public, no-cache, max-age=0, must-revalidate" + badgeErrorCacheControl = "no-store" + badgeFileSuffix = ".svg" +) + +var ( + badgeSlugPattern = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`) + + errPublishForbidden = errors.New("changing a filter's badge, or the selection of a published filter, requires the filter:publish permission") + errBadgeSlugTaken = errors.New("badge slug is already in use by another filter") + errBadgeNeedsSlug = errors.New("badge.enabled requires badge.slug") + errBadgeQueryParams = errors.New("badge URLs take no query parameters") + errBadgeLabelLength = fmt.Errorf("badge.label must be 1-%d characters after trimming", badge.MaxLabelRunes) + errBadgeLabelControl = errors.New("badge.label must not contain control characters") + errBadgeSlugFormat = fmt.Errorf("badge.slug must be 1-%d lowercase letters, digits and single hyphens, not starting or ending with a hyphen", maxBadgeSlugLen) +) + +// filterHTTPError carries a status and client-safe error out of a filter write +// transaction. +type filterHTTPError struct { + status int + err error +} + +func (e *filterHTTPError) Error() string { return e.err.Error() } +func (e *filterHTTPError) Unwrap() error { return e.err } + +func badRequest(err error) error { return &filterHTTPError{status: http.StatusBadRequest, err: err} } + +func normalizeBadgeLabel(label string) (string, error) { + label = strings.TrimSpace(label) + if n := utf8.RuneCountInString(label); n == 0 || n > badge.MaxLabelRunes { + return "", errBadgeLabelLength + } + for _, r := range label { + if unicode.IsControl(r) { + return "", errBadgeLabelControl + } + } + return label, nil +} + +func validBadgeSlug(slug string) bool { + return len(slug) <= maxBadgeSlugLen && badgeSlugPattern.MatchString(slug) +} + +// resolveFilterBadge applies a request's badge settings to the current ones. set reports +// whether the body had a badge key at all; a nil req with set means badge: null. +func resolveFilterBadge(current relational.FilterBadge, req *filterBadgeRequest, set bool) (relational.FilterBadge, error) { + if !set { + return current, nil + } + if req == nil { + return relational.DefaultFilterBadge(), nil + } + next := current + if current.Slug != nil { + slug := *current.Slug + next.Slug = &slug + } + if req.Label != nil { + label, err := normalizeBadgeLabel(*req.Label) + if err != nil { + return current, err + } + next.Label = label + } + if req.slugSet { + if req.Slug == nil { + // Clearing the slug unpublishes; only an explicit enabled: true below can + // contradict that, and is rejected. + next.Slug = nil + next.Enabled = false + } else { + if !validBadgeSlug(*req.Slug) { + return current, errBadgeSlugFormat + } + slug := *req.Slug + next.Slug = &slug + } + } + if req.Enabled != nil { + next.Enabled = *req.Enabled + } + if next.Enabled && next.Slug == nil { + return current, errBadgeNeedsSlug + } + return next, nil +} + +func badgeEqual(a, b relational.FilterBadge) bool { + if a.Enabled != b.Enabled || a.Label != b.Label || (a.Slug == nil) != (b.Slug == nil) { + return false + } + return a.Slug == nil || *a.Slug == *b.Slug +} + +// filterSelection is what decides a filter's badge state: its effective predicate, SSP +// binding and scope-following base. +type filterSelection struct { + sspID, filter, scopeBase string +} + +func selectionOf(f *relational.Filter) (filterSelection, error) { + var sel filterSelection + if f.SSPID != nil { + sel.sspID = f.SSPID.String() + } + predicate, err := json.Marshal(f.Filter.Data()) + if err != nil { + return sel, err + } + sel.filter = string(predicate) + if f.ScopeBase != nil { + base, err := json.Marshal(f.ScopeBase.Data()) + if err != nil { + return sel, err + } + sel.scopeBase = string(base) + } + return sel, nil +} + +// authorizePublish checks filter:publish for the caller. It fails closed whatever the +// PEP's fail mode: an unavailable PDP denies; any other evaluation error is a 500. +func (h *FilterHandler) authorizePublish(ctx *echo.Context, filterID string) error { + if h.pdp == nil { + return errPublishForbidden + } + subject := middleware.SubjectFromContext(ctx) + resource := authz.Resource{Type: authz.ResourceFilter, ID: filterID} + reqCtx := map[string]any{"method": ctx.Request().Method, "path": ctx.Path()} + decision, err := h.pdp.Evaluate(ctx.Request().Context(), subject, authz.ActionPublish, resource, reqCtx) + if err != nil { + if errors.Is(err, authz.ErrUnavailable) { + h.sugar.Warnw("authz PDP unavailable; denying filter:publish", "filterID", filterID, "error", err) + return errPublishForbidden + } + return fmt.Errorf("filter:publish check: %w", err) + } + h.sugar.Infow("authz decision", + "audit", true, + "decision", map[bool]string{true: "allow", false: "deny"}[decision.Allow], + "subjectType", subject.Type, + "subjectID", subject.ID, + "resource", resource.Type, + "resourceID", resource.ID, + "action", authz.ActionPublish, + "reason", decision.Reason, + ) + if !decision.Allow { + return errPublishForbidden + } + return nil +} + +// checkBadgeSlugAvailable reports a conflict when another filter holds slug. The +// partial unique index still decides races; isBadgeSlugConflict maps those. +func checkBadgeSlugAvailable(tx *gorm.DB, id *uuid.UUID, slug *string) error { + if slug == nil { + return nil + } + q := tx.Model(&relational.Filter{}).Where("badge_slug = ?", *slug) + if id != nil { + q = q.Where("id <> ?", *id) + } + var count int64 + if err := q.Count(&count).Error; err != nil { + return err + } + if count > 0 { + return errBadgeSlugTaken + } + return nil +} + +func isBadgeSlugConflict(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == relational.FilterBadgeSlugIndex +} + +// RegisterBadgePreview registers the authenticated badge preview. It discloses evidence- +// derived state, so it needs evidence read as well as filter read, exactly like +// /evidence/compliance-by-filter/:id (whose resource ID is also the filter ID). +func (h *FilterHandler) RegisterBadgePreview(group *echo.Group, filterGuard, evidenceGuard middleware.ResourceGuard) { + group.GET("/:id/badge.svg", h.BadgePreview, filterGuard.Read(), evidenceGuard.Read()) +} + +// RegisterPublicBadges registers the anonymous published-badge route on a group that must +// carry no authentication: publication is the access gate. Every other path in the group +// gets the same 404 as an unknown slug. +func (h *FilterHandler) RegisterPublicBadges(group *echo.Group) { + group.Use(badgeErrorNoStore) + group.GET("/:file", h.PublicBadge) + notFound := func(ctx *echo.Context) error { + return ctx.JSON(http.StatusNotFound, api.NotFound()) + } + group.RouteNotFound("", notFound) + group.RouteNotFound("/*", notFound) +} + +// badgeErrorNoStore marks a response uncacheable until a badge handler replaces the +// header on success, so error responses, including those from middleware that runs +// before the handler, are never cached. +func badgeErrorNoStore(next echo.HandlerFunc) echo.HandlerFunc { + return func(ctx *echo.Context) error { + ctx.Response().Header().Set("Cache-Control", badgeErrorCacheControl) + return next(ctx) + } +} + +// filterBadgeErrorNoStore is badgeErrorNoStore for the badge routes of a group that also +// serves cacheable JSON. +func filterBadgeErrorNoStore(next echo.HandlerFunc) echo.HandlerFunc { + noStore := badgeErrorNoStore(next) + return func(ctx *echo.Context) error { + if strings.HasSuffix(ctx.Request().URL.Path, "/badge.svg") { + return noStore(ctx) + } + return next(ctx) + } +} + +// BadgePreview godoc +// +// @Summary Preview a filter's badge +// @Description Renders the SVG badge of a saved filter by ID, whether or not it is published. +// @Description Requires filter read and the evidence read authorization of +// @Description /evidence/compliance-by-filter/{id}. Takes no query parameters. +// @Tags Filters +// @Produce image/svg+xml +// @Produce json +// @Param id path string true "Filter ID" +// @Success 200 {string} string "SVG badge" +// @Failure 400 {object} api.Error +// @Failure 401 {object} api.Error +// @Failure 403 {object} api.Error +// @Failure 404 {object} api.Error +// @Failure 500 {object} api.Error +// @Security OAuth2Password +// @Router /filters/{id}/badge.svg [get] +func (h *FilterHandler) BadgePreview(ctx *echo.Context) error { + if ctx.Request().URL.RawQuery != "" { + return ctx.JSON(http.StatusBadRequest, api.NewError(errBadgeQueryParams)) + } + idParam := ctx.Param("id") + id, err := uuid.Parse(idParam) + if err != nil { + return ctx.JSON(http.StatusBadRequest, api.NewError(err)) + } + + var filter relational.Filter + if err := h.db.First(&filter, "id = ?", id).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return ctx.JSON(http.StatusNotFound, api.NotFound()) + } + h.sugar.Errorw("Failed to load filter for badge preview", "filterID", id, "error", err) + return ctx.JSON(http.StatusInternalServerError, api.InternalServerError()) + } + return h.renderBadge(ctx, &filter, badgePreviewCacheControl) +} + +// PublicBadge godoc +// +// @Summary Get a published filter badge +// @Description Renders the SVG badge published under a slug. Anonymous: no token is needed. +// @Description Only the badge label and aggregate state (passing, failing, unknown or no +// @Description evidence) are disclosed. Unknown, invalid and unpublished slugs all return the +// @Description same 404. Takes no query parameters. +// @Tags Filters +// @Produce image/svg+xml +// @Produce json +// @Param file path string true "Badge slug followed by .svg, e.g. payments-service.svg" +// @Success 200 {string} string "SVG badge" +// @Failure 400 {object} api.Error +// @Failure 404 {object} api.Error +// @Failure 500 {object} api.Error +// @Router /public/badges/{file} [get] +func (h *FilterHandler) PublicBadge(ctx *echo.Context) error { + if ctx.Request().URL.RawQuery != "" { + return ctx.JSON(http.StatusBadRequest, api.NewError(errBadgeQueryParams)) + } + slug, ok := strings.CutSuffix(ctx.Param("file"), badgeFileSuffix) + if !ok || !validBadgeSlug(slug) { + return ctx.JSON(http.StatusNotFound, api.NotFound()) + } + + var filter relational.Filter + if err := h.db.First(&filter, "badge_slug = ? AND badge_enabled", slug).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return ctx.JSON(http.StatusNotFound, api.NotFound()) + } + h.sugar.Errorw("Failed to look up published badge", "error", err) + return ctx.JSON(http.StatusInternalServerError, api.InternalServerError()) + } + return h.renderBadge(ctx, &filter, badgePublicCacheControl) +} + +// renderBadge is the lookup-independent path both badge routes share: one grouped query +// over the latest evidence matching the filter's effective predicate, as +// /evidence/compliance-by-filter/:id runs, then the SVG. +func (h *FilterHandler) renderBadge(ctx *echo.Context, filter *relational.Filter, cacheControl string) error { + if h.evidenceService == nil { + h.sugar.Errorw("Badge requested but no evidence service is configured") + return ctx.JSON(http.StatusInternalServerError, api.InternalServerError()) + } + rows, err := h.evidenceService.GetStatusCountsByFilters(filter.Filter.Data()) + if err != nil { + h.sugar.Errorw("Failed to aggregate badge evidence", "filterID", filter.ID, "error", err) + return ctx.JSON(http.StatusInternalServerError, api.InternalServerError()) + } + counts := make([]badge.Count, 0, len(rows)) + for _, row := range rows { + counts = append(counts, badge.Count{State: row.Status, Count: row.Count}) + } + svg := badge.Render(filter.Badge.Label, badge.Aggregate(counts)) + + header := ctx.Response().Header() + header.Set("Cache-Control", cacheControl) + header.Set("X-Content-Type-Options", "nosniff") + header.Set("Content-Security-Policy", badgeContentSecurity) + return ctx.Blob(http.StatusOK, badgeContentType, svg) +} diff --git a/internal/api/handler/filter_badge_integration_test.go b/internal/api/handler/filter_badge_integration_test.go new file mode 100644 index 00000000..860a59be --- /dev/null +++ b/internal/api/handler/filter_badge_integration_test.go @@ -0,0 +1,887 @@ +//go:build integration + +package handler + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "mime/multipart" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/compliance-framework/api/internal/api" + "github.com/compliance-framework/api/internal/api/middleware" + "github.com/compliance-framework/api/internal/authn" + "github.com/compliance-framework/api/internal/authz" + "github.com/compliance-framework/api/internal/converters/labelfilter" + "github.com/compliance-framework/api/internal/service/relational" + evidencesvc "github.com/compliance-framework/api/internal/service/relational/evidence" + "github.com/compliance-framework/api/internal/service/relational/sspscope" + "github.com/compliance-framework/api/internal/tests" + oscalTypes_1_1_3 "github.com/defenseunicorns/go-oscal/src/types/oscal-1-1-3" + "github.com/google/uuid" + "github.com/labstack/echo/v5" + "github.com/stretchr/testify/suite" + "go.uber.org/zap" + "gorm.io/datatypes" + "gorm.io/gorm" +) + +func TestFilterBadges(t *testing.T) { + suite.Run(t, new(FilterBadgeIntegrationSuite)) +} + +type FilterBadgeIntegrationSuite struct { + tests.IntegrationTestSuite + logger *zap.SugaredLogger + + // builtin is the default server: builtin PDP, admin is the password super admin. + builtin *api.Server + admin string + + // cedar uses the Cedar PDP with admin and contributor role users. + cedar *api.Server + cedarAdmin string + cedarContributor string +} + +func (s *FilterBadgeIntegrationSuite) SetupTest() { + s.Require().NoError(s.Migrator.Refresh()) + s.logger = zap.NewNop().Sugar() + + s.builtin = s.newServer(nil, false) + token, err := s.GetAuthToken() + s.Require().NoError(err) + s.admin = *token + + s.cedarAdmin = s.roleToken("cedar-admin@example.com", "admin") + s.cedarContributor = s.roleToken("contributor@example.com", "contributor") + pdp, err := authz.Open(authz.Options{Driver: authz.DriverCedar}, authz.Deps{DB: s.DB, Config: s.Config, Logger: s.logger}) + s.Require().NoError(err) + s.cedar = s.newServer(middleware.NewPEP(pdp, authz.FailClosed, s.logger), false) +} + +func (s *FilterBadgeIntegrationSuite) newServer(pep *middleware.PEP, strict bool) *api.Server { + cfg := *s.Config + cfg.StrictDisablePublicAgentEndpoints = strict + server := api.NewServer(context.Background(), s.logger, &cfg, api.NewMetricsHandler(context.Background(), s.logger)) + RegisterHandlers(server, s.logger, s.DB, &cfg, &APIServices{ + EvidenceService: evidencesvc.NewEvidenceService(s.DB, s.logger, &cfg, nil), + PEP: pep, + }) + return server +} + +func (s *FilterBadgeIntegrationSuite) roleToken(email, role string) string { + user := relational.User{Email: email, FirstName: "Badge", LastName: "Tester", AuthMethod: "sso"} + s.Require().NoError(s.DB.Create(&user).Error) + s.Require().NoError(s.DB.Create(&relational.CCFRoleAssignment{ + RoleName: role, + AssigneeType: relational.RoleAssigneeTypeUser, + AssigneeID: relational.NormalizeAssigneeID(email), + }).Error) + token, err := authn.GenerateJWTToken(&user, s.Config.JWTPrivateKey) + s.Require().NoError(err) + return *token +} + +func (s *FilterBadgeIntegrationSuite) do(srv *api.Server, method, path, token string, body any) *httptest.ResponseRecorder { + var reader *bytes.Reader + if body != nil { + raw, err := json.Marshal(body) + s.Require().NoError(err) + reader = bytes.NewReader(raw) + } else { + reader = bytes.NewReader(nil) + } + req := httptest.NewRequest(method, path, reader) + if body != nil { + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + } + if token != "" { + req.Header.Set(echo.HeaderAuthorization, "Bearer "+token) + } + rec := httptest.NewRecorder() + srv.E().ServeHTTP(rec, req) + return rec +} + +func (s *FilterBadgeIntegrationSuite) decode(rec *httptest.ResponseRecorder) relational.Filter { + var out GenericDataResponse[relational.Filter] + s.Require().NoError(json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String()) + return out.Data +} + +func providerFilter(value string) labelfilter.Filter { + return labelfilter.Filter{Scope: &labelfilter.Scope{Condition: &labelfilter.Condition{Label: "provider", Operator: "=", Value: value}}} +} + +func filterBody(name, provider string, extra map[string]any) map[string]any { + body := map[string]any{"name": name, "filter": providerFilter(provider)} + for k, v := range extra { + body[k] = v + } + return body +} + +// create posts a filter as the builtin admin and returns it. +func (s *FilterBadgeIntegrationSuite) create(name, provider string, badge any) relational.Filter { + extra := map[string]any{} + if badge != nil { + extra["badge"] = badge + } + rec := s.do(s.builtin, http.MethodPost, "/api/filters", s.admin, filterBody(name, provider, extra)) + s.Require().Equal(http.StatusCreated, rec.Code, rec.Body.String()) + return s.decode(rec) +} + +func (s *FilterBadgeIntegrationSuite) stored(id uuid.UUID) relational.Filter { + var filter relational.Filter + s.Require().NoError(s.DB.Preload("Controls").First(&filter, "id = ?", id).Error) + return filter +} + +func published(slug string) map[string]any { + return map[string]any{"enabled": true, "slug": slug} +} + +func (s *FilterBadgeIntegrationSuite) evidence(stream uuid.UUID, provider, state string, age time.Duration) { + end := time.Now().Add(-age) + s.Require().NoError(s.DB.Create(&relational.Evidence{ + UUID: stream, + Title: "evidence-title-" + provider, + Start: end.Add(-time.Minute), + End: end, + Status: datatypes.NewJSONType(oscalTypes_1_1_3.ObjectiveStatus{State: state}), + Labels: []relational.Labels{{Name: "provider", Value: provider}}, + }).Error) +} + +func (s *FilterBadgeIntegrationSuite) public(srv *api.Server, file string) *httptest.ResponseRecorder { + return s.do(srv, http.MethodGet, "/api/public/badges/"+file, "", nil) +} + +func (s *FilterBadgeIntegrationSuite) assertBadge(rec *httptest.ResponseRecorder, label, state, cacheControl string) { + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.Equal("image/svg+xml; charset=utf-8", rec.Header().Get(echo.HeaderContentType)) + s.Equal(cacheControl, rec.Header().Get("Cache-Control")) + s.Equal("nosniff", rec.Header().Get("X-Content-Type-Options")) + s.Equal("default-src 'none'; style-src 'unsafe-inline'; sandbox", rec.Header().Get("Content-Security-Policy")) + s.Contains(rec.Body.String(), ""+label+": "+state+"") +} + +func (s *FilterBadgeIntegrationSuite) assertPublic(srv *api.Server, slug, state string) { + s.assertBadge(s.public(srv, slug+".svg"), "compliance", state, "public, no-cache, max-age=0, must-revalidate") +} + +// assertPublicNotFound checks the single generic, uncacheable public 404. +func (s *FilterBadgeIntegrationSuite) assertPublicNotFound(file string) { + rec := s.public(s.builtin, file) + s.Equal(http.StatusNotFound, rec.Code, file) + s.Equal("no-store", rec.Header().Get("Cache-Control"), file) + s.JSONEq(`{"errors":{"body":"resource not found"}}`, rec.Body.String(), file) +} + +// waitForLockWaiter blocks until some session is waiting on a lock. +func (s *FilterBadgeIntegrationSuite) waitForLockWaiter() { + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + var waiting int64 + s.Require().NoError(s.DB.Raw(`SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock'`).Scan(&waiting).Error) + if waiting > 0 { + return + } + time.Sleep(20 * time.Millisecond) + } + s.FailNow("no request blocked on the lock") +} + +func (s *FilterBadgeIntegrationSuite) TestExistingFiltersMigrateUnpublished() { + s.Require().NoError(s.DB.Exec(`ALTER TABLE filters DROP COLUMN badge_enabled, DROP COLUMN badge_label, DROP COLUMN badge_slug`).Error) + id := uuid.New() + s.Require().NoError(s.DB.Exec(`INSERT INTO filters (id, name, filter) VALUES (?, 'legacy', '{}')`, id).Error) + + s.Require().NoError(s.Migrator.Up()) + + s.Equal(relational.DefaultFilterBadge(), s.stored(id).Badge) + s.Error(s.DB.Exec(`UPDATE filters SET badge_enabled = true WHERE id = ?`, id).Error, "an enabled badge needs a slug") + s.Error(s.DB.Exec(`UPDATE filters SET badge_slug = '' WHERE id = ?`, id).Error, "an absent slug is NULL") + s.Require().NoError(s.DB.Exec(`UPDATE filters SET badge_slug = 'taken' WHERE id = ?`, id).Error) + s.Error(s.DB.Exec(`INSERT INTO filters (id, name, filter, badge_slug) VALUES (?, 'dup', '{}', 'taken')`, uuid.New()).Error, "slugs are unique") +} + +func (s *FilterBadgeIntegrationSuite) TestDefaultsAndOlderClients() { + created := s.create("plain", "aws", nil) + s.Equal(relational.DefaultFilterBadge(), created.Badge) + s.Equal(relational.DefaultFilterBadge(), s.stored(*created.ID).Badge) + + pub := s.create("pub", "aws", map[string]any{"enabled": true, "slug": "pub", "label": " payments "}) + s.Equal(relational.FilterBadge{Enabled: true, Label: "payments", Slug: &[]string{"pub"}[0]}, pub.Badge) + + // A PUT without badge keeps the settings; so does an identical round trip, which a + // contributor without filter:publish may send while leaving the selection alone. + path := "/api/filters/" + pub.ID.String() + rec := s.do(s.cedar, http.MethodPut, path, s.cedarContributor, filterBody("renamed", "aws", nil)) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.Equal(pub.Badge, s.decode(rec).Badge) + rec = s.do(s.cedar, http.MethodPut, path, s.cedarContributor, filterBody("renamed", "aws", map[string]any{"badge": pub.Badge})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.Equal(pub.Badge, s.stored(*pub.ID).Badge) + s.assertBadge(s.public(s.builtin, "pub.svg"), "payments", "no evidence", "public, no-cache, max-age=0, must-revalidate") + + // badge: null resets everything. + rec = s.do(s.builtin, http.MethodPut, path, s.admin, filterBody("renamed", "aws", map[string]any{"badge": nil})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.Equal(relational.DefaultFilterBadge(), s.stored(*pub.ID).Badge) + s.assertPublicNotFound("pub.svg") +} + +func (s *FilterBadgeIntegrationSuite) TestInvalidSettingsRejected() { + for _, badge := range []any{ + map[string]any{"enabled": true}, + map[string]any{"enabled": true, "slug": nil}, + map[string]any{"slug": ""}, + map[string]any{"slug": "Upper"}, + map[string]any{"slug": "a_b"}, + map[string]any{"label": " "}, + map[string]any{"label": "bell\u0007"}, + map[string]any{"label": strings.Repeat("x", 65)}, + "not-an-object", + } { + rec := s.do(s.builtin, http.MethodPost, "/api/filters", s.admin, filterBody("bad", "aws", map[string]any{"badge": badge})) + s.Equal(http.StatusBadRequest, rec.Code, "%v: %s", badge, rec.Body.String()) + } + var count int64 + s.Require().NoError(s.DB.Model(&relational.Filter{}).Count(&count).Error) + s.Zero(count) +} + +func (s *FilterBadgeIntegrationSuite) TestSlugReservationAndRollback() { + s.Require().NoError(s.DB.Create(&relational.Catalog{ + Metadata: relational.Metadata{Title: "Catalog"}, + Controls: []relational.Control{{ID: "AC-1", Title: "Access Control 1"}}, + }).Error) + + a := s.create("a", "aws", published("shared")) + rec := s.do(s.builtin, http.MethodPost, "/api/filters", s.admin, filterBody("b", "aws", map[string]any{"badge": published("shared")})) + s.Equal(http.StatusConflict, rec.Code, rec.Body.String()) + + b := s.create("b", "aws", nil) + bPath := "/api/filters/" + b.ID.String() + rec = s.do(s.builtin, http.MethodPut, bPath, s.admin, filterBody("b", "aws", map[string]any{"controls": []string{"AC-1"}})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + + // A conflicting update changes nothing, associations included. + rec = s.do(s.builtin, http.MethodPut, bPath, s.admin, filterBody("b-renamed", "gcp", map[string]any{ + "controls": []string{}, "badge": map[string]any{"slug": "shared"}, + })) + s.Equal(http.StatusConflict, rec.Code, rec.Body.String()) + kept := s.stored(*b.ID) + s.Equal("b", kept.Name) + s.Equal(providerFilter("aws"), kept.Filter.Data()) + s.Len(kept.Controls, 1) + s.Nil(kept.Badge.Slug) + + // A disabled filter keeps its slug reserved. + aPath := "/api/filters/" + a.ID.String() + rec = s.do(s.builtin, http.MethodPut, aPath, s.admin, filterBody("a", "aws", map[string]any{"badge": map[string]any{"enabled": false}})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.assertPublicNotFound("shared.svg") + rec = s.do(s.builtin, http.MethodPut, bPath, s.admin, filterBody("b", "aws", map[string]any{"badge": published("shared")})) + s.Equal(http.StatusConflict, rec.Code, rec.Body.String()) + + // Re-enabling by the same filter works, renaming frees the old slug for another. + rec = s.do(s.builtin, http.MethodPut, aPath, s.admin, filterBody("a", "aws", map[string]any{"badge": published("renamed")})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.assertPublicNotFound("shared.svg") + s.assertPublic(s.builtin, "renamed", "no evidence") + rec = s.do(s.builtin, http.MethodPut, bPath, s.admin, filterBody("b", "aws", map[string]any{"badge": published("shared")})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.assertPublic(s.builtin, "shared", "no evidence") + + // Clearing a slug, or deleting its filter, frees it too. + rec = s.do(s.builtin, http.MethodPut, bPath, s.admin, filterBody("b", "aws", map[string]any{"badge": map[string]any{"slug": nil}})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.assertPublicNotFound("shared.svg") + s.Require().Equal(http.StatusNoContent, s.do(s.builtin, http.MethodDelete, aPath, s.admin, nil).Code) + s.assertPublicNotFound("renamed.svg") + reclaimed := s.create("c", "aws", published("renamed")) + s.Equal("renamed", *reclaimed.Badge.Slug) + s.assertPublic(s.builtin, "renamed", "no evidence") +} + +// A claim racing another transaction past the pre-check is decided by the unique index, +// and still answered with 409. +func (s *FilterBadgeIntegrationSuite) TestConcurrentSlugClaim() { + slug := "race" + tx := s.DB.Begin() + defer tx.Rollback() + s.Require().NoError(tx.Create(&relational.Filter{ + Name: "holder", + Filter: datatypes.NewJSONType(providerFilter("aws")), + Badge: relational.FilterBadge{Label: "compliance", Slug: &slug}, + }).Error) + + done := make(chan *httptest.ResponseRecorder) + go func() { + done <- s.do(s.builtin, http.MethodPost, "/api/filters", s.admin, filterBody("claimer", "aws", map[string]any{"badge": published(slug)})) + }() + s.waitForLockWaiter() + s.Require().NoError(tx.Commit().Error) + + rec := <-done + s.Equal(http.StatusConflict, rec.Code, rec.Body.String()) + s.NotContains(rec.Body.String(), relational.FilterBadgeSlugIndex, "driver errors stay server-side") + var count int64 + s.Require().NoError(s.DB.Model(&relational.Filter{}).Count(&count).Error) + s.Equal(int64(1), count) +} + +func (s *FilterBadgeIntegrationSuite) TestParallelSlugClaims() { + const n = 4 + codes := make(chan int, n) + var wg sync.WaitGroup + for range n { + wg.Go(func() { + codes <- s.do(s.builtin, http.MethodPost, "/api/filters", s.admin, filterBody("p", "aws", map[string]any{"badge": published("parallel")})).Code + }) + } + wg.Wait() + close(codes) + got := map[int]int{} + for code := range codes { + got[code]++ + } + s.Equal(map[int]int{http.StatusCreated: 1, http.StatusConflict: n - 1}, got) +} + +func (s *FilterBadgeIntegrationSuite) TestPublishAuthorization() { + s.Require().NoError(s.DB.Create(&relational.Catalog{ + Metadata: relational.Metadata{Title: "Catalog"}, + Controls: []relational.Control{{ID: "AC-1", Title: "Access Control 1"}}, + }).Error) + sspID := uuid.New() + s.Require().NoError(s.DB.Create(&relational.SystemSecurityPlan{UUIDModel: relational.UUIDModel{ID: &sspID}}).Error) + + // Contributors may manage filters but not publish them. + rec := s.do(s.cedar, http.MethodPost, "/api/filters", s.cedarContributor, filterBody("c", "aws", map[string]any{"badge": published("contrib")})) + s.Equal(http.StatusForbidden, rec.Code, rec.Body.String()) + rec = s.do(s.cedar, http.MethodPost, "/api/filters", s.cedarContributor, filterBody("c", "aws", map[string]any{"badge": map[string]any{"label": "x"}})) + s.Equal(http.StatusForbidden, rec.Code, "any badge change needs publish: %s", rec.Body.String()) + rec = s.do(s.cedar, http.MethodPost, "/api/filters", s.cedarContributor, filterBody("c", "aws", map[string]any{"controls": []string{"AC-1"}})) + s.Require().Equal(http.StatusCreated, rec.Code, rec.Body.String()) + unpublished := s.decode(rec) + path := "/api/filters/" + unpublished.ID.String() + + rec = s.do(s.cedar, http.MethodPut, path, s.cedarContributor, filterBody("c", "gcp", nil)) + s.Require().Equal(http.StatusOK, rec.Code, "an unpublished filter's selection is not gated: %s", rec.Body.String()) + rec = s.do(s.cedar, http.MethodPut, path, s.cedarContributor, filterBody("c", "gcp", map[string]any{"badge": published("contrib")})) + s.Equal(http.StatusForbidden, rec.Code, rec.Body.String()) + s.Nil(s.stored(*unpublished.ID).Badge.Slug) + + rec = s.do(s.cedar, http.MethodPut, path, s.cedarAdmin, filterBody("c", "gcp", map[string]any{"badge": published("contrib"), "controls": []string{"AC-1"}})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + + // Once published, changing the predicate or SSP binding needs publish, and a denial + // leaves every part of the update unapplied. + rec = s.do(s.cedar, http.MethodPut, path, s.cedarContributor, filterBody("changed", "azure", map[string]any{"controls": []string{}})) + s.Equal(http.StatusForbidden, rec.Code, rec.Body.String()) + rec = s.do(s.cedar, http.MethodPut, path, s.cedarContributor, filterBody("changed", "gcp", map[string]any{"sspId": sspID})) + s.Equal(http.StatusForbidden, rec.Code, rec.Body.String()) + rec = s.do(s.cedar, http.MethodPut, path, s.cedarContributor, filterBody("c", "gcp", map[string]any{"badge": map[string]any{"enabled": false}})) + s.Equal(http.StatusForbidden, rec.Code, "unpublishing is a badge change: %s", rec.Body.String()) + kept := s.stored(*unpublished.ID) + s.Equal("c", kept.Name) + s.Equal(providerFilter("gcp"), kept.Filter.Data()) + s.Nil(kept.SSPID) + s.Len(kept.Controls, 1) + s.True(kept.Badge.Enabled) + + rec = s.do(s.cedar, http.MethodPut, path, s.cedarAdmin, filterBody("c", "azure", nil)) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + + // Delete keeps its own permission and revokes the badge. + s.assertPublic(s.builtin, "contrib", "no evidence") + s.Require().Equal(http.StatusNoContent, s.do(s.cedar, http.MethodDelete, path, s.cedarContributor, nil).Code) + s.assertPublicNotFound("contrib.svg") +} + +// badgeStubPDP allows everything except the listed "resource:action" keys. +type badgeStubPDP struct { + deny, unavailable, fail map[string]bool +} + +func (p badgeStubPDP) Evaluate(_ context.Context, _ authz.Subject, action string, r authz.Resource, _ map[string]any) (authz.Decision, error) { + key := r.Type + ":" + action + switch { + case p.unavailable[key]: + return authz.Decision{}, authz.ErrUnavailable + case p.fail[key]: + return authz.Decision{}, errors.New("policy evaluation exploded") + } + return authz.Decision{Allow: !p.deny[key]}, nil +} + +func (p badgeStubPDP) Evaluations(ctx context.Context, reqs []authz.EvalRequest) ([]authz.Decision, error) { + out := make([]authz.Decision, len(reqs)) + for i, r := range reqs { + d, err := p.Evaluate(ctx, r.Subject, r.Action, r.Resource, r.Context) + if err != nil { + return nil, err + } + out[i] = d + } + return out, nil +} + +// Publication fails closed even when ordinary authorization is configured fail-open. +func (s *FilterBadgeIntegrationSuite) TestPublishFailsClosed() { + key := authz.ResourceFilter + ":" + authz.ActionPublish + unavailable := s.newServer(middleware.NewPEP(badgeStubPDP{unavailable: map[string]bool{key: true}}, authz.FailOpen, s.logger), false) + failing := s.newServer(middleware.NewPEP(badgeStubPDP{fail: map[string]bool{key: true}}, authz.FailOpen, s.logger), false) + + rec := s.do(unavailable, http.MethodPost, "/api/filters", s.admin, filterBody("f", "aws", map[string]any{"badge": published("closed")})) + s.Equal(http.StatusForbidden, rec.Code, rec.Body.String()) + rec = s.do(failing, http.MethodPost, "/api/filters", s.admin, filterBody("f", "aws", map[string]any{"badge": published("closed")})) + s.Equal(http.StatusInternalServerError, rec.Code, rec.Body.String()) + s.NotContains(rec.Body.String(), "exploded") + + f := s.create("f", "aws", published("closed")) + rec = s.do(unavailable, http.MethodPut, "/api/filters/"+f.ID.String(), s.admin, filterBody("f", "gcp", nil)) + s.Equal(http.StatusForbidden, rec.Code, rec.Body.String()) + s.Equal(providerFilter("aws"), s.stored(*f.ID).Filter.Data()) + + // Without a publish decision needed, the PDP is never asked. + rec = s.do(unavailable, http.MethodPut, "/api/filters/"+f.ID.String(), s.admin, filterBody("renamed", "aws", nil)) + s.Equal(http.StatusOK, rec.Code, rec.Body.String()) +} + +// An update authorized while the badge was disabled must not commit over a concurrent +// publication: the row lock makes it re-decide against the published state. +func (s *FilterBadgeIntegrationSuite) TestConcurrentUpdateAndEnable() { + f := s.create("f", "aws", map[string]any{"slug": "racing"}) + tx := s.DB.Begin() + defer tx.Rollback() + s.Require().NoError(tx.Exec(`SELECT id FROM filters WHERE id = ? FOR UPDATE`, f.ID).Error) + s.Require().NoError(tx.Exec(`UPDATE filters SET badge_enabled = true WHERE id = ?`, f.ID).Error) + + done := make(chan *httptest.ResponseRecorder) + go func() { + done <- s.do(s.cedar, http.MethodPut, "/api/filters/"+f.ID.String(), s.cedarContributor, filterBody("f", "gcp", nil)) + }() + s.waitForLockWaiter() + s.Require().NoError(tx.Commit().Error) + + rec := <-done + s.Equal(http.StatusForbidden, rec.Code, rec.Body.String()) + kept := s.stored(*f.ID) + s.True(kept.Badge.Enabled) + s.Equal(providerFilter("aws"), kept.Filter.Data()) +} + +func (s *FilterBadgeIntegrationSuite) TestUpdateLocksScopeBeforeFilter() { + sspID := uuid.New() + s.Require().NoError(s.DB.Create(&relational.SystemSecurityPlan{UUIDModel: relational.UUIDModel{ID: &sspID}}).Error) + _, err := sspscope.NewService(s.DB).AddEntry(sspID, []relational.ScopeLabel{{Key: "repo", Value: "a"}}, nil) + s.Require().NoError(err) + rec := s.do(s.builtin, http.MethodPost, "/api/filters", s.admin, filterBody("f", "aws", map[string]any{ + "sspId": sspID, "followSspScope": true, + })) + s.Require().Equal(http.StatusCreated, rec.Code, rec.Body.String()) + f := s.decode(rec) + + tx := s.DB.Begin() + defer tx.Rollback() + effective, err := sspscope.FollowScope(tx, sspID, providerFilter("aws")) + s.Require().NoError(err) + s.Require().NoError(tx.Exec("SET LOCAL lock_timeout = '1s'").Error) + + done := make(chan *httptest.ResponseRecorder, 1) + go func() { + done <- s.do(s.builtin, http.MethodPut, "/api/filters/"+f.ID.String(), s.admin, + filterBody("updated", "gcp", map[string]any{"sspId": sspID})) + }() + s.waitForLockWaiter() + s.Require().NoError(tx.Model(&f).Update("filter", datatypes.NewJSONType(effective)).Error, + "the scope writer must be able to lock the filter while Update waits for the scope") + s.Require().NoError(tx.Commit().Error) + + rec = <-done + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + kept := s.stored(*f.ID) + s.Equal("updated", kept.Name) + s.Require().NotNil(kept.ScopeBase) + s.Equal(providerFilter("gcp"), kept.ScopeBase.Data()) +} + +// Moving a filter off an SSP waits for that SSP's scope edits, so they cannot rewrite the +// moved filter with the old scope. +func (s *FilterBadgeIntegrationSuite) TestUpdateLocksPreviousSSPScope() { + scope := sspscope.NewService(s.DB) + newSSP := func(repo string) uuid.UUID { + id := uuid.New() + s.Require().NoError(s.DB.Create(&relational.SystemSecurityPlan{UUIDModel: relational.UUIDModel{ID: &id}}).Error) + _, err := scope.AddEntry(id, []relational.ScopeLabel{{Key: "repo", Value: repo}}, nil) + s.Require().NoError(err) + return id + } + oldSSP, nextSSP := newSSP("a"), newSSP("b") + + for name, update := range map[string]map[string]any{ + "moved": {"sspId": nextSSP, "followSspScope": true}, + "cleared": {"followSspScope": false}, + } { + s.Run(name, func() { + rec := s.do(s.builtin, http.MethodPost, "/api/filters", s.admin, filterBody("f", "aws", map[string]any{ + "sspId": oldSSP, "followSspScope": true, + })) + s.Require().Equal(http.StatusCreated, rec.Code, rec.Body.String()) + f := s.decode(rec) + + // A scope edit on the old SSP: lock it, then list its following filters. + tx := s.DB.Begin() + defer tx.Rollback() + s.Require().NoError(sspscope.LockSSP(tx, oldSSP)) + var following []uuid.UUID + s.Require().NoError(tx.Model(&relational.Filter{}). + Where("ssp_id = ? AND scope_base IS NOT NULL", oldSSP).Pluck("id", &following).Error) + s.Require().Contains(following, *f.ID) + + done := make(chan *httptest.ResponseRecorder, 1) + go func() { + done <- s.do(s.builtin, http.MethodPut, "/api/filters/"+f.ID.String(), s.admin, filterBody("updated", "gcp", update)) + }() + s.waitForLockWaiter() + stale := datatypes.NewJSONType(providerFilter("stale")) + s.Require().NoError(tx.Model(&relational.Filter{}).Where("id IN ?", following).Update("filter", stale).Error) + s.Require().NoError(tx.Commit().Error) + + rec = <-done + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.Equal(s.decode(rec).Filter.Data(), s.stored(*f.ID).Filter.Data(), "the scope edit must not overwrite the update") + }) + } +} + +// A scope edit rewrites a following filter without filter:publish, and the published badge +// follows it. +func (s *FilterBadgeIntegrationSuite) TestScopeEditUpdatesFollowingBadge() { + sspID := uuid.New() + s.Require().NoError(s.DB.Create(&relational.SystemSecurityPlan{UUIDModel: relational.UUIDModel{ID: &sspID}}).Error) + scope := sspscope.NewService(s.DB) + _, err := scope.AddEntry(sspID, []relational.ScopeLabel{{Key: "repo", Value: "a"}}, nil) + s.Require().NoError(err) + + rec := s.do(s.builtin, http.MethodPost, "/api/filters", s.admin, filterBody("f", "aws", map[string]any{ + "sspId": sspID, "followSspScope": true, "badge": published("follow"), + })) + s.Require().Equal(http.StatusCreated, rec.Code, rec.Body.String()) + f := s.decode(rec) + + stream := uuid.New() + s.Require().NoError(s.DB.Create(&relational.Evidence{ + UUID: stream, Title: "b", Start: time.Now().Add(-2 * time.Minute), End: time.Now().Add(-time.Minute), + Status: datatypes.NewJSONType(oscalTypes_1_1_3.ObjectiveStatus{State: "not-satisfied"}), + Labels: []relational.Labels{{Name: "provider", Value: "aws"}, {Name: "repo", Value: "b"}}, + }).Error) + s.assertPublic(s.builtin, "follow", "no evidence") + + _, err = scope.AddEntry(sspID, []relational.ScopeLabel{{Key: "repo", Value: "b"}}, nil) + s.Require().NoError(err) + s.assertPublic(s.builtin, "follow", "failing") + s.True(s.stored(*f.ID).Badge.Enabled) + + // Re-sending the same base with the unchanged scope is not a selection change. + rec = s.do(s.cedar, http.MethodPut, "/api/filters/"+f.ID.String(), s.cedarContributor, filterBody("renamed", "aws", map[string]any{"sspId": sspID})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) +} + +func (s *FilterBadgeIntegrationSuite) TestPreview() { + f := s.create("secret-name", "aws", nil) + path := "/api/filters/" + f.ID.String() + "/badge.svg" + + rec := s.do(s.builtin, http.MethodGet, path, "", nil) + s.Equal(http.StatusUnauthorized, rec.Code) + s.Equal("no-store", rec.Header().Get("Cache-Control")) + + s.assertBadge(s.do(s.builtin, http.MethodGet, path, s.admin, nil), "compliance", "no evidence", "private, no-store") + s.assertBadge(s.do(s.cedar, http.MethodGet, path, s.cedarContributor, nil), "compliance", "no evidence", "private, no-store") + + for _, denied := range []string{authz.ResourceFilter + ":read", authz.ResourceEvidence + ":read"} { + srv := s.newServer(middleware.NewPEP(badgeStubPDP{deny: map[string]bool{denied: true}}, authz.FailClosed, s.logger), false) + rec = s.do(srv, http.MethodGet, path, s.admin, nil) + s.Equal(http.StatusForbidden, rec.Code, denied) + s.Equal("no-store", rec.Header().Get("Cache-Control"), denied) + } + + for p, want := range map[string]int{ + "/api/filters/not-a-uuid/badge.svg": http.StatusBadRequest, + "/api/filters/" + uuid.NewString() + "/badge.svg": http.StatusNotFound, + path + "?label=x": http.StatusBadRequest, + path + "?": http.StatusOK, + "/api/filters/" + f.ID.String() + "/badge.svg?x=1": http.StatusBadRequest, + } { + rec = s.do(s.builtin, http.MethodGet, p, s.admin, nil) + s.Equal(want, rec.Code, p) + if want != http.StatusOK { + s.Equal("no-store", rec.Header().Get("Cache-Control"), p) + } + } + + // Preview works after publication and after disabling. + rec = s.do(s.builtin, http.MethodPut, "/api/filters/"+f.ID.String(), s.admin, filterBody("secret-name", "aws", map[string]any{"badge": published("prev")})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + rec = s.do(s.builtin, http.MethodPut, "/api/filters/"+f.ID.String(), s.admin, filterBody("secret-name", "aws", map[string]any{"badge": map[string]any{"enabled": false}})) + s.Require().Equal(http.StatusOK, rec.Code, rec.Body.String()) + s.assertBadge(s.do(s.builtin, http.MethodGet, path, s.admin, nil), "compliance", "no evidence", "private, no-store") + s.assertPublicNotFound("prev.svg") + + // Filter JSON reads keep their cache behavior. + s.Empty(s.do(s.builtin, http.MethodGet, "/api/filters/"+f.ID.String(), s.admin, nil).Header().Get("Cache-Control")) +} + +func (s *FilterBadgeIntegrationSuite) TestPublicRouting() { + s.create("f", "aws", published("payments-service")) + for _, strict := range []bool{false, true} { + srv := s.newServer(nil, strict) + s.assertPublic(srv, "payments-service", "no evidence") + } + + for _, file := range []string{ + "payments-service", + "payments-service.SVG", + "payments-service.svg.svg", + "Payments-Service.svg", + "unknown.svg", + ".svg", + "payments-service.svg/extra", + "", + } { + s.assertPublicNotFound(file) + } + rec := s.public(s.builtin, "payments-service.svg?label=x") + s.Equal(http.StatusBadRequest, rec.Code) + s.Equal("no-store", rec.Header().Get("Cache-Control")) + rec = s.public(s.builtin, "unknown.svg?x") + s.Equal(http.StatusBadRequest, rec.Code) + + // A token neither helps nor hurts. + rec = s.do(s.builtin, http.MethodGet, "/api/public/badges/payments-service.svg", "not-a-valid-token", nil) + s.Equal(http.StatusOK, rec.Code) +} + +func (s *FilterBadgeIntegrationSuite) TestStatesParityAndDisclosure() { + cases := []struct { + slug string + provider string + seed func(provider string) + state string + }{ + {"empty", "zq-none", func(string) {}, "no evidence"}, + {"passing", "zq-pass", func(p string) { + s.evidence(uuid.New(), p, "satisfied", time.Hour) + // The stream's latest evidence wins over its older failure. + stream := uuid.New() + s.evidence(stream, p, "not-satisfied", 2*time.Hour) + s.evidence(stream, p, "satisfied", time.Minute) + }, "passing"}, + {"failing", "zq-fail", func(p string) { + s.evidence(uuid.New(), p, "satisfied", time.Hour) + s.evidence(uuid.New(), p, "not-satisfied", time.Hour) + s.evidence(uuid.New(), p, "mystery", time.Hour) + }, "failing"}, + {"unknown", "zq-unk", func(p string) { + s.evidence(uuid.New(), p, "satisfied", time.Hour) + s.evidence(uuid.New(), p, "mystery", time.Hour) + }, "unknown"}, + } + for _, tc := range cases { + tc.seed(tc.provider) + f := s.create("secret-name-"+tc.slug, tc.provider, published(tc.slug)) + + // The JSON compliance endpoint over the same filter agrees. + rec := s.do(s.builtin, http.MethodGet, "/api/evidence/compliance-by-filter/"+f.ID.String(), s.admin, nil) + s.Require().Equal(http.StatusOK, rec.Code) + var counts GenericDataListResponse[evidencesvc.StatusCount] + s.Require().NoError(json.Unmarshal(rec.Body.Bytes(), &counts)) + var total int64 + for _, c := range counts.Data { + total += c.Count + if tc.state == "passing" { + s.Equal("satisfied", c.Status, tc.slug) + } + } + s.Equal(tc.state == "no evidence", total == 0, tc.slug) + + rec = s.public(s.builtin, tc.slug+".svg") + s.assertBadge(rec, "compliance", tc.state, "public, no-cache, max-age=0, must-revalidate") + body := rec.Body.String() + for _, secret := range []string{f.ID.String(), "secret-name", tc.provider, "evidence-title", "provider"} { + s.NotContains(body, secret, tc.slug) + } + } +} + +// One filter lookup and one grouped evidence query per render. +func (s *FilterBadgeIntegrationSuite) TestRenderQueryCount() { + s.evidence(uuid.New(), "aws", "satisfied", time.Hour) + s.evidence(uuid.New(), "aws", "not-satisfied", time.Hour) + s.create("f", "aws", published("counted")) + + var queries int + // Sub-queries embedded as arguments are compiled through the callbacks in DryRun + // mode; only statements that reach the database count. + count := func(tx *gorm.DB) { + if !tx.DryRun { + queries++ + } + } + s.Require().NoError(s.DB.Callback().Query().After("gorm:query").Register("badge_count_query", count)) + s.Require().NoError(s.DB.Callback().Row().After("gorm:row").Register("badge_count_row", count)) + defer func() { + s.Require().NoError(s.DB.Callback().Query().Remove("badge_count_query")) + s.Require().NoError(s.DB.Callback().Row().Remove("badge_count_row")) + }() + + s.assertPublic(s.builtin, "counted", "failing") + s.Equal(2, queries) +} + +func (s *FilterBadgeIntegrationSuite) TestRenderFailureIsGeneric500() { + s.create("f", "aws", published("broken")) + s.Require().NoError(s.DB.Exec(`ALTER TABLE evidences RENAME TO evidences_hidden`).Error) + defer func() { + s.Require().NoError(s.DB.Exec(`ALTER TABLE evidences_hidden RENAME TO evidences`).Error) + }() + + rec := s.public(s.builtin, "broken.svg") + s.Equal(http.StatusInternalServerError, rec.Code) + s.Equal("no-store", rec.Header().Get("Cache-Control")) + s.JSONEq(`{"errors":{"body":"internal server error"}}`, rec.Body.String()) +} + +func (s *FilterBadgeIntegrationSuite) importRequest(token string, dashboards []map[string]any) *http.Request { + var buf bytes.Buffer + w := multipart.NewWriter(&buf) + part, err := w.CreateFormFile("files", "dashboards.json") + s.Require().NoError(err) + s.Require().NoError(json.NewEncoder(part).Encode(dashboards)) + s.Require().NoError(w.Close()) + req := httptest.NewRequest(http.MethodPost, "/api/filters/import", &buf) + req.Header.Set(echo.HeaderContentType, w.FormDataContentType()) + req.Header.Set(echo.HeaderAuthorization, "Bearer "+token) + return req +} + +func (s *FilterBadgeIntegrationSuite) importFilters(srv *api.Server, token string, dashboards []map[string]any) FilterImportResponse { + rec := httptest.NewRecorder() + srv.E().ServeHTTP(rec, s.importRequest(token, dashboards)) + return s.decodeImport(rec) +} + +func (s *FilterBadgeIntegrationSuite) decodeImport(rec *httptest.ResponseRecorder) FilterImportResponse { + var out GenericDataResponse[FilterImportResponse] + s.Require().NoError(json.Unmarshal(rec.Body.Bytes(), &out), rec.Body.String()) + return out.Data +} + +// Imports start unpublished, keep an overwritten filter's badge, and cannot change a +// published filter's selection without filter:publish. +func (s *FilterBadgeIntegrationSuite) TestImportKeepsBadges() { + f := s.create("f", "aws", map[string]any{"enabled": true, "slug": "imported", "label": "kept"}) + dashboard := func(provider string) map[string]any { + return map[string]any{"id": f.ID, "name": "imported-name", "filter": providerFilter(provider)} + } + + freshID := uuid.New() + out := s.importFilters(s.cedar, s.cedarContributor, []map[string]any{ + dashboard("aws"), + {"name": "new", "filter": providerFilter("x")}, + {"id": freshID, "name": "new-with-id", "filter": providerFilter("x")}, + }) + s.Require().Equal(1, out.SuccessfulCount, out.Results) + s.Equal(3, out.TotalDashboards) + kept := s.stored(*f.ID) + s.Equal("imported-name", kept.Name) + s.Equal(f.Badge, kept.Badge) + var fresh relational.Filter + s.Require().NoError(s.DB.First(&fresh, "name = ?", "new").Error) + s.Equal(relational.DefaultFilterBadge(), fresh.Badge) + fresh = s.stored(freshID) + s.Equal(providerFilter("x"), fresh.Filter.Data()) + s.Equal(relational.DefaultFilterBadge(), fresh.Badge) + + out = s.importFilters(s.cedar, s.cedarContributor, []map[string]any{dashboard("gcp")}) + s.Require().Equal(1, out.FailedCount, out.Results) + s.Contains(out.Results[0].Message, "filter:publish") + s.Equal(providerFilter("aws"), s.stored(*f.ID).Filter.Data()) + + out = s.importFilters(s.cedar, s.cedarAdmin, []map[string]any{dashboard("gcp")}) + s.Require().Equal(1, out.SuccessfulCount, out.Results) + kept = s.stored(*f.ID) + s.Equal(providerFilter("gcp"), kept.Filter.Data()) + s.Equal(f.Badge, kept.Badge) +} + +func (s *FilterBadgeIntegrationSuite) TestConcurrentImportAndCreate() { + for _, tc := range []struct { + name string + enabled bool + provider string + token string + allow bool + }{ + {"published selection change denied", true, "gcp", s.cedarContributor, false}, + {"published selection unchanged", true, "aws", s.cedarContributor, true}, + {"published selection change authorized", true, "gcp", s.cedarAdmin, true}, + {"unpublished selection change", false, "gcp", s.cedarContributor, true}, + } { + s.Run(tc.name, func() { + id := uuid.New() + slug := "import-" + id.String() + f := relational.Filter{ + UUIDModel: relational.UUIDModel{ID: &id}, + Name: "concurrent", + Filter: datatypes.NewJSONType(providerFilter("aws")), + Badge: relational.FilterBadge{Enabled: tc.enabled, Label: "kept", Slug: &slug}, + } + tx := s.DB.Begin() + defer tx.Rollback() + s.Require().NoError(tx.Create(&f).Error) + + // The lookup cannot see the uncommitted row; the insert must wait for it. + req := s.importRequest(tc.token, []map[string]any{ + {"id": id, "name": "imported-name", "filter": providerFilter(tc.provider)}, + }) + done := make(chan *httptest.ResponseRecorder, 1) + go func() { + rec := httptest.NewRecorder() + s.cedar.E().ServeHTTP(rec, req) + done <- rec + }() + s.waitForLockWaiter() + s.Require().NoError(tx.Commit().Error) + + out := s.decodeImport(<-done) + wantName, wantProvider := "imported-name", tc.provider + if tc.allow { + s.Require().Equal(1, out.SuccessfulCount, out.Results) + } else { + s.Require().Equal(1, out.FailedCount, out.Results) + s.Require().Len(out.Results, 1) + s.Contains(out.Results[0].Message, "filter:publish") + wantName, wantProvider = "concurrent", "aws" + } + kept := s.stored(id) + s.Equal(wantName, kept.Name) + s.Equal(providerFilter(wantProvider), kept.Filter.Data()) + s.Equal(f.Badge, kept.Badge) + }) + } +} diff --git a/internal/api/handler/filter_badge_test.go b/internal/api/handler/filter_badge_test.go new file mode 100644 index 00000000..bb976699 --- /dev/null +++ b/internal/api/handler/filter_badge_test.go @@ -0,0 +1,82 @@ +package handler + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/compliance-framework/api/internal/service/relational" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func strPtr(s string) *string { return &s } + +// resolveBody decodes body as a filter request and applies its badge to current. +func resolveBody(t *testing.T, current relational.FilterBadge, body string) (relational.FilterBadge, error) { + t.Helper() + var req createFilterRequest + require.NoError(t, json.Unmarshal([]byte(body), &req)) + return resolveFilterBadge(current, req.Badge, req.badgeSet) +} + +func TestResolveFilterBadge(t *testing.T) { + published := relational.FilterBadge{Enabled: true, Label: "payments", Slug: strPtr("payments")} + unpublished := relational.FilterBadge{Label: "payments", Slug: strPtr("payments")} + + cases := []struct { + name string + current relational.FilterBadge + body string + want relational.FilterBadge + wantErr bool + }{ + {"omitted keeps settings", published, `{}`, published, false}, + {"null resets to defaults", published, `{"badge":null}`, relational.DefaultFilterBadge(), false}, + {"empty object keeps settings", published, `{"badge":{}}`, published, false}, + {"disable keeps slug", published, `{"badge":{"enabled":false}}`, unpublished, false}, + {"slug null clears and unpublishes, keeps label", published, `{"badge":{"slug":null}}`, relational.FilterBadge{Label: "payments"}, false}, + {"enable with slug", relational.DefaultFilterBadge(), `{"badge":{"enabled":true,"slug":"a-1"}}`, relational.FilterBadge{Enabled: true, Label: "compliance", Slug: strPtr("a-1")}, false}, + {"label trimmed", relational.DefaultFilterBadge(), `{"badge":{"label":" ok "}}`, relational.FilterBadge{Label: "ok"}, false}, + {"enable without slug", relational.DefaultFilterBadge(), `{"badge":{"enabled":true}}`, relational.FilterBadge{}, true}, + {"enable with null slug", published, `{"badge":{"enabled":true,"slug":null}}`, relational.FilterBadge{}, true}, + {"empty slug", relational.DefaultFilterBadge(), `{"badge":{"slug":""}}`, relational.FilterBadge{}, true}, + {"uppercase slug not lowercased", relational.DefaultFilterBadge(), `{"badge":{"slug":"Payments"}}`, relational.FilterBadge{}, true}, + {"double hyphen", relational.DefaultFilterBadge(), `{"badge":{"slug":"a--b"}}`, relational.FilterBadge{}, true}, + {"leading hyphen", relational.DefaultFilterBadge(), `{"badge":{"slug":"-a"}}`, relational.FilterBadge{}, true}, + {"slug with suffix", relational.DefaultFilterBadge(), `{"badge":{"slug":"a.svg"}}`, relational.FilterBadge{}, true}, + {"slug too long", relational.DefaultFilterBadge(), `{"badge":{"slug":"` + strings.Repeat("a", 64) + `"}}`, relational.FilterBadge{}, true}, + {"blank label", relational.DefaultFilterBadge(), `{"badge":{"label":" "}}`, relational.FilterBadge{}, true}, + {"label too long", relational.DefaultFilterBadge(), `{"badge":{"label":"` + strings.Repeat("é", 65) + `"}}`, relational.FilterBadge{}, true}, + {"label control char", relational.DefaultFilterBadge(), `{"badge":{"label":"a\u0007b"}}`, relational.FilterBadge{}, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := resolveBody(t, tc.current, tc.body) + if tc.wantErr { + assert.Error(t, err) + return + } + require.NoError(t, err) + assert.True(t, badgeEqual(tc.want, got), "got %+v (slug %v), want %+v", got, got.Slug, tc.want) + }) + } + + // The longest valid slug is accepted. + _, err := resolveBody(t, relational.DefaultFilterBadge(), `{"badge":{"slug":"`+strings.Repeat("a", 63)+`"}}`) + assert.NoError(t, err) +} + +func TestFilterBadgeRequestRejectsMalformed(t *testing.T) { + for _, body := range []string{ + `{"badge":[]}`, + `{"badge":"x"}`, + `{"badge":{"enabled":null}}`, + `{"badge":{"enabled":"yes"}}`, + `{"badge":{"label":null}}`, + `{"badge":{"slug":1}}`, + } { + var req createFilterRequest + assert.Errorf(t, json.Unmarshal([]byte(body), &req), "body %s", body) + } +} diff --git a/internal/api/handler/filter_import.go b/internal/api/handler/filter_import.go index 6be47c48..e15267af 100644 --- a/internal/api/handler/filter_import.go +++ b/internal/api/handler/filter_import.go @@ -2,6 +2,7 @@ package handler import ( "encoding/json" + "errors" "fmt" "io" "mime/multipart" @@ -13,6 +14,7 @@ import ( "github.com/google/uuid" "github.com/labstack/echo/v5" "gorm.io/datatypes" + "gorm.io/gorm" "gorm.io/gorm/clause" ) @@ -73,7 +75,7 @@ func (h *FilterHandler) ImportFilters(ctx *echo.Context) error { } for _, fileHeader := range files { - result := h.processFilterFile(fileHeader) + result := h.processFilterFile(ctx, fileHeader) response.Results = append(response.Results, result) if result.Success { response.SuccessfulCount++ @@ -91,7 +93,7 @@ func (h *FilterHandler) ImportFilters(ctx *echo.Context) error { return ctx.JSON(statusCode, GenericDataResponse[FilterImportResponse]{Data: response}) } -func (h *FilterHandler) processFilterFile(fileHeader *multipart.FileHeader) FilterImportFileResult { +func (h *FilterHandler) processFilterFile(ctx *echo.Context, fileHeader *multipart.FileHeader) FilterImportFileResult { result := FilterImportFileResult{ Filename: fileHeader.Filename, Success: false, @@ -140,7 +142,13 @@ func (h *FilterHandler) processFilterFile(fileHeader *multipart.FileHeader) Filt rec.Filter = datatypes.NewJSONType(lf) } - if err := h.db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&rec).Error; err != nil { + if err := h.db.Transaction(func(tx *gorm.DB) error { + return h.upsertImportedFilter(ctx, tx, &rec) + }); err != nil { + if errors.Is(err, errPublishForbidden) { + result.Message = fmt.Sprintf("Failed to import filter '%s': %v", in.Name, err) + return result + } result.Message = fmt.Sprintf("Failed to create filter '%s': %v", in.Name, err) return result } @@ -172,3 +180,46 @@ func (h *FilterHandler) processFilterFile(fileHeader *multipart.FileHeader) Filt result.Message = fmt.Sprintf("Successfully imported %d dashboard(s)", created) return result } + +// upsertImportedFilter creates rec, or overwrites the imported fields of the filter with +// its ID. The existing filter keeps its badge settings, and changing the selection of a +// published one needs filter:publish, as on PUT /filters/:id. +func (h *FilterHandler) upsertImportedFilter(ctx *echo.Context, tx *gorm.DB, rec *relational.Filter) error { + for rec.ID != nil { + var existing relational.Filter + err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&existing, "id = ?", *rec.ID).Error + switch { + case errors.Is(err, gorm.ErrRecordNotFound): + insert := tx.Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "id"}}, + DoNothing: true, + }).Create(rec) + if insert.Error != nil { + return insert.Error + } + if insert.RowsAffected > 0 { + return nil + } + // A missing row cannot be locked; recheck the concurrent insert. + continue + case err != nil: + return err + case existing.Badge.Enabled: + before, err := selectionOf(&existing) + if err != nil { + return err + } + after, err := selectionOf(rec) + if err != nil { + return err + } + if before != after { + if err := h.authorizePublish(ctx, rec.ID.String()); err != nil { + return err + } + } + } + break + } + return tx.Clauses(relational.FilterImportUpsert()).Create(rec).Error +} diff --git a/internal/api/handler/request.go b/internal/api/handler/request.go index 5483489e..906dc0a8 100644 --- a/internal/api/handler/request.go +++ b/internal/api/handler/request.go @@ -2,6 +2,8 @@ package handler import ( "encoding/json" + "errors" + "fmt" "strings" "time" @@ -40,6 +42,65 @@ type createFilterRequest struct { // scope changes. Requires sspId and a non-empty scope. On PUT, false stops following // and keeps the current effective filter; omitted keeps the current state. FollowSSPScope *bool `json:"followSspScope,omitempty" yaml:"-"` + // Badge changes the filter's public badge (docs/filter-badges.md) and needs the + // filter:publish permission unless it leaves the settings unchanged. Omitted keeps the + // current settings (POST: unpublished defaults); null resets them to the defaults. + Badge *filterBadgeRequest `json:"badge,omitempty" yaml:"-" extensions:"x-nullable"` + + // badgeSet records that the body had a badge key, so a null badge can be told apart + // from an omitted one. + badgeSet bool +} + +// filterBadgeRequest is the badge object of a filter create or update. Omitted fields +// keep their current values on update and take the defaults on create. +type filterBadgeRequest struct { + // Enabled publishes the badge at /api/public/badges/{slug}.svg; it requires a slug. + Enabled *bool `json:"enabled,omitempty"` + // Label is the badge's left-hand text: 1-64 characters after trimming, no control + // characters. + Label *string `json:"label,omitempty" example:"compliance"` + // Slug is the public identifier: lowercase letters, digits and single hyphens, at + // most 63 characters, unique across filters. null clears it and unpublishes. + Slug *string `json:"slug,omitempty" extensions:"x-nullable" example:"payments-production"` + + // slugSet records that the body had a slug key, so a null slug can be told apart from + // an omitted one. + slugSet bool +} + +func (r *filterBadgeRequest) UnmarshalJSON(data []byte) error { + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + if fields == nil { + return errors.New("badge must be an object") + } + *r = filterBadgeRequest{} + if raw, ok := fields["enabled"]; ok { + if err := json.Unmarshal(raw, &r.Enabled); err != nil { + return fmt.Errorf("badge.enabled: %w", err) + } + if r.Enabled == nil { + return errors.New("badge.enabled must be true or false") + } + } + if raw, ok := fields["label"]; ok { + if err := json.Unmarshal(raw, &r.Label); err != nil { + return fmt.Errorf("badge.label: %w", err) + } + if r.Label == nil { + return errors.New("badge.label must be a string") + } + } + if raw, ok := fields["slug"]; ok { + r.slugSet = true + if err := json.Unmarshal(raw, &r.Slug); err != nil { + return fmt.Errorf("badge.slug: %w", err) + } + } + return nil } // UnmarshalJSON accepts sspId in either camelCase or kebab-case ("ssp-id"). The @@ -55,6 +116,7 @@ func (r *createFilterRequest) UnmarshalJSON(data []byte) error { Controls *[]string `json:"controls"` Components *[]string `json:"components"` Follow *bool `json:"followSspScope"` + Badge json.RawMessage `json:"badge"` } var decoded requestAlias @@ -71,6 +133,14 @@ func (r *createFilterRequest) UnmarshalJSON(data []byte) error { r.Controls = decoded.Controls r.Components = decoded.Components r.FollowSSPScope = decoded.Follow + r.Badge = nil + r.badgeSet = decoded.Badge != nil + if r.badgeSet && string(decoded.Badge) != "null" { + r.Badge = &filterBadgeRequest{} + if err := json.Unmarshal(decoded.Badge, r.Badge); err != nil { + return err + } + } return nil } diff --git a/internal/authz/builtin.go b/internal/authz/builtin.go index 735fcf5b..61feda5d 100644 --- a/internal/authz/builtin.go +++ b/internal/authz/builtin.go @@ -22,7 +22,8 @@ func init() { // Builtin is the default, in-process PDP. It reproduces CCF's pre-authz access rules with // zero behavior change: admin resources require SSO admin-group membership (password // users are treated as super admins), the agent resource requires the same admin check for -// users (agent service accounts may register, ingest and sync; anonymous is denied; R39), and every other +// users (agent service accounts may register, ingest and sync; anonymous is denied; R39), +// filter:publish requires the same admin check, and every other // resource is allowed once the request is authenticated — the authn middleware having already enforced authentication // and any public-endpoint policy before the PEP runs. // @@ -68,6 +69,11 @@ func (b *Builtin) Evaluate(ctx context.Context, s Subject, action string, r Reso return Decision{Allow: false, Reason: "builtin: anonymous access to agent resource"}, nil } default: + if r.Type == ResourceFilter && action == ActionPublish { + // Publishing makes evidence-derived state anonymous, so it needs the admin + // check rather than the authenticated-request allow below. + return b.evaluateAdmin(ctx, s) + } // Phase 1: authenticated = allowed. The authn middleware already enforced // authentication (and any public-endpoint policy) before the PEP runs, so any // request that reaches a decision is permitted. Resource-attribute policies @@ -90,8 +96,10 @@ func (b *Builtin) Evaluations(ctx context.Context, reqs []EvalRequest) ([]Decisi out := make([]Decision, len(reqs)) for i, req := range reqs { - // Agent-resource requests from users resolve through the same admin check. - if req.Resource.Type == ResourceAdmin || (req.Resource.Type == ResourceAgent && req.Subject.Type == "user") { + // Agent-resource requests from users, and filter:publish, resolve through the same + // admin check. + if req.Resource.Type == ResourceAdmin || (req.Resource.Type == ResourceAgent && req.Subject.Type == "user") || + (req.Resource.Type == ResourceFilter && req.Action == ActionPublish) { key := adminKey{req.Subject.Type, req.Subject.ID} if d, ok := adminMemo[key]; ok { out[i] = d diff --git a/internal/authz/builtin_admin_integration_test.go b/internal/authz/builtin_admin_integration_test.go index d7da4bf4..a0b4c715 100644 --- a/internal/authz/builtin_admin_integration_test.go +++ b/internal/authz/builtin_admin_integration_test.go @@ -206,3 +206,30 @@ func TestBuiltinEvaluationsMemoizesAdmin(t *testing.T) { // would issue 8 (2 × 4 actions); the memo keeps it at the single-resolution cost. require.LessOrEqualf(t, queries, 2, "admin facts should resolve once (<=2 queries), got %d", queries) } + +// filter:publish resolves through the admin check, with the same decision singly and in a +// batch, while filter:update stays allowed for any authenticated user. +func TestBuiltinFilterPublishAdminParity(t *testing.T) { + db := setupAuthzDB(t) + cfg := ssoEnabledConfig([]string{"ccf-admins"}) + admin := createUser(t, db, "admin@example.com", "sso") + createSSOLink(t, db, admin, "test", []string{"ccf-admins"}) + member := createUser(t, db, "member@example.com", "sso") + createSSOLink(t, db, member, "test", []string{"engineers"}) + + b := NewBuiltin(db, cfg, zap.NewNop().Sugar()) + filter := Resource{Type: ResourceFilter, ID: "f-1"} + for email, want := range map[string]bool{"admin@example.com": true, "member@example.com": false} { + s := Subject{Type: "user", ID: email} + single, err := b.Evaluate(context.Background(), s, ActionPublish, filter, nil) + require.NoError(t, err) + batch, err := b.Evaluations(context.Background(), []EvalRequest{ + {Subject: s, Action: ActionUpdate, Resource: filter}, + {Subject: s, Action: ActionPublish, Resource: filter}, + }) + require.NoError(t, err) + require.Equalf(t, want, single.Allow, "%s: single filter:publish", email) + require.Equalf(t, want, batch[1].Allow, "%s: batch filter:publish", email) + require.Truef(t, batch[0].Allow, "%s: filter:update", email) + } +} diff --git a/internal/authz/builtin_test.go b/internal/authz/builtin_test.go index f54caf13..0e5d4509 100644 --- a/internal/authz/builtin_test.go +++ b/internal/authz/builtin_test.go @@ -88,3 +88,28 @@ func TestBuiltinRegisteredAsDefaultDriver(t *testing.T) { t.Fatal("Open(unknown driver) expected error, got nil") } } + +// filter:publish is not implied by an authenticated request the way other filter actions +// are: without a user subject it is denied, before any DB access, singly and in a batch. +func TestBuiltinFilterPublishNeedsAdmin(t *testing.T) { + b := NewBuiltin(nil, nil, nil) + filter := Resource{Type: ResourceFilter, ID: "f-1"} + + for _, s := range []Subject{{Type: "anonymous"}, {Type: "agent", ID: "agent-1"}, {Type: "user", ID: ""}} { + update, err := b.Evaluate(context.Background(), s, ActionUpdate, filter, nil) + if err != nil || !update.Allow { + t.Fatalf("Evaluate(filter:update) subject=%+v = %+v, %v; want allow", s, update, err) + } + publish, err := b.Evaluate(context.Background(), s, ActionPublish, filter, nil) + if err != nil { + t.Fatalf("Evaluate(filter:publish) subject=%+v error = %v", s, err) + } + decs, err := b.Evaluations(context.Background(), []EvalRequest{{Subject: s, Action: ActionPublish, Resource: filter}}) + if err != nil { + t.Fatalf("Evaluations(filter:publish) subject=%+v error = %v", s, err) + } + if publish.Allow || decs[0].Allow { + t.Errorf("filter:publish subject=%+v allow = %v (single), %v (batch); want false", s, publish.Allow, decs[0].Allow) + } + } +} diff --git a/internal/authz/filter_publish_authz_test.go b/internal/authz/filter_publish_authz_test.go new file mode 100644 index 00000000..c5d8310a --- /dev/null +++ b/internal/authz/filter_publish_authz_test.go @@ -0,0 +1,49 @@ +package authz + +import ( + "slices" + "testing" +) + +func TestManifestDeclaresFilterPublish(t *testing.T) { + m, err := DefaultManifest() + if err != nil { + t.Fatal(err) + } + if !slices.Contains(m.Resources[ResourceFilter].Actions, ActionPublish) { + t.Fatalf("filter resource missing %q (have %v)", ActionPublish, m.Resources[ResourceFilter].Actions) + } +} + +// Under Cedar only admin ("*": ["*"]) holds filter:publish; contributors, who may update +// filters, may not publish them, and neither may agents or anonymous callers. +func TestCedarFilterPublishMatrix(t *testing.T) { + c := mustCedar(t, &RoleAssignments{ + Users: map[string]string{ + "admin@x": "admin", + "viewer@x": "viewer", + "auditor@x": "auditor", + "contributor@x": "contributor", + }, + }) + user := func(id string) Subject { return Subject{Type: "user", ID: id} } + cases := []struct { + subj Subject + want bool + }{ + {user("admin@x"), true}, + {user("viewer@x"), false}, + {user("auditor@x"), false}, + {user("contributor@x"), false}, + {Subject{Type: "agent", ID: "agent-1"}, false}, + {Subject{Type: "anonymous"}, false}, + } + for _, tc := range cases { + if got := allows(t, c, tc.subj, ActionPublish, ResourceFilter); got != tc.want { + t.Errorf("%s %s: filter:publish allow = %v, want %v", tc.subj.Type, tc.subj.ID, got, tc.want) + } + } + if !allows(t, c, user("contributor@x"), ActionUpdate, ResourceFilter) { + t.Error("contributor: filter:update should stay allowed") + } +} diff --git a/internal/authz/manifest.yaml b/internal/authz/manifest.yaml index fa01f3bf..1bd59542 100644 --- a/internal/authz/manifest.yaml +++ b/internal/authz/manifest.yaml @@ -28,7 +28,7 @@ # roles — it allows every authenticated non-admin request and only gates `admin` via SSO # groups (zero behavior change), except the `agent` resource: users need the same admin # check there, agent service accounts may only register, ingest and sync, and anonymous is -# denied (R39). The embedded Cedar engine (BCH-1316) DOES honor this C0 role +# denied (R39); filter:publish also needs the admin check. The embedded Cedar engine (BCH-1316) DOES honor this C0 role # set; select it with `authz.driver: cedar` (see docs/authz-oss-cedar.md). C1/C2 stay # Enterprise/BYO. schemaVersion: 1 @@ -168,7 +168,9 @@ resources: # ── Archetype E: dashboard / config (SSP-scoped) ── filter: - actions: [read, create, update, delete] + # publish changes a saved filter's anonymous badge (docs/filter-badges.md): its badge + # settings, or the selection of a published filter. Only admin ("*") holds it. + actions: [read, create, update, delete, publish] attributes: ssp_id: uuid dashboard-suggestion: diff --git a/internal/authz/pdp.go b/internal/authz/pdp.go index 6d8be9b1..7bfc4b26 100644 --- a/internal/authz/pdp.go +++ b/internal/authz/pdp.go @@ -142,6 +142,11 @@ const ( // Cedar grants it to admin only, unless an operator grants it to another role. ActionInspect = "inspect" + // ActionPublish (resource filter) publishes a saved filter's aggregate as an anonymous + // badge: changing its badge settings, or the selection of a published filter. Cedar + // grants it to admin only; builtin requires the admin check. + ActionPublish = "publish" + // Agent remote configuration (resource agent). ActionConfigure writes an agent's // configuration overlay; ActionSync is the agent fetching its overlay and reporting. ActionRegister = "register" diff --git a/internal/badge/badge.go b/internal/badge/badge.go new file mode 100644 index 00000000..0c4348b9 --- /dev/null +++ b/internal/badge/badge.go @@ -0,0 +1,155 @@ +// Package badge renders the SVG status badges published for saved evidence filters +// (docs/filter-badges.md). A badge discloses only its label and one aggregate state. +package badge + +import ( + "bytes" + "encoding/xml" + "fmt" + "strings" + "unicode/utf8" +) + +// State is the aggregate compliance state a badge displays. +type State string + +const ( + StateNoEvidence State = "no evidence" + StateFailing State = "failing" + StatePassing State = "passing" + StateUnknown State = "unknown" +) + +// MaxLabelRunes bounds the label, and so the rendered width. +const MaxLabelRunes = 64 + +const ( + colorLabel = "#555" + colorRed = "#e05d44" + colorGreen = "#4c1" + colorGray = "#9f9f9f" + height = 20 + padding = 6 + asciiWidth = 7 + wideWidth = 12 + minTextWidth = 8 +) + +// Count is one evidence state and how much latest evidence is in it. +type Count struct { + State string + Count int64 +} + +// Aggregate reduces evidence state counts to the badge state: no evidence, failing when +// any evidence is not-satisfied, passing when all of it is satisfied, otherwise unknown. +// Unfamiliar and empty states are never treated as satisfied. +func Aggregate(counts []Count) State { + var total int64 + failing := false + allSatisfied := true + for _, c := range counts { + if c.Count <= 0 { + continue + } + total += c.Count + switch strings.ToLower(strings.TrimSpace(c.State)) { + case "not-satisfied": + failing = true + case "satisfied": + default: + allSatisfied = false + } + } + switch { + case total == 0: + return StateNoEvidence + case failing: + return StateFailing + case allSatisfied: + return StatePassing + default: + return StateUnknown + } +} + +func (s State) color() string { + switch s { + case StateFailing: + return colorRed + case StatePassing: + return colorGreen + default: + return colorGray + } +} + +func (s State) text() string { + switch s { + case StateNoEvidence, StateFailing, StatePassing: + return string(s) + default: + return string(StateUnknown) + } +} + +// Render returns the badge SVG. It references nothing outside itself: no scripts, links, +// images, fonts or URLs. Every inserted string is XML-escaped, which is safe in both the +// text and attribute contexts it is used in. +func Render(label string, state State) []byte { + label = truncate(label, MaxLabelRunes) + value := state.text() + + labelTextWidth := textWidth(label) + valueTextWidth := textWidth(value) + labelWidth := labelTextWidth + 2*padding + valueWidth := valueTextWidth + 2*padding + width := labelWidth + valueWidth + title := escape(label + ": " + value) + color := state.color() + + var b bytes.Buffer + fmt.Fprintf(&b, ``, width, height, width, height, title) + fmt.Fprintf(&b, `%s`, title) + fmt.Fprintf(&b, ``, width, height, colorLabel) + fmt.Fprintf(&b, ``, labelWidth, valueWidth, height, color) + fmt.Fprintf(&b, ``, labelWidth, height, color) + b.WriteString(``) + writeText(&b, labelWidth/2, labelTextWidth, escape(label)) + writeText(&b, labelWidth+valueWidth/2, valueTextWidth, escape(value)) + b.WriteString(``) + return b.Bytes() +} + +func writeText(b *bytes.Buffer, x, length int, escaped string) { + fmt.Fprintf(b, ``, x, length, escaped) + fmt.Fprintf(b, `%s`, x, length, escaped) +} + +// textWidth estimates the rendered width of s at 11px. +func textWidth(s string) int { + w := 0 + for _, r := range s { + if r < utf8.RuneSelf { + w += asciiWidth + } else { + w += wideWidth + } + } + return max(w, minTextWidth) +} + +func truncate(s string, n int) string { + if utf8.RuneCountInString(s) <= n { + return s + } + return string([]rune(s)[:n]) +} + +func escape(s string) string { + var b bytes.Buffer + // xml.EscapeText escapes quotes and replaces characters XML cannot carry; writing to a + // bytes.Buffer cannot fail. + _ = xml.EscapeText(&b, []byte(s)) + return b.String() +} diff --git a/internal/badge/badge_test.go b/internal/badge/badge_test.go new file mode 100644 index 00000000..d2aaeb57 --- /dev/null +++ b/internal/badge/badge_test.go @@ -0,0 +1,89 @@ +package badge + +import ( + "encoding/xml" + "strings" + "testing" +) + +func TestAggregate(t *testing.T) { + cases := []struct { + name string + counts []Count + want State + }{ + {"empty", nil, StateNoEvidence}, + {"zero counts", []Count{{"satisfied", 0}}, StateNoEvidence}, + {"all satisfied", []Count{{"satisfied", 3}}, StatePassing}, + {"any not-satisfied", []Count{{"satisfied", 9}, {"not-satisfied", 1}}, StateFailing}, + {"failing beats unknown", []Count{{"not-satisfied", 1}, {"other", 1}}, StateFailing}, + {"unfamiliar state", []Count{{"satisfied", 9}, {"pending", 1}}, StateUnknown}, + {"empty state", []Count{{"satisfied", 9}, {"", 1}}, StateUnknown}, + {"case and space folded", []Count{{" Satisfied ", 2}}, StatePassing}, + } + for _, tc := range cases { + if got := Aggregate(tc.counts); got != tc.want { + t.Errorf("%s: Aggregate = %q, want %q", tc.name, got, tc.want) + } + } +} + +func TestRenderEscapesAndStaysSelfContained(t *testing.T) { + label := ` & 'q' ` + "\uFFFE" + svg := string(Render(label, StateFailing)) + + if err := xml.Unmarshal([]byte(svg), new(struct{})); err != nil { + t.Fatalf("rendered SVG is not well-formed XML: %v\n%s", err, svg) + } + for _, forbidden := range []string{"", "failing", "#e05d44"} { + if !strings.Contains(svg, want) { + t.Errorf("SVG lacks %q:\n%s", want, svg) + } + } + // Only the SVG namespace may appear as a URL. + if strings.Count(svg, "http") != 1 { + t.Errorf("SVG references URLs other than its namespace:\n%s", svg) + } +} + +func TestRenderIsBoundedAndDeterministic(t *testing.T) { + long := strings.Repeat("界", 500) + a, b := Render(long, StatePassing), Render(long, StatePassing) + if string(a) != string(b) { + t.Fatal("Render is not deterministic") + } + // aria-label, title, and the text and its shadow each carry the label once. + if got := strings.Count(string(a), "界"); got != 4*MaxLabelRunes { + t.Errorf("label occurrences = %d runes, want truncation to %d per use", got, MaxLabelRunes) + } + if len(a) > 4096 { + t.Errorf("SVG is %d bytes; want a small bounded document", len(a)) + } +} + +func TestRenderStates(t *testing.T) { + for state, color := range map[State]string{ + StatePassing: "#4c1", + StateFailing: "#e05d44", + StateNoEvidence: "#9f9f9f", + StateUnknown: "#9f9f9f", + State("bogus"): "#9f9f9f", + } { + svg := string(Render("compliance", state)) + if !strings.Contains(svg, color) { + t.Errorf("%q: missing color %s", state, color) + } + text := string(state) + if state == "bogus" { + text = string(StateUnknown) + } + if !strings.Contains(svg, "compliance: "+text+"") { + t.Errorf("%q: missing title text %q:\n%s", state, text, svg) + } + } +} diff --git a/internal/service/relational/filters.go b/internal/service/relational/filters.go index 72e4f4ba..775ef429 100644 --- a/internal/service/relational/filters.go +++ b/internal/service/relational/filters.go @@ -4,6 +4,7 @@ import ( "github.com/compliance-framework/api/internal/converters/labelfilter" "github.com/google/uuid" "gorm.io/datatypes" + "gorm.io/gorm/clause" ) // Origins of a filter. @@ -12,6 +13,39 @@ const ( FilterOriginScopePolicy = "scope-policy" ) +const ( + // DefaultFilterBadgeLabel is the badge label of a filter that has not set one. + DefaultFilterBadgeLabel = "compliance" + // FilterBadgeSlugIndex is the partial unique index reserving badge slugs across all + // filters, published or not. + FilterBadgeSlugIndex = "idx_filters_badge_slug" +) + +// FilterBadge holds a filter's public badge settings (docs/filter-badges.md). A slug is +// reserved while a filter holds it; the badge is public only while Enabled. +type FilterBadge struct { + Enabled bool `json:"enabled" gorm:"column:badge_enabled;not null;default:false;check:chk_filters_badge_enabled_slug,badge_enabled = false OR badge_slug IS NOT NULL"` + // Label is the plain-text left-hand side of the badge. + Label string `json:"label" gorm:"column:badge_label;not null;default:compliance"` + // Slug is the public identifier in /api/public/badges/{slug}.svg. Absent is NULL, never "". + Slug *string `json:"slug" gorm:"column:badge_slug;uniqueIndex:idx_filters_badge_slug,where:badge_slug IS NOT NULL;check:chk_filters_badge_slug_not_empty,badge_slug IS NULL OR badge_slug <> ''"` +} + +// DefaultFilterBadge returns the settings of an unpublished filter. +func DefaultFilterBadge() FilterBadge { + return FilterBadge{Label: DefaultFilterBadgeLabel} +} + +// FilterImportUpsert is the conflict clause for filter imports that may overwrite an +// existing filter by ID. It updates the imported fields only, so an import never +// copies, resets or clears another filter's badge settings. +func FilterImportUpsert() clause.OnConflict { + return clause.OnConflict{ + Columns: []clause.Column{{Name: "id"}}, + DoUpdates: clause.AssignmentColumns([]string{"name", "ssp_id", "filter", "scope_base", "origin"}), + } +} + type Filter struct { UUIDModel @@ -23,7 +57,10 @@ type Filter struct { ScopeBase *datatypes.JSONType[labelfilter.Filter] `json:"scopeBase,omitempty" yaml:"-"` // Origin is "manual" for user-made filters and "scope-policy" for automatic per-policy // filters. - Origin string `json:"origin" yaml:"-" gorm:"not null;default:manual"` + Origin string `json:"origin" yaml:"-" gorm:"not null;default:manual"` + // Badge is never imported or copied: imports, clones and generated filters start + // unpublished. + Badge FilterBadge `json:"badge" yaml:"-" gorm:"embedded"` Controls []Control `json:"controls" gorm:"many2many:filter_controls;"` Components []SystemComponent `json:"components" gorm:"many2many:filter_system_components;"` diff --git a/internal/service/relational/sspscope/following.go b/internal/service/relational/sspscope/following.go index 80d52dd5..dd7b6f0f 100644 --- a/internal/service/relational/sspscope/following.go +++ b/internal/service/relational/sspscope/following.go @@ -35,7 +35,7 @@ func (e *ScopeWouldEmptyError) Is(target error) bool { return target == ErrScope // open transaction and the filter must be written in it; a concurrent scope change then // waits and rewrites the filter. It fails with ErrSSPNotFound or ErrScopeEmpty. func FollowScope(tx *gorm.DB, sspID uuid.UUID, base labelfilter.Filter) (labelfilter.Filter, error) { - if err := lockSSP(tx, sspID); err != nil { + if err := LockSSP(tx, sspID); err != nil { return labelfilter.Filter{}, err } if err := ensureSSP(tx, sspID); err != nil { diff --git a/internal/service/relational/sspscope/service.go b/internal/service/relational/sspscope/service.go index 6c05d292..74430d13 100644 --- a/internal/service/relational/sspscope/service.go +++ b/internal/service/relational/sspscope/service.go @@ -200,7 +200,7 @@ type LearnResult struct { // immediately. func (s *Service) Learn(tx *gorm.DB, sspID, templateID uuid.UUID, entries [][]relational.ScopeLabel) (LearnResult, error) { result := LearnResult{Added: []relational.SSPScopeEntry{}, Skipped: []SkippedEntry{}} - if err := lockSSP(tx, sspID); err != nil { + if err := LockSSP(tx, sspID); err != nil { return LearnResult{}, err } if err := ensureSSP(tx, sspID); err != nil { @@ -341,7 +341,7 @@ func (s *Service) afterChange(tx *gorm.DB, sspID uuid.UUID) error { // exists. func (s *Service) write(sspID uuid.UUID, fn func(tx *gorm.DB) error) error { return s.db.Transaction(func(tx *gorm.DB) error { - if err := lockSSP(tx, sspID); err != nil { + if err := LockSSP(tx, sspID); err != nil { return err } if err := ensureSSP(tx, sspID); err != nil { @@ -351,8 +351,9 @@ func (s *Service) write(sspID uuid.UUID, fn func(tx *gorm.DB) error) error { }) } -// lockSSP takes the SSP's transaction-scoped advisory lock (postgres only). -func lockSSP(tx *gorm.DB, sspID uuid.UUID) error { +// LockSSP takes the SSP's transaction-scoped advisory lock (postgres only). +// tx must be an open transaction; acquire this lock before locking filter rows. +func LockSSP(tx *gorm.DB, sspID uuid.UUID) error { if tx.Name() != "postgres" { return nil }