From 7342aac03c930806d5ab35b8882bec50b4e623ca Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Sat, 31 Oct 2026 18:28:31 +0100 Subject: [PATCH 1/8] spec: issue-3762 policy enforcement at the contract level Refs #3762 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 44016fe6-1a31-4253-934f-ca70bc4b469d --- .../issue-3762-contract-policy-enforcement.md | 162 ++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 docs/specs/issue-3762-contract-policy-enforcement.md 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..fee571b1d --- /dev/null +++ b/docs/specs/issue-3762-contract-policy-enforcement.md @@ -0,0 +1,162 @@ +--- +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: organization, contract, or both. 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 user checks or saves the contract, and in the attestation status command. + +## 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 organization or the contract enforces policies, but the attestation does not record the expected gates. +- 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 + +## 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). | From f7f82329aceb122f3cb6aef02289969424198417 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Sat, 31 Oct 2026 18:40:09 +0100 Subject: [PATCH 2/8] feat(policies): add policy enforcement at the contract level Add spec.policies.gate to workflow contracts to enforce every policy of a contract, including its policy groups. Enforcement now only tightens: the organization, the contract, a policy group attachment or a policy attachment can turn enforcement on, but gate: false no longer turns off enforcement set at a higher level. The attestation status output shows the enforcement source and the gate: false values that have no effect, and hides the advisory strategy. The control plane applies the contract enforcement to the run policy status when the attestation was crafted by a CLI without support for it. Implements R-001 to R-005 and part of R-006 of spec issue-3762. Refs #3762 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 44016fe6-1a31-4253-934f-ca70bc4b469d --- app/cli/cmd/attestation_push.go | 13 +-- app/cli/cmd/attestation_push_test.go | 4 +- app/cli/cmd/attestation_status.go | 13 +-- app/cli/cmd/workflow_workflow_run_describe.go | 6 +- app/cli/pkg/action/attestation_status.go | 65 ++++++++++++++- app/cli/pkg/action/attestation_status_test.go | 82 +++++++++++++++++++ .../frontend/attestation/v1/crafting_state.ts | 25 +++++- .../workflowcontract/v1/crafting_schema.ts | 36 ++++++-- ...attestation.v1.Attestation.jsonschema.json | 12 ++- .../attestation.v1.Attestation.schema.json | 12 ++- ...rkflowcontract.v1.Policies.jsonschema.json | 4 + .../workflowcontract.v1.Policies.schema.json | 4 + ...ntract.v1.PolicyAttachment.jsonschema.json | 2 +- ...owcontract.v1.PolicyAttachment.schema.json | 2 +- ...t.v1.PolicyGroupAttachment.jsonschema.json | 2 +- ...tract.v1.PolicyGroupAttachment.schema.json | 2 +- .../workflowcontract/v1/crafting_schema.pb.go | 35 +++++--- .../workflowcontract/v1/crafting_schema.proto | 19 +++-- app/controlplane/pkg/biz/workflowrun.go | 45 +++++++--- .../pkg/biz/workflowrun_enforcement_test.go | 75 +++++++++++++++++ .../api/attestation/v1/crafting_state.go | 6 ++ .../api/attestation/v1/crafting_state.pb.go | 18 +++- .../api/attestation/v1/crafting_state.proto | 6 +- .../api/attestation/v1/crafting_state_test.go | 20 +++++ pkg/attestation/crafter/crafter.go | 10 ++- pkg/attestation/crafter/crafter_test.go | 51 ++++++++++++ pkg/attestation/renderer/chainloop/v02.go | 9 +- .../renderer/chainloop/v02_test.go | 33 ++++++++ pkg/policies/policies.go | 12 +-- pkg/policies/policies_test.go | 10 ++- pkg/policies/policy_groups.go | 8 +- pkg/policies/policy_groups_test.go | 14 +++- 32 files changed, 564 insertions(+), 91 deletions(-) create mode 100644 app/controlplane/pkg/biz/workflowrun_enforcement_test.go 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..82f1d8a32 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, strings.Join(status.PolicyEnforcementSources, ", ")) + 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/workflow_workflow_run_describe.go b/app/cli/cmd/workflow_workflow_run_describe.go index 6a8443e31..ef77d1b1e 100644 --- a/app/cli/cmd/workflow_workflow_run_describe.go +++ b/app/cli/cmd/workflow_workflow_run_describe.go @@ -164,7 +164,11 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { } } - gt.AppendRow(table.Row{"Policies violation strategy", att.PolicyEvaluationStatus.Strategy}) + // Only show the strategy when it is enforced. Showing "ADVISORY" is misleading + // when individual policies are configured as gates. + if att.PolicyEvaluationStatus.Strategy == action.PolicyViolationBlockingStrategyEnforced { + gt.AppendRow(table.Row{"Policies violation strategy", att.PolicyEvaluationStatus.Strategy}) + } if att.PolicyEvaluationStatus.Blocked { gt.AppendRow(table.Row{"Run Blocked", att.PolicyEvaluationStatus.Blocked}) } diff --git a/app/cli/pkg/action/attestation_status.go b/app/cli/pkg/action/attestation_status.go index 7c240af45..5cafdd04f 100644 --- a/app/cli/pkg/action/attestation_status.go +++ b/app/cli/pkg/action/attestation_status.go @@ -18,6 +18,7 @@ package action import ( "context" "fmt" + "slices" "time" pbc "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" @@ -53,8 +54,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"` + // Levels that enforce all policies: organization and/or contract + PolicyEnforcementSources []string `json:"policy_enforcement_sources,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 @@ -125,7 +131,9 @@ func (action *AttestationStatus) Run(ctx context.Context, attestationID string) DryRun: c.CraftingState.DryRun, Annotations: pbAnnotationsToAction(c.CraftingState.GetAnnotations()), IsPushed: action.isPushed, - MustBlockOnPolicyViolations: att.GetBlockOnPolicyViolation(), + MustBlockOnPolicyViolations: att.PoliciesEnforced(), + PolicyEnforcementSources: policyEnforcementSources(att), + IgnoredGateOptOuts: ignoredGateOptOuts(c.CraftingState.CraftingState), TimestampAuthority: att.GetSigningOptions().GetTimestampAuthorityUrl(), } @@ -179,6 +187,57 @@ func (action *AttestationStatus) Run(ctx context.Context, attestationID string) return res, nil } +const ( + PolicyEnforcementSourceOrganization = "organization" + PolicyEnforcementSourceContract = "contract" +) + +// policyEnforcementSources returns the levels that enforce all the policies of the attestation +func policyEnforcementSources(att *v1.Attestation) []string { + var sources []string + if att.GetBlockOnPolicyViolation() { + sources = append(sources, PolicyEnforcementSourceOrganization) + } + if att.GetContractBlockOnPolicyViolation() { + sources = append(sources, PolicyEnforcementSourceContract) + } + + return sources +} + +// ignoredGateOptOuts returns the contract 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 ignoredGateOptOuts(state *v1.CraftingState) []string { + if !state.GetAttestation().PoliciesEnforced() { + return nil + } + + var names []string + policies := state.GetPolicies() + for _, att := range slices.Concat(policies.GetMaterials(), policies.GetAttestation()) { + if att.Gate != nil && !att.GetGate() { + names = append(names, policyAttachmentName(att)) + } + } + + for _, group := range state.GetPolicyGroups() { + if group.Gate != nil && !group.GetGate() { + names = append(names, group.GetRef()) + } + } + + return names +} + +func policyAttachmentName(att *pbc.PolicyAttachment) string { + if ref := att.GetRef(); ref != "" { + return ref + } + + return att.GetEmbedded().GetMetadata().GetName() +} + // getPolicyEvaluations retrieves both material-level and attestation-level policy evaluations and returns if it has violations func getPolicyEvaluations(c *crafter.Crafter) (map[string][]*PolicyEvaluation, bool) { // grouped by material name diff --git a/app/cli/pkg/action/attestation_status_test.go b/app/cli/pkg/action/attestation_status_test.go index 2a662bf58..1db04df20 100644 --- a/app/cli/pkg/action/attestation_status_test.go +++ b/app/cli/pkg/action/attestation_status_test.go @@ -21,6 +21,7 @@ import ( craftingpb "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" v1 "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" "github.com/stretchr/testify/assert" + "google.golang.org/protobuf/proto" ) func TestPopulateContractMaterials(t *testing.T) { @@ -154,3 +155,84 @@ func TestPopulateContractMaterialsGroups(t *testing.T) { assert.Equal(t, "sbom", byName["sbom-spdx"].Group) assert.False(t, byName["sbom-spdx"].Required) } + +func TestPolicyEnforcementSources(t *testing.T) { + testCases := []struct { + name string + att *v1.Attestation + want []string + }{ + {name: "nothing enforces", att: &v1.Attestation{}}, + {name: "organization", att: &v1.Attestation{BlockOnPolicyViolation: true}, want: []string{PolicyEnforcementSourceOrganization}}, + {name: "contract", att: &v1.Attestation{ContractBlockOnPolicyViolation: true}, want: []string{PolicyEnforcementSourceContract}}, + { + name: "both", + att: &v1.Attestation{BlockOnPolicyViolation: true, ContractBlockOnPolicyViolation: true}, + want: []string{PolicyEnforcementSourceOrganization, PolicyEnforcementSourceContract}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, policyEnforcementSources(tc.att)) + }) + } +} + +func TestIgnoredGateOptOuts(t *testing.T) { + const ( + refPolicy = "sbom-banned-licenses" + embeddedPolicy = "embedded-policy" + group = "slsa-checks" + ) + + schema := &craftingpb.CraftingSchemaV2{ + Spec: &craftingpb.CraftingSchemaV2Spec{ + Policies: &craftingpb.Policies{ + Materials: []*craftingpb.PolicyAttachment{ + {Policy: &craftingpb.PolicyAttachment_Ref{Ref: refPolicy}, Gate: proto.Bool(false)}, + {Policy: &craftingpb.PolicyAttachment_Ref{Ref: "sbom-present"}}, + }, + Attestation: []*craftingpb.PolicyAttachment{ + { + Policy: &craftingpb.PolicyAttachment_Embedded{Embedded: &craftingpb.Policy{Metadata: &craftingpb.Metadata{Name: embeddedPolicy}}}, + Gate: proto.Bool(false), + }, + }, + }, + PolicyGroups: []*craftingpb.PolicyGroupAttachment{ + {Ref: group, Gate: proto.Bool(false)}, + {Ref: "sast"}, + }, + }, + } + ignored := []string{refPolicy, embeddedPolicy, group} + + testCases := []struct { + name string + att *v1.Attestation + want []string + }{ + {name: "gate false is honored when nothing enforces", att: &v1.Attestation{}}, + { + name: "gate false is ignored when the organization enforces", + att: &v1.Attestation{BlockOnPolicyViolation: true}, + want: ignored, + }, + { + name: "gate false is ignored when the contract enforces", + att: &v1.Attestation{ContractBlockOnPolicyViolation: true}, + want: ignored, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + state := &v1.CraftingState{ + Attestation: tc.att, + Schema: &v1.CraftingState_SchemaV2{SchemaV2: schema}, + } + assert.Equal(t, tc.want, ignoredGateOptOuts(state)) + }) + } +} 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..6cf732702 100644 --- a/app/controlplane/api/gen/frontend/attestation/v1/crafting_state.ts +++ b/app/controlplane/api/gen/frontend/attestation/v1/crafting_state.ts @@ -31,8 +31,14 @@ 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 (organization setting) */ blockOnPolicyViolation: boolean; + /** + * the workflow contract enforces all of its policies (spec.policies.gate). + * Copied from the contract at init so the renderer and the status output, + * which only see the attestation, can tell the enforcement source. + */ + contractBlockOnPolicyViolation: boolean; /** bypass policy check */ bypassPolicyCheck: boolean; /** Signing options */ @@ -653,6 +659,7 @@ function createBaseAttestation(): Attestation { head: undefined, policyEvaluations: [], blockOnPolicyViolation: false, + contractBlockOnPolicyViolation: false, bypassPolicyCheck: false, signingOptions: undefined, runnerEnvironment: undefined, @@ -698,6 +705,9 @@ export const Attestation = { if (message.blockOnPolicyViolation === true) { writer.uint32(104).bool(message.blockOnPolicyViolation); } + if (message.contractBlockOnPolicyViolation === true) { + writer.uint32(168).bool(message.contractBlockOnPolicyViolation); + } if (message.bypassPolicyCheck === true) { writer.uint32(112).bool(message.bypassPolicyCheck); } @@ -815,6 +825,13 @@ export const Attestation = { message.blockOnPolicyViolation = reader.bool(); continue; + case 21: + if (tag !== 168) { + break; + } + + message.contractBlockOnPolicyViolation = reader.bool(); + continue; case 14: if (tag !== 112) { break; @@ -903,6 +920,9 @@ export const Attestation = { ? object.policyEvaluations.map((e: any) => PolicyEvaluation.fromJSON(e)) : [], blockOnPolicyViolation: isSet(object.blockOnPolicyViolation) ? Boolean(object.blockOnPolicyViolation) : false, + contractBlockOnPolicyViolation: isSet(object.contractBlockOnPolicyViolation) + ? Boolean(object.contractBlockOnPolicyViolation) + : false, bypassPolicyCheck: isSet(object.bypassPolicyCheck) ? Boolean(object.bypassPolicyCheck) : false, signingOptions: isSet(object.signingOptions) ? Attestation_SigningOptions.fromJSON(object.signingOptions) @@ -952,6 +972,8 @@ export const Attestation = { obj.policyEvaluations = []; } message.blockOnPolicyViolation !== undefined && (obj.blockOnPolicyViolation = message.blockOnPolicyViolation); + message.contractBlockOnPolicyViolation !== undefined && + (obj.contractBlockOnPolicyViolation = message.contractBlockOnPolicyViolation); message.bypassPolicyCheck !== undefined && (obj.bypassPolicyCheck = message.bypassPolicyCheck); message.signingOptions !== undefined && (obj.signingOptions = message.signingOptions ? Attestation_SigningOptions.toJSON(message.signingOptions) @@ -1011,6 +1033,7 @@ export const Attestation = { message.head = (object.head !== undefined && object.head !== null) ? Commit.fromPartial(object.head) : undefined; message.policyEvaluations = object.policyEvaluations?.map((e) => PolicyEvaluation.fromPartial(e)) || []; message.blockOnPolicyViolation = object.blockOnPolicyViolation ?? false; + message.contractBlockOnPolicyViolation = object.contractBlockOnPolicyViolation ?? false; message.bypassPolicyCheck = object.bypassPolicyCheck ?? false; message.signingOptions = (object.signingOptions !== undefined && object.signingOptions !== null) ? Attestation_SigningOptions.fromPartial(object.signingOptions) 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..3a72381b5 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 (organization setting)", "type": "boolean" }, "^(bypass_policy_check)$": { @@ -15,6 +15,10 @@ "$ref": "attestation.v1.Attestation.CASBackend.jsonschema.json", "description": "CAS backend information used during attestation" }, + "^(contract_block_on_policy_violation)$": { + "description": "the workflow contract enforces all of its policies (spec.policies.gate).\n Copied from the contract at init so the renderer and the status output,\n which only see the attestation, can tell the enforcement source.", + "type": "boolean" + }, "^(env_vars)$": { "additionalProperties": { "type": "string" @@ -103,7 +107,7 @@ "description": "Authentication information used during attestation" }, "blockOnPolicyViolation": { - "description": "fail the attestation if policy evaluation fails", + "description": "fail the attestation if policy evaluation fails (organization setting)", "type": "boolean" }, "bypassPolicyCheck": { @@ -114,6 +118,10 @@ "$ref": "attestation.v1.Attestation.CASBackend.jsonschema.json", "description": "CAS backend information used during attestation" }, + "contractBlockOnPolicyViolation": { + "description": "the workflow contract enforces all of its policies (spec.policies.gate).\n Copied from the contract at init so the renderer and the status output,\n which only see the attestation, can tell the enforcement source.", + "type": "boolean" + }, "envVars": { "additionalProperties": { "type": "string" 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..e5859bb00 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 (organization setting)", "type": "boolean" }, "^(bypassPolicyCheck)$": { @@ -15,6 +15,10 @@ "$ref": "attestation.v1.Attestation.CASBackend.schema.json", "description": "CAS backend information used during attestation" }, + "^(contractBlockOnPolicyViolation)$": { + "description": "the workflow contract enforces all of its policies (spec.policies.gate).\n Copied from the contract at init so the renderer and the status output,\n which only see the attestation, can tell the enforcement source.", + "type": "boolean" + }, "^(envVars)$": { "additionalProperties": { "type": "string" @@ -103,7 +107,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 (organization setting)", "type": "boolean" }, "bypass_policy_check": { @@ -114,6 +118,10 @@ "$ref": "attestation.v1.Attestation.CASBackend.schema.json", "description": "CAS backend information used during attestation" }, + "contract_block_on_policy_violation": { + "description": "the workflow contract enforces all of its policies (spec.policies.gate).\n Copied from the contract at init so the renderer and the status output,\n which only see the attestation, can tell the enforcement source.", + "type": "boolean" + }, "env_vars": { "additionalProperties": { "type": "string" 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..9e03d7ee0 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,27 @@ 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 +} + +// applyContractEnforcement returns the policy evaluation status with the +// contract enforcement applied. A CLI without support for contract enforcement +// renders the attestation as advisory, so the control plane marks it enforced +// to keep the run status true to the contract. The bool reports whether the +// status changed. +func applyContractEnforcement(status *chainloop.PolicyEvaluationStatus, contractEnforces bool) (*chainloop.PolicyEvaluationStatus, bool) { + if status == nil || !contractEnforces || status.Strategy == chainloop.PolicyViolationBlockingStrategyEnforced { + return status, false + } + + enforced := *status + enforced.Strategy = chainloop.PolicyViolationBlockingStrategyEnforced + enforced.HasGates = true + + return &enforced, true } func (uc *WorkflowRunUseCase) SaveAttestation(ctx context.Context, id string, bundle []byte, opts ...SaveAttestationOption) (*v1.Hash, error) { @@ -589,7 +608,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 +625,12 @@ 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, applied := applyContractEnforcement(predicate.GetPolicyEvaluationStatus(), contractSchema.GetPolicies().GetGate()) + if applied { + 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/app/controlplane/pkg/biz/workflowrun_enforcement_test.go b/app/controlplane/pkg/biz/workflowrun_enforcement_test.go new file mode 100644 index 000000000..ee7334d48 --- /dev/null +++ b/app/controlplane/pkg/biz/workflowrun_enforcement_test.go @@ -0,0 +1,75 @@ +// +// Copyright 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. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package biz + +import ( + "testing" + + "github.com/chainloop-dev/chainloop/pkg/attestation/renderer/chainloop" + "github.com/stretchr/testify/assert" +) + +func TestApplyContractEnforcement(t *testing.T) { + advisory := chainloop.PolicyViolationBlockingStrategyAdvisory + enforced := chainloop.PolicyViolationBlockingStrategyEnforced + + testCases := []struct { + name string + status *chainloop.PolicyEvaluationStatus + contractEnforces bool + want *chainloop.PolicyEvaluationStatus + wantApplied bool + }{ + { + name: "nil status", + status: nil, + want: nil, + }, + { + name: "contract does not enforce", + status: &chainloop.PolicyEvaluationStatus{Strategy: advisory, HasViolations: true}, + want: &chainloop.PolicyEvaluationStatus{Strategy: advisory, HasViolations: true}, + }, + { + name: "attestation already enforced", + status: &chainloop.PolicyEvaluationStatus{Strategy: enforced, HasViolations: true, Blocked: true}, + contractEnforces: true, + want: &chainloop.PolicyEvaluationStatus{Strategy: enforced, HasViolations: true, Blocked: true}, + }, + { + name: "advisory attestation with violations under an enforcing contract", + status: &chainloop.PolicyEvaluationStatus{Strategy: advisory, HasViolations: true}, + contractEnforces: true, + want: &chainloop.PolicyEvaluationStatus{Strategy: enforced, HasViolations: true, HasGates: true}, + wantApplied: true, + }, + { + name: "advisory attestation with a bypass under an enforcing contract", + status: &chainloop.PolicyEvaluationStatus{Strategy: advisory, HasViolations: true, Bypassed: true}, + contractEnforces: true, + want: &chainloop.PolicyEvaluationStatus{Strategy: enforced, HasViolations: true, HasGates: true, Bypassed: true}, + wantApplied: true, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got, applied := applyContractEnforcement(tc.status, tc.contractEnforces) + assert.Equal(t, tc.want, got) + assert.Equal(t, tc.wantApplied, applied) + }) + } +} diff --git a/pkg/attestation/crafter/api/attestation/v1/crafting_state.go b/pkg/attestation/crafter/api/attestation/v1/crafting_state.go index 00410aef4..3525885e6 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state.go +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state.go @@ -493,6 +493,12 @@ func (state *CraftingState) GetAnnotations() []*v1.Annotation { } } +// PoliciesEnforced reports whether every policy of the attestation acts as a +// gate, because the organization or the workflow contract enforces policies. +func (a *Attestation) PoliciesEnforced() bool { + return a.GetBlockOnPolicyViolation() || a.GetContractBlockOnPolicyViolation() +} + // 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..17a7c8586 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state.pb.go +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state.pb.go @@ -171,8 +171,12 @@ 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 (organization setting) BlockOnPolicyViolation bool `protobuf:"varint,13,opt,name=block_on_policy_violation,json=blockOnPolicyViolation,proto3" json:"block_on_policy_violation,omitempty"` + // the workflow contract enforces all of its policies (spec.policies.gate). + // Copied from the contract at init so the renderer and the status output, + // which only see the attestation, can tell the enforcement source. + ContractBlockOnPolicyViolation bool `protobuf:"varint,21,opt,name=contract_block_on_policy_violation,json=contractBlockOnPolicyViolation,proto3" json:"contract_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"` // Signing options @@ -299,6 +303,13 @@ func (x *Attestation) GetBlockOnPolicyViolation() bool { return false } +func (x *Attestation) GetContractBlockOnPolicyViolation() bool { + if x != nil { + return x.ContractBlockOnPolicyViolation + } + return false +} + func (x *Attestation) GetBypassPolicyCheck() bool { if x != nil { return x.BypassPolicyCheck @@ -2841,7 +2852,7 @@ var File_attestation_v1_crafting_state_proto protoreflect.FileDescriptor const file_attestation_v1_crafting_state_proto_rawDesc = "" + "\n" + - "#attestation/v1/crafting_state.proto\x12\x0eattestation.v1\x1a\x1bbuf/validate/validate.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a)workflowcontract/v1/crafting_schema.proto\"\xbd\x1c\n" + + "#attestation/v1/crafting_state.proto\x12\x0eattestation.v1\x1a\x1bbuf/validate/validate.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a)workflowcontract/v1/crafting_schema.proto\"\x89\x1d\n" + "\vAttestation\x12I\n" + "\x0einitialized_at\x18\x01 \x01(\v2\x1a.google.protobuf.TimestampB\x06\xbaH\x03\xc8\x01\x01R\rinitializedAt\x12;\n" + "\vfinished_at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\n" + @@ -2857,7 +2868,8 @@ const file_attestation_v1_crafting_state_proto_rawDesc = "" + "\x04head\x18\t \x01(\v2\x16.attestation.v1.CommitR\x04head\x12O\n" + "\x12policy_evaluations\x18\n" + " \x03(\v2 .attestation.v1.PolicyEvaluationR\x11policyEvaluations\x129\n" + - "\x19block_on_policy_violation\x18\r \x01(\bR\x16blockOnPolicyViolation\x12.\n" + + "\x19block_on_policy_violation\x18\r \x01(\bR\x16blockOnPolicyViolation\x12J\n" + + "\"contract_block_on_policy_violation\x18\x15 \x01(\bR\x1econtractBlockOnPolicyViolation\x12.\n" + "\x13bypass_policy_check\x18\x0e \x01(\bR\x11bypassPolicyCheck\x12S\n" + "\x0fsigning_options\x18\x0f \x01(\v2*.attestation.v1.Attestation.SigningOptionsR\x0esigningOptions\x12P\n" + "\x12runner_environment\x18\x10 \x01(\v2!.attestation.v1.RunnerEnvironmentR\x11runnerEnvironment\x124\n" + diff --git a/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto b/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto index 7d33b70e9..af35b94cb 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto @@ -142,8 +142,12 @@ 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 (organization setting) bool block_on_policy_violation = 13; + // the workflow contract enforces all of its policies (spec.policies.gate). + // Copied from the contract at init so the renderer and the status output, + // which only see the attestation, can tell the enforcement source. + bool contract_block_on_policy_violation = 21; // 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..a4c476ed9 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,23 @@ func TestPitestInvalidReportIsNotEvaluable(t *testing.T) { _, err := pitestMaterial().GetEvaluableContent("testdata/cobertura.xml", nil) require.ErrorContains(t, err, "invalid PIT report file") } + +func TestAttestationPoliciesEnforced(t *testing.T) { + testCases := []struct { + name string + att *Attestation + expected bool + }{ + {name: "nil attestation", att: nil}, + {name: "no enforcement", att: &Attestation{}}, + {name: "organization enforces", att: &Attestation{BlockOnPolicyViolation: true}, expected: true}, + {name: "contract enforces", att: &Attestation{ContractBlockOnPolicyViolation: true}, expected: true}, + {name: "both enforce", att: &Attestation{BlockOnPolicyViolation: true, ContractBlockOnPolicyViolation: true}, expected: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.expected, tc.att.PoliciesEnforced()) + }) + } +} diff --git a/pkg/attestation/crafter/crafter.go b/pkg/attestation/crafter/crafter.go index c2a6345b5..3f6739443 100644 --- a/pkg/attestation/crafter/crafter.go +++ b/pkg/attestation/crafter/crafter.go @@ -557,6 +557,8 @@ func initialCraftingState(cwd string, opts *InitOpts) (*api.CraftingState, error } } + craftingState.Attestation.ContractBlockOnPolicyViolation = craftingState.GetPolicies().GetGate() + return craftingState, nil } @@ -838,7 +840,7 @@ func (c *Crafter) stageMaterial(ctx context.Context, m *schemaapi.CraftingSchema c.attClient, c.Logger, policies.WithAllowedHostnames(c.CraftingState.Attestation.PoliciesAllowedHostnames...), - policies.WithDefaultGate(c.CraftingState.Attestation.GetBlockOnPolicyViolation()), + policies.WithDefaultGate(c.CraftingState.Attestation.PoliciesEnforced()), policies.WithProjectContext(projectName, projectVersion), ) // crafted.Content is what a crafter that transformed the artifact scanned and @@ -863,7 +865,7 @@ func (c *Crafter) stageMaterial(ctx context.Context, m *schemaapi.CraftingSchema c.attClient, c.Logger, policies.WithAllowedHostnames(c.CraftingState.Attestation.PoliciesAllowedHostnames...), - policies.WithDefaultGate(c.CraftingState.Attestation.GetBlockOnPolicyViolation()), + policies.WithDefaultGate(c.CraftingState.Attestation.PoliciesEnforced()), policies.WithProjectContext(projectName, projectVersion), policies.WithRuntimeInputs(addOptions.runtimeInputs), ) @@ -1119,7 +1121,7 @@ func (c *Crafter) EvaluateAttestationPolicies(ctx context.Context, attestationID // evaluate attestation-level policies pv := policies.NewPolicyVerifier(c.CraftingState.GetPolicies(), c.attClient, c.Logger, policies.WithAllowedHostnames(c.CraftingState.Attestation.PoliciesAllowedHostnames...), - policies.WithDefaultGate(c.CraftingState.Attestation.GetBlockOnPolicyViolation()), + policies.WithDefaultGate(c.CraftingState.Attestation.PoliciesEnforced()), policies.WithEvalPhase(phase), policies.WithProjectContext(projectName, projectVersion), ) @@ -1130,7 +1132,7 @@ func (c *Crafter) EvaluateAttestationPolicies(ctx context.Context, attestationID pgv := policies.NewPolicyGroupVerifier(c.CraftingState.GetPolicyGroups(), c.CraftingState.GetPolicies(), c.attClient, c.Logger, policies.WithAllowedHostnames(c.CraftingState.Attestation.PoliciesAllowedHostnames...), - policies.WithDefaultGate(c.CraftingState.Attestation.GetBlockOnPolicyViolation()), + policies.WithDefaultGate(c.CraftingState.Attestation.PoliciesEnforced()), policies.WithEvalPhase(phase), policies.WithProjectContext(projectName, projectVersion), ) diff --git a/pkg/attestation/crafter/crafter_test.go b/pkg/attestation/crafter/crafter_test.go index 4ab4b0700..1808f3029 100644 --- a/pkg/attestation/crafter/crafter_test.go +++ b/pkg/attestation/crafter/crafter_test.go @@ -272,6 +272,57 @@ func (s *crafterSuite) TestInitPRMode() { } } +func (s *crafterSuite) TestInitContractEnforcement() { + enforcedPolicies := &schemaapi.Policies{Gate: proto.Bool(true)} + + testCases := []struct { + name string + schemaV1 *schemaapi.CraftingSchema + schemaV2 *schemaapi.CraftingSchemaV2 + 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: &schemaapi.CraftingSchemaV2{Spec: &schemaapi.CraftingSchemaV2Spec{Policies: &schemaapi.Policies{Gate: proto.Bool(false)}}}, + }, + { + 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, + })) + + s.Equal(tc.want, c.CraftingState.GetAttestation().GetContractBlockOnPolicyViolation()) + }) + } +} + type testingCrafter struct { *crafter.Crafter } diff --git a/pkg/attestation/renderer/chainloop/v02.go b/pkg/attestation/renderer/chainloop/v02.go index aa68a2862..3642c8b1d 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.PoliciesEnforced() 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..dec6a6bc6 100644 --- a/pkg/attestation/renderer/chainloop/v02_test.go +++ b/pkg/attestation/renderer/chainloop/v02_test.go @@ -519,6 +519,39 @@ func TestPredicatePolicyEvaluationsRef(t *testing.T) { } } +func TestPredicatePolicyCheckBlockingStrategy(t *testing.T) { + testCases := []struct { + name string + org bool + contract bool + wantStrategy PolicyViolationBlockingStrategy + }{ + {name: "advisory when nothing enforces", wantStrategy: PolicyViolationBlockingStrategyAdvisory}, + {name: "enforced by the organization", org: true, wantStrategy: PolicyViolationBlockingStrategyEnforced}, + {name: "enforced by the contract", contract: true, wantStrategy: PolicyViolationBlockingStrategyEnforced}, + } + + 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.org + state.Attestation.ContractBlockOnPolicyViolation = tc.contract + + 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) + }) + } +} + // 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 { From 5bcac7188b95c07b7b268fd368c9c705cb841542 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Sat, 31 Oct 2026 21:46:00 +0100 Subject: [PATCH 3/8] feat(cli): warn when gate: false has no effect Warn at attestation init when a contract policy, policy group or the contract-wide setting sets gate: false while the organization or the contract enforces policies, since enforcement cannot be relaxed. The status output also lists the contract-wide opt-out. Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 44016fe6-1a31-4253-934f-ca70bc4b469d --- app/cli/pkg/action/attestation_init.go | 5 ++++ app/cli/pkg/action/attestation_status.go | 27 ++++++++++++++++--- app/cli/pkg/action/attestation_status_test.go | 17 ++++++++---- .../issue-3762-contract-policy-enforcement.md | 2 +- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/app/cli/pkg/action/attestation_init.go b/app/cli/pkg/action/attestation_init.go index 0d37bad1b..21c1c300d 100644 --- a/app/cli/pkg/action/attestation_init.go +++ b/app/cli/pkg/action/attestation_init.go @@ -333,6 +333,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 { diff --git a/app/cli/pkg/action/attestation_status.go b/app/cli/pkg/action/attestation_status.go index 5cafdd04f..c38ab2993 100644 --- a/app/cli/pkg/action/attestation_status.go +++ b/app/cli/pkg/action/attestation_status.go @@ -19,6 +19,7 @@ import ( "context" "fmt" "slices" + "strings" "time" pbc "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" @@ -205,9 +206,12 @@ func policyEnforcementSources(att *v1.Attestation) []string { return sources } -// ignoredGateOptOuts returns the contract policies and policy groups that set -// `gate: false`, which has no effect when the organization or the contract -// enforces policies, since enforcement only tightens. +// contractGateField names the contract-wide opt-out in the ignored opt-outs +const contractGateField = "spec.policies.gate" + +// 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 ignoredGateOptOuts(state *v1.CraftingState) []string { if !state.GetAttestation().PoliciesEnforced() { return nil @@ -215,6 +219,11 @@ func ignoredGateOptOuts(state *v1.CraftingState) []string { var names []string policies := state.GetPolicies() + // A contract-wide opt-out can only be overridden by the organization + if policies.Gate != nil && !policies.GetGate() && state.GetAttestation().GetBlockOnPolicyViolation() { + names = append(names, contractGateField) + } + for _, att := range slices.Concat(policies.GetMaterials(), policies.GetAttestation()) { if att.Gate != nil && !att.GetGate() { names = append(names, policyAttachmentName(att)) @@ -230,6 +239,18 @@ func ignoredGateOptOuts(state *v1.CraftingState) []string { return names } +// 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 *v1.CraftingState) string { + ignored := ignoredGateOptOuts(state) + if len(ignored) == 0 { + return "" + } + + return fmt.Sprintf("gate: false has no effect on %s because the %s enforces policies, and enforcement cannot be relaxed", + strings.Join(ignored, ", "), strings.Join(policyEnforcementSources(state.GetAttestation()), " and the ")) +} + func policyAttachmentName(att *pbc.PolicyAttachment) string { if ref := att.GetRef(); ref != "" { return ref diff --git a/app/cli/pkg/action/attestation_status_test.go b/app/cli/pkg/action/attestation_status_test.go index 1db04df20..33e95d31c 100644 --- a/app/cli/pkg/action/attestation_status_test.go +++ b/app/cli/pkg/action/attestation_status_test.go @@ -189,6 +189,7 @@ func TestIgnoredGateOptOuts(t *testing.T) { schema := &craftingpb.CraftingSchemaV2{ Spec: &craftingpb.CraftingSchemaV2Spec{ Policies: &craftingpb.Policies{ + Gate: proto.Bool(false), Materials: []*craftingpb.PolicyAttachment{ {Policy: &craftingpb.PolicyAttachment_Ref{Ref: refPolicy}, Gate: proto.Bool(false)}, {Policy: &craftingpb.PolicyAttachment_Ref{Ref: "sbom-present"}}, @@ -209,20 +210,25 @@ func TestIgnoredGateOptOuts(t *testing.T) { ignored := []string{refPolicy, embeddedPolicy, group} testCases := []struct { - name string - att *v1.Attestation - want []string + name string + att *v1.Attestation + want []string + wantWarning string }{ {name: "gate false is honored when nothing enforces", att: &v1.Attestation{}}, { - name: "gate false is ignored when the organization enforces", + name: "gate false is ignored when the organization enforces, contract-wide opt-out included", att: &v1.Attestation{BlockOnPolicyViolation: true}, - want: ignored, + want: append([]string{contractGateField}, ignored...), + wantWarning: "gate: false has no effect on spec.policies.gate, sbom-banned-licenses, embedded-policy, slsa-checks " + + "because the organization enforces policies, and enforcement cannot be relaxed", }, { name: "gate false is ignored when the contract enforces", att: &v1.Attestation{ContractBlockOnPolicyViolation: true}, want: ignored, + wantWarning: "gate: false has no effect on sbom-banned-licenses, embedded-policy, slsa-checks " + + "because the contract enforces policies, and enforcement cannot be relaxed", }, } @@ -233,6 +239,7 @@ func TestIgnoredGateOptOuts(t *testing.T) { Schema: &v1.CraftingState_SchemaV2{SchemaV2: schema}, } assert.Equal(t, tc.want, ignoredGateOptOuts(state)) + assert.Equal(t, tc.wantWarning, IgnoredGateOptOutsWarning(state)) }) } } diff --git a/docs/specs/issue-3762-contract-policy-enforcement.md b/docs/specs/issue-3762-contract-policy-enforcement.md index fee571b1d..ca124b366 100644 --- a/docs/specs/issue-3762-contract-policy-enforcement.md +++ b/docs/specs/issue-3762-contract-policy-enforcement.md @@ -69,7 +69,7 @@ The bypass flag of the push command MUST apply to gates from contract enforcemen 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: organization, contract, or both. 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 user checks or saves the contract, and in the attestation status command. +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 From ed6ffeac77eea97c8288a58ad6c7f614271982fc Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Sat, 31 Oct 2026 21:49:27 +0100 Subject: [PATCH 4/8] test(policies): cover enforcement output and clarify older CLI detection Add table tests for the enforcement rows of attestation status and workflow run describe, and check blocked and has-gates in the renderer under contract enforcement. Clarify in D-006 that the control plane marks only runs whose attestation does not record the enforced strategy. Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 44016fe6-1a31-4253-934f-ca70bc4b469d --- app/cli/cmd/attestation_status_test.go | 63 ++++++++++++++++++- app/cli/cmd/workflow_workflow_run_describe.go | 34 +++++----- .../workflow_workflow_run_describe_test.go | 43 +++++++++++++ .../issue-3762-contract-policy-enforcement.md | 2 +- .../renderer/chainloop/v02_test.go | 13 +++- 5 files changed, 137 insertions(+), 18 deletions(-) diff --git a/app/cli/cmd/attestation_status_test.go b/app/cli/cmd/attestation_status_test.go index 4f119fff5..13fa5a4a6 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,73 @@ package cmd import ( + "bytes" "testing" + "time" "github.com/chainloop-dev/chainloop/app/cli/pkg/action" "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 sources", + status: &action.AttestationStatusResult{ + MustBlockOnPolicyViolations: true, + PolicyEnforcementSources: []string{action.PolicyEnforcementSourceOrganization, action.PolicyEnforcementSourceContract}, + }, + wantContain: []string{strategyRowLabel, "ENFORCED (by organization, contract)"}, + wantAbsent: []string{ignoredRowLabel}, + }, + { + name: "ignored gate opt-outs are listed", + status: &action.AttestationStatusResult{ + MustBlockOnPolicyViolations: true, + PolicyEnforcementSources: []string{action.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 ef77d1b1e..45c4d7486 100644 --- a/app/cli/cmd/workflow_workflow_run_describe.go +++ b/app/cli/cmd/workflow_workflow_run_describe.go @@ -164,20 +164,7 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { } } - // Only show the strategy when it is enforced. Showing "ADVISORY" is misleading - // when individual policies are configured as gates. - if att.PolicyEvaluationStatus.Strategy == action.PolicyViolationBlockingStrategyEnforced { - 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) @@ -192,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/docs/specs/issue-3762-contract-policy-enforcement.md b/docs/specs/issue-3762-contract-policy-enforcement.md index ca124b366..36efa1e05 100644 --- a/docs/specs/issue-3762-contract-policy-enforcement.md +++ b/docs/specs/issue-3762-contract-policy-enforcement.md @@ -144,7 +144,7 @@ The contract stays valid when it has `gate: false`. The system warns as R-006 sa - 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 organization or the contract enforces policies, but the attestation does not record the expected gates. +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. diff --git a/pkg/attestation/renderer/chainloop/v02_test.go b/pkg/attestation/renderer/chainloop/v02_test.go index dec6a6bc6..a12f5d6e6 100644 --- a/pkg/attestation/renderer/chainloop/v02_test.go +++ b/pkg/attestation/renderer/chainloop/v02_test.go @@ -520,15 +520,20 @@ 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 org bool contract bool + bypass bool wantStrategy PolicyViolationBlockingStrategy + wantBlocked bool + wantHasGates bool }{ {name: "advisory when nothing enforces", wantStrategy: PolicyViolationBlockingStrategyAdvisory}, - {name: "enforced by the organization", org: true, wantStrategy: PolicyViolationBlockingStrategyEnforced}, - {name: "enforced by the contract", contract: true, wantStrategy: PolicyViolationBlockingStrategyEnforced}, + {name: "enforced by the organization", org: true, wantStrategy: PolicyViolationBlockingStrategyEnforced, wantBlocked: true, wantHasGates: true}, + {name: "enforced by the contract", contract: true, wantStrategy: PolicyViolationBlockingStrategyEnforced, wantBlocked: true, wantHasGates: true}, + {name: "contract enforcement with bypass", contract: true, bypass: true, wantStrategy: PolicyViolationBlockingStrategyEnforced, wantHasGates: true}, } for _, tc := range testCases { @@ -540,6 +545,7 @@ func TestPredicatePolicyCheckBlockingStrategy(t *testing.T) { require.NoError(t, protojson.Unmarshal(stateRaw, state)) state.Attestation.BlockOnPolicyViolation = tc.org state.Attestation.ContractBlockOnPolicyViolation = tc.contract + state.Attestation.BypassPolicyCheck = tc.bypass renderer := NewChainloopRendererV02(state.Attestation, "dev", "sha256:59e14f1a9de709cdd0e91c36b33e54fcca95f7dba1dc7169a7f81986e02108e5", nil, nil) statement, err := renderer.Statement(context.TODO()) @@ -548,6 +554,9 @@ func TestPredicatePolicyCheckBlockingStrategy(t *testing.T) { 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) }) } } From 42bea231d794908ed007ada251fe3c5676e56d08 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Sat, 31 Oct 2026 21:58:37 +0100 Subject: [PATCH 5/8] refactor(policies): reuse block_on_policy_violation for contract enforcement The attestation records one enforcement value, set at init when the organization or the contract enforces policies, so the renderer, push and control plane need no new field. The status output reads the contract to name the source. Also fix a nil dereference in the ignored opt-out check for contracts without policies, name the v1 contract-wide setting correctly, and reword the warning. Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 44016fe6-1a31-4253-934f-ca70bc4b469d --- app/cli/cmd/attestation_status.go | 2 +- app/cli/cmd/attestation_status_test.go | 8 +- app/cli/pkg/action/attestation_status.go | 51 +++++--- app/cli/pkg/action/attestation_status_test.go | 122 +++++++++++------- .../frontend/attestation/v1/crafting_state.ts | 26 +--- ...attestation.v1.Attestation.jsonschema.json | 12 +- .../attestation.v1.Attestation.schema.json | 12 +- .../issue-3762-contract-policy-enforcement.md | 9 +- .../api/attestation/v1/crafting_state.go | 6 - .../api/attestation/v1/crafting_state.pb.go | 19 +-- .../api/attestation/v1/crafting_state.proto | 7 +- .../api/attestation/v1/crafting_state_test.go | 20 --- pkg/attestation/crafter/crafter.go | 11 +- pkg/attestation/crafter/crafter_test.go | 20 ++- pkg/attestation/renderer/chainloop/v02.go | 2 +- .../renderer/chainloop/v02_test.go | 11 +- 16 files changed, 156 insertions(+), 182 deletions(-) diff --git a/app/cli/cmd/attestation_status.go b/app/cli/cmd/attestation_status.go index 82f1d8a32..57d6e0af9 100644 --- a/app/cli/cmd/attestation_status.go +++ b/app/cli/cmd/attestation_status.go @@ -127,7 +127,7 @@ func attestationStatusTableOutput(status *action.AttestationStatusResult, w io.W // Only show the strategy when it is enforced. Showing "ADVISORY" is misleading // when individual policies are configured as gates. if status.MustBlockOnPolicyViolations { - strategy := fmt.Sprintf("%s (by %s)", action.PolicyViolationBlockingStrategyEnforced, strings.Join(status.PolicyEnforcementSources, ", ")) + strategy := fmt.Sprintf("%s (by %s)", action.PolicyViolationBlockingStrategyEnforced, status.PolicyEnforcementSource) gt.AppendRow(table.Row{"Policy violation strategy", text.FgHiYellow.Sprint(strategy)}) } diff --git a/app/cli/cmd/attestation_status_test.go b/app/cli/cmd/attestation_status_test.go index 13fa5a4a6..1c5e873de 100644 --- a/app/cli/cmd/attestation_status_test.go +++ b/app/cli/cmd/attestation_status_test.go @@ -42,19 +42,19 @@ func TestAttestationStatusPolicyEnforcementRows(t *testing.T) { wantAbsent: []string{strategyRowLabel, action.PolicyViolationBlockingStrategyAdvisory, ignoredRowLabel}, }, { - name: "enforced strategy names its sources", + name: "enforced strategy names its source", status: &action.AttestationStatusResult{ MustBlockOnPolicyViolations: true, - PolicyEnforcementSources: []string{action.PolicyEnforcementSourceOrganization, action.PolicyEnforcementSourceContract}, + PolicyEnforcementSource: action.PolicyEnforcementSourceOrganization, }, - wantContain: []string{strategyRowLabel, "ENFORCED (by organization, contract)"}, + wantContain: []string{strategyRowLabel, "ENFORCED (by organization)"}, wantAbsent: []string{ignoredRowLabel}, }, { name: "ignored gate opt-outs are listed", status: &action.AttestationStatusResult{ MustBlockOnPolicyViolations: true, - PolicyEnforcementSources: []string{action.PolicyEnforcementSourceContract}, + PolicyEnforcementSource: action.PolicyEnforcementSourceContract, IgnoredGateOptOuts: []string{"sbom-banned-licenses", "slsa-checks"}, }, wantContain: []string{ignoredRowLabel, "sbom-banned-licenses, slsa-checks (enforcement cannot be relaxed)"}, diff --git a/app/cli/pkg/action/attestation_status.go b/app/cli/pkg/action/attestation_status.go index c38ab2993..83f703439 100644 --- a/app/cli/pkg/action/attestation_status.go +++ b/app/cli/pkg/action/attestation_status.go @@ -55,8 +55,8 @@ 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"` - // Levels that enforce all policies: organization and/or contract - PolicyEnforcementSources []string `json:"policy_enforcement_sources,omitempty"` + // 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"` @@ -132,8 +132,8 @@ func (action *AttestationStatus) Run(ctx context.Context, attestationID string) DryRun: c.CraftingState.DryRun, Annotations: pbAnnotationsToAction(c.CraftingState.GetAnnotations()), IsPushed: action.isPushed, - MustBlockOnPolicyViolations: att.PoliciesEnforced(), - PolicyEnforcementSources: policyEnforcementSources(att), + MustBlockOnPolicyViolations: att.GetBlockOnPolicyViolation(), + PolicyEnforcementSource: policyEnforcementSource(c.CraftingState.CraftingState), IgnoredGateOptOuts: ignoredGateOptOuts(c.CraftingState.CraftingState), TimestampAuthority: att.GetSigningOptions().GetTimestampAuthorityUrl(), } @@ -193,35 +193,44 @@ const ( PolicyEnforcementSourceContract = "contract" ) -// policyEnforcementSources returns the levels that enforce all the policies of the attestation -func policyEnforcementSources(att *v1.Attestation) []string { - var sources []string - if att.GetBlockOnPolicyViolation() { - sources = append(sources, PolicyEnforcementSourceOrganization) +// policyEnforcementSource returns the level that enforces all the policies of +// the attestation. The attestation records one enforcement flag for both +// levels, so the contract setting tells them apart. When both levels enforce, +// it names the contract. +func policyEnforcementSource(state *v1.CraftingState) string { + switch { + case !state.GetAttestation().GetBlockOnPolicyViolation(): + return "" + case state.GetPolicies().GetGate(): + return PolicyEnforcementSourceContract + default: + return PolicyEnforcementSourceOrganization } - if att.GetContractBlockOnPolicyViolation() { - sources = append(sources, PolicyEnforcementSourceContract) +} + +// contractGateField returns how the contract-wide opt-out is written in the +// contract, which depends on the contract schema version. +func contractGateField(state *v1.CraftingState) string { + if state.GetSchemaV2() != nil { + return "spec.policies.gate" } - return sources + return "policies.gate" } -// contractGateField names the contract-wide opt-out in the ignored opt-outs -const contractGateField = "spec.policies.gate" - // 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 ignoredGateOptOuts(state *v1.CraftingState) []string { - if !state.GetAttestation().PoliciesEnforced() { + if !state.GetAttestation().GetBlockOnPolicyViolation() { return nil } var names []string policies := state.GetPolicies() - // A contract-wide opt-out can only be overridden by the organization - if policies.Gate != nil && !policies.GetGate() && state.GetAttestation().GetBlockOnPolicyViolation() { - names = append(names, contractGateField) + // A contract-wide opt-out with enforcement on means the organization enforces + if policies != nil && policies.Gate != nil && !policies.GetGate() { + names = append(names, contractGateField(state)) } for _, att := range slices.Concat(policies.GetMaterials(), policies.GetAttestation()) { @@ -247,8 +256,8 @@ func IgnoredGateOptOutsWarning(state *v1.CraftingState) string { return "" } - return fmt.Sprintf("gate: false has no effect on %s because the %s enforces policies, and enforcement cannot be relaxed", - strings.Join(ignored, ", "), strings.Join(policyEnforcementSources(state.GetAttestation()), " and the ")) + 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, ", "), policyEnforcementSource(state)) } func policyAttachmentName(att *pbc.PolicyAttachment) string { diff --git a/app/cli/pkg/action/attestation_status_test.go b/app/cli/pkg/action/attestation_status_test.go index 33e95d31c..ab06c1674 100644 --- a/app/cli/pkg/action/attestation_status_test.go +++ b/app/cli/pkg/action/attestation_status_test.go @@ -156,25 +156,34 @@ func TestPopulateContractMaterialsGroups(t *testing.T) { assert.False(t, byName["sbom-spdx"].Required) } -func TestPolicyEnforcementSources(t *testing.T) { +func TestPolicyEnforcementSource(t *testing.T) { + contractV2 := func(gate *bool) *v1.CraftingState_SchemaV2 { + return &v1.CraftingState_SchemaV2{SchemaV2: &craftingpb.CraftingSchemaV2{ + Spec: &craftingpb.CraftingSchemaV2Spec{Policies: &craftingpb.Policies{Gate: gate}}, + }} + } + testCases := []struct { - name string - att *v1.Attestation - want []string + name string + state *v1.CraftingState + want string }{ - {name: "nothing enforces", att: &v1.Attestation{}}, - {name: "organization", att: &v1.Attestation{BlockOnPolicyViolation: true}, want: []string{PolicyEnforcementSourceOrganization}}, - {name: "contract", att: &v1.Attestation{ContractBlockOnPolicyViolation: true}, want: []string{PolicyEnforcementSourceContract}}, + {name: "nothing enforces", state: &v1.CraftingState{Attestation: &v1.Attestation{}, Schema: contractV2(nil)}}, { - name: "both", - att: &v1.Attestation{BlockOnPolicyViolation: true, ContractBlockOnPolicyViolation: true}, - want: []string{PolicyEnforcementSourceOrganization, PolicyEnforcementSourceContract}, + name: "organization", + state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: contractV2(nil)}, + want: PolicyEnforcementSourceOrganization, + }, + { + name: "contract, also when the organization enforces", + state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: contractV2(proto.Bool(true))}, + want: PolicyEnforcementSourceContract, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, policyEnforcementSources(tc.att)) + assert.Equal(t, tc.want, policyEnforcementSource(tc.state)) }) } } @@ -184,62 +193,81 @@ func TestIgnoredGateOptOuts(t *testing.T) { refPolicy = "sbom-banned-licenses" embeddedPolicy = "embedded-policy" group = "slsa-checks" + warningPrefix = "gate: false has no effect on " ) - schema := &craftingpb.CraftingSchemaV2{ - Spec: &craftingpb.CraftingSchemaV2Spec{ - Policies: &craftingpb.Policies{ - Gate: proto.Bool(false), - Materials: []*craftingpb.PolicyAttachment{ - {Policy: &craftingpb.PolicyAttachment_Ref{Ref: refPolicy}, Gate: proto.Bool(false)}, - {Policy: &craftingpb.PolicyAttachment_Ref{Ref: "sbom-present"}}, - }, - Attestation: []*craftingpb.PolicyAttachment{ - { - Policy: &craftingpb.PolicyAttachment_Embedded{Embedded: &craftingpb.Policy{Metadata: &craftingpb.Metadata{Name: embeddedPolicy}}}, - Gate: proto.Bool(false), - }, - }, + policies := func(contractGate bool) *craftingpb.Policies { + return &craftingpb.Policies{ + Gate: proto.Bool(contractGate), + Materials: []*craftingpb.PolicyAttachment{ + {Policy: &craftingpb.PolicyAttachment_Ref{Ref: refPolicy}, Gate: proto.Bool(false)}, + {Policy: &craftingpb.PolicyAttachment_Ref{Ref: "sbom-present"}}, }, - PolicyGroups: []*craftingpb.PolicyGroupAttachment{ - {Ref: group, Gate: proto.Bool(false)}, - {Ref: "sast"}, + Attestation: []*craftingpb.PolicyAttachment{ + { + Policy: &craftingpb.PolicyAttachment_Embedded{Embedded: &craftingpb.Policy{Metadata: &craftingpb.Metadata{Name: embeddedPolicy}}}, + Gate: proto.Bool(false), + }, }, - }, + } + } + groups := []*craftingpb.PolicyGroupAttachment{ + {Ref: group, Gate: proto.Bool(false)}, + {Ref: "sast"}, + } + schemaV2 := func(contractGate bool) *v1.CraftingState_SchemaV2 { + return &v1.CraftingState_SchemaV2{SchemaV2: &craftingpb.CraftingSchemaV2{ + Spec: &craftingpb.CraftingSchemaV2Spec{Policies: policies(contractGate), PolicyGroups: groups}, + }} } ignored := []string{refPolicy, embeddedPolicy, group} testCases := []struct { name string - att *v1.Attestation + state *v1.CraftingState want []string wantWarning string }{ - {name: "gate false is honored when nothing enforces", att: &v1.Attestation{}}, { - name: "gate false is ignored when the organization enforces, contract-wide opt-out included", - att: &v1.Attestation{BlockOnPolicyViolation: true}, - want: append([]string{contractGateField}, ignored...), - wantWarning: "gate: false has no effect on spec.policies.gate, sbom-banned-licenses, embedded-policy, slsa-checks " + - "because the organization enforces policies, and enforcement cannot be relaxed", + name: "gate false is honored when nothing enforces", + state: &v1.CraftingState{Attestation: &v1.Attestation{}, Schema: schemaV2(false)}, + }, + { + name: "gate false is ignored when the organization enforces, contract-wide opt-out included", + state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: schemaV2(false)}, + want: append([]string{"spec.policies.gate"}, ignored...), + wantWarning: warningPrefix + "spec.policies.gate, sbom-banned-licenses, embedded-policy, slsa-checks " + + "because policies are enforced by the organization, and enforcement cannot be relaxed", }, { - name: "gate false is ignored when the contract enforces", - att: &v1.Attestation{ContractBlockOnPolicyViolation: true}, - want: ignored, - wantWarning: "gate: false has no effect on sbom-banned-licenses, embedded-policy, slsa-checks " + - "because the contract enforces policies, and enforcement cannot be relaxed", + name: "gate false is ignored when the contract enforces", + state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: schemaV2(true)}, + want: ignored, + wantWarning: warningPrefix + "sbom-banned-licenses, embedded-policy, slsa-checks " + + "because policies are enforced by the contract, and enforcement cannot be relaxed", + }, + { + name: "v1 contracts name the top-level contract-wide opt-out", + state: &v1.CraftingState{ + Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, + Schema: &v1.CraftingState_InputSchema{InputSchema: &craftingpb.CraftingSchema{ + SchemaVersion: "v1", Policies: &craftingpb.Policies{Gate: proto.Bool(false)}, + }}, + }, + want: []string{"policies.gate"}, + wantWarning: warningPrefix + "policies.gate " + + "because policies are enforced by the organization, and enforcement cannot be relaxed", + }, + { + name: "a contract without policies does not panic", + state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: &v1.CraftingState_SchemaV2{SchemaV2: &craftingpb.CraftingSchemaV2{}}}, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - state := &v1.CraftingState{ - Attestation: tc.att, - Schema: &v1.CraftingState_SchemaV2{SchemaV2: schema}, - } - assert.Equal(t, tc.want, ignoredGateOptOuts(state)) - assert.Equal(t, tc.wantWarning, IgnoredGateOptOutsWarning(state)) + assert.Equal(t, tc.want, ignoredGateOptOuts(tc.state)) + assert.Equal(t, tc.wantWarning, IgnoredGateOptOutsWarning(tc.state)) }) } } 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 6cf732702..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,14 +31,11 @@ export interface Attestation { head?: Commit; /** Policies that materials in this attestation were validated against */ policyEvaluations: PolicyEvaluation[]; - /** fail the attestation if policy evaluation fails (organization setting) */ - blockOnPolicyViolation: boolean; /** - * the workflow contract enforces all of its policies (spec.policies.gate). - * Copied from the contract at init so the renderer and the status output, - * which only see the attestation, can tell the enforcement source. + * fail the attestation if policy evaluation fails. Set at init when the + * organization or the workflow contract (policies.gate) enforces policies. */ - contractBlockOnPolicyViolation: boolean; + blockOnPolicyViolation: boolean; /** bypass policy check */ bypassPolicyCheck: boolean; /** Signing options */ @@ -659,7 +656,6 @@ function createBaseAttestation(): Attestation { head: undefined, policyEvaluations: [], blockOnPolicyViolation: false, - contractBlockOnPolicyViolation: false, bypassPolicyCheck: false, signingOptions: undefined, runnerEnvironment: undefined, @@ -705,9 +701,6 @@ export const Attestation = { if (message.blockOnPolicyViolation === true) { writer.uint32(104).bool(message.blockOnPolicyViolation); } - if (message.contractBlockOnPolicyViolation === true) { - writer.uint32(168).bool(message.contractBlockOnPolicyViolation); - } if (message.bypassPolicyCheck === true) { writer.uint32(112).bool(message.bypassPolicyCheck); } @@ -825,13 +818,6 @@ export const Attestation = { message.blockOnPolicyViolation = reader.bool(); continue; - case 21: - if (tag !== 168) { - break; - } - - message.contractBlockOnPolicyViolation = reader.bool(); - continue; case 14: if (tag !== 112) { break; @@ -920,9 +906,6 @@ export const Attestation = { ? object.policyEvaluations.map((e: any) => PolicyEvaluation.fromJSON(e)) : [], blockOnPolicyViolation: isSet(object.blockOnPolicyViolation) ? Boolean(object.blockOnPolicyViolation) : false, - contractBlockOnPolicyViolation: isSet(object.contractBlockOnPolicyViolation) - ? Boolean(object.contractBlockOnPolicyViolation) - : false, bypassPolicyCheck: isSet(object.bypassPolicyCheck) ? Boolean(object.bypassPolicyCheck) : false, signingOptions: isSet(object.signingOptions) ? Attestation_SigningOptions.fromJSON(object.signingOptions) @@ -972,8 +955,6 @@ export const Attestation = { obj.policyEvaluations = []; } message.blockOnPolicyViolation !== undefined && (obj.blockOnPolicyViolation = message.blockOnPolicyViolation); - message.contractBlockOnPolicyViolation !== undefined && - (obj.contractBlockOnPolicyViolation = message.contractBlockOnPolicyViolation); message.bypassPolicyCheck !== undefined && (obj.bypassPolicyCheck = message.bypassPolicyCheck); message.signingOptions !== undefined && (obj.signingOptions = message.signingOptions ? Attestation_SigningOptions.toJSON(message.signingOptions) @@ -1033,7 +1014,6 @@ export const Attestation = { message.head = (object.head !== undefined && object.head !== null) ? Commit.fromPartial(object.head) : undefined; message.policyEvaluations = object.policyEvaluations?.map((e) => PolicyEvaluation.fromPartial(e)) || []; message.blockOnPolicyViolation = object.blockOnPolicyViolation ?? false; - message.contractBlockOnPolicyViolation = object.contractBlockOnPolicyViolation ?? false; message.bypassPolicyCheck = object.bypassPolicyCheck ?? false; message.signingOptions = (object.signingOptions !== undefined && object.signingOptions !== null) ? Attestation_SigningOptions.fromPartial(object.signingOptions) 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 3a72381b5..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 (organization setting)", + "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)$": { @@ -15,10 +15,6 @@ "$ref": "attestation.v1.Attestation.CASBackend.jsonschema.json", "description": "CAS backend information used during attestation" }, - "^(contract_block_on_policy_violation)$": { - "description": "the workflow contract enforces all of its policies (spec.policies.gate).\n Copied from the contract at init so the renderer and the status output,\n which only see the attestation, can tell the enforcement source.", - "type": "boolean" - }, "^(env_vars)$": { "additionalProperties": { "type": "string" @@ -107,7 +103,7 @@ "description": "Authentication information used during attestation" }, "blockOnPolicyViolation": { - "description": "fail the attestation if policy evaluation fails (organization setting)", + "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": { @@ -118,10 +114,6 @@ "$ref": "attestation.v1.Attestation.CASBackend.jsonschema.json", "description": "CAS backend information used during attestation" }, - "contractBlockOnPolicyViolation": { - "description": "the workflow contract enforces all of its policies (spec.policies.gate).\n Copied from the contract at init so the renderer and the status output,\n which only see the attestation, can tell the enforcement source.", - "type": "boolean" - }, "envVars": { "additionalProperties": { "type": "string" 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 e5859bb00..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 (organization setting)", + "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)$": { @@ -15,10 +15,6 @@ "$ref": "attestation.v1.Attestation.CASBackend.schema.json", "description": "CAS backend information used during attestation" }, - "^(contractBlockOnPolicyViolation)$": { - "description": "the workflow contract enforces all of its policies (spec.policies.gate).\n Copied from the contract at init so the renderer and the status output,\n which only see the attestation, can tell the enforcement source.", - "type": "boolean" - }, "^(envVars)$": { "additionalProperties": { "type": "string" @@ -107,7 +103,7 @@ "description": "Authentication information used during attestation" }, "block_on_policy_violation": { - "description": "fail the attestation if policy evaluation fails (organization setting)", + "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": { @@ -118,10 +114,6 @@ "$ref": "attestation.v1.Attestation.CASBackend.schema.json", "description": "CAS backend information used during attestation" }, - "contract_block_on_policy_violation": { - "description": "the workflow contract enforces all of its policies (spec.policies.gate).\n Copied from the contract at init so the renderer and the status output,\n which only see the attestation, can tell the enforcement source.", - "type": "boolean" - }, "env_vars": { "additionalProperties": { "type": "string" diff --git a/docs/specs/issue-3762-contract-policy-enforcement.md b/docs/specs/issue-3762-contract-policy-enforcement.md index 36efa1e05..1395e94e9 100644 --- a/docs/specs/issue-3762-contract-policy-enforcement.md +++ b/docs/specs/issue-3762-contract-policy-enforcement.md @@ -66,7 +66,7 @@ A contract that does not set the contract enforcement MUST behave as the organiz 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: organization, contract, or both. When neither level enforces, they MUST NOT show an advisory strategy, because single policies can still be gates. +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. @@ -150,6 +150,13 @@ The documentation names the minimum CLI version for contract enforcement. The co - 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. diff --git a/pkg/attestation/crafter/api/attestation/v1/crafting_state.go b/pkg/attestation/crafter/api/attestation/v1/crafting_state.go index 3525885e6..00410aef4 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state.go +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state.go @@ -493,12 +493,6 @@ func (state *CraftingState) GetAnnotations() []*v1.Annotation { } } -// PoliciesEnforced reports whether every policy of the attestation acts as a -// gate, because the organization or the workflow contract enforces policies. -func (a *Attestation) PoliciesEnforced() bool { - return a.GetBlockOnPolicyViolation() || a.GetContractBlockOnPolicyViolation() -} - // 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 17a7c8586..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,12 +171,9 @@ 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 (organization setting) + // 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"` - // the workflow contract enforces all of its policies (spec.policies.gate). - // Copied from the contract at init so the renderer and the status output, - // which only see the attestation, can tell the enforcement source. - ContractBlockOnPolicyViolation bool `protobuf:"varint,21,opt,name=contract_block_on_policy_violation,json=contractBlockOnPolicyViolation,proto3" json:"contract_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"` // Signing options @@ -303,13 +300,6 @@ func (x *Attestation) GetBlockOnPolicyViolation() bool { return false } -func (x *Attestation) GetContractBlockOnPolicyViolation() bool { - if x != nil { - return x.ContractBlockOnPolicyViolation - } - return false -} - func (x *Attestation) GetBypassPolicyCheck() bool { if x != nil { return x.BypassPolicyCheck @@ -2852,7 +2842,7 @@ var File_attestation_v1_crafting_state_proto protoreflect.FileDescriptor const file_attestation_v1_crafting_state_proto_rawDesc = "" + "\n" + - "#attestation/v1/crafting_state.proto\x12\x0eattestation.v1\x1a\x1bbuf/validate/validate.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a)workflowcontract/v1/crafting_schema.proto\"\x89\x1d\n" + + "#attestation/v1/crafting_state.proto\x12\x0eattestation.v1\x1a\x1bbuf/validate/validate.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1egoogle/protobuf/wrappers.proto\x1a)workflowcontract/v1/crafting_schema.proto\"\xbd\x1c\n" + "\vAttestation\x12I\n" + "\x0einitialized_at\x18\x01 \x01(\v2\x1a.google.protobuf.TimestampB\x06\xbaH\x03\xc8\x01\x01R\rinitializedAt\x12;\n" + "\vfinished_at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\n" + @@ -2868,8 +2858,7 @@ const file_attestation_v1_crafting_state_proto_rawDesc = "" + "\x04head\x18\t \x01(\v2\x16.attestation.v1.CommitR\x04head\x12O\n" + "\x12policy_evaluations\x18\n" + " \x03(\v2 .attestation.v1.PolicyEvaluationR\x11policyEvaluations\x129\n" + - "\x19block_on_policy_violation\x18\r \x01(\bR\x16blockOnPolicyViolation\x12J\n" + - "\"contract_block_on_policy_violation\x18\x15 \x01(\bR\x1econtractBlockOnPolicyViolation\x12.\n" + + "\x19block_on_policy_violation\x18\r \x01(\bR\x16blockOnPolicyViolation\x12.\n" + "\x13bypass_policy_check\x18\x0e \x01(\bR\x11bypassPolicyCheck\x12S\n" + "\x0fsigning_options\x18\x0f \x01(\v2*.attestation.v1.Attestation.SigningOptionsR\x0esigningOptions\x12P\n" + "\x12runner_environment\x18\x10 \x01(\v2!.attestation.v1.RunnerEnvironmentR\x11runnerEnvironment\x124\n" + diff --git a/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto b/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto index af35b94cb..3caa49e4e 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state.proto @@ -142,12 +142,9 @@ message Attestation { // Policies that materials in this attestation were validated against repeated PolicyEvaluation policy_evaluations = 10; - // fail the attestation if policy evaluation fails (organization setting) + // 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; - // the workflow contract enforces all of its policies (spec.policies.gate). - // Copied from the contract at init so the renderer and the status output, - // which only see the attestation, can tell the enforcement source. - bool contract_block_on_policy_violation = 21; // 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 a4c476ed9..b7af12f62 100644 --- a/pkg/attestation/crafter/api/attestation/v1/crafting_state_test.go +++ b/pkg/attestation/crafter/api/attestation/v1/crafting_state_test.go @@ -859,23 +859,3 @@ func TestPitestInvalidReportIsNotEvaluable(t *testing.T) { _, err := pitestMaterial().GetEvaluableContent("testdata/cobertura.xml", nil) require.ErrorContains(t, err, "invalid PIT report file") } - -func TestAttestationPoliciesEnforced(t *testing.T) { - testCases := []struct { - name string - att *Attestation - expected bool - }{ - {name: "nil attestation", att: nil}, - {name: "no enforcement", att: &Attestation{}}, - {name: "organization enforces", att: &Attestation{BlockOnPolicyViolation: true}, expected: true}, - {name: "contract enforces", att: &Attestation{ContractBlockOnPolicyViolation: true}, expected: true}, - {name: "both enforce", att: &Attestation{BlockOnPolicyViolation: true, ContractBlockOnPolicyViolation: true}, expected: true}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.expected, tc.att.PoliciesEnforced()) - }) - } -} diff --git a/pkg/attestation/crafter/crafter.go b/pkg/attestation/crafter/crafter.go index 3f6739443..5b64dc471 100644 --- a/pkg/attestation/crafter/crafter.go +++ b/pkg/attestation/crafter/crafter.go @@ -557,7 +557,8 @@ func initialCraftingState(cwd string, opts *InitOpts) (*api.CraftingState, error } } - craftingState.Attestation.ContractBlockOnPolicyViolation = craftingState.GetPolicies().GetGate() + // Enforcement only tightens: the contract can turn it on, but not off + craftingState.Attestation.BlockOnPolicyViolation = opts.BlockOnPolicyViolation || craftingState.GetPolicies().GetGate() return craftingState, nil } @@ -840,7 +841,7 @@ func (c *Crafter) stageMaterial(ctx context.Context, m *schemaapi.CraftingSchema c.attClient, c.Logger, policies.WithAllowedHostnames(c.CraftingState.Attestation.PoliciesAllowedHostnames...), - policies.WithDefaultGate(c.CraftingState.Attestation.PoliciesEnforced()), + policies.WithDefaultGate(c.CraftingState.Attestation.GetBlockOnPolicyViolation()), policies.WithProjectContext(projectName, projectVersion), ) // crafted.Content is what a crafter that transformed the artifact scanned and @@ -865,7 +866,7 @@ func (c *Crafter) stageMaterial(ctx context.Context, m *schemaapi.CraftingSchema c.attClient, c.Logger, policies.WithAllowedHostnames(c.CraftingState.Attestation.PoliciesAllowedHostnames...), - policies.WithDefaultGate(c.CraftingState.Attestation.PoliciesEnforced()), + policies.WithDefaultGate(c.CraftingState.Attestation.GetBlockOnPolicyViolation()), policies.WithProjectContext(projectName, projectVersion), policies.WithRuntimeInputs(addOptions.runtimeInputs), ) @@ -1121,7 +1122,7 @@ func (c *Crafter) EvaluateAttestationPolicies(ctx context.Context, attestationID // evaluate attestation-level policies pv := policies.NewPolicyVerifier(c.CraftingState.GetPolicies(), c.attClient, c.Logger, policies.WithAllowedHostnames(c.CraftingState.Attestation.PoliciesAllowedHostnames...), - policies.WithDefaultGate(c.CraftingState.Attestation.PoliciesEnforced()), + policies.WithDefaultGate(c.CraftingState.Attestation.GetBlockOnPolicyViolation()), policies.WithEvalPhase(phase), policies.WithProjectContext(projectName, projectVersion), ) @@ -1132,7 +1133,7 @@ func (c *Crafter) EvaluateAttestationPolicies(ctx context.Context, attestationID pgv := policies.NewPolicyGroupVerifier(c.CraftingState.GetPolicyGroups(), c.CraftingState.GetPolicies(), c.attClient, c.Logger, policies.WithAllowedHostnames(c.CraftingState.Attestation.PoliciesAllowedHostnames...), - policies.WithDefaultGate(c.CraftingState.Attestation.PoliciesEnforced()), + policies.WithDefaultGate(c.CraftingState.Attestation.GetBlockOnPolicyViolation()), policies.WithEvalPhase(phase), policies.WithProjectContext(projectName, projectVersion), ) diff --git a/pkg/attestation/crafter/crafter_test.go b/pkg/attestation/crafter/crafter_test.go index 1808f3029..f562b8713 100644 --- a/pkg/attestation/crafter/crafter_test.go +++ b/pkg/attestation/crafter/crafter_test.go @@ -279,6 +279,7 @@ func (s *crafterSuite) TestInitContractEnforcement() { name string schemaV1 *schemaapi.CraftingSchema schemaV2 *schemaapi.CraftingSchemaV2 + org bool want bool }{ { @@ -294,6 +295,12 @@ func (s *crafterSuite) TestInitContractEnforcement() { name: "v2 contract with gate false", schemaV2: &schemaapi.CraftingSchemaV2{Spec: &schemaapi.CraftingSchemaV2Spec{Policies: &schemaapi.Policies{Gate: proto.Bool(false)}}}, }, + { + name: "contract gate false does not relax organization enforcement", + schemaV2: &schemaapi.CraftingSchemaV2{Spec: &schemaapi.CraftingSchemaV2Spec{Policies: &schemaapi.Policies{Gate: proto.Bool(false)}}}, + org: true, + want: true, + }, { name: "v2 contract enforcing policies", schemaV2: &schemaapi.CraftingSchemaV2{Spec: &schemaapi.CraftingSchemaV2Spec{Policies: enforcedPolicies}}, @@ -311,14 +318,15 @@ func (s *crafterSuite) TestInitContractEnforcement() { 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, + SchemaV1: tc.schemaV1, + SchemaV2: tc.schemaV2, + WfInfo: s.workflowMetadata, + DryRun: true, + Runner: runner, + BlockOnPolicyViolation: tc.org, })) - s.Equal(tc.want, c.CraftingState.GetAttestation().GetContractBlockOnPolicyViolation()) + s.Equal(tc.want, c.CraftingState.GetAttestation().GetBlockOnPolicyViolation()) }) } } diff --git a/pkg/attestation/renderer/chainloop/v02.go b/pkg/attestation/renderer/chainloop/v02.go index 3642c8b1d..0e20929cb 100644 --- a/pkg/attestation/renderer/chainloop/v02.go +++ b/pkg/attestation/renderer/chainloop/v02.go @@ -290,7 +290,7 @@ func (r *RendererV02) predicate() (*structpb.Struct, error) { return nil, fmt.Errorf("error rendering policy evaluations: %w", err) } - policiesEnforced := r.att.PoliciesEnforced() + policiesEnforced := r.att.GetBlockOnPolicyViolation() policyCheckBlockingStrategy := PolicyViolationBlockingStrategyAdvisory if policiesEnforced { policyCheckBlockingStrategy = PolicyViolationBlockingStrategyEnforced diff --git a/pkg/attestation/renderer/chainloop/v02_test.go b/pkg/attestation/renderer/chainloop/v02_test.go index a12f5d6e6..f2f665cad 100644 --- a/pkg/attestation/renderer/chainloop/v02_test.go +++ b/pkg/attestation/renderer/chainloop/v02_test.go @@ -523,17 +523,15 @@ func TestPredicatePolicyCheckBlockingStrategy(t *testing.T) { // The fixture has one violation on a policy that is not a gate testCases := []struct { name string - org bool - contract bool + enforced bool bypass bool wantStrategy PolicyViolationBlockingStrategy wantBlocked bool wantHasGates bool }{ {name: "advisory when nothing enforces", wantStrategy: PolicyViolationBlockingStrategyAdvisory}, - {name: "enforced by the organization", org: true, wantStrategy: PolicyViolationBlockingStrategyEnforced, wantBlocked: true, wantHasGates: true}, - {name: "enforced by the contract", contract: true, wantStrategy: PolicyViolationBlockingStrategyEnforced, wantBlocked: true, wantHasGates: true}, - {name: "contract enforcement with bypass", contract: true, bypass: true, wantStrategy: PolicyViolationBlockingStrategyEnforced, wantHasGates: true}, + {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 { @@ -543,8 +541,7 @@ func TestPredicatePolicyCheckBlockingStrategy(t *testing.T) { state := &api.CraftingState{} require.NoError(t, protojson.Unmarshal(stateRaw, state)) - state.Attestation.BlockOnPolicyViolation = tc.org - state.Attestation.ContractBlockOnPolicyViolation = tc.contract + state.Attestation.BlockOnPolicyViolation = tc.enforced state.Attestation.BypassPolicyCheck = tc.bypass renderer := NewChainloopRendererV02(state.Attestation, "dev", "sha256:59e14f1a9de709cdd0e91c36b33e54fcca95f7dba1dc7169a7f81986e02108e5", nil, nil) From 0f95c06aed94f741c28efd0e422bac912750fb7b Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Sat, 31 Oct 2026 22:03:40 +0100 Subject: [PATCH 6/8] refactor(policies): move enforcement helpers next to the data they read The enforcement source and the ignored gate: false opt-outs are now methods of the crafting state, so attestation init and status share them without reaching into the status action. The rule that marks a policy status as enforced moves to the renderer policy status, next to DerivePolicyStatusSummary. Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 44016fe6-1a31-4253-934f-ca70bc4b469d --- app/cli/cmd/attestation_status_test.go | 5 +- app/cli/pkg/action/attestation_status.go | 77 +---------- app/cli/pkg/action/attestation_status_test.go | 120 +++--------------- app/controlplane/pkg/biz/workflowrun.go | 28 ++-- .../pkg/biz/workflowrun_enforcement_test.go | 75 ----------- .../api/attestation/v1/crafting_state.go | 74 +++++++++++ .../api/attestation/v1/crafting_state_test.go | 109 ++++++++++++++++ .../renderer/chainloop/policy_status.go | 16 +++ .../renderer/chainloop/policy_status_test.go | 36 ++++++ 9 files changed, 270 insertions(+), 270 deletions(-) delete mode 100644 app/controlplane/pkg/biz/workflowrun_enforcement_test.go diff --git a/app/cli/cmd/attestation_status_test.go b/app/cli/cmd/attestation_status_test.go index 1c5e873de..d05603afc 100644 --- a/app/cli/cmd/attestation_status_test.go +++ b/app/cli/cmd/attestation_status_test.go @@ -20,6 +20,7 @@ import ( "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" ) @@ -45,7 +46,7 @@ func TestAttestationStatusPolicyEnforcementRows(t *testing.T) { name: "enforced strategy names its source", status: &action.AttestationStatusResult{ MustBlockOnPolicyViolations: true, - PolicyEnforcementSource: action.PolicyEnforcementSourceOrganization, + PolicyEnforcementSource: attestationv1.PolicyEnforcementSourceOrganization, }, wantContain: []string{strategyRowLabel, "ENFORCED (by organization)"}, wantAbsent: []string{ignoredRowLabel}, @@ -54,7 +55,7 @@ func TestAttestationStatusPolicyEnforcementRows(t *testing.T) { name: "ignored gate opt-outs are listed", status: &action.AttestationStatusResult{ MustBlockOnPolicyViolations: true, - PolicyEnforcementSource: action.PolicyEnforcementSourceContract, + PolicyEnforcementSource: attestationv1.PolicyEnforcementSourceContract, IgnoredGateOptOuts: []string{"sbom-banned-licenses", "slsa-checks"}, }, wantContain: []string{ignoredRowLabel, "sbom-banned-licenses, slsa-checks (enforcement cannot be relaxed)"}, diff --git a/app/cli/pkg/action/attestation_status.go b/app/cli/pkg/action/attestation_status.go index 83f703439..7e2f97411 100644 --- a/app/cli/pkg/action/attestation_status.go +++ b/app/cli/pkg/action/attestation_status.go @@ -18,7 +18,6 @@ package action import ( "context" "fmt" - "slices" "strings" "time" @@ -133,8 +132,8 @@ func (action *AttestationStatus) Run(ctx context.Context, attestationID string) Annotations: pbAnnotationsToAction(c.CraftingState.GetAnnotations()), IsPushed: action.isPushed, MustBlockOnPolicyViolations: att.GetBlockOnPolicyViolation(), - PolicyEnforcementSource: policyEnforcementSource(c.CraftingState.CraftingState), - IgnoredGateOptOuts: ignoredGateOptOuts(c.CraftingState.CraftingState), + PolicyEnforcementSource: c.CraftingState.PolicyEnforcementSource(), + IgnoredGateOptOuts: c.CraftingState.IgnoredGateOptOuts(), TimestampAuthority: att.GetSigningOptions().GetTimestampAuthorityUrl(), } @@ -188,84 +187,16 @@ func (action *AttestationStatus) Run(ctx context.Context, attestationID string) return res, nil } -const ( - PolicyEnforcementSourceOrganization = "organization" - PolicyEnforcementSourceContract = "contract" -) - -// policyEnforcementSource returns the level that enforces all the policies of -// the attestation. The attestation records one enforcement flag for both -// levels, so the contract setting tells them apart. When both levels enforce, -// it names the contract. -func policyEnforcementSource(state *v1.CraftingState) string { - switch { - case !state.GetAttestation().GetBlockOnPolicyViolation(): - return "" - case state.GetPolicies().GetGate(): - return PolicyEnforcementSourceContract - default: - return PolicyEnforcementSourceOrganization - } -} - -// contractGateField returns how the contract-wide opt-out is written in the -// contract, which depends on the contract schema version. -func contractGateField(state *v1.CraftingState) string { - if state.GetSchemaV2() != nil { - return "spec.policies.gate" - } - - return "policies.gate" -} - -// 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 ignoredGateOptOuts(state *v1.CraftingState) []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 && policies.Gate != nil && !policies.GetGate() { - names = append(names, contractGateField(state)) - } - - for _, att := range slices.Concat(policies.GetMaterials(), policies.GetAttestation()) { - if att.Gate != nil && !att.GetGate() { - names = append(names, policyAttachmentName(att)) - } - } - - for _, group := range state.GetPolicyGroups() { - if group.Gate != nil && !group.GetGate() { - names = append(names, group.GetRef()) - } - } - - return names -} - // 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 *v1.CraftingState) string { - ignored := ignoredGateOptOuts(state) + 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, ", "), policyEnforcementSource(state)) -} - -func policyAttachmentName(att *pbc.PolicyAttachment) string { - if ref := att.GetRef(); ref != "" { - return ref - } - - return att.GetEmbedded().GetMetadata().GetName() + strings.Join(ignored, ", "), state.PolicyEnforcementSource()) } // getPolicyEvaluations retrieves both material-level and attestation-level policy evaluations and returns if it has violations diff --git a/app/cli/pkg/action/attestation_status_test.go b/app/cli/pkg/action/attestation_status_test.go index ab06c1674..57b0cb9c4 100644 --- a/app/cli/pkg/action/attestation_status_test.go +++ b/app/cli/pkg/action/attestation_status_test.go @@ -156,118 +156,38 @@ func TestPopulateContractMaterialsGroups(t *testing.T) { assert.False(t, byName["sbom-spdx"].Required) } -func TestPolicyEnforcementSource(t *testing.T) { - contractV2 := func(gate *bool) *v1.CraftingState_SchemaV2 { - return &v1.CraftingState_SchemaV2{SchemaV2: &craftingpb.CraftingSchemaV2{ - Spec: &craftingpb.CraftingSchemaV2Spec{Policies: &craftingpb.Policies{Gate: gate}}, - }} - } +func TestIgnoredGateOptOutsWarning(t *testing.T) { + gateFalse := []*craftingpb.PolicyAttachment{{Policy: &craftingpb.PolicyAttachment_Ref{Ref: "sbom-banned-licenses"}, Gate: proto.Bool(false)}} testCases := []struct { - name string - state *v1.CraftingState - want string + name string + enforced bool + contractGate bool + want string }{ - {name: "nothing enforces", state: &v1.CraftingState{Attestation: &v1.Attestation{}, Schema: contractV2(nil)}}, + {name: "no warning when nothing enforces"}, { - name: "organization", - state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: contractV2(nil)}, - want: PolicyEnforcementSourceOrganization, + 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, also when the organization enforces", - state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: contractV2(proto.Bool(true))}, - want: PolicyEnforcementSourceContract, + 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) { - assert.Equal(t, tc.want, policyEnforcementSource(tc.state)) - }) - } -} - -func TestIgnoredGateOptOuts(t *testing.T) { - const ( - refPolicy = "sbom-banned-licenses" - embeddedPolicy = "embedded-policy" - group = "slsa-checks" - warningPrefix = "gate: false has no effect on " - ) - - policies := func(contractGate bool) *craftingpb.Policies { - return &craftingpb.Policies{ - Gate: proto.Bool(contractGate), - Materials: []*craftingpb.PolicyAttachment{ - {Policy: &craftingpb.PolicyAttachment_Ref{Ref: refPolicy}, Gate: proto.Bool(false)}, - {Policy: &craftingpb.PolicyAttachment_Ref{Ref: "sbom-present"}}, - }, - Attestation: []*craftingpb.PolicyAttachment{ - { - Policy: &craftingpb.PolicyAttachment_Embedded{Embedded: &craftingpb.Policy{Metadata: &craftingpb.Metadata{Name: embeddedPolicy}}}, - Gate: proto.Bool(false), - }, - }, - } - } - groups := []*craftingpb.PolicyGroupAttachment{ - {Ref: group, Gate: proto.Bool(false)}, - {Ref: "sast"}, - } - schemaV2 := func(contractGate bool) *v1.CraftingState_SchemaV2 { - return &v1.CraftingState_SchemaV2{SchemaV2: &craftingpb.CraftingSchemaV2{ - Spec: &craftingpb.CraftingSchemaV2Spec{Policies: policies(contractGate), PolicyGroups: groups}, - }} - } - ignored := []string{refPolicy, embeddedPolicy, group} - - testCases := []struct { - name string - state *v1.CraftingState - want []string - wantWarning string - }{ - { - name: "gate false is honored when nothing enforces", - state: &v1.CraftingState{Attestation: &v1.Attestation{}, Schema: schemaV2(false)}, - }, - { - name: "gate false is ignored when the organization enforces, contract-wide opt-out included", - state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: schemaV2(false)}, - want: append([]string{"spec.policies.gate"}, ignored...), - wantWarning: warningPrefix + "spec.policies.gate, sbom-banned-licenses, embedded-policy, slsa-checks " + - "because policies are enforced by the organization, and enforcement cannot be relaxed", - }, - { - name: "gate false is ignored when the contract enforces", - state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: schemaV2(true)}, - want: ignored, - wantWarning: warningPrefix + "sbom-banned-licenses, embedded-policy, slsa-checks " + - "because policies are enforced by the contract, and enforcement cannot be relaxed", - }, - { - name: "v1 contracts name the top-level contract-wide opt-out", - state: &v1.CraftingState{ - Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, - Schema: &v1.CraftingState_InputSchema{InputSchema: &craftingpb.CraftingSchema{ - SchemaVersion: "v1", Policies: &craftingpb.Policies{Gate: proto.Bool(false)}, + state := &v1.CraftingState{ + Attestation: &v1.Attestation{BlockOnPolicyViolation: tc.enforced}, + Schema: &v1.CraftingState_SchemaV2{SchemaV2: &craftingpb.CraftingSchemaV2{ + Spec: &craftingpb.CraftingSchemaV2Spec{Policies: &craftingpb.Policies{Gate: proto.Bool(tc.contractGate), Materials: gateFalse}}, }}, - }, - want: []string{"policies.gate"}, - wantWarning: warningPrefix + "policies.gate " + - "because policies are enforced by the organization, and enforcement cannot be relaxed", - }, - { - name: "a contract without policies does not panic", - state: &v1.CraftingState{Attestation: &v1.Attestation{BlockOnPolicyViolation: true}, Schema: &v1.CraftingState_SchemaV2{SchemaV2: &craftingpb.CraftingSchemaV2{}}}, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, ignoredGateOptOuts(tc.state)) - assert.Equal(t, tc.wantWarning, IgnoredGateOptOutsWarning(tc.state)) + } + assert.Equal(t, tc.want, IgnoredGateOptOutsWarning(state)) }) } } diff --git a/app/controlplane/pkg/biz/workflowrun.go b/app/controlplane/pkg/biz/workflowrun.go index 9e03d7ee0..8800046c9 100644 --- a/app/controlplane/pkg/biz/workflowrun.go +++ b/app/controlplane/pkg/biz/workflowrun.go @@ -526,23 +526,6 @@ func (uc *WorkflowRunUseCase) validateAgainstContract(ctx context.Context, run * return schema, nil } -// applyContractEnforcement returns the policy evaluation status with the -// contract enforcement applied. A CLI without support for contract enforcement -// renders the attestation as advisory, so the control plane marks it enforced -// to keep the run status true to the contract. The bool reports whether the -// status changed. -func applyContractEnforcement(status *chainloop.PolicyEvaluationStatus, contractEnforces bool) (*chainloop.PolicyEvaluationStatus, bool) { - if status == nil || !contractEnforces || status.Strategy == chainloop.PolicyViolationBlockingStrategyEnforced { - return status, false - } - - enforced := *status - enforced.Strategy = chainloop.PolicyViolationBlockingStrategyEnforced - enforced.HasGates = true - - return &enforced, true -} - func (uc *WorkflowRunUseCase) SaveAttestation(ctx context.Context, id string, bundle []byte, opts ...SaveAttestationOption) (*v1.Hash, error) { ctx, span := otelx.Start(ctx, workflowRunTracer, "WorkflowRunUseCase.SaveAttestation") defer span.End() @@ -625,9 +608,14 @@ 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. - policyStatus, applied := applyContractEnforcement(predicate.GetPolicyEvaluationStatus(), contractSchema.GetPolicies().GetGate()) - if applied { - uc.logger.Warnf("workflow run %s: the contract enforces policies but the attestation does not, the CLI might not support contract enforcement", runID) + 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() { + var changed bool + if policyStatus, changed = policyStatus.Enforced(); changed { + 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) diff --git a/app/controlplane/pkg/biz/workflowrun_enforcement_test.go b/app/controlplane/pkg/biz/workflowrun_enforcement_test.go deleted file mode 100644 index ee7334d48..000000000 --- a/app/controlplane/pkg/biz/workflowrun_enforcement_test.go +++ /dev/null @@ -1,75 +0,0 @@ -// -// Copyright 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. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package biz - -import ( - "testing" - - "github.com/chainloop-dev/chainloop/pkg/attestation/renderer/chainloop" - "github.com/stretchr/testify/assert" -) - -func TestApplyContractEnforcement(t *testing.T) { - advisory := chainloop.PolicyViolationBlockingStrategyAdvisory - enforced := chainloop.PolicyViolationBlockingStrategyEnforced - - testCases := []struct { - name string - status *chainloop.PolicyEvaluationStatus - contractEnforces bool - want *chainloop.PolicyEvaluationStatus - wantApplied bool - }{ - { - name: "nil status", - status: nil, - want: nil, - }, - { - name: "contract does not enforce", - status: &chainloop.PolicyEvaluationStatus{Strategy: advisory, HasViolations: true}, - want: &chainloop.PolicyEvaluationStatus{Strategy: advisory, HasViolations: true}, - }, - { - name: "attestation already enforced", - status: &chainloop.PolicyEvaluationStatus{Strategy: enforced, HasViolations: true, Blocked: true}, - contractEnforces: true, - want: &chainloop.PolicyEvaluationStatus{Strategy: enforced, HasViolations: true, Blocked: true}, - }, - { - name: "advisory attestation with violations under an enforcing contract", - status: &chainloop.PolicyEvaluationStatus{Strategy: advisory, HasViolations: true}, - contractEnforces: true, - want: &chainloop.PolicyEvaluationStatus{Strategy: enforced, HasViolations: true, HasGates: true}, - wantApplied: true, - }, - { - name: "advisory attestation with a bypass under an enforcing contract", - status: &chainloop.PolicyEvaluationStatus{Strategy: advisory, HasViolations: true, Bypassed: true}, - contractEnforces: true, - want: &chainloop.PolicyEvaluationStatus{Strategy: enforced, HasViolations: true, HasGates: true, Bypassed: true}, - wantApplied: true, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - got, applied := applyContractEnforcement(tc.status, tc.contractEnforces) - assert.Equal(t, tc.want, got) - assert.Equal(t, tc.wantApplied, applied) - }) - } -} 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_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/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) + }) + } +} From 817fbfa3b882f3d2ec474a917ffbf0b15abf9daa Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Sat, 31 Oct 2026 22:09:39 +0100 Subject: [PATCH 7/8] refactor(cli): keep the gate opt-out warning in attestation init Its only caller is attestation init, so the warning and its test move there from the status action. Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 44016fe6-1a31-4253-934f-ca70bc4b469d --- app/cli/pkg/action/attestation_init.go | 15 +++++++- app/cli/pkg/action/attestation_init_test.go | 37 +++++++++++++++++++ app/cli/pkg/action/attestation_status.go | 13 ------- app/cli/pkg/action/attestation_status_test.go | 37 ------------------- 4 files changed, 51 insertions(+), 51 deletions(-) diff --git a/app/cli/pkg/action/attestation_init.go b/app/cli/pkg/action/attestation_init.go index 21c1c300d..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" @@ -334,7 +335,7 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun } // gate: false can not relax organization or contract enforcement (R-006) - if msg := IgnoredGateOptOutsWarning(action.c.CraftingState.CraftingState); msg != "" { + if msg := ignoredGateOptOutsWarning(action.c.CraftingState.CraftingState); msg != "" { action.Logger.Warn().Msg(msg) } @@ -389,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 7e2f97411..6d4c0be14 100644 --- a/app/cli/pkg/action/attestation_status.go +++ b/app/cli/pkg/action/attestation_status.go @@ -18,7 +18,6 @@ package action import ( "context" "fmt" - "strings" "time" pbc "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" @@ -187,18 +186,6 @@ func (action *AttestationStatus) Run(ctx context.Context, attestationID string) return res, nil } -// 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 *v1.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()) -} - // getPolicyEvaluations retrieves both material-level and attestation-level policy evaluations and returns if it has violations func getPolicyEvaluations(c *crafter.Crafter) (map[string][]*PolicyEvaluation, bool) { // grouped by material name diff --git a/app/cli/pkg/action/attestation_status_test.go b/app/cli/pkg/action/attestation_status_test.go index 57b0cb9c4..2a662bf58 100644 --- a/app/cli/pkg/action/attestation_status_test.go +++ b/app/cli/pkg/action/attestation_status_test.go @@ -21,7 +21,6 @@ import ( craftingpb "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" v1 "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" "github.com/stretchr/testify/assert" - "google.golang.org/protobuf/proto" ) func TestPopulateContractMaterials(t *testing.T) { @@ -155,39 +154,3 @@ func TestPopulateContractMaterialsGroups(t *testing.T) { assert.Equal(t, "sbom", byName["sbom-spdx"].Group) assert.False(t, byName["sbom-spdx"].Required) } - -func TestIgnoredGateOptOutsWarning(t *testing.T) { - gateFalse := []*craftingpb.PolicyAttachment{{Policy: &craftingpb.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 := &v1.CraftingState{ - Attestation: &v1.Attestation{BlockOnPolicyViolation: tc.enforced}, - Schema: &v1.CraftingState_SchemaV2{SchemaV2: &craftingpb.CraftingSchemaV2{ - Spec: &craftingpb.CraftingSchemaV2Spec{Policies: &craftingpb.Policies{Gate: proto.Bool(tc.contractGate), Materials: gateFalse}}, - }}, - } - assert.Equal(t, tc.want, IgnoredGateOptOutsWarning(state)) - }) - } -} From c23271556b52988cfdcbf7a193d40249ce3a544b Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 4 Nov 2026 21:26:03 +0100 Subject: [PATCH 8/8] refactor(policies): simplify contract enforcement wiring Set the resolved block_on_policy_violation once in the crafting state, scope the enforced policy status override in SaveAttestation, and share the v2 opt-out contract in the enforcement init test. Refs #3762 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: cf19648f-6bfb-4478-8ce9-4223348384c0 --- app/controlplane/pkg/biz/workflowrun.go | 4 ++-- pkg/attestation/crafter/crafter.go | 11 +++++------ pkg/attestation/crafter/crafter_test.go | 5 +++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/app/controlplane/pkg/biz/workflowrun.go b/app/controlplane/pkg/biz/workflowrun.go index 8800046c9..20ff7070a 100644 --- a/app/controlplane/pkg/biz/workflowrun.go +++ b/app/controlplane/pkg/biz/workflowrun.go @@ -612,8 +612,8 @@ func (uc *WorkflowRunUseCase) SaveAttestation(ctx context.Context, id string, bu // 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() { - var changed bool - if policyStatus, changed = policyStatus.Enforced(); changed { + 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) } } diff --git a/pkg/attestation/crafter/crafter.go b/pkg/attestation/crafter/crafter.go index 5b64dc471..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, diff --git a/pkg/attestation/crafter/crafter_test.go b/pkg/attestation/crafter/crafter_test.go index f562b8713..c2836adc1 100644 --- a/pkg/attestation/crafter/crafter_test.go +++ b/pkg/attestation/crafter/crafter_test.go @@ -274,6 +274,7 @@ 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 @@ -293,11 +294,11 @@ func (s *crafterSuite) TestInitContractEnforcement() { }, { name: "v2 contract with gate false", - schemaV2: &schemaapi.CraftingSchemaV2{Spec: &schemaapi.CraftingSchemaV2Spec{Policies: &schemaapi.Policies{Gate: proto.Bool(false)}}}, + schemaV2: optOutV2, }, { name: "contract gate false does not relax organization enforcement", - schemaV2: &schemaapi.CraftingSchemaV2{Spec: &schemaapi.CraftingSchemaV2Spec{Policies: &schemaapi.Policies{Gate: proto.Bool(false)}}}, + schemaV2: optOutV2, org: true, want: true, },