From 11882b88c9c60841f0642855395f797a12078703 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 21:55:45 +0300 Subject: [PATCH 01/15] feat(marketplace): accept @sha256 digest references in tap connect parseOCIRef (CLI) and parseConnectURL (API) now accept a pinned digest reference (oci://host/org/repo@sha256:...), with an optional informational tag before it. The digest must be a full sha256:<64 hex>, the same contract the platform source's digest= reference enforces. A reference carrying only a digest no longer defaults its tag to latest, since the digest is the authoritative reference Flux resolves before any tag. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit b8a129e356d362e4bed9fd3dea6fb035499b7c77) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/tap.go | 30 ++++++++++++++++++++++------ cmd/cozypkg/cmd/tap_test.go | 32 +++++++++++++++++++----------- pkg/registry/core/tap/compute.go | 25 +++++++++++++++++++---- pkg/registry/core/tap/rest_test.go | 21 +++++++++++++++++++- 4 files changed, 85 insertions(+), 23 deletions(-) diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index 9ed4a8c91..8b0fd08c6 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -65,10 +65,18 @@ type ociRef struct { // Repo is the last path segment. Repo string Tag string + // Digest, when set, pins the exact content (sha256:<64 hex>). It takes + // precedence over Tag at pull time (Flux resolves digest before tag), so a + // digest-pinned reference never follows a moved tag. + Digest string } var sanitizeName = regexp.MustCompile(`[^a-z0-9-]+`) +// ociDigestRe matches a full OCI manifest digest (sha256:<64 hex>), the same +// shape the platform source's "digest=" reference enforces. +var ociDigestRe = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) + // parseOCIRef splits an oci:// reference into its URL (without tag), org, repo, // and tag. A missing tag defaults to "latest". func parseOCIRef(ref string) (ociRef, error) { @@ -77,11 +85,20 @@ func parseOCIRef(ref string) (ociRef, error) { } body := strings.TrimPrefix(ref, "oci://") - tag := "" - // Digest pins are not tag-addressable; tap is tag-based for now. - if strings.Contains(body, "@") { - return ociRef{}, fmt.Errorf("digest references are not supported by tap yet; use a tag (oci://host/org/repo:tag)") + // A digest pins the exact content (oci://host/org/repo@sha256:...). An + // optional tag may precede it and is then informational only. The digest + // must be a full sha256:<64 hex>, the same contract the platform source's + // "digest=" reference enforces. + digest := "" + if at := strings.LastIndex(body, "@"); at >= 0 { + digest = body[at+1:] + body = body[:at] + if !ociDigestRe.MatchString(digest) { + return ociRef{}, fmt.Errorf("invalid digest %q in reference %q: want sha256:<64 hex>", digest, ref) + } } + + tag := "" if colon := strings.LastIndex(body, ":"); colon >= 0 && !strings.Contains(body[colon:], "/") { tag = body[colon+1:] body = body[:colon] @@ -96,10 +113,11 @@ func parseOCIRef(ref string) (ociRef, error) { if len(segs) >= 3 { org = segs[len(segs)-2] } - if tag == "" { + // Default to latest only when neither a tag nor a digest pins the content. + if tag == "" && digest == "" { tag = "latest" } - return ociRef{URL: "oci://" + body, Org: org, Repo: repo, Tag: tag}, nil + return ociRef{URL: "oci://" + body, Org: org, Repo: repo, Tag: tag, Digest: digest}, nil } // fluxSourceName is the RFC-1123 name of the OCIRepository tap creates. It diff --git a/cmd/cozypkg/cmd/tap_test.go b/cmd/cozypkg/cmd/tap_test.go index 27d25ff37..2441ea607 100644 --- a/cmd/cozypkg/cmd/tap_test.go +++ b/cmd/cozypkg/cmd/tap_test.go @@ -36,18 +36,26 @@ import ( ) func TestParseOCIRef(t *testing.T) { + const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" cases := []struct { - in string - wantURL, wantOrg, wantRepo, wantTag string - wantErr bool + in string + wantURL, wantOrg, wantRepo, wantTag, wantDigest string + wantErr bool }{ - {"oci://ghcr.io/foo/bar:v1", "oci://ghcr.io/foo/bar", "foo", "bar", "v1", false}, - {"oci://ghcr.io/foo/bar", "oci://ghcr.io/foo/bar", "foo", "bar", "latest", false}, - {"oci://ghcr.io/foo/group/bar:1.2.3", "oci://ghcr.io/foo/group/bar", "group", "bar", "1.2.3", false}, - {"oci://registry.example.com/solo:tag", "oci://registry.example.com/solo", "", "solo", "tag", false}, - {"https://ghcr.io/foo/bar", "", "", "", "", true}, - {"oci://ghcr.io/foo/bar@sha256:abc", "", "", "", "", true}, - {"oci://ghcr.io", "", "", "", "", true}, + {"oci://ghcr.io/foo/bar:v1", "oci://ghcr.io/foo/bar", "foo", "bar", "v1", "", false}, + {"oci://ghcr.io/foo/bar", "oci://ghcr.io/foo/bar", "foo", "bar", "latest", "", false}, + {"oci://ghcr.io/foo/group/bar:1.2.3", "oci://ghcr.io/foo/group/bar", "group", "bar", "1.2.3", "", false}, + {"oci://registry.example.com/solo:tag", "oci://registry.example.com/solo", "", "solo", "tag", "", false}, + // A digest pin is accepted; the tag is left empty (not defaulted to + // latest) because the digest is the authoritative reference. + {"oci://ghcr.io/foo/bar@" + digest, "oci://ghcr.io/foo/bar", "foo", "bar", "", digest, false}, + // A tag may precede the digest; the tag is then informational only. + {"oci://ghcr.io/foo/bar:v1@" + digest, "oci://ghcr.io/foo/bar", "foo", "bar", "v1", digest, false}, + {"https://ghcr.io/foo/bar", "", "", "", "", "", true}, + // A malformed digest (not sha256:<64 hex>) is still rejected. + {"oci://ghcr.io/foo/bar@sha256:abc", "", "", "", "", "", true}, + {"oci://ghcr.io/foo/bar@notadigest", "", "", "", "", "", true}, + {"oci://ghcr.io", "", "", "", "", "", true}, } for _, c := range cases { got, err := parseOCIRef(c.in) @@ -61,8 +69,8 @@ func TestParseOCIRef(t *testing.T) { t.Errorf("parseOCIRef(%q) unexpected error: %v", c.in, err) continue } - if got.URL != c.wantURL || got.Org != c.wantOrg || got.Repo != c.wantRepo || got.Tag != c.wantTag { - t.Errorf("parseOCIRef(%q) = %+v, want url=%q org=%q repo=%q tag=%q", c.in, got, c.wantURL, c.wantOrg, c.wantRepo, c.wantTag) + if got.URL != c.wantURL || got.Org != c.wantOrg || got.Repo != c.wantRepo || got.Tag != c.wantTag || got.Digest != c.wantDigest { + t.Errorf("parseOCIRef(%q) = %+v, want url=%q org=%q repo=%q tag=%q digest=%q", c.in, got, c.wantURL, c.wantOrg, c.wantRepo, c.wantTag, c.wantDigest) } } } diff --git a/pkg/registry/core/tap/compute.go b/pkg/registry/core/tap/compute.go index b4e17f4e0..9df414f76 100644 --- a/pkg/registry/core/tap/compute.go +++ b/pkg/registry/core/tap/compute.go @@ -20,12 +20,18 @@ import ( var sanitizeDNSRe = regexp.MustCompile(`[^a-z0-9-]+`) +var ociDigestRe = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) + // connectTarget is the parsed form of a connect request's oci:// URL. type connectTarget struct { URL string // reference without a tag Org string Repo string Tag string + // Digest, when set, pins the exact content (sha256:<64 hex>); it takes + // precedence over Tag at pull time, so a digest-pinned connect never + // follows a moved tag. Mirrors the CLI's ociRef.Digest. + Digest string // FluxSourceName is the RFC-1123 name of the tap's OCIRepository. The tapped // repository keeps its own declared PackageSource name(s), which are not // known until the artifact is materialized, so the source (this name) is the @@ -41,9 +47,19 @@ func parseConnectURL(url, tagOverride string) (connectTarget, error) { return connectTarget{}, fmt.Errorf("url %q must start with oci://", url) } body := strings.TrimPrefix(url, "oci://") - if strings.Contains(body, "@") { - return connectTarget{}, fmt.Errorf("digest references are not supported; use a tag") + + // A digest pins the exact content (oci://host/org/repo@sha256:...); an + // optional tag may precede it and is then informational only. Mirrors the + // CLI's parseOCIRef so the API and CLI agree on digest handling. + digest := "" + if at := strings.LastIndex(body, "@"); at >= 0 { + digest = body[at+1:] + body = body[:at] + if !ociDigestRe.MatchString(digest) { + return connectTarget{}, fmt.Errorf("invalid digest %q in url %q: want sha256:<64 hex>", digest, url) + } } + tag := tagOverride if colon := strings.LastIndex(body, ":"); colon >= 0 && !strings.Contains(body[colon:], "/") { if tag == "" { @@ -55,11 +71,12 @@ func parseConnectURL(url, tagOverride string) (connectTarget, error) { if len(segs) < 2 { return connectTarget{}, fmt.Errorf("url %q must include a host and a repository path", url) } - t := connectTarget{URL: "oci://" + body, Repo: segs[len(segs)-1], Tag: tag} + t := connectTarget{URL: "oci://" + body, Repo: segs[len(segs)-1], Tag: tag, Digest: digest} if len(segs) >= 3 { t.Org = segs[len(segs)-2] } - if t.Tag == "" { + // Default to latest only when neither a tag nor a digest pins the content. + if t.Tag == "" && digest == "" { t.Tag = "latest" } fluxBase := t.Repo diff --git a/pkg/registry/core/tap/rest_test.go b/pkg/registry/core/tap/rest_test.go index e0ef88962..d05c13512 100644 --- a/pkg/registry/core/tap/rest_test.go +++ b/pkg/registry/core/tap/rest_test.go @@ -240,8 +240,27 @@ func TestParseConnectURL(t *testing.T) { if _, err := parseConnectURL("ghcr.io/foo/bar", ""); err == nil { t.Error("expected error for non-oci url") } + // A malformed digest (not sha256:<64 hex>) is rejected. if _, err := parseConnectURL("oci://ghcr.io/foo/bar@sha256:abc", ""); err == nil { - t.Error("expected error for digest ref") + t.Error("expected error for malformed digest ref") + } + // A valid digest pins the content: the tag is left empty (not defaulted to + // latest), mirroring the CLI's parseOCIRef. + const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" + d, err := parseConnectURL("oci://ghcr.io/foo/bar@"+digest, "") + if err != nil { + t.Fatalf("digest ref err: %v", err) + } + if d.URL != "oci://ghcr.io/foo/bar" || d.Tag != "" || d.Digest != digest || d.FluxSourceName != "tap-foo-bar" { + t.Fatalf("unexpected digest parse: %+v", d) + } + // A tag may precede the digest and is then informational. + td, err := parseConnectURL("oci://ghcr.io/foo/bar:v1@"+digest, "") + if err != nil { + t.Fatalf("tag+digest ref err: %v", err) + } + if td.Tag != "v1" || td.Digest != digest { + t.Fatalf("unexpected tag+digest parse: %+v", td) } } From 6621606ae999a6dbd52e370f0ea029c7a60c9a17 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 21:58:07 +0300 Subject: [PATCH 02/15] feat(marketplace): pin an explicit digest at tap connect (CLI) buildTapOCIRepository now writes spec.ref.digest when the reference carries one, and the pull resolves the artifact by digest so it fetches the exact content regardless of where the tag points. A tag-only reference keeps being pinned to a digest later by the tap materializer; an explicit @sha256 reference is pinned here at connect time, with any tag left informational. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit 840a6005436df903d093237e8b7d6b96b09c5738) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/tap.go | 28 +++++++++++++++++++--------- cmd/cozypkg/cmd/tap_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index 8b0fd08c6..6260e14d0 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -71,6 +71,16 @@ type ociRef struct { Digest string } +// pullRef is the reference to pull: by digest when one is pinned (so the pull +// resolves the exact content regardless of where the tag points), otherwise by +// tag. +func (r ociRef) pullRef() string { + if r.Digest != "" { + return r.URL + "@" + r.Digest + } + return r.URL + ":" + r.Tag +} + var sanitizeName = regexp.MustCompile(`[^a-z0-9-]+`) // ociDigestRe matches a full OCI manifest digest (sha256:<64 hex>), the same @@ -134,8 +144,10 @@ func fluxSourceName(r ociRef) string { } // buildTapOCIRepository mirrors the operator's generateOCIRepository: an -// OCIRepository in cozy-system, 5m interval, optional tag reference, optional -// pull-credential secretRef (the private-tap credential, symmetric with #2472). +// OCIRepository in cozy-system, 5m interval, a tag and/or digest reference, +// optional pull-credential secretRef (the private-tap credential, symmetric +// with #2472). A tag-only reference is pinned to a digest later by the tap +// materializer; an explicit digest is pinned here at connect time. func buildTapOCIRepository(name string, r ociRef, secret string) *sourcev1.OCIRepository { obj := &sourcev1.OCIRepository{ TypeMeta: metav1.TypeMeta{ @@ -152,11 +164,9 @@ func buildTapOCIRepository(name string, r ociRef, secret string) *sourcev1.OCIRe Annotations: map[string]string{tapconst.NameAnnotation: name}, }, Spec: sourcev1.OCIRepositorySpec{ - URL: r.URL, - Interval: metav1.Duration{Duration: 5 * time.Minute}, - Reference: &sourcev1.OCIRepositoryRef{ - Tag: r.Tag, - }, + URL: r.URL, + Interval: metav1.Duration{Duration: 5 * time.Minute}, + Reference: &sourcev1.OCIRepositoryRef{Tag: r.Tag, Digest: r.Digest}, }, } if secret != "" { @@ -279,7 +289,7 @@ runs its charts in your management cluster: tap only sources you trust.`, // Pull first: an unreachable/invalid ref must fail before any cluster // resource is created (no half-created source). - fullRef := ref.URL + ":" + ref.Tag + fullRef := ref.pullRef() dir, cleanup, err := pullOCIArtifact(fullRef) if err != nil { return err @@ -373,7 +383,7 @@ runs its charts in your management cluster: tap only sources you trust.`, _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "warning: could not reset materialization state on OCIRepository/%s: %v\n", srcName, err) } - fmt.Fprintf(cmd.OutOrStdout(), "Tapped %s\n OCIRepository/%s (%s:%s)\n", fullRef, srcName, ref.URL, ref.Tag) + fmt.Fprintf(cmd.OutOrStdout(), "Tapped %s\n OCIRepository/%s\n", fullRef, srcName) for _, n := range names { fmt.Fprintf(cmd.OutOrStdout(), " PackageSource/%s\n", n) } diff --git a/cmd/cozypkg/cmd/tap_test.go b/cmd/cozypkg/cmd/tap_test.go index 2441ea607..c6a6a9309 100644 --- a/cmd/cozypkg/cmd/tap_test.go +++ b/cmd/cozypkg/cmd/tap_test.go @@ -151,6 +151,36 @@ func TestBuildTapOCIRepository(t *testing.T) { if withSecret.Spec.SecretRef == nil || withSecret.Spec.SecretRef.Name != "pull-creds" { t.Fatalf("expected secretRef pull-creds, got %+v", withSecret.Spec.SecretRef) } + + // A digest-pinned reference sets spec.ref.digest; an explicit digest from + // the user is written by the CLI itself (the operator only pins tag refs). + const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" + rd := ociRef{URL: "oci://ghcr.io/foo/bar", Org: "foo", Repo: "bar", Digest: digest} + objd := buildTapOCIRepository("tap-foo-bar", rd, "") + if objd.Spec.Reference == nil || objd.Spec.Reference.Digest != digest { + t.Fatalf("expected digest pin %q, got %+v", digest, objd.Spec.Reference) + } + if objd.Spec.Reference.Tag != "" { + t.Errorf("a digest-only reference must not carry a tag, got %q", objd.Spec.Reference.Tag) + } + // A tag may accompany the digest and is then informational. + rtd := ociRef{URL: "oci://ghcr.io/foo/bar", Repo: "bar", Tag: "v1", Digest: digest} + objtd := buildTapOCIRepository("n", rtd, "") + if objtd.Spec.Reference.Digest != digest || objtd.Spec.Reference.Tag != "v1" { + t.Fatalf("expected tag v1 + digest, got %+v", objtd.Spec.Reference) + } +} + +func TestOCIRefPullRef(t *testing.T) { + const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" + if got := (ociRef{URL: "oci://ghcr.io/foo/bar", Tag: "v1"}).pullRef(); got != "oci://ghcr.io/foo/bar:v1" { + t.Errorf("tag pullRef = %q", got) + } + // A digest is pulled by digest, so the pull resolves the exact content + // regardless of where the tag currently points. + if got := (ociRef{URL: "oci://ghcr.io/foo/bar", Tag: "v1", Digest: digest}).pullRef(); got != "oci://ghcr.io/foo/bar@"+digest { + t.Errorf("digest pullRef = %q", got) + } } // rewritePackageSourceForTap must NOT rename the PackageSource: a tapped From 07cd563436eb6145c3af2bd0ef5d3fac01fe079b Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 22:02:49 +0300 Subject: [PATCH 03/15] fix(marketplace): pin a tag-following tap source to the resolved digest A tapped repository followed a mutable tag: the OCIRepository carried only spec.ref.tag with a 5m interval, so Flux re-pulled whatever the tag pointed at, and a moved tag reached running tenant application instances within the interval. Whoever controlled the tag controlled what ran in the cluster. The materializer now pins the source to the digest Flux resolved for the artifact it just verified: it reads the manifest digest from status.artifact.revision (source-controller formats an OCI tag revision as '@') and writes it to spec.ref.digest, which Flux resolves ahead of the tag. The tag is kept informational. Moving the tag upstream no longer changes what the cluster pulls; an explicit re-connect is required to move the pin. A user-supplied explicit digest is never rewritten, and a revision without a well-formed digest leaves the source following its tag rather than writing a malformed reference. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit c837838cc2b14f18849f5400d48603143fe283ef) Signed-off-by: Myasnikov Daniil --- internal/marketplace/tapconst/tapconst.go | 6 + .../operator/tapmaterializer_reconciler.go | 48 ++++++++ .../tapmaterializer_reconciler_test.go | 105 ++++++++++++++++++ 3 files changed, 159 insertions(+) diff --git a/internal/marketplace/tapconst/tapconst.go b/internal/marketplace/tapconst/tapconst.go index b88b99bf0..aa76a1628 100644 --- a/internal/marketplace/tapconst/tapconst.go +++ b/internal/marketplace/tapconst/tapconst.go @@ -24,6 +24,12 @@ const ( // MaterializedRevisionAnnotation records the artifact revision last // materialized, so an unchanged revision is not re-pulled. MaterializedRevisionAnnotation = "apps.cozystack.io/materialized-revision" + // PinnedDigestAnnotation records the digest the materializer pinned a + // tag-following source to (spec.ref.digest). It distinguishes an operator + // pin, which a re-connect may move, from a user-supplied explicit digest, + // which the operator never rewrites. Cleared by a re-connect so the operator + // re-pins the newly requested tag. + PinnedDigestAnnotation = "apps.cozystack.io/tap-pinned-digest" // MaterializeErrorAnnotation records why the last materialization failed // (e.g. a name collision with a core component), so the failure surfaces on // the Tap resource and dashboard instead of only in the operator log. diff --git a/internal/operator/tapmaterializer_reconciler.go b/internal/operator/tapmaterializer_reconciler.go index a2747db6a..fd4b4994c 100644 --- a/internal/operator/tapmaterializer_reconciler.go +++ b/internal/operator/tapmaterializer_reconciler.go @@ -24,6 +24,7 @@ import ( "net/http" neturl "net/url" "os" + "regexp" "strings" "time" @@ -189,6 +190,13 @@ func (r *TapMaterializerReconciler) Reconcile(ctx context.Context, req ctrl.Requ return ctrl.Result{}, err } + // Pin the resolved digest so the source stops following a mutable tag: the + // tag may move upstream, but the cluster keeps pulling this exact content + // until an explicit re-connect. This runs only after verifyAndExtract + // accepted the artifact, so the digest pinned is the digest of verified + // content. A user-supplied explicit digest is never rewritten. + pinTapDigest(&repo, art.Revision) + // Stamp the revision so an unchanged artifact is not re-pulled every resync. if repo.Annotations == nil { repo.Annotations = map[string]string{} @@ -200,6 +208,46 @@ func (r *TapMaterializerReconciler) Reconcile(ctx context.Context, req ctrl.Requ return ctrl.Result{}, nil } +// manifestDigestRe matches a full OCI manifest digest (sha256:<64 hex>). +var manifestDigestRe = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) + +// pinTapDigest pins a tag-following tap source to the digest Flux resolved for +// the current artifact, so moving the tag upstream no longer changes what the +// cluster pulls. source-controller formats an OCI tag revision as +// '@' and a digest revision as the bare '', so the +// manifest digest is the segment after the last '@'. +// +// A user-supplied explicit digest (ref.digest set without the operator's pin +// annotation) is left untouched: the operator pins only what a tag resolved to, +// or re-pins its own prior pin. A revision without a well-formed digest leaves +// the source following its tag rather than writing a malformed reference (the +// caller requires a non-empty art.Digest, so this is defensive). +func pinTapDigest(repo *sourcev1.OCIRepository, revision string) { + parts := strings.Split(revision, "@") + digest := parts[len(parts)-1] + if !manifestDigestRe.MatchString(digest) { + return + } + ref := repo.Spec.Reference + // A user-supplied explicit digest carries no matching operator pin + // annotation; never rewrite it. + if ref != nil && ref.Digest != "" && repo.Annotations[tapconst.PinnedDigestAnnotation] != ref.Digest { + return + } + if ref != nil && ref.Digest == digest && repo.Annotations[tapconst.PinnedDigestAnnotation] == digest { + return // already pinned to this digest + } + if ref == nil { + ref = &sourcev1.OCIRepositoryRef{} + repo.Spec.Reference = ref + } + ref.Digest = digest + if repo.Annotations == nil { + repo.Annotations = map[string]string{} + } + repo.Annotations[tapconst.PinnedDigestAnnotation] = digest +} + // failMaterialize records a materialization failure (e.g. a name collision with // a core component) on the tap source so it surfaces on the Tap resource and the // dashboard, and emits a warning Event. It deliberately does not stamp the diff --git a/internal/operator/tapmaterializer_reconciler_test.go b/internal/operator/tapmaterializer_reconciler_test.go index ddb124b7c..404ce6e48 100644 --- a/internal/operator/tapmaterializer_reconciler_test.go +++ b/internal/operator/tapmaterializer_reconciler_test.go @@ -18,6 +18,7 @@ package operator import ( "context" + "strings" "testing" fluxmeta "github.com/fluxcd/pkg/apis/meta" @@ -535,3 +536,107 @@ func TestReconcileBlocksNameCollision(t *testing.T) { t.Error("the collision check must not overwrite the foreign PackageSource") } } + +// A tag-following tap source must be pinned to the digest Flux resolved, so it +// stops following a moved tag. The manifest digest is the part of the artifact +// revision after '@' (source-controller formats an OCI tag revision as +// '@'). +func TestReconcilePinsDigestFromTagRevision(t *testing.T) { + scheme := tapScheme(t) + data, digest := tarGz(t, map[string]string{"packages/core/platform/sources/hello.yaml": samplePS}) + manifest := "sha256:" + strings.Repeat("a", 64) + repo := tapRepo(true) + repo.Spec.Reference = &sourcev1.OCIRepositoryRef{Tag: "v1"} + cl := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(repo). + WithStatusSubresource(&sourcev1.OCIRepository{}). + Build() + setArtifact(t, cl, digest, "v1@"+manifest) + + r := materializerFor(scheme, cl, record.NewFakeRecorder(10), &data) + if _, err := r.Reconcile(context.Background(), req()); err != nil { + t.Fatalf("reconcile: %v", err) + } + + var got sourcev1.OCIRepository + if err := cl.Get(context.Background(), req().NamespacedName, &got); err != nil { + t.Fatal(err) + } + if got.Spec.Reference == nil || got.Spec.Reference.Digest != manifest { + t.Fatalf("expected ref.digest pinned to %q, got %+v", manifest, got.Spec.Reference) + } + if got.Spec.Reference.Tag != "v1" { + t.Errorf("tag must stay informational, got %q", got.Spec.Reference.Tag) + } + if got.Annotations[tapconst.PinnedDigestAnnotation] != manifest { + t.Errorf("expected pinned-digest annotation %q, got %v", manifest, got.Annotations) + } +} + +// A user-supplied explicit digest (ref.digest set with no operator pin +// annotation) must never be rewritten by the operator: the operator pins only +// tag-following sources. +func TestReconcileDoesNotRepinUserDigest(t *testing.T) { + scheme := tapScheme(t) + data, digest := tarGz(t, map[string]string{"packages/core/platform/sources/hello.yaml": samplePS}) + userDigest := "sha256:" + strings.Repeat("c", 64) + repo := tapRepo(true) + repo.Spec.Reference = &sourcev1.OCIRepositoryRef{Digest: userDigest} + cl := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(repo). + WithStatusSubresource(&sourcev1.OCIRepository{}). + Build() + // A digest-pinned source reports its revision as the bare digest. + setArtifact(t, cl, digest, userDigest) + + r := materializerFor(scheme, cl, record.NewFakeRecorder(10), &data) + if _, err := r.Reconcile(context.Background(), req()); err != nil { + t.Fatalf("reconcile: %v", err) + } + + var got sourcev1.OCIRepository + if err := cl.Get(context.Background(), req().NamespacedName, &got); err != nil { + t.Fatal(err) + } + if got.Spec.Reference.Digest != userDigest { + t.Errorf("a user-supplied digest must be left as is, got %q", got.Spec.Reference.Digest) + } + if got.Annotations[tapconst.PinnedDigestAnnotation] != "" { + t.Errorf("the operator must not claim a user-supplied digest as its own pin, got %v", got.Annotations) + } +} + +// Once pinned, the source reports its revision as the bare digest; a further +// reconcile must keep the same pin rather than thrash it. +func TestReconcilePinIsIdempotent(t *testing.T) { + scheme := tapScheme(t) + data, digest := tarGz(t, map[string]string{"packages/core/platform/sources/hello.yaml": samplePS}) + manifest := "sha256:" + strings.Repeat("a", 64) + repo := tapRepo(true) + repo.Spec.Reference = &sourcev1.OCIRepositoryRef{Tag: "v1"} + cl := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(repo). + WithStatusSubresource(&sourcev1.OCIRepository{}). + Build() + setArtifact(t, cl, digest, "v1@"+manifest) + r := materializerFor(scheme, cl, record.NewFakeRecorder(10), &data) + if _, err := r.Reconcile(context.Background(), req()); err != nil { + t.Fatalf("first reconcile: %v", err) + } + // Flux re-resolves by digest now and reports the bare-digest revision. + setArtifact(t, cl, digest, manifest) + if _, err := r.Reconcile(context.Background(), req()); err != nil { + t.Fatalf("second reconcile: %v", err) + } + + var got sourcev1.OCIRepository + if err := cl.Get(context.Background(), req().NamespacedName, &got); err != nil { + t.Fatal(err) + } + if got.Spec.Reference.Digest != manifest { + t.Errorf("pin must be stable, got %q", got.Spec.Reference.Digest) + } + if got.Annotations[tapconst.MaterializedRevisionAnnotation] != manifest { + t.Errorf("expected materialized revision stamped to the bare digest, got %q", got.Annotations[tapconst.MaterializedRevisionAnnotation]) + } +} From a31ae909092836130dafcac1b4eaee0b7c78ac33 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 22:06:16 +0300 Subject: [PATCH 04/15] fix(marketplace): preserve verify and reset the pin on repeat connect (API) The connect API replaced the whole OCIRepository spec on a repeat connect, so a spec.verify signature policy added earlier was silently dropped. It now updates url, interval, ref and secretRef from the request while preserving an existing spec.verify: a repeat connect never silently downgrades trust. An explicit digest reference is pinned on the source directly; a tag-only connect is left for the operator to pin. Replacing the whole ref on a repeat connect drops the operator's prior digest pin so the newly requested tag re- resolves, and the pinned-digest annotation is cleared alongside the materialized-revision annotation so the operator re-pins and re-materializes. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit e93db8848027450c2e23d21348409efa641cb6f1) Signed-off-by: Myasnikov Daniil --- pkg/registry/core/tap/rest.go | 40 ++++++++++++++---- pkg/registry/core/tap/rest_test.go | 67 ++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 9 deletions(-) diff --git a/pkg/registry/core/tap/rest.go b/pkg/registry/core/tap/rest.go index 1a3228a2c..b75fde3d9 100644 --- a/pkg/registry/core/tap/rest.go +++ b/pkg/registry/core/tap/rest.go @@ -217,6 +217,15 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation } } + // A connect carries a tag, a digest, or both; an explicit digest is pinned + // here, while a tag-only source is pinned to a digest later by the operator. + refSpec := map[string]any{} + if target.Tag != "" { + refSpec["tag"] = target.Tag + } + if target.Digest != "" { + refSpec["digest"] = target.Digest + } repo := &unstructured.Unstructured{Object: map[string]any{ "apiVersion": "source.toolkit.fluxcd.io/v1", "kind": "OCIRepository", @@ -229,7 +238,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation "spec": map[string]any{ "url": target.URL, "interval": "5m0s", - "ref": map[string]any{"tag": target.Tag}, + "ref": refSpec, }, }} if in.Spec.SecretRef != "" { @@ -255,14 +264,22 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation return nil, apierrors.NewConflict(r.gvr.GroupResource(), target.FluxSourceName, fmt.Errorf("a different repository (%s) is already connected as %q; disconnect it before connecting %s", curURL, target.FluxSourceName, target.URL)) } - // Update only the fields this API owns (spec, the tap label and name - // annotation) on the FETCHED object, so the operator's finalizer survives. - // Clear the materialized-revision annotation so a re-connect re-materializes - // and recovers a PackageSource removed out-of-band since the last - // materialization, the same recovery `cozypkg tap` performs. Connecting - // installs nothing, so this does not re-install an app removed with - // `cozypkg del`. - cur.Object["spec"] = repo.Object["spec"] + // Update the fields this API owns on the FETCHED object, so the operator's + // finalizer survives. Replace url, interval, ref and secretRef from this + // connect, but PRESERVE a spec.verify set earlier (by this API or by an + // admin): a repeat connect must never silently drop a signature-verification + // policy. Replacing the whole ref rather than merging it is deliberate: it + // drops the operator's prior digest pin so the newly requested tag re- + // resolves (the operator re-pins it). A connect that itself carries verify + // overrides the preserved one. + newSpec := map[string]any{} + if existingVerify, ok, _ := unstructured.NestedMap(cur.Object, "spec", "verify"); ok { + newSpec["verify"] = existingVerify + } + for k, v := range repo.Object["spec"].(map[string]any) { + newSpec[k] = v + } + cur.Object["spec"] = newSpec labels := cur.GetLabels() if labels == nil { labels = map[string]string{} @@ -274,7 +291,12 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation ann = map[string]string{} } ann[tapconst.NameAnnotation] = target.FluxSourceName + // Clear the materialized-revision annotation so a re-connect re-materializes + // (recovering a PackageSource removed out-of-band, the same recovery `cozypkg + // tap` performs), and the pinned-digest annotation so the operator re-pins + // the newly requested tag rather than treating the dropped pin as a user digest. delete(ann, tapconst.MaterializedRevisionAnnotation) + delete(ann, tapconst.PinnedDigestAnnotation) cur.SetAnnotations(ann) if _, err := src.Update(ctx, cur, metav1.UpdateOptions{FieldManager: "cozystack-api", DryRun: createDryRun(opts)}); err != nil { return nil, apierrors.NewInternalError(fmt.Errorf("update Flux source for tap %s: %w", target.FluxSourceName, err)) diff --git a/pkg/registry/core/tap/rest_test.go b/pkg/registry/core/tap/rest_test.go index d05c13512..112381b0b 100644 --- a/pkg/registry/core/tap/rest_test.go +++ b/pkg/registry/core/tap/rest_test.go @@ -309,6 +309,73 @@ func TestCreateRepeatPreservesFinalizerAndForcesRematerialize(t *testing.T) { } } +func TestCreatePinsExplicitDigest(t *testing.T) { + const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" + r := fakeREST() + in := &corev1alpha1.Tap{Spec: corev1alpha1.TapSpec{URL: "oci://ghcr.io/foo/bar@" + digest}} + if _, err := r.Create(context.Background(), in, nil, nil); err != nil { + t.Fatalf("create: %v", err) + } + u, err := r.dyn.Resource(gvrOCIRepos).Namespace("cozy-system").Get(context.Background(), "tap-foo-bar", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if got, _, _ := unstructured.NestedString(u.Object, "spec", "ref", "digest"); got != digest { + t.Errorf("explicit digest not pinned on the source: got %q", got) + } + // A digest-only connect must not also follow a tag. + if tag, found, _ := unstructured.NestedString(u.Object, "spec", "ref", "tag"); found && tag != "" { + t.Errorf("digest connect must not set a tag, got %q", tag) + } +} + +func TestCreateRepeatPreservesVerifyAndResetsPin(t *testing.T) { + // A source connected earlier, pinned by the operator to a digest, with a + // signature-verification policy added by an admin. A repeat connect at a new + // tag must: preserve spec.verify (never silently downgrade trust), drop the + // operator's digest pin so the new tag re-resolves, and clear the pin and + // materialized-revision annotations so the operator re-pins and re-materializes. + const oldDigest = "sha256:2222222222222222222222222222222222222222222222222222222222222222" + existing := ociRepoObj("tap-foo-bar") + _ = unstructured.SetNestedField(existing.Object, "oci://ghcr.io/foo/bar", "spec", "url") + _ = unstructured.SetNestedField(existing.Object, oldDigest, "spec", "ref", "digest") + _ = unstructured.SetNestedField(existing.Object, "v1", "spec", "ref", "tag") + _ = unstructured.SetNestedMap(existing.Object, map[string]any{ + "provider": "cosign", + "matchOIDCIdentity": []any{map[string]any{"issuer": "https://token.actions.githubusercontent.com", "subject": "https://github.com/org/repo/.github/workflows/release.yml@refs/tags/v1"}}, + }, "spec", "verify") + existing.SetFinalizers([]string{"apps.cozystack.io/tap-materializer"}) + existing.SetAnnotations(map[string]string{ + "apps.cozystack.io/materialized-revision": "v1@" + oldDigest, + "apps.cozystack.io/tap-pinned-digest": oldDigest, + }) + r := fakeREST(existing) + + in := &corev1alpha1.Tap{Spec: corev1alpha1.TapSpec{URL: "oci://ghcr.io/foo/bar:v2"}} + if _, err := r.Create(context.Background(), in, nil, nil); err != nil { + t.Fatalf("repeat create: %v", err) + } + u, err := r.dyn.Resource(gvrOCIRepos).Namespace("cozy-system").Get(context.Background(), "tap-foo-bar", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if prov, _, _ := unstructured.NestedString(u.Object, "spec", "verify", "provider"); prov != "cosign" { + t.Errorf("spec.verify was dropped on repeat connect: %+v", u.Object["spec"]) + } + if tag, _, _ := unstructured.NestedString(u.Object, "spec", "ref", "tag"); tag != "v2" { + t.Errorf("tag not updated to v2, got %q", tag) + } + if d, found, _ := unstructured.NestedString(u.Object, "spec", "ref", "digest"); found && d != "" { + t.Errorf("operator digest pin must be dropped so the new tag re-resolves, got %q", d) + } + if _, ok := u.GetAnnotations()["apps.cozystack.io/tap-pinned-digest"]; ok { + t.Error("pinned-digest annotation must be cleared on re-connect") + } + if _, ok := u.GetAnnotations()["apps.cozystack.io/materialized-revision"]; ok { + t.Error("materialized-revision annotation must be cleared on re-connect") + } +} + func TestCreateRefusesConflictingURL(t *testing.T) { // A source with the same derived name but a different registry host must not // be silently retargeted. From b326e0badd627e724119e60d993acc993cbd4a77 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 22:07:46 +0300 Subject: [PATCH 05/15] fix(marketplace): reset the operator digest pin on re-tap (CLI) A re-tap applies the OCIRepository under field owner cozypkg via server-side apply, which cannot clear spec.ref.digest once the operator owns it. A tag-based re-tap would therefore leave the source pinned to the old digest and never follow the newly requested tag. After applying, the CLI now clears the operator's digest pin and the pinned-digest annotation for a tag-based re-tap (an explicit-digest re-tap keeps the digest it just set), alongside the materialized-revision annotation, so the operator re-pins the new reference. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit cbd116b40d3fd40a3a43cfbf57c58efd388a763e) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/tap.go | 40 +++++++++++++++++++++++--------- cmd/cozypkg/cmd/tap_test.go | 46 ++++++++++++++++++++++++++++++++----- 2 files changed, 69 insertions(+), 17 deletions(-) diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index 6260e14d0..3f844bfc7 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -209,21 +209,38 @@ func rewritePackageSourceForTap(ps *cozyv1alpha1.PackageSource, sourceName, sour } } -// clearMaterializedRevision removes the operator's materialized-revision -// annotation from the tap's OCIRepository, so the next reconcile does not -// short-circuit on the unchanged artifact revision and re-materializes its -// PackageSources (recovering one removed out-of-band). A no-op when the source or -// the annotation is absent. -func clearMaterializedRevision(ctx context.Context, k8sClient client.Client, srcName string) error { +// resetTapPinState prepares a tap's OCIRepository for a re-tap. It clears the +// materialized-revision annotation so the next reconcile does not short-circuit +// on the unchanged revision and re-materializes its PackageSources (recovering +// one removed out-of-band), and the pinned-digest annotation so the operator +// re-pins the newly requested reference. For a tag-based re-tap (explicitDigest +// false) it also drops the operator's prior digest pin from spec.ref: a +// server-side apply under field owner cozypkg cannot clear a field the operator +// owns, so a moved tag would otherwise stay pinned to the old digest. An +// explicit-digest re-tap keeps the digest the apply itself set. A no-op (and no +// error) when the source is absent or there is nothing to clear. +func resetTapPinState(ctx context.Context, k8sClient client.Client, srcName string, explicitDigest bool) error { reg := &sourcev1.OCIRepository{} if err := k8sClient.Get(ctx, client.ObjectKey{Name: srcName, Namespace: cozySystemNamespace}, reg); err != nil { return client.IgnoreNotFound(err) } - if _, ok := reg.Annotations[tapconst.MaterializedRevisionAnnotation]; !ok { + base := reg.DeepCopy() + changed := false + if _, ok := reg.Annotations[tapconst.MaterializedRevisionAnnotation]; ok { + delete(reg.Annotations, tapconst.MaterializedRevisionAnnotation) + changed = true + } + if _, ok := reg.Annotations[tapconst.PinnedDigestAnnotation]; ok { + delete(reg.Annotations, tapconst.PinnedDigestAnnotation) + changed = true + } + if !explicitDigest && reg.Spec.Reference != nil && reg.Spec.Reference.Digest != "" { + reg.Spec.Reference.Digest = "" + changed = true + } + if !changed { return nil } - base := reg.DeepCopy() - delete(reg.Annotations, tapconst.MaterializedRevisionAnnotation) return k8sClient.Patch(ctx, reg, client.MergeFrom(base)) } @@ -378,8 +395,9 @@ runs its charts in your management cluster: tap only sources you trust.`, // PackageSource removed out-of-band since the last materialization. Tapping // no longer installs anything, so a re-tap does NOT re-install an app removed // with `cozypkg del`; re-install it with `cozypkg add`. A first tap has no - // such annotation, so this is a no-op then. - if err := clearMaterializedRevision(ctx, k8sClient, srcName); err != nil { + // such annotation, so this is a no-op then. resetTapPinState also drops the + // operator's prior digest pin so the newly requested tag re-resolves. + if err := resetTapPinState(ctx, k8sClient, srcName, ref.Digest != ""); err != nil { _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "warning: could not reset materialization state on OCIRepository/%s: %v\n", srcName, err) } diff --git a/cmd/cozypkg/cmd/tap_test.go b/cmd/cozypkg/cmd/tap_test.go index c6a6a9309..d57e75b2e 100644 --- a/cmd/cozypkg/cmd/tap_test.go +++ b/cmd/cozypkg/cmd/tap_test.go @@ -317,16 +317,23 @@ func TestCreatePackageIdempotent(t *testing.T) { } } -func TestClearMaterializedRevision(t *testing.T) { +func TestResetTapPinState(t *testing.T) { s := untapScheme(t) + const oldDigest = "sha256:2222222222222222222222222222222222222222222222222222222222222222" oci := &sourcev1.OCIRepository{ObjectMeta: metav1.ObjectMeta{ Name: "tap-acme-hello", Namespace: "cozy-system", - Annotations: map[string]string{tapconst.MaterializedRevisionAnnotation: "rev-1", "keep": "me"}, - }} + Annotations: map[string]string{ + tapconst.MaterializedRevisionAnnotation: "v1@" + oldDigest, + tapconst.PinnedDigestAnnotation: oldDigest, + "keep": "me", + }, + }, Spec: sourcev1.OCIRepositorySpec{Reference: &sourcev1.OCIRepositoryRef{Tag: "v1", Digest: oldDigest}}} cl := fake.NewClientBuilder().WithScheme(s).WithObjects(oci).Build() - if err := clearMaterializedRevision(context.Background(), cl, "tap-acme-hello"); err != nil { - t.Fatalf("clear: %v", err) + // A tag-based re-tap must drop the operator's digest pin (cozypkg cannot + // clear a field the operator owns via server-side apply) and both annotations. + if err := resetTapPinState(context.Background(), cl, "tap-acme-hello", false); err != nil { + t.Fatalf("reset: %v", err) } var got sourcev1.OCIRepository if err := cl.Get(context.Background(), client.ObjectKey{Name: "tap-acme-hello", Namespace: "cozy-system"}, &got); err != nil { @@ -335,11 +342,38 @@ func TestClearMaterializedRevision(t *testing.T) { if _, ok := got.Annotations[tapconst.MaterializedRevisionAnnotation]; ok { t.Error("materialized-revision annotation must be cleared to force re-materialization") } + if _, ok := got.Annotations[tapconst.PinnedDigestAnnotation]; ok { + t.Error("pinned-digest annotation must be cleared so the operator re-pins") + } + if got.Spec.Reference != nil && got.Spec.Reference.Digest != "" { + t.Errorf("a tag re-tap must drop the operator digest pin, got %q", got.Spec.Reference.Digest) + } + if got.Spec.Reference == nil || got.Spec.Reference.Tag != "v1" { + t.Errorf("the tag must be left in place, got %+v", got.Spec.Reference) + } if got.Annotations["keep"] != "me" { t.Error("unrelated annotations must be preserved") } + + // An explicit-digest re-tap must NOT drop the digest the CLI itself set. + oci2 := &sourcev1.OCIRepository{ObjectMeta: metav1.ObjectMeta{ + Name: "tap-acme-two", Namespace: "cozy-system", + Annotations: map[string]string{tapconst.MaterializedRevisionAnnotation: oldDigest}, + }, Spec: sourcev1.OCIRepositorySpec{Reference: &sourcev1.OCIRepositoryRef{Digest: oldDigest}}} + cl2 := fake.NewClientBuilder().WithScheme(s).WithObjects(oci2).Build() + if err := resetTapPinState(context.Background(), cl2, "tap-acme-two", true); err != nil { + t.Fatalf("reset explicit: %v", err) + } + var got2 sourcev1.OCIRepository + if err := cl2.Get(context.Background(), client.ObjectKey{Name: "tap-acme-two", Namespace: "cozy-system"}, &got2); err != nil { + t.Fatal(err) + } + if got2.Spec.Reference == nil || got2.Spec.Reference.Digest != oldDigest { + t.Errorf("an explicit-digest re-tap must keep its digest, got %+v", got2.Spec.Reference) + } + // Absent source: no error. - if err := clearMaterializedRevision(context.Background(), cl, "missing"); err != nil { + if err := resetTapPinState(context.Background(), cl, "missing", false); err != nil { t.Errorf("a missing source must not error, got %v", err) } } From 9fb9ae400017fbbd0af4e3569d2e6da7d9d0ec4b Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 22:14:32 +0300 Subject: [PATCH 06/15] feat(marketplace): accept a signature-verification policy at tap connect A tap can now carry a keyless cosign verification policy (spec.verify), so a reference is only pulled when signed by the recorded identity. The CLI takes --certificate-identity and --certificate-oidc-issuer (both required together, mirroring validate); the API takes spec.verify.{issuer,subject} on the Tap connect object. Both map to a Flux OCIRepository verify block with provider cosign and a matchOIDCIdentity entry. A half-configured policy (only one of the identity pair) is refused rather than set, since a policy that matched any signer is worse than none. A key-based policy an admin sets on the source by hand is preserved across repeat connects. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit c56b9876f488cdcb7ae6a74e43a1ac2f702db254) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/tap.go | 33 +++++++++++++- cmd/cozypkg/cmd/tap_test.go | 44 +++++++++++++++++-- pkg/apis/core/v1alpha1/tap_types.go | 19 ++++++++ .../core/v1alpha1/zz_generated.deepcopy.go | 21 +++++++++ pkg/registry/core/tap/compute.go | 19 ++++++++ pkg/registry/core/tap/rest.go | 7 +++ pkg/registry/core/tap/rest_test.go | 40 +++++++++++++++++ 7 files changed, 177 insertions(+), 6 deletions(-) diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index 3f844bfc7..96e3bb9cc 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -55,6 +55,8 @@ var tapCmdFlags struct { kubeconfig string index string skipValidate bool + certIdentity string + certIssuer string } // ociRef is the parsed form of an oci:// reference. @@ -148,7 +150,7 @@ func fluxSourceName(r ociRef) string { // optional pull-credential secretRef (the private-tap credential, symmetric // with #2472). A tag-only reference is pinned to a digest later by the tap // materializer; an explicit digest is pinned here at connect time. -func buildTapOCIRepository(name string, r ociRef, secret string) *sourcev1.OCIRepository { +func buildTapOCIRepository(name string, r ociRef, secret string, verify *sourcev1.OCIRepositoryVerification) *sourcev1.OCIRepository { obj := &sourcev1.OCIRepository{ TypeMeta: metav1.TypeMeta{ APIVersion: sourcev1.GroupVersion.String(), @@ -172,9 +174,30 @@ func buildTapOCIRepository(name string, r ociRef, secret string) *sourcev1.OCIRe if secret != "" { obj.Spec.SecretRef = &fluxmeta.LocalObjectReference{Name: secret} } + if verify != nil { + obj.Spec.Verify = verify + } return obj } +// tapVerification builds a keyless cosign verification policy from the connect +// flags, or nil when neither is set. Both the certificate identity (subject) +// and the OIDC issuer are required together: a policy that verified a signature +// without pinning who signed it would be worse than none. Both are Go regular +// expressions at the Flux layer, so an exact identity should be anchored. +func tapVerification(identity, issuer string) (*sourcev1.OCIRepositoryVerification, error) { + if identity == "" && issuer == "" { + return nil, nil + } + if identity == "" || issuer == "" { + return nil, fmt.Errorf("keyless signature verification needs both --certificate-identity and --certificate-oidc-issuer") + } + return &sourcev1.OCIRepositoryVerification{ + Provider: "cosign", + MatchOIDCIdentity: []sourcev1.OIDCIdentityMatch{{Issuer: issuer, Subject: identity}}, + }, nil +} + // rewritePackageSourceForTap prepares a PackageSource read from the artifact for // apply: it keeps the repository's own declared name (no community rename), // clears server-set metadata, stamps the tap marker (label + source annotation) @@ -303,6 +326,10 @@ runs its charts in your management cluster: tap only sources you trust.`, if tapCmdFlags.tag != "" { ref.Tag = tapCmdFlags.tag } + verify, err := tapVerification(tapCmdFlags.certIdentity, tapCmdFlags.certIssuer) + if err != nil { + return err + } // Pull first: an unreachable/invalid ref must fail before any cluster // resource is created (no half-created source). @@ -332,7 +359,7 @@ runs its charts in your management cluster: tap only sources you trust.`, } srcName := fluxSourceName(ref) - ociRepo := buildTapOCIRepository(srcName, ref, tapCmdFlags.secret) + ociRepo := buildTapOCIRepository(srcName, ref, tapCmdFlags.secret, verify) toApply := make([]client.Object, 0, len(sources)+1) toApply = append(toApply, ociRepo) @@ -555,6 +582,8 @@ func init() { tapCmd.Flags().StringVar(&tapCmdFlags.kubeconfig, "kubeconfig", "", "Path to kubeconfig file") tapCmd.Flags().StringVar(&tapCmdFlags.index, "index", "", "Index location for resolving a short name (local dir or oci:// ref; defaults to COZYPKG_INDEX)") tapCmd.Flags().BoolVar(&tapCmdFlags.skipValidate, "skip-validate", false, "Skip validating the artifact before tapping") + tapCmd.Flags().StringVar(&tapCmdFlags.certIdentity, "certificate-identity", "", "Keyless cosign certificate identity (subject regex) to verify the artifact's signature against at pull time; requires --certificate-oidc-issuer") + tapCmd.Flags().StringVar(&tapCmdFlags.certIssuer, "certificate-oidc-issuer", "", "Keyless cosign OIDC issuer (regex) to verify the artifact's signature against at pull time; requires --certificate-identity") untapCmd.Flags().StringVar(&tapCmdFlags.kubeconfig, "kubeconfig", "", "Path to kubeconfig file") untapCmd.Flags().BoolVar(&untapConfirmFlag, "yes", false, "Untap even if a Package from this source is still installed") } diff --git a/cmd/cozypkg/cmd/tap_test.go b/cmd/cozypkg/cmd/tap_test.go index d57e75b2e..f3041d312 100644 --- a/cmd/cozypkg/cmd/tap_test.go +++ b/cmd/cozypkg/cmd/tap_test.go @@ -126,7 +126,7 @@ func TestObjectExists(t *testing.T) { func TestBuildTapOCIRepository(t *testing.T) { r := ociRef{URL: "oci://ghcr.io/foo/bar", Org: "foo", Repo: "bar", Tag: "v1"} - obj := buildTapOCIRepository("tap-foo-bar", r, "") + obj := buildTapOCIRepository("tap-foo-bar", r, "", nil) if obj.Namespace != "cozy-system" || obj.Spec.URL != "oci://ghcr.io/foo/bar" { t.Fatalf("unexpected OCIRepository: %+v", obj.Spec) } @@ -147,7 +147,7 @@ func TestBuildTapOCIRepository(t *testing.T) { if obj.Spec.SecretRef != nil { t.Fatalf("expected no secretRef, got %+v", obj.Spec.SecretRef) } - withSecret := buildTapOCIRepository("n", r, "pull-creds") + withSecret := buildTapOCIRepository("n", r, "pull-creds", nil) if withSecret.Spec.SecretRef == nil || withSecret.Spec.SecretRef.Name != "pull-creds" { t.Fatalf("expected secretRef pull-creds, got %+v", withSecret.Spec.SecretRef) } @@ -156,7 +156,7 @@ func TestBuildTapOCIRepository(t *testing.T) { // the user is written by the CLI itself (the operator only pins tag refs). const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" rd := ociRef{URL: "oci://ghcr.io/foo/bar", Org: "foo", Repo: "bar", Digest: digest} - objd := buildTapOCIRepository("tap-foo-bar", rd, "") + objd := buildTapOCIRepository("tap-foo-bar", rd, "", nil) if objd.Spec.Reference == nil || objd.Spec.Reference.Digest != digest { t.Fatalf("expected digest pin %q, got %+v", digest, objd.Spec.Reference) } @@ -165,7 +165,7 @@ func TestBuildTapOCIRepository(t *testing.T) { } // A tag may accompany the digest and is then informational. rtd := ociRef{URL: "oci://ghcr.io/foo/bar", Repo: "bar", Tag: "v1", Digest: digest} - objtd := buildTapOCIRepository("n", rtd, "") + objtd := buildTapOCIRepository("n", rtd, "", nil) if objtd.Spec.Reference.Digest != digest || objtd.Spec.Reference.Tag != "v1" { t.Fatalf("expected tag v1 + digest, got %+v", objtd.Spec.Reference) } @@ -183,6 +183,42 @@ func TestOCIRefPullRef(t *testing.T) { } } +func TestTapVerification(t *testing.T) { + // No identity and no issuer: no verification policy. + if v, err := tapVerification("", ""); err != nil || v != nil { + t.Fatalf("empty flags should yield no policy, got %+v err %v", v, err) + } + // Only one of the pair: an error, never a half-configured policy. + if _, err := tapVerification("subj", ""); err == nil { + t.Error("identity without issuer must error") + } + if _, err := tapVerification("", "iss"); err == nil { + t.Error("issuer without identity must error") + } + v, err := tapVerification("https://github.com/org/repo/.github/workflows/release.yml@refs/tags/v1", "https://token.actions.githubusercontent.com") + if err != nil { + t.Fatalf("valid pair: %v", err) + } + if v == nil || v.Provider != "cosign" || len(v.MatchOIDCIdentity) != 1 { + t.Fatalf("unexpected verification: %+v", v) + } + if v.MatchOIDCIdentity[0].Issuer != "https://token.actions.githubusercontent.com" || v.MatchOIDCIdentity[0].Subject == "" { + t.Errorf("identity matcher not set: %+v", v.MatchOIDCIdentity[0]) + } +} + +func TestBuildTapOCIRepositoryWithVerify(t *testing.T) { + r := ociRef{URL: "oci://ghcr.io/foo/bar", Repo: "bar", Tag: "v1"} + v := &sourcev1.OCIRepositoryVerification{ + Provider: "cosign", + MatchOIDCIdentity: []sourcev1.OIDCIdentityMatch{{Issuer: "iss", Subject: "subj"}}, + } + obj := buildTapOCIRepository("tap-foo-bar", r, "", v) + if obj.Spec.Verify == nil || obj.Spec.Verify.Provider != "cosign" || len(obj.Spec.Verify.MatchOIDCIdentity) != 1 { + t.Fatalf("verify not set on the source: %+v", obj.Spec.Verify) + } +} + // rewritePackageSourceForTap must NOT rename the PackageSource: a tapped // repository keeps its own declared name. It only clears server-set metadata, // stamps the tap marker (label + source annotation), and repoints the sourceRef. diff --git a/pkg/apis/core/v1alpha1/tap_types.go b/pkg/apis/core/v1alpha1/tap_types.go index 573337bd9..076925271 100644 --- a/pkg/apis/core/v1alpha1/tap_types.go +++ b/pkg/apis/core/v1alpha1/tap_types.go @@ -52,6 +52,25 @@ type TapSpec struct { // Secret in cozy-system for a private repository. It is consumed when a Tap // is created and, being a credential reference, is never returned on read. SecretRef string `json:"secretRef,omitempty"` + // Verify is a connect-time input only: a signature-verification policy to + // set on the tap's Flux source (spec.verify). It is consumed when a Tap is + // created, preserved across repeat connects, and never returned on read. + Verify *TapVerify `json:"verify,omitempty"` +} + +// TapVerify is a connect-time signature-verification policy for a tap. It maps +// to the Flux OCIRepository spec.verify: keyless cosign identity matching +// (issuer + subject) is the supported form, so a moved tag cannot be followed +// unless it is also signed by the recorded identity. +type TapVerify struct { + // Provider is the signature technology: "cosign" (default) or "notation". + Provider string `json:"provider,omitempty"` + // Issuer is the OIDC issuer URL for keyless cosign verification, e.g. + // https://token.actions.githubusercontent.com. + Issuer string `json:"issuer,omitempty"` + // Subject is the certificate identity (subject) for keyless cosign + // verification; it is matched against the artifact's signing identity. + Subject string `json:"subject,omitempty"` } // TapSource identifies the Flux source backing a tap. It carries no credential. diff --git a/pkg/apis/core/v1alpha1/zz_generated.deepcopy.go b/pkg/apis/core/v1alpha1/zz_generated.deepcopy.go index 66219aaa8..8088e27fd 100644 --- a/pkg/apis/core/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/apis/core/v1alpha1/zz_generated.deepcopy.go @@ -231,6 +231,11 @@ func (in *TapSpec) DeepCopyInto(out *TapSpec) { (*in)[i].DeepCopyInto(&(*out)[i]) } } + if in.Verify != nil { + in, out := &in.Verify, &out.Verify + *out = new(TapVerify) + **out = **in + } return } @@ -244,6 +249,22 @@ func (in *TapSpec) DeepCopy() *TapSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TapVerify) DeepCopyInto(out *TapVerify) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TapVerify. +func (in *TapVerify) DeepCopy() *TapVerify { + if in == nil { + return nil + } + out := new(TapVerify) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TenantModule) DeepCopyInto(out *TenantModule) { *out = *in diff --git a/pkg/registry/core/tap/compute.go b/pkg/registry/core/tap/compute.go index 9df414f76..af25ab1da 100644 --- a/pkg/registry/core/tap/compute.go +++ b/pkg/registry/core/tap/compute.go @@ -87,6 +87,25 @@ func parseConnectURL(url, tagOverride string) (connectTarget, error) { return t, nil } +// buildVerifySpec maps a connect-time TapVerify input to a Flux OCIRepository +// spec.verify. Only keyless cosign identity matching is exposed, so both the +// issuer and the subject are required: a verification policy that matched any +// signer would be worse than none. A key-based policy an admin sets by hand on +// the source is preserved across connects (see Create) but is not settable here. +func buildVerifySpec(v *corev1alpha1.TapVerify) (map[string]any, error) { + if v.Issuer == "" || v.Subject == "" { + return nil, fmt.Errorf("verify requires both issuer and subject (keyless cosign identity)") + } + provider := v.Provider + if provider == "" { + provider = "cosign" + } + return map[string]any{ + "provider": provider, + "matchOIDCIdentity": []any{map[string]any{"issuer": v.Issuer, "subject": v.Subject}}, + }, nil +} + var ( gvrPackageSources = schema.GroupVersionResource{Group: "cozystack.io", Version: "v1alpha1", Resource: "packagesources"} gvrPackages = schema.GroupVersionResource{Group: "cozystack.io", Version: "v1alpha1", Resource: "packages"} diff --git a/pkg/registry/core/tap/rest.go b/pkg/registry/core/tap/rest.go index b75fde3d9..64d81e8c7 100644 --- a/pkg/registry/core/tap/rest.go +++ b/pkg/registry/core/tap/rest.go @@ -244,6 +244,13 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation if in.Spec.SecretRef != "" { _ = unstructured.SetNestedMap(repo.Object, map[string]any{"name": in.Spec.SecretRef}, "spec", "secretRef") } + if in.Spec.Verify != nil { + verifySpec, err := buildVerifySpec(in.Spec.Verify) + if err != nil { + return nil, apierrors.NewBadRequest(err.Error()) + } + _ = unstructured.SetNestedMap(repo.Object, verifySpec, "spec", "verify") + } // Create the Flux source, idempotently: a repeat connect updates the // existing source (new tag/secret) rather than erroring. diff --git a/pkg/registry/core/tap/rest_test.go b/pkg/registry/core/tap/rest_test.go index 112381b0b..9525de1d6 100644 --- a/pkg/registry/core/tap/rest_test.go +++ b/pkg/registry/core/tap/rest_test.go @@ -376,6 +376,46 @@ func TestCreateRepeatPreservesVerifyAndResetsPin(t *testing.T) { } } +func TestCreateSetsVerify(t *testing.T) { + r := fakeREST() + in := &corev1alpha1.Tap{Spec: corev1alpha1.TapSpec{ + URL: "oci://ghcr.io/foo/bar:v1", + Verify: &corev1alpha1.TapVerify{ + Issuer: "https://token.actions.githubusercontent.com", + Subject: "https://github.com/org/repo/.github/workflows/release.yml@refs/tags/v1", + }, + }} + if _, err := r.Create(context.Background(), in, nil, nil); err != nil { + t.Fatalf("create: %v", err) + } + u, err := r.dyn.Resource(gvrOCIRepos).Namespace("cozy-system").Get(context.Background(), "tap-foo-bar", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if prov, _, _ := unstructured.NestedString(u.Object, "spec", "verify", "provider"); prov != "cosign" { + t.Errorf("verify.provider = %q, want cosign", prov) + } + ids, _, _ := unstructured.NestedSlice(u.Object, "spec", "verify", "matchOIDCIdentity") + if len(ids) != 1 { + t.Fatalf("expected one matchOIDCIdentity, got %v", ids) + } + id := ids[0].(map[string]any) + if id["issuer"] != "https://token.actions.githubusercontent.com" || id["subject"] == "" { + t.Errorf("unexpected identity matcher: %v", id) + } +} + +func TestCreateVerifyRequiresBothIdentityFields(t *testing.T) { + r := fakeREST() + in := &corev1alpha1.Tap{Spec: corev1alpha1.TapSpec{ + URL: "oci://ghcr.io/foo/bar:v1", + Verify: &corev1alpha1.TapVerify{Issuer: "https://token.actions.githubusercontent.com"}, + }} + if _, err := r.Create(context.Background(), in, nil, nil); !apierrors.IsBadRequest(err) { + t.Errorf("a keyless verify with only an issuer must be BadRequest, got %v", err) + } +} + func TestCreateRefusesConflictingURL(t *testing.T) { // A source with the same derived name but a different registry host must not // be silently retargeted. From c20d9319c72518a8db1c32d0d5fbc3e093a63bd3 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 22:16:39 +0300 Subject: [PATCH 07/15] feat(marketplace): record and pin a digest in community index entries An index entry can now carry a digest (sha256:<64 hex>) alongside its version. Resolving a short name pins that digest, so 'cozypkg tap ' consumes the exact content the CI gate verified rather than following a mutable tag; the version is kept informational. A malformed digest in an entry is a hard load error, consistent with the rest of the strict index decoding. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit c59ced04cc548c2fdfce6694512f076c03fbc06d) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/index.go | 22 +++++++++++++++++----- cmd/cozypkg/cmd/index_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/cmd/cozypkg/cmd/index.go b/cmd/cozypkg/cmd/index.go index c9fe82714..aa684ed56 100644 --- a/cmd/cozypkg/cmd/index.go +++ b/cmd/cozypkg/cmd/index.go @@ -38,7 +38,11 @@ type IndexEntry struct { // OCIRef is the artifact location, e.g. oci://ghcr.io/org/repo. OCIRef string `json:"ociRef"` // Version is the OCI tag of the listed release; a version bump updates it. - Version string `json:"version,omitempty"` + Version string `json:"version,omitempty"` + // Digest pins the exact content the CI gate verified (sha256:<64 hex>). When + // set, tapping the entry's short name pins this digest, so a short-name tap + // does not follow a moved tag. The version is kept informational alongside it. + Digest string `json:"digest,omitempty"` Description string `json:"description,omitempty"` Homepage string `json:"homepage,omitempty"` Maintainer string `json:"maintainer,omitempty"` @@ -88,6 +92,9 @@ func loadIndex(dir string) ([]IndexEntry, error) { if entry.Name == "" || entry.OCIRef == "" { return fmt.Errorf("%s: index entry must set both name and ociRef", rel) } + if entry.Digest != "" && !ociDigestRe.MatchString(entry.Digest) { + return fmt.Errorf("%s: index entry digest %q must be sha256:<64 hex>", rel, entry.Digest) + } entries = append(entries, entry) return nil }) @@ -218,13 +225,18 @@ func resolveTapTarget(arg, indexRef string) (string, error) { if !ok { return "", fmt.Errorf("no index entry named %q", arg) } - // Pin to the entry's recorded version: the CI gate validated and + // Pin to the entry's recorded version and digest: the CI gate validated and // cosign-verified :, so tapping must consume that exact - // tag rather than defaulting to latest. + // release rather than defaulting to latest. A recorded digest pins the exact + // content (the strongest form); the version is kept informational alongside it. + ref := entry.OCIRef if entry.Version != "" { - return entry.OCIRef + ":" + entry.Version, nil + ref += ":" + entry.Version } - return entry.OCIRef, nil + if entry.Digest != "" { + ref += "@" + entry.Digest + } + return ref, nil } func init() { diff --git a/cmd/cozypkg/cmd/index_test.go b/cmd/cozypkg/cmd/index_test.go index e43ff13d5..082b2d748 100644 --- a/cmd/cozypkg/cmd/index_test.go +++ b/cmd/cozypkg/cmd/index_test.go @@ -124,6 +124,31 @@ func TestResolveTapTarget(t *testing.T) { } } +func TestResolveTapTargetPinsDigest(t *testing.T) { + const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" + dir := t.TempDir() + writeFile(t, dir, "pinned.yaml", "name: pin.ned\nociRef: oci://ghcr.io/foo/bar\nversion: v1.2.3\ndigest: "+digest+"\n") + writeFile(t, dir, "digestonly.yaml", "name: dig.only\nociRef: oci://ghcr.io/baz/qux\ndigest: "+digest+"\n") + + // A recorded digest pins the exact content the CI gate verified; the version + // is kept informational alongside it. + if got, err := resolveTapTarget("pin.ned", dir); err != nil || got != "oci://ghcr.io/foo/bar:v1.2.3@"+digest { + t.Fatalf("version+digest resolve = %q err %v", got, err) + } + // A digest with no version resolves to the bare ref pinned by digest. + if got, err := resolveTapTarget("dig.only", dir); err != nil || got != "oci://ghcr.io/baz/qux@"+digest { + t.Fatalf("digest-only resolve = %q err %v", got, err) + } +} + +func TestLoadIndexRejectsBadDigest(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "bad.yaml", "name: x\nociRef: oci://r/x\ndigest: sha256:not-a-digest\n") + if _, err := loadIndex(dir); err == nil { + t.Fatal("expected error for a malformed digest in an index entry") + } +} + func TestDefaultIndexRef(t *testing.T) { if got := defaultIndexRef("/explicit"); got != "/explicit" { t.Errorf("flag should win, got %q", got) From a3d883b4bf5b61564904389503bb4365b783cd9e Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 22:20:34 +0300 Subject: [PATCH 08/15] docs(marketplace): document digest pinning and verify on tap Update the tap command help and the community-index README for the new behaviour: digest references, the automatic tag-to-digest pin, the --certificate-identity / --certificate-oidc-issuer pull-time verify flags, and the optional index entry digest. Extend the generated openapi definitions and model-name helper for the new TapVerify type (code generation is otherwise run in CI). Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit 5747f94781687ef55f9b52e072f9579a58e67d40) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/tap.go | 17 +++++--- hack/packages-index/README.md | 7 ++- pkg/apis/core/v1alpha1/model_name.go | 4 ++ pkg/generated/openapi/zz_generated.openapi.go | 43 ++++++++++++++++++- 4 files changed, 63 insertions(+), 8 deletions(-) diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index 96e3bb9cc..c41a655e3 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -306,11 +306,18 @@ With --secret the OCIRepository is given a pull-credential secretRef (the admin pre-creates the Secret in cozy-system), so a private repository taps in one command. -Trust: tap validates the artifact's structure but does NOT verify its cosign -signature. Signature verification is the community index's job at publication -time ('cozypkg validate --require-signature' in the index CI gate, pinned to -the entry's recorded identity), and can additionally be enforced at pull time -via Flux OCIRepository verification. Installing an app from a tapped repository +Pinning: a tapped repository does not follow a moving tag. A reference given by +digest (oci://host/org/repo@sha256:...) is pinned to that digest immediately; a +tag reference is pinned to the digest it currently resolves to as soon as the +source materializes, with the tag kept informational. Moving the tag upstream +changes nothing in the cluster; tap the repository again to move the pin. + +Trust: tap validates the artifact's structure. Keyless signature verification at +pull time is enabled with --certificate-identity and --certificate-oidc-issuer, +which set a Flux cosign verify policy on the source so content is pulled only +when signed by that identity. Signature verification at publication time is the +community index's job ('cozypkg validate --require-signature' in the index CI +gate, pinned to the entry's recorded identity). Installing an app from a tapped repository runs its charts in your management cluster: tap only sources you trust.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/hack/packages-index/README.md b/hack/packages-index/README.md index 7de796195..52cbc1205 100644 --- a/hack/packages-index/README.md +++ b/hack/packages-index/README.md @@ -20,6 +20,7 @@ Each file under `entries/` is a single record (see `entries/example.foo.yaml`): name: foo.bar ociRef: oci://ghcr.io/foo/bar version: v1.2.3 +digest: sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef description: A SQL database operator maintainer: Foo homepage: https://example.com/foo @@ -31,15 +32,17 @@ signing: issuer: https://token.actions.githubusercontent.com ``` +`digest` is optional but recommended: when set to the `sha256:` the gate verified, tapping the entry's short name pins that exact content instead of following the `version` tag, so a later retag of the same version cannot change what installs. The gate records it from the artifact it just verified, and `version` is kept informational alongside it. + ## Two-lane merge policy Following krew-index, submissions take one of two lanes: -- **Owner version bump.** A change that only updates an existing entry's `version` or description, leaving `ociRef` and `signing` untouched, auto-merges once the new artifact validates and is signed by the entry's **recorded** cosign identity. This keeps the routine "new release of a listed package" path fast. +- **Owner version bump.** A change that only updates an existing entry's `version`, `digest`, or description, leaving `ociRef` and `signing` untouched, auto-merges once the new artifact validates and is signed by the entry's **recorded** cosign identity. This keeps the routine "new release of a listed package" path fast. - **New entry, or a change to `ociRef`, `maintainer`, or `signing`.** These are the security-relevant edits and require maintainer review before merge. Cosign verification is **mandatory** on the gate for both lanes: the trust anchor is the recorded signing identity, so a bump fails if the new artifact is not signed by the originally approved identity. ## Trust model -Signature verification happens here, at publication time, not at tap time. `cozypkg tap` and the dashboard connect flow validate an artifact's structure but do not verify its cosign signature: a cluster that taps a listed repository trusts that this index already verified it. The verification points are this CI gate (which pins each release to the entry's recorded identity) and, optionally, Flux `OCIRepository` verification at pull time. Installing an app from a tapped repository runs its charts in the management cluster, so operators should tap only sources they trust or that appear in a curated index like this one. +Signature verification happens here, at publication time, not at tap time. `cozypkg tap` and the dashboard connect flow validate an artifact's structure; they do not verify a cosign signature unless asked (with `--certificate-identity` / `--certificate-oidc-issuer`, which set a Flux pull-time verify policy). A cluster that taps a listed repository otherwise trusts that this index already verified it. The verification point is this CI gate, which pins each release to the entry's recorded identity. Independently of signing, a tapped repository is pinned to a digest and does not follow a moved tag: a `digest` recorded on the entry pins the exact content the gate verified, and a tag-only tap is pinned to the digest it first resolves to. Installing an app from a tapped repository runs its charts in the management cluster, so operators should tap only sources they trust or that appear in a curated index like this one. diff --git a/pkg/apis/core/v1alpha1/model_name.go b/pkg/apis/core/v1alpha1/model_name.go index 1fca4d7d6..3ba6d8f36 100644 --- a/pkg/apis/core/v1alpha1/model_name.go +++ b/pkg/apis/core/v1alpha1/model_name.go @@ -118,3 +118,7 @@ func (in TapSource) OpenAPIModelName() string { func (in TapPackage) OpenAPIModelName() string { return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.TapPackage" } + +func (in TapVerify) OpenAPIModelName() string { + return "com.github.cozystack.cozystack.pkg.apis.core.v1alpha1.TapVerify" +} diff --git a/pkg/generated/openapi/zz_generated.openapi.go b/pkg/generated/openapi/zz_generated.openapi.go index 1edff5230..e34c63d72 100644 --- a/pkg/generated/openapi/zz_generated.openapi.go +++ b/pkg/generated/openapi/zz_generated.openapi.go @@ -48,6 +48,7 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA corev1alpha1.TapPackage{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapPackage(ref), corev1alpha1.TapSource{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapSource(ref), corev1alpha1.TapSpec{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapSpec(ref), + corev1alpha1.TapVerify{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TapVerify(ref), corev1alpha1.TenantModule{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantModule(ref), corev1alpha1.TenantModuleList{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantModuleList(ref), corev1alpha1.TenantModuleStatus{}.OpenAPIModelName(): schema_pkg_apis_core_v1alpha1_TenantModuleStatus(ref), @@ -715,11 +716,51 @@ func schema_pkg_apis_core_v1alpha1_TapSpec(ref common.ReferenceCallback) common. Format: "", }, }, + "verify": { + SchemaProps: spec.SchemaProps{ + Description: "Verify is a connect-time input only: a signature-verification policy to set on the tap's Flux source (spec.verify). It is consumed when a Tap is created, preserved across repeat connects, and never returned on read.", + Ref: ref(corev1alpha1.TapVerify{}.OpenAPIModelName()), + }, + }, }, }, }, Dependencies: []string{ - corev1alpha1.TapPackage{}.OpenAPIModelName(), corev1alpha1.TapSource{}.OpenAPIModelName()}, + corev1alpha1.TapPackage{}.OpenAPIModelName(), corev1alpha1.TapSource{}.OpenAPIModelName(), corev1alpha1.TapVerify{}.OpenAPIModelName()}, + } +} + +func schema_pkg_apis_core_v1alpha1_TapVerify(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "TapVerify is a connect-time signature-verification policy for a tap. It maps to the Flux OCIRepository spec.verify: keyless cosign identity matching (issuer + subject) is the supported form, so a moved tag cannot be followed unless it is also signed by the recorded identity.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "provider": { + SchemaProps: spec.SchemaProps{ + Description: "Provider is the signature technology: \"cosign\" (default) or \"notation\".", + Type: []string{"string"}, + Format: "", + }, + }, + "issuer": { + SchemaProps: spec.SchemaProps{ + Description: "Issuer is the OIDC issuer URL for keyless cosign verification, e.g. https://token.actions.githubusercontent.com.", + Type: []string{"string"}, + Format: "", + }, + }, + "subject": { + SchemaProps: spec.SchemaProps{ + Description: "Subject is the certificate identity (subject) for keyless cosign verification; it is matched against the artifact's signing identity.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, } } From f49979a01e41aaa0725c79efb65adcf6d565ea42 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 22:35:21 +0300 Subject: [PATCH 09/15] fix(marketplace): preserve verify and pull secret on CLI re-tap A re-tap applies the OCIRepository under field owner cozypkg via server-side apply; a field this owner set earlier and now omits is removed. Re-tapping to move the pin without repeating --certificate-identity/--certificate-oidc-issuer therefore silently dropped the signature-verification policy, and re-tapping a private repo without --secret dropped the pull credential. The CLI now carries an existing source's spec.verify and secretRef onto the applied object when the invocation does not set them, mirroring the API connect path, so moving the pin never silently downgrades trust or breaks a private pull. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit 0fd970304ca3eb017357504202fb233771a00b43) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/tap.go | 21 +++++++++++++++++++++ cmd/cozypkg/cmd/tap_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index c41a655e3..30c21fbc3 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -180,6 +180,24 @@ func buildTapOCIRepository(name string, r ociRef, secret string, verify *sourcev return obj } +// carryoverSourceFields preserves an existing tap source's verification policy +// and pull credential when this invocation did not set them from flags, so a +// re-tap (e.g. to move the pin to a new tag) never silently drops signature +// verification or the pull secret. A server-side apply that omits a field this +// field owner previously set would otherwise remove it, which the API connect +// path (rest.go) deliberately avoids; this keeps the CLI symmetric with it. +func carryoverSourceFields(obj, existing *sourcev1.OCIRepository, flagVerify *sourcev1.OCIRepositoryVerification, flagSecret string) { + if existing == nil { + return + } + if flagVerify == nil && existing.Spec.Verify != nil { + obj.Spec.Verify = existing.Spec.Verify + } + if flagSecret == "" && existing.Spec.SecretRef != nil { + obj.Spec.SecretRef = existing.Spec.SecretRef + } +} + // tapVerification builds a keyless cosign verification policy from the connect // flags, or nil when neither is set. Both the certificate identity (subject) // and the OIDC issuer are required together: a policy that verified a signature @@ -395,6 +413,9 @@ runs its charts in your management cluster: tap only sources you trust.`, if existing.Spec.URL != "" && existing.Spec.URL != ref.URL { return fmt.Errorf("a different repository (%s) is already tapped as %q; run 'cozypkg untap %s' before tapping %s", existing.Spec.URL, srcName, names[0], ref.URL) } + // Same repository, re-tapped: carry over a verify policy or pull secret + // this invocation did not set, so moving the pin never silently drops them. + carryoverSourceFields(ociRepo, existing, verify, tapCmdFlags.secret) } // A tapped repository keeps its own declared name. Refuse the whole tap diff --git a/cmd/cozypkg/cmd/tap_test.go b/cmd/cozypkg/cmd/tap_test.go index f3041d312..af4c03a8c 100644 --- a/cmd/cozypkg/cmd/tap_test.go +++ b/cmd/cozypkg/cmd/tap_test.go @@ -22,6 +22,7 @@ import ( "io" "testing" + fluxmeta "github.com/fluxcd/pkg/apis/meta" sourcev1 "github.com/fluxcd/source-controller/api/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -207,6 +208,40 @@ func TestTapVerification(t *testing.T) { } } +func TestCarryoverSourceFields(t *testing.T) { + verifyPol := &sourcev1.OCIRepositoryVerification{Provider: "cosign", MatchOIDCIdentity: []sourcev1.OIDCIdentityMatch{{Issuer: "iss", Subject: "subj"}}} + existing := &sourcev1.OCIRepository{Spec: sourcev1.OCIRepositorySpec{ + Verify: verifyPol, + SecretRef: &fluxmeta.LocalObjectReference{Name: "pull-creds"}, + }} + + // Re-tap without flags: an existing verify policy and pull secret are carried + // onto the object to apply, so a server-side apply that omits them does not + // remove them (SSA prunes a previously-owned field left out of the apply). + obj := &sourcev1.OCIRepository{} + carryoverSourceFields(obj, existing, nil, "") + if obj.Spec.Verify == nil { + t.Error("existing verify policy must be preserved when no --certificate-* flags are given") + } + if obj.Spec.SecretRef == nil || obj.Spec.SecretRef.Name != "pull-creds" { + t.Error("existing pull secret must be preserved when no --secret is given") + } + + // Flags present: the invocation's own values win, nothing is carried over. + flagVerify := &sourcev1.OCIRepositoryVerification{Provider: "cosign"} + obj2 := &sourcev1.OCIRepository{Spec: sourcev1.OCIRepositorySpec{Verify: flagVerify, SecretRef: &fluxmeta.LocalObjectReference{Name: "new-creds"}}} + carryoverSourceFields(obj2, existing, flagVerify, "new-creds") + if obj2.Spec.Verify != flagVerify { + t.Error("a verify policy from flags must not be overwritten by the existing one") + } + if obj2.Spec.SecretRef.Name != "new-creds" { + t.Error("a secret from --secret must not be overwritten by the existing one") + } + + // No existing source: a no-op, no panic. + carryoverSourceFields(&sourcev1.OCIRepository{}, nil, nil, "") +} + func TestBuildTapOCIRepositoryWithVerify(t *testing.T) { r := ociRef{URL: "oci://ghcr.io/foo/bar", Repo: "bar", Tag: "v1"} v := &sourcev1.OCIRepositoryVerification{ From 56be1644b79acbf42f41ad0336e2ae55a5ff58dd Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 22:35:27 +0300 Subject: [PATCH 10/15] fix(marketplace): reject a non-cosign verify provider at connect TapVerify advertised provider notation, but buildVerifySpec always emits a matchOIDCIdentity block, which is meaningful only for keyless cosign. Setting provider: notation produced a nonsensical verify block. The connect now rejects any provider other than cosign and the type doc no longer advertises notation, since only keyless cosign identity matching is settable here. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit 10be3d2770dcd97b018cf6a845e857161a27e907) Signed-off-by: Myasnikov Daniil --- pkg/apis/core/v1alpha1/tap_types.go | 4 +++- pkg/generated/openapi/zz_generated.openapi.go | 2 +- pkg/registry/core/tap/compute.go | 11 ++++++----- pkg/registry/core/tap/rest_test.go | 15 +++++++++++++++ 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/pkg/apis/core/v1alpha1/tap_types.go b/pkg/apis/core/v1alpha1/tap_types.go index 076925271..42181715a 100644 --- a/pkg/apis/core/v1alpha1/tap_types.go +++ b/pkg/apis/core/v1alpha1/tap_types.go @@ -63,7 +63,9 @@ type TapSpec struct { // (issuer + subject) is the supported form, so a moved tag cannot be followed // unless it is also signed by the recorded identity. type TapVerify struct { - // Provider is the signature technology: "cosign" (default) or "notation". + // Provider is the signature technology. Only keyless cosign (the default) is + // settable at connect, since the identity match below is a cosign construct; + // a non-cosign value is rejected. Provider string `json:"provider,omitempty"` // Issuer is the OIDC issuer URL for keyless cosign verification, e.g. // https://token.actions.githubusercontent.com. diff --git a/pkg/generated/openapi/zz_generated.openapi.go b/pkg/generated/openapi/zz_generated.openapi.go index e34c63d72..68bb1713f 100644 --- a/pkg/generated/openapi/zz_generated.openapi.go +++ b/pkg/generated/openapi/zz_generated.openapi.go @@ -739,7 +739,7 @@ func schema_pkg_apis_core_v1alpha1_TapVerify(ref common.ReferenceCallback) commo Properties: map[string]spec.Schema{ "provider": { SchemaProps: spec.SchemaProps{ - Description: "Provider is the signature technology: \"cosign\" (default) or \"notation\".", + Description: "Provider is the signature technology. Only keyless cosign (the default) is settable at connect, since the identity match below is a cosign construct; a non-cosign value is rejected.", Type: []string{"string"}, Format: "", }, diff --git a/pkg/registry/core/tap/compute.go b/pkg/registry/core/tap/compute.go index af25ab1da..25f567a0a 100644 --- a/pkg/registry/core/tap/compute.go +++ b/pkg/registry/core/tap/compute.go @@ -93,15 +93,16 @@ func parseConnectURL(url, tagOverride string) (connectTarget, error) { // signer would be worse than none. A key-based policy an admin sets by hand on // the source is preserved across connects (see Create) but is not settable here. func buildVerifySpec(v *corev1alpha1.TapVerify) (map[string]any, error) { + // Only keyless cosign is settable here; matchOIDCIdentity is a cosign-only + // construct, so a non-cosign provider would produce a nonsensical policy. + if v.Provider != "" && v.Provider != "cosign" { + return nil, fmt.Errorf("verify.provider %q is not supported; only keyless cosign identity matching is settable at connect", v.Provider) + } if v.Issuer == "" || v.Subject == "" { return nil, fmt.Errorf("verify requires both issuer and subject (keyless cosign identity)") } - provider := v.Provider - if provider == "" { - provider = "cosign" - } return map[string]any{ - "provider": provider, + "provider": "cosign", "matchOIDCIdentity": []any{map[string]any{"issuer": v.Issuer, "subject": v.Subject}}, }, nil } diff --git a/pkg/registry/core/tap/rest_test.go b/pkg/registry/core/tap/rest_test.go index 9525de1d6..406a7fb68 100644 --- a/pkg/registry/core/tap/rest_test.go +++ b/pkg/registry/core/tap/rest_test.go @@ -416,6 +416,21 @@ func TestCreateVerifyRequiresBothIdentityFields(t *testing.T) { } } +func TestCreateVerifyRejectsNonCosignProvider(t *testing.T) { + r := fakeREST() + in := &corev1alpha1.Tap{Spec: corev1alpha1.TapSpec{ + URL: "oci://ghcr.io/foo/bar:v1", + Verify: &corev1alpha1.TapVerify{ + Provider: "notation", + Issuer: "https://token.actions.githubusercontent.com", + Subject: "https://github.com/org/repo/.github/workflows/release.yml@refs/tags/v1", + }, + }} + if _, err := r.Create(context.Background(), in, nil, nil); !apierrors.IsBadRequest(err) { + t.Errorf("a non-cosign provider must be BadRequest (matchOIDCIdentity is cosign-only), got %v", err) + } +} + func TestCreateRefusesConflictingURL(t *testing.T) { // A source with the same derived name but a different registry host must not // be silently retargeted. From 1f31dd77e5834986145c3e031198b0aa3aae7f3c Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Thu, 22 Oct 2026 22:36:22 +0300 Subject: [PATCH 11/15] fix(marketplace): preserve the pull secret on API repeat connect The repeat-connect merge preserved spec.verify but still dropped spec.secretRef when the connect omitted a secret, breaking a private tap on a pin move. It now preserves an existing secretRef the same way, so the API and CLI connect paths are symmetric: a repeat connect overrides verify and the secret only when it carries its own, and never silently drops either. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit f8e3b0d04323f49e2e5c7c544d03dd4df9b8bf81) Signed-off-by: Myasnikov Daniil --- pkg/registry/core/tap/rest.go | 16 ++++++++++------ pkg/registry/core/tap/rest_test.go | 4 ++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/pkg/registry/core/tap/rest.go b/pkg/registry/core/tap/rest.go index 64d81e8c7..85e4d36a1 100644 --- a/pkg/registry/core/tap/rest.go +++ b/pkg/registry/core/tap/rest.go @@ -272,17 +272,21 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation fmt.Errorf("a different repository (%s) is already connected as %q; disconnect it before connecting %s", curURL, target.FluxSourceName, target.URL)) } // Update the fields this API owns on the FETCHED object, so the operator's - // finalizer survives. Replace url, interval, ref and secretRef from this - // connect, but PRESERVE a spec.verify set earlier (by this API or by an - // admin): a repeat connect must never silently drop a signature-verification - // policy. Replacing the whole ref rather than merging it is deliberate: it - // drops the operator's prior digest pin so the newly requested tag re- - // resolves (the operator re-pins it). A connect that itself carries verify + // finalizer survives. Replace url, interval and ref from this connect, but + // PRESERVE a spec.verify or spec.secretRef set earlier (by this API or by + // an admin) when this connect does not carry its own: a repeat connect must + // never silently drop a signature-verification policy or a pull credential. + // Replacing the whole ref rather than merging it is deliberate: it drops the + // operator's prior digest pin so the newly requested tag re-resolves (the + // operator re-pins it). A connect that itself carries verify or a secret // overrides the preserved one. newSpec := map[string]any{} if existingVerify, ok, _ := unstructured.NestedMap(cur.Object, "spec", "verify"); ok { newSpec["verify"] = existingVerify } + if existingSecret, ok, _ := unstructured.NestedMap(cur.Object, "spec", "secretRef"); ok { + newSpec["secretRef"] = existingSecret + } for k, v := range repo.Object["spec"].(map[string]any) { newSpec[k] = v } diff --git a/pkg/registry/core/tap/rest_test.go b/pkg/registry/core/tap/rest_test.go index 406a7fb68..eb75c3ceb 100644 --- a/pkg/registry/core/tap/rest_test.go +++ b/pkg/registry/core/tap/rest_test.go @@ -344,6 +344,7 @@ func TestCreateRepeatPreservesVerifyAndResetsPin(t *testing.T) { "provider": "cosign", "matchOIDCIdentity": []any{map[string]any{"issuer": "https://token.actions.githubusercontent.com", "subject": "https://github.com/org/repo/.github/workflows/release.yml@refs/tags/v1"}}, }, "spec", "verify") + _ = unstructured.SetNestedMap(existing.Object, map[string]any{"name": "pull-creds"}, "spec", "secretRef") existing.SetFinalizers([]string{"apps.cozystack.io/tap-materializer"}) existing.SetAnnotations(map[string]string{ "apps.cozystack.io/materialized-revision": "v1@" + oldDigest, @@ -362,6 +363,9 @@ func TestCreateRepeatPreservesVerifyAndResetsPin(t *testing.T) { if prov, _, _ := unstructured.NestedString(u.Object, "spec", "verify", "provider"); prov != "cosign" { t.Errorf("spec.verify was dropped on repeat connect: %+v", u.Object["spec"]) } + if name, _, _ := unstructured.NestedString(u.Object, "spec", "secretRef", "name"); name != "pull-creds" { + t.Errorf("spec.secretRef must be preserved on a repeat connect that omits a secret, got %q", name) + } if tag, _, _ := unstructured.NestedString(u.Object, "spec", "ref", "tag"); tag != "v2" { t.Errorf("tag not updated to v2, got %q", tag) } From f8509450f7ca090d9873a0d1c397efcf233e7715 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Mon, 26 Oct 2026 16:55:36 +0300 Subject: [PATCH 12/15] fix(marketplace): drop the index-entry digest from the tap pin change The index-entry `digest` field, and the gate and README claims around it, assume a published index that does not exist yet: decision 0002 in the marketplace proposal defers it, and #4981 tracks that work. The gate also never compared a recorded digest against the artifact it verified, so the field added surface without the check that would make it trustworthy. Drop it from this PR. Digest pinning still works from an explicit oci://host/org/repo@sha256:... reference and from the digest a tag resolves to; only the index-entry path is removed. The tag-based pinning and the verify-flag wording stay in the index README. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit 96758b9e3dbfa984a5594d63c9d8a8c63cb9f2a1) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/index.go | 22 +++++----------------- cmd/cozypkg/cmd/index_test.go | 25 ------------------------- hack/packages-index/README.md | 7 ++----- 3 files changed, 7 insertions(+), 47 deletions(-) diff --git a/cmd/cozypkg/cmd/index.go b/cmd/cozypkg/cmd/index.go index aa684ed56..c9fe82714 100644 --- a/cmd/cozypkg/cmd/index.go +++ b/cmd/cozypkg/cmd/index.go @@ -38,11 +38,7 @@ type IndexEntry struct { // OCIRef is the artifact location, e.g. oci://ghcr.io/org/repo. OCIRef string `json:"ociRef"` // Version is the OCI tag of the listed release; a version bump updates it. - Version string `json:"version,omitempty"` - // Digest pins the exact content the CI gate verified (sha256:<64 hex>). When - // set, tapping the entry's short name pins this digest, so a short-name tap - // does not follow a moved tag. The version is kept informational alongside it. - Digest string `json:"digest,omitempty"` + Version string `json:"version,omitempty"` Description string `json:"description,omitempty"` Homepage string `json:"homepage,omitempty"` Maintainer string `json:"maintainer,omitempty"` @@ -92,9 +88,6 @@ func loadIndex(dir string) ([]IndexEntry, error) { if entry.Name == "" || entry.OCIRef == "" { return fmt.Errorf("%s: index entry must set both name and ociRef", rel) } - if entry.Digest != "" && !ociDigestRe.MatchString(entry.Digest) { - return fmt.Errorf("%s: index entry digest %q must be sha256:<64 hex>", rel, entry.Digest) - } entries = append(entries, entry) return nil }) @@ -225,18 +218,13 @@ func resolveTapTarget(arg, indexRef string) (string, error) { if !ok { return "", fmt.Errorf("no index entry named %q", arg) } - // Pin to the entry's recorded version and digest: the CI gate validated and + // Pin to the entry's recorded version: the CI gate validated and // cosign-verified :, so tapping must consume that exact - // release rather than defaulting to latest. A recorded digest pins the exact - // content (the strongest form); the version is kept informational alongside it. - ref := entry.OCIRef + // tag rather than defaulting to latest. if entry.Version != "" { - ref += ":" + entry.Version + return entry.OCIRef + ":" + entry.Version, nil } - if entry.Digest != "" { - ref += "@" + entry.Digest - } - return ref, nil + return entry.OCIRef, nil } func init() { diff --git a/cmd/cozypkg/cmd/index_test.go b/cmd/cozypkg/cmd/index_test.go index 082b2d748..e43ff13d5 100644 --- a/cmd/cozypkg/cmd/index_test.go +++ b/cmd/cozypkg/cmd/index_test.go @@ -124,31 +124,6 @@ func TestResolveTapTarget(t *testing.T) { } } -func TestResolveTapTargetPinsDigest(t *testing.T) { - const digest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" - dir := t.TempDir() - writeFile(t, dir, "pinned.yaml", "name: pin.ned\nociRef: oci://ghcr.io/foo/bar\nversion: v1.2.3\ndigest: "+digest+"\n") - writeFile(t, dir, "digestonly.yaml", "name: dig.only\nociRef: oci://ghcr.io/baz/qux\ndigest: "+digest+"\n") - - // A recorded digest pins the exact content the CI gate verified; the version - // is kept informational alongside it. - if got, err := resolveTapTarget("pin.ned", dir); err != nil || got != "oci://ghcr.io/foo/bar:v1.2.3@"+digest { - t.Fatalf("version+digest resolve = %q err %v", got, err) - } - // A digest with no version resolves to the bare ref pinned by digest. - if got, err := resolveTapTarget("dig.only", dir); err != nil || got != "oci://ghcr.io/baz/qux@"+digest { - t.Fatalf("digest-only resolve = %q err %v", got, err) - } -} - -func TestLoadIndexRejectsBadDigest(t *testing.T) { - dir := t.TempDir() - writeFile(t, dir, "bad.yaml", "name: x\nociRef: oci://r/x\ndigest: sha256:not-a-digest\n") - if _, err := loadIndex(dir); err == nil { - t.Fatal("expected error for a malformed digest in an index entry") - } -} - func TestDefaultIndexRef(t *testing.T) { if got := defaultIndexRef("/explicit"); got != "/explicit" { t.Errorf("flag should win, got %q", got) diff --git a/hack/packages-index/README.md b/hack/packages-index/README.md index 52cbc1205..1f0195ea1 100644 --- a/hack/packages-index/README.md +++ b/hack/packages-index/README.md @@ -20,7 +20,6 @@ Each file under `entries/` is a single record (see `entries/example.foo.yaml`): name: foo.bar ociRef: oci://ghcr.io/foo/bar version: v1.2.3 -digest: sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef description: A SQL database operator maintainer: Foo homepage: https://example.com/foo @@ -32,17 +31,15 @@ signing: issuer: https://token.actions.githubusercontent.com ``` -`digest` is optional but recommended: when set to the `sha256:` the gate verified, tapping the entry's short name pins that exact content instead of following the `version` tag, so a later retag of the same version cannot change what installs. The gate records it from the artifact it just verified, and `version` is kept informational alongside it. - ## Two-lane merge policy Following krew-index, submissions take one of two lanes: -- **Owner version bump.** A change that only updates an existing entry's `version`, `digest`, or description, leaving `ociRef` and `signing` untouched, auto-merges once the new artifact validates and is signed by the entry's **recorded** cosign identity. This keeps the routine "new release of a listed package" path fast. +- **Owner version bump.** A change that only updates an existing entry's `version` or description, leaving `ociRef` and `signing` untouched, auto-merges once the new artifact validates and is signed by the entry's **recorded** cosign identity. This keeps the routine "new release of a listed package" path fast. - **New entry, or a change to `ociRef`, `maintainer`, or `signing`.** These are the security-relevant edits and require maintainer review before merge. Cosign verification is **mandatory** on the gate for both lanes: the trust anchor is the recorded signing identity, so a bump fails if the new artifact is not signed by the originally approved identity. ## Trust model -Signature verification happens here, at publication time, not at tap time. `cozypkg tap` and the dashboard connect flow validate an artifact's structure; they do not verify a cosign signature unless asked (with `--certificate-identity` / `--certificate-oidc-issuer`, which set a Flux pull-time verify policy). A cluster that taps a listed repository otherwise trusts that this index already verified it. The verification point is this CI gate, which pins each release to the entry's recorded identity. Independently of signing, a tapped repository is pinned to a digest and does not follow a moved tag: a `digest` recorded on the entry pins the exact content the gate verified, and a tag-only tap is pinned to the digest it first resolves to. Installing an app from a tapped repository runs its charts in the management cluster, so operators should tap only sources they trust or that appear in a curated index like this one. +Signature verification happens here, at publication time, not at tap time. `cozypkg tap` and the dashboard connect flow validate an artifact's structure; they do not verify a cosign signature unless asked (with `--certificate-identity` / `--certificate-oidc-issuer`, which set a Flux pull-time verify policy). A cluster that taps a listed repository otherwise trusts that this index already verified it. The verification point is this CI gate, which pins each release to the entry's recorded identity. Independently of signing, a tapped repository is pinned to a digest and does not follow a moved tag: a tag-only tap is pinned to the digest it first resolves to. Installing an app from a tapped repository runs its charts in the management cluster, so operators should tap only sources they trust or that appear in a curated index like this one. From e2f87c0cd774f01255e9dd10b34e9d2971ec8d16 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Mon, 26 Oct 2026 16:55:40 +0300 Subject: [PATCH 13/15] fix(marketplace): pin a tap digest only from a current-generation artifact The materializer pinned whatever digest status.artifact reported, even when the artifact still described the previous reference. On a re-connect to a new tag, source-controller has not re-resolved yet, so the operator materialized and pinned the old tag's content (issue #4979). Gate materialization and pinning on the artifact reflecting the current spec: status.observedGeneration equals metadata.generation, and for a tag-only source a revision that belongs to that tag (@). A tap connected before digest pinning existed already has its materialized-revision equal to the artifact revision, so Reconcile short-circuited and never pinned, letting it follow the tag one more time. Pin the current digest before that early return. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit 7494d1fad20f8c4b18d52f71f4a3311643fd90d4) Signed-off-by: Myasnikov Daniil --- .../operator/tapmaterializer_reconciler.go | 34 +++++++++ .../tapmaterializer_reconciler_test.go | 70 +++++++++++++++++++ 2 files changed, 104 insertions(+) diff --git a/internal/operator/tapmaterializer_reconciler.go b/internal/operator/tapmaterializer_reconciler.go index fd4b4994c..a578862cb 100644 --- a/internal/operator/tapmaterializer_reconciler.go +++ b/internal/operator/tapmaterializer_reconciler.go @@ -105,7 +105,24 @@ func (r *TapMaterializerReconciler) Reconcile(ctx context.Context, req ctrl.Requ // fail-closed on the integrity check. return ctrl.Result{RequeueAfter: tapWaitRequeue}, nil } + // Act only on an artifact that reflects the current spec. After a re-connect + // changes spec.ref, source-controller must re-resolve before status.artifact + // describes the new reference; acting early would materialize and pin the + // previous revision (issue #4979). + if !r.artifactReady(&repo, art.Revision) { + return ctrl.Result{RequeueAfter: tapWaitRequeue}, nil + } if repo.Annotations[tapconst.MaterializedRevisionAnnotation] == art.Revision { + // Already materialized at this revision. A tap connected before digest + // pinning existed still follows its tag (no digest on spec.ref); pin the + // current digest now so moving the tag upstream cannot pull new content on + // the next revision. A source that already carries a digest needs nothing. + if ref := repo.Spec.Reference; ref == nil || ref.Digest == "" { + pinTapDigest(&repo, art.Revision) + if err := r.Update(ctx, &repo); err != nil { + return ctrl.Result{}, err + } + } return ctrl.Result{}, nil } @@ -208,6 +225,23 @@ func (r *TapMaterializerReconciler) Reconcile(ctx context.Context, req ctrl.Requ return ctrl.Result{}, nil } +// artifactReady reports whether status.artifact reflects the current spec +// generation and, for a tag-only source, the tag the source now follows. It +// gates materialization and pinning so a re-connect's new spec is never acted on +// with the previous revision's artifact. source-controller formats a tag +// revision as '@', so a tag-only ref requires that prefix; a source +// pinned to a digest reports a bare digest revision and needs only the +// generation check. +func (r *TapMaterializerReconciler) artifactReady(repo *sourcev1.OCIRepository, revision string) bool { + if repo.Status.ObservedGeneration != repo.Generation { + return false + } + if ref := repo.Spec.Reference; ref != nil && ref.Tag != "" && ref.Digest == "" { + return strings.HasPrefix(revision, ref.Tag+"@") + } + return true +} + // manifestDigestRe matches a full OCI manifest digest (sha256:<64 hex>). var manifestDigestRe = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) diff --git a/internal/operator/tapmaterializer_reconciler_test.go b/internal/operator/tapmaterializer_reconciler_test.go index 404ce6e48..e7c6f7148 100644 --- a/internal/operator/tapmaterializer_reconciler_test.go +++ b/internal/operator/tapmaterializer_reconciler_test.go @@ -640,3 +640,73 @@ func TestReconcilePinIsIdempotent(t *testing.T) { t.Errorf("expected materialized revision stamped to the bare digest, got %q", got.Annotations[tapconst.MaterializedRevisionAnnotation]) } } + +// On a re-connect to a new tag, status.artifact still describes the previous +// tag's content until source-controller re-resolves. The reconciler must not +// materialize and pin that stale revision (issue #4979): spec.ref.Tag is v2 but +// the revision is still v1@, so nothing is pinned until the revision +// belongs to the tag now followed. +func TestReconcileDoesNotPinStaleArtifactOnReconnect(t *testing.T) { + scheme := tapScheme(t) + data, digest := tarGz(t, map[string]string{"packages/core/platform/sources/hello.yaml": samplePS}) + oldManifest := "sha256:" + strings.Repeat("a", 64) + repo := tapRepo(true) + repo.Spec.Reference = &sourcev1.OCIRepositoryRef{Tag: "v2"} // re-connect cleared the pin, requested v2 + cl := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(repo). + WithStatusSubresource(&sourcev1.OCIRepository{}). + Build() + setArtifact(t, cl, digest, "v1@"+oldManifest) // still the old tag's revision + + r := materializerFor(scheme, cl, record.NewFakeRecorder(10), &data) + if _, err := r.Reconcile(context.Background(), req()); err != nil { + t.Fatalf("reconcile: %v", err) + } + var got sourcev1.OCIRepository + if err := cl.Get(context.Background(), req().NamespacedName, &got); err != nil { + t.Fatal(err) + } + if got.Spec.Reference.Digest != "" { + t.Errorf("must not pin the previous tag's digest while the artifact is stale, got %q", got.Spec.Reference.Digest) + } + if got.Annotations[tapconst.PinnedDigestAnnotation] != "" { + t.Errorf("must not record a pin from a stale artifact, got %v", got.Annotations) + } + if got.Annotations[tapconst.MaterializedRevisionAnnotation] != "" { + t.Errorf("must not stamp a revision from a stale artifact, got %v", got.Annotations) + } +} + +// A tap materialized before digest pinning existed already has its +// materialized-revision equal to the artifact revision, so Reconcile would +// short-circuit. It must still pin the current digest before that early return, +// so moving the tag upstream does not pull new content on the next revision +// (issue #4979). +func TestReconcilePinsPreUpgradeTapBeforeEarlyReturn(t *testing.T) { + scheme := tapScheme(t) + data, digest := tarGz(t, map[string]string{"packages/core/platform/sources/hello.yaml": samplePS}) + manifest := "sha256:" + strings.Repeat("b", 64) + repo := tapRepo(true) + repo.Spec.Reference = &sourcev1.OCIRepositoryRef{Tag: "v1"} // tag-only, never pinned + repo.Annotations = map[string]string{tapconst.MaterializedRevisionAnnotation: "v1@" + manifest} + cl := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(repo). + WithStatusSubresource(&sourcev1.OCIRepository{}). + Build() + setArtifact(t, cl, digest, "v1@"+manifest) + + r := materializerFor(scheme, cl, record.NewFakeRecorder(10), &data) + if _, err := r.Reconcile(context.Background(), req()); err != nil { + t.Fatalf("reconcile: %v", err) + } + var got sourcev1.OCIRepository + if err := cl.Get(context.Background(), req().NamespacedName, &got); err != nil { + t.Fatal(err) + } + if got.Spec.Reference == nil || got.Spec.Reference.Digest != manifest { + t.Fatalf("a pre-upgrade tap must be pinned to the current digest, got %+v", got.Spec.Reference) + } + if got.Annotations[tapconst.PinnedDigestAnnotation] != manifest { + t.Errorf("expected pinned-digest annotation %q, got %v", manifest, got.Annotations) + } +} From 606f056b65d34173ee4680a9b2fa59d85988a908 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Mon, 26 Oct 2026 16:55:47 +0300 Subject: [PATCH 14/15] fix(marketplace): verify the signature before pulling, and anchor the identity match With --certificate-identity and --certificate-oidc-issuer, `cozypkg tap` pulled by tag without verifying and applied the artifact's PackageSources with ForceOwnership; only the Flux source carried the verify policy. A tag moved by someone without the signing identity could land unsigned content in the cluster. Verify the signature at tap time and pin the verified digest, so the content pulled and applied is what a trusted identity signed. Flux evaluates a cosign matchOIDCIdentity issuer and subject as Go regexps, and they were written unanchored. An exact identity such as alice@example.com would also accept malice@example.com, and the dots would match any character. Anchor and quote both values at the API and the CLI. Reject --tag together with a digest reference instead of silently ignoring the tag. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit 0195e73d38a4dc0e69e4ae86963dbd3902e37ba7) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/tap.go | 29 +++++++++++++++++++++++++++-- cmd/cozypkg/cmd/tap_test.go | 18 +++++++++++++++--- pkg/registry/core/tap/compute.go | 10 ++++++++-- pkg/registry/core/tap/rest_test.go | 17 +++++++++++++++-- 4 files changed, 65 insertions(+), 9 deletions(-) diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index 30c21fbc3..23524049a 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -210,9 +210,15 @@ func tapVerification(identity, issuer string) (*sourcev1.OCIRepositoryVerificati if identity == "" || issuer == "" { return nil, fmt.Errorf("keyless signature verification needs both --certificate-identity and --certificate-oidc-issuer") } + // Flux treats Issuer and Subject as Go regexps, so anchor and quote them for + // an exact match: an unanchored identity would also accept a superstring + // (e.g. alice@example.com matching malice@example.com). return &sourcev1.OCIRepositoryVerification{ - Provider: "cosign", - MatchOIDCIdentity: []sourcev1.OIDCIdentityMatch{{Issuer: issuer, Subject: identity}}, + Provider: "cosign", + MatchOIDCIdentity: []sourcev1.OIDCIdentityMatch{{ + Issuer: "^" + regexp.QuoteMeta(issuer) + "$", + Subject: "^" + regexp.QuoteMeta(identity) + "$", + }}, }, nil } @@ -349,6 +355,9 @@ runs its charts in your management cluster: tap only sources you trust.`, return err } if tapCmdFlags.tag != "" { + if ref.Digest != "" { + return fmt.Errorf("--tag cannot override the digest in %q; drop the digest or the --tag flag", args[0]) + } ref.Tag = tapCmdFlags.tag } verify, err := tapVerification(tapCmdFlags.certIdentity, tapCmdFlags.certIssuer) @@ -356,6 +365,22 @@ runs its charts in your management cluster: tap only sources you trust.`, return err } + // With verification flags set, verify the signature now and pin the verified + // digest, so the artifact we pull and the PackageSources we apply are the + // exact content a trusted identity signed. Without this the CLI would apply + // an unverified tag pull (only the Flux source would carry the policy), so a + // moved tag could land unsigned PackageSource content in the cluster before + // the operator re-materialized. + if verify != nil { + verifiedDigest, verr := verifyCosignSignature(ref.pullRef(), tapCmdFlags.certIdentity, tapCmdFlags.certIssuer) + if verr != nil { + return verr + } + if ref.Digest == "" && verifiedDigest != "" { + ref.Digest = verifiedDigest + } + } + // Pull first: an unreachable/invalid ref must fail before any cluster // resource is created (no half-created source). fullRef := ref.pullRef() diff --git a/cmd/cozypkg/cmd/tap_test.go b/cmd/cozypkg/cmd/tap_test.go index af4c03a8c..a342f4fe8 100644 --- a/cmd/cozypkg/cmd/tap_test.go +++ b/cmd/cozypkg/cmd/tap_test.go @@ -20,6 +20,7 @@ import ( "context" "errors" "io" + "regexp" "testing" fluxmeta "github.com/fluxcd/pkg/apis/meta" @@ -196,15 +197,26 @@ func TestTapVerification(t *testing.T) { if _, err := tapVerification("", "iss"); err == nil { t.Error("issuer without identity must error") } - v, err := tapVerification("https://github.com/org/repo/.github/workflows/release.yml@refs/tags/v1", "https://token.actions.githubusercontent.com") + id := "https://github.com/org/repo/.github/workflows/release.yml@refs/tags/v1" + iss := "https://token.actions.githubusercontent.com" + v, err := tapVerification(id, iss) if err != nil { t.Fatalf("valid pair: %v", err) } if v == nil || v.Provider != "cosign" || len(v.MatchOIDCIdentity) != 1 { t.Fatalf("unexpected verification: %+v", v) } - if v.MatchOIDCIdentity[0].Issuer != "https://token.actions.githubusercontent.com" || v.MatchOIDCIdentity[0].Subject == "" { - t.Errorf("identity matcher not set: %+v", v.MatchOIDCIdentity[0]) + // Flux evaluates the matcher as a regexp. It must be an anchored exact match: + // it matches the exact identity and rejects a superstring (a moved tag v10, or + // malice@... for an email identity), which an unanchored matcher would accept. + m := v.MatchOIDCIdentity[0] + subjRe := regexp.MustCompile(m.Subject) + if !subjRe.MatchString(id) || subjRe.MatchString(id+"0") { + t.Errorf("subject must be an anchored exact match, got %q", m.Subject) + } + issRe := regexp.MustCompile(m.Issuer) + if !issRe.MatchString(iss) || issRe.MatchString(iss+"x") { + t.Errorf("issuer must be an anchored exact match, got %q", m.Issuer) } } diff --git a/pkg/registry/core/tap/compute.go b/pkg/registry/core/tap/compute.go index 25f567a0a..b2e699bb9 100644 --- a/pkg/registry/core/tap/compute.go +++ b/pkg/registry/core/tap/compute.go @@ -101,9 +101,15 @@ func buildVerifySpec(v *corev1alpha1.TapVerify) (map[string]any, error) { if v.Issuer == "" || v.Subject == "" { return nil, fmt.Errorf("verify requires both issuer and subject (keyless cosign identity)") } + // Flux treats issuer and subject as Go regexps. Anchor and quote them so an + // exact identity matches exactly: an unanchored `alice@example.com` would also + // accept `malice@example.com`, and the `.` would match any character. return map[string]any{ - "provider": "cosign", - "matchOIDCIdentity": []any{map[string]any{"issuer": v.Issuer, "subject": v.Subject}}, + "provider": "cosign", + "matchOIDCIdentity": []any{map[string]any{ + "issuer": "^" + regexp.QuoteMeta(v.Issuer) + "$", + "subject": "^" + regexp.QuoteMeta(v.Subject) + "$", + }}, }, nil } diff --git a/pkg/registry/core/tap/rest_test.go b/pkg/registry/core/tap/rest_test.go index eb75c3ceb..a3de2bb1e 100644 --- a/pkg/registry/core/tap/rest_test.go +++ b/pkg/registry/core/tap/rest_test.go @@ -5,6 +5,7 @@ package tap import ( "context" + "regexp" "testing" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -404,8 +405,20 @@ func TestCreateSetsVerify(t *testing.T) { t.Fatalf("expected one matchOIDCIdentity, got %v", ids) } id := ids[0].(map[string]any) - if id["issuer"] != "https://token.actions.githubusercontent.com" || id["subject"] == "" { - t.Errorf("unexpected identity matcher: %v", id) + issuer, _ := id["issuer"].(string) + subject, _ := id["subject"].(string) + if issuer == "" || subject == "" { + t.Fatalf("identity matcher not set: %v", id) + } + // Flux evaluates these as regexps; they must be anchored exact matches so a + // superstring identity (e.g. a moved tag v10) is rejected. + wantIssuer := "https://token.actions.githubusercontent.com" + wantSubject := "https://github.com/org/repo/.github/workflows/release.yml@refs/tags/v1" + if ir := regexp.MustCompile(issuer); !ir.MatchString(wantIssuer) || ir.MatchString(wantIssuer+"x") { + t.Errorf("issuer must be an anchored exact match, got %q", issuer) + } + if sr := regexp.MustCompile(subject); !sr.MatchString(wantSubject) || sr.MatchString(wantSubject+"0") { + t.Errorf("subject must be an anchored exact match, got %q", subject) } } From 9cff86f85124454812cbbba99bf98258572a20e4 Mon Sep 17 00:00:00 2001 From: IvanHunters Date: Mon, 26 Oct 2026 17:11:52 +0300 Subject: [PATCH 15/15] fix(marketplace): fail closed on an unparseable verified digest, and cover the generation gate A verified cosign signature whose manifest digest could not be parsed fell back to an unpinned tag pull, which reopens the tag-mutation window the verification was meant to close. Return an error instead. Add a test that isolates the status.observedGeneration == metadata.generation conjunct of artifactReady; the existing tests exercised only the tag-prefix conjunct, so a mutation of the generation check went uncaught. Assisted-by: LLM Signed-off-by: IvanHunters (cherry picked from commit 09b0688abdf1f4e4ae0f48029e3eac74c817bce7) Signed-off-by: Myasnikov Daniil --- cmd/cozypkg/cmd/tap.go | 8 +++- .../tapmaterializer_reconciler_test.go | 43 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/cmd/cozypkg/cmd/tap.go b/cmd/cozypkg/cmd/tap.go index 23524049a..e04edebd7 100644 --- a/cmd/cozypkg/cmd/tap.go +++ b/cmd/cozypkg/cmd/tap.go @@ -376,7 +376,13 @@ runs its charts in your management cluster: tap only sources you trust.`, if verr != nil { return verr } - if ref.Digest == "" && verifiedDigest != "" { + // Fail closed: a verified signature with no parseable digest must not + // fall back to an unpinned tag pull, which would reopen the tag-mutation + // window between verify and pull. + if verifiedDigest == "" { + return fmt.Errorf("cosign verified %q but returned no manifest digest; refusing to pull by an unpinned tag", ref.pullRef()) + } + if ref.Digest == "" { ref.Digest = verifiedDigest } } diff --git a/internal/operator/tapmaterializer_reconciler_test.go b/internal/operator/tapmaterializer_reconciler_test.go index e7c6f7148..c1c59c775 100644 --- a/internal/operator/tapmaterializer_reconciler_test.go +++ b/internal/operator/tapmaterializer_reconciler_test.go @@ -710,3 +710,46 @@ func TestReconcilePinsPreUpgradeTapBeforeEarlyReturn(t *testing.T) { t.Errorf("expected pinned-digest annotation %q, got %v", manifest, got.Annotations) } } + +// artifactReady must also wait when status.observedGeneration lags +// metadata.generation: the artifact may still describe the spec from before the +// current re-connect, so pinning from it would pin stale content even when the +// revision happens to match the tag. This isolates the generation conjunct of the +// gate (the revision here matches the tag, so only the generation check can block). +func TestReconcileWaitsWhenObservedGenerationLags(t *testing.T) { + scheme := tapScheme(t) + data, digest := tarGz(t, map[string]string{"packages/core/platform/sources/hello.yaml": samplePS}) + manifest := "sha256:" + strings.Repeat("d", 64) + repo := tapRepo(true) + repo.Generation = 2 // spec advanced by a re-connect + repo.Spec.Reference = &sourcev1.OCIRepositoryRef{Tag: "v1"} + cl := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(repo). + WithStatusSubresource(&sourcev1.OCIRepository{}). + Build() + + var live sourcev1.OCIRepository + if err := cl.Get(context.Background(), req().NamespacedName, &live); err != nil { + t.Fatal(err) + } + live.Status.Artifact = &fluxmeta.Artifact{URL: "http://example.com/a.tar.gz", Digest: digest, Revision: "v1@" + manifest} + live.Status.ObservedGeneration = 1 // source-controller has not caught up to generation 2 + if err := cl.Status().Update(context.Background(), &live); err != nil { + t.Fatal(err) + } + + r := materializerFor(scheme, cl, record.NewFakeRecorder(10), &data) + if _, err := r.Reconcile(context.Background(), req()); err != nil { + t.Fatalf("reconcile: %v", err) + } + var got sourcev1.OCIRepository + if err := cl.Get(context.Background(), req().NamespacedName, &got); err != nil { + t.Fatal(err) + } + if got.Spec.Reference.Digest != "" { + t.Errorf("must not pin while observedGeneration lags generation, got %q", got.Spec.Reference.Digest) + } + if got.Annotations[tapconst.PinnedDigestAnnotation] != "" { + t.Errorf("must not record a pin while observedGeneration lags, got %v", got.Annotations) + } +}