From 7909f1e1caf71f4983221a2cb72a78e7bbbf803a Mon Sep 17 00:00:00 2001 From: "Alen M." <18172779+alenmalhas@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:54:46 +0000 Subject: [PATCH 1/7] feat(docs): add API specification for saved evidence filter badges --- docs/filter-badges.md | 312 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 312 insertions(+) create mode 100644 docs/filter-badges.md diff --git a/docs/filter-badges.md b/docs/filter-badges.md new file mode 100644 index 00000000..14dff5f6 --- /dev/null +++ b/docs/filter-badges.md @@ -0,0 +1,312 @@ +# Saved evidence filter badges: API specification + +Status: proposed. This document specifies API work; it does not describe an +already implemented feature. + +## 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. + +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. + +To keep a revoked URL from later publishing a different filter, v1 must reject +reassignment of a retired slug, including reassignment to the original filter. +Retain retired slugs in a small reservation/tombstone table when a slug is +changed, cleared, or its filter is deleted. Claiming and retiring slugs must +serialize transactionally against concurrent claims. The partial unique index +on `filters.badge_slug` still protects active reservations; tombstones protect +retired names. Disabling without clearing does not retire the retained slug. + +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 user-authored changes to its effective +predicate, SSP binding, or scope-following configuration while it is enabled. +Otherwise a contributor could broaden a published filter without enabling a +badge themselves. 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 already-configured automatic +SSP scope updates affect it without another publication request. 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. Evaluate before side effects, and use +the current persisted state when checking an update. 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 and `filter:read` | 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 route is explicitly `/api/public/badges/:slug.svg`; the slug is the +dynamic path segment preceding the `.svg` suffix. + +Register preview in the existing authenticated filter group with its read +guard. 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` for denied read permission; `404` for an unknown filter. +- Public: `404` for an invalid, unknown, retired, cleared, disabled, or deleted + slug, with the same generic response shape for each case. +- 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. +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 + +``` + +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. API rate +limits and bounded request handling still apply to this anonymous endpoint. + +## Implementation and verification checklist + +1. Add model fields, defaults, validation, the partial unique index, retired + slug reservations, 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, retired-slug rejection, 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. + - Preview before publication and after disabling; JWT/read enforcement; + public success with no token under both values of the strict-agent flag. + - `404` after disable, rename, clear, deletion, and attempted slug reuse; + no redirect, alias, or conditional-cache bypass. + - 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. + +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. From fae14c603d951f6d0af7a81f9acc6fc44533c049 Mon Sep 17 00:00:00 2001 From: "Alen M." <18172779+alenmalhas@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:32:41 +0000 Subject: [PATCH 2/7] feat(docs): update API specification for saved evidence filter badge publishing --- docs/filter-badges.md | 127 +++++++++++++++++++++++++++++------------- 1 file changed, 88 insertions(+), 39 deletions(-) diff --git a/docs/filter-badges.md b/docs/filter-badges.md index 14dff5f6..245b48a4 100644 --- a/docs/filter-badges.md +++ b/docs/filter-badges.md @@ -10,6 +10,11 @@ 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. @@ -108,13 +113,15 @@ 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. -To keep a revoked URL from later publishing a different filter, v1 must reject -reassignment of a retired slug, including reassignment to the original filter. -Retain retired slugs in a small reservation/tombstone table when a slug is -changed, cleared, or its filter is deleted. Claiming and retiring slugs must -serialize transactionally against concurrent claims. The partial unique index -on `filters.badge_slug` still protects active reservations; tombstones protect -retired names. Disabling without clearing does not retire the retained slug. +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. @@ -139,36 +146,59 @@ 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 user-authored changes to its effective -predicate, SSP binding, or scope-following configuration while it is enabled. -Otherwise a contributor could broaden a published filter without enabling a -badge themselves. Reject the entire unauthorized write before any mutation. +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 already-configured automatic -SSP scope updates affect it without another publication request. This behavior -must be made clear at publication time. Filter deletion retains its existing -delete permission and revokes the badge. +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. Evaluate before side effects, and use -the current persisted state when checking an update. Publication checks must -fail closed if the PDP is unavailable, even if ordinary authorization is -configured fail-open. +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. + +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 and `filter:read` | 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 route is explicitly `/api/public/badges/:slug.svg`; the slug is the -dynamic path segment preceding the `.svg` suffix. - -Register preview in the existing authenticated filter group with its read -guard. Register public badges in a separate, deliberately anonymous group in +| `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. @@ -186,9 +216,11 @@ aggregation. Reject unsupported query parameters with `400`. - 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` for denied read permission; `404` for an unknown filter. -- Public: `404` for an invalid, unknown, retired, cleared, disabled, or deleted - slug, with the same generic response shape for each case. + 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. @@ -251,6 +283,9 @@ 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. @@ -269,13 +304,16 @@ 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. API rate -limits and bounded request handling still apply to this anonymous endpoint. +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, retired - slug reservations, and migrations in the production and test migrators. +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. @@ -287,16 +325,25 @@ limits and bounded request handling still apply to this anonymous endpoint. Swagger files. 6. Add focused tests covering: - Defaults, omitted/null settings, label/slug validation, duplicate slugs, - concurrent claims, retired-slug rejection, and transactional rollback. + 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. - - Preview before publication and after disabling; JWT/read enforcement; + 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, deletion, and attempted slug reuse; - no redirect, alias, or conditional-cache bypass. + - `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; @@ -305,6 +352,8 @@ limits and bounded request handling still apply to this anonymous endpoint. 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 From be7cff540bcb59326abcee0b338ef52e45130cda Mon Sep 17 00:00:00 2001 From: "Alen M." <18172779+alenmalhas@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:31:51 +0000 Subject: [PATCH 3/7] feat: implement filter badge functionality with publishing permissions - Add badge rendering logic to display compliance states for filters. - Introduce badge settings in filter creation and update requests. - Implement authorization checks for publishing filter badges, requiring admin permissions. - Create tests for badge functionality, including validation of badge settings and publishing rules. - Update database schema to support badge attributes and constraints. - Ensure badge settings are preserved during filter imports and updates. --- cmd/dashboards/import.go | 4 +- docs/authz-oss-cedar.md | 4 +- docs/docs.go | 202 ++++- docs/filter-badges.md | 6 +- docs/swagger.json | 202 ++++- docs/swagger.yaml | 159 +++- internal/api/handler/api.go | 10 +- internal/api/handler/filter.go | 243 +++--- internal/api/handler/filter_badge.go | 352 +++++++++ .../handler/filter_badge_integration_test.go | 729 ++++++++++++++++++ internal/api/handler/filter_badge_test.go | 82 ++ internal/api/handler/filter_import.go | 44 +- internal/api/handler/request.go | 70 ++ internal/authz/builtin.go | 14 +- .../authz/builtin_admin_integration_test.go | 27 + internal/authz/builtin_test.go | 25 + internal/authz/filter_publish_authz_test.go | 49 ++ internal/authz/manifest.yaml | 6 +- internal/authz/pdp.go | 5 + internal/badge/badge.go | 155 ++++ internal/badge/badge_test.go | 89 +++ internal/service/relational/filters.go | 39 +- 22 files changed, 2408 insertions(+), 108 deletions(-) create mode 100644 internal/api/handler/filter_badge.go create mode 100644 internal/api/handler/filter_badge_integration_test.go create mode 100644 internal/api/handler/filter_badge_test.go create mode 100644 internal/authz/filter_publish_authz_test.go create mode 100644 internal/badge/badge.go create mode 100644 internal/badge/badge_test.go 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 index 245b48a4..39307be3 100644 --- a/docs/filter-badges.md +++ b/docs/filter-badges.md @@ -1,7 +1,9 @@ # Saved evidence filter badges: API specification -Status: proposed. This document specifies API work; it does not describe an -already implemented feature. +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 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..28ed78ce 100644 --- a/internal/api/handler/filter.go +++ b/internal/api/handler/filter.go @@ -8,8 +8,10 @@ import ( "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 +24,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 +37,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 +210,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 +244,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 +299,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 +313,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 +324,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 +345,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,72 +354,129 @@ 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 + if err := h.db.Transaction(func(tx *gorm.DB) error { + 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 + } + 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 { return h.filterWriteError(ctx, err) @@ -863,9 +926,17 @@ 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)) + 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)) } - return ctx.JSON(http.StatusInternalServerError, api.NewError(err)) + 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..ca2f4f75 --- /dev/null +++ b/internal/api/handler/filter_badge_integration_test.go @@ -0,0 +1,729 @@ +//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(), "