diff --git a/app/cli/cmd/attestation_push.go b/app/cli/cmd/attestation_push.go index f6785113e..2442fb74c 100644 --- a/app/cli/cmd/attestation_push.go +++ b/app/cli/cmd/attestation_push.go @@ -199,7 +199,8 @@ func hasGatingViolation(violations []*action.PolicyViolation) bool { } func validatePolicyEnforcement(status *action.AttestationStatusResult, bypassPolicyCheck bool) error { - // Block if any of the policies has been configured as a gate. Entries + // Block if any of the policies acts as a gate. Organization and contract + // enforcement are already resolved into each evaluation's gate. Entries // flagged Suppress are excluded from the gate count but remain in // eval.Violations for CAS storage and ingestion (audit trail preserved). for _, evaluations := range status.PolicyEvaluations { @@ -215,15 +216,5 @@ func validatePolicyEnforcement(status *action.AttestationStatusResult, bypassPol } } - // Do a final check in case the operator has configured the attestation - // to be blocked on any policy violation. - if status.MustBlockOnPolicyViolations { - if bypassPolicyCheck { - logger.Warn().Msg(exceptionBypassPolicyCheck) - return nil - } - - } - return nil } diff --git a/app/cli/cmd/attestation_push_test.go b/app/cli/cmd/attestation_push_test.go index 5e1b78147..50bc0c868 100644 --- a/app/cli/cmd/attestation_push_test.go +++ b/app/cli/cmd/attestation_push_test.go @@ -68,7 +68,9 @@ func TestValidatePolicyEnforcement(t *testing.T) { require.Equal(t, "cdx-fresh", gateErr.PolicyName) }) - t.Run("does not block when strategy is enforced and policy is explicitly not gated", func(t *testing.T) { + // Enforcement is resolved into each evaluation's gate when the policy is + // evaluated, so only the per-evaluation gate decides here. + t.Run("blocking depends on the evaluation gate, not on the strategy flag", func(t *testing.T) { status := &action.AttestationStatusResult{ PolicyEvaluations: map[string][]*action.PolicyEvaluation{ "materials": { diff --git a/app/cli/cmd/attestation_status.go b/app/cli/cmd/attestation_status.go index 7ac1dd5f1..57d6e0af9 100644 --- a/app/cli/cmd/attestation_status.go +++ b/app/cli/cmd/attestation_status.go @@ -124,13 +124,16 @@ func attestationStatusTableOutput(status *action.AttestationStatusResult, w io.W gt.AppendRow(table.Row{"Timestamp Authority", status.TimestampAuthority}) } - var blockingColor text.Color - var blockingText = action.PolicyViolationBlockingStrategyAdvisory + // Only show the strategy when it is enforced. Showing "ADVISORY" is misleading + // when individual policies are configured as gates. if status.MustBlockOnPolicyViolations { - blockingColor = text.FgHiYellow - blockingText = action.PolicyViolationBlockingStrategyEnforced + strategy := fmt.Sprintf("%s (by %s)", action.PolicyViolationBlockingStrategyEnforced, status.PolicyEnforcementSource) + gt.AppendRow(table.Row{"Policy violation strategy", text.FgHiYellow.Sprint(strategy)}) + } + + if len(status.IgnoredGateOptOuts) > 0 { + gt.AppendRow(table.Row{"Ignored gate: false", text.FgHiYellow.Sprintf("%s (enforcement cannot be relaxed)", strings.Join(status.IgnoredGateOptOuts, ", "))}) } - gt.AppendRow(table.Row{"Policy violation strategy", blockingColor.Sprint(blockingText)}) evs := status.PolicyEvaluations[chainloop.AttPolicyEvaluation] if len(evs) > 0 { diff --git a/app/cli/cmd/attestation_status_test.go b/app/cli/cmd/attestation_status_test.go index 4f119fff5..d05603afc 100644 --- a/app/cli/cmd/attestation_status_test.go +++ b/app/cli/cmd/attestation_status_test.go @@ -1,4 +1,4 @@ -// Copyright 2024 The Chainloop Authors. +// Copyright 2024-2026 The Chainloop Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,12 +15,74 @@ package cmd import ( + "bytes" "testing" + "time" "github.com/chainloop-dev/chainloop/app/cli/pkg/action" + attestationv1 "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +func TestAttestationStatusPolicyEnforcementRows(t *testing.T) { + const ( + strategyRowLabel = "Policy violation strategy" + ignoredRowLabel = "Ignored gate: false" + ) + + testCases := []struct { + name string + status *action.AttestationStatusResult + wantContain []string + wantAbsent []string + }{ + { + name: "advisory strategy is hidden", + status: &action.AttestationStatusResult{}, + wantAbsent: []string{strategyRowLabel, action.PolicyViolationBlockingStrategyAdvisory, ignoredRowLabel}, + }, + { + name: "enforced strategy names its source", + status: &action.AttestationStatusResult{ + MustBlockOnPolicyViolations: true, + PolicyEnforcementSource: attestationv1.PolicyEnforcementSourceOrganization, + }, + wantContain: []string{strategyRowLabel, "ENFORCED (by organization)"}, + wantAbsent: []string{ignoredRowLabel}, + }, + { + name: "ignored gate opt-outs are listed", + status: &action.AttestationStatusResult{ + MustBlockOnPolicyViolations: true, + PolicyEnforcementSource: attestationv1.PolicyEnforcementSourceContract, + IgnoredGateOptOuts: []string{"sbom-banned-licenses", "slsa-checks"}, + }, + wantContain: []string{ignoredRowLabel, "sbom-banned-licenses, slsa-checks (enforcement cannot be relaxed)"}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + now := time.Now() + tc.status.InitializedAt = &now + tc.status.WorkflowMeta = &action.AttestationStatusWorkflowMeta{} + tc.status.RunnerContext = &action.AttestationResultRunnerContext{} + + var buf bytes.Buffer + require.NoError(t, fullStatusTableWithWriter(tc.status, &buf)) + got := buf.String() + + for _, want := range tc.wantContain { + assert.Contains(t, got, want) + } + for _, absent := range tc.wantAbsent { + assert.NotContains(t, got, absent) + } + }) + } +} + func TestVersionStringAttestation(t *testing.T) { testCases := []struct { name string diff --git a/app/cli/cmd/workflow_workflow_run_describe.go b/app/cli/cmd/workflow_workflow_run_describe.go index 6a8443e31..45c4d7486 100644 --- a/app/cli/cmd/workflow_workflow_run_describe.go +++ b/app/cli/cmd/workflow_workflow_run_describe.go @@ -164,16 +164,7 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { } } - gt.AppendRow(table.Row{"Policies violation strategy", att.PolicyEvaluationStatus.Strategy}) - if att.PolicyEvaluationStatus.Blocked { - gt.AppendRow(table.Row{"Run Blocked", att.PolicyEvaluationStatus.Blocked}) - } - if att.PolicyEvaluationStatus.HasGatedViolations { - gt.AppendRow(table.Row{"Run Gated", text.Colors{text.FgHiRed}.Sprint(att.PolicyEvaluationStatus.HasGatedViolations)}) - } - if att.PolicyEvaluationStatus.Strategy == action.PolicyViolationBlockingStrategyEnforced { - gt.AppendRow(table.Row{"Policy enforcement bypassed", att.PolicyEvaluationStatus.Bypassed}) - } + appendPolicyStrategyRows(att.PolicyEvaluationStatus, gt) appendPolicySection(att, gt, flagDebug) @@ -188,6 +179,25 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { return nil } +// appendPolicyStrategyRows adds the policy enforcement rows of a run. +// Only show the strategy when it is enforced. Showing "ADVISORY" is misleading +// when individual policies are configured as gates. +func appendPolicyStrategyRows(status *action.PolicyEvaluationStatus, gt table.Writer) { + enforced := status.Strategy == action.PolicyViolationBlockingStrategyEnforced + if enforced { + gt.AppendRow(table.Row{"Policies violation strategy", status.Strategy}) + } + if status.Blocked { + gt.AppendRow(table.Row{"Run Blocked", status.Blocked}) + } + if status.HasGatedViolations { + gt.AppendRow(table.Row{"Run Gated", text.Colors{text.FgHiRed}.Sprint(status.HasGatedViolations)}) + } + if enforced { + gt.AppendRow(table.Row{"Policy enforcement bypassed", status.Bypassed}) + } +} + func predicateV1Table(att *action.WorkflowRunAttestationItem) { // Materials materials := att.Materials diff --git a/app/cli/cmd/workflow_workflow_run_describe_test.go b/app/cli/cmd/workflow_workflow_run_describe_test.go index 6f8e5e1ca..ff83fa3cb 100644 --- a/app/cli/cmd/workflow_workflow_run_describe_test.go +++ b/app/cli/cmd/workflow_workflow_run_describe_test.go @@ -414,3 +414,46 @@ func TestAppendPolicySection(t *testing.T) { }) } } + +func TestAppendPolicyStrategyRows(t *testing.T) { + const strategyRowLabel = "Policies violation strategy" + + tests := []struct { + name string + status *action.PolicyEvaluationStatus + wantContain []string + wantAbsent []string + }{ + { + name: "enforced strategy is shown", + status: &action.PolicyEvaluationStatus{Strategy: action.PolicyViolationBlockingStrategyEnforced, Blocked: true}, + wantContain: []string{strategyRowLabel, action.PolicyViolationBlockingStrategyEnforced, "Run Blocked", "Policy enforcement bypassed"}, + }, + { + name: "advisory strategy is hidden", + status: &action.PolicyEvaluationStatus{Strategy: action.PolicyViolationBlockingStrategyAdvisory}, + wantAbsent: []string{strategyRowLabel, action.PolicyViolationBlockingStrategyAdvisory, "Policy enforcement bypassed"}, + }, + { + name: "gated violations show without an enforced strategy", + status: &action.PolicyEvaluationStatus{Strategy: action.PolicyViolationBlockingStrategyAdvisory, HasGatedViolations: true}, + wantContain: []string{"Run Gated"}, + wantAbsent: []string{strategyRowLabel}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + tw := table.NewWriter() + appendPolicyStrategyRows(tc.status, tw) + got := tw.Render() + + for _, want := range tc.wantContain { + assert.Contains(t, got, want) + } + for _, absent := range tc.wantAbsent { + assert.NotContains(t, got, absent) + } + }) + } +} diff --git a/app/cli/pkg/action/attestation_init.go b/app/cli/pkg/action/attestation_init.go index 0d37bad1b..d0d5efa4c 100644 --- a/app/cli/pkg/action/attestation_init.go +++ b/app/cli/pkg/action/attestation_init.go @@ -21,6 +21,7 @@ import ( "fmt" "slices" "strconv" + "strings" "github.com/chainloop-dev/chainloop/app/cli/internal/token" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" @@ -333,6 +334,11 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun return "", err } + // gate: false can not relax organization or contract enforcement (R-006) + if msg := ignoredGateOptOutsWarning(action.c.CraftingState.CraftingState); msg != "" { + action.Logger.Warn().Msg(msg) + } + // Load the env variables both the system populated and the user predefined ones if err := action.c.ResolveEnvVars(ctx, attestationID); err != nil { if action.dryRun { @@ -384,6 +390,18 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun // enrichContractMaterials augments a V1 contract schema with the materials // declared by its attached policy groups. +// ignoredGateOptOutsWarning returns a message that names the `gate: false` +// settings that have no effect, or an empty string when there are none. +func ignoredGateOptOutsWarning(state *clientAPI.CraftingState) string { + ignored := state.IgnoredGateOptOuts() + if len(ignored) == 0 { + return "" + } + + return fmt.Sprintf("gate: false has no effect on %s because policies are enforced by the %s, and enforcement cannot be relaxed", + strings.Join(ignored, ", "), state.PolicyEnforcementSource()) +} + func enrichContractMaterials(ctx context.Context, schema *v1.CraftingSchema, client pb.AttestationServiceClient, logger *zerolog.Logger) error { merged, err := mergePolicyGroupMaterials(ctx, schema.GetPolicyGroups(), schema.GetMaterials(), client, logger) if err != nil { diff --git a/app/cli/pkg/action/attestation_init_test.go b/app/cli/pkg/action/attestation_init_test.go index 3452cba13..930298715 100644 --- a/app/cli/pkg/action/attestation_init_test.go +++ b/app/cli/pkg/action/attestation_init_test.go @@ -24,6 +24,7 @@ import ( "github.com/rs/zerolog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" v1 "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" @@ -425,3 +426,39 @@ func setupGitHubPREnv(t *testing.T) { t.Setenv("RUNNER_NAME", "chainloop-runner") t.Setenv("RUNNER_OS", "linux") } + +func TestIgnoredGateOptOutsWarning(t *testing.T) { + gateFalse := []*v1.PolicyAttachment{{Policy: &v1.PolicyAttachment_Ref{Ref: "sbom-banned-licenses"}, Gate: proto.Bool(false)}} + + testCases := []struct { + name string + enforced bool + contractGate bool + want string + }{ + {name: "no warning when nothing enforces"}, + { + name: "organization", + enforced: true, + want: "gate: false has no effect on spec.policies.gate, sbom-banned-licenses because policies are enforced by the organization, and enforcement cannot be relaxed", + }, + { + name: "contract", + enforced: true, + contractGate: true, + want: "gate: false has no effect on sbom-banned-licenses because policies are enforced by the contract, and enforcement cannot be relaxed", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + state := &craftingv1.CraftingState{ + Attestation: &craftingv1.Attestation{BlockOnPolicyViolation: tc.enforced}, + Schema: &craftingv1.CraftingState_SchemaV2{SchemaV2: &v1.CraftingSchemaV2{ + Spec: &v1.CraftingSchemaV2Spec{Policies: &v1.Policies{Gate: proto.Bool(tc.contractGate), Materials: gateFalse}}, + }}, + } + assert.Equal(t, tc.want, ignoredGateOptOutsWarning(state)) + }) + } +} diff --git a/app/cli/pkg/action/attestation_status.go b/app/cli/pkg/action/attestation_status.go index 7c240af45..6d4c0be14 100644 --- a/app/cli/pkg/action/attestation_status.go +++ b/app/cli/pkg/action/attestation_status.go @@ -53,8 +53,13 @@ type AttestationStatusResult struct { PolicyEvaluations map[string][]*PolicyEvaluation `json:"policy_evaluations,omitempty"` HasPolicyViolations bool `json:"has_policy_violations"` MustBlockOnPolicyViolations bool `json:"must_block_on_policy_violations"` - TimestampAuthority string `json:"timestamp_authority"` - AttestationViewURL string `json:"attestation_view_url"` + // Level that enforces all policies: organization or contract + PolicyEnforcementSource string `json:"policy_enforcement_source,omitempty"` + // Contract policies and policy groups with `gate: false` that have no effect + // because the organization or the contract enforces policies + IgnoredGateOptOuts []string `json:"ignored_gate_opt_outs,omitempty"` + TimestampAuthority string `json:"timestamp_authority"` + AttestationViewURL string `json:"attestation_view_url"` // This might only be set if the attestation is pushed Digest string `json:"digest"` // This is the human readable output of the attestation status @@ -126,6 +131,8 @@ func (action *AttestationStatus) Run(ctx context.Context, attestationID string) Annotations: pbAnnotationsToAction(c.CraftingState.GetAnnotations()), IsPushed: action.isPushed, MustBlockOnPolicyViolations: att.GetBlockOnPolicyViolation(), + PolicyEnforcementSource: c.CraftingState.PolicyEnforcementSource(), + IgnoredGateOptOuts: c.CraftingState.IgnoredGateOptOuts(), TimestampAuthority: att.GetSigningOptions().GetTimestampAuthorityUrl(), } diff --git a/app/controlplane/api/gen/frontend/attestation/v1/crafting_state.ts b/app/controlplane/api/gen/frontend/attestation/v1/crafting_state.ts index ad8aaa49b..e7ccd2de2 100644 --- a/app/controlplane/api/gen/frontend/attestation/v1/crafting_state.ts +++ b/app/controlplane/api/gen/frontend/attestation/v1/crafting_state.ts @@ -31,7 +31,10 @@ export interface Attestation { head?: Commit; /** Policies that materials in this attestation were validated against */ policyEvaluations: PolicyEvaluation[]; - /** fail the attestation if policy evaluation fails */ + /** + * fail the attestation if policy evaluation fails. Set at init when the + * organization or the workflow contract (policies.gate) enforces policies. + */ blockOnPolicyViolation: boolean; /** bypass policy check */ bypassPolicyCheck: boolean; diff --git a/app/controlplane/api/gen/frontend/workflowcontract/v1/crafting_schema.ts b/app/controlplane/api/gen/frontend/workflowcontract/v1/crafting_schema.ts index 66b585d7c..936c339bc 100644 --- a/app/controlplane/api/gen/frontend/workflowcontract/v1/crafting_schema.ts +++ b/app/controlplane/api/gen/frontend/workflowcontract/v1/crafting_schema.ts @@ -646,6 +646,13 @@ export interface Policies { materials: PolicyAttachment[]; /** Policies to be applied to attestation metadata */ attestation: PolicyAttachment[]; + /** + * Enforce every policy of this contract, including the policies of its policy groups. + * Enforcement only tightens: + * - true: every policy of the contract acts as a gate + * - false or unset: the organization default and the attachment `gate` values decide + */ + gate?: boolean | undefined; } /** A policy to be applied to this contract */ @@ -679,10 +686,10 @@ export interface PolicyAttachment { /** List of requirements this policy contributes to satisfy */ requirements: string[]; /** - * Controls whether policy violations act as a gate. + * Controls whether policy violations act as a gate. Enforcement only tightens. * - true: policy violations are blocking for this policy - * - false: policy violations are non-blocking for this policy - * - unset: inherit organization-level default behavior + * - false or unset: inherit the organization and contract enforcement. + * It does not turn off enforcement set at those levels. */ gate?: boolean | undefined; } @@ -879,10 +886,10 @@ export interface PolicyGroupAttachment { /** policy names to skip (matched against metadata.name) */ skip: string[]; /** - * Controls whether policy violations act as a gate for this group. - * - true: policy violations are blocking for this policy group - * - false: policy violations are non-blocking for this policy group - * - unset: inherit organization-level default behavior + * Controls whether policy violations act as a gate for this group. Enforcement only tightens. + * - true: policy violations are blocking for every policy of this group + * - false or unset: inherit the organization and contract enforcement, and the policy `gate` values. + * It does not turn off enforcement set at those levels. */ gate?: boolean | undefined; } @@ -1615,7 +1622,7 @@ export const Annotation = { }; function createBasePolicies(): Policies { - return { materials: [], attestation: [] }; + return { materials: [], attestation: [], gate: undefined }; } export const Policies = { @@ -1626,6 +1633,9 @@ export const Policies = { for (const v of message.attestation) { PolicyAttachment.encode(v!, writer.uint32(18).fork()).ldelim(); } + if (message.gate !== undefined) { + writer.uint32(24).bool(message.gate); + } return writer; }, @@ -1650,6 +1660,13 @@ export const Policies = { message.attestation.push(PolicyAttachment.decode(reader, reader.uint32())); continue; + case 3: + if (tag !== 24) { + break; + } + + message.gate = reader.bool(); + continue; } if ((tag & 7) === 4 || tag === 0) { break; @@ -1665,6 +1682,7 @@ export const Policies = { attestation: Array.isArray(object?.attestation) ? object.attestation.map((e: any) => PolicyAttachment.fromJSON(e)) : [], + gate: isSet(object.gate) ? Boolean(object.gate) : undefined, }; }, @@ -1680,6 +1698,7 @@ export const Policies = { } else { obj.attestation = []; } + message.gate !== undefined && (obj.gate = message.gate); return obj; }, @@ -1691,6 +1710,7 @@ export const Policies = { const message = createBasePolicies(); message.materials = object.materials?.map((e) => PolicyAttachment.fromPartial(e)) || []; message.attestation = object.attestation?.map((e) => PolicyAttachment.fromPartial(e)) || []; + message.gate = object.gate ?? undefined; return message; }, }; diff --git a/app/controlplane/api/gen/jsonschema/attestation.v1.Attestation.jsonschema.json b/app/controlplane/api/gen/jsonschema/attestation.v1.Attestation.jsonschema.json index 95888e48b..49d088f37 100644 --- a/app/controlplane/api/gen/jsonschema/attestation.v1.Attestation.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/attestation.v1.Attestation.jsonschema.json @@ -4,7 +4,7 @@ "additionalProperties": false, "patternProperties": { "^(block_on_policy_violation)$": { - "description": "fail the attestation if policy evaluation fails", + "description": "fail the attestation if policy evaluation fails. Set at init when the\n organization or the workflow contract (policies.gate) enforces policies.", "type": "boolean" }, "^(bypass_policy_check)$": { @@ -103,7 +103,7 @@ "description": "Authentication information used during attestation" }, "blockOnPolicyViolation": { - "description": "fail the attestation if policy evaluation fails", + "description": "fail the attestation if policy evaluation fails. Set at init when the\n organization or the workflow contract (policies.gate) enforces policies.", "type": "boolean" }, "bypassPolicyCheck": { diff --git a/app/controlplane/api/gen/jsonschema/attestation.v1.Attestation.schema.json b/app/controlplane/api/gen/jsonschema/attestation.v1.Attestation.schema.json index 7d2d3331f..edc32cbd8 100644 --- a/app/controlplane/api/gen/jsonschema/attestation.v1.Attestation.schema.json +++ b/app/controlplane/api/gen/jsonschema/attestation.v1.Attestation.schema.json @@ -4,7 +4,7 @@ "additionalProperties": false, "patternProperties": { "^(blockOnPolicyViolation)$": { - "description": "fail the attestation if policy evaluation fails", + "description": "fail the attestation if policy evaluation fails. Set at init when the\n organization or the workflow contract (policies.gate) enforces policies.", "type": "boolean" }, "^(bypassPolicyCheck)$": { @@ -103,7 +103,7 @@ "description": "Authentication information used during attestation" }, "block_on_policy_violation": { - "description": "fail the attestation if policy evaluation fails", + "description": "fail the attestation if policy evaluation fails. Set at init when the\n organization or the workflow contract (policies.gate) enforces policies.", "type": "boolean" }, "bypass_policy_check": { diff --git a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.Policies.jsonschema.json b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.Policies.jsonschema.json index 7cff59fdb..29fb9f68c 100644 --- a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.Policies.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.Policies.jsonschema.json @@ -10,6 +10,10 @@ }, "type": "array" }, + "gate": { + "description": "Enforce every policy of this contract, including the policies of its policy groups.\n Enforcement only tightens:\n - true: every policy of the contract acts as a gate\n - false or unset: the organization default and the attachment `gate` values decide", + "type": "boolean" + }, "materials": { "description": "Policies to be applied to materials", "items": { diff --git a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.Policies.schema.json b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.Policies.schema.json index 8a9282900..bc829f1aa 100644 --- a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.Policies.schema.json +++ b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.Policies.schema.json @@ -10,6 +10,10 @@ }, "type": "array" }, + "gate": { + "description": "Enforce every policy of this contract, including the policies of its policy groups.\n Enforcement only tightens:\n - true: every policy of the contract acts as a gate\n - false or unset: the organization default and the attachment `gate` values decide", + "type": "boolean" + }, "materials": { "description": "Policies to be applied to materials", "items": { diff --git a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyAttachment.jsonschema.json b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyAttachment.jsonschema.json index 1ab915cdb..357cf4f5f 100644 --- a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyAttachment.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyAttachment.jsonschema.json @@ -13,7 +13,7 @@ "description": "meant to be used to embed the policy in the contract" }, "gate": { - "description": "Controls whether policy violations act as a gate.\n - true: policy violations are blocking for this policy\n - false: policy violations are non-blocking for this policy\n - unset: inherit organization-level default behavior", + "description": "Controls whether policy violations act as a gate. Enforcement only tightens.\n - true: policy violations are blocking for this policy\n - false or unset: inherit the organization and contract enforcement.\n It does not turn off enforcement set at those levels.", "type": "boolean" }, "ref": { diff --git a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyAttachment.schema.json b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyAttachment.schema.json index a7764cefe..6acea05ee 100644 --- a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyAttachment.schema.json +++ b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyAttachment.schema.json @@ -13,7 +13,7 @@ "description": "meant to be used to embed the policy in the contract" }, "gate": { - "description": "Controls whether policy violations act as a gate.\n - true: policy violations are blocking for this policy\n - false: policy violations are non-blocking for this policy\n - unset: inherit organization-level default behavior", + "description": "Controls whether policy violations act as a gate. Enforcement only tightens.\n - true: policy violations are blocking for this policy\n - false or unset: inherit the organization and contract enforcement.\n It does not turn off enforcement set at those levels.", "type": "boolean" }, "ref": { diff --git a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyGroupAttachment.jsonschema.json b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyGroupAttachment.jsonschema.json index 8fd71a4dd..5ff6fbff9 100644 --- a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyGroupAttachment.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyGroupAttachment.jsonschema.json @@ -5,7 +5,7 @@ "description": "Represents a group attachment in a contract", "properties": { "gate": { - "description": "Controls whether policy violations act as a gate for this group.\n - true: policy violations are blocking for this policy group\n - false: policy violations are non-blocking for this policy group\n - unset: inherit organization-level default behavior", + "description": "Controls whether policy violations act as a gate for this group. Enforcement only tightens.\n - true: policy violations are blocking for every policy of this group\n - false or unset: inherit the organization and contract enforcement, and the policy `gate` values.\n It does not turn off enforcement set at those levels.", "type": "boolean" }, "ref": { diff --git a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyGroupAttachment.schema.json b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyGroupAttachment.schema.json index bed2a06f2..087c23c4d 100644 --- a/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyGroupAttachment.schema.json +++ b/app/controlplane/api/gen/jsonschema/workflowcontract.v1.PolicyGroupAttachment.schema.json @@ -5,7 +5,7 @@ "description": "Represents a group attachment in a contract", "properties": { "gate": { - "description": "Controls whether policy violations act as a gate for this group.\n - true: policy violations are blocking for this policy group\n - false: policy violations are non-blocking for this policy group\n - unset: inherit organization-level default behavior", + "description": "Controls whether policy violations act as a gate for this group. Enforcement only tightens.\n - true: policy violations are blocking for every policy of this group\n - false or unset: inherit the organization and contract enforcement, and the policy `gate` values.\n It does not turn off enforcement set at those levels.", "type": "boolean" }, "ref": { diff --git a/app/controlplane/api/workflowcontract/v1/crafting_schema.pb.go b/app/controlplane/api/workflowcontract/v1/crafting_schema.pb.go index 0381d74cf..1711c8b65 100644 --- a/app/controlplane/api/workflowcontract/v1/crafting_schema.pb.go +++ b/app/controlplane/api/workflowcontract/v1/crafting_schema.pb.go @@ -789,7 +789,12 @@ type Policies struct { // Policies to be applied to materials Materials []*PolicyAttachment `protobuf:"bytes,1,rep,name=materials,proto3" json:"materials,omitempty"` // Policies to be applied to attestation metadata - Attestation []*PolicyAttachment `protobuf:"bytes,2,rep,name=attestation,proto3" json:"attestation,omitempty"` + Attestation []*PolicyAttachment `protobuf:"bytes,2,rep,name=attestation,proto3" json:"attestation,omitempty"` + // Enforce every policy of this contract, including the policies of its policy groups. + // Enforcement only tightens: + // - true: every policy of the contract acts as a gate + // - false or unset: the organization default and the attachment `gate` values decide + Gate *bool `protobuf:"varint,3,opt,name=gate,proto3,oneof" json:"gate,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -838,6 +843,13 @@ func (x *Policies) GetAttestation() []*PolicyAttachment { return nil } +func (x *Policies) GetGate() bool { + if x != nil && x.Gate != nil { + return *x.Gate + } + return false +} + // A policy to be applied to this contract type PolicyAttachment struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -862,10 +874,10 @@ type PolicyAttachment struct { With map[string]string `protobuf:"bytes,5,rep,name=with,proto3" json:"with,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // List of requirements this policy contributes to satisfy Requirements []string `protobuf:"bytes,6,rep,name=requirements,proto3" json:"requirements,omitempty"` - // Controls whether policy violations act as a gate. + // Controls whether policy violations act as a gate. Enforcement only tightens. // - true: policy violations are blocking for this policy - // - false: policy violations are non-blocking for this policy - // - unset: inherit organization-level default behavior + // - false or unset: inherit the organization and contract enforcement. + // It does not turn off enforcement set at those levels. Gate *bool `protobuf:"varint,7,opt,name=gate,proto3,oneof" json:"gate,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -1568,10 +1580,10 @@ type PolicyGroupAttachment struct { With map[string]string `protobuf:"bytes,2,rep,name=with,proto3" json:"with,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // policy names to skip (matched against metadata.name) Skip []string `protobuf:"bytes,3,rep,name=skip,proto3" json:"skip,omitempty"` - // Controls whether policy violations act as a gate for this group. - // - true: policy violations are blocking for this policy group - // - false: policy violations are non-blocking for this policy group - // - unset: inherit organization-level default behavior + // Controls whether policy violations act as a gate for this group. Enforcement only tightens. + // - true: policy violations are blocking for every policy of this group + // - false or unset: inherit the organization and contract enforcement, and the policy `gate` values. + // It does not turn off enforcement set at those levels. Gate *bool `protobuf:"varint,4,opt,name=gate,proto3,oneof" json:"gate,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -2220,10 +2232,12 @@ const file_workflowcontract_v1_crafting_schema_proto_rawDesc = "" + "Annotation\x12#\n" + "\x04name\x18\x01 \x01(\tB\x0f\xbaH\fr\n" + "2\b^[\\w-]+$R\x04name\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value\"\x98\x01\n" + + "\x05value\x18\x02 \x01(\tR\x05value\"\xba\x01\n" + "\bPolicies\x12C\n" + "\tmaterials\x18\x01 \x03(\v2%.workflowcontract.v1.PolicyAttachmentR\tmaterials\x12G\n" + - "\vattestation\x18\x02 \x03(\v2%.workflowcontract.v1.PolicyAttachmentR\vattestation\"\xaf\x05\n" + + "\vattestation\x18\x02 \x03(\v2%.workflowcontract.v1.PolicyAttachmentR\vattestation\x12\x17\n" + + "\x04gate\x18\x03 \x01(\bH\x00R\x04gate\x88\x01\x01B\a\n" + + "\x05_gate\"\xaf\x05\n" + "\x10PolicyAttachment\x12\x1b\n" + "\x03ref\x18\x01 \x01(\tB\a\xbaH\x04r\x02\x10\x01H\x00R\x03ref\x129\n" + "\bembedded\x18\x02 \x01(\v2\x1b.workflowcontract.v1.PolicyH\x00R\bembedded\x12R\n" + @@ -2427,6 +2441,7 @@ func file_workflowcontract_v1_crafting_schema_proto_init() { if File_workflowcontract_v1_crafting_schema_proto != nil { return } + file_workflowcontract_v1_crafting_schema_proto_msgTypes[4].OneofWrappers = []any{} file_workflowcontract_v1_crafting_schema_proto_msgTypes[5].OneofWrappers = []any{ (*PolicyAttachment_Ref)(nil), (*PolicyAttachment_Embedded)(nil), diff --git a/app/controlplane/api/workflowcontract/v1/crafting_schema.proto b/app/controlplane/api/workflowcontract/v1/crafting_schema.proto index 4124983c1..adab187fb 100644 --- a/app/controlplane/api/workflowcontract/v1/crafting_schema.proto +++ b/app/controlplane/api/workflowcontract/v1/crafting_schema.proto @@ -256,6 +256,11 @@ message Policies { repeated PolicyAttachment materials = 1; // Policies to be applied to attestation metadata repeated PolicyAttachment attestation = 2; + // Enforce every policy of this contract, including the policies of its policy groups. + // Enforcement only tightens: + // - true: every policy of the contract acts as a gate + // - false or unset: the organization default and the attachment `gate` values decide + optional bool gate = 3; } // A policy to be applied to this contract @@ -301,10 +306,10 @@ message PolicyAttachment { } }]; - // Controls whether policy violations act as a gate. + // Controls whether policy violations act as a gate. Enforcement only tightens. // - true: policy violations are blocking for this policy - // - false: policy violations are non-blocking for this policy - // - unset: inherit organization-level default behavior + // - false or unset: inherit the organization and contract enforcement. + // It does not turn off enforcement set at those levels. optional bool gate = 7; message MaterialSelector { @@ -482,10 +487,10 @@ message PolicyGroupAttachment { map with = 2; // policy names to skip (matched against metadata.name) repeated string skip = 3; - // Controls whether policy violations act as a gate for this group. - // - true: policy violations are blocking for this policy group - // - false: policy violations are non-blocking for this policy group - // - unset: inherit organization-level default behavior + // Controls whether policy violations act as a gate for this group. Enforcement only tightens. + // - true: policy violations are blocking for every policy of this group + // - false or unset: inherit the organization and contract enforcement, and the policy `gate` values. + // It does not turn off enforcement set at those levels. optional bool gate = 4; } diff --git a/app/controlplane/pkg/biz/workflowrun.go b/app/controlplane/pkg/biz/workflowrun.go index d21ca04cc..20ff7070a 100644 --- a/app/controlplane/pkg/biz/workflowrun.go +++ b/app/controlplane/pkg/biz/workflowrun.go @@ -479,7 +479,8 @@ func (uc *WorkflowRunUseCase) ValidateAttestationContract(ctx context.Context, r return fmt.Errorf("extracting predicate: %w", err) } - return uc.validateAgainstContract(ctx, run, predicate) + _, err = uc.validateAgainstContract(ctx, run, predicate) + return err } // validateAgainstContract rejects an attestation that does not satisfy the @@ -488,19 +489,20 @@ func (uc *WorkflowRunUseCase) ValidateAttestationContract(ctx context.Context, r // The CLI runs the same check before pushing, but it signs the bundle with the // same client that decided whether to run it, so a valid signature says nothing // about contract compliance. The control plane is the authority here. -func (uc *WorkflowRunUseCase) validateAgainstContract(ctx context.Context, run *WorkflowRun, predicate chainloop.NormalizablePredicate) error { +// It returns the contract schema it validated against. +func (uc *WorkflowRunUseCase) validateAgainstContract(ctx context.Context, run *WorkflowRun, predicate chainloop.NormalizablePredicate) (*schemaapi.CraftingSchema, error) { // Every run created through the attestation init endpoint pins a contract // revision, so a run without one is an integrity problem rather than a // reason to skip the check. if run.ContractVersionID == uuid.Nil { - return NewErrValidation(errors.New("workflow run has no contract revision associated")) + return nil, NewErrValidation(errors.New("workflow run has no contract revision associated")) } contract, err := uc.contractRepo.FindVersionByID(ctx, run.ContractVersionID) if err != nil { - return fmt.Errorf("finding contract version: %w", err) + return nil, fmt.Errorf("finding contract version: %w", err) } else if contract == nil || contract.Version == nil || contract.Version.Schema == nil { - return NewErrNotFound("contract version") + return nil, NewErrNotFound("contract version") } // Schema is the v1 form of the contract and is populated for v2 contracts @@ -509,7 +511,7 @@ func (uc *WorkflowRunUseCase) validateAgainstContract(ctx context.Context, run * // would silently wave the attestation through. schema := contract.Version.Schema.Schema if schema == nil { - return NewErrValidation(fmt.Errorf("contract revision %d could not be read", run.ContractRevisionUsed)) + return nil, NewErrValidation(fmt.Errorf("contract revision %d could not be read", run.ContractRevisionUsed)) } craftedNames := make(map[string]struct{}, len(predicate.GetMaterials())) @@ -518,10 +520,10 @@ func (uc *WorkflowRunUseCase) validateAgainstContract(ctx context.Context, run * } if err := attestationapi.ValidateMaterialsPresence(schema.GetMaterials(), craftedNames); err != nil { - return NewErrValidation(fmt.Errorf("attestation does not satisfy contract revision %d: %w", run.ContractRevisionUsed, err)) + return nil, NewErrValidation(fmt.Errorf("attestation does not satisfy contract revision %d: %w", run.ContractRevisionUsed, err)) } - return nil + return schema, nil } func (uc *WorkflowRunUseCase) SaveAttestation(ctx context.Context, id string, bundle []byte, opts ...SaveAttestationOption) (*v1.Hash, error) { @@ -589,7 +591,8 @@ func (uc *WorkflowRunUseCase) SaveAttestation(ctx context.Context, id string, bu } } - if err := uc.validateAgainstContract(ctx, run, predicate); err != nil { + contractSchema, err := uc.validateAgainstContract(ctx, run, predicate) + if err != nil { return nil, err } @@ -605,7 +608,17 @@ func (uc *WorkflowRunUseCase) SaveAttestation(ctx context.Context, id string, bu // Compute and persist the canonical policy status summary so the list // handler can render a status badge without pulling the full attestation. - summary := chainloop.DerivePolicyStatusSummary(predicate.GetPolicyEvaluationStatus()) + policyStatus := predicate.GetPolicyEvaluationStatus() + // A CLI without support for contract enforcement renders the attestation as + // advisory, so mark it enforced to keep the run status true to the contract. + if contractSchema.GetPolicies().GetGate() { + if enforced, changed := policyStatus.Enforced(); changed { + policyStatus = enforced + uc.logger.Warnf("workflow run %s: the contract enforces policies but the attestation does not, the CLI might not support contract enforcement", runID) + } + } + + summary := chainloop.DerivePolicyStatusSummary(policyStatus) if err := uc.wfRunRepo.UpdatePolicyStatus(ctx, runID, &summary); err != nil { return nil, fmt.Errorf("updating policy status: %w", err) } diff --git a/docs/specs/issue-3762-contract-policy-enforcement.md b/docs/specs/issue-3762-contract-policy-enforcement.md new file mode 100644 index 000000000..1395e94e9 --- /dev/null +++ b/docs/specs/issue-3762-contract-policy-enforcement.md @@ -0,0 +1,169 @@ +--- +owner: migmartri +ticket: https://github.com/chainloop-dev/chainloop/issues/3762 +prd: +--- + + + +# Spec issue-3762: Policy Enforcement at the Contract Level + +## Summary + +A workflow contract will have one setting that enforces all of its policies. With it, a contract author can make every policy of the contract a control gate, without changes to each policy attachment and without enforcement for the whole organization. Enforcement will also only tighten. A level can turn enforcement on, but it cannot turn off enforcement that a higher level set. Today a policy attachment with `gate: false` opts out of the organization enforcement. This spec removes that opt-out. + +## Problem + +Today enforcement is set at two levels: + +- The organization default. When it is on, each policy that does not set `gate` is a control gate, in all contracts of the organization. +- Each policy attachment and each policy group attachment, with the `gate` field. + +This causes these gaps: + +- To enforce all the policies of one contract, the author must set `gate: true` on each attachment. A new attachment without `gate` is not enforced, and nothing warns the author. +- The other option is to enforce the whole organization. That affects all contracts, also the contracts that are not ready. +- A contract author can turn off the organization enforcement for one policy with `gate: false`. An organization administrator who turns on enforcement expects that all policies are enforced. The documented behavior lets a contract author override this decision without notice. +- The CLI output shows the organization strategy only. It does not show when a contract or an attachment enforces policies, so the user cannot see the real state. + +## Goals and Non-Goals + +- Goal: A contract author can enforce all the policies of a contract with one setting. +- Goal: Enforcement set at a higher level always applies. A lower level cannot turn it off. +- Goal: The user can see the enforcement that applies to an attestation, and where it comes from. +- Non-goal: Enforcement at the project or the workflow level. The contract is the unit that defines the policies. +- Non-goal: Change the bypass flag of the push command, or the requirement exceptions of compliance frameworks. Both keep their current behavior. +- Non-goal: Enforcement for each material, or for each phase of the attestation. + +## Requirements + +### R-001: Contract enforcement +When a contract turns on enforcement, each policy evaluation of an attestation made with that contract MUST be a control gate. This includes the policies of the policy groups of the contract. +- Done when: a contract with enforcement on and one policy without `gate` blocks the push when that policy has a violation. + +### R-002: Enforcement only tightens +A policy evaluation MUST be a control gate when the organization, the contract, the policy group attachment, or the policy attachment turns on enforcement. A `gate: false` value at a lower level MUST NOT turn off enforcement from a higher level. +- Done when: in an organization with enforcement on, a policy attachment with `gate: false` blocks the push when the policy has a violation. + +### R-003: Contracts without the setting +A contract that does not set the contract enforcement MUST behave as the organization default and the attachment `gate` values decide. The only change is R-002. + +### R-004: Bypass still works +The bypass flag of the push command MUST apply to gates from contract enforcement in the same way as it applies to other gates. The control plane MUST record the bypass. + +### R-005: Show the enforcement that applies +The attestation status command and the workflow run describe command MUST show the strategy as enforced when the organization or the contract turns on enforcement. They SHOULD name the source: the contract when the contract turns on enforcement, else the organization (D-007). When neither level enforces, they MUST NOT show an advisory strategy, because single policies can still be gates. + +### R-006: Warn about an ignored opt-out +When a contract has `gate: false` at a level where a higher level turns on enforcement, the system SHOULD warn the user. The warning SHOULD show when the attestation starts, in the attestation status command, and when the user checks or saves the contract. + +## Constraints + +- Existing contracts MUST stay valid. The new setting is optional. +- The CLI decides the gate of each policy evaluation when it crafts the attestation. An older CLI does not know the contract setting. +- Public repository: the spec and the PR contain no internal links. + +## Proposal + +The contract author adds `gate: true` in the policies section of the contract spec: + +```mermaid +flowchart TD + A[Contract spec.policies.gate: true] --> R + O[Organization enforcement] --> R + G[Policy group attachment gate] --> R + P[Policy attachment gate] --> R + R{Any level is true?} + R -- yes --> Gate[Evaluation is a control gate] + R -- no --> Info[Evaluation is informational] + Gate --> Push{Violation at push?} + Push -- yes, no bypass --> Block[Push fails, attestation is stored] + Push -- yes, bypass --> Rec[Push succeeds, bypass is recorded] +``` + +The field has the same name and the same type as the `gate` field of the attachments. The user does not learn a new word. + +**Resolution.** For each policy evaluation, the gate is true when one or more levels set it to true. The levels are the organization, the contract, the policy group attachment, and the policy attachment. A `false` value or no value at a level has the same effect: that level does not add enforcement. This replaces the current rule, where the nearest level that sets a value wins. + +**Where it runs.** The CLI resolves the gate when it crafts the attestation, as it does today. The CLI already gets the contract and the organization enforcement when the attestation starts. So the change needs no new API between the CLI and the control plane. The attestation records the resolved gate of each evaluation, as it does today. + +**Output.** The attestation status command shows the strategy row only when the organization or the contract enforces policies, with the source. The workflow run describe command does the same. The first part of this behavior (no advisory row) ships on its own in PR #3761. + +**Documentation.** The control gates page changes its table for the `gate` field. `gate: false` no longer opts out of organization enforcement. The page adds the contract setting. + +## Decision Record + +### D-001: The setting is `spec.policies.gate` +An optional boolean in the policies section of the contract spec. +- Why: it is next to the policies it controls, and it uses the same name and type as the attachment `gate` field. +- Alternatives considered: + - A top-level `spec.gate`: less clear that it applies to policies only. +- Source: drafting + +### D-002: Enforcement only tightens, at every level +A level can turn enforcement on. No level can turn off enforcement from a higher level. This removes the documented opt-out of `gate: false`. +- Why: an administrator or a contract author who turns on enforcement expects that it applies to all policies under that level. A silent opt-out goes against that. +- Alternatives considered: + - The nearest level wins, in both directions (the current model): a contract could turn off organization enforcement. + - Only the contract level tightens, and attachments keep the opt-out: two rules for one field. +- Source: drafting + +### D-003: The CLI resolves the gate +The CLI resolves the gate when it crafts the attestation, as it does today for the attachment `gate`. +- Why: the push command blocks on the CLI side, and the CLI already has the contract and the organization setting. No new API is needed. +- Alternatives considered: + - The control plane resolves the gate at push: it cannot fail the CI job of an older CLI either. It also adds a second place that holds the rule. +- Source: drafting + +### D-004: The R-002 change ships in the next release +The opt-out of `gate: false` stops working in the next release. The release notes and the control gates page announce it. +- Why: a warning period keeps the governance gap open for one more release, and the fix is a small contract change. +- Alternatives considered: + - One release with warnings only, then the change: slower, and the gap stays open. +- Source: drafting + +### D-005: Accept `gate: false` and warn +The contract stays valid when it has `gate: false`. The system warns as R-006 says. +- Why: existing contracts stay valid, and the warning tells the author that the value has no effect. +- Alternatives considered: + - Reject `gate: false` when a higher level enforces: existing contracts fail to save. +- Source: drafting + +### D-006: Detect older CLI versions +The documentation names the minimum CLI version for contract enforcement. The control plane marks the workflow run when the contract enforces policies, but the attestation does not record the enforced strategy. A supported CLI always records the enforced strategy, so the control plane marks only runs from older CLIs. The control plane does not need the CLI version for this check. +- Why: an older CLI ignores the contract setting and keeps the opt-out. The control plane cannot fail that CI job, but it can show the gap. +- Alternatives considered: + - Documentation only: the gap stays hidden. +- Source: drafting + +### D-007: One enforcement value for both levels +The attestation records one value for enforcement. The value is on when the organization or the contract turns on enforcement. The status output reads the contract to name the source, so it names the contract when both levels enforce. +- Why: the renderer, the push command, and the control plane already read this value. No new attestation field is necessary. +- Alternatives considered: + - A separate value for the contract: the status can name both levels, but each reader must combine two values. +- Source: [review comment](https://github.com/chainloop-dev/chainloop/pull/3763#discussion_r4433259187) + +## Open Questions + +None. + +## Risks + +| Risk | Mitigation | +|------|------------| +| Pipelines that rely on `gate: false` start to fail after the upgrade. | Release notes, the control gates page, and the R-006 warning (D-004). | +| An older CLI does not enforce the contract setting. | Minimum CLI version in the documentation, and control plane detection (D-006). | diff --git a/pkg/attestation/crafter/api/attestation/v1/crafting_state.go b/pkg/attestation/crafter/api/attestation/v1/crafting_state.go index 00410aef4..085fdfcec 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state.go +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state.go @@ -22,6 +22,7 @@ import ( "errors" "fmt" "os" + "slices" "strings" v1 "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" @@ -493,6 +494,79 @@ func (state *CraftingState) GetAnnotations() []*v1.Annotation { } } +const ( + PolicyEnforcementSourceOrganization = "organization" + PolicyEnforcementSourceContract = "contract" +) + +// PolicyEnforcementSource returns the level that enforces all the policies of +// the attestation, or an empty string when none does. The attestation records +// one enforcement value for both levels, so the contract setting tells them +// apart. When both levels enforce, it names the contract. +func (state *CraftingState) PolicyEnforcementSource() string { + switch { + case !state.GetAttestation().GetBlockOnPolicyViolation(): + return "" + case state.GetPolicies().GetGate(): + return PolicyEnforcementSourceContract + default: + return PolicyEnforcementSourceOrganization + } +} + +// IgnoredGateOptOuts returns the contract settings, policies and policy groups +// that set `gate: false`, which has no effect when the organization or the +// contract enforces policies, since enforcement only tightens. +func (state *CraftingState) IgnoredGateOptOuts() []string { + if !state.GetAttestation().GetBlockOnPolicyViolation() { + return nil + } + + var names []string + policies := state.GetPolicies() + // A contract-wide opt-out with enforcement on means the organization enforces + if policies != nil && optsOut(policies.Gate) { + names = append(names, state.contractGateField()) + } + + for _, att := range slices.Concat(policies.GetMaterials(), policies.GetAttestation()) { + if optsOut(att.Gate) { + names = append(names, policyAttachmentName(att)) + } + } + + for _, group := range state.GetPolicyGroups() { + if optsOut(group.Gate) { + names = append(names, group.GetRef()) + } + } + + return names +} + +// optsOut reports whether a gate is explicitly set to false +func optsOut(gate *bool) bool { + return gate != nil && !*gate +} + +// contractGateField returns how the contract-wide opt-out is written in the +// contract, which depends on the contract schema version. +func (state *CraftingState) contractGateField() string { + if state.GetSchemaV2() != nil { + return "spec.policies.gate" + } + + return "policies.gate" +} + +func policyAttachmentName(att *v1.PolicyAttachment) string { + if ref := att.GetRef(); ref != "" { + return ref + } + + return att.GetEmbedded().GetMetadata().GetName() +} + // GetPolicyGroups returns the policy groups from either v1 or v2 schema func (state *CraftingState) GetPolicyGroups() []*v1.PolicyGroupAttachment { switch schema := state.GetSchema().(type) { diff --git a/pkg/attestation/crafter/api/attestation/v1/crafting_state.pb.go b/pkg/attestation/crafter/api/attestation/v1/crafting_state.pb.go index 5357b2615..880291159 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state.pb.go +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state.pb.go @@ -171,7 +171,8 @@ type Attestation struct { Head *Commit `protobuf:"bytes,9,opt,name=head,proto3" json:"head,omitempty"` // Policies that materials in this attestation were validated against PolicyEvaluations []*PolicyEvaluation `protobuf:"bytes,10,rep,name=policy_evaluations,json=policyEvaluations,proto3" json:"policy_evaluations,omitempty"` - // fail the attestation if policy evaluation fails + // fail the attestation if policy evaluation fails. Set at init when the + // organization or the workflow contract (policies.gate) enforces policies. BlockOnPolicyViolation bool `protobuf:"varint,13,opt,name=block_on_policy_violation,json=blockOnPolicyViolation,proto3" json:"block_on_policy_violation,omitempty"` // bypass policy check BypassPolicyCheck bool `protobuf:"varint,14,opt,name=bypass_policy_check,json=bypassPolicyCheck,proto3" json:"bypass_policy_check,omitempty"` diff --git a/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto b/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto index 7d33b70e9..3caa49e4e 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto @@ -142,7 +142,8 @@ message Attestation { // Policies that materials in this attestation were validated against repeated PolicyEvaluation policy_evaluations = 10; - // fail the attestation if policy evaluation fails + // fail the attestation if policy evaluation fails. Set at init when the + // organization or the workflow contract (policies.gate) enforces policies. bool block_on_policy_violation = 13; // bypass policy check bool bypass_policy_check = 14; diff --git a/pkg/attestation/crafter/api/attestation/v1/crafting_state_test.go b/pkg/attestation/crafter/api/attestation/v1/crafting_state_test.go index b7af12f62..3183919d4 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state_test.go +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state_test.go @@ -859,3 +859,112 @@ func TestPitestInvalidReportIsNotEvaluable(t *testing.T) { _, err := pitestMaterial().GetEvaluableContent("testdata/cobertura.xml", nil) require.ErrorContains(t, err, "invalid PIT report file") } + +func TestPolicyEnforcementSource(t *testing.T) { + contractV2 := func(gate *bool) *CraftingState_SchemaV2 { + return &CraftingState_SchemaV2{SchemaV2: &schemaapi.CraftingSchemaV2{ + Spec: &schemaapi.CraftingSchemaV2Spec{Policies: &schemaapi.Policies{Gate: gate}}, + }} + } + + testCases := []struct { + name string + state *CraftingState + want string + }{ + {name: "nothing enforces", state: &CraftingState{Attestation: &Attestation{}, Schema: contractV2(nil)}}, + { + name: "organization", + state: &CraftingState{Attestation: &Attestation{BlockOnPolicyViolation: true}, Schema: contractV2(nil)}, + want: PolicyEnforcementSourceOrganization, + }, + { + name: "contract, also when the organization enforces", + state: &CraftingState{Attestation: &Attestation{BlockOnPolicyViolation: true}, Schema: contractV2(ptrTo(true))}, + want: PolicyEnforcementSourceContract, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, tc.state.PolicyEnforcementSource()) + }) + } +} + +func TestIgnoredGateOptOuts(t *testing.T) { + const ( + refPolicy = "sbom-banned-licenses" + embeddedPolicy = "embedded-policy" + group = "slsa-checks" + ) + + policies := func(contractGate bool) *schemaapi.Policies { + return &schemaapi.Policies{ + Gate: ptrTo(contractGate), + Materials: []*schemaapi.PolicyAttachment{ + {Policy: &schemaapi.PolicyAttachment_Ref{Ref: refPolicy}, Gate: ptrTo(false)}, + {Policy: &schemaapi.PolicyAttachment_Ref{Ref: "sbom-present"}}, + }, + Attestation: []*schemaapi.PolicyAttachment{ + { + Policy: &schemaapi.PolicyAttachment_Embedded{Embedded: &schemaapi.Policy{Metadata: &schemaapi.Metadata{Name: embeddedPolicy}}}, + Gate: ptrTo(false), + }, + }, + } + } + groups := []*schemaapi.PolicyGroupAttachment{ + {Ref: group, Gate: ptrTo(false)}, + {Ref: "sast"}, + } + schemaV2 := func(contractGate bool) *CraftingState_SchemaV2 { + return &CraftingState_SchemaV2{SchemaV2: &schemaapi.CraftingSchemaV2{ + Spec: &schemaapi.CraftingSchemaV2Spec{Policies: policies(contractGate), PolicyGroups: groups}, + }} + } + ignored := []string{refPolicy, embeddedPolicy, group} + + testCases := []struct { + name string + state *CraftingState + want []string + }{ + { + name: "gate false is honored when nothing enforces", + state: &CraftingState{Attestation: &Attestation{}, Schema: schemaV2(false)}, + }, + { + name: "gate false is ignored when the organization enforces, contract-wide opt-out included", + state: &CraftingState{Attestation: &Attestation{BlockOnPolicyViolation: true}, Schema: schemaV2(false)}, + want: append([]string{"spec.policies.gate"}, ignored...), + }, + { + name: "gate false is ignored when the contract enforces", + state: &CraftingState{Attestation: &Attestation{BlockOnPolicyViolation: true}, Schema: schemaV2(true)}, + want: ignored, + }, + { + name: "v1 contracts name the top-level contract-wide opt-out", + state: &CraftingState{ + Attestation: &Attestation{BlockOnPolicyViolation: true}, + Schema: &CraftingState_InputSchema{InputSchema: &schemaapi.CraftingSchema{ + SchemaVersion: "v1", Policies: &schemaapi.Policies{Gate: ptrTo(false)}, + }}, + }, + want: []string{"policies.gate"}, + }, + { + name: "a contract without policies does not panic", + state: &CraftingState{Attestation: &Attestation{BlockOnPolicyViolation: true}, Schema: &CraftingState_SchemaV2{SchemaV2: &schemaapi.CraftingSchemaV2{}}}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, tc.state.IgnoredGateOptOuts()) + }) + } +} + +func ptrTo[T any](v T) *T { return &v } diff --git a/pkg/attestation/crafter/crafter.go b/pkg/attestation/crafter/crafter.go index c2a6345b5..f86f34702 100644 --- a/pkg/attestation/crafter/crafter.go +++ b/pkg/attestation/crafter/crafter.go @@ -511,12 +511,11 @@ func initialCraftingState(cwd string, opts *InitOpts) (*api.CraftingState, error // Generate Crafting state craftingState := &api.CraftingState{ Attestation: &api.Attestation{ - InitializedAt: timestamppb.New(time.Now()), - Workflow: opts.WfInfo, - RunnerType: opts.Runner.ID(), - RunnerUrl: opts.Runner.RunURI(), - Head: headCommitP, - BlockOnPolicyViolation: opts.BlockOnPolicyViolation, + InitializedAt: timestamppb.New(time.Now()), + Workflow: opts.WfInfo, + RunnerType: opts.Runner.ID(), + RunnerUrl: opts.Runner.RunURI(), + Head: headCommitP, SigningOptions: &api.Attestation_SigningOptions{ TimestampAuthorityUrl: tsURL, SigningCa: caName, @@ -557,6 +556,9 @@ func initialCraftingState(cwd string, opts *InitOpts) (*api.CraftingState, error } } + // Enforcement only tightens: the contract can turn it on, but not off + craftingState.Attestation.BlockOnPolicyViolation = opts.BlockOnPolicyViolation || craftingState.GetPolicies().GetGate() + return craftingState, nil } diff --git a/pkg/attestation/crafter/crafter_test.go b/pkg/attestation/crafter/crafter_test.go index 4ab4b0700..c2836adc1 100644 --- a/pkg/attestation/crafter/crafter_test.go +++ b/pkg/attestation/crafter/crafter_test.go @@ -272,6 +272,66 @@ func (s *crafterSuite) TestInitPRMode() { } } +func (s *crafterSuite) TestInitContractEnforcement() { + enforcedPolicies := &schemaapi.Policies{Gate: proto.Bool(true)} + optOutV2 := &schemaapi.CraftingSchemaV2{Spec: &schemaapi.CraftingSchemaV2Spec{Policies: &schemaapi.Policies{Gate: proto.Bool(false)}}} + + testCases := []struct { + name string + schemaV1 *schemaapi.CraftingSchema + schemaV2 *schemaapi.CraftingSchemaV2 + org bool + want bool + }{ + { + name: "v1 contract without policies", + schemaV1: &schemaapi.CraftingSchema{SchemaVersion: "v1"}, + }, + { + name: "v1 contract enforcing policies", + schemaV1: &schemaapi.CraftingSchema{SchemaVersion: "v1", Policies: enforcedPolicies}, + want: true, + }, + { + name: "v2 contract with gate false", + schemaV2: optOutV2, + }, + { + name: "contract gate false does not relax organization enforcement", + schemaV2: optOutV2, + org: true, + want: true, + }, + { + name: "v2 contract enforcing policies", + schemaV2: &schemaapi.CraftingSchemaV2{Spec: &schemaapi.CraftingSchemaV2Spec{Policies: enforcedPolicies}}, + want: true, + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + statePath := fmt.Sprintf("%s/attestation.json", s.T().TempDir()) + c, err := crafter.NewCrafter(testingStateManager(s.T(), statePath), nil) + require.NoError(s.T(), err) + + testLogger := zerolog.New(zerolog.Nop()).Level(zerolog.Disabled) + runner := crafter.NewRunner(schemaapi.CraftingSchema_Runner_RUNNER_TYPE_UNSPECIFIED, "", &testLogger) + + require.NoError(s.T(), c.Init(context.Background(), &crafter.InitOpts{ + SchemaV1: tc.schemaV1, + SchemaV2: tc.schemaV2, + WfInfo: s.workflowMetadata, + DryRun: true, + Runner: runner, + BlockOnPolicyViolation: tc.org, + })) + + s.Equal(tc.want, c.CraftingState.GetAttestation().GetBlockOnPolicyViolation()) + }) + } +} + type testingCrafter struct { *crafter.Crafter } diff --git a/pkg/attestation/renderer/chainloop/policy_status.go b/pkg/attestation/renderer/chainloop/policy_status.go index 55e7307db..f0e54316e 100644 --- a/pkg/attestation/renderer/chainloop/policy_status.go +++ b/pkg/attestation/renderer/chainloop/policy_status.go @@ -93,3 +93,19 @@ func DerivePolicyStatusSummary(s *PolicyEvaluationStatus) PolicyStatusSummary { return summary } + +// Enforced returns a copy of the status with the enforced strategy, in which +// every policy acts as a gate. The bool reports whether the status changed. +// The control plane uses it when the contract enforces policies, but the CLI +// that rendered the attestation did not apply the contract setting. +func (s *PolicyEvaluationStatus) Enforced() (*PolicyEvaluationStatus, bool) { + if s == nil || s.Strategy == PolicyViolationBlockingStrategyEnforced { + return s, false + } + + enforced := *s + enforced.Strategy = PolicyViolationBlockingStrategyEnforced + enforced.HasGates = true + + return &enforced, true +} diff --git a/pkg/attestation/renderer/chainloop/policy_status_test.go b/pkg/attestation/renderer/chainloop/policy_status_test.go index 8df7d3e2e..41034841f 100644 --- a/pkg/attestation/renderer/chainloop/policy_status_test.go +++ b/pkg/attestation/renderer/chainloop/policy_status_test.go @@ -368,3 +368,39 @@ func TestPredicateToPolicyStatusSummary(t *testing.T) { }) } } + +func TestPolicyEvaluationStatusEnforced(t *testing.T) { + testCases := []struct { + name string + status *PolicyEvaluationStatus + want *PolicyEvaluationStatus + wantChanged bool + }{ + {name: "nil status"}, + { + name: "already enforced", + status: &PolicyEvaluationStatus{Strategy: PolicyViolationBlockingStrategyEnforced, HasViolations: true, Blocked: true}, + want: &PolicyEvaluationStatus{Strategy: PolicyViolationBlockingStrategyEnforced, HasViolations: true, Blocked: true}, + }, + { + name: "advisory with violations", + status: &PolicyEvaluationStatus{Strategy: PolicyViolationBlockingStrategyAdvisory, HasViolations: true}, + want: &PolicyEvaluationStatus{Strategy: PolicyViolationBlockingStrategyEnforced, HasViolations: true, HasGates: true}, + wantChanged: true, + }, + { + name: "advisory with a bypass", + status: &PolicyEvaluationStatus{Strategy: PolicyViolationBlockingStrategyAdvisory, HasViolations: true, Bypassed: true}, + want: &PolicyEvaluationStatus{Strategy: PolicyViolationBlockingStrategyEnforced, HasViolations: true, HasGates: true, Bypassed: true}, + wantChanged: true, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got, changed := tc.status.Enforced() + assert.Equal(t, tc.want, got) + assert.Equal(t, tc.wantChanged, changed) + }) + } +} diff --git a/pkg/attestation/renderer/chainloop/v02.go b/pkg/attestation/renderer/chainloop/v02.go index aa68a2862..0e20929cb 100644 --- a/pkg/attestation/renderer/chainloop/v02.go +++ b/pkg/attestation/renderer/chainloop/v02.go @@ -290,18 +290,19 @@ func (r *RendererV02) predicate() (*structpb.Struct, error) { return nil, fmt.Errorf("error rendering policy evaluations: %w", err) } + policiesEnforced := r.att.GetBlockOnPolicyViolation() policyCheckBlockingStrategy := PolicyViolationBlockingStrategyAdvisory - if r.att.GetBlockOnPolicyViolation() { + if policiesEnforced { policyCheckBlockingStrategy = PolicyViolationBlockingStrategyEnforced } // An attestation is blocked when: // - any of the policies marked as gate has violations - // - or if there are any policy violations and the attestation is configured to be blocked on violations + // - or if there are any policy violations and the organization or the contract enforces policies // In all cases, if the bypass flag is set, the attestation is not blocked - blocked := !r.att.GetBypassPolicyCheck() && (evalResult.hasGatedViolations || (evalResult.hasViolations && r.att.GetBlockOnPolicyViolation())) + blocked := !r.att.GetBypassPolicyCheck() && (evalResult.hasGatedViolations || (evalResult.hasViolations && policiesEnforced)) - hasGates := evalResult.hasGates || policyCheckBlockingStrategy == PolicyViolationBlockingStrategyEnforced + hasGates := evalResult.hasGates || policiesEnforced p := ProvenancePredicateV02{ ProvenancePredicateCommon: predicateCommon(r.builder, r.att), diff --git a/pkg/attestation/renderer/chainloop/v02_test.go b/pkg/attestation/renderer/chainloop/v02_test.go index 0778933f5..f2f665cad 100644 --- a/pkg/attestation/renderer/chainloop/v02_test.go +++ b/pkg/attestation/renderer/chainloop/v02_test.go @@ -519,6 +519,45 @@ func TestPredicatePolicyEvaluationsRef(t *testing.T) { } } +func TestPredicatePolicyCheckBlockingStrategy(t *testing.T) { + // The fixture has one violation on a policy that is not a gate + testCases := []struct { + name string + enforced bool + bypass bool + wantStrategy PolicyViolationBlockingStrategy + wantBlocked bool + wantHasGates bool + }{ + {name: "advisory when nothing enforces", wantStrategy: PolicyViolationBlockingStrategyAdvisory}, + {name: "enforced by the organization or the contract", enforced: true, wantStrategy: PolicyViolationBlockingStrategyEnforced, wantBlocked: true, wantHasGates: true}, + {name: "enforcement with bypass", enforced: true, bypass: true, wantStrategy: PolicyViolationBlockingStrategyEnforced, wantHasGates: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + stateRaw, err := os.ReadFile("testdata/attestation.source.v2.json") + require.NoError(t, err) + + state := &api.CraftingState{} + require.NoError(t, protojson.Unmarshal(stateRaw, state)) + state.Attestation.BlockOnPolicyViolation = tc.enforced + state.Attestation.BypassPolicyCheck = tc.bypass + + renderer := NewChainloopRendererV02(state.Attestation, "dev", "sha256:59e14f1a9de709cdd0e91c36b33e54fcca95f7dba1dc7169a7f81986e02108e5", nil, nil) + statement, err := renderer.Statement(context.TODO()) + require.NoError(t, err) + + var predicate ProvenancePredicateV02 + require.NoError(t, extractPredicate(statement, &predicate)) + assert.Equal(t, tc.wantStrategy, predicate.PolicyCheckBlockingStrategy) + assert.True(t, predicate.PolicyHasViolations) + assert.Equal(t, tc.wantBlocked, predicate.PolicyAttBlocked) + assert.Equal(t, tc.wantHasGates, predicate.PolicyHasGates) + }) + } +} + // TestPolicyEvaluationsRefJSON pins the rendered shape: the size is a key of the // reference object itself, alongside the descriptor's own fields. func TestPolicyEvaluationsRefJSON(t *testing.T) { diff --git a/pkg/policies/policies.go b/pkg/policies/policies.go index f4aff7795..6e8d15429 100644 --- a/pkg/policies/policies.go +++ b/pkg/policies/policies.go @@ -556,16 +556,10 @@ func (pv *PolicyVerifier) evaluatePolicyAttachment(ctx context.Context, attachme }, nil } +// policyAttachmentGate resolves whether a policy acts as a gate. Enforcement +// only tightens: an explicit `gate: false` cannot relax an enforced default. func policyAttachmentGate(attachment *v1.PolicyAttachment, defaultGate bool) bool { - if attachment == nil { - return defaultGate - } - - if attachment.Gate != nil { - return attachment.GetGate() - } - - return defaultGate + return defaultGate || attachment.GetGate() } // ComputeArguments takes a list of arguments, and matches it against the expected inputs. It also applies a set of interpolations if needed. diff --git a/pkg/policies/policies_test.go b/pkg/policies/policies_test.go index cc7eecc7d..098481a80 100644 --- a/pkg/policies/policies_test.go +++ b/pkg/policies/policies_test.go @@ -2019,11 +2019,19 @@ func (s *testSuite) TestPolicyAttachmentGate() { expectedGate: true, }, { - name: "explicit gate false overrides default true", + name: "explicit gate false does not relax default true", attachment: &v12.PolicyAttachment{ Gate: &falseGate, }, defaultGate: true, + expectedGate: true, + }, + { + name: "explicit gate false with default false", + attachment: &v12.PolicyAttachment{ + Gate: &falseGate, + }, + defaultGate: false, expectedGate: false, }, { diff --git a/pkg/policies/policy_groups.go b/pkg/policies/policy_groups.go index 4520e388f..a0f03e059 100644 --- a/pkg/policies/policy_groups.go +++ b/pkg/policies/policy_groups.go @@ -231,14 +231,16 @@ func (pgv *PolicyGroupVerifier) VerifyStatement(ctx context.Context, statement * return result, nil } +// applyGroupGate makes every policy of the group a gate when the group +// attachment enforces it. Enforcement only tightens: a group with `gate: false` +// leaves the policy gates as they are. func applyGroupGate(policyAtt *v1.PolicyAttachment, groupAtt *v1.PolicyGroupAttachment) *v1.PolicyAttachment { - if policyAtt == nil || groupAtt == nil || groupAtt.Gate == nil { + if policyAtt == nil || !groupAtt.GetGate() || policyAtt.GetGate() { return policyAtt } cloned := proto.Clone(policyAtt).(*v1.PolicyAttachment) - groupGate := groupAtt.GetGate() - cloned.Gate = &groupGate + cloned.Gate = proto.Bool(true) return cloned } diff --git a/pkg/policies/policy_groups_test.go b/pkg/policies/policy_groups_test.go index 50b95571d..5914d02f8 100644 --- a/pkg/policies/policy_groups_test.go +++ b/pkg/policies/policy_groups_test.go @@ -793,13 +793,25 @@ func (s *groupsTestSuite) TestApplyGroupGate() { expectedGate: boolPtr(true), }, { - name: "group gate overrides policy gate", + name: "group gate true tightens policy gate false", policyAtt: &v1.PolicyAttachment{ Gate: &policyGate, }, groupAtt: &v1.PolicyGroupAttachment{Gate: &groupGate}, expectedGate: boolPtr(true), }, + { + name: "group gate false does not relax policy gate true", + policyAtt: &v1.PolicyAttachment{Gate: boolPtr(true)}, + groupAtt: &v1.PolicyGroupAttachment{Gate: boolPtr(false)}, + expectedGate: boolPtr(true), + }, + { + name: "group gate false leaves unset policy gate unset", + policyAtt: &v1.PolicyAttachment{}, + groupAtt: &v1.PolicyGroupAttachment{Gate: boolPtr(false)}, + expectedGate: nil, + }, } for _, tc := range cases {