diff --git a/.env.example b/.env.example index 819917b9..59f87bb3 100644 --- a/.env.example +++ b/.env.example @@ -69,6 +69,10 @@ CCF_AGENT_MAX_INSTANCES=500 CCF_ARTIFACT_MAX_BYTES=16777216 CCF_ARTIFACT_MAX_CONCURRENT=8 +# Evidence compliance badge +# Maximum arbitrary label query parameters for GET /api/evidence/badge.svg (positive integer). +CCF_EVIDENCE_BADGE_MAX_PARAMS=3 + # Evidence subjects # Agent evidence whose labels match no component subject template: off (accept), warn (accept # and log) or enforce (reject with 400). diff --git a/README.md b/README.md index a7609a94..f1956f36 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,29 @@ Copy this file to .env to configure environment variables cp .env.example .env ``` +### Evidence compliance badge + +`GET /api/evidence/badge.svg?provider=aws&environment=production` returns an SVG +badge using the latest evidence per stream matching **all** supplied labels. +Every query key is a label name; `source`, `repo`, and `branch` have no special +meaning, required format, or defaults. The one exception is `label`: it is reserved +for the repeatable `label=:` form (split at the first colon), e.g. +`?label=provider:aws&label=environment:production`. This form is what Swagger UI +sends, and it can be mixed with plain `name=value` labels. Send a label literally +named `label` as `label=label:`. + +Supply between one and `CCF_EVIDENCE_BADGE_MAX_PARAMS` labels (default **3**). +The setting must be a positive integer; an explicitly empty setting is invalid. +Empty names/values, repeated keys +(case-insensitive), and exceeding the limit return HTTP 400. Names and values +must be valid UTF-8, at most 255 characters, without surrounding whitespace or +control characters. Internal spaces are allowed; URL-encode label names and values. + +The badge is red for `not-satisfied`, green for `satisfied` when no failures are +present, and grey for `unknown` (including no matching evidence). Responses use +`Cache-Control: no-store`. Existing evidence-read authentication and authorization +rules apply. + ## Contributing We welcome contributions to the API! @@ -99,4 +122,3 @@ export TESTCONTAINERS_RYUK_DISABLED=true; ## License This project is licensed under the GNU AGPLv3 License - see the [LICENSE](LICENSE) file for details. - diff --git a/cmd/root.go b/cmd/root.go index 66b31f3b..f223f590 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -22,6 +22,7 @@ var ( } ) +// setDefaultEnvironmentVariables configures defaults for supported Viper keys. func setDefaultEnvironmentVariables() { viper.SetDefault("app_port", ":8080") viper.SetDefault("db_debug", "false") @@ -48,6 +49,7 @@ func setDefaultEnvironmentVariables() { viper.SetDefault("authz_fail_mode", "closed") } +// bindEnvironmentVariables binds supported Viper keys to CCF-prefixed environment variables. func bindEnvironmentVariables() { viper.SetEnvPrefix("ccf") viper.MustBindEnv("app_port") @@ -69,6 +71,7 @@ func bindEnvironmentVariables() { viper.MustBindEnv("metrics_port") viper.MustBindEnv("use_dev_logger") viper.MustBindEnv("evidence_default_expiry_months") + viper.MustBindEnv("evidence_badge_max_params") viper.MustBindEnv("evidence_require_subject") viper.MustBindEnv("manual_evidence_require_subject") viper.MustBindEnv("digest_enabled") @@ -149,6 +152,7 @@ func init() { rootCmd.AddCommand(RiskDigestCmd) } +// Execute runs the root API command. func Execute() error { if err := rootCmd.Execute(); err != nil { fmt.Println("Error executing root command:", err) diff --git a/cmd/root_test.go b/cmd/root_test.go index c9f4e3a7..642308c5 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -5,7 +5,9 @@ import ( "time" "github.com/compliance-framework/api/internal/config" + "github.com/spf13/viper" "github.com/stretchr/testify/require" + "go.uber.org/zap" ) // The config loaders below read the global viper, which only sees CCF_* environment @@ -18,6 +20,7 @@ func TestBindEnvironmentVariables_ConfigLoadersReadEnv(t *testing.T) { t.Setenv("CCF_EVIDENCE_BATCH_WORKERS", "8") t.Setenv("CCF_EVIDENCE_BATCH_RETENTION", "72h") t.Setenv("CCF_EVIDENCE_BATCH_PRUNE_SCHEDULE", "0 5 * * * *") + t.Setenv("CCF_EVIDENCE_BADGE_MAX_PARAMS", "7") t.Setenv("CCF_SSP_SCOPE_AUTO_FILTERS_SCHEDULE", "0 6 * * * *") t.Setenv("CCF_SSP_TEMPLATE_DISCOVERY_SCHEDULE", "0 7 * * * *") t.Setenv("CCF_SSP_TEMPLATE_STALE_AFTER", "48h") @@ -32,9 +35,31 @@ func TestBindEnvironmentVariables_ConfigLoadersReadEnv(t *testing.T) { PruneSchedule: "0 5 * * * *", }, batch) + badgeMaxParams, err := config.LoadEvidenceBadgeMaxParamsFromViper(viper.GetViper()) + require.NoError(t, err) + require.Equal(t, 7, badgeMaxParams) + require.Equal(t, &config.SSPScopeConfig{AutoFiltersSchedule: "0 6 * * * *"}, config.LoadSSPScopeConfig()) template, err := config.LoadSSPTemplateConfig() require.NoError(t, err) require.Equal(t, &config.SSPTemplateConfig{DiscoverySchedule: "0 7 * * * *", StaleAfter: 48 * time.Hour}, template) + + t.Setenv("CCF_EVIDENCE_BADGE_MAX_PARAMS", "invalid") + _, err = config.LoadEvidenceBadgeMaxParamsFromViper(viper.GetViper()) + require.ErrorContains(t, err, "CCF_EVIDENCE_BADGE_MAX_PARAMS") +} + +// TestNewConfigEvidenceBadgeMaxParams verifies environment settings reach the application config. +func TestNewConfigEvidenceBadgeMaxParams(t *testing.T) { + t.Setenv("CCF_DB_DRIVER", "postgres") + t.Setenv("CCF_DB_CONNECTION", "host=localhost dbname=test") + t.Setenv("CCF_JWT_SECRET", "test-secret") + t.Setenv("CCF_JWT_PRIVATE_KEY", "") + t.Setenv("CCF_JWT_PUBLIC_KEY", "") + t.Setenv("CCF_EVIDENCE_BADGE_MAX_PARAMS", "7") + + cfg := config.NewConfig(zap.NewNop().Sugar()) + + require.Equal(t, 7, cfg.EvidenceBadgeMaxParams) } diff --git a/docs/docs.go b/docs/docs.go index 6b0eb173..013d9bd6 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -4827,6 +4827,69 @@ const docTemplate = `{ ] } }, + "/evidence/badge.svg": { + "get": { + "description": "Returns an SVG badge for the latest evidence matching ALL supplied query parameters as label name/value pairs, e.g. ?provider=aws\u0026environment=production.\nAggregates the latest evidence from each matching stream, so a failure in another stream can make the badge red (not-satisfied).\nRequires 1 to CCF_EVIDENCE_BADGE_MAX_PARAMS labels (default 3). Each key must occur exactly once (keys must be unique case-insensitively) with a non-empty value. No labels are implicit. Names and values are limited to 255 characters without surrounding whitespace or control characters; internal spaces are allowed.\nLabels can be sent in two equivalent forms, which may be mixed: one ?\u003clabel-name\u003e=\u003clabel-value\u003e query parameter per label, or the repeatable label parameter as label=\u003clabel-name\u003e:\u003clabel-value\u003e (split at the first colon). Swagger UI exposes only the label parameter; add one item per label pair.\nThe label key is reserved for the second form, so a label literally named \"label\" must be sent as label=label:\u003cvalue\u003e.\nAuthentication is conditional. When public evidence reads are enabled (CCF_STRICT_DISABLE_PUBLIC_AGENT_ENDPOINTS is false, the default) and the authorization policy permits the read, no credentials are required. Otherwise send an OAuth2 bearer token (Authorization: Bearer \u003ctoken\u003e) or the ccf_auth_token session cookie for a user or agent allowed to read evidence. A supplied Authorization header must always be valid.", + "produces": [ + "image/svg+xml", + "application/json" + ], + "tags": [ + "Evidence" + ], + "summary": "Get an SVG compliance status badge", + "parameters": [ + { + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi", + "description": "Label pair as name:value, e.g. provider:aws. Repeat for each label.", + "name": "label", + "in": "query" + } + ], + "responses": { + "200": { + "description": "SVG compliance badge", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Missing, duplicate, too many or invalid label parameters", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "401": { + "description": "Credentials are required (public evidence reads disabled) or the supplied token is invalid", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "403": { + "description": "The authorization policy denies reading evidence", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "429": { + "description": "Too many badge requests in progress", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + } + } + }, "/evidence/batches": { "post": { "description": "Accepts up to CCF_EVIDENCE_BATCH_MAX_ITEMS evidence and stores them asynchronously, returning the batch to poll with GET /evidence/batches/{id}. Each evidence is the body POST /evidence accepts; its shape and times are checked on submit, everything else when it is processed, where a failure fails that evidence only. Needs an authenticated user or agent, and the worker service.", diff --git a/docs/swagger.json b/docs/swagger.json index 9b005b7f..b30c0b41 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -4821,6 +4821,69 @@ ] } }, + "/evidence/badge.svg": { + "get": { + "description": "Returns an SVG badge for the latest evidence matching ALL supplied query parameters as label name/value pairs, e.g. ?provider=aws\u0026environment=production.\nAggregates the latest evidence from each matching stream, so a failure in another stream can make the badge red (not-satisfied).\nRequires 1 to CCF_EVIDENCE_BADGE_MAX_PARAMS labels (default 3). Each key must occur exactly once (keys must be unique case-insensitively) with a non-empty value. No labels are implicit. Names and values are limited to 255 characters without surrounding whitespace or control characters; internal spaces are allowed.\nLabels can be sent in two equivalent forms, which may be mixed: one ?\u003clabel-name\u003e=\u003clabel-value\u003e query parameter per label, or the repeatable label parameter as label=\u003clabel-name\u003e:\u003clabel-value\u003e (split at the first colon). Swagger UI exposes only the label parameter; add one item per label pair.\nThe label key is reserved for the second form, so a label literally named \"label\" must be sent as label=label:\u003cvalue\u003e.\nAuthentication is conditional. When public evidence reads are enabled (CCF_STRICT_DISABLE_PUBLIC_AGENT_ENDPOINTS is false, the default) and the authorization policy permits the read, no credentials are required. Otherwise send an OAuth2 bearer token (Authorization: Bearer \u003ctoken\u003e) or the ccf_auth_token session cookie for a user or agent allowed to read evidence. A supplied Authorization header must always be valid.", + "produces": [ + "image/svg+xml", + "application/json" + ], + "tags": [ + "Evidence" + ], + "summary": "Get an SVG compliance status badge", + "parameters": [ + { + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi", + "description": "Label pair as name:value, e.g. provider:aws. Repeat for each label.", + "name": "label", + "in": "query" + } + ], + "responses": { + "200": { + "description": "SVG compliance badge", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Missing, duplicate, too many or invalid label parameters", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "401": { + "description": "Credentials are required (public evidence reads disabled) or the supplied token is invalid", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "403": { + "description": "The authorization policy denies reading evidence", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "429": { + "description": "Too many badge requests in progress", + "schema": { + "$ref": "#/definitions/api.Error" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/api.Error" + } + } + } + } + }, "/evidence/batches": { "post": { "description": "Accepts up to CCF_EVIDENCE_BATCH_MAX_ITEMS evidence and stores them asynchronously, returning the batch to poll with GET /evidence/batches/{id}. Each evidence is the body POST /evidence accepts; its shape and times are checked on submit, everything else when it is processed, where a failure fails that evidence only. Needs an authenticated user or agent, and the worker service.", diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 98ea21a3..20c55974 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -16753,6 +16753,56 @@ paths: summary: Verify Evidence signature by ID tags: - Evidence + /evidence/badge.svg: + get: + description: |- + Returns an SVG badge for the latest evidence matching ALL supplied query parameters as label name/value pairs, e.g. ?provider=aws&environment=production. + Aggregates the latest evidence from each matching stream, so a failure in another stream can make the badge red (not-satisfied). + Requires 1 to CCF_EVIDENCE_BADGE_MAX_PARAMS labels (default 3). Each key must occur exactly once (keys must be unique case-insensitively) with a non-empty value. No labels are implicit. Names and values are limited to 255 characters without surrounding whitespace or control characters; internal spaces are allowed. + Labels can be sent in two equivalent forms, which may be mixed: one ?= query parameter per label, or the repeatable label parameter as label=: (split at the first colon). Swagger UI exposes only the label parameter; add one item per label pair. + The label key is reserved for the second form, so a label literally named "label" must be sent as label=label:. + Authentication is conditional. When public evidence reads are enabled (CCF_STRICT_DISABLE_PUBLIC_AGENT_ENDPOINTS is false, the default) and the authorization policy permits the read, no credentials are required. Otherwise send an OAuth2 bearer token (Authorization: Bearer ) or the ccf_auth_token session cookie for a user or agent allowed to read evidence. A supplied Authorization header must always be valid. + parameters: + - collectionFormat: multi + description: Label pair as name:value, e.g. provider:aws. Repeat for each + label. + in: query + items: + type: string + name: label + type: array + produces: + - image/svg+xml + - application/json + responses: + "200": + description: SVG compliance badge + schema: + type: string + "400": + description: Missing, duplicate, too many or invalid label parameters + schema: + $ref: '#/definitions/api.Error' + "401": + description: Credentials are required (public evidence reads disabled) or + the supplied token is invalid + schema: + $ref: '#/definitions/api.Error' + "403": + description: The authorization policy denies reading evidence + schema: + $ref: '#/definitions/api.Error' + "429": + description: Too many badge requests in progress + schema: + $ref: '#/definitions/api.Error' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/api.Error' + summary: Get an SVG compliance status badge + tags: + - Evidence /evidence/batches: post: consumes: diff --git a/internal/api/handler/api.go b/internal/api/handler/api.go index 1e98f9fa..5b8af50d 100644 --- a/internal/api/handler/api.go +++ b/internal/api/handler/api.go @@ -118,6 +118,9 @@ func RegisterHandlers(server *api.Server, logger *zap.SugaredLogger, db *gorm.DB artifactService := artifactsvc.NewService(db) evidenceHandler := NewEvidenceHandler(logger, services.EvidenceService, riskService).WithArtifactService(artifactService) + if config.EvidenceBadgeMaxParams != 0 { + evidenceHandler.badgeMaxParams = config.EvidenceBadgeMaxParams + } evidenceGuard := pep.For(authz.ResourceEvidence) // Batches are stored in the background, signed as their submitter, and read back only diff --git a/internal/api/handler/evidence.go b/internal/api/handler/evidence.go index 950e80cc..73c0e25d 100644 --- a/internal/api/handler/evidence.go +++ b/internal/api/handler/evidence.go @@ -14,6 +14,7 @@ import ( "github.com/compliance-framework/api/internal/api/authcontext" "github.com/compliance-framework/api/internal/artifact" "github.com/compliance-framework/api/internal/authz" + "github.com/compliance-framework/api/internal/config" "github.com/compliance-framework/api/internal/converters/labelfilter" svc "github.com/compliance-framework/api/internal/service" "github.com/compliance-framework/api/internal/service/relational" @@ -39,6 +40,8 @@ type EvidenceHandler struct { batchMaxItems int batchPDP authz.PDP sspScope *sspscope.Service + badgeMaxParams int + badgeSlots chan struct{} } // WithArtifactService lets evidence refer to stored policy artifacts. Without it, evidence @@ -48,18 +51,23 @@ func (h *EvidenceHandler) WithArtifactService(service *artifactsvc.Service) *Evi return h } +// NewEvidenceHandler constructs evidence endpoints with default pagination and badge limits. func NewEvidenceHandler(sugar *zap.SugaredLogger, evidenceService *evidencesvc.EvidenceService, riskService *riskrel.RiskService) *EvidenceHandler { return &EvidenceHandler{ evidenceService: evidenceService, riskService: riskService, pagination: svc.NewPaginationConfig(), sugar: sugar, + badgeMaxParams: config.DefaultEvidenceBadgeMaxParams, + badgeSlots: make(chan struct{}, complianceBadgeMaxConcurrent), } } +// Register mounts evidence creation and read routes on the supplied group. func (h *EvidenceHandler) Register(api *echo.Group) { api.POST("", h.Create) api.GET("/config", h.Config) + api.GET("/badge.svg", h.ComplianceBadge) api.GET("/:id", h.Get) api.GET("/history/:id", h.History) api.GET("/latest/:id", h.Latest) @@ -81,6 +89,7 @@ func (h *EvidenceHandler) RegisterCreate(api *echo.Group, middlewares ...echo.Mi // POST /status-over-time are queries, not mutations — hence read. func (h *EvidenceHandler) RegisterReadRoutes(api *echo.Group, middlewares ...echo.MiddlewareFunc) { api.GET("/config", h.Config, middlewares...) + api.GET("/badge.svg", h.ComplianceBadge, middlewares...) api.GET("/:id", h.Get, middlewares...) api.GET("/history/:id", h.History, middlewares...) api.GET("/latest/:id", h.Latest, middlewares...) @@ -1203,7 +1212,7 @@ func (h *EvidenceHandler) statusOverTime(ctx *echo.Context, restrict scopeRestri t := now.Add(-d).UTC() endBefore = &t } - rows, err := h.evidenceService.GetStatusCountsAtPoint(*filter, endBefore) + rows, err := h.evidenceService.GetStatusCountsAtPoint(ctx.Request().Context(), *filter, endBefore) if err != nil { ch <- result{idx: i, err: err} return diff --git a/internal/api/handler/evidence_badge.go b/internal/api/handler/evidence_badge.go new file mode 100644 index 00000000..23983b74 --- /dev/null +++ b/internal/api/handler/evidence_badge.go @@ -0,0 +1,186 @@ +package handler + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "slices" + "strings" + "unicode" + "unicode/utf8" + + "github.com/compliance-framework/api/internal/api" + "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/labstack/echo/v5" +) + +const complianceBadgeMaxParamLength = 255 + +const complianceBadgeMaxConcurrent = 4 + +// ComplianceBadge godoc +// +// @Summary Get an SVG compliance status badge +// @Description Returns an SVG badge for the latest evidence matching ALL supplied query parameters as label name/value pairs, e.g. ?provider=aws&environment=production. +// @Description Aggregates the latest evidence from each matching stream, so a failure in another stream can make the badge red (not-satisfied). +// @Description Requires 1 to CCF_EVIDENCE_BADGE_MAX_PARAMS labels (default 3). Each key must occur exactly once (keys must be unique case-insensitively) with a non-empty value. No labels are implicit. Names and values are limited to 255 characters without surrounding whitespace or control characters; internal spaces are allowed. +// @Description Labels can be sent in two equivalent forms, which may be mixed: one ?= query parameter per label, or the repeatable label parameter as label=: (split at the first colon). Swagger UI exposes only the label parameter; add one item per label pair. +// @Description The label key is reserved for the second form, so a label literally named "label" must be sent as label=label:. +// @Description Authentication is conditional. When public evidence reads are enabled (CCF_STRICT_DISABLE_PUBLIC_AGENT_ENDPOINTS is false, the default) and the authorization policy permits the read, no credentials are required. Otherwise send an OAuth2 bearer token (Authorization: Bearer ) or the ccf_auth_token session cookie for a user or agent allowed to read evidence. A supplied Authorization header must always be valid. +// @Tags Evidence +// @Produce image/svg+xml +// @Produce application/json +// @Param label query []string false "Label pair as name:value, e.g. provider:aws. Repeat for each label." collectionFormat(multi) +// @Success 200 {string} string "SVG compliance badge" +// @Failure 400 {object} api.Error "Missing, duplicate, too many or invalid label parameters" +// @Failure 401 {object} api.Error "Credentials are required (public evidence reads disabled) or the supplied token is invalid" +// @Failure 403 {object} api.Error "The authorization policy denies reading evidence" +// @Failure 429 {object} api.Error "Too many badge requests in progress" +// @Failure 500 {object} api.Error +// @Router /evidence/badge.svg [get] +func (h *EvidenceHandler) ComplianceBadge(ctx *echo.Context) error { + select { + case h.badgeSlots <- struct{}{}: + defer func() { <-h.badgeSlots }() + default: + return ctx.JSON(http.StatusTooManyRequests, api.NewError(errors.New("too many compliance badge requests in progress, retry shortly"))) + } + + if countComplianceBadgeQueryComponents(ctx.Request().URL.RawQuery) > h.badgeMaxParams { + return ctx.JSON(http.StatusBadRequest, api.NewError(fmt.Errorf("provide between 1 and %d label query parameters", h.badgeMaxParams))) + } + + params, err := url.ParseQuery(ctx.Request().URL.RawQuery) + if err != nil { + return ctx.JSON(http.StatusBadRequest, api.NewError(fmt.Errorf("invalid label query: %w", err))) + } + filter, err := parseComplianceBadgeParams(params, h.badgeMaxParams) + if err != nil { + return ctx.JSON(http.StatusBadRequest, api.NewError(err)) + } + + rows, err := h.evidenceService.GetStatusCountsAtPoint(ctx.Request().Context(), filter, nil) + if err != nil { + h.sugar.Errorw("Failed to get compliance badge status", "error", err) + return ctx.JSON(http.StatusInternalServerError, api.InternalServerError()) + } + + ctx.Response().Header().Set("Cache-Control", "no-store") + return ctx.Blob(http.StatusOK, "image/svg+xml; charset=utf-8", []byte(complianceBadgeSVG(complianceBadgeStatus(rows)))) +} + +// complianceBadgeLabelParam is the reserved query key for repeatable name:value label pairs, +// which lets clients that only support fixed parameter names (such as Swagger UI) send labels. +const complianceBadgeLabelParam = "label" + +type complianceBadgeLabel struct { + name string + value string +} + +// complianceBadgeLabels flattens ?name=value pairs and repeatable ?label=name:value pairs. +func complianceBadgeLabels(params url.Values) ([]complianceBadgeLabel, error) { + labels := make([]complianceBadgeLabel, 0, len(params)) + for name, values := range params { + if name != complianceBadgeLabelParam { + if len(values) != 1 { + return nil, fmt.Errorf("label %q must occur exactly once", name) + } + labels = append(labels, complianceBadgeLabel{name: name, value: values[0]}) + continue + } + for _, pair := range values { + labelName, labelValue, ok := strings.Cut(pair, ":") + if !ok { + return nil, fmt.Errorf("%s parameter %q must use the form name:value", complianceBadgeLabelParam, pair) + } + labels = append(labels, complianceBadgeLabel{name: labelName, value: labelValue}) + } + } + slices.SortFunc(labels, func(a, b complianceBadgeLabel) int { return strings.Compare(a.name, b.name) }) + return labels, nil +} + +// parseComplianceBadgeParams validates badge labels and builds their AND filter. +func parseComplianceBadgeParams(params url.Values, maxParams int) (labelfilter.Filter, error) { + labels, err := complianceBadgeLabels(params) + if err != nil { + return labelfilter.Filter{}, err + } + if len(labels) == 0 || len(labels) > maxParams { + return labelfilter.Filter{}, fmt.Errorf("provide between 1 and %d label query parameters", maxParams) + } + + scopes := make([]labelfilter.Scope, 0, len(labels)) + seen := make(map[string]bool, len(labels)) + for _, label := range labels { + name := label.name + normalized := strings.ToLower(name) + turkishNormalized := strings.ToLowerSpecial(unicode.TurkishCase, name) + if seen[normalized] || seen[turkishNormalized] { + return labelfilter.Filter{}, fmt.Errorf("label %q must occur exactly once", name) + } + seen[normalized] = true + seen[turkishNormalized] = true + for _, text := range []string{name, label.value} { + if text == "" || strings.TrimSpace(text) != text { + return labelfilter.Filter{}, fmt.Errorf("label %q must have a non-empty name and value without surrounding whitespace", name) + } + if !utf8.ValidString(text) || utf8.RuneCountInString(text) > complianceBadgeMaxParamLength { + return labelfilter.Filter{}, fmt.Errorf("label %q names and values must be valid UTF-8 of at most %d characters", name, complianceBadgeMaxParamLength) + } + if strings.ContainsFunc(text, unicode.IsControl) { + return labelfilter.Filter{}, fmt.Errorf("label %q must not contain control characters", name) + } + } + scopes = append(scopes, labelfilter.Scope{ + Condition: &labelfilter.Condition{Label: name, Operator: "=", Value: label.value}, + }) + } + return labelfilter.Filter{ + Scope: &labelfilter.Scope{ + Query: &labelfilter.Query{ + Operator: "and", + Scopes: scopes, + }, + }, + }, nil +} + +// countComplianceBadgeQueryComponents counts non-empty raw query components without allocating. +func countComplianceBadgeQueryComponents(rawQuery string) int { + count := 0 + for i := 0; i < len(rawQuery); i++ { + if rawQuery[i] != '&' && (i == 0 || rawQuery[i-1] == '&') { + count++ + } + } + return count +} + +// complianceBadgeStatus collapses evidence status counts into one badge status. +func complianceBadgeStatus(rows []evidencesvc.StatusCount) string { + statusCounts := make([]relational.StatusCount, len(rows)) + for i, row := range rows { + statusCounts[i] = relational.StatusCount{Count: row.Count, Status: row.Status} + } + return relational.CollapseEvidenceStatus(statusCounts) +} + +// complianceBadgeSVG renders the compliance status as an SVG badge. +func complianceBadgeSVG(status string) string { + color := "#9f9f9f" + switch status { + case relational.EvidenceStatusSatisfied: + color = "#4c1" + case relational.EvidenceStatusNotSatisfied: + color = "#e05d44" + default: + status = "unknown" + } + + return fmt.Sprintf(`Compliance status: %scompliance%s`, status, status, color, status) +} diff --git a/internal/api/handler/evidence_badge_integration_test.go b/internal/api/handler/evidence_badge_integration_test.go new file mode 100644 index 00000000..325ad932 --- /dev/null +++ b/internal/api/handler/evidence_badge_integration_test.go @@ -0,0 +1,82 @@ +//go:build integration + +package handler + +import ( + "encoding/xml" + "net/http" + "net/http/httptest" + "time" + + "github.com/compliance-framework/api/internal/api" + "github.com/compliance-framework/api/internal/service/relational" + oscal "github.com/defenseunicorns/go-oscal/src/types/oscal-1-1-3" + "github.com/google/uuid" + "gorm.io/datatypes" +) + +// TestComplianceBadge checks badge rendering, stream aggregation, and configured label limits. +func (suite *EvidenceApiIntegrationSuite) TestComplianceBadge() { + suite.Require().NoError(suite.Migrator.Refresh()) + suite.Config.StrictDisablePublicAgentEndpoints = false + suite.Config.EvidenceBadgeMaxParams = 4 + now := time.Now().Add(-time.Hour) + labels := []relational.Labels{ + {Name: "provider", Value: "azure"}, + {Name: "team", Value: "platform team"}, + {Name: "region", Value: "eu"}, + {Name: "_policy", Value: "hardening"}, + } + create := func(stream uuid.UUID, state string, end time.Time, evidenceLabels []relational.Labels) { + evidence := relational.Evidence{ + UUID: stream, Title: "Badge check", Start: end.Add(-time.Minute), End: end, + Status: datatypes.NewJSONType(oscal.ObjectiveStatus{State: state}), + Labels: evidenceLabels, + } + suite.Require().NoError(suite.DB.Create(&evidence).Error) + } + stream := uuid.New() + create(stream, relational.EvidenceStatusNotSatisfied, now, labels) + create(stream, relational.EvidenceStatusSatisfied, now.Add(time.Minute), labels) + create(uuid.New(), relational.EvidenceStatusNotSatisfied, now, []relational.Labels{ + {Name: "provider", Value: "azure"}, {Name: "team", Value: "other"}, + }) + + server := suite.setupServer() + request := func(server *api.Server, query string, code int, status string) { + rec := httptest.NewRecorder() + server.E().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/evidence/badge.svg?"+query, nil)) + suite.Require().Equal(code, rec.Code, rec.Body.String()) + if code == http.StatusOK { + suite.Equal("image/svg+xml; charset=utf-8", rec.Header().Get("Content-Type")) + suite.Equal("no-store", rec.Header().Get("Cache-Control")) + var svg struct{ XMLName xml.Name } + suite.Require().NoError(xml.Unmarshal(rec.Body.Bytes(), &svg)) + suite.Equal("svg", svg.XMLName.Local) + suite.Contains(rec.Body.String(), `aria-label="Compliance status: `+status+`"`) + } + } + query := "provider=azure&team=platform+team®ion=eu&_policy=hardening" + request(server, query, http.StatusOK, "satisfied") + request(server, "provider=missing", http.StatusOK, "unknown") + request(server, "provider=azure&team=other", http.StatusOK, "not-satisfied") + // Swagger UI sends the repeatable label=name:value form, alone or mixed with plain labels. + request(server, "label=provider%3Aazure&label=team%3Aother", http.StatusOK, "not-satisfied") + request(server, "label=provider:azure&team=other", http.StatusOK, "not-satisfied") + request(server, "label=provider:missing", http.StatusOK, "unknown") + request(server, "label=provider", http.StatusBadRequest, "") + request(server, "label=provider:azure&provider=azure", http.StatusBadRequest, "") + create(uuid.New(), relational.EvidenceStatusNotSatisfied, now, labels) + request(server, query, http.StatusOK, "not-satisfied") + request(server, "provider=azure&provider=azure", http.StatusBadRequest, "") + request(server, "", http.StatusBadRequest, "") + + suite.Config.EvidenceBadgeMaxParams = 0 + server = suite.setupServer() + request(server, "provider=azure&team=platform+team®ion=eu", http.StatusOK, "not-satisfied") + request(server, query, http.StatusBadRequest, "") + suite.Config.EvidenceBadgeMaxParams = 1 + server = suite.setupServer() + request(server, "provider=azure", http.StatusOK, "not-satisfied") + request(server, "provider=azure&team=other", http.StatusBadRequest, "") +} diff --git a/internal/api/handler/evidence_badge_test.go b/internal/api/handler/evidence_badge_test.go new file mode 100644 index 00000000..81bb0afa --- /dev/null +++ b/internal/api/handler/evidence_badge_test.go @@ -0,0 +1,263 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "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/labstack/echo/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +// TestParseComplianceBadgeParams checks label validation and filter construction. +func TestParseComplianceBadgeParams(t *testing.T) { + tests := []struct { + name string + params url.Values + maxParams int + wantErr bool + }{ + {name: "one arbitrary label", params: url.Values{"provider": {"aws"}}, maxParams: 3}, + {name: "three labels at limit", params: url.Values{"source": {"github"}, "repo": {"any-format"}, "branch": {"release/2026"}}, maxParams: 3}, + {name: "internal spaces", params: url.Values{"team": {"platform team"}}, maxParams: 3}, + {name: "Unicode boundary", params: url.Values{"team": {strings.Repeat("é", complianceBadgeMaxParamLength)}}, maxParams: 3}, + {name: "custom larger limit", params: url.Values{"a": {"1"}, "b": {"2"}, "c": {"3"}, "d": {"4"}}, maxParams: 4}, + {name: "no labels", maxParams: 3, wantErr: true}, + {name: "over default limit", params: url.Values{"a": {"1"}, "b": {"2"}, "c": {"3"}, "d": {"4"}}, maxParams: 3, wantErr: true}, + {name: "over custom limit", params: url.Values{"a": {"1"}, "b": {"2"}}, maxParams: 1, wantErr: true}, + {name: "repeated key", params: url.Values{"team": {"a", "b"}}, maxParams: 3, wantErr: true}, + {name: "case-insensitive repeated key", params: url.Values{"team": {"a"}, "Team": {"b"}}, maxParams: 3, wantErr: true}, + {name: "ASCII I repeated key", params: url.Values{"I": {"a"}, "i": {"b"}}, maxParams: 3, wantErr: true}, + {name: "Turkish case-insensitive repeated key", params: url.Values{"I": {"a"}, "ı": {"b"}}, maxParams: 3, wantErr: true}, + {name: "Turkish dotted I repeated key", params: url.Values{"İ": {"a"}, "i": {"b"}}, maxParams: 3, wantErr: true}, + {name: "empty name", params: url.Values{"": {"a"}}, maxParams: 3, wantErr: true}, + {name: "empty value", params: url.Values{"team": {""}}, maxParams: 3, wantErr: true}, + {name: "missing value", params: url.Values{"team": nil}, maxParams: 3, wantErr: true}, + {name: "surrounding whitespace", params: url.Values{"team": {" a "}}, maxParams: 3, wantErr: true}, + {name: "name whitespace", params: url.Values{" team": {"a"}}, maxParams: 3, wantErr: true}, + {name: "control character", params: url.Values{"team": {"a\nb"}}, maxParams: 3, wantErr: true}, + {name: "name control character", params: url.Values{"te\x00am": {"a"}}, maxParams: 3, wantErr: true}, + {name: "oversized value", params: url.Values{"team": {strings.Repeat("a", complianceBadgeMaxParamLength+1)}}, maxParams: 3, wantErr: true}, + {name: "oversized name", params: url.Values{strings.Repeat("a", complianceBadgeMaxParamLength+1): {"a"}}, maxParams: 3, wantErr: true}, + {name: "invalid UTF-8", params: url.Values{"team": {"\xff"}}, maxParams: 3, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + filter, err := parseComplianceBadgeParams(tt.params, tt.maxParams) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + require.NotNil(t, filter.Scope.Query) + assert.Equal(t, "and", filter.Scope.Query.Operator) + require.Len(t, filter.Scope.Scopes, len(tt.params)) + for _, scope := range filter.Scope.Scopes { + require.NotNil(t, scope.Condition) + assert.Equal(t, "=", scope.Condition.Operator) + assert.Equal(t, tt.params.Get(scope.Label), scope.Value) + } + }) + } +} + +// TestComplianceBadgeFilter verifies labels are combined in a deterministic AND filter. +func TestComplianceBadgeFilter(t *testing.T) { + filter, err := parseComplianceBadgeParams(url.Values{"provider": {"aws"}, "environment": {"production"}, "team": {"platform team"}}, 3) + require.NoError(t, err) + + require.NotNil(t, filter.Scope) + require.NotNil(t, filter.Scope.Query) + assert.Equal(t, "and", filter.Scope.Query.Operator) + require.Len(t, filter.Scope.Scopes, 3) + assert.Equal(t, &labelfilter.Condition{Label: "environment", Operator: "=", Value: "production"}, filter.Scope.Query.Scopes[0].Condition) + assert.Equal(t, &labelfilter.Condition{Label: "provider", Operator: "=", Value: "aws"}, filter.Scope.Query.Scopes[1].Condition) + assert.Equal(t, &labelfilter.Condition{Label: "team", Operator: "=", Value: "platform team"}, filter.Scope.Query.Scopes[2].Condition) +} + +// TestComplianceBadgeLabelParam checks the repeatable label=name:value form used by Swagger UI. +func TestComplianceBadgeLabelParam(t *testing.T) { + tests := []struct { + name string + params url.Values + maxParams int + want []labelfilter.Condition + wantErr bool + }{ + {name: "single pair", params: url.Values{"label": {"provider:aws"}}, maxParams: 3, + want: []labelfilter.Condition{{Label: "provider", Operator: "=", Value: "aws"}}}, + {name: "repeated pairs sorted", params: url.Values{"label": {"provider:aws", "environment:production"}}, maxParams: 3, + want: []labelfilter.Condition{{Label: "environment", Operator: "=", Value: "production"}, {Label: "provider", Operator: "=", Value: "aws"}}}, + {name: "mixed with plain labels", params: url.Values{"label": {"provider:aws"}, "team": {"platform team"}}, maxParams: 3, + want: []labelfilter.Condition{{Label: "provider", Operator: "=", Value: "aws"}, {Label: "team", Operator: "=", Value: "platform team"}}}, + {name: "splits at first colon", params: url.Values{"label": {"arn:aws:iam::123"}}, maxParams: 3, + want: []labelfilter.Condition{{Label: "arn", Operator: "=", Value: "aws:iam::123"}}}, + {name: "label named label", params: url.Values{"label": {"label:x"}}, maxParams: 3, + want: []labelfilter.Condition{{Label: "label", Operator: "=", Value: "x"}}}, + {name: "missing colon", params: url.Values{"label": {"provider"}}, maxParams: 3, wantErr: true}, + {name: "empty pair", params: url.Values{"label": {""}}, maxParams: 3, wantErr: true}, + {name: "empty name", params: url.Values{"label": {":aws"}}, maxParams: 3, wantErr: true}, + {name: "empty value", params: url.Values{"label": {"provider:"}}, maxParams: 3, wantErr: true}, + {name: "surrounding whitespace", params: url.Values{"label": {"provider: aws"}}, maxParams: 3, wantErr: true}, + {name: "control character", params: url.Values{"label": {"provider:a\nb"}}, maxParams: 3, wantErr: true}, + {name: "duplicate within label param", params: url.Values{"label": {"team:a", "Team:b"}}, maxParams: 3, wantErr: true}, + {name: "duplicate across forms", params: url.Values{"label": {"team:a"}, "team": {"b"}}, maxParams: 3, wantErr: true}, + {name: "over limit across forms", params: url.Values{"label": {"a:1", "b:2"}, "c": {"3"}, "d": {"4"}}, maxParams: 3, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + filter, err := parseComplianceBadgeParams(tt.params, tt.maxParams) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + require.NotNil(t, filter.Scope.Query) + got := make([]labelfilter.Condition, 0, len(filter.Scope.Scopes)) + for _, scope := range filter.Scope.Scopes { + require.NotNil(t, scope.Condition) + got = append(got, *scope.Condition) + } + assert.Equal(t, tt.want, got) + }) + } +} + +// TestComplianceBadgeInvalidQueries verifies malformed label queries return HTTP 400. +func TestComplianceBadgeInvalidQueries(t *testing.T) { + h := NewEvidenceHandler(zap.NewNop().Sugar(), nil, nil) + require.Equal(t, 3, h.badgeMaxParams) + server := echo.New() + server.GET("/badge.svg", h.ComplianceBadge) + for _, query := range []string{"", "team=a&team=b", "I=a&i=b", "I=a&%C4%B1=b", "%C4%B0=a&i=b", "a=1&b=2&c=3&d=4", "team=", "team=%ZZ", "team=a;ignored=b", "label=provider", "label=a:1&label=b:2&label=c:3&label=d:4", "label=team:a&team=b"} { + t.Run(query, func(t *testing.T) { + rec := httptest.NewRecorder() + server.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/badge.svg?"+query, nil)) + assert.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String()) + assert.Contains(t, rec.Body.String(), `"errors"`) + assert.Empty(t, h.badgeSlots, "invalid queries must release their badge slot") + }) + } +} + +// TestComplianceBadgeReturns429WhenBusy checks the badge concurrency limit. +func TestComplianceBadgeReturns429WhenBusy(t *testing.T) { + h := NewEvidenceHandler(zap.NewNop().Sugar(), nil, nil) + for range cap(h.badgeSlots) { + h.badgeSlots <- struct{}{} + } + + for _, tt := range []struct { + name string + query string + }{ + {name: "valid", query: "team=platform"}, + {name: "malformed", query: "team=%ZZ"}, + {name: "over limit", query: "a=1&b=2&c=3&d=4"}, + {name: "separator run", query: strings.Repeat("&", 900_000)}, + } { + t.Run(tt.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/badge.svg", nil) + req.URL.RawQuery = tt.query + rec := httptest.NewRecorder() + err := h.ComplianceBadge(echo.New().NewContext(req, rec)) + + require.NoError(t, err) + assert.Equal(t, http.StatusTooManyRequests, rec.Code) + assert.Contains(t, rec.Body.String(), "too many compliance badge requests") + assert.Len(t, h.badgeSlots, cap(h.badgeSlots)) + }) + } +} + +// TestCountComplianceBadgeQueryComponents checks component counts and zero allocations. +func TestCountComplianceBadgeQueryComponents(t *testing.T) { + for _, tt := range []struct { + name string + query string + want int + }{ + {name: "empty"}, + {name: "separators only", query: "&&&"}, + {name: "one label", query: "team=platform", want: 1}, + {name: "empty components", query: "&a=1&&b=2&", want: 2}, + {name: "encoded separator", query: "team=a%26b", want: 1}, + {name: "duplicate label", query: "team=a&team=b", want: 2}, + {name: "missing value", query: "team", want: 1}, + {name: "separator run", query: strings.Repeat("&", 900_000)}, + {name: "labels around separator run", query: "a=1" + strings.Repeat("&", 900_000) + "b=2", want: 2}, + } { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, countComplianceBadgeQueryComponents(tt.query)) + var got int + allocations := testing.AllocsPerRun(10, func() { + got = countComplianceBadgeQueryComponents(tt.query) + }) + assert.Equal(t, tt.want, got) + assert.Zero(t, allocations) + }) + } +} + +// TestComplianceBadgeSVG checks status colors and safe rendering of unknown states. +func TestComplianceBadgeSVG(t *testing.T) { + tests := []struct { + status string + color string + }{ + {status: relational.EvidenceStatusSatisfied, color: "#4c1"}, + {status: relational.EvidenceStatusNotSatisfied, color: "#e05d44"}, + {status: "unknown", color: "#9f9f9f"}, + {status: "unrecognized", color: "#9f9f9f"}, + } + + for _, tt := range tests { + t.Run(tt.status, func(t *testing.T) { + svg := complianceBadgeSVG(tt.status) + assert.Contains(t, svg, `xmlns="http://www.w3.org/2000/svg"`) + assert.Contains(t, svg, `fill="`+tt.color+`"`) + assert.Contains(t, svg, "Compliance status:") + assert.Contains(t, svg, `>compliance`) + }) + } + + assert.Contains(t, complianceBadgeSVG("unknown"), `aria-label="Compliance status: unknown"`) + assert.NotContains(t, complianceBadgeSVG("unrecognized"), "unrecognized", "unknown input must not be reflected into SVG markup") +} + +// TestComplianceBadgeStatus checks precedence when combining evidence stream statuses. +func TestComplianceBadgeStatus(t *testing.T) { + tests := []struct { + name string + rows []evidencesvc.StatusCount + want string + }{ + {name: "not satisfied takes precedence", rows: []evidencesvc.StatusCount{ + {Count: 1, Status: relational.EvidenceStatusSatisfied}, + {Count: 1, Status: relational.EvidenceStatusNotSatisfied}, + }, want: relational.EvidenceStatusNotSatisfied}, + {name: "satisfied when no failures", rows: []evidencesvc.StatusCount{ + {Count: 1, Status: relational.EvidenceStatusSatisfied}, + {Count: 1, Status: "unknown"}, + }, want: relational.EvidenceStatusSatisfied}, + {name: "unknown when no known positive counts", rows: []evidencesvc.StatusCount{ + {Count: 0, Status: relational.EvidenceStatusNotSatisfied}, + }, want: "unknown"}, + {name: "unknown when there are no counts", want: "unknown"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, complianceBadgeStatus(tt.rows)) + }) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index f2de8e96..f309c5e5 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -36,6 +36,7 @@ type Config struct { Slack *SlackConfig Worker *WorkerConfig EvidenceDefaultExpiryMonths int // Default expiration in months for evidence without explicit expiry + EvidenceBadgeMaxParams int // Maximum label query parameters on the compliance badge endpoint DigestEnabled bool // Enable or disable the digest scheduler DigestSchedule string // Cron schedule for digest emails Workflow *WorkflowConfig @@ -56,6 +57,7 @@ type Config struct { SSPTemplate *SSPTemplateConfig } +// NewConfig loads application settings and terminates on invalid required configuration. func NewConfig(logger *zap.SugaredLogger) *Config { if !viper.IsSet("db_driver") { logger.Fatal( @@ -193,6 +195,11 @@ func NewConfig(logger *zap.SugaredLogger) *Config { logger.Fatalw("Invalid evidence batch config", "error", err) } + evidenceBadgeMaxParams, err := LoadEvidenceBadgeMaxParamsFromViper(viper.GetViper()) + if err != nil { + logger.Fatalw("Invalid evidence badge config", "error", err) + } + lineageConfig, err := LoadLineageConfig() if err != nil { logger.Fatalw("Invalid lineage config", "error", err) @@ -292,6 +299,7 @@ func NewConfig(logger *zap.SugaredLogger) *Config { Slack: slackConfig, Worker: workerConfig, EvidenceDefaultExpiryMonths: evidenceDefaultExpiryMonths, + EvidenceBadgeMaxParams: evidenceBadgeMaxParams, EvidenceSubjects: evidenceSubjectConfig, EvidenceBatch: evidenceBatchConfig, SSPScope: LoadSSPScopeConfig(), diff --git a/internal/config/evidence.go b/internal/config/evidence.go index 711127ac..b34f5e4d 100644 --- a/internal/config/evidence.go +++ b/internal/config/evidence.go @@ -2,12 +2,34 @@ package config import ( "fmt" + "os" + "strconv" "strings" "time" "github.com/spf13/viper" ) +// DefaultEvidenceBadgeMaxParams is the default number of label parameters accepted by a badge request. +const DefaultEvidenceBadgeMaxParams = 3 + +// LoadEvidenceBadgeMaxParamsFromViper reads the maximum number of compliance badge labels, +// defaulting to three only when absent and rejecting empty or non-positive settings. +func LoadEvidenceBadgeMaxParamsFromViper(v *viper.Viper) (int, error) { + if raw, present := os.LookupEnv("CCF_EVIDENCE_BADGE_MAX_PARAMS"); present && raw == "" { + return 0, fmt.Errorf("CCF_EVIDENCE_BADGE_MAX_PARAMS must be a positive integer, got %q", raw) + } + if !v.IsSet("evidence_badge_max_params") { + return DefaultEvidenceBadgeMaxParams, nil + } + raw := strings.TrimSpace(v.GetString("evidence_badge_max_params")) + value, err := strconv.Atoi(raw) + if err != nil || value <= 0 { + return 0, fmt.Errorf("CCF_EVIDENCE_BADGE_MAX_PARAMS must be a positive integer, got %q", raw) + } + return value, nil +} + // EvidenceRequireSubjectMode is how agent evidence without a derived subject is handled // (CCF_EVIDENCE_REQUIRE_SUBJECT). type EvidenceRequireSubjectMode string diff --git a/internal/config/evidence_test.go b/internal/config/evidence_test.go index c69e5763..36bcbd85 100644 --- a/internal/config/evidence_test.go +++ b/internal/config/evidence_test.go @@ -1,6 +1,7 @@ package config import ( + "os" "testing" "time" @@ -8,6 +9,63 @@ import ( "github.com/stretchr/testify/require" ) +// TestLoadEvidenceBadgeMaxParams checks defaults, configured limits, and invalid settings. +func TestLoadEvidenceBadgeMaxParams(t *testing.T) { + t.Setenv("CCF_EVIDENCE_BADGE_MAX_PARAMS", "") + require.NoError(t, os.Unsetenv("CCF_EVIDENCE_BADGE_MAX_PARAMS")) + + for _, tt := range []struct { + name string + value string + want int + wantErr bool + }{ + {name: "default", want: 3}, + {name: "custom", value: "5", want: 5}, + {name: "one", value: "1", want: 1}, + {name: "zero", value: "0", wantErr: true}, + {name: "negative", value: "-1", wantErr: true}, + {name: "fraction", value: "1.5", wantErr: true}, + {name: "not an integer", value: "unlimited", wantErr: true}, + {name: "empty", wantErr: true}, + {name: "whitespace", value: " ", wantErr: true}, + } { + t.Run(tt.name, func(t *testing.T) { + v := viper.New() + if tt.name != "default" { + v.Set("evidence_badge_max_params", tt.value) + } + value, err := LoadEvidenceBadgeMaxParamsFromViper(v) + if tt.wantErr { + require.ErrorContains(t, err, "CCF_EVIDENCE_BADGE_MAX_PARAMS") + return + } + require.NoError(t, err) + require.Equal(t, tt.want, value) + }) + } + t.Run("environment override", func(t *testing.T) { + t.Setenv("CCF_EVIDENCE_BADGE_MAX_PARAMS", "7") + v := viper.New() + v.SetEnvPrefix("CCF") + v.AutomaticEnv() + value, err := LoadEvidenceBadgeMaxParamsFromViper(v) + require.NoError(t, err) + require.Equal(t, 7, value) + }) + t.Run("empty environment override", func(t *testing.T) { + t.Setenv("CCF_EVIDENCE_BADGE_MAX_PARAMS", "") + v := viper.New() + v.SetEnvPrefix("CCF") + v.MustBindEnv("evidence_badge_max_params") + v.SetDefault("evidence_badge_max_params", DefaultEvidenceBadgeMaxParams) + + _, err := LoadEvidenceBadgeMaxParamsFromViper(v) + + require.ErrorContains(t, err, "CCF_EVIDENCE_BADGE_MAX_PARAMS") + }) +} + func TestLoadEvidenceSubjectConfigDefaults(t *testing.T) { cfg, err := LoadEvidenceSubjectConfigFromViper(viper.New()) diff --git a/internal/service/relational/evidence/latest_integration_test.go b/internal/service/relational/evidence/latest_integration_test.go index 6512a176..f3f4dd81 100644 --- a/internal/service/relational/evidence/latest_integration_test.go +++ b/internal/service/relational/evidence/latest_integration_test.go @@ -3,6 +3,7 @@ package evidence import ( + "context" "fmt" "sort" "testing" @@ -167,7 +168,7 @@ func (suite *LatestEvidenceIntegrationSuite) TestMatchesDistinctOn() { for i, filter := range filters { want, err := oldStatusCountsAtPoint(suite.DB, filter, at) suite.Require().NoError(err) - got, err := svc.GetStatusCountsAtPoint(filter, at) + got, err := svc.GetStatusCountsAtPoint(context.Background(), filter, at) suite.Require().NoError(err) suite.Equal(sortedStatusCounts(want), sortedStatusCounts(got), "filter %d at %s", i, label) } @@ -256,7 +257,7 @@ func (suite *LatestEvidenceIntegrationSuite) TestScale() { start = time.Now() var newCounts [][]StatusCount for _, at := range points { - rows, err := svc.GetStatusCountsAtPoint(filter, at) + rows, err := svc.GetStatusCountsAtPoint(context.Background(), filter, at) suite.Require().NoError(err) newCounts = append(newCounts, sortedStatusCounts(rows)) } diff --git a/internal/service/relational/evidence/search_integration_test.go b/internal/service/relational/evidence/search_integration_test.go index 05bacd10..edce06b6 100644 --- a/internal/service/relational/evidence/search_integration_test.go +++ b/internal/service/relational/evidence/search_integration_test.go @@ -3,6 +3,7 @@ package evidence import ( + "context" "testing" "time" @@ -226,7 +227,7 @@ func (suite *EvidenceServiceSearchIntegrationSuite) TestStatusCountsReturnEmptyS svc := NewEvidenceService(suite.DB, nil, nil, nil) - rows, err := svc.GetStatusCountsAtPoint(labelfilter.Filter{}, nil) + rows, err := svc.GetStatusCountsAtPoint(context.Background(), labelfilter.Filter{}, nil) suite.Require().NoError(err) suite.NotNil(rows) suite.Empty(rows) diff --git a/internal/service/relational/evidence/service.go b/internal/service/relational/evidence/service.go index 2af93969..f73231c4 100644 --- a/internal/service/relational/evidence/service.go +++ b/internal/service/relational/evidence/service.go @@ -510,14 +510,15 @@ func (s *EvidenceService) GetLatestForFilters(filters ...labelfilter.Filter) ([] return evidences, nil } -func (s *EvidenceService) GetStatusCountsAtPoint(filter labelfilter.Filter, endBefore *time.Time) ([]StatusCount, error) { +// GetStatusCountsAtPoint counts latest matching evidence streams by status before the optional cutoff. +func (s *EvidenceService) GetStatusCountsAtPoint(ctx context.Context, filter labelfilter.Filter, endBefore *time.Time) ([]StatusCount, error) { latestQuery := relational.LatestEvidenceQuery(s.db, relational.LatestEvidenceOptions{EndBefore: endBefore}) q, err := relational.GetEvidenceSearchByFilterQuery(latestQuery, s.db, filter) if err != nil { return nil, err } var rows []StatusCount - if err := q.Model(&relational.Evidence{}). + if err := q.WithContext(ctx).Model(&relational.Evidence{}). Select("count(DISTINCT uuid) as count, status->>'state' as status"). Group("status->>'state'"). Scan(&rows).Error; err != nil {