diff --git a/pkg/policies/engine/builtins/discover.go b/pkg/policies/engine/builtins/discover.go index e898ba4a4..b6d84754e 100644 --- a/pkg/policies/engine/builtins/discover.go +++ b/pkg/policies/engine/builtins/discover.go @@ -17,9 +17,12 @@ package builtins import ( "context" + "encoding/json" v1 "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) const ( @@ -38,6 +41,23 @@ type DiscoverResult struct { Truncated bool `json:"truncated"` } +// MarshalJSON always writes references as an array, an empty one when there are no references. +// The proto field omits an empty list, and then a policy that counts the references gets an +// undefined value instead of 0. Rego converts the result through this JSON too. +func (r DiscoverResult) MarshalJSON() ([]byte, error) { + refs := r.GetReferences() + if refs == nil { + refs = []*v1.ReferrerItem{} + } + + // the shallower references field hides the one of the embedded item + return json.Marshal(struct { + *v1.ReferrerItem + References []*v1.ReferrerItem `json:"references"` + Truncated bool `json:"truncated"` + }{r.ReferrerItem, refs, r.Truncated}) +} + // DiscoverService wraps the gRPC discover functionality to be shared across engines type DiscoverService struct { client v1.ReferrerServiceClient @@ -60,6 +80,9 @@ func NewDiscoverService(conn *grpc.ClientConn) *DiscoverService { // returns all the references in one response with no next cursor, so the read // ends after the first page. A next cursor that does not advance also ends the // read, so the same page is never merged twice, and marks the result as truncated. +// +// A digest with no node in the graph gives a result with no references. A NotFound on +// a later page is still an error, because the node existed for the first page. func (s *DiscoverService) Discover(ctx context.Context, digest, kind string) (*DiscoverResult, error) { if s.client == nil { return nil, nil @@ -75,6 +98,14 @@ func (s *DiscoverService) Discover(ctx context.Context, digest, kind string) (*D resp, err := readPage("") if err != nil { + // NotFound means that no node of the graph has this digest yet, for example a material + // that no workflow run has attested. Return an empty result with no references, so a + // policy can report it, instead of failing the whole evaluation. A nil result keeps + // meaning "no connection to the control plane". + if status.Code(err) == codes.NotFound { + return &DiscoverResult{ReferrerItem: &v1.ReferrerItem{Digest: digest, Kind: kind}}, nil + } + return nil, err } diff --git a/pkg/policies/engine/builtins/discover_test.go b/pkg/policies/engine/builtins/discover_test.go index 812a83b57..5354fbf56 100644 --- a/pkg/policies/engine/builtins/discover_test.go +++ b/pkg/policies/engine/builtins/discover_test.go @@ -26,10 +26,14 @@ import ( v1 "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" "github.com/open-policy-agent/opa/v1/ast" + "github.com/open-policy-agent/opa/v1/rego" "github.com/open-policy-agent/opa/v1/topdown" + "github.com/open-policy-agent/opa/v1/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // testKind is the kind of the referrer that the tests discover @@ -41,6 +45,8 @@ type fakeReferrerClient struct { v1.ReferrerServiceClient total int failAt int // fail the request with this page number (1-based), 0 means never + // failErr is the error of the failed request, a generic error when nil + failErr error // noPagination acts as a control plane without pagination: it ignores the // pagination request and returns all the references with no pagination response noPagination bool @@ -52,6 +58,9 @@ type fakeReferrerClient struct { func (f *fakeReferrerClient) DiscoverPrivate(_ context.Context, req *v1.ReferrerServiceDiscoverPrivateRequest, _ ...grpc.CallOption) (*v1.ReferrerServiceDiscoverPrivateResponse, error) { f.requests = append(f.requests, req) if f.failAt == len(f.requests) { + if f.failErr != nil { + return nil, f.failErr + } return nil, errors.New("boom") } @@ -191,27 +200,147 @@ func refsJSON(n int) string { return strings.Join(refs, ",") } +func TestDiscoverErrors(t *testing.T) { + notFound := status.Error(codes.NotFound, "artifact or piece of evidence with digest sha256:deadbeef not found") + testCases := []struct { + name string + failAt int + failErr error + wantErr bool + }{ + // the digest has no node in the graph yet: no references, not an error + {name: "not found", failAt: 1, failErr: notFound}, + {name: "unavailable", failAt: 1, failErr: status.Error(codes.Unavailable, "down"), wantErr: true}, + {name: "permission denied", failAt: 1, failErr: status.Error(codes.PermissionDenied, "denied"), wantErr: true}, + {name: "unauthenticated", failAt: 1, failErr: status.Error(codes.Unauthenticated, "no token"), wantErr: true}, + {name: "internal", failAt: 1, failErr: status.Error(codes.Internal, "boom"), wantErr: true}, + {name: "not a gRPC status", failAt: 1, failErr: errors.New("boom"), wantErr: true}, + // the node existed for the first page, so a later NotFound is not "no node yet" + {name: "not found on a later page", failAt: 2, failErr: notFound, wantErr: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + svc := &DiscoverService{client: &fakeReferrerClient{total: 2 * discoverPageSize, failAt: tc.failAt, failErr: tc.failErr}} + + got, err := svc.Discover(context.Background(), "sha256:deadbeef", "") + if tc.wantErr { + require.Error(t, err) + assert.Equal(t, status.Code(tc.failErr), status.Code(err)) + assert.Nil(t, got) + return + } + + require.NoError(t, err) + // an empty result, not nil: nil means no connection to the control plane + require.NotNil(t, got) + assert.Empty(t, got.GetReferences()) + assert.False(t, got.Truncated) + + raw, err := json.Marshal(got) + require.NoError(t, err) + assert.JSONEq(t, `{"digest": "sha256:deadbeef", "references": [], "truncated": false}`, string(raw)) + }) + } +} + +// TestDiscoverBuiltinInRego evaluates a policy that calls the builtin with strict builtin errors, +// as the policy engine does, so a builtin error fails the evaluation +func TestDiscoverBuiltinInRego(t *testing.T) { + const ( + iterQuery = `count([ref | some ref in chainloop.discover("sha256:deadbeef", "").references])` + countQuery = `count(chainloop.discover("sha256:deadbeef", "").references)` + emptyQuery = `count(chainloop.discover("sha256:deadbeef", "").references) == 0` + ) + notFound := status.Error(codes.NotFound, "not found") + testCases := []struct { + name string + query string + client *fakeReferrerClient + want any + wantErr bool + }{ + {name: "references", query: iterQuery, client: &fakeReferrerClient{total: 3}, want: json.Number("3")}, + {name: "references counted directly", query: countQuery, client: &fakeReferrerClient{total: 3}, want: json.Number("3")}, + {name: "digest not found", query: iterQuery, client: &fakeReferrerClient{failAt: 1, failErr: notFound}, want: json.Number("0")}, + // references is an empty array, not absent, so counting it does not make the rule undefined + {name: "digest not found counted directly", query: emptyQuery, client: &fakeReferrerClient{failAt: 1, failErr: notFound}, want: true}, + {name: "node with no references counted directly", query: emptyQuery, client: &fakeReferrerClient{total: 0}, want: true}, + {name: "control plane unavailable", query: iterQuery, client: &fakeReferrerClient{failAt: 1, failErr: status.Error(codes.Unavailable, "down")}, wantErr: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + impl := getDiscoverRegoImpl(&DiscoverService{client: tc.client}) + discover := rego.Function2( + ®o.Function{Name: discoverBuiltinName, Decl: types.NewFunction(types.Args(types.S, types.S), types.A), Nondeterministic: true}, + func(bctx rego.BuiltinContext, digest, kind *ast.Term) (*ast.Term, error) { + var out *ast.Term + err := impl(bctx, []*ast.Term{digest, kind}, func(term *ast.Term) error { out = term; return nil }) + return out, err + }, + ) + + rs, err := rego.New(rego.Query(tc.query), discover, rego.StrictBuiltinErrors(true)).Eval(context.Background()) + if tc.wantErr { + require.Error(t, err) + return + } + + require.NoError(t, err) + require.Len(t, rs, 1) + assert.Equal(t, tc.want, rs[0].Expressions[0].Value) + }) + } +} + func TestDiscoverNoConnection(t *testing.T) { got, err := NewDiscoverService(nil).Discover(context.Background(), "sha256:deadbeef", "") require.NoError(t, err) assert.Nil(t, got) } +// TestDiscoverResultJSONShape checks the JSON that the WASM builtin returns and that Rego sees func TestDiscoverResultJSONShape(t *testing.T) { - res := &DiscoverResult{ - ReferrerItem: &v1.ReferrerItem{ - Digest: "sha256:deadbeef", - Kind: testKind, - References: []*v1.ReferrerItem{{Digest: "sha256:1", Kind: "ATTESTATION"}}, + testCases := []struct { + name string + res *DiscoverResult + want string + }{ + { + name: "references", + res: &DiscoverResult{ReferrerItem: &v1.ReferrerItem{ + Digest: "sha256:deadbeef", + Kind: testKind, + References: []*v1.ReferrerItem{{Digest: "sha256:1", Kind: "ATTESTATION"}}, + }}, + want: `{ + "digest": "sha256:deadbeef", + "kind": "CONTAINER_IMAGE", + "references": [{"digest": "sha256:1", "kind": "ATTESTATION"}], + "truncated": false + }`, + }, + { + name: "no references is an empty array", + res: &DiscoverResult{ReferrerItem: &v1.ReferrerItem{Digest: "sha256:deadbeef", Kind: testKind}}, + want: `{"digest": "sha256:deadbeef", "kind": "CONTAINER_IMAGE", "references": [], "truncated": false}`, + }, + { + name: "no referrer item", + res: &DiscoverResult{Truncated: true}, + want: `{"references": [], "truncated": true}`, }, } - raw, err := json.Marshal(res) - require.NoError(t, err) - assert.JSONEq(t, `{ - "digest": "sha256:deadbeef", - "kind": "CONTAINER_IMAGE", - "references": [{"digest": "sha256:1", "kind": "ATTESTATION"}], - "truncated": false - }`, string(raw)) + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + raw, err := json.Marshal(tc.res) + require.NoError(t, err) + assert.JSONEq(t, tc.want, string(raw)) + + // Rego converts the result through the same JSON + assert.JSONEq(t, tc.want, ast.NewTerm(ast.MustInterfaceToValue(tc.res)).String()) + }) + } }