Skip to content

Commit aa20495

Browse files
committed
feat(marketplace): register a tapped repository's apps on connect
Connecting a marketplace repository materialized its PackageSource but created no Package, so its ApplicationDefinitions never rendered and its apps never appeared in the dashboard catalog until a manual `cozypkg add` the dashboard cannot drive (the package list is computed from the ApplicationDefinitions, which do not exist yet). The tap materializer now creates a tap-managed registration Package for each materialized PackageSource, the way the platform ships a Package per built-in app, so the ApplicationDefinition registrations deploy on connect and the apps become browsable; the app components carry no install block and are still instantiated per user resource. Privileged install components of an unconfirmed tap auto-registration (a Package that still carries the marketplace-tap label) are refused on several best-effort layers: the Package reconciler skips their HelmRelease and prunes a lingering one at the install site, and the PackageSource reconciler withholds their ExternalArtifact so the helm-controller has no privileged content to deploy, re-running on confirmation via a Package watch. `cozypkg add --allow-privileged` sheds the label as an explicit ownership handover, which is the confirmation; a platform Package never carries the label. A benign component flipped to privileged in a new revision can still be materialized by source-watcher before these layers observe the flip; closing that race fully requires decoupling the catalog registration from install and is tracked in issue #4359. `cozypkg untap` and the dashboard disconnect remove the registration Package (de-registering the apps) under a UID + ResourceVersion precondition, so a concurrent `cozypkg add` handover is never clobbered; running instances are left but unmanaged. `cozypkg add` re-opens a tap auto-registration for variant selection and hands it over. The cozystack-api ClusterRole gains delete on packages for the disconnect path. Assisted-by: LLM Signed-off-by: IvanHunters <[email protected]>
1 parent 92d2eed commit aa20495

18 files changed

Lines changed: 1296 additions & 111 deletions

‎cmd/cozypkg/cmd/add.go‎

Lines changed: 100 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@ import (
2626
"strings"
2727

2828
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
29+
"github.com/cozystack/cozystack/internal/marketplace/collision"
30+
"github.com/cozystack/cozystack/internal/marketplace/tapconst"
2931
"github.com/spf13/cobra"
32+
apierrors "k8s.io/apimachinery/pkg/api/errors"
3033
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
3134
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
3235
"k8s.io/apimachinery/pkg/runtime"
@@ -435,9 +438,17 @@ func installPackage(ctx context.Context, k8sClient client.Client, packageSourceN
435438
fmt.Fprintf(os.Stderr, "Installing %s and its dependencies...\n\n", packageSourceName)
436439
packageVariants := make(map[string]string) // packageName -> variant
437440

441+
// reopen holds the names whose installed Package is THIS source's managed
442+
// auto-registration, which `add` re-opens for a variant choice and then hands
443+
// over to the user (below). Every other installed Package is left as is.
444+
reopen := make(map[string]bool)
438445
for _, pkgName := range installOrder {
439-
// Check if already installed
440-
if installed, exists := installedMap[pkgName]; exists {
446+
installed, isInstalled := installedMap[pkgName]
447+
ps, psExists := packageSourceMap[pkgName]
448+
// A user's own Package, or a foreign leftover, is left untouched; only the
449+
// managed auto-registration of THIS source (owned + empty variant, the same
450+
// predicate the operator uses) is re-opened for a variant choice.
451+
if isInstalled && !collision.ManagedRegistration(installed, tapSourceName(ps), installed.Spec.Variant) {
441452
variant := installed.Spec.Variant
442453
if variant == "" {
443454
variant = "default"
@@ -447,9 +458,7 @@ func installPackage(ctx context.Context, k8sClient client.Client, packageSourceN
447458
continue
448459
}
449460

450-
// Get PackageSource for this dependency
451-
ps, exists := packageSourceMap[pkgName]
452-
if !exists {
461+
if !psExists {
453462
requester := dependencyRequesters[pkgName]
454463
if requester != "" {
455464
return fmt.Errorf("PackageSource %s not found (required by %s)", pkgName, requester)
@@ -465,7 +474,7 @@ func installPackage(ctx context.Context, k8sClient client.Client, packageSourceN
465474

466475
// A privileged component runs with elevated access; require an explicit
467476
// confirmation (or --allow-privileged) before installing it.
468-
if privileged := privilegedComponents(ps, variant); len(privileged) > 0 && !addCmdFlags.allowPrivileged {
477+
if privileged := collision.PrivilegedInstallComponents(ps, variant); len(privileged) > 0 && !addCmdFlags.allowPrivileged {
469478
ok, err := confirmPrivileged(pkgName, variant, privileged)
470479
if err != nil {
471480
return err
@@ -476,16 +485,34 @@ func installPackage(ctx context.Context, k8sClient client.Client, packageSourceN
476485
}
477486

478487
packageVariants[pkgName] = variant
488+
if isInstalled {
489+
reopen[pkgName] = true
490+
}
479491
}
480492

481493
// Now create all Package resources
482494
for _, pkgName := range installOrder {
483-
// Skip if already installed
484-
if _, exists := installedMap[pkgName]; exists {
495+
variant := packageVariants[pkgName]
496+
497+
if reopen[pkgName] {
498+
// Running `add` is an explicit ownership handover: convert the managed
499+
// auto-registration into a plain user Package pinned to the chosen
500+
// variant (shedding the tap markers and the PackageSource ownerRef), so
501+
// the materializer no longer manages or de-registers it. Otherwise a
502+
// later revision that turns the DEFAULT variant privileged would undo
503+
// the user's deliberate choice, including a confirmed privileged one.
504+
installed := installedMap[pkgName]
505+
if err := handoverManagedRegistration(ctx, k8sClient, installed, variant); err != nil {
506+
return fmt.Errorf("failed to set variant %s on Package %s: %w", variant, pkgName, err)
507+
}
508+
fmt.Fprintf(os.Stderr, "✓ %s (variant set to %s)\n", pkgName, variant)
509+
continue
510+
}
511+
// A non-reopened already-installed Package (a user's own, or a foreign
512+
// leftover) was reported in phase 1 and needs nothing here.
513+
if _, isInstalled := installedMap[pkgName]; isInstalled {
485514
continue
486515
}
487-
488-
variant := packageVariants[pkgName]
489516

490517
// Create Package
491518
pkg := &cozyv1alpha1.Package{
@@ -497,16 +524,78 @@ func installPackage(ctx context.Context, k8sClient client.Client, packageSourceN
497524
},
498525
}
499526

500-
if err := k8sClient.Create(ctx, pkg); err != nil {
527+
created, err := createPackageIdempotent(ctx, k8sClient, pkg)
528+
if err != nil {
501529
return fmt.Errorf("failed to create Package %s: %w", pkgName, err)
502530
}
531+
if !created {
532+
// The materializer auto-created the registration Package between the
533+
// List above and this Create, so this run did not take ownership of it
534+
// (its markers are not shed). Re-run so the reopen path pins it -- for a
535+
// non-default variant to apply the choice, and for the default variant so
536+
// a later privileged flip does not de-register this deliberate install.
537+
_, _ = fmt.Fprintf(os.Stderr, "Package %s was just auto-registered; re-run 'cozypkg add %s' to install variant %q as your own\n", pkgName, pkgName, variant)
538+
continue
539+
}
503540

504541
fmt.Fprintf(os.Stderr, "✓ Added Package %s\n", pkgName)
505542
}
506543

507544
return nil
508545
}
509546

547+
// tapSourceName returns the PackageSource's tap source (its OCIRepository name),
548+
// or "" when it is not a tapped source; it is the name collision.ManagedRegistration
549+
// matches a registration Package's tap-source annotation against.
550+
func tapSourceName(ps *cozyv1alpha1.PackageSource) string {
551+
if ps != nil && ps.Spec.SourceRef != nil {
552+
return ps.Spec.SourceRef.Name
553+
}
554+
return ""
555+
}
556+
557+
// handoverManagedRegistration converts a tap-managed auto-registration Package
558+
// into a plain user Package pinned to variant and persists it. Running `cozypkg
559+
// add` is the operator's explicit ownership handover: pinRegistrationToUser sheds
560+
// the tap markers and the PackageSource ownerRef so the materializer no longer
561+
// manages or de-registers the Package, and so a later revision that turns the
562+
// variant privileged cannot silently reinstall over the user's deliberate choice.
563+
func handoverManagedRegistration(ctx context.Context, k8sClient client.Client, installed *cozyv1alpha1.Package, variant string) error {
564+
pinRegistrationToUser(installed, variant)
565+
return k8sClient.Update(ctx, installed)
566+
}
567+
568+
// pinRegistrationToUser turns a tap auto-registration Package into a plain
569+
// user-owned Package pinned to variant: it sets the variant and sheds the tap
570+
// markers (label, source annotation) and the PackageSource ownerReference, so the
571+
// tap materializer no longer manages or de-registers it and untap treats it as
572+
// the user's.
573+
func pinRegistrationToUser(pkg *cozyv1alpha1.Package, variant string) {
574+
pkg.Spec.Variant = variant
575+
delete(pkg.Labels, tapconst.Label)
576+
delete(pkg.Annotations, tapconst.SourceAnnotation)
577+
kept := pkg.OwnerReferences[:0]
578+
for _, ref := range pkg.OwnerReferences {
579+
if ref.Kind != "PackageSource" {
580+
kept = append(kept, ref)
581+
}
582+
}
583+
pkg.OwnerReferences = kept
584+
}
585+
586+
// createPackageIdempotent creates pkg and reports whether it created a new
587+
// object. A tapped repository registers its apps on connect, so the Package may
588+
// already exist; that is treated as done (created=false) rather than an error.
589+
func createPackageIdempotent(ctx context.Context, k8sClient client.Client, pkg *cozyv1alpha1.Package) (bool, error) {
590+
if err := k8sClient.Create(ctx, pkg); err != nil {
591+
if apierrors.IsAlreadyExists(err) {
592+
return false, nil
593+
}
594+
return false, err
595+
}
596+
return true, nil
597+
}
598+
510599
// selectVariantInteractive prompts user to select a variant
511600
func selectVariantInteractive(ps *cozyv1alpha1.PackageSource) (string, error) {
512601
if len(ps.Spec.Variants) == 0 {
@@ -554,23 +643,6 @@ func selectVariantInteractive(ps *cozyv1alpha1.PackageSource) (string, error) {
554643
}
555644
}
556645

557-
// privilegedComponents returns the names of components in the given variant
558-
// that declare install.privileged: true.
559-
func privilegedComponents(ps *cozyv1alpha1.PackageSource, variantName string) []string {
560-
var names []string
561-
for _, v := range ps.Spec.Variants {
562-
if v.Name != variantName {
563-
continue
564-
}
565-
for _, c := range v.Components {
566-
if c.Install != nil && c.Install.Privileged {
567-
names = append(names, c.Name)
568-
}
569-
}
570-
}
571-
return names
572-
}
573-
574646
// confirmPrivileged prompts the operator to confirm installing privileged
575647
// components. It defaults to No.
576648
func confirmPrivileged(pkgName, variant string, components []string) (bool, error) {

‎cmd/cozypkg/cmd/add_test.go‎

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,18 @@ limitations under the License.
1717
package cmd
1818

1919
import (
20+
"context"
2021
"testing"
2122

2223
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
24+
"github.com/cozystack/cozystack/internal/marketplace/collision"
25+
"github.com/cozystack/cozystack/internal/marketplace/tapconst"
26+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27+
"k8s.io/apimachinery/pkg/runtime"
28+
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
29+
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
30+
"sigs.k8s.io/controller-runtime/pkg/client"
31+
"sigs.k8s.io/controller-runtime/pkg/client/fake"
2332
)
2433

2534
func TestPrivilegedComponents(t *testing.T) {
@@ -41,13 +50,79 @@ func TestPrivilegedComponents(t *testing.T) {
4150
},
4251
}
4352

44-
if got := privilegedComponents(ps, "default"); len(got) != 1 || got[0] != "risky" {
53+
if got := collision.PrivilegedInstallComponents(ps, "default"); len(got) != 1 || got[0] != "risky" {
4554
t.Errorf("default variant privileged = %v, want [risky]", got)
4655
}
47-
if got := privilegedComponents(ps, "safe"); len(got) != 0 {
56+
if got := collision.PrivilegedInstallComponents(ps, "safe"); len(got) != 0 {
4857
t.Errorf("safe variant should have no privileged components, got %v", got)
4958
}
50-
if got := privilegedComponents(ps, "nonexistent"); len(got) != 0 {
59+
if got := collision.PrivilegedInstallComponents(ps, "nonexistent"); len(got) != 0 {
5160
t.Errorf("unknown variant should return none, got %v", got)
5261
}
5362
}
63+
64+
func TestPinRegistrationToUser(t *testing.T) {
65+
pkg := &cozyv1alpha1.Package{
66+
ObjectMeta: metav1.ObjectMeta{
67+
Labels: map[string]string{tapconst.Label: "true", "keep": "me"},
68+
Annotations: map[string]string{tapconst.SourceAnnotation: "tap-a", "keep": "me"},
69+
OwnerReferences: []metav1.OwnerReference{
70+
{Kind: "PackageSource", Name: "acme.app"},
71+
{Kind: "SomethingElse", Name: "other"},
72+
},
73+
},
74+
}
75+
pinRegistrationToUser(pkg, "full")
76+
if pkg.Spec.Variant != "full" {
77+
t.Errorf("variant not pinned, got %q", pkg.Spec.Variant)
78+
}
79+
if pkg.GetLabels()[tapconst.Label] == "true" {
80+
t.Error("a pinned Package must no longer carry the tap label")
81+
}
82+
if _, ok := pkg.Labels[tapconst.Label]; ok {
83+
t.Error("tap label must be shed")
84+
}
85+
if _, ok := pkg.Annotations[tapconst.SourceAnnotation]; ok {
86+
t.Error("source annotation must be shed")
87+
}
88+
if pkg.Labels["keep"] != "me" || pkg.Annotations["keep"] != "me" {
89+
t.Error("unrelated labels/annotations must be preserved")
90+
}
91+
if len(pkg.OwnerReferences) != 1 || pkg.OwnerReferences[0].Kind != "SomethingElse" {
92+
t.Errorf("only the PackageSource ownerRef must be dropped, got %+v", pkg.OwnerReferences)
93+
}
94+
}
95+
96+
func TestHandoverManagedRegistration(t *testing.T) {
97+
s := runtime.NewScheme()
98+
utilruntime.Must(clientgoscheme.AddToScheme(s))
99+
utilruntime.Must(cozyv1alpha1.AddToScheme(s))
100+
pkg := &cozyv1alpha1.Package{ObjectMeta: metav1.ObjectMeta{
101+
Name: "acme.app",
102+
Labels: map[string]string{tapconst.Label: "true"},
103+
Annotations: map[string]string{tapconst.SourceAnnotation: "tap-acme-app"},
104+
OwnerReferences: []metav1.OwnerReference{{APIVersion: "cozystack.io/v1alpha1", Kind: "PackageSource", Name: "acme.app"}},
105+
}}
106+
cl := fake.NewClientBuilder().WithScheme(s).WithObjects(pkg).Build()
107+
if err := handoverManagedRegistration(context.Background(), cl, pkg, "full"); err != nil {
108+
t.Fatalf("handover: %v", err)
109+
}
110+
var got cozyv1alpha1.Package
111+
if err := cl.Get(context.Background(), client.ObjectKey{Name: "acme.app"}, &got); err != nil {
112+
t.Fatal(err)
113+
}
114+
if got.Spec.Variant != "full" {
115+
t.Errorf("variant not pinned, got %q", got.Spec.Variant)
116+
}
117+
if got.Labels[tapconst.Label] == "true" {
118+
t.Error("tap label must be shed on handover")
119+
}
120+
if _, ok := got.Annotations[tapconst.SourceAnnotation]; ok {
121+
t.Error("source annotation must be shed on handover")
122+
}
123+
for _, ref := range got.OwnerReferences {
124+
if ref.Kind == "PackageSource" {
125+
t.Error("PackageSource ownerRef must be shed on handover")
126+
}
127+
}
128+
}

0 commit comments

Comments
 (0)