mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 04:06:34 +09:00
fix(marketplace): pin a tapped repository to a digest instead of a mutable tag (#5082)
## What this PR does
A tapped (community-connected) repository followed a mutable OCI tag:
the Flux `OCIRepository` carried only `spec.ref.tag` with a 5-minute
interval, so whoever controlled the tag controlled what ran in the
management cluster within that interval, down to the HelmReleases of
already-running tenant application instances. Fixes #4979.
A tap is now pinned to a digest. `cozypkg tap` and the connect API
accept an explicit `oci://host/org/repo@sha256:...` reference; a tag
reference is resolved and pinned to its digest by the tap materializer
once the artifact for the current spec generation is ready, from the
digest Flux reports in `status.artifact.revision`, with the tag kept
informational. A tap connected before this change is pinned to its
current digest on the first reconcile after upgrade, and a re-connect to
a new tag waits for source-controller to re-resolve before pinning, so a
stale revision is never pinned. Moving the tag upstream no longer
changes anything in the cluster; an explicit re-connect moves the pin.
Connect also accepts an optional keyless cosign verification policy
(`--certificate-identity` / `--certificate-oidc-issuer` on the CLI,
`spec.verify` on the API), anchored to an exact identity so a
superstring cannot match, and preserves it, and the pull secret, across
repeat connects rather than silently dropping them. With those flags the
CLI verifies the signature at tap time and pins the verified digest
before pulling, so the content it applies is what a trusted identity
signed; it fails closed if the verified digest cannot be determined.
### Screenshots
Not applicable: no UI changes.
### Downstream repositories
I walked the trigger map against the diff. The change is confined to
`cozypkg`, the `Tap` aggregated API (a virtual, cluster-scoped resource
with no CRD), the tap materializer, and the community-index docs. It
does not touch `packages/apps`, `packages/core/platform/values.yaml`,
installer values, platform variants/components, release assets,
`ApplicationDefinition` semantics, the `hack/` make targets, or the
commit convention, so the provider, ansible, ccp and external-apps paths
are not reached.
One path is arguable and needs a human decision, so I have left every
box unticked rather than tick or dismiss it:
- `cozystack/website` — `cozypkg tap` gains flags and digest-pinning
behaviour. The marketplace tap flow is new and I am not sure it has a
reference page on the site yet, so whether a docs follow-up is warranted
(and where) is a maintainer call.
- [ ] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:
### Release note
```release-note
fix(marketplace): a tapped repository is pinned to a digest instead of following a mutable tag, so moving the tag upstream no longer changes what runs in the cluster; connect accepts oci://...@sha256:... and an optional keyless cosign verify policy (anchored to an exact identity and preserved across re-connects), and with verify flags the CLI verifies the signature and pins the verified digest at tap time.
```
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
- **New Features**
- OCI repositories can be connected using a SHA-256 digest, with or
without a tag. Tag-based sources are pinned to the resolved artifact
digest.
- Optional Cosign keyless verification is available during connection
using certificate identity and OIDC issuer details.
- Reconnecting preserves existing verification and pull-credential
settings when replacement values aren’t provided.
- **Bug Fixes**
- Reconnecting with a new tag clears previous operator-managed pins so
the requested tag can resolve to its current artifact.
- **Documentation**
- Clarified tag pinning, signature verification, and where tapped app
charts run.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Backported-from: 94ada11eef
This commit is contained in:
13 files changed
+985
-69
No files matched your search
+167
-33
@@ -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.
|
||||
@@ -65,10 +67,28 @@ 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
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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 +97,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 +125,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
|
||||
@@ -116,9 +146,11 @@ 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).
|
||||
func buildTapOCIRepository(name string, r ociRef, secret string) *sourcev1.OCIRepository {
|
||||
// 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, verify *sourcev1.OCIRepositoryVerification) *sourcev1.OCIRepository {
|
||||
obj := &sourcev1.OCIRepository{
|
||||
TypeMeta: metav1.TypeMeta{
|
||||
APIVersion: sourcev1.GroupVersion.String(),
|
||||
@@ -134,19 +166,62 @@ 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 != "" {
|
||||
obj.Spec.SecretRef = &fluxmeta.LocalObjectReference{Name: secret}
|
||||
}
|
||||
if verify != nil {
|
||||
obj.Spec.Verify = verify
|
||||
}
|
||||
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
|
||||
// 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")
|
||||
}
|
||||
// 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: "^" + regexp.QuoteMeta(issuer) + "$",
|
||||
Subject: "^" + regexp.QuoteMeta(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)
|
||||
@@ -181,21 +256,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))
|
||||
}
|
||||
|
||||
@@ -238,11 +330,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 {
|
||||
@@ -256,12 +355,41 @@ 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)
|
||||
if err != nil {
|
||||
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
|
||||
}
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -287,7 +415,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)
|
||||
@@ -316,6 +444,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
|
||||
@@ -350,12 +481,13 @@ 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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -509,6 +641,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")
|
||||
}
|
||||
+175
-20
@@ -20,8 +20,10 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"regexp"
|
||||
"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"
|
||||
@@ -36,18 +38,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 +71,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,7 +128,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)
|
||||
}
|
||||
@@ -139,10 +149,121 @@ 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)
|
||||
}
|
||||
|
||||
// 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, "", nil)
|
||||
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, "", nil)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
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)
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
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{
|
||||
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
|
||||
@@ -279,16 +400,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 {
|
||||
@@ -297,11 +425,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)
|
||||
}
|
||||
}
|
||||
@@ -42,4 +42,4 @@ Cosign verification is **mandatory** on the gate for both lanes: the trust ancho
|
||||
|
||||
## 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 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.
|
||||
@@ -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.
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"net/http"
|
||||
neturl "net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -104,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
|
||||
}
|
||||
|
||||
@@ -189,6 +207,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 +225,63 @@ 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 '<tag>@<digest>', 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}$`)
|
||||
|
||||
// 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
|
||||
// '<tag>@<digest>' and a digest revision as the bare '<digest>', 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
|
||||
|
||||
@@ -18,6 +18,7 @@ package operator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
fluxmeta "github.com/fluxcd/pkg/apis/meta"
|
||||
@@ -535,3 +536,220 @@ 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
|
||||
// '<tag>@<digest>').
|
||||
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])
|
||||
}
|
||||
}
|
||||
|
||||
// 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@<digest>, 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -52,6 +52,27 @@ 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. 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.
|
||||
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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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. 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: "",
|
||||
},
|
||||
},
|
||||
"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: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -70,6 +87,32 @@ 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) {
|
||||
// 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)")
|
||||
}
|
||||
// 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": "^" + regexp.QuoteMeta(v.Issuer) + "$",
|
||||
"subject": "^" + regexp.QuoteMeta(v.Subject) + "$",
|
||||
}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
var (
|
||||
gvrPackageSources = schema.GroupVersionResource{Group: "cozystack.io", Version: "v1alpha1", Resource: "packagesources"}
|
||||
gvrPackages = schema.GroupVersionResource{Group: "cozystack.io", Version: "v1alpha1", Resource: "packages"}
|
||||
|
||||
@@ -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,12 +238,19 @@ 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 != "" {
|
||||
_ = 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.
|
||||
@@ -255,14 +271,26 @@ 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 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
|
||||
}
|
||||
cur.Object["spec"] = newSpec
|
||||
labels := cur.GetLabels()
|
||||
if labels == nil {
|
||||
labels = map[string]string{}
|
||||
@@ -274,7 +302,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))
|
||||
|
||||
@@ -5,6 +5,7 @@ package tap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
@@ -240,8 +241,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,6 +310,144 @@ 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")
|
||||
_ = 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,
|
||||
"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 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)
|
||||
}
|
||||
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 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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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 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.
|
||||
|
||||
Reference in new issue
Block a user