From b470646a46b4853251c224d709f51d637a203103 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 23 Nov 2026 18:22:50 +0100 Subject: [PATCH 1/2] fix(policies): return no references when discover finds no node The chainloop.discover builtin failed when no node of the graph had the requested digest yet, for example a material that no workflow run has attested. The control plane answers that case with a gRPC NotFound, the builtin returned it as an error, and because policies are evaluated with strict builtin errors the whole policy evaluation failed. Adding the material with chainloop att add failed, even with gate: false, instead of the policy reporting that the material has no upstream run. DiscoverService.Discover now turns a NotFound on the first page into a result with no references and truncated false. This covers both the Rego and the WASM builtins. A nil result still means no connection to the control plane. Every other error, and a NotFound on a later page, still fails as before. Fixes PFM-8307 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 0e3b127c-259e-426a-bf46-54e6f073f9c3 --- pkg/policies/engine/builtins/discover.go | 13 +++ pkg/policies/engine/builtins/discover_test.go | 93 +++++++++++++++++++ 2 files changed, 106 insertions(+) diff --git a/pkg/policies/engine/builtins/discover.go b/pkg/policies/engine/builtins/discover.go index e898ba4a4..aa87ec993 100644 --- a/pkg/policies/engine/builtins/discover.go +++ b/pkg/policies/engine/builtins/discover.go @@ -20,6 +20,8 @@ import ( 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 ( @@ -60,6 +62,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 +80,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..55a055939 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,6 +200,90 @@ 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", "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 query = `count([ref | some ref in chainloop.discover("sha256:deadbeef", "").references])` + testCases := []struct { + name string + client *fakeReferrerClient + want int + wantErr bool + }{ + {name: "references", client: &fakeReferrerClient{total: 3}, want: 3}, + {name: "digest not found", client: &fakeReferrerClient{failAt: 1, failErr: status.Error(codes.NotFound, "not found")}, want: 0}, + {name: "control plane unavailable", 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(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.EqualValues(t, json.Number(strconv.Itoa(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) From c155bc67a68954491135490cf5bcb7862326268b Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 23 Nov 2026 18:31:07 +0100 Subject: [PATCH 2/2] fix(policies): always return references as an array from discover The discover result embeds the proto ReferrerItem, whose references field is omitted from JSON when empty. A policy that checks count(discovered.references) == 0 then got an undefined value and the rule never fired, both for a digest with no node and for a node with no references. DiscoverResult now marshals references as an array, an empty one when there are none. The WASM builtin returns this JSON and Rego converts the result through it, so both see "references": []. A result of null still means no connection to the control plane. Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 0e3b127c-259e-426a-bf46-54e6f073f9c3 --- pkg/policies/engine/builtins/discover.go | 18 +++++ pkg/policies/engine/builtins/discover_test.go | 78 ++++++++++++++----- 2 files changed, 75 insertions(+), 21 deletions(-) diff --git a/pkg/policies/engine/builtins/discover.go b/pkg/policies/engine/builtins/discover.go index aa87ec993..b6d84754e 100644 --- a/pkg/policies/engine/builtins/discover.go +++ b/pkg/policies/engine/builtins/discover.go @@ -17,6 +17,7 @@ package builtins import ( "context" + "encoding/json" v1 "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" "google.golang.org/grpc" @@ -40,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 diff --git a/pkg/policies/engine/builtins/discover_test.go b/pkg/policies/engine/builtins/discover_test.go index 55a055939..5354fbf56 100644 --- a/pkg/policies/engine/builtins/discover_test.go +++ b/pkg/policies/engine/builtins/discover_test.go @@ -239,7 +239,7 @@ func TestDiscoverErrors(t *testing.T) { raw, err := json.Marshal(got) require.NoError(t, err) - assert.JSONEq(t, `{"digest": "sha256:deadbeef", "truncated": false}`, string(raw)) + assert.JSONEq(t, `{"digest": "sha256:deadbeef", "references": [], "truncated": false}`, string(raw)) }) } } @@ -247,16 +247,26 @@ func TestDiscoverErrors(t *testing.T) { // 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 query = `count([ref | some ref in chainloop.discover("sha256:deadbeef", "").references])` + 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 int + want any wantErr bool }{ - {name: "references", client: &fakeReferrerClient{total: 3}, want: 3}, - {name: "digest not found", client: &fakeReferrerClient{failAt: 1, failErr: status.Error(codes.NotFound, "not found")}, want: 0}, - {name: "control plane unavailable", client: &fakeReferrerClient{failAt: 1, failErr: status.Error(codes.Unavailable, "down")}, wantErr: true}, + {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 { @@ -271,7 +281,7 @@ func TestDiscoverBuiltinInRego(t *testing.T) { }, ) - rs, err := rego.New(rego.Query(query), discover, rego.StrictBuiltinErrors(true)).Eval(context.Background()) + rs, err := rego.New(rego.Query(tc.query), discover, rego.StrictBuiltinErrors(true)).Eval(context.Background()) if tc.wantErr { require.Error(t, err) return @@ -279,7 +289,7 @@ func TestDiscoverBuiltinInRego(t *testing.T) { require.NoError(t, err) require.Len(t, rs, 1) - assert.EqualValues(t, json.Number(strconv.Itoa(tc.want)), rs[0].Expressions[0].Value) + assert.Equal(t, tc.want, rs[0].Expressions[0].Value) }) } } @@ -290,21 +300,47 @@ func TestDiscoverNoConnection(t *testing.T) { 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()) + }) + } }