|
| 1 | +// |
| 2 | +// Copyright 2024-2026 The Chainloop Authors. |
| 3 | +// |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// |
| 8 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +// |
| 10 | +// Unless required by applicable law or agreed to in writing, software |
| 11 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +// See the License for the specific language governing permissions and |
| 14 | +// limitations under the License. |
| 15 | + |
| 16 | +package policies |
| 17 | + |
| 18 | +import ( |
| 19 | + "context" |
| 20 | + "os" |
| 21 | + "sync" |
| 22 | + "testing" |
| 23 | + |
| 24 | + v12 "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" |
| 25 | + v1 "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" |
| 26 | + intoto "github.com/in-toto/attestation/go/v1" |
| 27 | + "github.com/rs/zerolog" |
| 28 | + "github.com/stretchr/testify/assert" |
| 29 | + "github.com/stretchr/testify/require" |
| 30 | + "google.golang.org/protobuf/encoding/protojson" |
| 31 | +) |
| 32 | + |
| 33 | +// TestConcurrentVerifyStatement runs VerifyStatement from multiple goroutines |
| 34 | +// to exercise errgroup parallelism and catch race conditions. |
| 35 | +// Run with: go test -race -count=1 -run TestConcurrentVerifyStatement ./pkg/policies/... |
| 36 | +func TestConcurrentVerifyStatement(t *testing.T) { |
| 37 | + logger := zerolog.Nop() |
| 38 | + |
| 39 | + schema := &v12.CraftingSchema{ |
| 40 | + Policies: &v12.Policies{ |
| 41 | + Attestation: []*v12.PolicyAttachment{ |
| 42 | + {Policy: &v12.PolicyAttachment_Ref{Ref: "file://testdata/workflow.yaml"}}, |
| 43 | + {Policy: &v12.PolicyAttachment_Ref{Ref: "file://testdata/materials.yaml"}}, |
| 44 | + }, |
| 45 | + }, |
| 46 | + } |
| 47 | + |
| 48 | + statement := loadStatementForTest(t, "testdata/statement.json") |
| 49 | + |
| 50 | + pv := NewPolicyVerifier(schema.GetPolicies(), nil, &logger) |
| 51 | + |
| 52 | + // Run multiple VerifyStatement calls concurrently |
| 53 | + const goroutines = 10 |
| 54 | + var wg sync.WaitGroup |
| 55 | + errs := make([]error, goroutines) |
| 56 | + results := make([][]*v1.PolicyEvaluation, goroutines) |
| 57 | + |
| 58 | + for i := range goroutines { |
| 59 | + wg.Add(1) |
| 60 | + go func() { |
| 61 | + defer wg.Done() |
| 62 | + res, err := pv.VerifyStatement(context.Background(), statement) |
| 63 | + errs[i] = err |
| 64 | + results[i] = res |
| 65 | + }() |
| 66 | + } |
| 67 | + |
| 68 | + wg.Wait() |
| 69 | + |
| 70 | + // All calls should succeed |
| 71 | + for i := range goroutines { |
| 72 | + assert.NoError(t, errs[i], "goroutine %d failed", i) |
| 73 | + } |
| 74 | + |
| 75 | + // All calls should return the same number of evaluations |
| 76 | + for i := 1; i < goroutines; i++ { |
| 77 | + assert.Equal(t, len(results[0]), len(results[i]), |
| 78 | + "goroutine %d returned different number of evaluations", i) |
| 79 | + } |
| 80 | +} |
| 81 | + |
| 82 | +// TestConcurrentVerifyMaterial runs VerifyMaterial from multiple goroutines. |
| 83 | +func TestConcurrentVerifyMaterial(t *testing.T) { |
| 84 | + logger := zerolog.Nop() |
| 85 | + |
| 86 | + schema := &v12.CraftingSchema{ |
| 87 | + Policies: &v12.Policies{ |
| 88 | + Materials: []*v12.PolicyAttachment{ |
| 89 | + { |
| 90 | + Policy: &v12.PolicyAttachment_Ref{Ref: "file://testdata/materials.yaml"}, |
| 91 | + Selector: &v12.PolicyAttachment_MaterialSelector{Name: "sbom"}, |
| 92 | + }, |
| 93 | + }, |
| 94 | + }, |
| 95 | + } |
| 96 | + |
| 97 | + material := &v1.Attestation_Material{ |
| 98 | + MaterialType: v12.CraftingSchema_Material_SBOM_CYCLONEDX_JSON, |
| 99 | + M: &v1.Attestation_Material_String_{ |
| 100 | + String_: &v1.Attestation_Material_KeyVal{ |
| 101 | + Id: "sbom", |
| 102 | + Value: "testdata/sbom.cyclonedx.json", |
| 103 | + }, |
| 104 | + }, |
| 105 | + } |
| 106 | + |
| 107 | + pv := NewPolicyVerifier(schema.GetPolicies(), nil, &logger) |
| 108 | + |
| 109 | + const goroutines = 10 |
| 110 | + var wg sync.WaitGroup |
| 111 | + errs := make([]error, goroutines) |
| 112 | + results := make([][]*v1.PolicyEvaluation, goroutines) |
| 113 | + |
| 114 | + for i := range goroutines { |
| 115 | + wg.Add(1) |
| 116 | + go func() { |
| 117 | + defer wg.Done() |
| 118 | + res, err := pv.VerifyMaterial(context.Background(), material, "") |
| 119 | + errs[i] = err |
| 120 | + results[i] = res |
| 121 | + }() |
| 122 | + } |
| 123 | + |
| 124 | + wg.Wait() |
| 125 | + |
| 126 | + for i := range goroutines { |
| 127 | + assert.NoError(t, errs[i], "goroutine %d failed", i) |
| 128 | + } |
| 129 | + |
| 130 | + for i := 1; i < goroutines; i++ { |
| 131 | + assert.Equal(t, len(results[0]), len(results[i]), |
| 132 | + "goroutine %d returned different number of evaluations", i) |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +// TestWithMaxConcurrency verifies the WithMaxConcurrency option is applied. |
| 137 | +func TestWithMaxConcurrency(t *testing.T) { |
| 138 | + logger := zerolog.Nop() |
| 139 | + |
| 140 | + // Test default |
| 141 | + pv := NewPolicyVerifier(nil, nil, &logger) |
| 142 | + assert.Greater(t, pv.maxConcurrency, 0, "default maxConcurrency should be positive") |
| 143 | + |
| 144 | + // Test custom value |
| 145 | + pv = NewPolicyVerifier(nil, nil, &logger, WithMaxConcurrency(5)) |
| 146 | + assert.Equal(t, 5, pv.maxConcurrency) |
| 147 | + |
| 148 | + // Test zero defaults to computed default |
| 149 | + pv = NewPolicyVerifier(nil, nil, &logger, WithMaxConcurrency(0)) |
| 150 | + assert.Equal(t, defaultMaxConcurrency, pv.maxConcurrency) |
| 151 | + |
| 152 | + // Test negative defaults to computed default |
| 153 | + pv = NewPolicyVerifier(nil, nil, &logger, WithMaxConcurrency(-1)) |
| 154 | + assert.Equal(t, defaultMaxConcurrency, pv.maxConcurrency) |
| 155 | +} |
| 156 | + |
| 157 | +// TestVerifyStatementWithConcurrencyOne ensures sequential mode (maxConcurrency=1) |
| 158 | +// produces identical results to default parallel mode. |
| 159 | +func TestVerifyStatementWithConcurrencyOne(t *testing.T) { |
| 160 | + logger := zerolog.Nop() |
| 161 | + |
| 162 | + schema := &v12.CraftingSchema{ |
| 163 | + Policies: &v12.Policies{ |
| 164 | + Attestation: []*v12.PolicyAttachment{ |
| 165 | + {Policy: &v12.PolicyAttachment_Ref{Ref: "file://testdata/workflow.yaml"}}, |
| 166 | + {Policy: &v12.PolicyAttachment_Ref{Ref: "file://testdata/materials.yaml"}}, |
| 167 | + }, |
| 168 | + }, |
| 169 | + } |
| 170 | + |
| 171 | + statement := loadStatementForTest(t, "testdata/statement.json") |
| 172 | + |
| 173 | + // Sequential |
| 174 | + pvSeq := NewPolicyVerifier(schema.GetPolicies(), nil, &logger, WithMaxConcurrency(1)) |
| 175 | + seqResults, seqErr := pvSeq.VerifyStatement(context.Background(), statement) |
| 176 | + |
| 177 | + // Parallel (default) |
| 178 | + pvPar := NewPolicyVerifier(schema.GetPolicies(), nil, &logger) |
| 179 | + parResults, parErr := pvPar.VerifyStatement(context.Background(), statement) |
| 180 | + |
| 181 | + require.NoError(t, seqErr) |
| 182 | + require.NoError(t, parErr) |
| 183 | + assert.Equal(t, len(seqResults), len(parResults), |
| 184 | + "sequential and parallel should return same number of evaluations") |
| 185 | + |
| 186 | + // Build name→result maps for comparison (order may differ) |
| 187 | + seqByName := make(map[string]*v1.PolicyEvaluation) |
| 188 | + for _, ev := range seqResults { |
| 189 | + seqByName[ev.Name] = ev |
| 190 | + } |
| 191 | + |
| 192 | + for _, ev := range parResults { |
| 193 | + seqEv, ok := seqByName[ev.Name] |
| 194 | + assert.True(t, ok, "parallel result has policy %q not found in sequential", ev.Name) |
| 195 | + if ok { |
| 196 | + assert.Equal(t, len(seqEv.Violations), len(ev.Violations), |
| 197 | + "policy %q: violation count mismatch", ev.Name) |
| 198 | + assert.Equal(t, seqEv.Skipped, ev.Skipped, |
| 199 | + "policy %q: skipped mismatch", ev.Name) |
| 200 | + } |
| 201 | + } |
| 202 | +} |
| 203 | + |
| 204 | +// TestErrGroupCancellation verifies that when one policy evaluation fails, |
| 205 | +// the errgroup context is cancelled and propagated. |
| 206 | +func TestErrGroupCancellation(t *testing.T) { |
| 207 | + logger := zerolog.Nop() |
| 208 | + |
| 209 | + schema := &v12.CraftingSchema{ |
| 210 | + Policies: &v12.Policies{ |
| 211 | + Attestation: []*v12.PolicyAttachment{ |
| 212 | + {Policy: &v12.PolicyAttachment_Ref{Ref: "file://testdata/workflow.yaml"}}, |
| 213 | + // This policy ref does not exist — will cause an error |
| 214 | + {Policy: &v12.PolicyAttachment_Ref{Ref: "file://testdata/nonexistent_policy.yaml"}}, |
| 215 | + }, |
| 216 | + }, |
| 217 | + } |
| 218 | + |
| 219 | + statement := loadStatementForTest(t, "testdata/statement.json") |
| 220 | + |
| 221 | + pv := NewPolicyVerifier(schema.GetPolicies(), nil, &logger) |
| 222 | + _, err := pv.VerifyStatement(context.Background(), statement) |
| 223 | + |
| 224 | + assert.Error(t, err, "should fail when a policy file does not exist") |
| 225 | + assert.IsType(t, &PolicyError{}, err, "error should be a PolicyError") |
| 226 | +} |
| 227 | + |
| 228 | +func loadStatementForTest(t *testing.T, file string) *intoto.Statement { |
| 229 | + t.Helper() |
| 230 | + stContent, err := os.ReadFile(file) |
| 231 | + require.NoError(t, err) |
| 232 | + var statement intoto.Statement |
| 233 | + err = protojson.Unmarshal(stContent, &statement) |
| 234 | + require.NoError(t, err) |
| 235 | + return &statement |
| 236 | +} |
0 commit comments