Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support imageRef field in volatileConfig #1745

Merged
merged 1 commit into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 46 additions & 14 deletions acceptance/kubernetes/stub/stub.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"errors"
"fmt"
"os"
"regexp"
"strings"

"k8s.io/client-go/tools/clientcmd"
Expand All @@ -46,12 +47,56 @@ func (s stubCluster) CreateNamespace(ctx context.Context) (context.Context, erro
return ctx, nil
}

func expandSpecification(ctx context.Context, specification string) (string, error) {
vars := make(map[string]string)
if registry.IsRunning(ctx) {
digests, err := registry.AllDigests(ctx)
if err != nil {
return "", err
}

for repositoryAndTag, digest := range digests {
vars[fmt.Sprintf("REGISTRY_%s_DIGEST", repositoryAndTag)] = digest
}
}

return os.Expand(specification, func(key string) string {
// Handle predefined keys
switch key {
case "GITHOST":
return git.Host(ctx)
case "REGISTRY":
uri, err := registry.Url(ctx)
if err != nil {
panic(err)
}
return uri
}

// Use a regular expression to match and extract dynamic keys
re := regexp.MustCompile(`^REGISTRY_(.+)_DIGEST$`)
matches := re.FindStringSubmatch(key)
if len(matches) == 2 {
if value, ok := vars[key]; ok {
return value
}
}
return ""
}), nil
}

// CreateNamedPolicy stubs a response from the apiserver to fetch a EnterpriseContractPolicy
// custom resource from the `acceptance` namespace with the given name and specification
// the specification part can be templated using ${...} notation and supports
// `GITHOST` and `REGISTRY` variable substitution
func (s stubCluster) CreateNamedPolicy(ctx context.Context, name string, specification string) error {
ns := "acceptance" // TODO: namespace support

specification, err := expandSpecification(ctx, specification)
if err != nil {
return err
}

return wiremock.StubFor(ctx, wiremock.Get(wiremock.URLPathEqualTo(fmt.Sprintf("/apis/appstudio.redhat.com/v1alpha1/namespaces/%s/enterprisecontractpolicies/%s", ns, name))).
WillReturnResponse(wiremock.NewResponse().WithBody(fmt.Sprintf(`{
"apiVersion": "appstudio.redhat.com/v1alpha1",
Expand All @@ -61,20 +106,7 @@ func (s stubCluster) CreateNamedPolicy(ctx context.Context, name string, specifi
"namespace": "%s"
},
"spec": %s
}`, name, ns, os.Expand(specification, func(key string) string {
switch key {
case "GITHOST":
return git.Host(ctx)
case "REGISTRY":
uri, err := registry.Url(ctx)
if err != nil {
panic(err)
}
return uri
}

return ""
}))).WithHeaders(map[string]string{"Content-Type": "application/json"}).WithStatus(200)))
}`, name, ns, specification)).WithHeaders(map[string]string{"Content-Type": "application/json"}).WithStatus(200)))
}

// CreateNamedSnapshot stubs a response from the apiserver to fetch a Snapshot
Expand Down
4 changes: 2 additions & 2 deletions cmd/validate/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ type mockEvaluator struct {
mock.Mock
}

func (e *mockEvaluator) Evaluate(ctx context.Context, inputs []string) ([]evaluator.Outcome, evaluator.Data, error) {
args := e.Called(ctx, inputs)
func (e *mockEvaluator) Evaluate(ctx context.Context, target evaluator.EvaluationTarget) ([]evaluator.Outcome, evaluator.Data, error) {
args := e.Called(ctx, target.Inputs)

return args.Get(0).([]evaluator.Outcome), args.Get(1).(evaluator.Data), args.Error(2)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/validate/image_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func TestEvaluatorLifecycle(t *testing.T) {

validate := func(_ context.Context, component app.SnapshotComponent, _ policy.Policy, evaluators []evaluator.Evaluator, _ bool) (*output.Output, error) {
for _, e := range evaluators {
_, _, err := e.Evaluate(ctx, []string{})
_, _, err := e.Evaluate(ctx, evaluator.EvaluationTarget{Inputs: []string{}})
require.NoError(t, err)
}

Expand Down
101 changes: 101 additions & 0 deletions features/__snapshots__/validate_image.snap
Original file line number Diff line number Diff line change
Expand Up @@ -808,6 +808,107 @@ Error: success criteria not met

---

[policy rule filtering on imageRef:stdout - 1]
{
"success": true,
"components": [
{
"name": "Unnamed",
"containerImage": "${REGISTRY}/acceptance/ec-happy-day@sha256:${REGISTRY_acceptance/ec-happy-day:latest_DIGEST}",
"source": {},
"successes": [
{
"msg": "Pass",
"metadata": {
"code": "builtin.attestation.signature_check"
}
},
{
"msg": "Pass",
"metadata": {
"code": "builtin.attestation.syntax_check"
}
},
{
"msg": "Pass",
"metadata": {
"code": "builtin.image.signature_check"
}
},
{
"msg": "Pass",
"metadata": {
"code": "filtering.always_pass"
}
},
{
"msg": "Pass",
"metadata": {
"code": "filtering.always_pass_with_collection"
}
}
],
"success": true,
"signatures": [
{
"keyid": "",
"sig": "${IMAGE_SIGNATURE_acceptance/ec-happy-day}"
}
],
"attestations": [
{
"type": "https://in-toto.io/Statement/v0.1",
"predicateType": "https://slsa.dev/provenance/v0.2",
"predicateBuildType": "https://tekton.dev/attestations/chains/pipelinerun@v2",
"signatures": [
{
"keyid": "",
"sig": "${ATTESTATION_SIGNATURE_acceptance/ec-happy-day}"
}
]
}
]
}
],
"key": "${known_PUBLIC_KEY_JSON}",
"policy": {
"sources": [
{
"policy": [
"git::https://${GITHOST}/git/happy-day-policy.git"
],
"volatileConfig": {
"exclude": [
{
"value": "filtering.always_fail",
"imageRef": "sha256:${REGISTRY_acceptance/ec-happy-day:latest_DIGEST}"
},
{
"value": "filtering.always_fail_with_collection",
"imageRef": "sha256:${REGISTRY_acceptance/ec-happy-day:latest_DIGEST}"
}
]
}
}
],
"configuration": {
"include": [
"@stamps",
"filtering.always_pass"
]
},
"rekorUrl": "${REKOR}",
"publicKey": "${known_PUBLIC_KEY}"
},
"ec-version": "${EC_VERSION}",
"effective-time": "${TIMESTAMP}"
}
---

[policy rule filtering on imageRef:stderr - 1]

---

[application snapshot reference:stdout - 1]
{
"success": true,
Expand Down
40 changes: 40 additions & 0 deletions features/validate_image.feature
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,46 @@ Feature: evaluate enterprise contract
When ec command is run with "validate image --image ${REGISTRY}/acceptance/ec-happy-day --policy acceptance/ec-policy --public-key ${known_PUBLIC_KEY} --rekor-url ${REKOR} --show-successes"
Then the exit status should be 0
Then the output should match the snapshot

Scenario: policy rule filtering on imageRef
Given a key pair named "known"
Given an image named "acceptance/ec-happy-day"
Given a valid image signature of "acceptance/ec-happy-day" image signed by the "known" key
Given a valid Rekor entry for image signature of "acceptance/ec-happy-day"
Given a valid attestation of "acceptance/ec-happy-day" signed by the "known" key
Given a valid Rekor entry for attestation of "acceptance/ec-happy-day"
Given a git repository named "happy-day-policy" with
| filtering.rego | examples/filtering.rego |
Given policy configuration named "ec-policy" with specification
"""
{
"configuration": {
"include": ["@stamps", "filtering.always_pass"]
},
"sources": [
{
"volatileConfig": {
"exclude": [
{
"value": "filtering.always_fail",
"imageRef": "sha256:${REGISTRY_acceptance/ec-happy-day:latest_DIGEST}"
},
{
"value": "filtering.always_fail_with_collection",
"imageRef": "sha256:${REGISTRY_acceptance/ec-happy-day:latest_DIGEST}"
}
]
},
"policy": [
"git::https://${GITHOST}/git/happy-day-policy.git"
]
}
]
}
"""
When ec command is run with "validate image --image ${REGISTRY}/acceptance/ec-happy-day --policy acceptance/ec-policy --public-key ${known_PUBLIC_KEY} --rekor-url ${REKOR} --show-successes"
Then the exit status should be 0
Then the output should match the snapshot

Scenario: policy rule filtering for successes
Given a key pair named "known"
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ require (
github.com/digitorus/pkcs7 v0.0.0-20230818184609-3a137a874352 // indirect
github.com/digitorus/timestamp v0.0.0-20231217203849-220c5c2851b7 // indirect
github.com/dimchansky/utfbom v1.1.1 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/cli v25.0.3+incompatible // indirect
github.com/docker/distribution v2.8.3+incompatible // indirect
github.com/docker/docker v25.0.5+incompatible // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,8 @@ github.com/digitorus/timestamp v0.0.0-20231217203849-220c5c2851b7 h1:lxmTCgmHE1G
github.com/digitorus/timestamp v0.0.0-20231217203849-220c5c2851b7/go.mod h1:GvWntX9qiTlOud0WkQ6ewFm0LPy5JUR1Xo0Ngbd1w6Y=
github.com/dimchansky/utfbom v1.1.1 h1:vV6w1AhK4VMnhBno/TPVCoK9U/LP0PkLCS9tbxHdi/U=
github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE=
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
github.com/docker/cli v25.0.3+incompatible h1:KLeNs7zws74oFuVhgZQ5ONGZiXUUdgsdy6/EsX/6284=
github.com/docker/cli v25.0.3+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=
Expand Down
3 changes: 2 additions & 1 deletion internal/definition/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/spf13/afero"

"github.com/enterprise-contract/ec-cli/internal/evaluation_target/definition"
"github.com/enterprise-contract/ec-cli/internal/evaluator"
"github.com/enterprise-contract/ec-cli/internal/output"
"github.com/enterprise-contract/ec-cli/internal/policy/source"
"github.com/enterprise-contract/ec-cli/internal/utils"
Expand All @@ -45,7 +46,7 @@ func ValidateDefinition(ctx context.Context, fpath string, sources []source.Poli
return nil, err
}

results, _, err := p.Evaluator.Evaluate(ctx, defFiles)
results, _, err := p.Evaluator.Evaluate(ctx, evaluator.EvaluationTarget{Inputs: defFiles})
if err != nil {
log.Debug("Problem running conftest policy check!")
return nil, err
Expand Down
4 changes: 2 additions & 2 deletions internal/definition/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ type (
badMockEvaluator struct{}
)

func (e mockEvaluator) Evaluate(ctx context.Context, inputs []string) ([]evaluator.Outcome, evaluator.Data, error) {
func (e mockEvaluator) Evaluate(ctx context.Context, target evaluator.EvaluationTarget) ([]evaluator.Outcome, evaluator.Data, error) {
return []evaluator.Outcome{}, nil, nil
}

Expand All @@ -51,7 +51,7 @@ func (e mockEvaluator) CapabilitiesPath() string {
return ""
}

func (b badMockEvaluator) Evaluate(ctx context.Context, inputs []string) ([]evaluator.Outcome, evaluator.Data, error) {
func (b badMockEvaluator) Evaluate(ctx context.Context, target evaluator.EvaluationTarget) ([]evaluator.Outcome, evaluator.Data, error) {
return nil, nil, errors.New("Evaluator error")
}

Expand Down
Loading
Loading