From 2088de19c73a24d246883f19ff6a41bafe37bb79 Mon Sep 17 00:00:00 2001 From: Thibaut Lapierre Date: Mon, 30 Nov 2026 09:51:05 +0100 Subject: [PATCH 1/9] desktops: staged only where they are on, shown while git alone declares them Assisted by LLM --- cmd/dotvirt/main.go | 2 +- docs/personas.md | 9 ++ internal/api/api.go | 8 +- internal/api/coordinator_test.go | 73 ++++------ internal/api/desktop_create_test.go | 125 ++++++++++++++-- internal/api/desktops_git_test.go | 73 +++++++++- internal/api/fakecluster_test.go | 20 ++- internal/api/gates_test.go | 4 +- internal/api/handlers_capabilities.go | 33 ++++- internal/api/handlers_desktops.go | 66 ++++++++- internal/api/handlers_draft.go | 44 +----- internal/api/handlers_objects.go | 29 +++- internal/api/routes.go | 2 + internal/api/watermark.go | 12 +- internal/argo/argo.go | 21 ++- internal/argo/snapshot.go | 89 ++++++------ internal/argo/snapshot_test.go | 133 ++++++++++++++---- internal/changeset/changeset.go | 18 ++- internal/changeset/desktops.go | 50 ++++++- internal/changeset/desktops_test.go | 133 ++++++++++++++++++ internal/changeset/drift.go | 51 +++++-- internal/changeset/gate.go | 43 ++++-- internal/changeset/needs.go | 44 ++++-- internal/changeset/resync_test.go | 66 +++++++-- internal/changeset/revert.go | 21 +-- internal/desktops/desktops.go | 23 +++ internal/model/caps.go | 12 +- internal/model/desktop.go | 20 +++ web/e2e/fixture/create.mjs | 22 ++- web/e2e/fixture/scenarios.mjs | 56 ++++++++ web/e2e/fixture/server.mjs | 30 +++- web/e2e/ui/desktopsingit.spec.ts | 104 ++++++++++++++ web/src/lib/api.ts | 7 + .../components/create/DesktopOneForm.svelte | 13 +- .../components/create/DesktopPoolForm.svelte | 14 +- web/src/lib/desktops.test.ts | 45 +++++- web/src/lib/desktops.ts | 32 ++++- web/src/lib/gates.test.ts | 27 ++++ web/src/lib/gates.ts | 28 +++- web/src/lib/model.gen.ts | 31 ++++ web/src/lib/state/desktops.test.ts | 1 + web/src/lib/tree/DesktopsTree.svelte | 33 ++++- .../lib/workspace/desktops/DesktopPage.svelte | 18 ++- .../workspace/desktops/DesktopsRoot.svelte | 12 +- .../workspace/desktops/DesktopsScope.svelte | 36 ++++- .../lib/workspace/desktops/InGitBody.svelte | 29 ++++ .../lib/workspace/desktops/InGitNext.svelte | 87 ++++++++++++ .../lib/workspace/desktops/InGitTable.svelte | 67 +++++++++ .../lib/workspace/desktops/PoolPage.svelte | 23 ++- 49 files changed, 1633 insertions(+), 306 deletions(-) create mode 100644 web/e2e/ui/desktopsingit.spec.ts create mode 100644 web/src/lib/workspace/desktops/InGitBody.svelte create mode 100644 web/src/lib/workspace/desktops/InGitNext.svelte create mode 100644 web/src/lib/workspace/desktops/InGitTable.svelte diff --git a/cmd/dotvirt/main.go b/cmd/dotvirt/main.go index 22dcdded4..6757ab3c5 100644 --- a/cmd/dotvirt/main.go +++ b/cmd/dotvirt/main.go @@ -288,7 +288,7 @@ func run() error { coordinator := changeset.New(draftStore, repos, forgeFactory, resyncer, liveVMs{clusterSnapshot}, pruneSource, cfg.BaseBranch, cfg.ProposedBranch).WithSyncNamespace(cfg.ArgoNamespace). WithTenantKinds(cfg.TenantKinds).WithUsersOpeningPRs(cfg.UsersOpenPRs).WithPublishing(publishing).WithDesktops(desktopsSnapshot). - WithProductName(cfg.ProductName) + WithProductName(cfg.ProductName).WithPlatformRepo(cfg.PlatformRepo) if cfg.ForgeDelegated { coordinator.WithDelegation(delegation) } diff --git a/docs/personas.md b/docs/personas.md index 52e064475..580527c53 100644 --- a/docs/personas.md +++ b/docs/personas.md @@ -99,6 +99,10 @@ It stages one RoleBinding in the platform repo, beside the namespace's admin gra | --- | --- | --- | | `-desktops` | `dotvirt-tenant-desktops` | the admin grant's subjects, the project's sync account among them | +Turn desktops on before any pool or desktop is staged in the namespace: until git holds that grant, the project's account may not apply one, so dotvirt refuses to stage it, and its form says so first. +That is told to whoever may list the namespace's role bindings, or could make a pool or a desktop there. +Classes need no such step: the platform repo's account writes them cluster-wide. + `dotvirt-tenant-desktops` holds the rules of DeskuBe's pool editor, desktop editor and claim user roles, and create on pairing requests: pool and desktop writes, `use` on pools, and the claim verbs. DeskuBe's admission asks these of whoever sets a pool's subjects or a desktop's owner, the sync account included. The admin grant beside it carries the rest DeskuBe asks of a desktop's owner: create on rolebindings, and get on the desktop's admin Secret. @@ -133,6 +137,11 @@ DeskuBe aggregates its pool, claim and desktop viewer roles into `view`, so ever No persona reads pairing requests. Whoever reads a pool, or a desktop made one by one, is shown the file declaring it and its Argo CD sync and health, its manifest, its history and each change in it. +One git declares that the cluster does not run is a row and a page of its own, In git, not running, with the same, and what it waits on: +- desktops turned on there, to whoever is told they are off; +- a resync, where Argo CD's last sync failed on the revision declaring it: Argo CD never tries that revision again by itself; +- else Argo CD's own apply error. +A resync syncs that one pool or desktop from git, as a VM's does, by whoever may change it, weighed under their own rights, and only where desktops are on. A class's file goes to who may create classes; its apply error too, the other class readers seeing that it failed. Adopting one asks create or update on its kind, and a repo that may declare it; until then a caller who could is told what holds it back. A new pool, or a desktop made one by one, is staged as a file of its own from its project's Desktops page, by whoever may create its kind there; a new class goes to the platform repo, by who may create classes. diff --git a/internal/api/api.go b/internal/api/api.go index 40fd81f50..b0b5d7352 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -174,7 +174,7 @@ type Draft interface { // the implementation weighs what the sync applies under id's own token // before escalating, so no future caller can reach the SA-privileged patch // unchecked. - Resync(ctx context.Context, id auth.Identity, proj project.ProjectInfo, namespace, name string) (model.ResyncResult, error) + Resync(ctx context.Context, id auth.Identity, proj project.ProjectInfo, kind model.Kind, namespace, name string) (model.ResyncResult, error) // The Needs are what the gate would ask of a tenancy or DRS change the // matching route stages, unstaged: the capability signals weigh them. ProjectNeeds(commitProj project.ProjectInfo, spec json.RawMessage) ([]changeset.Access, error) @@ -184,10 +184,14 @@ type Draft interface { PublishingNeeds(commitProj, target project.ProjectInfo, pt changeset.PublishTarget) (changeset.PublishPlan, []changeset.Access, error) PublishNamespaceNeeds(commitProj, target project.ProjectInfo, pt changeset.PublishTarget) ([]changeset.Access, error) DesktopsNeeds(commitProj, target project.ProjectInfo, ns string) (on bool, need []changeset.Access, err error) + // DesktopsOn reports whether commitProj, the platform repo, turns + // desktops on in ns: the one answer the gate refuses a pool or a desktop + // by. + DesktopsOn(commitProj project.ProjectInfo, ns string) (bool, error) ReleaseNeeds(commitProj, target project.ProjectInfo) (need []changeset.Access, residue []string, err error) EnableDRSNeeds(proj project.ProjectInfo, spec json.RawMessage) ([]changeset.Access, error) DisableDRSNeeds(proj project.ProjectInfo) ([]changeset.Access, error) - ResyncNeeds(proj project.ProjectInfo, namespace, name string) ([]changeset.Access, error) + ResyncNeeds(proj project.ProjectInfo, kind model.Kind, namespace, name string) ([]changeset.Access, error) Revert(id auth.Identity, proj project.ProjectInfo, hash string, ack model.PruneSet) (model.ProposeResult, error) RevertPrune(id auth.Identity, proj project.ProjectInfo, hash string) (model.PruneSet, error) // RestoreVersion stages one object's manifest as a past commit held it: diff --git a/internal/api/coordinator_test.go b/internal/api/coordinator_test.go index f0e3f88bc..d944dc754 100644 --- a/internal/api/coordinator_test.go +++ b/internal/api/coordinator_test.go @@ -26,7 +26,6 @@ import ( "github.com/epheo/dotvirt/internal/model" "github.com/epheo/dotvirt/internal/netgen" "github.com/epheo/dotvirt/internal/netstate" - "github.com/epheo/dotvirt/internal/project" "github.com/epheo/dotvirt/internal/publish" "github.com/epheo/dotvirt/pkg/forge" "github.com/epheo/dotvirt/pkg/tenancy" @@ -246,7 +245,7 @@ func (liveOff) Ready() bool { return true } type resyncOK struct{} -func (resyncOK) Resync(context.Context, string, string, string) (model.ResyncResult, error) { +func (resyncOK) Resync(context.Context, string, model.Kind, string, string) (model.ResyncResult, error) { return model.ResyncResult{Application: "app"}, nil } @@ -391,52 +390,36 @@ func TestDesktopsOnFollowsBindingReads(t *testing.T) { } } -// Adopting a pool or a desktop into a namespace without desktops on warns -// that its project's account may not apply it: whether they are on only to a -// caller who may list rolebindings there, the same words to every other. -func TestAdoptingDesktopsWarnsWhereDesktopsAreOff(t *testing.T) { - item := func(r draft.Resource, name string) model.DraftItem { - return model.DraftItem{Resource: string(r), Namespace: "team-a-dev", Name: name} - } - path, binding, err := netgen.DesktopsManifest(netgen.RoleBindingSpec{Namespace: "team-a-dev", Kept: []netgen.Subject{{Kind: "User", Name: "alice"}}}) +// Desktops off is told in a namespace's capabilities as the Configure tab +// tells it, to who may list rolebindings there, and as staging one tells +// it, to who could write a pool or a desktop there; never to anyone else, +// whatever git holds. +func TestDesktopsOffIsToldAsTheyWouldHearIt(t *testing.T) { + path, binding, err := netgen.DesktopsManifest(netgen.RoleBindingSpec{Namespace: "team-a-dev", Project: "team-a", Kept: []netgen.Subject{{Kind: "User", Name: "alice"}}}) if err != nil { t.Fatal(err) } - for _, tc := range []struct { - staged []model.DraftItem - neutral string - }{ - {[]model.DraftItem{item(draft.ResourceDesktopPool, "design")}, - "team-a-dev: desktop pools apply only where a platform admin has turned desktops on."}, - {[]model.DraftItem{item(draft.ResourceDesktop, "alice-desk")}, - "team-a-dev: desktops apply only where a platform admin has turned desktops on."}, - {[]model.DraftItem{item(draft.ResourceDesktop, "alice-desk"), item(draft.ResourceDesktopPool, "design")}, - "team-a-dev: desktop pools and desktops apply only where a platform admin has turned desktops on."}, - } { - v := model.DraftView{Items: tc.staged} - for _, on := range []bool{false, true} { - files := map[string]string{} - if on { - files[path] = string(binding) - } - g := newCoordinatorRig(t, files) - warning := func(grants []grant, v model.DraftView) string { - t.Helper() - id, c, err := g.s.userCluster(asUser(httptest.NewRequest(http.MethodGet, "/", nil), g.token(grants))) - if err != nil { - t.Fatal(err) - } - return g.s.desktopsWarning(t.Context(), scope{id: id, cluster: c, proj: project.ProjectInfo{Name: "team-a"}}, "team-a-dev", v) - } - lister := []grant{kind(verbList, model.KindRB, "team-a-dev")} - if got := warning(lister, v); on && got != "" || !on && !strings.Contains(got, "desktops are not on there") { - t.Errorf("on=%v, %d staged, told: %q", on, len(tc.staged), got) - } - if got := warning(nil, v); got != tc.neutral { - t.Errorf("on=%v, not told: %q, want %q either way", on, got, tc.neutral) - } - if got := warning(lister, model.DraftView{}); got != "" { - t.Errorf("on=%v, nothing of DeskuBe's staged: %q", on, got) + var author []grant + for _, k := range []model.Kind{model.KindVdiPool, model.KindVdiInstance} { + author = append(author, kind(verbCreate, k, "team-a-dev"), kind(verbUpdate, k, "team-a-dev")) + } + for _, on := range []bool{false, true} { + files := map[string]string{} + if on { + files[path] = string(binding) + } + g := newCoordinatorRig(t, files) + for _, c := range []struct { + who string + grants []grant + told bool + }{ + {"a rolebinding lister", []grant{kind(verbList, model.KindRB, "team-a-dev")}, true}, + {"a pool and desktop writer", author, true}, + {"anyone else", []grant{kind(verbList, model.KindVdiPool, "team-a-dev")}, false}, + } { + if _, nc := g.caps(g.token(c.grants), "team-a-dev"); nc.DesktopsOff != (c.told && !on) { + t.Errorf("desktops on=%v, %s is told off=%v", on, c.who, nc.DesktopsOff) } } } diff --git a/internal/api/desktop_create_test.go b/internal/api/desktop_create_test.go index da7a476ef..065f799d5 100644 --- a/internal/api/desktop_create_test.go +++ b/internal/api/desktop_create_test.go @@ -1,6 +1,8 @@ package api import ( + "context" + "encoding/json" "net/http" "slices" "strings" @@ -14,26 +16,38 @@ import ( "github.com/epheo/dotvirt/internal/draft" "github.com/epheo/dotvirt/internal/git" "github.com/epheo/dotvirt/internal/model" + "github.com/epheo/dotvirt/internal/netgen" "github.com/epheo/dotvirt/pkg/tenancy" ) var desktopKinds = tenancy.Policy{Allowed: []tenancy.GroupKind{{Group: desktops.Group, Kind: "VdiPool"}, {Group: desktops.Group, Kind: "VdiInstance"}}} -// createServer serves team-a-dev's repo, declaring pool eng, which does not -// run, and the platform repo, declaring class office, through the real -// coordinator over the desktops as they run: pool lab, desktop solo and class -// workstation among them. kinds is what a tenant repo may declare. author -// may write pools and desktops in team-a-dev and grant nothing; admin may -// also bind and claim there, as DeskuBe asks of whoever grants; classes may -// create classes alone; viewer lists them all. +// createServer is deskServer with desktops on in team-a-dev. func createServer(t *testing.T, kinds tenancy.Policy) *Server { + t.Helper() + return deskServer(t, kinds, true, nil) +} + +// deskServer serves team-a-dev's repo, declaring pool eng, which does not +// run, and the platform repo, declaring class office and, when on, the +// grant turning desktops on in team-a-dev, through the real coordinator over +// the desktops as they run: pool lab, desktop solo and class workstation +// among them, Argo CD's syncs going to rs. kinds is what a tenant repo may +// declare. author may write +// pools and desktops in team-a-dev and grant nothing; admin may also bind +// and claim there, as DeskuBe asks of whoever grants; classes may create +// classes alone; viewer lists them all. +func deskServer(t *testing.T, kinds tenancy.Policy, on bool, rs changeset.Resyncer) *Server { t.Helper() tenant, _, _ := seedCommits(t, map[string]string{"team-a-dev/side.yaml": "x: 1\n"}, map[string]string{ "team-a-dev/desktop-pools/eng.yaml": poolManifest("eng", 2), }) - platform, _, _ := seedCommits(t, map[string]string{"side.yaml": "x: 1\n"}, map[string]string{ - "desktop-classes/office.yaml": classManifest("office", 1), - }) + merged := map[string]string{"desktop-classes/office.yaml": classManifest("office", 1)} + if on { + path, grant := desktopsOnFile(t) + merged[path] = grant + } + platform, _, _ := seedCommits(t, map[string]string{"side.yaml": "x: 1\n"}, merged) fc := newFakeCluster(t) fc.namespaces[0].Annotations["dotvirt.io/repo"] = tenant fc.readsVMs = func(token, ns string) bool { return ns == "team-a-dev" } @@ -58,13 +72,25 @@ func createServer(t *testing.T, kinds tenancy.Policy) *Server { t.Fatal(err) } repos := git.NewRepoSet(t.Context(), "", "", nil, false, nil, time.Hour) - co := changeset.New(store, repos, nil, nil, nil, nil, "main", "dotvirt/proposed").WithTenantKinds(kinds) + co := changeset.New(store, repos, nil, rs, nil, nil, "main", "dotvirt/proposed").WithTenantKinds(kinds).WithPlatformRepo(platform) s := desktopsServerWith(t, fc, &desktopsSource{held: true}, co, Config{BaseBranch: "main", TenantKinds: kinds, PlatformRepo: platform}) co.UseAuthorizer(s) co.WithDesktops(s.desktops) return s } +// desktopsOnFile is the platform repo's file turning desktops on in +// team-a-dev. +func desktopsOnFile(t *testing.T) (path, content string) { + t.Helper() + path, grant, err := netgen.DesktopsManifest(netgen.RoleBindingSpec{Namespace: "team-a-dev", Project: "team-a", + Kept: []netgen.Subject{{Kind: "User", APIGroup: "rbac.authorization.k8s.io", Name: "alice"}}}) + if err != nil { + t.Fatal(err) + } + return path, string(grant) +} + const ( newPool = `{"namespace":"team-a-dev","name":"design","class":"workstation","seats":4,"warm":1,"assignment":"Personal","idleTimeout":"30m","releaseAfter":"720h","subjects":[{"kind":"Group","name":"designers"}]}` newDesktop = `{"namespace":"team-a-dev","name":"carol-dev","owner":"carol","class":"workstation","running":true}` @@ -259,3 +285,80 @@ func TestDesktopCreatesWaitOnTheSyncAccount(t *testing.T) { t.Errorf("caps = %+v, want no create and held said", c) } } + +const desktopsOffSays = "desktops are not on for team-a-dev: a platform admin turns them on from the project's Configure tab" + +// Where desktops are not on, no pool or desktop is offered, whoever could +// make one is told why, and each route writing one refuses it, naming the fix +// and who makes it; once on, each passes. Git's pool that never ran is a row +// of its own, with its file. +func TestDesktopsWaitToBeTurnedOn(t *testing.T) { + put := func(yaml string) string { + raw, _ := json.Marshal(model.UpdateManifestRequest{YAML: yaml}) + return string(raw) + } + pool := `{"namespace":"team-a-dev","name":"open","class":"workstation","seats":2}` + writes := []struct{ name, method, path, body string }{ + {"a new pool", http.MethodPost, "/api/desktoppools", pool}, + {"a new pool's dry run", http.MethodPost, "/api/desktoppools?dryRun=true", pool}, + {"a new desktop", http.MethodPost, "/api/desktops", `{"namespace":"team-a-dev","name":"spare","class":"workstation","running":true}`}, + {"git's pool, edited", http.MethodPut, "/api/objects/desktoppool/team-a-dev/eng", put(poolManifest("eng", 3))}, + } + for _, on := range []bool{false, true} { + s := deskServer(t, desktopKinds, on, nil) + for _, w := range writes { + rec := do(s, "admin", w.method, w.path, w.body) + switch { + case on && rec.Code != http.StatusOK: + t.Errorf("%s, desktops on: %d %q", w.name, rec.Code, rec.Body.String()) + case !on && (rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), desktopsOffSays)): + t.Errorf("%s, desktops off: %d %q, want refused naming the fix", w.name, rec.Code, rec.Body.String()) + } + } + for _, token := range []string{"admin", "author"} { + c := decodeBody[model.Capabilities](t, do(s, token, http.MethodGet, "/api/capabilities?namespace=team-a-dev", "")).Namespace + if c.DesktopPool.Create != on || c.Desktop.Update != on || c.DesktopsOff == on || c.DesktopsHeld { + t.Errorf("desktops on=%v, %s's caps %+v", on, token, c) + } + } + if c := decodeBody[model.Capabilities](t, do(s, "viewer", http.MethodGet, "/api/capabilities?namespace=team-a-dev", "")).Namespace; c.DesktopsOff { + t.Errorf("desktops on=%v, told off to a viewer who may list no rolebindings", on) + } + got := getDesktops(t, s, "viewer", "/api/desktops") + if want := []model.DesktopInGit{{Resource: "vdipools", Namespace: "team-a-dev", Name: "eng", SourceFile: "team-a-dev/desktop-pools/eng.yaml"}}; !slices.Equal(got.InGit, want) { + t.Errorf("desktops on=%v: in git, not running = %+v, want %+v", on, got.InGit, want) + } + } +} + +// syncRecorder records each sync asked of Argo CD. +type syncRecorder struct{ synced []string } + +func (r *syncRecorder) Resync(_ context.Context, _ string, k model.Kind, ns, name string) (model.ResyncResult, error) { + r.synced = append(r.synced, k.Kind+" "+ns+"/"+name) + return model.ResyncResult{Application: "team-a"}, nil +} + +// A pool or a desktop git declares is synced alone from its own route, by +// who may change it, through the VMs' Resync: weighed as the caller beside +// the escalation, and only where desktops are on. +func TestDeclaredDesktopsResyncAlone(t *testing.T) { + for _, on := range []bool{false, true} { + rs := &syncRecorder{} + s := deskServer(t, desktopKinds, on, rs) + rec := do(s, "admin", http.MethodPost, "/api/objects/desktoppool/team-a-dev/eng/resync", "") + switch { + case on && (rec.Code != http.StatusOK || !slices.Equal(rs.synced, []string{"VdiPool team-a-dev/eng"})): + t.Errorf("desktops on: %d %q, synced %v", rec.Code, rec.Body.String(), rs.synced) + case !on && (rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), desktopsOffSays) || len(rs.synced) != 0): + t.Errorf("desktops off: %d %q, synced %v", rec.Code, rec.Body.String(), rs.synced) + } + rs.synced = nil + wantStatus(t, do(s, "viewer", http.MethodPost, "/api/objects/desktoppool/team-a-dev/eng/resync", ""), http.StatusForbidden) + wantStatus(t, do(s, "admin", http.MethodPost, "/api/objects/desktoppool/team-a-dev/ghost/resync", ""), http.StatusNotFound) + wantStatus(t, do(s, "admin", http.MethodPost, "/api/objects/network/team-a-dev/eng/resync", ""), http.StatusBadRequest) + if len(rs.synced) != 0 { + t.Errorf("desktops on=%v: refused syncs reached Argo CD: %v", on, rs.synced) + } + } +} diff --git a/internal/api/desktops_git_test.go b/internal/api/desktops_git_test.go index d586ee8ef..ecdb20075 100644 --- a/internal/api/desktops_git_test.go +++ b/internal/api/desktops_git_test.go @@ -149,6 +149,61 @@ func TestDesktopsPullTellsGitWithinTheCallersRights(t *testing.T) { } } +// A pool or a desktop git declares and the cluster does not run is a row of +// its own: its file, and Argo CD's sync, health and apply error for it, +// stalled where Argo CD gave up on the revision declaring it, to whoever may +// list its kind there; nothing of it to anyone else. +func TestDeclaredDesktopsThatDoNotRun(t *testing.T) { + const pools = "pools" + fc := newFakeCluster(t) + fc.readsVMs = func(token, ns string) bool { + return (token == tenantToken || token == pools) && slices.Contains(teams, ns) + } + fc.ssar = func(token string, a *authzv1.ResourceAttributes) bool { + if token == pools { + return a.Verb == verbList && a.Group == desktops.Group && a.Resource == "vdipools" && a.Namespace == "team-a-dev" + } + return listsKinds(allKinds, "team-a-dev")(token, a) + } + d := &planeDraft{declared: deskDeclared()} + d.declared[model.ObjectRef{Kind: "VdiInstance", Namespace: "team-a-dev", Name: "de"}] = "team-a-dev/desktops/de.yaml" + d.declared[model.ObjectRef{Kind: "VdiPool", Namespace: "team-a-dev", Name: "design"}] = "team-a-dev/desktop-pools/design.yaml" + d.declared[model.ObjectRef{Kind: "VdiInstance", Namespace: "team-b-dev", Name: "de"}] = "team-b-dev/desktops/de.yaml" + s := desktopsServerWith(t, fc, &desktopsSource{held: true}, d, Config{PlatformRepo: "https://forge/platform.git"}) + const forbidden = `vdiinstances.vdi.desku.be is forbidden: User "system:serviceaccount:openshift-gitops:dotvirt-p-team-a" cannot create resource "vdiinstances"` + app := deskApp("1", append(slices.Clone(deskDrift), + deskRes{"VdiInstance", "team-a-dev", "de", "OutOfSync", "Missing", forbidden}, + deskRes{"VdiInstance", "team-b-dev", "de", "OutOfSync", "Missing", forbidden})...) + // Argo CD's last sync failed on the revision it compares: it gave up. + status := app["status"].(map[string]any) + status["sync"] = map[string]any{"revision": "c1"} + status["operationState"].(map[string]any)["syncResult"].(map[string]any)["revision"] = "c1" + fc.on(http.MethodGet, applications, unstructuredList("argoproj.io/v1alpha1", "Application", app)) + _ = fc.watch(applications) + s.drift = syncedSnapshot(t, fc) + + got := getDesktops(t, s, tenantToken, "/api/desktops") + want := []model.DesktopInGit{ + {Resource: "vdiinstances", Namespace: "team-a-dev", Name: "de", SourceFile: "team-a-dev/desktops/de.yaml", + Sync: model.SyncOutOfSync, Health: "Missing", SyncError: forbidden, SyncStalled: true}, + {Resource: "vdiinstances", Namespace: "team-a-dev", Name: "kept", SourceFile: "team-a-dev/desktops/kept.yaml"}, + {Resource: "vdipools", Namespace: "team-a-dev", Name: "design", SourceFile: "team-a-dev/desktop-pools/design.yaml"}, + } + if !slices.Equal(got.InGit, want) { + t.Errorf("the tenant's rows in git, not running = %+v, want %+v", got.InGit, want) + } + + body := desktopsBody(t, s, pools, "/api/desktops") + for _, leak := range []string{"forbidden", "de.yaml", "kept", "team-b-dev/"} { + if strings.Contains(body, leak) { + t.Errorf("a pool reader's pull carries %q: %s", leak, body) + } + } + if got := getDesktops(t, s, pools, "/api/desktops"); !slices.Equal(got.InGit, want[2:]) { + t.Errorf("a pool reader's rows = %+v, want the pool alone", got.InGit) + } +} + // A partial viewer's version moves with what its pull shows of git and of // Argo CD: a merge or a drift where it reads, never one where it does not. func TestDesktopsVersionMovesOnAMergeAndOnDrift(t *testing.T) { @@ -181,6 +236,10 @@ func TestDesktopsVersionMovesOnAMergeAndOnDrift(t *testing.T) { moved("a merge removing its desktop's file", true) d.declared[model.ObjectRef{Kind: "VdiInstance", Namespace: "team-a-dev", Name: "lab-2"}] = "team-a-dev/desktops/lab-2.yaml" moved("a file declaring a pool's desktop", false) + d.declared[model.ObjectRef{Kind: "VdiPool", Namespace: "team-a-dev", Name: "design"}] = "team-a-dev/desktop-pools/design.yaml" + moved("a merge declaring a pool that does not run", true) + d.declared[model.ObjectRef{Kind: "VdiPool", Namespace: "team-b-dev", Name: "design"}] = "team-b-dev/desktop-pools/design.yaml" + moved("one where the tenant lists nothing", false) next := slices.Clone(deskDrift) next[3].health = "Healthy" @@ -206,8 +265,9 @@ func TestDesktopObjectRoutes(t *testing.T) { }, map[string]string{"team-a-dev/desktop-pools/lab.yaml": poolManifest("lab", 4)}, ) + grantPath, grant := desktopsOnFile(t) platform, pc, _ := seedCommits(t, map[string]string{"side.yaml": "x: 1\n"}, - map[string]string{"desktop-classes/workstation.yaml": classManifest("workstation", 1)}, + map[string]string{"desktop-classes/workstation.yaml": classManifest("workstation", 1), grantPath: grant}, map[string]string{"desktop-classes/workstation.yaml": classManifest("workstation", 2)}, ) @@ -260,7 +320,7 @@ func TestDesktopObjectRoutes(t *testing.T) { } repos := git.NewRepoSet(t.Context(), "", "", nil, false, nil, time.Hour) kinds := tenancy.Policy{Allowed: []tenancy.GroupKind{{Group: desktops.Group, Kind: "VdiPool"}, {Group: desktops.Group, Kind: "VdiInstance"}}} - co := changeset.New(store, repos, nil, nil, nil, nil, "main", "dotvirt/proposed").WithTenantKinds(kinds) + co := changeset.New(store, repos, nil, nil, nil, nil, "main", "dotvirt/proposed").WithTenantKinds(kinds).WithPlatformRepo(platform) s := desktopsServerWith(t, fc, &desktopsSource{held: true}, co, Config{BaseBranch: "main", PlatformRepo: platform, TenantKinds: kinds}) co.UseAuthorizer(s) @@ -333,8 +393,8 @@ func TestDesktopObjectRoutes(t *testing.T) { } } - // Adopted where the capture finds it, with the warning a namespace - // adoption carries; a pool's desktop never, said only to its readers. + // Adopted where the capture finds it, desktops being on there; a pool's + // desktop never, said only to its readers. adopt := func(token, path string, status int) model.DraftView { t.Helper() rec := do(s, token, http.MethodPost, path+"/adopt", "") @@ -349,8 +409,7 @@ func TestDesktopObjectRoutes(t *testing.T) { return it.Resource == resource && it.Name == name && it.Kind == "create" }) } - if v := adopt(tenantToken, pool("design"), http.StatusOK); !staged(v, "desktoppool", "design") || - !strings.Contains(v.Warning, "team-a-dev: desktop pools apply only where a platform admin has turned desktops on.") { + if v := adopt(tenantToken, pool("design"), http.StatusOK); !staged(v, "desktoppool", "design") || v.Warning != "" { t.Errorf("design adopted = %+v", v) } // carol's owner is a grant git never held: DeskuBe asks its writer for @@ -359,7 +418,7 @@ func TestDesktopObjectRoutes(t *testing.T) { if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "you may not create rolebindings in team-a-dev") { t.Errorf("carol adopted by a caller who may not bind = %d %q", rec.Code, rec.Body.String()) } - if v := adopt(owner, desk("carol"), http.StatusOK); !staged(v, "desktop", "carol") || !strings.Contains(v.Warning, "desktops are not on there") { + if v := adopt(owner, desk("carol"), http.StatusOK); !staged(v, "desktop", "carol") || v.Warning != "" { t.Errorf("carol adopted = %+v", v) } if v := adopt(adminToken, class("cad"), http.StatusOK); !staged(v, "desktopclass", "cad") { diff --git a/internal/api/fakecluster_test.go b/internal/api/fakecluster_test.go index 0da958749..05fa60110 100644 --- a/internal/api/fakecluster_test.go +++ b/internal/api/fakecluster_test.go @@ -532,10 +532,11 @@ type planeDraft struct { releaseStaged, releaseResidue []string - declared map[model.ObjectRef]string // what DeclaredFiles answers - kinds []schema.GroupKind // what DeclaredKinds answers, each unplaced - placed []changeset.DeclaredKind // and these, where they say - staged bool // a call staged something: Get shows a draft + declared map[model.ObjectRef]string // what DeclaredFiles answers + desktopsOff []string // namespaces DesktopsOn reads off + kinds []schema.GroupKind // what DeclaredKinds answers, each unplaced + placed []changeset.DeclaredKind // and these, where they say + staged bool // a call staged something: Get shows a draft } var stagedView = model.DraftView{Base: "main", Count: 1} @@ -752,6 +753,11 @@ func (d *planeDraft) PublishNamespaceNeeds(project.ProjectInfo, project.ProjectI func (d *planeDraft) DesktopsNeeds(project.ProjectInfo, project.ProjectInfo, string) (bool, []changeset.Access, error) { return false, nil, nil } + +// DesktopsOn reads desktops on wherever desktopsOff does not name. +func (d *planeDraft) DesktopsOn(_ project.ProjectInfo, ns string) (bool, error) { + return !slices.Contains(d.desktopsOff, ns), nil +} func (d *planeDraft) ReleaseNeeds(project.ProjectInfo, project.ProjectInfo) ([]changeset.Access, []string, error) { return nil, d.releaseResidue, nil } @@ -762,10 +768,10 @@ func (d *planeDraft) DisableDRSNeeds(project.ProjectInfo) ([]changeset.Access, e return nil, nil } -// ResyncNeeds is the VM's create carrying its object, as the coordinator +// ResyncNeeds is the object's create carrying itself, as the coordinator // states what Argo applying it does. -func (d *planeDraft) ResyncNeeds(_ project.ProjectInfo, ns, name string) ([]changeset.Access, error) { - return []changeset.Access{{Verb: "create", Group: model.KindVM.Group, Resource: model.KindVM.Plural, Namespace: ns, Name: name, Object: "{}"}}, nil +func (d *planeDraft) ResyncNeeds(_ project.ProjectInfo, k model.Kind, ns, name string) ([]changeset.Access, error) { + return []changeset.Access{{Verb: "create", Group: k.Group, Resource: k.Plural, Namespace: ns, Name: name, Object: "{}"}}, nil } func (d *planeDraft) Discard(auth.Identity, project.ProjectInfo) error { diff --git a/internal/api/gates_test.go b/internal/api/gates_test.go index 788aaddbf..b84e09ebb 100644 --- a/internal/api/gates_test.go +++ b/internal/api/gates_test.go @@ -157,8 +157,8 @@ func (d *gatedDraft) AdoptObjects(_ auth.Identity, _ project.ProjectInfo, _ stri } // Resync asks the server, as the coordinator does, its ResyncNeeds. -func (d *gatedDraft) Resync(_ context.Context, id auth.Identity, proj project.ProjectInfo, ns, name string) (model.ResyncResult, error) { - need, _ := d.ResyncNeeds(proj, ns, name) +func (d *gatedDraft) Resync(_ context.Context, id auth.Identity, proj project.ProjectInfo, k model.Kind, ns, name string) (model.ResyncResult, error) { + need, _ := d.ResyncNeeds(proj, k, ns, name) if err := d.authz.Authorize(id, need); err != nil { return model.ResyncResult{}, err } diff --git a/internal/api/handlers_capabilities.go b/internal/api/handlers_capabilities.go index 2e92e5ff9..3f6fd3b7d 100644 --- a/internal/api/handlers_capabilities.go +++ b/internal/api/handlers_capabilities.go @@ -243,10 +243,13 @@ func (s *Server) namespaceCaps(ctx context.Context, sc scope, ns string) model.N fields = append(fields, objectFields(&out.NetworkPolicy, model.KindNetpol, ns, un)...) fields = append(fields, objectFields(&out.EgressFirewall, model.KindEgressFW, ns, un)...) // A tenant repo declares the desktop kinds only once Argo CD applies them - // as the project's own account: until then what the caller could author - // is weighed apart, and only said. + // as the project's own account, and only where desktops are on: until + // then what the caller could author is weighed apart, and only said. rule := s.tenantKindRule() + off, offKnown := s.desktopsOff(ns, un) + var listsGrants bool var held [2]model.ObjectCaps + var undeclarable [2]bool for i, d := range []struct { dst *model.ObjectCaps kind model.Kind @@ -255,15 +258,23 @@ func (s *Server) namespaceCaps(ctx context.Context, sc scope, ns string) model.N continue } dst := d.dst - if !rule.Declarable(d.kind.Group, d.kind.Kind) { + undeclarable[i] = !rule.Declarable(d.kind.Group, d.kind.Kind) + if undeclarable[i] || off { dst = &held[i] } fields = append(fields, manifestFields(dst, d.kind, ns)...) } + if off && offKnown { + fields = append(fields, capField{&listsGrants, kindAction(verbList, model.KindRB, ns)}) + } s.fill(ctx, sc.id, sc.cluster, fields) - for _, h := range held { - out.DesktopsHeld = out.DesktopsHeld || h.Create || h.Update + var could bool + for i, h := range held { + authors := h.Create || h.Update + could = could || authors + out.DesktopsHeld = out.DesktopsHeld || undeclarable[i] && authors } + out.DesktopsOff = off && offKnown && (could || listsGrants) out.RepoRead = s.readsRepo(ctx, sc, ns) == nil out.Project.RepoRead = s.readsRepo(ctx, sc, "") == nil out.Project.TemplateEdit, _ = s.projectAuthor(ctx, sc.id, sc.cluster, sc.proj.Namespaces) @@ -275,6 +286,18 @@ func (s *Server) namespaceCaps(ctx context.Context, sc scope, ns string) model.N return out } +// desktopsOff reports whether desktops are not on in ns, as the gate reads +// it. known is false where the platform repo could not say: that offers no +// pool or desktop, and says nothing. Nothing is weighed without a platform +// repo, nor where the cluster serves neither kind. +func (s *Server) desktopsOff(ns string, un map[model.Kind]bool) (off, known bool) { + if s.cfg.PlatformRepo == "" || un[model.KindVdiPool] && un[model.KindVdiInstance] { + return false, true + } + on, err := s.draft.DesktopsOn(s.platformProject(), ns) + return !on, err == nil +} + // desktopsCaps answers the desktops route over each namespace of project full // as handleDesktopsOn weighs it: DeskuBe served, the whole project in view or // any namespace claimable, and the gate's accesses allowed. DesktopsOn is diff --git a/internal/api/handlers_desktops.go b/internal/api/handlers_desktops.go index 5de1fb291..8beeb83b4 100644 --- a/internal/api/handlers_desktops.go +++ b/internal/api/handlers_desktops.go @@ -1,10 +1,14 @@ package api import ( + "cmp" "context" "encoding/json" "fmt" + "maps" "net/http" + "slices" + "strings" "k8s.io/apimachinery/pkg/runtime/schema" @@ -96,12 +100,55 @@ type desktopsGit struct { drift func(kind, namespace, name string) (argo.Drift, bool) file func(kind, namespace, name string) string authors bool + // inGit is each pool and desktop made one by one the caller's repos + // declare where readable lists its kind, and the cluster does not run, + // by its file. + inGit map[model.ObjectRef]string } func (s *Server) desktopsGitFor(ctx context.Context, id auth.Identity, c *cluster.Client, projects []project.ProjectInfo, readable map[desktops.Kind]bool) desktopsGit { authors := readable[desktops.Kind{Resource: desktops.GVRClass.Resource}] && s.cfg.PlatformRepo != "" && s.capable(ctx, id, c, kindAction(verbCreate, model.KindVdiClass, "")) - return desktopsGit{drift: s.driftFor, file: s.declaredIn(projects, authors), authors: authors} + declared := s.declaredDesktops(projects, readable) + inGit := map[model.ObjectRef]string{} + for _, ref := range s.desktops.NotRunning(slices.Collect(maps.Keys(declared))) { + inGit[ref] = declared[ref] + } + return desktopsGit{drift: s.driftFor, file: s.declaredIn(projects, authors), authors: authors, inGit: inGit} +} + +// declaredResource is the resource of each kind a project's repo declares +// of DeskuBe's. +var declaredResource = map[string]string{ + model.KindVdiPool.Kind: desktops.GVRPool.Resource, + model.KindVdiInstance.Kind: desktops.GVRInstance.Resource, +} + +// declaredDesktops is each pool and desktop made one by one that projects' +// repos declare in their own namespaces, where readable lists its kind, by +// its file: the git half the pull joins to what runs. +func (s *Server) declaredDesktops(projects []project.ProjectInfo, readable map[desktops.Kind]bool) map[model.ObjectRef]string { + lists := func(ns string) bool { + return readable[desktops.Kind{Namespace: ns, Resource: desktops.GVRPool.Resource}] || + readable[desktops.Kind{Namespace: ns, Resource: desktops.GVRInstance.Resource}] + } + out := map[model.ObjectRef]string{} + for _, p := range projects { + if p.Repo == "" || p.Error != "" || !slices.ContainsFunc(p.Namespaces, lists) { + continue + } + files, err := s.reader.DeclaredFiles(p) + if err != nil { + continue + } + for ref, file := range files { + resource, ok := declaredResource[ref.Kind] + if ok && slices.Contains(p.Namespaces, ref.Namespace) && readable[desktops.Kind{Namespace: ref.Namespace, Resource: resource}] { + out[ref] = file + } + } + } + return out } // classErrorForReaders stands in for a class's apply error to a reader who @@ -109,7 +156,9 @@ func (s *Server) desktopsGitFor(ctx context.Context, id auth.Identity, c *cluste const classErrorForReaders = "the platform could not apply this class" // declare sets each class's, pool's and desktop made one by one's file and -// drift in out. A pooled desktop gets neither: no repo declares it. +// drift in out, and lists each pool and desktop git declares that does not +// run, once out is synced. A pooled desktop gets neither: no repo declares +// it. func (g desktopsGit) declare(out *model.Desktops) { for i := range out.Classes { c := &out.Classes[i] @@ -138,6 +187,19 @@ func (g desktopsGit) declare(out *model.Desktops) { d.Sync, d.Health, d.SyncError = dr.Sync, dr.Health, dr.Message } } + if !out.Synced { + return + } + for ref, file := range g.inGit { + row := model.DesktopInGit{Resource: declaredResource[ref.Kind], Namespace: ref.Namespace, Name: ref.Name, SourceFile: file} + if d, ok := g.drift(ref.Kind, ref.Namespace, ref.Name); ok { + row.Sync, row.Health, row.SyncError, row.SyncStalled = d.Sync, d.Health, d.Message, d.Stalled + } + out.InGit = append(out.InGit, row) + } + slices.SortFunc(out.InGit, func(a, b model.DesktopInGit) int { + return cmp.Or(strings.Compare(a.Namespace, b.Namespace), strings.Compare(a.Resource, b.Resource), strings.Compare(a.Name, b.Name)) + }) } // notRunning refuses a create form's class, pool or desktop of gvr when one diff --git a/internal/api/handlers_draft.go b/internal/api/handlers_draft.go index 9e3de90bb..277a2370f 100644 --- a/internal/api/handlers_draft.go +++ b/internal/api/handlers_draft.go @@ -186,7 +186,7 @@ func (s *Server) handleDrift(w http.ResponseWriter, r *http.Request) { } result, err := s.reader.VMDrift(sc.proj, ns, name) if err == nil && s.drift != nil { - need, nerr := s.draft.ResyncNeeds(sc.proj, ns, name) + need, nerr := s.draft.ResyncNeeds(sc.proj, model.KindVM, ns, name) result.CanResync = s.needsAllowed(r.Context(), sc.id, sc.cluster, need, nerr) } respond(w, result, err) @@ -220,49 +220,9 @@ func (s *Server) handleAdoptNamespace(w http.ResponseWriter, r *http.Request) { return } result, err := s.draft.AdoptObjects(sc.id, sc.proj, ns, objs) - if err == nil { - result.Warning = changeset.JoinWarning(result.Warning, s.desktopsWarning(r.Context(), sc, ns, result)) - } respond(w, withUnreadable(result, ns, unreadable, denied), err) } -// desktopsWarning is what v staging desktop pools or desktops into ns says of -// desktops there, "" when it stages neither. Whether they are on is what -// Kubernetes shows the caller, as the capabilities tell it: only to one who -// may list rolebindings in ns, the others reading the same words whatever git -// holds. -func (s *Server) desktopsWarning(ctx context.Context, sc scope, ns string, v model.DraftView) string { - var staged []string - for _, r := range []struct { - resource draft.Resource - noun string - }{{draft.ResourceDesktopPool, "desktop pools"}, {draft.ResourceDesktop, "desktops"}} { - if slices.ContainsFunc(v.Items, func(it model.DraftItem) bool { return it.Resource == string(r.resource) && it.Namespace == ns }) { - staged = append(staged, r.noun) - } - } - if len(staged) == 0 { - return "" - } - what := strings.Join(staged, " and ") - neutral := ns + ": " + what + " apply only where a platform admin has turned desktops on." - if !s.capable(ctx, sc.id, sc.cluster, kindAction(verbList, model.KindRB, ns)) { - return neutral - } - full, ok := s.projectByName(sc.proj.Name) - if s.cfg.PlatformRepo == "" || !ok { - return neutral - } - on, _, err := s.draft.DesktopsNeeds(s.platformProject(), full, ns) - switch { - case err != nil && !errors.Is(err, changeset.ErrDesktopsOn) && !errors.Is(err, changeset.ErrDesktopsUngranted): - return neutral - case !on: - return ns + ": desktops are not on there, so the project's account may not apply the " + what + " staged until a platform admin turns them on." - } - return "" -} - // captureAdoptable runs the caller-token capture for one namespace ("" = the // cluster scope, for the platform tier) and applies the shared refusals: no // ArgoCD picture yet, nothing readable, nothing left to adopt. ok=false means @@ -333,7 +293,7 @@ func (s *Server) handleResync(w http.ResponseWriter, r *http.Request) { if !ok { return } - result, err := s.draft.Resync(r.Context(), sc.id, sc.proj, ns, name) + result, err := s.draft.Resync(r.Context(), sc.id, sc.proj, model.KindVM, ns, name) s.recordTask("Resync", ns, name, sc.id.Username, err == nil) respond(w, result, s.withheld(r.Context(), sc, err)) } diff --git a/internal/api/handlers_objects.go b/internal/api/handlers_objects.go index 4e2d84773..11fd8942b 100644 --- a/internal/api/handlers_objects.go +++ b/internal/api/handlers_objects.go @@ -9,11 +9,11 @@ import ( "strings" "github.com/epheo/dotvirt/internal/auth" - "github.com/epheo/dotvirt/internal/changeset" "github.com/epheo/dotvirt/internal/cluster" "github.com/epheo/dotvirt/internal/draft" "github.com/epheo/dotvirt/internal/model" "github.com/epheo/dotvirt/internal/project" + "github.com/epheo/dotvirt/internal/tasks" ) // The object routes act on one git-declared object of the network family, or @@ -181,9 +181,6 @@ func (s *Server) handleObjectAdopt(w http.ResponseWriter, r *http.Request) { return } result, err := s.draft.AdoptObject(sc.id, sc.proj, picked[0]) - if err == nil && (desktop || draft.Resource(resource) == draft.ResourceDesktopPool) { - result.Warning = changeset.JoinWarning(result.Warning, s.desktopsWarning(r.Context(), sc, ns, result)) - } respond(w, withUnreadable(result, ns, unreadable, nil), err) } @@ -267,6 +264,30 @@ func (s *Server) handleObjectRunning(w http.ResponseWriter, r *http.Request) { respond(w, view, err) } +// handleObjectResync syncs a declared pool, or desktop made one by one, alone +// from git through the VMs' Resync: what applies it once Argo CD gave up on +// the revision declaring it. It opens on the right to change it; the +// coordinator weighs what the sync applies under the caller's token beside +// the escalation. +func (s *Server) handleObjectResync(w http.ResponseWriter, r *http.Request) { + kind := map[draft.Resource]model.Kind{draft.ResourceDesktopPool: model.KindVdiPool, draft.ResourceDesktop: model.KindVdiInstance} + k, ok := kind[draft.Resource(r.PathValue("resource"))] + if !ok { + fail(w, invalid(errors.New("only a pool or a desktop made one by one is synced here; a VM is synced from its own page"))) + return + } + sc, _, ns, name, ok := s.objectScope(w, r, verbUpdate) + if !ok { + return + } + result, err := s.draft.Resync(r.Context(), sc.id, sc.proj, k, ns, name) + // The feed names a desktop or a VM by its act; it has no word for a pool. + if k == model.KindVdiInstance { + s.recordOp(tasks.Op{Verb: "Resync", Namespace: ns, Name: name, Desktop: true, By: sc.id.Username, OK: err == nil}) + } + respond(w, result, s.withheld(r.Context(), sc, err)) +} + // handlePlatformAdopt stages every cluster-scoped object the platform repo does // not describe - the platform tier's counterpart of the namespace adoption - // of the objects the gate would let the caller bring under git. diff --git a/internal/api/routes.go b/internal/api/routes.go index d26954fc6..470b2f3b0 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -110,6 +110,8 @@ func (s *Server) routes(mux *http.ServeMux) { mux.HandleFunc("POST /api/objects/{resource}/{namespace}/{name}/restore", s.handleObjectRestore) // A desktop's power in git, staged as a VM's is. mux.HandleFunc("POST /api/objects/{resource}/{namespace}/{name}/running", s.handleObjectRunning) + // A pool's or a desktop's sync of git, alone, as a VM's is. + mux.HandleFunc("POST /api/objects/{resource}/{namespace}/{name}/resync", s.handleObjectResync) mux.HandleFunc("POST /api/platform/adopt", s.handlePlatformAdopt) mux.HandleFunc("POST /api/namespaces", s.handleCreateNamespace) mux.HandleFunc("POST /api/projects", s.handleCreateProject) diff --git a/internal/api/watermark.go b/internal/api/watermark.go index a3cee566f..4ed25c753 100644 --- a/internal/api/watermark.go +++ b/internal/api/watermark.go @@ -196,10 +196,11 @@ func (s *Server) routesWatermark(ctx context.Context, id auth.Identity, c *clust // desktopsWatermark covers what the caller's desktops pull reads, from its // own rights: each kind where it may list it, the kinds it may not list // beside those, whether the kinds it reads are synced or stale, the file -// declaring each object it shows a repo may declare, and their drift by -// namespace. A file is the pull's own answer, never a repo head: a merge -// moves it only where the pull shows what moved. 0 for a caller who may list -// none, as on a cluster without DeskuBe. +// declaring each object it shows a repo may declare, each pool and desktop +// git declares where it lists the kind and the cluster does not run, by its +// file, and their drift by namespace. A file is the pull's own answer, never +// a repo head: a merge moves it only where the pull shows what moved. 0 for +// a caller who may list none, as on a cluster without DeskuBe. func (s *Server) desktopsWatermark(v callerView, projects []project.ProjectInfo) uint64 { if s.desktops == nil { return 0 @@ -229,6 +230,9 @@ func (s *Server) desktopsWatermark(v callerView, projects []project.ProjectInfo) for _, o := range s.desktops.Declarable(readable) { sum += t.start("desktops-file").str(o.Kind, o.Namespace, o.Name, g.file(o.Kind, o.Namespace, o.Name)).sum() } + for o, file := range g.inGit { + sum += t.start("desktops-in-git").str(o.Kind, o.Namespace, o.Name, file).sum() + } if s.drift != nil { for scope := range scopes { sum += t.start("desktops-drift").str(scope).num(s.drift.ObjectDriftGen(scope)).sum() diff --git a/internal/argo/argo.go b/internal/argo/argo.go index 71dde98ad..2c2c07bf0 100644 --- a/internal/argo/argo.go +++ b/internal/argo/argo.go @@ -41,6 +41,10 @@ type Drift struct { // Message is the apply/sync error from the Application's last operation, when // this VM failed to sync (e.g. a KubeVirt webhook rejection). Empty when synced. Message string + // Stalled: not synced, and the Application's last sync failed on the + // revision it compares now. Automated sync never retries a revision whose + // sync failed: only a new commit, or a sync someone asks for, applies it. + Stalled bool } // Client reads Application status via the dynamic client - no heavy argo-cd @@ -118,6 +122,7 @@ func ClusterScope(group, kind string) string { return group + "/" + kind } func resourceDriftFromApps(objs []*unstructured.Unstructured) map[resKey]Drift { out := map[resKey]Drift{} for _, app := range objs { + stalled := gaveUp(app) for _, raw := range nestedSlice(app.Object, "status", "resources") { res, ok := raw.(map[string]any) if !ok { @@ -126,9 +131,11 @@ func resourceDriftFromApps(objs []*unstructured.Unstructured) map[resKey]Drift { if asString(res, "name") == "" { continue } + sync := syncStatus(asString(res, "status")) out[keyOf(res)] = Drift{ - Sync: syncStatus(asString(res, "status")), - Health: nestedString(res, "health", "status"), + Sync: sync, + Health: nestedString(res, "health", "status"), + Stalled: stalled && sync != model.SyncSynced, } } mergeSyncMessages(out, app.Object) @@ -136,6 +143,16 @@ func resourceDriftFromApps(objs []*unstructured.Unstructured) map[resKey]Drift { return out } +// gaveUp reports whether app's last sync ended Failed or Error on the +// revision it compares now, with no sync asked since: automated sync never +// tries that revision again by itself. +func gaveUp(app *unstructured.Unstructured) bool { + phase := nestedString(app.Object, "status", "operationState", "phase") + tried := nestedString(app.Object, "status", "operationState", "syncResult", "revision") + return (phase == "Failed" || phase == "Error") && tried != "" && + tried == nestedString(app.Object, "status", "sync", "revision") && !operating(app) +} + // vmView is the VM slice of the general drift map, re-keyed "namespace/name" - the // shape the inventory VM enrichment consumes. func vmView(all map[resKey]Drift) map[string]Drift { diff --git a/internal/argo/snapshot.go b/internal/argo/snapshot.go index 7bf530803..4aca9e2f8 100644 --- a/internal/argo/snapshot.go +++ b/internal/argo/snapshot.go @@ -586,23 +586,23 @@ type AppRef struct { const projectAppLabel = "dotvirt.io/project" // managingApp returns the dotvirt Application whose status.resources[] includes -// the VirtualMachine namespace/name, read from the in-memory store (no cluster -// call). ok=false if the snapshot hasn't synced or no such Application manages -// the VM - the caller (Resync) then falls back to a live lookup. -func (s *Snapshot) managingApp(namespace, name string) (AppRef, bool) { +// the object obj, read from the in-memory store (no cluster call). ok=false if +// the snapshot hasn't synced or no such Application manages it - the caller +// (Resync) then falls back to a live lookup. +func (s *Snapshot) managingApp(obj resKey) (AppRef, bool) { if !s.synced.Done() { return AppRef{}, false } - return pickManaging(reflect.List(s.apps), namespace, name, s.writable) + return pickManaging(reflect.List(s.apps), obj, s.writable) } -// pickManaging is the dotvirt Application among apps managing the VM -// namespace/name, one in a writable namespace first: a hand-labelled copy -// elsewhere must not make Resync refuse depending on list order. -func pickManaging(apps []*unstructured.Unstructured, namespace, name string, writable func(string) bool) (AppRef, bool) { +// pickManaging is the dotvirt Application among apps managing the object obj, +// one in a writable namespace first: a hand-labelled copy elsewhere must not +// make Resync refuse depending on list order. +func pickManaging(apps []*unstructured.Unstructured, obj resKey, writable func(string) bool) (AppRef, bool) { var other *unstructured.Unstructured for _, app := range apps { - if !resyncable(app, namespace, name) { + if !resyncable(app, obj) { continue } if writable(app.GetNamespace()) { @@ -618,21 +618,23 @@ func pickManaging(apps []*unstructured.Unstructured, namespace, name string, wri return appRefOf(other), true } -// Resync triggers an ArgoCD sync of the given VM alone, from the dotvirt -// Application managing it, so the VM is reconciled back to git. It finds the -// managing Application from the in-memory snapshot (falling back to a live LIST -// when the snapshot hasn't synced, so a resync right after startup doesn't -// spuriously 404), then requests a sync via the Application's operation field - -// the k8s API dotvirt already has, no separate Argo API token. (Distinct from -// RefreshForRepo: this is the user's explicit per-VM "sync now", which must work -// even when auto-sync is off.) The operation names the VM as its only resource: -// the caller's right covers that VM, never the rest of the Application. username -// is the caller, recorded as the operation's initiator so Argo's history names -// the person, not dotvirt's SA. -func (s *Snapshot) Resync(ctx context.Context, username, namespace, name string) (model.ResyncResult, error) { - ref, ok := s.managingApp(namespace, name) +// Resync triggers an ArgoCD sync of the given object alone - a VM, a pool or a +// desktop made one by one - from the dotvirt Application managing it, so it +// is reconciled back to git. It finds the managing Application from the +// in-memory snapshot (falling back to a live LIST when the snapshot hasn't +// synced, so a resync right after startup doesn't spuriously 404), then +// requests a sync via the Application's operation field - the k8s API dotvirt +// already has, no separate Argo API token. (Distinct from RefreshForRepo: this +// is the user's explicit per-object "sync now", which must work even when +// auto-sync is off, or has given up on a revision.) The operation names the +// object as its only resource: the caller's right covers that object, never +// the rest of the Application. username is the caller, recorded as the +// operation's initiator so Argo's history names the person, not dotvirt's SA. +func (s *Snapshot) Resync(ctx context.Context, username string, kind model.Kind, namespace, name string) (model.ResyncResult, error) { + obj := resKey{kind.Group, kind.Kind, namespace, name} + ref, ok := s.managingApp(obj) if !ok { - ref, ok = s.sa.findmanagingAppLive(ctx, namespace, name, s.writable) + ref, ok = s.sa.findmanagingAppLive(ctx, obj, s.writable) if !ok { return model.ResyncResult{}, fmt.Errorf("%w: no ArgoCD Application manages %s/%s", model.ErrNotFound, namespace, name) } @@ -644,7 +646,7 @@ func (s *Snapshot) Resync(ctx context.Context, username, namespace, name string) // Read from the snapshot, so an operation starting after it is not seen. // That window is accepted rather than closed with a resourceVersion // precondition: this patch's bytes stay exactly as installs know them, - // and any change to it is announced to them first. + // one shape per kind, and any change to them is announced to them first. if ref.Operating { return model.ResyncResult{}, fmt.Errorf("%w: a sync of %s is already requested or running; try again when it finishes", model.ErrConflict, ref.Name) @@ -653,7 +655,7 @@ func (s *Snapshot) Resync(ctx context.Context, username, namespace, name string) if revision == "" { revision = "HEAD" } - patch, err := resyncPatch(username, revision, namespace, name) + patch, err := resyncPatch(username, revision, obj) if err != nil { return model.ResyncResult{}, err } @@ -666,10 +668,10 @@ func (s *Snapshot) Resync(ctx context.Context, username, namespace, name string) return model.ResyncResult{Application: ref.Name, Revision: revision}, nil } -// resyncPatch is the Application operation requesting a sync of the VM -// namespace/name alone, to revision. It is marshalled, not formatted: username -// is caller-controlled text. -func resyncPatch(username, revision, namespace, name string) ([]byte, error) { +// resyncPatch is the Application operation requesting a sync of the object +// obj alone, to revision. It is marshalled, not formatted: username is +// caller-controlled text. +func resyncPatch(username, revision string, obj resKey) ([]byte, error) { type kv struct { Name string `json:"name"` Value string `json:"value"` @@ -694,7 +696,7 @@ func resyncPatch(username, revision, namespace, name string) ([]byte, error) { } op.Operation.InitiatedBy.Username = username op.Operation.Sync.Revision = revision - op.Operation.Sync.Resources = []resource{{Group: "kubevirt.io", Kind: "VirtualMachine", Namespace: namespace, Name: name}} + op.Operation.Sync.Resources = []resource{{Group: obj.group, Kind: obj.kind, Namespace: obj.namespace, Name: obj.name}} op.Operation.Info = []kv{{"reason", "dotvirt re-sync from git"}} return json.Marshal(op) } @@ -741,7 +743,7 @@ func (c *Client) patchApp(ctx context.Context, namespace, name string, patch []b // findmanagingAppLive is managingApp's cluster fallback: a one-shot LIST used only // when the snapshot hasn't synced yet, so an early resync still resolves its app. -func (c *Client) findmanagingAppLive(ctx context.Context, namespace, name string, writable func(string) bool) (AppRef, bool) { +func (c *Client) findmanagingAppLive(ctx context.Context, obj resKey, writable func(string) bool) (AppRef, bool) { apps, err := c.dyn.Resource(applicationsGVR).Namespace(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) if err != nil { return AppRef{}, false @@ -750,13 +752,12 @@ func (c *Client) findmanagingAppLive(ctx context.Context, namespace, name string for i := range apps.Items { items[i] = &apps.Items[i] } - return pickManaging(items, namespace, name, writable) + return pickManaging(items, obj, writable) } -// resyncable reports whether app is a dotvirt Application managing the VM -// namespace/name. -func resyncable(app *unstructured.Unstructured, namespace, name string) bool { - return app.GetLabels()[projectAppLabel] != "" && appManagesVM(app.Object, namespace, name) +// resyncable reports whether app is a dotvirt Application managing obj. +func resyncable(app *unstructured.Unstructured, obj resKey) bool { + return app.GetLabels()[projectAppLabel] != "" && appManages(app.Object, obj) } // appRefOf reads the AppRef (name/namespace/sync revision/operation in flight) from an Application. @@ -775,17 +776,11 @@ func operating(app *unstructured.Unstructured) bool { return phase == "Running" || phase == "Terminating" } -// appManagesVM reports whether app's status.resources[] includes the VirtualMachine -// namespace/name. -func appManagesVM(app map[string]any, namespace, name string) bool { +// appManages reports whether app's status.resources[] includes obj: Argo +// lists there what git declares, applied or not. +func appManages(app map[string]any, obj resKey) bool { for _, raw := range nestedSlice(app, "status", "resources") { - res, ok := raw.(map[string]any) - if !ok { - continue - } - if asString(res, "kind") == "VirtualMachine" && - asString(res, "namespace") == namespace && - asString(res, "name") == name { + if res, ok := raw.(map[string]any); ok && keyOf(res) == obj { return true } } diff --git a/internal/argo/snapshot_test.go b/internal/argo/snapshot_test.go index 3c280862e..8ef27ff65 100644 --- a/internal/argo/snapshot_test.go +++ b/internal/argo/snapshot_test.go @@ -57,11 +57,11 @@ func TestSnapshotmanagingApp(t *testing.T) { []any{vmResource("prod", "vm-a", "Synced", "Healthy")})) s.synced.Mark() - ref, ok := s.managingApp("prod", "vm-a") + ref, ok := s.managingApp(vmKey("prod", "vm-a")) if !ok || ref.Name != "team-a" || ref.Namespace != "argocd" || ref.TargetRevision != "main" { t.Fatalf("managingApp wrong: %+v ok=%v", ref, ok) } - if _, ok := s.managingApp("prod", "ghost"); ok { + if _, ok := s.managingApp(vmKey("prod", "ghost")); ok { t.Error("managingApp should miss an unmanaged VM") } } @@ -393,6 +393,81 @@ func dotvirtApp(ns, name, repoURL string, resources []any) *unstructured.Unstruc return a } +func vmKey(ns, name string) resKey { return resKey{"kubevirt.io", "VirtualMachine", ns, name} } + +// desktopResource is a desktop of DeskuBe's as status.resources[] lists it. +func desktopResource(ns, name, status, health string) map[string]any { + return map[string]any{"group": "vdi.desku.be", "kind": "VdiInstance", "namespace": ns, "name": name, + "status": status, "health": map[string]any{"status": health}} +} + +// A desktop git declares and Argo could not create is synced alone by kind: +// a VM under its name is not it, and the operation names the desktop. +func TestResyncSyncsADesktopAlone(t *testing.T) { + a := dotvirtApp("argocd", "team-a", "https://forge/team-a.git", + []any{vmResource("prod", "twin", "Synced", "Healthy"), desktopResource("prod", "de", "OutOfSync", "Missing")}) + dyn := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme(), a) + var sent []byte + dyn.PrependReactor("patch", "applications", func(act k8stesting.Action) (bool, runtime.Object, error) { + sent = act.(k8stesting.PatchAction).GetPatch() + return false, nil, nil + }) + s := NewSnapshot(&Client{dyn: dyn}, nil) + _ = s.apps.Add(a) + s.synced.Mark() + if _, err := s.Resync(context.Background(), "alice", model.KindVdiInstance, "prod", "twin"); !errors.Is(err, model.ErrNotFound) { + t.Errorf("a VM asked as a desktop: %v, want ErrNotFound", err) + } + res, err := s.Resync(context.Background(), "alice", model.KindVdiInstance, "prod", "de") + if err != nil { + t.Fatal(err) + } + want, _ := resyncPatch("alice", "main", resKey{"vdi.desku.be", "VdiInstance", "prod", "de"}) + if res.Application != "team-a" || string(sent) != string(want) { + t.Errorf("result %+v, patch %s; want team-a and %s", res, sent, want) + } +} + +// An object is stalled while the last sync failed on the revision the +// Application compares: automated sync never tries that revision again. A +// failure on an older revision, a sync asked since, or the object synced +// is not. +func TestDriftTellsASyncArgoGaveUpOn(t *testing.T) { + failed := func(tried, compared string, edit func(map[string]any)) *unstructured.Unstructured { + a := appWithSource("argocd", "team-a", "https://forge/team-a.git", + []any{desktopResource("prod", "de", "OutOfSync", "Missing"), desktopResource("prod", "ok", "Synced", "Healthy")}) + _ = unstructured.SetNestedField(a.Object, compared, "status", "sync", "revision") + _ = unstructured.SetNestedMap(a.Object, map[string]any{"phase": "Failed", "syncResult": map[string]any{"revision": tried}}, "status", "operationState") + if edit != nil { + edit(a.Object) + } + return a + } + for _, c := range []struct { + name string + app *unstructured.Unstructured + stall bool + }{ + {"failed on the revision compared", failed("c1", "c1", nil), true}, + {"failed on an older revision", failed("c0", "c1", nil), false}, + {"a sync asked since", failed("c1", "c1", func(o map[string]any) { o["operation"] = map[string]any{"sync": map[string]any{}} }), false}, + {"errored on the revision compared", failed("c1", "c1", func(o map[string]any) { + _ = unstructured.SetNestedField(o, "Error", "status", "operationState", "phase") + }), true}, + {"succeeded", failed("c1", "c1", func(o map[string]any) { + _ = unstructured.SetNestedField(o, "Succeeded", "status", "operationState", "phase") + }), false}, + } { + d := resourceDriftFromApps([]*unstructured.Unstructured{c.app}) + if got := d[resKey{"vdi.desku.be", "VdiInstance", "prod", "de"}].Stalled; got != c.stall { + t.Errorf("%s: stalled = %v, want %v", c.name, got, c.stall) + } + if d[resKey{"vdi.desku.be", "VdiInstance", "prod", "ok"}].Stalled { + t.Errorf("%s: a synced object reads stalled", c.name) + } + } +} + func TestResyncRecordsCallerAndMissesAsNotFound(t *testing.T) { a := dotvirtApp("argocd", "team-a", "https://forge/team-a.git", []any{vmResource("prod", "vm-a", "Synced", "Healthy")}) @@ -401,11 +476,11 @@ func TestResyncRecordsCallerAndMissesAsNotFound(t *testing.T) { _ = s.apps.Add(a) s.synced.Mark() - if _, err := s.Resync(context.Background(), "alice", "prod", "ghost"); !errors.Is(err, model.ErrNotFound) { + if _, err := s.Resync(context.Background(), "alice", model.KindVM, "prod", "ghost"); !errors.Is(err, model.ErrNotFound) { t.Errorf("unmanaged VM: err = %v, want ErrNotFound", err) } - res, err := s.Resync(context.Background(), `al"ice`, "prod", "vm-a") + res, err := s.Resync(context.Background(), `al"ice`, model.KindVM, "prod", "vm-a") if err != nil { t.Fatal(err) } @@ -441,7 +516,7 @@ func TestResyncSkipsForeignApplications(t *testing.T) { _ = s.apps.Add(foreign) s.synced.Mark() } - if _, err := s.Resync(context.Background(), "alice", "prod", "vm-a"); !errors.Is(err, model.ErrNotFound) { + if _, err := s.Resync(context.Background(), "alice", model.KindVM, "prod", "vm-a"); !errors.Is(err, model.ErrNotFound) { t.Errorf("synced=%v: err = %v, want ErrNotFound", synced, err) } got, err := dyn.Resource(applicationsGVR).Namespace("argocd").Get(context.Background(), "cluster-config", metav1.GetOptions{}) @@ -468,7 +543,7 @@ func TestResyncHidesTheSAStatus(t *testing.T) { _ = s.apps.Add(a) s.synced.Mark() - _, err := s.Resync(context.Background(), "alice", "prod", "vm-a") + _, err := s.Resync(context.Background(), "alice", model.KindVM, "prod", "vm-a") if apierrors.IsUnauthorized(err) || !errors.Is(err, model.ErrUnavailable) { t.Fatalf("err = %v; want ErrUnavailable with the SA status dropped", err) } @@ -492,11 +567,11 @@ func TestApplicationWritesStayInTheArgoNamespace(t *testing.T) { _ = s.apps.Add(out) s.synced.Mark() - _, err := s.Resync(context.Background(), "alice", "dev", "vm-b") + _, err := s.Resync(context.Background(), "alice", model.KindVM, "dev", "vm-b") if !errors.Is(err, model.ErrUnavailable) || !strings.Contains(err.Error(), "only in the ArgoCD namespace argocd") { t.Errorf("Resync outside the ArgoCD namespace: err = %v, want ErrUnavailable naming it", err) } - if _, err := s.Resync(context.Background(), "alice", "prod", "vm-a"); err != nil { + if _, err := s.Resync(context.Background(), "alice", model.KindVM, "prod", "vm-a"); err != nil { t.Errorf("Resync in the ArgoCD namespace: %v", err) } s.RefreshForRepo(context.Background(), "https://forge/team-a") @@ -515,11 +590,11 @@ func TestResyncPrefersTheArgoNamespace(t *testing.T) { out := dotvirtApp("apps", "team-a-copy", "https://forge/team-a.git", vm) s := NewSnapshot(&Client{}, nil).WithWriteNamespace("argocd") for _, apps := range [][]*unstructured.Unstructured{{in, out}, {out, in}} { - if ref, ok := pickManaging(apps, "prod", "vm-a", s.writable); !ok || ref.Namespace != "argocd" { + if ref, ok := pickManaging(apps, vmKey("prod", "vm-a"), s.writable); !ok || ref.Namespace != "argocd" { t.Errorf("order %s first: picked %+v, want the ArgoCD namespace's", apps[0].GetNamespace(), ref) } } - if ref, ok := pickManaging([]*unstructured.Unstructured{out}, "prod", "vm-a", s.writable); !ok || ref.Namespace != "apps" { + if ref, ok := pickManaging([]*unstructured.Unstructured{out}, vmKey("prod", "vm-a"), s.writable); !ok || ref.Namespace != "apps" { t.Errorf("only a copy elsewhere: picked %+v ok=%v, want it, for Resync to refuse with a reason", ref, ok) } for _, synced := range []bool{true, false} { @@ -531,23 +606,33 @@ func TestResyncPrefersTheArgoNamespace(t *testing.T) { _ = s.apps.Add(in) s.synced.Mark() } - res, err := s.Resync(context.Background(), "alice", "prod", "vm-a") + res, err := s.Resync(context.Background(), "alice", model.KindVM, "prod", "vm-a") if err != nil || res.Application != "team-a" { t.Errorf("synced=%v: Resync = %+v, %v; want team-a in the ArgoCD namespace", synced, res, err) } } } -// installs pin the resync operation's exact shape in admission; any change to -// it must be deliberate. +// installs pin the resync operation's exact shape in admission, one per kind +// it syncs; any change to it must be deliberate. func TestResyncPatchShapeIsPinned(t *testing.T) { - got, err := resyncPatch(`al"ice`, "main", "prod", "vm-a") - if err != nil { - t.Fatal(err) - } - want := `{"operation":{"initiatedBy":{"username":"al\"ice"},"sync":{"revision":"main","resources":[{"group":"kubevirt.io","kind":"VirtualMachine","namespace":"prod","name":"vm-a"}]},"info":[{"name":"reason","value":"dotvirt re-sync from git"}]}}` - if string(got) != want { - t.Errorf("resync patch =\n%s\nwant\n%s", got, want) + for _, c := range []struct { + obj resKey + group, kind string + }{ + {vmKey("prod", "vm-a"), "kubevirt.io", "VirtualMachine"}, + {resKey{"vdi.desku.be", "VdiInstance", "prod", "vm-a"}, "vdi.desku.be", "VdiInstance"}, + {resKey{"vdi.desku.be", "VdiPool", "prod", "vm-a"}, "vdi.desku.be", "VdiPool"}, + } { + got, err := resyncPatch(`al"ice`, "main", c.obj) + if err != nil { + t.Fatal(err) + } + want := `{"operation":{"initiatedBy":{"username":"al\"ice"},"sync":{"revision":"main","resources":[{"group":"` + c.group + `","kind":"` + c.kind + + `","namespace":"prod","name":"vm-a"}]},"info":[{"name":"reason","value":"dotvirt re-sync from git"}]}}` + if string(got) != want { + t.Errorf("resync patch =\n%s\nwant\n%s", got, want) + } } } @@ -592,7 +677,7 @@ func TestResyncWaitsForTheRunningOperation(t *testing.T) { _ = s.apps.Add(a) s.synced.Mark() } - _, err := s.Resync(context.Background(), "alice", "prod", "vm-a") + _, err := s.Resync(context.Background(), "alice", model.KindVM, "prod", "vm-a") if tc.busy { if !errors.Is(err, model.ErrConflict) || !strings.Contains(err.Error(), "already requested or running") { t.Errorf("%s, synced=%v: err = %v, want a conflict saying a sync is already running", tc.name, synced, err) @@ -631,7 +716,7 @@ func TestResyncReadsInFlightFromTheSnapshot(t *testing.T) { s := NewSnapshot(&Client{dyn: dyn}, nil) _ = s.apps.Add(seen) s.synced.Mark() - if _, err := s.Resync(context.Background(), "alice", "prod", "vm-a"); err != nil { + if _, err := s.Resync(context.Background(), "alice", model.KindVM, "prod", "vm-a"); err != nil { t.Errorf("snapshot shows no operation: err = %v, want the resync to proceed", err) } if gets != 0 { @@ -654,11 +739,11 @@ func TestResyncWithoutTargetRevisionSyncsHEAD(t *testing.T) { s := NewSnapshot(&Client{dyn: dyn}, nil) _ = s.apps.Add(a) s.synced.Mark() - res, err := s.Resync(context.Background(), "alice", "prod", "vm-a") + res, err := s.Resync(context.Background(), "alice", model.KindVM, "prod", "vm-a") if err != nil { t.Fatal(err) } - want, _ := resyncPatch("alice", "HEAD", "prod", "vm-a") + want, _ := resyncPatch("alice", "HEAD", vmKey("prod", "vm-a")) if res.Revision != "HEAD" || string(sent) != string(want) { t.Errorf("revision = %q, patch = %s; want HEAD and %s", res.Revision, sent, want) } diff --git a/internal/changeset/changeset.go b/internal/changeset/changeset.go index c67137bfd..1006610f6 100644 --- a/internal/changeset/changeset.go +++ b/internal/changeset/changeset.go @@ -29,10 +29,11 @@ import ( "github.com/epheo/dotvirt/pkg/tenancy" ) -// Resyncer triggers an ArgoCD sync of the Application managing a VM, for the -// main->running drift reconcile. Implemented by the argo client. May be nil. +// Resyncer triggers an ArgoCD sync of one object of kind from the Application +// managing it, for the main->running drift reconcile. Implemented by the argo +// client. May be nil. type Resyncer interface { - Resync(ctx context.Context, username, namespace, name string) (model.ResyncResult, error) + Resync(ctx context.Context, username string, kind model.Kind, namespace, name string) (model.ResyncResult, error) } // LiveSource supplies the cluster's current VM manifests, serialized exactly as git @@ -129,6 +130,9 @@ type Coordinator struct { // desktops is DeskuBe's pools and desktops as they run (WithDesktops); // nil reads every one as unknown. desktops DesktopsLive + // platformRepo holds each namespace's desktop grant (WithPlatformRepo); + // "" weighs none. + platformRepo string // seeds is what this process knows of each repo's starter-library offer // (seed.go), keyed by normalized repo URL; seedQueue feeds its one @@ -159,6 +163,14 @@ func (c *Coordinator) WithDesktops(live DesktopsLive) *Coordinator { return c } +// WithPlatformRepo names the platform repo, whose desktop grants say where +// desktops are on: the gate refuses a pool or a desktop anywhere else. Set +// once, before serving. +func (c *Coordinator) WithPlatformRepo(repo string) *Coordinator { + c.platformRepo = repo + return c +} + // WithPublishing sets the platform's publishing settings; the zero value // leaves publishing off. Set once, before serving. func (c *Coordinator) WithPublishing(s publish.Settings) *Coordinator { diff --git a/internal/changeset/desktops.go b/internal/changeset/desktops.go index 47742f8ae..fd2276461 100644 --- a/internal/changeset/desktops.go +++ b/internal/changeset/desktops.go @@ -25,6 +25,52 @@ var ErrDesktopsOn = fmt.Errorf("%w: desktops are already on", model.ErrInvalid) // as egress writes do. Granting the project's sync access stages one. var ErrDesktopsUngranted = fmt.Errorf("%w: desktops follow the namespace's admin grant, which the platform repo does not hold", model.ErrInvalid) +// ErrDesktopsOff refuses a pool, or a desktop made one by one, staged where +// desktops are not on: Argo CD applies it as the project's sync account, +// which may write them only where the platform repo grants it. +var ErrDesktopsOff = fmt.Errorf("%w: desktops are not on", model.ErrInvalid) + +// DesktopsOn reports whether desktops are on in ns: commitProj, the platform +// repo, holds ns's desktop grant. The project's Configure tab, the +// capabilities and the gate all read this one answer. +func (c *Coordinator) DesktopsOn(commitProj project.ProjectInfo, ns string) (bool, error) { + grants, err := c.grantSource(commitProj) + if err != nil { + return false, err + } + return grants.desktopsOn(ns) +} + +func (g grantSource) desktopsOn(ns string) (bool, error) { + path, _, err := g.declared(model.ObjectRef{Kind: model.KindRB.Kind, Namespace: ns, Name: tenancy.DesktopsBinding(ns)}, false) + return path != "", err +} + +// desktopsAreOn refuses a write to proj of a pool or a desktop in one of +// namespaces where desktops are not on. It weighs none in the platform repo, +// or without one. The gate asks it past the caller's rights, so whether +// desktops are on goes only to whoever may write one there, as the Configure +// tab tells it only to who may list rolebindings. +func (c *Coordinator) desktopsAreOn(proj project.ProjectInfo, namespaces []string) error { + if len(namespaces) == 0 || c.platformRepo == "" || proj.Name == project.PlatformName { + return nil + } + grants, err := c.grantSource(project.ProjectInfo{Name: project.PlatformName, Repo: c.platformRepo}) + if err != nil { + return fmt.Errorf("whether desktops are on is read from the platform repo: %w", err) + } + for _, ns := range namespaces { + on, err := grants.desktopsOn(ns) + switch { + case err != nil: + return err + case !on: + return fmt.Errorf("%w for %s: a platform admin turns them on from the project's Configure tab", ErrDesktopsOff, ns) + } + } + return nil +} + // StageDesktops stages, into the platform draft, what turning desktops on in // target's namespace ns lacks: the grant of DeskuBe's pool and desktop writes // (tenancy.TenantDesktopsRole) to the subjects of ns's admin grant and the @@ -61,11 +107,9 @@ func (c *Coordinator) desktopsPlan(commitProj, target project.ProjectInfo, ns st if err != nil { return false, nil, err } - path, _, err := grants.declared(model.ObjectRef{Kind: model.KindRB.Kind, Namespace: ns, Name: tenancy.DesktopsBinding(ns)}, false) - if err != nil { + if on, err = grants.desktopsOn(ns); err != nil { return false, nil, err } - on = path != "" spec, ok, err := grants.adminGrant(ns, target.Name) switch { case err != nil: diff --git a/internal/changeset/desktops_test.go b/internal/changeset/desktops_test.go index 65ac6916a..ae7a17fb7 100644 --- a/internal/changeset/desktops_test.go +++ b/internal/changeset/desktops_test.go @@ -1,6 +1,7 @@ package changeset import ( + "encoding/json" "errors" "maps" "slices" @@ -179,3 +180,135 @@ func TestDesktopsWaitOnImpersonation(t *testing.T) { } } } + +// desktopsOnRig is team-a's repo, declaring pool lab and alice's desktop +// solo, each changed once since first, by last; the platform repo holds +// team-a's admin grant and, when on, its desktop grant. rights is the +// caller's RBAC. +func desktopsOnRig(t *testing.T, on bool, rights Authorizer) (c *Coordinator, proj project.ProjectInfo, first, last string) { + t.Helper() + bare, work := seedWork(t, map[string][]byte{ + "team-a/desktops/solo.yaml": []byte(soloManifest("", soloSpec)), + "team-a/desktop-pools/lab.yaml": []byte(labManifest("", " className: workstation\n seats: 2\n")), + }) + first = head(t, work) + writeWorkFile(t, work, "team-a/desktops/solo.yaml", []byte(soloManifest("", soloSpec+" idleTimeout: 1h\n"))) + writeWorkFile(t, work, "team-a/desktop-pools/lab.yaml", []byte(labManifest("", labSpec))) + gitRun(t, work, "commit", "-qam", "solo idles out, lab grows") + last = head(t, work) + gitRun(t, work, "push", "-q", "origin", "main") + + platform := map[string][]byte{"rbac/team-a.yaml": grantYAML("team-a", "admin", user("alice"))} + if on { + path, grant, err := netgen.DesktopsManifest(netgen.RoleBindingSpec{Namespace: "team-a", Project: "team-a", Kept: []netgen.Subject{user("alice")}}) + if err != nil { + t.Fatal(err) + } + platform[path] = grant + } + c = newTestCoordinator(t, true).WithPlatformRepo(seedBareFiles(t, platform)).WithTenantKinds(tenancy.Policy{Allowed: []tenancy.GroupKind{ + {Group: "vdi.desku.be", Kind: "VdiPool"}, {Group: "vdi.desku.be", Kind: "VdiInstance"}, + }}) + c.UseAuthorizer(rights) + return c, project.ProjectInfo{Name: "team-a", Repo: bare}, first, last +} + +// A pool, or a desktop made one by one, goes into git only where desktops +// are on, through every path that writes one: made, adopted alone or with +// its namespace, edited, restored, turned on or off in git, and reverted. +// The refusal names the namespace, the fix and who makes it; once desktops +// are on, each passes. +func TestDesktopsAreStagedOnlyWhereTheyAreOn(t *testing.T) { + adoptable := func(kind model.Kind, name, yaml string) model.Adoptable { + return model.Adoptable{Namespace: "team-a", Name: name, Kind: kind.Kind, Path: kind.RepoPath("team-a", name), Manifest: []byte(yaml)} + } + carol := adoptable(model.KindVdiInstance, "carol", strings.ReplaceAll(soloManifest("", " className: workstation\n owner: carol\n"), "name: solo", "name: carol")) + web := adoptable(model.KindVM, "web", "apiVersion: kubevirt.io/v1\nkind: VirtualMachine\nmetadata:\n name: web\n namespace: team-a\nspec:\n runStrategy: Always\n") + paths := func(c *Coordinator, proj project.ProjectInfo, first, last string) map[string]func() error { + id := auth.Identity{Username: "alice"} + staged := func(_ model.DraftView, err error) error { return err } + return map[string]func() error{ + "a new pool": func() error { + return staged(c.StageCreate(id, proj, draft.ResourceDesktopPool, json.RawMessage(`{"namespace":"team-a","name":"design","class":"workstation","seats":2}`))) + }, + "a new desktop": func() error { + return staged(c.StageCreate(id, proj, draft.ResourceDesktop, json.RawMessage(`{"namespace":"team-a","name":"kiosk","image":"quay.io/deskube/desktop:3","running":true}`))) + }, + "an adopted desktop": func() error { return staged(c.AdoptObject(id, proj, carol)) }, + "a desktop adopted with its namespace": func() error { + return staged(c.AdoptObjects(id, proj, "team-a", []model.Adoptable{carol})) + }, + "an edited pool": func() error { + return staged(c.StageUpdateManifest(id, proj, "desktoppool", "team-a", "lab", model.UpdateManifestRequest{YAML: labManifest("", labSpec+" warm: 1\n")})) + }, + "a restored pool": func() error { return staged(c.RestoreVersion(id, proj, "desktoppool", "team-a", "lab", first)) }, + "a desktop turned off in git": func() error { + return staged(c.StageDesktopRunning(id, proj, "team-a", "solo", false)) + }, + "a reverted merge": func() error { + _, err := c.Revert(id, proj, last, model.PruneSet{}) + return err + }, + } + } + + off, proj, first, last := desktopsOnRig(t, false, allowAll{}) + for name, stage := range paths(off, proj, first, last) { + err := stage() + if !errors.Is(err, ErrDesktopsOff) || !errors.Is(err, model.ErrInvalid) || + !strings.HasSuffix(err.Error(), "desktops are not on for team-a: a platform admin turns them on from the project's Configure tab") { + t.Errorf("%s, desktops off: %v, want refused naming the fix", name, err) + } + } + if d, _ := off.store.List("alice", proj.Name); len(d) != 0 { + t.Errorf("staged where desktops are off: %+v", d) + } + // Beside the rest of its namespace, a desktop is left out, and said so. + v, err := off.AdoptObjects(auth.Identity{Username: "alice"}, proj, "team-a", []model.Adoptable{carol, web}) + if err != nil || len(v.Items) != 1 || v.Items[0].Name != "web" || + !strings.Contains(v.Warning, "team-a: desktops are not on there, so its pools and desktops stay outside git until a platform admin turns them on") { + t.Errorf("team-a adopted, desktops off: %v %+v", err, v) + } + + on, proj, first, last := desktopsOnRig(t, true, allowAll{}) + for name, stage := range paths(on, proj, first, last) { + if err := stage(); err != nil { + t.Errorf("%s, desktops on: %v", name, err) + } + } +} + +// Whether desktops are on is told only past the caller's rights: one who may +// not write the pool hears that, whatever the platform repo holds. +func TestDesktopsOffIsToldOnlyToTheirWriters(t *testing.T) { + reader := &rbac{deny: func(a Access) bool { return a.Group == "vdi.desku.be" }} + c, proj, _, last := desktopsOnRig(t, false, reader) + id := auth.Identity{Username: "dave"} + _, err := c.StageUpdateManifest(id, proj, "desktoppool", "team-a", "lab", model.UpdateManifestRequest{YAML: labManifest("", labSpec+" warm: 1\n")}) + if !errors.Is(err, model.ErrForbidden) || errors.Is(err, ErrDesktopsOff) { + t.Errorf("an edit by who may not write pools: %v, want forbidden alone", err) + } + if _, err := c.Revert(id, proj, last, model.PruneSet{}); !errors.Is(err, model.ErrForbidden) || errors.Is(err, ErrDesktopsOff) { + t.Errorf("a revert by who may not write pools: %v, want forbidden alone", err) + } +} + +// The Configure tab and the gate read one answer: the namespace's desktop +// grant in the platform repo. +func TestDesktopsOnIsTheGrantInGit(t *testing.T) { + path, grant, err := netgen.DesktopsManifest(netgen.RoleBindingSpec{Namespace: "web", Project: "shop", Kept: []netgen.Subject{user("alice")}}) + if err != nil { + t.Fatal(err) + } + c, plat := desktopsCoordinator(t, map[string][]byte{"rbac/web.yaml": grantYAML("web", "admin", user("alice")), path: grant}) + shop := project.ProjectInfo{Name: "shop", Namespaces: []string{"web", "db"}} + for ns, want := range map[string]bool{"web": true, "db": false} { + on, err := c.DesktopsOn(plat, ns) + if err != nil || on != want { + t.Errorf("%s: on=%v %v, want %v", ns, on, err, want) + } + if tab, _, _ := c.DesktopsNeeds(plat, shop, ns); tab != on { + t.Errorf("%s: the Configure tab reads on=%v, the gate %v", ns, tab, on) + } + } +} diff --git a/internal/changeset/drift.go b/internal/changeset/drift.go index 1670cd3e7..52d585e72 100644 --- a/internal/changeset/drift.go +++ b/internal/changeset/drift.go @@ -2,6 +2,7 @@ package changeset import ( "context" + "errors" "fmt" "log" @@ -141,7 +142,7 @@ func (c *Coordinator) AdoptObjects(id auth.Identity, proj project.ProjectInfo, w return model.DraftView{}, err } var entries []draft.Entry - var platformTier error + var platformTier, off error for _, o := range objs { if _, ok := idx.Files[model.ObjectRef{Kind: o.Kind, Namespace: o.Namespace, Name: o.Name}]; ok { continue @@ -153,6 +154,18 @@ func (c *Coordinator) AdoptObjects(id auth.Identity, proj project.ProjectInfo, w platformTier = err continue } + // So are pools and desktops where desktops are not on. Told to who may + // create them there: the route kept those alone. + if k == model.KindVdiPool || k == model.KindVdiInstance { + err := c.desktopsAreOn(proj, []string{o.Namespace}) + if errors.Is(err, ErrDesktopsOff) { + off = err + continue + } + if err != nil { + return model.DraftView{}, err + } + } entries = append(entries, draft.Entry{ Kind: draft.KindCreate, Resource: adoptResource(o.Kind), @@ -162,13 +175,19 @@ func (c *Coordinator) AdoptObjects(id auth.Identity, proj project.ProjectInfo, w Manifest: string(o.Manifest), }) } - if len(entries) == 0 && platformTier != nil { + switch { + case len(entries) == 0 && platformTier != nil: return model.DraftView{}, platformTier - } - if len(entries) == 0 { + case len(entries) == 0 && off != nil: + return model.DraftView{}, off + case len(entries) == 0: return model.DraftView{}, fmt.Errorf("%w: nothing to adopt in %s: git already describes everything running there", model.ErrInvalid, where) } - return c.stage(id, proj, entries...) + v, err := c.stage(id, proj, entries...) + if err == nil && off != nil { + v.Warning = JoinWarning(v.Warning, where+": desktops are not on there, so its pools and desktops stay outside git until a platform admin turns them on from the project's Configure tab.") + } + return v, err } // adoptResource maps a captured kind onto the draft vocabulary, so the Changes view @@ -182,26 +201,36 @@ func adoptResource(kind string) draft.Resource { return draft.ResourceVM } -// Resync triggers an ArgoCD sync of the Application managing the VM, bringing the -// cluster back to git (main->live reconcile). Writes nothing to git. It uses the +// Resync triggers an ArgoCD sync of the Application managing one object of +// kind - a VM, a pool or a desktop made one by one - bringing the cluster back +// to git (main->live reconcile). Writes nothing to git. It uses the // SA-identity resyncer (Argo operations have no user context, but the request's // ctx still bounds the call so a hung Argo op doesn't outlive the HTTP request). // Because this is the one operation that escalates to dotvirt's SA, the caller's // own authority over what the sync applies (ResyncNeeds, weighed by the gate's // authorizer under the caller's token) is enforced here, beside the escalation - -// not only at the transport layer. -func (c *Coordinator) Resync(ctx context.Context, id auth.Identity, proj project.ProjectInfo, namespace, name string) (model.ResyncResult, error) { +// not only at the transport layer. A pool or a desktop is synced only where +// desktops are on, as the gate stages one. +func (c *Coordinator) Resync(ctx context.Context, id auth.Identity, proj project.ProjectInfo, kind model.Kind, namespace, name string) (model.ResyncResult, error) { if c.resyncer == nil { return model.ResyncResult{}, fmt.Errorf("%w: re-sync unavailable (ArgoCD not configured)", model.ErrUnavailable) } - need, err := c.ResyncNeeds(proj, namespace, name) + if kind != model.KindVM && kind != model.KindVdiPool && kind != model.KindVdiInstance { + return model.ResyncResult{}, fmt.Errorf("%w: only a VM, a pool or a desktop made one by one is synced alone", model.ErrInvalid) + } + need, err := c.ResyncNeeds(proj, kind, namespace, name) if err != nil { return model.ResyncResult{}, err } if err := c.authorize(id, need); err != nil { return model.ResyncResult{}, err } - return c.resyncer.Resync(ctx, id.Username, namespace, name) + if kind != model.KindVM { + if err := c.desktopsAreOn(proj, []string{namespace}); err != nil { + return model.ResyncResult{}, err + } + } + return c.resyncer.Resync(ctx, id.Username, kind, namespace, name) } // VMDrift returns the semantic diff between a VM as it runs (actual) and as main diff --git a/internal/changeset/gate.go b/internal/changeset/gate.go index 62f17f94e..a6ea54b43 100644 --- a/internal/changeset/gate.go +++ b/internal/changeset/gate.go @@ -126,37 +126,46 @@ func (c *Coordinator) authorize(id auth.Identity, need []Access) error { // on. It pins each entry writing or removing a file to the version of that // file it weighed (draft.Entry.BaseBlob) and answers *git.BaseMovedError for // one pinned to another: its accesses would be read off the wrong version. +// A pool or a desktop goes only where desktops are on. func (c *Coordinator) gate(id auth.Identity, proj project.ProjectInfo, entries []draft.Entry) error { - need, err := c.needs(proj, entries) + need, desks, err := c.weigh(proj, entries) if err != nil { return err } - return c.authorize(id, need) + if err := c.authorize(id, need); err != nil { + return err + } + return c.desktopsAreOn(proj, desks) } // needs is every access committing entries to proj's base branch makes the // cluster perform once merged. func (c *Coordinator) needs(proj project.ProjectInfo, entries []draft.Entry) ([]Access, error) { + need, _, err := c.weigh(proj, entries) + return need, err +} + +// weigh is needs, and the namespaces entries write a pool or a desktop in. +func (c *Coordinator) weigh(proj project.ProjectInfo, entries []draft.Entry) (need []Access, desks []string, err error) { if len(entries) == 0 { - return nil, nil + return nil, nil, nil } read, err := c.read(proj) if err != nil { - return nil, err + return nil, nil, err } idx, err := indexDeclared(read, c.baseBranch) if err != nil { - return nil, err + return nil, nil, err } - var need []Access for i := range entries { - a, err := c.entryAccess(read, idx, proj, &entries[i]) + a, err := c.entryAccess(read, idx, proj, &entries[i], &desks) if err != nil { - return nil, err + return nil, nil, err } need = append(need, a...) } - return need, nil + return need, desks, nil } // write is how an entry changes its file: the one reading the gate weighs @@ -182,8 +191,9 @@ func writeOf(e draft.Entry) write { return noWrite } -// entryAccess is what committing e does to the cluster. -func (c *Coordinator) entryAccess(read *git.Repo, idx declaredIndex, proj project.ProjectInfo, e *draft.Entry) ([]Access, error) { +// entryAccess is what committing e does to the cluster, adding to desks each +// namespace it writes a pool or a desktop in. +func (c *Coordinator) entryAccess(read *git.Repo, idx declaredIndex, proj project.ProjectInfo, e *draft.Entry, desks *[]string) ([]Access, error) { if e.Manifest != "" && e.Edit != nil { return nil, fmt.Errorf("%w: %s carries both a manifest and a settings edit; unstage it and make the change again", model.ErrInvalid, objectLabel(*e)) } @@ -193,7 +203,7 @@ func (c *Coordinator) entryAccess(read *git.Repo, idx declaredIndex, proj projec if err != nil { return nil, err } - return fileAccess(c.kindRule(), proj, idx, fileChange{path: e.SourceFile, before: before, after: []byte(e.Manifest), declared: c.declaredBody(read, idx), live: c.desktops}, expected(*e)) + return fileAccess(c.kindRule(), proj, idx, fileChange{path: e.SourceFile, before: before, after: []byte(e.Manifest), declared: c.declaredBody(read, idx), live: c.desktops, desks: desks}, expected(*e)) case removal: before, err := c.based(read, e) if err != nil || before == nil { @@ -380,6 +390,9 @@ type fileChange struct { declared func(model.ObjectRef) map[string]any // live is DeskuBe's pools and desktops as they run, nil for unknown. live DesktopsLive + // desks, when set, collects each namespace the write puts a pool or a + // desktop in, which desktopsAreOn weighs. + desks *[]string } // fileAccess validates what ch leaves at its path and derives the accesses it @@ -443,8 +456,12 @@ func fileAccess(rule KindRule, proj project.ProjectInfo, idx declaredIndex, ch f if err := ownNetworks(rule, o); err != nil { return nil, err } + desk := o.kind == model.KindVdiInstance || o.kind == model.KindVdiPool + if desk && ch.desks != nil && !slices.Contains(*ch.desks, o.ref.Namespace) { + *ch.desks = append(*ch.desks, o.ref.Namespace) + } held := prev.body - if !inFile && onBranch && (o.kind == model.KindVdiInstance || o.kind == model.KindVdiPool) && ch.declared != nil { + if !inFile && onBranch && desk && ch.declared != nil { held = ch.declared(o.ref) } if err := desktopFields(o, held); err != nil { diff --git a/internal/changeset/needs.go b/internal/changeset/needs.go index 677d71844..c5f57c8c2 100644 --- a/internal/changeset/needs.go +++ b/internal/changeset/needs.go @@ -97,11 +97,14 @@ func (c *Coordinator) DisableDRSNeeds(proj project.ProjectInfo) ([]Access, error return c.needs(proj, entries) } -// ResyncNeeds is syncing VM namespace/name from proj's base branch: Argo -// applying its declared object, a create the authorizer weighs as the update -// of a running VM, or a delete and a create when its sync options replace it. -func (c *Coordinator) ResyncNeeds(proj project.ProjectInfo, namespace, name string) ([]Access, error) { - path, content, err := c.Manifest(proj, namespace, name, true) +// ResyncNeeds is syncing the object of kind namespace/name - a VM, a pool or +// a desktop made one by one - from proj's base branch: Argo applying its +// declared object, a create the authorizer weighs as the update of a running +// one, or a delete and a create when its sync options replace it; for a pool +// or a desktop, what DeskuBe asks of whoever grants what git's version grants +// beside what runs. +func (c *Coordinator) ResyncNeeds(proj project.ProjectInfo, kind model.Kind, namespace, name string) ([]Access, error) { + path, content, err := c.resyncFile(proj, kind, namespace, name) if err != nil { return nil, err } @@ -110,9 +113,34 @@ func (c *Coordinator) ResyncNeeds(proj project.ProjectInfo, namespace, name stri return nil, err } for _, o := range objs { - if o.kind == model.KindVM && o.ref.Namespace == namespace && o.ref.Name == name { - return objectAccess(o, false) + if o.kind == kind && o.ref.Namespace == namespace && o.ref.Name == name { + need, err := objectAccess(o, false) + if err != nil { + return nil, err + } + return append(need, desktopGrants(o, o.body, c.desktops)...), nil } } - return nil, fmt.Errorf("%w: VM %s/%s is not in git", model.ErrNotFound, namespace, name) + noun := kind.Kind + if kind == model.KindVM { + noun = "VM" + } + return nil, fmt.Errorf("%w: %s %s/%s is not in git", model.ErrNotFound, noun, namespace, name) +} + +// resyncFile is the whole file declaring the object of kind namespace/name. +func (c *Coordinator) resyncFile(proj project.ProjectInfo, kind model.Kind, namespace, name string) (string, []byte, error) { + if kind == model.KindVM { + return c.Manifest(proj, namespace, name, true) + } + read, err := c.read(proj) + if err != nil { + return "", nil, err + } + path, err := c.locate(read, []model.Kind{kind}, namespace, name) + if err != nil { + return "", nil, err + } + content, err := read.FileOnBranch(c.baseBranch, path) + return path, content, err } diff --git a/internal/changeset/resync_test.go b/internal/changeset/resync_test.go index 7352c5c25..250c46d91 100644 --- a/internal/changeset/resync_test.go +++ b/internal/changeset/resync_test.go @@ -10,13 +10,63 @@ import ( "github.com/epheo/dotvirt/internal/project" ) -type fakeResyncer struct{ called bool } +type fakeResyncer struct { + called bool + synced model.Kind +} -func (f *fakeResyncer) Resync(ctx context.Context, username, namespace, name string) (model.ResyncResult, error) { - f.called = true +func (f *fakeResyncer) Resync(_ context.Context, _ string, kind model.Kind, _, _ string) (model.ResyncResult, error) { + f.called, f.synced = true, kind return model.ResyncResult{Application: "app"}, nil } +// A pool or a desktop git declares is synced alone, by its kind, as a VM is: +// the caller is asked what Argo applying it asks, a desktop owner's grants +// among them, and the escalation is reached only where desktops are on, told +// only to who may sync it. +func TestResyncSyncsADesktopWhereDesktopsAreOn(t *testing.T) { + id := auth.Identity{Username: "alice"} + for _, on := range []bool{false, true} { + r := &rbac{} + c, proj, _, _ := desktopsOnRig(t, on, r) + rs := &fakeResyncer{} + c.resyncer = rs + for _, k := range []model.Kind{model.KindVdiInstance, model.KindVdiPool} { + name := map[model.Kind]string{model.KindVdiInstance: "solo", model.KindVdiPool: "lab"}[k] + rs.called = false + _, err := c.Resync(context.Background(), id, proj, k, "team-a", name) + if !on { + if !errors.Is(err, ErrDesktopsOff) || rs.called { + t.Errorf("%s, desktops off: %v, reached %v; want refused before the escalation", k.Kind, err, rs.called) + } + continue + } + if err != nil || !rs.called || rs.synced != k { + t.Errorf("%s, desktops on: %v, synced %v", k.Kind, err, rs.synced) + } + } + asked := map[string]bool{} + for _, a := range r.questions() { + asked[a.Verb+" "+a.Resource+" "+a.Name] = true + } + for _, q := range []string{"create vdiinstances solo", "create rolebindings ", "create vdipools lab"} { + if !asked[q] { + t.Errorf("desktops on=%v: asked %v, want %q among them", on, asked, q) + } + } + } + + r := &rbac{deny: func(a Access) bool { return a.Group == "vdi.desku.be" }} + c, proj, _, _ := desktopsOnRig(t, false, r) + c.resyncer = &fakeResyncer{} + if _, err := c.Resync(context.Background(), id, proj, model.KindVdiInstance, "team-a", "solo"); !errors.Is(err, model.ErrForbidden) || errors.Is(err, ErrDesktopsOff) { + t.Errorf("who may not sync the desktop: %v, want forbidden alone", err) + } + if _, err := c.Resync(context.Background(), id, proj, model.KindVdiInstance, "team-a", "ghost"); !errors.Is(err, model.ErrNotFound) { + t.Errorf("a desktop git does not declare: %v", err) + } +} + // A resync asks what Argo applying the VM's declared object asks - its // create, which the authorizer weighs as the update of a running VM - and a // replacing sync option makes it a delete and a create; a refusal never @@ -40,13 +90,13 @@ func TestResyncWeighsWhatTheSyncApplies(t *testing.T) { } return out } - if res, err := c.Resync(context.Background(), id, proj, "alpha", "web"); err != nil || res.Application != "app" { + if res, err := c.Resync(context.Background(), id, proj, model.KindVM, "alpha", "web"); err != nil || res.Application != "app" { t.Fatalf("allowed caller: got %+v, %v", res, err) } if got := verbs(); len(got) != 1 || got[0] != "create virtualmachines web" { t.Errorf("asked %v, want the VM's create", got) } - if _, err := c.Resync(context.Background(), id, proj, "alpha", "db"); err != nil { + if _, err := c.Resync(context.Background(), id, proj, model.KindVM, "alpha", "db"); err != nil { t.Fatal(err) } if got := verbs(); len(got) != 3 || got[1] != "delete virtualmachines db" || got[2] != "create virtualmachines db" { @@ -55,20 +105,20 @@ func TestResyncWeighsWhatTheSyncApplies(t *testing.T) { rs.called = false r.refuse(func(Access) bool { return true }) - if _, err := c.Resync(context.Background(), id, proj, "alpha", "web"); !errors.Is(err, model.ErrForbidden) { + if _, err := c.Resync(context.Background(), id, proj, model.KindVM, "alpha", "web"); !errors.Is(err, model.ErrForbidden) { t.Fatalf("denied caller: want ErrForbidden, got %v", err) } if rs.called { t.Fatal("resyncer reached despite the refusal") } - if _, err := c.Resync(context.Background(), id, proj, "alpha", "ghost"); !errors.Is(err, model.ErrNotFound) { + if _, err := c.Resync(context.Background(), id, proj, model.KindVM, "alpha", "ghost"); !errors.Is(err, model.ErrNotFound) { t.Errorf("a VM git does not declare: %v", err) } } func TestResyncUnavailableWithoutArgo(t *testing.T) { c := newTestCoordinator(t, false) - if _, err := c.Resync(context.Background(), auth.Identity{}, project.ProjectInfo{}, "a", "b"); !errors.Is(err, model.ErrUnavailable) { + if _, err := c.Resync(context.Background(), auth.Identity{}, project.ProjectInfo{}, model.KindVM, "a", "b"); !errors.Is(err, model.ErrUnavailable) { t.Fatalf("want ErrUnavailable, got %v", err) } } diff --git a/internal/changeset/revert.go b/internal/changeset/revert.go index ed68504d8..b3d52d0dc 100644 --- a/internal/changeset/revert.go +++ b/internal/changeset/revert.go @@ -42,13 +42,16 @@ func (c *Coordinator) Revert(id auth.Identity, proj project.ProjectInfo, hash st if len(items) == 0 { return model.ProposeResult{}, fmt.Errorf("%w: nothing to revert in that commit", model.ErrInvalid) } - need, err := c.revertAccess(read, proj, items) + need, desks, err := c.revertAccess(read, proj, items) if err != nil { return model.ProposeResult{}, err } if err := c.authorize(id, need); err != nil { return model.ProposeResult{}, err } + if err := c.desktopsAreOn(proj, desks); err != nil { + return model.ProposeResult{}, err + } p := c.pruning(id, proj, restoredBy(items)) if err := p.refuse(ack); err != nil { return model.ProposeResult{}, err @@ -143,29 +146,29 @@ func restoredBy(items []git.ChangesetItem) []model.ObjectRef { // revertAccess is what the revert's items do to the cluster, each file read // against base as it stands; each item is pinned to that version, so the -// commit lands on exactly what was weighed. -func (c *Coordinator) revertAccess(read *git.Repo, proj project.ProjectInfo, items []git.ChangesetItem) ([]Access, error) { +// commit lands on exactly what was weighed. desks are the namespaces it +// writes a pool or a desktop in. +func (c *Coordinator) revertAccess(read *git.Repo, proj project.ProjectInfo, items []git.ChangesetItem) (need []Access, desks []string, err error) { idx, err := indexDeclared(read, c.baseBranch) if err != nil { - return nil, err + return nil, nil, err } - var need []Access for i, it := range items { before, ok, err := read.LookupOnBranch(c.baseBranch, it.Path) if err != nil { - return nil, err + return nil, nil, err } if !ok { before = nil } items[i].BaseBlob = pinOf(before, ok) - a, err := fileAccess(c.kindRule(), proj, idx, fileChange{path: it.Path, before: before, after: it.NewContent, remove: it.Delete, declared: c.declaredBody(read, idx), live: c.desktops}, nil) + a, err := fileAccess(c.kindRule(), proj, idx, fileChange{path: it.Path, before: before, after: it.NewContent, remove: it.Delete, declared: c.declaredBody(read, idx), live: c.desktops, desks: &desks}, nil) if err != nil { - return nil, err + return nil, nil, err } need = append(need, a...) } - return need, nil + return need, desks, nil } // revertBranch is the per-(user, project, commit) branch a revert lands on. diff --git a/internal/desktops/desktops.go b/internal/desktops/desktops.go index cda0c0912..c000f1b92 100644 --- a/internal/desktops/desktops.go +++ b/internal/desktops/desktops.go @@ -292,6 +292,7 @@ func none() model.Desktops { Desktops: []model.Desktop{}, Claims: []model.DesktopClaim{}, Unlisted: []model.DesktopKind{}, + InGit: []model.DesktopInGit{}, } } @@ -483,6 +484,28 @@ func (s *Snapshot) Runs(gvr schema.GroupVersionResource, namespace, name string) return false } +// NotRunning is those of refs, pools and desktops by kind, the snapshot +// holds no row of, as Overview reads its rows: the last known while a watch +// is down. +func (s *Snapshot) NotRunning(refs []model.ObjectRef) []model.ObjectRef { + s.mu.RLock() + defer s.mu.RUnlock() + var out []model.ObjectRef + for _, r := range refs { + var held bool + switch r.Kind { + case model.KindVdiPool.Kind: + _, held = s.pools.Rows[r.Namespace+"/"+r.Name] + case model.KindVdiInstance.Kind: + _, held = s.instances.Rows[r.Namespace+"/"+r.Name] + } + if !held { + out = append(out, r) + } + } + return out +} + // HasPod reports whether a desktop's phase shows its pod: Ready, or Starting // on a node. Any other has no session a restart would end: a Stopping or // Stopped one stays stopped, a Provisioning one has no pod yet, a Failed one diff --git a/internal/model/caps.go b/internal/model/caps.go index 13a09d9db..64fc73f58 100644 --- a/internal/model/caps.go +++ b/internal/model/caps.go @@ -160,10 +160,14 @@ type NamespaceCaps struct { // false until a tenant repo may declare them: Argo CD applies them as the // project's own account. DesktopsHeld says the caller could author one // here but for that. - DesktopPool ObjectCaps `json:"desktopPool"` - Desktop ObjectCaps `json:"desktop"` - DesktopsHeld bool `json:"desktopsHeld,omitempty"` - Project ProjectCaps `json:"project"` + DesktopPool ObjectCaps `json:"desktopPool"` + Desktop ObjectCaps `json:"desktop"` + DesktopsHeld bool `json:"desktopsHeld,omitempty"` + // DesktopsOff: desktops are not on here, so both stay false. Told to a + // caller who may list rolebindings here, as ProjectCaps.DesktopsOn is, + // or who could author one here but for it, as staging one tells them. + DesktopsOff bool `json:"desktopsOff,omitempty"` + Project ProjectCaps `json:"project"` } // ProjectCaps are the actions on a namespace's whole project, over every one diff --git a/internal/model/desktop.go b/internal/model/desktop.go index 6f73430c4..a2c2dd656 100644 --- a/internal/model/desktop.go +++ b/internal/model/desktop.go @@ -17,6 +17,9 @@ type Desktops struct { // not shown. Desktops []Desktop `json:"desktops"` Claims []DesktopClaim `json:"claims"` + // InGit are the pools and desktops made one by one that a repo declares + // and the cluster does not run, where the caller may list their kind. + InGit []DesktopInGit `json:"inGit"` // Unlisted are, for a caller who may list some kind, the kinds it may // not list in each namespace of the request, and the classes when it may // not list them cluster-wide: its own rights, never what exists. A pool's @@ -25,6 +28,23 @@ type Desktops struct { Unlisted []DesktopKind `json:"unlisted"` } +// DesktopInGit is a pool, or a desktop made one by one, its project's repo +// declares that does not run: Argo CD has not applied it yet, or could not. +// Sync, Health and SyncError are its own Argo CD drift. +type DesktopInGit struct { + Resource string `json:"resource"` // vdipools | vdiinstances + Namespace string `json:"namespace"` + Name string `json:"name"` + SourceFile string `json:"sourceFile"` + Sync SyncStatus `json:"sync,omitempty"` + Health string `json:"health,omitempty"` + SyncError string `json:"syncError,omitempty"` + // SyncStalled: Argo CD's last sync failed on the revision declaring it, + // which automated sync never tries again: a new merge, or a resync of + // it, applies it. + SyncStalled bool `json:"syncStalled,omitempty"` +} + // DesktopKind is one kind in one namespace, "" for the classes. type DesktopKind struct { Namespace string `json:"namespace"` diff --git a/web/e2e/fixture/create.mjs b/web/e2e/fixture/create.mjs index b612d9c9f..f1c815731 100644 --- a/web/e2e/fixture/create.mjs +++ b/web/e2e/fixture/create.mjs @@ -424,7 +424,9 @@ const ROUTES = { }, '/api/desktoppools': { tier: () => 'tenant', - gate: (b, ctx) => deskWriter(ctx.nsCaps(b.namespace).desktopPool, 'vdipools', b.namespace), + gate: (b, ctx) => + deskOn(ctx, b.namespace) ?? + deskWriter(ctx.nsCaps(b.namespace).desktopPool, 'vdipools', b.namespace), render: (b, s) => { named('name', b.name); deskFree(s, 'desktop pool', b.namespace, b.name); @@ -448,7 +450,9 @@ const ROUTES = { }, '/api/desktops': { tier: () => 'tenant', - gate: (b, ctx) => deskWriter(ctx.nsCaps(b.namespace).desktop, 'vdiinstances', b.namespace), + gate: (b, ctx) => + deskOn(ctx, b.namespace) ?? + deskWriter(ctx.nsCaps(b.namespace).desktop, 'vdiinstances', b.namespace), render: (b, s) => { named('name', b.name); deskFree(s, 'desktop', b.namespace, b.name); @@ -512,10 +516,20 @@ const ROUTES = { }, }; -// DeskuBe's creates, refused as the server refuses them: the route's right on -// the kind there, a name that runs, the guard's rules, and an owner or +// DeskuBe's creates, refused as the server refuses them: desktops not on +// there, the route's right on the kind there, a name that runs, the guard's +// rules, and an owner or // subjects set by a caller the scenario's desktopsUnbound says may bind no one // in that namespace. +// Where the scenario's desktopsOff says desktops are not on, the server +// refuses past the caller's right, which these scenarios hold. +function deskOn(ctx, ns) { + if (ctx.state.scenario.desktopsOff?.includes(ns)) + throw new Refused( + 400, + `invalid request: desktops are not on for ${ns}: a platform admin turns them on from the project's Configure tab`, + ); +} function deskWriter(caps, resource, ns) { if (!caps?.create && !caps?.update) throw new Refused( diff --git a/web/e2e/fixture/scenarios.mjs b/web/e2e/fixture/scenarios.mjs index df88c621a..da2531a2b 100644 --- a/web/e2e/fixture/scenarios.mjs +++ b/web/e2e/fixture/scenarios.mjs @@ -2605,6 +2605,59 @@ const desktopsgitheld = { // there: a new owner or new subjects ask what it lacks. const desktopsunbound = { ...desktopsgit, name: 'desktopsunbound', desktopsUnbound: ['web-prod'] }; +// de, a desktop git declares in web-prod that Argo CD could not create, and +// design, a pool it has not applied yet. +const forbidden = + 'vdiinstances.vdi.desku.be is forbidden: User "system:serviceaccount:openshift-gitops:dotvirt-p-team-web" cannot create resource "vdiinstances" in API group "vdi.desku.be" in the namespace "web-prod"'; +const inGit = (over = {}) => [ + { + resource: 'vdiinstances', + namespace: 'web-prod', + name: 'de', + sourceFile: 'web-prod/desktops/de.yaml', + sync: 'OutOfSync', + health: 'Missing', + syncError: forbidden, + syncStalled: true, + ...over, + }, + { + resource: 'vdipools', + namespace: 'web-prod', + name: 'design', + sourceFile: 'web-prod/desktop-pools/design.yaml', + }, +]; +// A platform admin, where desktops are not on in web-prod: it may turn them +// on, and Argo CD gave up on de, which they hold back. +const desktopsoff = { + ...desktopsgit, + name: 'desktopsoff', + desktopsOff: ['web-prod'], + capabilities: { + 'web-prod': { + desktopPool: { create: false, update: false, delete: false }, + desktop: { create: false, update: false, delete: false }, + desktopsOff: true, + project: { desktops: ['web-prod'] }, + }, + }, + desktops: { ...deskubeGit, inGit: inGit() }, +}; +// Desktops on in web-prod since, and Argo CD gave up on de before: a resync +// applies it. +const desktopsstalled = { + ...desktopsgit, + name: 'desktopsstalled', + desktops: { ...deskubeGit, inGit: inGit() }, +}; +// The same, to a project viewer, who may resync nothing. +const desktopsstalledviewer = { + ...desktopsgitviewer, + name: 'desktopsstalledviewer', + desktops: { ...desktopsgitviewer.desktops, inGit: inGit() }, +}; + // Desktops made one by one in git, each powered otherwise: carol-dev on, on // her running claim; erin-dev off in git, her claim running on top; frank-dev // on in git and stopped on his claim, which DeskuBe records; gina-dev on in @@ -2821,6 +2874,9 @@ export const scenarios = { desktopsgitviewer, desktopsgitheld, desktopsunbound, + desktopsoff, + desktopsstalled, + desktopsstalledviewer, desktopspower, desktopspowerviewer, desktopspowerreclaimed, diff --git a/web/e2e/fixture/server.mjs b/web/e2e/fixture/server.mjs index d04cd79f0..01e4873a9 100644 --- a/web/e2e/fixture/server.mjs +++ b/web/e2e/fixture/server.mjs @@ -737,7 +737,7 @@ async function handleAPI(req, res, url) { if (path === '/api/networking/routes') return sendJSON(res, 200, s.tenantRoutes ?? []); if (path === '/api/desktops') { const none = { synced: true, classes: [], pools: [], desktops: [], claims: [], unlisted: [] }; - return sendJSON(res, 200, s.desktops ?? none); + return sendJSON(res, 200, { inGit: [], ...(s.desktops ?? none) }); } if (path === '/api/storage/replication') return sendJSON(res, 200, s.replication); if (path === '/api/storage/protection') return sendJSON(res, 200, s.protection ?? []); @@ -937,6 +937,34 @@ async function handleAPI(req, res, url) { state.staged.set(p.name, rest); return sendJSON(res, 200, draftFor(p.name)); } + // A pool or a desktop git declares synced alone, as a VM's resync is: by + // who may change it, where desktops are on. Argo CD then tries again. + m = path.match(/^\/api\/objects\/([^/]+)\/([^/]+)\/([^/]+)\/resync$/); + if (m && req.method === 'POST') { + const [, resource, ns, name] = m; + const kind = { desktoppool: 'desktopPool', desktop: 'desktop' }[resource]; + if (!kind) + return sendText( + res, + 400, + 'invalid request: only a pool or a desktop made one by one is synced here; a VM is synced from its own page', + ); + const p = projectOf(ns); + if (!p || !namespaceCaps(s, p, ns)[kind].update) + return sendText(res, 403, `forbidden: not authorized to update ${resource}s in ${ns}`); + if (s.desktopsOff?.includes(ns)) + return sendText( + res, + 400, + `invalid request: desktops are not on for ${ns}: a platform admin turns them on from the project's Configure tab`, + ); + const row = s.desktops?.inGit?.find((r) => r.namespace === ns && r.name === name); + if (!row) return sendText(res, 404, `not found: ${ns}/${name} not on main`); + row.syncStalled = false; + s.inventory.desktopsVersion = (s.inventory.desktopsVersion ?? 0) + 1; + broadcastInventory(); + return sendJSON(res, 200, { application: `dotvirt-${p.name}`, revision: 'main' }); + } m = path.match(/^\/api\/objects\/([^/]+)\/([^/]+)\/([^/]+)\/restore$/); if (m && req.method === 'POST') { const [, resource, ns, name] = m; diff --git a/web/e2e/ui/desktopsingit.spec.ts b/web/e2e/ui/desktopsingit.spec.ts new file mode 100644 index 000000000..6404eed2d --- /dev/null +++ b/web/e2e/ui/desktopsingit.spec.ts @@ -0,0 +1,104 @@ +import { expect, login, setScenario, test } from './fx'; +import type { Page } from '@playwright/test'; + +// A pool or a desktop git declares and the cluster does not run is a row and +// a page of its own, marked In git, not running, with what Argo CD says of it +// and its next step: desktops turned on where they are off, a resync of the +// revision Argo CD gave up on, or Argo CD's own refusal. No pool or desktop +// is made where desktops are off: the form says so before it sends. + +const OFF = + "Desktops are not on in web-prod: a platform admin turns them on from the project's Configure tab."; +const main = (page: Page) => page.locator('main'); +const inGit = (page: Page) => main(page).getByRole('table', { name: 'In git, not running' }); + +test('where desktops are off, nothing new is offered, and the form says who turns them on', async ({ + page, +}) => { + await setScenario(page, 'desktopsoff'); + await login(page); + await page.goto('/desktops/team-web/web-prod'); + await expect(main(page).getByText(`${OFF} Then add pools and desktops here.`)).toBeVisible(); + await expect(main(page).getByRole('button', { name: 'New pool' })).toHaveCount(0); + await expect(main(page).getByRole('button', { name: 'New desktop' })).toHaveCount(0); + + await page.getByRole('button', { name: 'New', exact: true }).click(); + const sheet = page.getByRole('dialog'); + await expect(sheet.getByRole('heading', { name: 'New desktop pool' })).toBeVisible(); + await expect(sheet.getByRole('status')).toHaveText(OFF); + await expect(sheet.getByRole('button', { name: 'Stage pool' })).toBeDisabled(); + await sheet.locator('input[name="desktop-kind"][value="desktop"]').check(); + await sheet.getByLabel('Name', { exact: true }).fill('dana-dev'); + await expect(sheet.getByRole('status')).toHaveText(OFF); + await expect(sheet.getByRole('button', { name: 'Stage desktop' })).toBeDisabled(); +}); + +test('a desktop Argo CD may not create here is a row and a page that lead to turning desktops on', async ({ + page, +}) => { + await setScenario(page, 'desktopsoff'); + await login(page); + await page.goto('/desktops/team-web/web-prod'); + const rows = inGit(page); + await expect(rows.locator('tbody tr')).toHaveCount(2); + await expect(rows.getByRole('row', { name: /de Desktop/ })).toContainText( + 'Desktops are not on here.', + ); + + await rows.getByRole('link', { name: 'de', exact: true }).click(); + await expect(page).toHaveURL(/\/desktops\/team-web\/web-prod\/desktop\/de$/); + await expect(main(page).getByText('In git, not running').first()).toBeVisible(); + await expect( + main(page).getByText('Git declares this desktop, and the cluster does not run it.'), + ).toBeVisible(); + const git = main(page).getByRole('region', { name: 'Git', exact: true }); + await expect(git).toContainText('In git, web-prod/desktops/de.yaml'); + await git.getByRole('button', { name: 'Sync failed' }).click(); + await expect(page.getByRole('dialog')).toContainText('cannot create resource "vdiinstances"'); + await page.keyboard.press('Escape'); + + await main(page).getByRole('link', { name: "the project's Configure tab" }).click(); + await expect(page).toHaveURL(/\/compute\/team-web\?tab=configure$/); + await expect(page.getByRole('button', { name: 'Turn desktops on' })).toBeVisible(); +}); + +test('once desktops are on, a desktop Argo CD gave up on is resynced from its page', async ({ + page, +}) => { + await setScenario(page, 'desktopsstalled'); + await login(page); + await page.goto('/desktops/team-web/web-prod/desktop/de'); + const note = main(page).getByText(/Argo CD tried the revision declaring this desktop, failed/); + await expect(note).toBeVisible(); + const resync = page.waitForRequest( + (r) => + r.method() === 'POST' && + new URL(r.url()).pathname === '/api/objects/desktop/web-prod/de/resync', + ); + await main(page).getByRole('button', { name: 'Resync' }).click(); + await resync; + await expect( + page.getByText('Resync of de asked of Argo CD app "dotvirt-team-web".'), + ).toBeVisible(); + // Argo CD tries again: its refusal stands until it applies it. + await expect( + main(page).getByText(/Argo CD could not apply this desktop, and tries again/), + ).toBeVisible(); + + // The pool Argo CD has not applied yet waits on Argo CD alone, and its + // name is git's: a new pool does not take it. + await page.goto('/desktops/team-web/web-prod/pool/design'); + await expect(main(page).getByText('Argo CD has not applied it yet.')).toBeVisible(); + await page.getByRole('button', { name: 'New', exact: true }).click(); + const sheet = page.getByRole('dialog'); + await sheet.getByLabel('Name', { exact: true }).fill('design'); + await expect(sheet.getByRole('status')).toHaveText('design is taken in web-prod'); +}); + +test('a viewer is told who may resync, and offered no resync', async ({ page }) => { + await setScenario(page, 'desktopsstalledviewer'); + await login(page); + await page.goto('/desktops/team-web/web-prod/desktop/de'); + await expect(main(page).getByText(/A project admin can resync it\./)).toBeVisible(); + await expect(main(page).getByRole('button', { name: 'Resync' })).toHaveCount(0); +}); diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index be1c52317..bb374437b 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -605,6 +605,13 @@ export const api = { // staged as a VM's power is. desktopRunning: (namespace: string, name: string, running: boolean) => post(`/api/objects/desktop/${enc(namespace)}/${enc(name)}/running`, { running }), + // Syncs a pool or a desktop made one by one alone from git, as a VM's + // resync does: what applies it once Argo CD gave up on its revision. + resyncObject: (resource: string, namespace: string, name: string) => + post<{ application: string; revision: string }>( + `/api/objects/${enc(resource)}/${enc(namespace)}/${enc(name)}/resync`, + {}, + ), // The VM page's history and restore, for every other declared object. objectHistory: (resource: string, namespace: string, name: string) => get(`/api/objects/${enc(resource)}/${enc(namespace)}/${enc(name)}/history`), diff --git a/web/src/lib/components/create/DesktopOneForm.svelte b/web/src/lib/components/create/DesktopOneForm.svelte index 8d1fe2bfd..81958a699 100644 --- a/web/src/lib/components/create/DesktopOneForm.svelte +++ b/web/src/lib/components/create/DesktopOneForm.svelte @@ -4,6 +4,7 @@ import { allDesktops } from '#lib/desktops.js'; import { desktopRefusals } from '#lib/desktopspec.js'; import { desktopGitGate } from '#lib/gates.js'; + import { CHECKING } from '#lib/state/caps.svelte.js'; import { action } from '#lib/resource.svelte.js'; import { desktops } from '#lib/state/desktops.svelte.js'; import { inventory } from '#lib/state/inventory.svelte.js'; @@ -52,18 +53,24 @@ if (from === 'image' && image.trim()) req.image = image.trim(); return req; }); + // A name that runs, or that git declares and the cluster does not run yet. const taken = $derived( !!desktops.value && - allDesktops(desktops.value).some((d) => d.namespace === namespace && d.name === name), + [ + ...allDesktops(desktops.value), + ...desktops.value.inGit.filter((r) => r.resource === 'vdiinstances'), + ].some((d) => d.namespace === namespace && d.name === name), ); const gate = $derived(desktopGitGate({ resource: 'desktop', namespace }, 'create')); const missing = $derived.by(() => { const m: string[] = []; + // The place, and what holds it back, come first: no other field fixes them. + const held = !namespace ? 'Pick a project and namespace' : gate.ok ? '' : gate.why; + if (held && held !== CHECKING) m.push(held); if (!name) m.push('Name the desktop'); else if (!validName(name)) m.push('The name needs lowercase letters, digits and -'); else if (taken) m.push(`${name} is taken in ${namespace}`); - if (!namespace) m.push('Pick a project and namespace'); - else if (!gate.ok) m.push(gate.why); + if (held === CHECKING) m.push(held); m.push(...desktopRefusals(request).map((r) => r.why)); return m; }); diff --git a/web/src/lib/components/create/DesktopPoolForm.svelte b/web/src/lib/components/create/DesktopPoolForm.svelte index 65364742d..90982aa9e 100644 --- a/web/src/lib/components/create/DesktopPoolForm.svelte +++ b/web/src/lib/components/create/DesktopPoolForm.svelte @@ -5,6 +5,7 @@ import { POOL_NAME_HINT, poolRefusals } from '#lib/desktopspec.js'; import { plural } from '#lib/format.js'; import { desktopGitGate } from '#lib/gates.js'; + import { CHECKING } from '#lib/state/caps.svelte.js'; import { action } from '#lib/resource.svelte.js'; import { rowList } from '#lib/rowlist.svelte.js'; import { desktops } from '#lib/state/desktops.svelte.js'; @@ -69,16 +70,23 @@ }); const refusals = $derived(poolRefusals(request)); const refused = (path: string) => refusals.find((r) => r.path === path)?.why ?? ''; + // A name that runs, or that git declares and the cluster does not run yet. const taken = $derived( - !!desktops.value?.pools.some((p) => p.namespace === namespace && p.name === name), + !!desktops.value && + [ + ...desktops.value.pools, + ...desktops.value.inGit.filter((r) => r.resource === 'vdipools'), + ].some((p) => p.namespace === namespace && p.name === name), ); const gate = $derived(desktopGitGate({ resource: 'desktoppool', namespace }, 'create')); const missing = $derived.by(() => { const m: string[] = []; + // The place, and what holds it back, come first: no other field fixes them. + const held = !namespace ? 'Pick a project and namespace' : gate.ok ? '' : gate.why; + if (held && held !== CHECKING) m.push(held); if (!name) m.push('Name the pool'); else if (taken) m.push(`${name} is taken in ${namespace}`); - if (!namespace) m.push('Pick a project and namespace'); - else if (!gate.ok) m.push(gate.why); + if (held === CHECKING) m.push(held); m.push(...refusals.filter((r) => name || r.path !== 'metadata.name').map((r) => r.why)); return m; }); diff --git a/web/src/lib/desktops.test.ts b/web/src/lib/desktops.test.ts index d44face00..8681c747f 100644 --- a/web/src/lib/desktops.test.ts +++ b/web/src/lib/desktops.test.ts @@ -1,11 +1,13 @@ import { describe, expect, it } from 'vitest'; -import type { Desktop, DesktopClaim, DesktopPool, Desktops, Project } from './api'; +import type { Desktop, DesktopClaim, DesktopInGit, DesktopPool, Desktops, Project } from './api'; import { actingClaim, byProject, count, desktopState, duration, + inGitNoun, + inGitStep, joinClaims, person, poolState, @@ -194,6 +196,7 @@ describe('unlisted kinds', () => { pools: [pool(), pool({ namespace: 'batch-prod', name: 'render' })], desktops: [desktop('ops', { namespace: 'db-prod' })], claims: [], + inGit: [], unlisted: [ { namespace: 'batch-prod', resource: 'vdiinstances' }, { namespace: 'qa', resource: 'vdiclaims' }, @@ -215,6 +218,46 @@ describe('unlisted kinds', () => { }); }); +describe('in git, not running', () => { + const de: DesktopInGit = { + resource: 'vdiinstances', + namespace: 'qa', + name: 'de', + sourceFile: 'qa/desktops/de.yaml', + sync: 'OutOfSync', + health: 'Missing', + syncError: 'vdiinstances.vdi.desku.be is forbidden', + }; + + it('keeps a namespace that holds only what git declares, and counts none of it', () => { + const data: Desktops = { + synced: true, + classes: [], + pools: [], + desktops: [], + claims: [], + inGit: [de], + unlisted: [], + }; + const projects: Project[] = [{ name: 'team', namespaces: [{ namespace: 'qa', vms: [] }] }]; + const [team] = byProject(data, projects, rights(data, new Set(['qa']))); + expect(team.namespaces).toEqual([ + expect.objectContaining({ namespace: 'qa', inGit: [de], count: 0 }), + ]); + }); + + it('waits on desktops turned on, then on a resync of what Argo CD gave up on', () => { + expect(inGitStep({ ...de, syncStalled: true }, true)).toEqual({ step: 'off' }); + expect(inGitStep({ ...de, syncStalled: true }, false)).toEqual({ step: 'resync' }); + expect(inGitStep(de, false)).toEqual({ step: 'failed', error: de.syncError }); + expect(inGitStep({ ...de, sync: undefined, syncError: undefined }, false)).toEqual({ + step: 'pending', + }); + expect(inGitNoun(de)).toBe('desktop'); + expect(inGitNoun({ resource: 'vdipools' })).toBe('pool'); + }); +}); + describe('power of a desktop made one by one', () => { const carols = claim('carol', { user: 'carol', desktop: 'carol-dev', phase: 'Bound' }); const carol = (over: Partial = {}) => diff --git a/web/src/lib/desktops.ts b/web/src/lib/desktops.ts index aa0f75882..645ce1b81 100644 --- a/web/src/lib/desktops.ts +++ b/web/src/lib/desktops.ts @@ -6,6 +6,7 @@ import type { DesktopClaim, DesktopClass, DesktopCondition, + DesktopInGit, DesktopKind, DesktopPool, DesktopPoolCounts, @@ -253,11 +254,33 @@ export function unlistedLines( ); } +// A pool or a desktop git declares and the cluster does not run. +export const IN_GIT = 'In git, not running'; + +export const inGitNoun = (r: Pick) => + r.resource === 'vdipools' ? 'pool' : 'desktop'; + +// What applies a pool or a desktop git declares and the cluster does not +// run, in the order it waits on them: desktops turned on there (off: what +// the caller is told of it), Argo CD asked to try the revision it gave up on, +// the apply Argo CD refused, else Argo CD itself. +export type InGitStep = + { step: 'off' } | { step: 'resync' } | { step: 'failed'; error: string } | { step: 'pending' }; + +export function inGitStep(r: DesktopInGit, off: boolean): InGitStep { + if (off) return { step: 'off' }; + if (r.syncStalled) return { step: 'resync' }; + if (r.syncError) return { step: 'failed', error: r.syncError }; + return { step: 'pending' }; +} + export interface DesktopsNamespace { namespace: string; pools: DesktopPool[]; // Made one by one: a pool-made desktop is a row of its pool, never its own. desktops: Desktop[]; + // What git declares there and the cluster does not run. + inGit: DesktopInGit[]; unlisted: string[]; // null where the caller may not list desktops: a 0 there would read as none. count: number | null; @@ -272,8 +295,8 @@ export interface DesktopsProject { } // byProject groups what the caller may see under the projects, in their order, -// keeping only the namespaces that hold a pool or a desktop: a kind the caller -// may not list says nothing of what a namespace holds. +// keeping only the namespaces that hold a pool or a desktop, running or in +// git: a kind the caller may not list says nothing of what a namespace holds. export function byProject( d: Desktops, projects: readonly Project[], @@ -290,6 +313,7 @@ export function byProject( }; const poolsIn = pick(d.pools); const desktopsIn = pick(d.desktops); + const inGitIn = pick(d.inGit); const unlistedIn = pick(d.unlisted); const out: DesktopsProject[] = []; for (const p of projects) { @@ -298,11 +322,13 @@ export function byProject( const pools = poolsIn(namespace); // Besides those made one by one, the desktops of pools not shown. const loose = desktopsIn(namespace); - if (!pools.length && !loose.length) continue; + const inGit = inGitIn(namespace); + if (!pools.length && !loose.length && !inGit.length) continue; namespaces.push({ namespace, pools, desktops: loose.filter((x) => !x.pool), + inGit, unlisted: unlistedIn(namespace).map((u) => u.resource), count: may.lists(namespace, 'vdiinstances') ? pools.reduce((n, x) => n + x.desktops.length, 0) + loose.length diff --git a/web/src/lib/gates.test.ts b/web/src/lib/gates.test.ts index ffe5a2898..dd4bd65b1 100644 --- a/web/src/lib/gates.test.ts +++ b/web/src/lib/gates.test.ts @@ -11,6 +11,7 @@ import { clusterGate, DESKTOPS_HELD, desktopCreateGate, + desktopsOffWhy, desktopGate, desktopGitGate, desktopsGate, @@ -91,6 +92,16 @@ describe('desktopGitGate', () => { expect(desktopGitGate(pool)).toEqual({ ok: false, why: DESKTOPS_HELD }); expect(desktopGitGate(pool, 'update')).toEqual({ ok: false, why: DESKTOPS_HELD }); }); + + it('says desktops are off where they are, and who turns them on', async () => { + await answer({ + namespace: { namespace: 'web', desktopPool: own(false), desktopsOff: true }, + }); + const why = + "Desktops are not on in web: a platform admin turns them on from the project's Configure tab."; + expect(desktopsOffWhy('web')).toBe(why); + expect(desktopGitGate(pool, 'create')).toEqual({ ok: false, why }); + }); }); describe('desktopCreateGate', () => { @@ -104,6 +115,7 @@ describe('desktopCreateGate', () => { ok: true, why: '', namespace: 'db', + off: [], }); expect(desktopCreateGate('desktop', ['web', 'db']).why).toBe( 'You may not create desktops in web.', @@ -121,6 +133,21 @@ describe('desktopCreateGate', () => { expect(desktopCreateGate('desktoppool', ['web', 'db']).why).toBe(DESKTOPS_HELD); expect(desktopCreateGate('desktoppool', []).ok).toBe(false); }); + + it('names every namespace desktops are off in, where they are off in each', async () => { + api.api.capabilities.mockImplementation(async (ns: string) => ({ + namespace: { namespace: ns, desktopPool: own(false), desktopsOff: true }, + })); + caps.invalidate(); + desktopCreateGate('desktoppool', ['web', 'db']); + await flush(); + expect(desktopCreateGate('desktoppool', ['web', 'db'])).toEqual({ + ok: false, + why: "Desktops are not on in web, db: a platform admin turns them on from the project's Configure tab.", + namespace: '', + off: ['web', 'db'], + }); + }); }); describe('repoReadGate', () => { diff --git a/web/src/lib/gates.ts b/web/src/lib/gates.ts index c1135b90f..0cae380f3 100644 --- a/web/src/lib/gates.ts +++ b/web/src/lib/gates.ts @@ -171,36 +171,50 @@ export function objectAdoptGate(ref: { resource: string; namespace: string }): G export const DESKTOPS_HELD = "Argo CD does not apply desktops as their project's own account yet: a cluster admin turns sync impersonation on and installs the operator guard."; +// No pool or desktop goes into git where desktops are not on: the project's +// account could not apply it. Told where the server tells it, with who acts. +export const DESKTOPS_OFF_FIX = "a platform admin turns them on from the project's Configure tab."; +export const desktopsOffWhy = (namespace: string) => + `Desktops are not on in ${namespace}: ${DESKTOPS_OFF_FIX}`; + // A pool's or a desktop's verdict on one of the object routes' writes, adopt -// by default, said apart where only the sync account's setup holds it back. +// by default, said apart where only the sync account's setup, or desktops +// being off there, holds it back. export function desktopGitGate( ref: { resource: string; namespace: string }, verb: Verb | 'adopt' = 'adopt', ): Gate { const g = verb === 'adopt' ? objectAdoptGate(ref) : objectGate(ref, verb); if (g.ok || ref.namespace === CLUSTER_NS) return g; - return caps.ns(ref.namespace)?.desktopsHeld ? { ok: false, why: DESKTOPS_HELD } : g; + const c = caps.ns(ref.namespace); + if (c?.desktopsHeld) return { ok: false, why: DESKTOPS_HELD }; + return c?.desktopsOff ? { ok: false, why: desktopsOffWhy(ref.namespace) } : g; } // Where among namespaces the caller may make a new pool or desktop made one // by one: the first that opens it, else why none does. Still checking any -// says nothing yet; held anywhere is said apart, as adopting says it. +// says nothing yet; held anywhere is said apart, as adopting says it, and so +// is desktops being off in every one. export function desktopCreateGate( resource: 'desktoppool' | 'desktop', namespaces: Iterable, -): Gate & { namespace: string } { +): Gate & { namespace: string; off: string[] } { const whys: string[] = []; + const off: string[] = []; for (const namespace of namespaces) { const g = desktopGitGate({ resource, namespace }, 'create'); - if (g.ok) return { ...g, namespace }; + if (g.ok) return { ...g, namespace, off: [] }; whys.push(g.why); + if (g.why === desktopsOffWhy(namespace)) off.push(namespace); } const why = whys.includes(CHECKING) ? CHECKING : whys.includes(DESKTOPS_HELD) ? DESKTOPS_HELD - : (whys[0] ?? ''); - return { ok: false, why, namespace: '' }; + : off.length === whys.length && off.length + ? `Desktops are not on in ${off.join(', ')}: ${DESKTOPS_OFF_FIX}` + : (whys[0] ?? ''); + return { ok: false, why, namespace: '', off }; } // The platform tier and the cluster-wide actions. diff --git a/web/src/lib/model.gen.ts b/web/src/lib/model.gen.ts index de046010f..63b88ad9d 100644 --- a/web/src/lib/model.gen.ts +++ b/web/src/lib/model.gen.ts @@ -266,6 +266,12 @@ export interface NamespaceCaps { desktopPool: ObjectCaps; desktop: ObjectCaps; desktopsHeld?: boolean; + /** + * DesktopsOff: desktops are not on here, so both stay false. Told to a + * caller who may list rolebindings here, as ProjectCaps.DesktopsOn is, + * or who could author one here but for it, as staging one tells them. + */ + desktopsOff?: boolean; project: ProjectCaps; } /** @@ -456,6 +462,11 @@ export interface Desktops { */ desktops: Desktop[]; claims: DesktopClaim[]; + /** + * InGit are the pools and desktops made one by one that a repo declares + * and the cluster does not run, where the caller may list their kind. + */ + inGit: DesktopInGit[]; /** * Unlisted are, for a caller who may list some kind, the kinds it may * not list in each namespace of the request, and the classes when it may @@ -465,6 +476,26 @@ export interface Desktops { */ unlisted: DesktopKind[]; } +/** + * DesktopInGit is a pool, or a desktop made one by one, its project's repo + * declares that does not run: Argo CD has not applied it yet, or could not. + * Sync, Health and SyncError are its own Argo CD drift. + */ +export interface DesktopInGit { + resource: string; // vdipools | vdiinstances + namespace: string; + name: string; + sourceFile: string; + sync?: SyncStatus; + health?: string; + syncError?: string; + /** + * SyncStalled: Argo CD's last sync failed on the revision declaring it, + * which automated sync never tries again: a new merge, or a resync of + * it, applies it. + */ + syncStalled?: boolean; +} /** * DesktopKind is one kind in one namespace, "" for the classes. */ diff --git a/web/src/lib/state/desktops.test.ts b/web/src/lib/state/desktops.test.ts index ecdffd213..ff9b2c048 100644 --- a/web/src/lib/state/desktops.test.ts +++ b/web/src/lib/state/desktops.test.ts @@ -22,6 +22,7 @@ const answer: Desktops = { desktops: [], claims: [], unlisted: [], + inGit: [], }; describe('desktops.covered', () => { diff --git a/web/src/lib/tree/DesktopsTree.svelte b/web/src/lib/tree/DesktopsTree.svelte index 5c9129896..bfef6f619 100644 --- a/web/src/lib/tree/DesktopsTree.svelte +++ b/web/src/lib/tree/DesktopsTree.svelte @@ -6,6 +6,7 @@ byProject, count, desktopState, + IN_GIT, poolState, stateLine, type DesktopsNamespace, @@ -22,9 +23,9 @@ import RailMore from './RailMore.svelte'; // The Desktops tree: All desktops, Desktop classes, then projects, - // namespaces, and in each its pools and the desktops made one by one. A - // pool's desktops are rows of its page, never rows here. Highlights derive - // from the URL. + // namespaces, and in each its pools and the desktops made one by one, then + // those git declares that do not run. A pool's desktops are rows of its + // page, never rows here. Highlights derive from the URL. const scope = $derived(scopeFromPath(page.url.pathname)); const data = $derived(desktops.value?.synced ? desktops.value : null); const may = $derived(data ? desktops.may : null); @@ -41,7 +42,13 @@ let query = $state(''); const nsShown = (ns: DesktopsNamespace) => - matches(query, ns.namespace, ...ns.pools.map((p) => p.name), ...ns.desktops.map((d) => d.name)); + matches( + query, + ns.namespace, + ...ns.pools.map((p) => p.name), + ...ns.desktops.map((d) => d.name), + ...ns.inGit.map((r) => r.name), + ); const shown = $derived( groups .map((g) => @@ -221,6 +228,24 @@ {#if leaves.more > 0} {fmt(leaves.more)} more desktops {/if} + {#each ns.inGit as r (`${r.resource}/${r.name}`)} + {@const kind = r.resource === 'vdipools' ? 'pool' : 'desktop'} + + {#snippet icon()}{/snippet} + {r.name} + + {/each} {#each ns.unlisted.filter((r) => KIND_LINE[r]) as r (r)}
{KIND_LINE[r]}
{/each} diff --git a/web/src/lib/workspace/desktops/DesktopPage.svelte b/web/src/lib/workspace/desktops/DesktopPage.svelte index 752711590..78996093b 100644 --- a/web/src/lib/workspace/desktops/DesktopPage.svelte +++ b/web/src/lib/workspace/desktops/DesktopPage.svelte @@ -2,6 +2,7 @@ import { desktopRef, desktopState, + IN_GIT, joinClaims, sessionLabel, stateLine, @@ -18,10 +19,12 @@ import DesktopHistory from './DesktopHistory.svelte'; import DesktopPower from './DesktopPower.svelte'; import DesktopsFrame from './DesktopsFrame.svelte'; + import InGitBody from './InGitBody.svelte'; import UnlistedNote from './UnlistedNote.svelte'; // A desktop made one by one: who it is for, what it runs, how it stands, - // its power and why, what git declares of it, and its acts. + // its power and why, what git declares of it, and its acts. One git + // declares that does not run says what it waits on. let { scope }: { scope: Extract } = $props(); const data = $derived(desktops.value?.synced ? desktops.value : null); @@ -39,6 +42,12 @@ const poolShown = $derived( !!ofPool && !!data?.pools.some((p) => p.namespace === scope.namespace && p.name === ofPool), ); + // Git declares it and the cluster does not run it. + const declared = $derived( + desktop || ofPool + ? undefined + : data?.inGit.find((r) => r.resource === 'vdiinstances' && mine(r)), + ); const row = $derived(desktop && data ? joinClaims([desktop], data.claims)[0] : undefined); const st = $derived(desktop && desktopState(desktop)); const cls = $derived(desktop?.class && data?.classes.find((c) => c.name === desktop.class)); @@ -51,6 +60,7 @@ ); const context = $derived.by(() => { + if (declared) return `Desktop in ${declared.namespace}`; if (!desktop) return ''; const of = desktop.owner ? `Desktop of ${desktop.owner}` : 'Desktop'; return desktop.class ? `${of}, class ${desktop.class}` : of; @@ -66,12 +76,14 @@ desktops.title(p), 'desktops')} title={scope.desktop} - status={st && { tone: st.tone, text: st.label }} + status={st ? { tone: st.tone, text: st.label } : declared && { tone: 'warn', text: IN_GIT }} {context} actions={row ? acts : undefined} > {#snippet children(d)} - {#if ofPool} + {#if declared} + + {:else if ofPool}

{scope.desktop} is a desktop of pool {#if poolShown} diff --git a/web/src/lib/workspace/desktops/DesktopsRoot.svelte b/web/src/lib/workspace/desktops/DesktopsRoot.svelte index af582d971..0034d1fbb 100644 --- a/web/src/lib/workspace/desktops/DesktopsRoot.svelte +++ b/web/src/lib/workspace/desktops/DesktopsRoot.svelte @@ -1,6 +1,6 @@ @@ -116,17 +125,34 @@

{:else} - {#if newWhy}

{newWhy}

{/if} + {#if newWhy} +

+ {newWhy} + {#if turnOn} + + Turn them on + + {/if} +

+ {/if} - {#if pools.length === 0 && loose.length === 0 && lines.length === 0} + {#if pools.length === 0 && loose.length === 0 && inGit.length === 0 && lines.length === 0}

No desktop here yet.

- A pool or a desktop declared in the project's repo shows here once applied. + A pool or a desktop declared in the project's repo shows here.

{/if} + {#if inGit.length} + + + + {/if} {#if pools.length} diff --git a/web/src/lib/workspace/desktops/InGitBody.svelte b/web/src/lib/workspace/desktops/InGitBody.svelte new file mode 100644 index 000000000..b51821752 --- /dev/null +++ b/web/src/lib/workspace/desktops/InGitBody.svelte @@ -0,0 +1,29 @@ + + + + Git declares this {inGitNoun(row)}, and the cluster does not run it. + + + +
+ +
+ diff --git a/web/src/lib/workspace/desktops/InGitNext.svelte b/web/src/lib/workspace/desktops/InGitNext.svelte new file mode 100644 index 000000000..099f988b5 --- /dev/null +++ b/web/src/lib/workspace/desktops/InGitNext.svelte @@ -0,0 +1,87 @@ + + +{#if step.step === 'off' && compact} + + Desktops are not on here. + {#if turnOn}Turn them on{/if} + +{:else if step.step === 'off'} + + Desktops are not on in {row.namespace}: + {#if turnOn} + turn them on from the project's Configure tab. + {:else} + {DESKTOPS_OFF_FIX} + {/if} + +{:else if step.step === 'resync'} + + + {compact + ? 'Argo CD gave up on it.' + : `Argo CD tried the revision declaring this ${noun}, failed, and does not try it again by itself: a resync applies it now.`} + + {#if resync.ok} + + {:else if !compact} + {resync.why} A project admin can resync it. + {/if} + +{:else if step.step === 'failed'} + {#if compact} + Argo CD could not apply it. + {:else} +
+ Argo CD could not apply this {noun}, and tries again on its own: + +
+ {/if} +{:else} + Argo CD has not applied it yet. +{/if} diff --git a/web/src/lib/workspace/desktops/InGitTable.svelte b/web/src/lib/workspace/desktops/InGitTable.svelte new file mode 100644 index 000000000..f92966e66 --- /dev/null +++ b/web/src/lib/workspace/desktops/InGitTable.svelte @@ -0,0 +1,67 @@ + + +
+ + + + + {#if namespace}{/if} + + + + + + + {#each rows as r (`${r.namespace}/${r.resource}/${r.name}`)} + {@const project = desktops.owners.get(r.namespace)} + {@const pool = r.resource === 'vdipools'} + + + {#if namespace}{/if} + + + + + {/each} + +
NameNamespaceKindStatusWaits on
+ {#if project} + + {r.name} + + {:else}{r.name}{/if} + {r.namespace}{pool ? 'Pool' : 'Desktop'} + + + {#if r.sync}{/if} + + + {#if project}{/if} +
+
diff --git a/web/src/lib/workspace/desktops/PoolPage.svelte b/web/src/lib/workspace/desktops/PoolPage.svelte index 52278c090..9d9a213f5 100644 --- a/web/src/lib/workspace/desktops/PoolPage.svelte +++ b/web/src/lib/workspace/desktops/PoolPage.svelte @@ -3,6 +3,7 @@ assignment, count, duration, + IN_GIT, joinClaims, poolRef, poolState, @@ -21,12 +22,13 @@ import DesktopHistory from './DesktopHistory.svelte'; import DesktopTable from './DesktopTable.svelte'; import DesktopsFrame from './DesktopsFrame.svelte'; + import InGitBody from './InGitBody.svelte'; import RepoLink from './RepoLink.svelte'; import UnlistedNote from './UnlistedNote.svelte'; // One pool: how its seats stand, its rules, what git declares of it, // whether DeskuBe can make its desktops, and its desktops with the people - // holding them. + // holding them. One git declares that does not run says what it waits on. let { scope }: { scope: Extract } = $props(); const data = $derived(desktops.value?.synced ? desktops.value : null); @@ -34,6 +36,15 @@ const pool = $derived( data?.pools.find((p) => p.namespace === scope.namespace && p.name === scope.pool), ); + // Git declares it and the cluster does not run it. + const declared = $derived( + pool + ? undefined + : data?.inGit.find( + (r) => + r.resource === 'vdipools' && r.namespace === scope.namespace && r.name === scope.pool, + ), + ); const st = $derived(pool && poolState(pool)); const ready = $derived(pool && readyOf(pool.conditions)); const personal = $derived(!!pool && assignment(pool) === 'Personal'); @@ -69,13 +80,17 @@ desktops.title(p), 'desktops')} title={scope.pool} - status={st && { tone: st.tone, text: st.label }} + status={st ? { tone: st.tone, text: st.label } : declared && { tone: 'warn', text: IN_GIT }} context={pool ? `${assignment(pool)} pool of class ${pool.class} in ${pool.namespace}${pool.closed ? ', closed' : ''}` - : ''} + : declared + ? `Pool in ${declared.namespace}` + : ''} > {#snippet children(d)} - {#if !pool} + {#if declared} + + {:else if !pool} {@const lines = unlistedLines(d.unlisted, here, true)} {#if may?.lists(scope.namespace, 'vdipools')}

From e770c1a838f755addaff97798fe832e02673f49b Mon Sep 17 00:00:00 2001 From: Thibaut Lapierre Date: Mon, 30 Nov 2026 10:05:34 +0100 Subject: [PATCH 2/9] desktops: turned on from the form that needs them; a failure named by what fails Assisted by LLM --- docs/personas.md | 3 +- web/e2e/fixture/scenarios.mjs | 80 ++++++++++++++ web/e2e/fixture/server.mjs | 2 + web/e2e/ui/desktopsingit.spec.ts | 101 ++++++++++++++++-- .../components/create/DesktopOneForm.svelte | 14 ++- .../components/create/DesktopPoolForm.svelte | 14 ++- .../create/DesktopsOffNotice.svelte | 87 +++++++++++++++ .../lib/components/create/PlacePicker.svelte | 19 +++- web/src/lib/desktops.test.ts | 67 +++++++++++- web/src/lib/desktops.ts | 29 ++++- web/src/lib/gates.test.ts | 4 +- web/src/lib/gates.ts | 16 ++- web/src/lib/state/caps.svelte.ts | 7 ++ .../lib/workspace/desktops/DesktopPage.svelte | 3 +- .../lib/workspace/desktops/InGitNext.svelte | 4 +- 15 files changed, 423 insertions(+), 27 deletions(-) create mode 100644 web/src/lib/components/create/DesktopsOffNotice.svelte diff --git a/docs/personas.md b/docs/personas.md index 580527c53..0975e6bdb 100644 --- a/docs/personas.md +++ b/docs/personas.md @@ -99,7 +99,8 @@ It stages one RoleBinding in the platform repo, beside the namespace's admin gra | --- | --- | --- | | `-desktops` | `dotvirt-tenant-desktops` | the admin grant's subjects, the project's sync account among them | -Turn desktops on before any pool or desktop is staged in the namespace: until git holds that grant, the project's account may not apply one, so dotvirt refuses to stage it, and its form says so first. +Turn desktops on before any pool or desktop is staged in the namespace: until git holds that grant, the project's account may not apply one, so dotvirt refuses to stage it. +A new pool's or desktop's form does not place one there: where its namespace is picked, it says desktops are off, with the one click that stages turning them on for whoever may, else who can, then whether that is staged or proposed, linking the PR. That is told to whoever may list the namespace's role bindings, or could make a pool or a desktop there. Classes need no such step: the platform repo's account writes them cluster-wide. diff --git a/web/e2e/fixture/scenarios.mjs b/web/e2e/fixture/scenarios.mjs index da2531a2b..bd706f754 100644 --- a/web/e2e/fixture/scenarios.mjs +++ b/web/e2e/fixture/scenarios.mjs @@ -2644,6 +2644,48 @@ const desktopsoff = { }, desktops: { ...deskubeGit, inGit: inGit() }, }; +// The same, once the caller proposed turning desktops on in web-prod: its +// own platform PR #79 carries the grant. +const desktopsoffproposed = { + ...desktopsoff, + name: 'desktopsoffproposed', + inventory: { + ...desktopsoff.inventory, + proposals: [ + ...(desktopsoff.inventory.proposals ?? []), + { + project: 'platform', + prNumber: 79, + prURL: 'https://forge.example/dotvirt/platform/pulls/79', + title: 'Turn desktops on in web-prod', + branch: 'dotvirt/proposed/admin/platform-7c7c', + by: 'admin', + mine: true, + }, + ], + }, + proposalItems: { + 'platform#79': [ + { + kind: 'create', + resource: 'rolebinding', + namespace: 'web-prod', + name: 'web-prod-desktops', + changes: [], + }, + ], + }, + capabilities: { ...desktopsoff.capabilities, cluster: { platformRead: true } }, +}; +// A project admin where desktops are off in web-prod: told so, as it may +// list its role bindings, and who turns them on. +const desktopsoffadmin = { + ...desktopsoff, + name: 'desktopsoffadmin', + capabilities: { + 'web-prod': { ...desktopsoff.capabilities['web-prod'], project: {} }, + }, +}; // Desktops on in web-prod since, and Argo CD gave up on de before: a resync // applies it. const desktopsstalled = { @@ -2651,6 +2693,41 @@ const desktopsstalled = { name: 'desktopsstalled', desktops: { ...deskubeGit, inGit: inGit() }, }; +// de once it runs, as hetznet reported it: its pod crash loops, while +// UnpairPending and UpdatePending read False because all is well. +const desktopscrash = { + ...desktopsgit, + name: 'desktopscrash', + desktops: { + ...deskubeGit, + desktops: [ + ...deskubeGit.desktops, + desk('web-prod', 'de', { + class: undefined, + image: 'quay.io/example/desktop:3', + running: true, + phase: 'Failed', + session: undefined, + ...gitOf('web-prod/desktops/de.yaml'), + conditions: [ + { type: 'UnpairPending', status: 'False', reason: 'NoFormerClients' }, + { type: 'SeccompFiltered', status: 'True', reason: 'RuntimeDefault' }, + { type: 'UpdatePending', status: 'False', reason: 'UpToDate' }, + { + type: 'PodReady', + status: 'False', + reason: 'CrashLoopBackOff', + message: + 'back-off 5m0s restarting failed container=desktop pod=de-74d5989bf5-69vfd_default(75429a32-4dd2-49d6-b716-1659023f724b)', + }, + { type: 'NetworkReady', status: 'True', reason: 'Address' }, + { type: 'StreamingReady', status: 'False', reason: 'PodNotReady' }, + { type: 'Ready', status: 'False', reason: 'Aggregate' }, + ], + }), + ], + }, +}; // The same, to a project viewer, who may resync nothing. const desktopsstalledviewer = { ...desktopsgitviewer, @@ -2875,6 +2952,9 @@ export const scenarios = { desktopsgitheld, desktopsunbound, desktopsoff, + desktopsoffproposed, + desktopsoffadmin, + desktopscrash, desktopsstalled, desktopsstalledviewer, desktopspower, diff --git a/web/e2e/fixture/server.mjs b/web/e2e/fixture/server.mjs index 01e4873a9..a51eaf866 100644 --- a/web/e2e/fixture/server.mjs +++ b/web/e2e/fixture/server.mjs @@ -1177,6 +1177,8 @@ async function handleAPI(req, res, url) { ); const denied = s.proposalDenied?.[`${m[1]}#${m[2]}`]; if (denied) return sendText(res, 403, denied); + const scenarioItems = s.proposalItems?.[`${m[1]}#${m[2]}`]; + if (scenarioItems) return sendJSON(res, 200, { proposal: pr, items: scenarioItems }); const items = { 41: { kind: 'edit', diff --git a/web/e2e/ui/desktopsingit.spec.ts b/web/e2e/ui/desktopsingit.spec.ts index 6404eed2d..bc754d6f0 100644 --- a/web/e2e/ui/desktopsingit.spec.ts +++ b/web/e2e/ui/desktopsingit.spec.ts @@ -5,14 +5,16 @@ import type { Page } from '@playwright/test'; // a page of its own, marked In git, not running, with what Argo CD says of it // and its next step: desktops turned on where they are off, a resync of the // revision Argo CD gave up on, or Argo CD's own refusal. No pool or desktop -// is made where desktops are off: the form says so before it sends. +// is made where desktops are off: the form says so where its place is picked, +// with the one click that turns them on, else who can. const OFF = - "Desktops are not on in web-prod: a platform admin turns them on from the project's Configure tab."; + "Desktops are off in web-prod: a platform admin turns them on from the project's Configure tab."; +const ELSEWHERE = 'Pick a namespace where desktops are on'; const main = (page: Page) => page.locator('main'); const inGit = (page: Page) => main(page).getByRole('table', { name: 'In git, not running' }); -test('where desktops are off, nothing new is offered, and the form says who turns them on', async ({ +test('where desktops are off, nothing new is offered, and the form stages nothing there', async ({ page, }) => { await setScenario(page, 'desktopsoff'); @@ -25,14 +27,101 @@ test('where desktops are off, nothing new is offered, and the form says who turn await page.getByRole('button', { name: 'New', exact: true }).click(); const sheet = page.getByRole('dialog'); await expect(sheet.getByRole('heading', { name: 'New desktop pool' })).toBeVisible(); - await expect(sheet.getByRole('status')).toHaveText(OFF); + await expect(sheet.getByRole('status')).toHaveText(ELSEWHERE); await expect(sheet.getByRole('button', { name: 'Stage pool' })).toBeDisabled(); await sheet.locator('input[name="desktop-kind"][value="desktop"]').check(); await sheet.getByLabel('Name', { exact: true }).fill('dana-dev'); - await expect(sheet.getByRole('status')).toHaveText(OFF); + await expect(sheet.getByRole('status')).toHaveText(ELSEWHERE); await expect(sheet.getByRole('button', { name: 'Stage desktop' })).toBeDisabled(); }); +test('the form turns desktops on in one click, then says where that stands', async ({ page }) => { + await setScenario(page, 'desktopsoff'); + await login(page); + await page.goto('/desktops/team-web/web-prod'); + await page.getByRole('button', { name: 'New', exact: true }).click(); + const sheet = page.getByRole('dialog'); + await expect(sheet.getByText('Desktops are off in web-prod.', { exact: true })).toBeVisible(); + const staged = page.waitForRequest( + (r) => + r.method() === 'POST' && + new URL(r.url()).pathname === '/api/projects/team-web/namespaces/web-prod/desktops', + ); + await sheet.getByRole('button', { name: 'Turn desktops on' }).click(); + await staged; + await expect( + sheet.getByText( + 'Desktops are off in web-prod: turning them on is staged in the platform draft.', + ), + ).toBeVisible(); + await expect(sheet.getByRole('link', { name: 'Review and propose it' })).toHaveAttribute( + 'href', + '/changes?project=platform&item=rolebinding%3Aweb-prod%2Fweb-prod-desktops', + ); + await expect(sheet.getByRole('button', { name: 'Stage pool' })).toBeDisabled(); +}); + +test('once proposed, the form links the PR that turns desktops on', async ({ page }) => { + await setScenario(page, 'desktopsoffproposed'); + await login(page); + await page.goto('/desktops/team-web/web-prod'); + await page.getByRole('button', { name: 'New', exact: true }).click(); + const sheet = page.getByRole('dialog'); + await expect(sheet.getByText(/turning them on is proposed in PR #79/)).toBeVisible(); + await expect(sheet.getByRole('link', { name: 'PR #79' })).toHaveAttribute( + 'href', + 'https://forge.example/dotvirt/platform/pulls/79', + ); + await expect(sheet.getByRole('button', { name: 'Turn desktops on' })).toHaveCount(0); +}); + +test('who may not turn desktops on is told who can, and a place they are off in is not chosen', async ({ + page, +}) => { + await setScenario(page, 'desktopsoffadmin'); + await login(page); + await page.goto('/desktops/team-web/web-prod'); + await expect(main(page).getByText(OFF, { exact: false })).toBeVisible(); + // Moving within the app keeps what it read of web-prod. + await page + .locator('aside') + .first() + .getByRole('link', { name: /^db-prod/ }) + .click(); + await expect(page).toHaveURL(/\/desktops\/team-db\/db-prod$/); + await main(page).getByRole('button', { name: 'New pool' }).click(); + const sheet = page.getByRole('dialog'); + const place = sheet.getByLabel('Project and namespace'); + await expect(place).toContainText('db-prod'); + await place.click(); + const webProd = sheet.getByRole('option', { name: /web-prod/ }); + await expect(webProd).toHaveAttribute('aria-disabled', 'true'); + await expect(webProd).toContainText('desktops off'); + await webProd.dispatchEvent('pointerdown'); + await expect(place).toContainText('db-prod'); + + await page.goto('/desktops/team-web/web-prod'); + await page.getByRole('button', { name: 'New', exact: true }).click(); + await expect(page.getByRole('dialog').getByText(OFF, { exact: true })).toBeVisible(); + await expect( + page.getByRole('dialog').getByRole('button', { name: 'Turn desktops on' }), + ).toHaveCount(0); +}); + +test('a failed desktop says its failing part, never a condition whose False is well', async ({ + page, +}) => { + await setScenario(page, 'desktopscrash'); + await login(page); + await page.goto('/desktops/team-web/web-prod/desktop/de'); + await expect( + main(page).getByText( + 'DeskuBe reports: back-off 5m0s restarting failed container=desktop pod=de-74d5989bf5-69vfd_default(75429a32-4dd2-49d6-b716-1659023f724b)', + ), + ).toBeVisible(); + await expect(main(page).getByText(/DeskuBe reports: NoFormerClients/)).toHaveCount(0); +}); + test('a desktop Argo CD may not create here is a row and a page that lead to turning desktops on', async ({ page, }) => { @@ -42,7 +131,7 @@ test('a desktop Argo CD may not create here is a row and a page that lead to tur const rows = inGit(page); await expect(rows.locator('tbody tr')).toHaveCount(2); await expect(rows.getByRole('row', { name: /de Desktop/ })).toContainText( - 'Desktops are not on here.', + 'Desktops are off here.', ); await rows.getByRole('link', { name: 'de', exact: true }).click(); diff --git a/web/src/lib/components/create/DesktopOneForm.svelte b/web/src/lib/components/create/DesktopOneForm.svelte index 81958a699..b7f4c6e61 100644 --- a/web/src/lib/components/create/DesktopOneForm.svelte +++ b/web/src/lib/components/create/DesktopOneForm.svelte @@ -3,7 +3,7 @@ import { api, type DesktopCreate } from '#lib/api.js'; import { allDesktops } from '#lib/desktops.js'; import { desktopRefusals } from '#lib/desktopspec.js'; - import { desktopGitGate } from '#lib/gates.js'; + import { desktopGitGate, desktopPlaceHeld, desktopsOffPlace } from '#lib/gates.js'; import { CHECKING } from '#lib/state/caps.svelte.js'; import { action } from '#lib/resource.svelte.js'; import { desktops } from '#lib/state/desktops.svelte.js'; @@ -12,6 +12,7 @@ import { NAME_HINT, validName } from '#lib/validate.js'; import Consequence from '../Consequence.svelte'; import DesktopClassField from './DesktopClassField.svelte'; + import DesktopsOffNotice from './DesktopsOffNotice.svelte'; import PlacePicker from './PlacePicker.svelte'; import SheetBody from './SheetBody.svelte'; import SheetFooter from './SheetFooter.svelte'; @@ -65,7 +66,7 @@ const missing = $derived.by(() => { const m: string[] = []; // The place, and what holds it back, come first: no other field fixes them. - const held = !namespace ? 'Pick a project and namespace' : gate.ok ? '' : gate.why; + const held = desktopPlaceHeld(namespace, gate); if (held && held !== CHECKING) m.push(held); if (!name) m.push('Name the desktop'); else if (!validName(name)) m.push('The name needs lowercase letters, digits and -'); @@ -108,9 +109,16 @@

- +
+
diff --git a/web/src/lib/components/create/DesktopPoolForm.svelte b/web/src/lib/components/create/DesktopPoolForm.svelte index 90982aa9e..51b40a127 100644 --- a/web/src/lib/components/create/DesktopPoolForm.svelte +++ b/web/src/lib/components/create/DesktopPoolForm.svelte @@ -4,7 +4,7 @@ import { api, type DesktopAssignment, type DesktopPoolCreate } from '#lib/api.js'; import { POOL_NAME_HINT, poolRefusals } from '#lib/desktopspec.js'; import { plural } from '#lib/format.js'; - import { desktopGitGate } from '#lib/gates.js'; + import { desktopGitGate, desktopPlaceHeld, desktopsOffPlace } from '#lib/gates.js'; import { CHECKING } from '#lib/state/caps.svelte.js'; import { action } from '#lib/resource.svelte.js'; import { rowList } from '#lib/rowlist.svelte.js'; @@ -14,6 +14,7 @@ import Button from '../Button.svelte'; import Consequence from '../Consequence.svelte'; import DesktopClassField from './DesktopClassField.svelte'; + import DesktopsOffNotice from './DesktopsOffNotice.svelte'; import PlacePicker from './PlacePicker.svelte'; import SheetBody from './SheetBody.svelte'; import SheetFooter from './SheetFooter.svelte'; @@ -82,7 +83,7 @@ const missing = $derived.by(() => { const m: string[] = []; // The place, and what holds it back, come first: no other field fixes them. - const held = !namespace ? 'Pick a project and namespace' : gate.ok ? '' : gate.why; + const held = desktopPlaceHeld(namespace, gate); if (held && held !== CHECKING) m.push(held); if (!name) m.push('Name the pool'); else if (taken) m.push(`${name} is taken in ${namespace}`); @@ -127,9 +128,16 @@
- +
+
diff --git a/web/src/lib/components/create/DesktopsOffNotice.svelte b/web/src/lib/components/create/DesktopsOffNotice.svelte new file mode 100644 index 000000000..22294e7dd --- /dev/null +++ b/web/src/lib/components/create/DesktopsOffNotice.svelte @@ -0,0 +1,87 @@ + + +{#if off} + + {#if proposed} + + Desktops are off in {namespace}: turning them on is proposed in + + PR #{proposed.prNumber} + . A pool or a desktop goes here once it merges. + + {:else if staged} + Desktops are off in {namespace}: turning them on is staged in the platform draft. + + Review and propose it + + {:else if turnOn} + Desktops are off in {namespace}. + + {:else} + Desktops are off in {namespace}: {DESKTOPS_OFF_FIX} + {/if} + +{/if} diff --git a/web/src/lib/components/create/PlacePicker.svelte b/web/src/lib/components/create/PlacePicker.svelte index b06b9d860..34548877c 100644 --- a/web/src/lib/components/create/PlacePicker.svelte +++ b/web/src/lib/components/create/PlacePicker.svelte @@ -5,19 +5,22 @@ // Where a create lands, as "project / namespace": a combobox that searches // at scale, the opener's project first. A project with one namespace reads - // as the project alone when short is set. + // as the project alone when short is set. A place held says why, and is + // listed but cannot be chosen. let { id, value = $bindable(), namespaces, first = '', short = false, + held = () => '', }: { id: string; value: string; namespaces: string[]; first?: string; // the project listed first short?: boolean; + held?: (namespace: string) => string; } = $props(); let open = $state(false); @@ -49,6 +52,7 @@ const current = $derived(places.find((p) => p.ns === value)); function choose(ns: string) { + if (held(ns)) return; value = ns; open = false; query = ''; @@ -120,13 +124,19 @@
    {#each shown.slice(0, 50) as p, i (p.ns)} + {@const why = held(p.ns)}
  • { e.preventDefault(); choose(p.ns); @@ -134,7 +144,8 @@ onpointerenter={() => (active = i)} > {label(p)} - {#if p.project === first} + {#if why}{why} + {:else if p.project === first} yours {/if}
  • diff --git a/web/src/lib/desktops.test.ts b/web/src/lib/desktops.test.ts index 8681c747f..cdf9a5129 100644 --- a/web/src/lib/desktops.test.ts +++ b/web/src/lib/desktops.test.ts @@ -1,11 +1,21 @@ import { describe, expect, it } from 'vitest'; -import type { Desktop, DesktopClaim, DesktopInGit, DesktopPool, Desktops, Project } from './api'; +import type { + Desktop, + DesktopClaim, + DesktopCondition, + DesktopInGit, + DesktopPool, + Desktops, + Project, +} from './api'; import { actingClaim, byProject, count, desktopState, duration, + failingCondition, + failure, inGitNoun, inGitStep, joinClaims, @@ -157,6 +167,61 @@ describe('restart', () => { }); }); +describe('why a desktop fails', () => { + // default/de on hetznet, as DeskuBe reported it: its pod crash loops, + // while UnpairPending and UpdatePending read False because all is well. + const hetznet: DesktopCondition[] = [ + { type: 'UnpairPending', status: 'False', reason: 'NoFormerClients' }, + { type: 'SeccompFiltered', status: 'True', reason: 'RuntimeDefault' }, + { type: 'UpdatePending', status: 'False', reason: 'UpToDate' }, + { + type: 'PodReady', + status: 'False', + reason: 'CrashLoopBackOff', + message: + 'back-off 5m0s restarting failed container=desktop pod=de-74d5989bf5-69vfd_default(75429a32-4dd2-49d6-b716-1659023f724b)', + }, + { type: 'NetworkReady', status: 'True', reason: 'Address' }, + { type: 'StreamingReady', status: 'False', reason: 'PodNotReady' }, + { type: 'Ready', status: 'False', reason: 'Aggregate' }, + ]; + + it('names the part that fails, never a condition whose False is well', () => { + const st = desktopState( + desktop('de', { namespace: 'default', phase: 'Failed', conditions: hetznet }), + ); + expect(st).toMatchObject({ tone: 'danger', label: 'Failed', message: hetznet[3].message }); + expect(hetznet.filter(failingCondition).map((c) => c.type)).toEqual([ + 'PodReady', + 'StreamingReady', + 'Ready', + ]); + }); + + it("takes Ready's own reason, with the message of the part it names", () => { + const refused = { type: 'PodReady', status: 'False', reason: 'Seccomp', message: 'refused' }; + expect( + failure([ + { type: 'NetworkReady', status: 'False', reason: 'Address', message: 'no node' }, + refused, + { type: 'Ready', status: 'False', reason: 'Seccomp' }, + ]), + ).toBe(refused); + const home = { type: 'Ready', status: 'False', reason: 'HomeRefused' }; + expect(failure([...hetznet.slice(0, 3), home])).toBe(home); + }); + + it('says nothing where only a condition whose False is well is False', () => { + const well = hetznet.filter((c) => !READY_TYPES.includes(c.type)); + expect(failure(well)).toBeUndefined(); + expect(desktopState(desktop('de', { phase: 'Failed', conditions: well })).message).toBe( + undefined, + ); + }); +}); + +const READY_TYPES = ['PodReady', 'NetworkReady', 'StreamingReady', 'Ready']; + describe('unlisted kinds', () => { const unlisted = [ { namespace: '', resource: 'vdiclasses' }, diff --git a/web/src/lib/desktops.ts b/web/src/lib/desktops.ts index 645ce1b81..a0a69e404 100644 --- a/web/src/lib/desktops.ts +++ b/web/src/lib/desktops.ts @@ -157,6 +157,32 @@ export interface State { export const readyOf = (conditions?: DesktopCondition[]) => conditions?.find((c) => c.type === 'Ready'); +// The parts DeskuBe's Ready aggregates, whose False is a failure, in the +// order one causes the next: no pod, no address, no stream. UnpairPending and +// UpdatePending read False when all is well, and SeccompFiltered says how the +// desktop runs: none of them is why it fails. +const READY_PARTS = ['PodReady', 'NetworkReady', 'StreamingReady']; +// Ready's reason when it only sums up its parts. +const AGGREGATE = ['Aggregate', 'Unknown']; + +// failingCondition reports whether c says the desktop fails: Ready, or a part +// of it, False. +export const failingCondition = (c: DesktopCondition): boolean => + c.status === 'False' && (c.type === 'Ready' || READY_PARTS.includes(c.type)); + +// failure is the condition that says why a desktop fails: the part Ready +// names by its own reason, with that part's message, or Ready itself; where +// Ready only sums its parts up, the first part that is False. +export function failure(conditions?: DesktopCondition[]): DesktopCondition | undefined { + const parts = READY_PARTS.flatMap( + (t) => conditions?.filter((c) => c.type === t && c.status === 'False') ?? [], + ); + const ready = readyOf(conditions); + if (ready?.status === 'False' && ready.reason && !AGGREGATE.includes(ready.reason)) + return parts.find((c) => c.reason === ready.reason) ?? ready; + return parts[0]; +} + // Why a condition is False, in words. export const why = (c: DesktopCondition, cls?: string): string => c.reason === 'ClassNotFound' && cls ? `class ${cls} does not exist` : c.message || c.reason || ''; @@ -182,8 +208,7 @@ export function desktopState(d: Desktop): State { const ready = readyOf(d.conditions); if (ready?.status === 'False' && ready.reason === 'ClassNotFound') return { tone: 'danger', label: 'Class missing', missingClass: d.class, note }; - const failing = - d.phase === 'Failed' ? d.conditions?.find((c) => c.status === 'False') : undefined; + const failing = d.phase === 'Failed' ? failure(d.conditions) : undefined; return { tone: desktopTone(d.phase), label: d.phase || 'Not read yet', diff --git a/web/src/lib/gates.test.ts b/web/src/lib/gates.test.ts index dd4bd65b1..45856a7aa 100644 --- a/web/src/lib/gates.test.ts +++ b/web/src/lib/gates.test.ts @@ -98,7 +98,7 @@ describe('desktopGitGate', () => { namespace: { namespace: 'web', desktopPool: own(false), desktopsOff: true }, }); const why = - "Desktops are not on in web: a platform admin turns them on from the project's Configure tab."; + "Desktops are off in web: a platform admin turns them on from the project's Configure tab."; expect(desktopsOffWhy('web')).toBe(why); expect(desktopGitGate(pool, 'create')).toEqual({ ok: false, why }); }); @@ -143,7 +143,7 @@ describe('desktopCreateGate', () => { await flush(); expect(desktopCreateGate('desktoppool', ['web', 'db'])).toEqual({ ok: false, - why: "Desktops are not on in web, db: a platform admin turns them on from the project's Configure tab.", + why: "Desktops are off in web, db: a platform admin turns them on from the project's Configure tab.", namespace: '', off: ['web', 'db'], }); diff --git a/web/src/lib/gates.ts b/web/src/lib/gates.ts index 0cae380f3..7b9f88b2c 100644 --- a/web/src/lib/gates.ts +++ b/web/src/lib/gates.ts @@ -175,7 +175,19 @@ export const DESKTOPS_HELD = // account could not apply it. Told where the server tells it, with who acts. export const DESKTOPS_OFF_FIX = "a platform admin turns them on from the project's Configure tab."; export const desktopsOffWhy = (namespace: string) => - `Desktops are not on in ${namespace}: ${DESKTOPS_OFF_FIX}`; + `Desktops are off in ${namespace}: ${DESKTOPS_OFF_FIX}`; +// What holds a new pool or desktop back from namespace, for its form's +// submit, gate being the create's there. Where desktops are off the form's +// notice carries the fix, so the submit asks only for another place. +export function desktopPlaceHeld(namespace: string, gate: Gate): string { + if (!namespace) return 'Pick a project and namespace'; + if (gate.ok) return ''; + return caps.ns(namespace)?.desktopsOff ? 'Pick a namespace where desktops are on' : gate.why; +} +// A namespace a new pool or desktop cannot be placed in, as far as answers +// already read say: a list of places reads none of its own. +export const desktopsOffPlace = (namespace: string) => + caps.known(namespace)?.desktopsOff ? 'desktops off' : ''; // A pool's or a desktop's verdict on one of the object routes' writes, adopt // by default, said apart where only the sync account's setup, or desktops @@ -212,7 +224,7 @@ export function desktopCreateGate( : whys.includes(DESKTOPS_HELD) ? DESKTOPS_HELD : off.length === whys.length && off.length - ? `Desktops are not on in ${off.join(', ')}: ${DESKTOPS_OFF_FIX}` + ? `Desktops are off in ${off.join(', ')}: ${DESKTOPS_OFF_FIX}` : (whys[0] ?? ''); return { ok: false, why, namespace: '', off }; } diff --git a/web/src/lib/state/caps.svelte.ts b/web/src/lib/state/caps.svelte.ts index 14e7ac064..4cd7f9799 100644 --- a/web/src/lib/state/caps.svelte.ts +++ b/web/src/lib/state/caps.svelte.ts @@ -63,6 +63,13 @@ class CapsStore { return r?.state === 'ok' ? r.value : null; } + // A namespace's answer if one has landed, without asking for one: marking + // a long list of namespaces must not read each of them. + known(namespace: string): NamespaceCaps | null { + const r = this.#ns[namespace]; + return r?.state === 'ok' ? r.value : null; + } + // clusterGate offers what pick says the cluster answer allows. clusterGate(pick: (c: ClusterCaps) => boolean, denied: string): Gate { this.#want(''); diff --git a/web/src/lib/workspace/desktops/DesktopPage.svelte b/web/src/lib/workspace/desktops/DesktopPage.svelte index 78996093b..f4760b499 100644 --- a/web/src/lib/workspace/desktops/DesktopPage.svelte +++ b/web/src/lib/workspace/desktops/DesktopPage.svelte @@ -2,6 +2,7 @@ import { desktopRef, desktopState, + failingCondition, IN_GIT, joinClaims, sessionLabel, @@ -180,7 +181,7 @@ {#each desktop.conditions as c (c.type)}
    {c.type}
    -
    +
    {c.status === 'True' ? 'Yes' : c.status === 'False' diff --git a/web/src/lib/workspace/desktops/InGitNext.svelte b/web/src/lib/workspace/desktops/InGitNext.svelte index 099f988b5..8089e38de 100644 --- a/web/src/lib/workspace/desktops/InGitNext.svelte +++ b/web/src/lib/workspace/desktops/InGitNext.svelte @@ -48,12 +48,12 @@ {#if step.step === 'off' && compact} - Desktops are not on here. + Desktops are off here. {#if turnOn}Turn them on{/if} {:else if step.step === 'off'} - Desktops are not on in {row.namespace}: + Desktops are off in {row.namespace}: {#if turnOn} turn them on from the project's Configure tab. {:else} From 26320288d7bcb23e3c8675c79f8c46429a8007bf Mon Sep 17 00:00:00 2001 From: Thibaut Lapierre Date: Mon, 30 Nov 2026 10:06:17 +0100 Subject: [PATCH 3/9] operator: the sync request role names the desktop resync it now serves Assisted by LLM --- operator/config/rbac/operand_roles.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/operator/config/rbac/operand_roles.yaml b/operator/config/rbac/operand_roles.yaml index 49536a76f..7db016a85 100644 --- a/operator/config/rbac/operand_roles.yaml +++ b/operator/config/rbac/operand_roles.yaml @@ -467,8 +467,9 @@ rules: # The one Application write dotvirt's ServiceAccount makes, bound by a RoleBinding in # the Argo namespace only, so Applications elsewhere stay out of reach. patch serves # exactly two merge patches (internal/argo/snapshot.go), never spec: a top-level -# `operation` syncing one VirtualMachine, sent only after the caller passes a -# CanUpdateVM review, and the argocd.argoproj.io/refresh annotation, set for a push +# `operation` syncing one VirtualMachine, desktop pool or desktop, sent only after the +# caller passes the review of what that sync applies (an update of the object, and for +# a pool or desktop the grants DeskuBe asks), and the argocd.argoproj.io/refresh annotation, set for a push # the forge webhook's HMAC verified. RBAC cannot scope patch to fields: a guard on # spec, if wanted, is an admission policy on this ServiceAccount. apiVersion: rbac.authorization.k8s.io/v1 From 6b941ebf27833fd48b5dee1cf1baee2b0aaf8f97 Mon Sep 17 00:00:00 2001 From: Thibaut Lapierre Date: Mon, 30 Nov 2026 10:21:23 +0100 Subject: [PATCH 4/9] desktops: whom a project grants in git, and the cluster's people searched as the caller Assisted by LLM --- internal/api/api.go | 5 + internal/api/fakecluster_test.go | 6 + internal/api/handlers_adminobjects.go | 13 + internal/api/handlers_adminobjects_test.go | 9 +- internal/api/handlers_people.go | 261 +++++++++++++++++ internal/api/people_test.go | 309 +++++++++++++++++++++ internal/api/routes.go | 4 + internal/changeset/grants.go | 97 +++++++ internal/cluster/people.go | 47 ++++ internal/model/caps.go | 4 + internal/model/desktop.go | 10 + internal/model/people.go | 40 +++ web/src/lib/model.gen.ts | 74 +++++ 13 files changed, 878 insertions(+), 1 deletion(-) create mode 100644 internal/api/handlers_people.go create mode 100644 internal/api/people_test.go create mode 100644 internal/changeset/grants.go create mode 100644 internal/cluster/people.go create mode 100644 internal/model/people.go diff --git a/internal/api/api.go b/internal/api/api.go index b0b5d7352..7addab14b 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -188,6 +188,9 @@ type Draft interface { // desktops on in ns: the one answer the gate refuses a pool or a desktop // by. DesktopsOn(commitProj project.ProjectInfo, ns string) (bool, error) + // Grants are the RoleBindings commitProj, the platform repo, declares in + // namespaces: who a project already grants, read from git alone. + Grants(commitProj project.ProjectInfo, namespaces []string) ([]changeset.Grant, error) ReleaseNeeds(commitProj, target project.ProjectInfo) (need []changeset.Access, residue []string, err error) EnableDRSNeeds(proj project.ProjectInfo, spec json.RawMessage) ([]changeset.Access, error) DisableDRSNeeds(proj project.ProjectInfo) ([]changeset.Access, error) @@ -288,6 +291,7 @@ type Server struct { kindFill *ttlcache.Cache[*kindIndex] // single-flights its refresh proposals *ttlcache.Cache[[]model.Proposal] // per-project open-PR set; written by the refresher, read on broadcast options *ttlcache.Cache[model.Options] // shared wizard catalog (SA-read, identical for all) + people *ttlcache.Cache[[]model.Person] // per-(identity, kind) list of the cluster's users or groups storage *ttlcache.Cache[[]cluster.SheetClass] metrics *metrics.Client // Prometheus/Thanos for the Performance tab; nil disables it tasks *tasks.Feed // recent-activity feed (ops + merged PRs); nil disables it @@ -383,6 +387,7 @@ func NewServer(d Deps) *Server { proposals: ttlcache.New[[]model.Proposal](proposalsCacheTTL), options: ttlcache.New[model.Options](optionsTTL), storage: ttlcache.New[[]cluster.SheetClass](storageTTL), + people: ttlcache.New[[]model.Person](peopleTTL), metrics: d.Metrics, tasks: d.Tasks, forge: d.Forge, diff --git a/internal/api/fakecluster_test.go b/internal/api/fakecluster_test.go index 05fa60110..ee72ae2e8 100644 --- a/internal/api/fakecluster_test.go +++ b/internal/api/fakecluster_test.go @@ -758,6 +758,12 @@ func (d *planeDraft) DesktopsNeeds(project.ProjectInfo, project.ProjectInfo, str func (d *planeDraft) DesktopsOn(_ project.ProjectInfo, ns string) (bool, error) { return !slices.Contains(d.desktopsOff, ns), nil } + +// Grants declares none: a test of who a project grants runs a real +// coordinator (people_test.go). +func (d *planeDraft) Grants(project.ProjectInfo, []string) ([]changeset.Grant, error) { + return nil, nil +} func (d *planeDraft) ReleaseNeeds(project.ProjectInfo, project.ProjectInfo) ([]changeset.Access, []string, error) { return nil, d.releaseResidue, nil } diff --git a/internal/api/handlers_adminobjects.go b/internal/api/handlers_adminobjects.go index 09791b9d8..b720a090d 100644 --- a/internal/api/handlers_adminobjects.go +++ b/internal/api/handlers_adminobjects.go @@ -197,6 +197,9 @@ func (s *Server) adminObjects(ctx context.Context, id auth.Identity, c *cluster. Purpose: o.Purpose, Kind: ref.Kind, Name: ref.Name, Namespace: ref.Namespace, State: string(state), Detail: detail, Object: o.Object.Object, }) + if ref.Name == adminobjects.GuardArgoName { + out.DesktopsGuard = worseState(out.DesktopsGuard, state) + } } // What the install no longer asks for but is still there: listed to remove, // never applied. @@ -214,3 +217,13 @@ func (s *Server) adminObjects(ctx context.Context, id auth.Identity, c *cluster. } return out, nil } + +// worseState is the worse of was, "" for none yet, and s: NotInstalled, then +// Outdated, then Installed. +func worseState(was string, s adminobjects.State) string { + rank := map[string]int{"": 3, string(adminobjects.Installed): 2, string(adminobjects.Outdated): 1, string(adminobjects.NotInstalled): 0} + if rank[string(s)] < rank[was] { + return string(s) + } + return was +} diff --git a/internal/api/handlers_adminobjects_test.go b/internal/api/handlers_adminobjects_test.go index 8c4fb9df7..9c29d6321 100644 --- a/internal/api/handlers_adminobjects_test.go +++ b/internal/api/handlers_adminobjects_test.go @@ -269,14 +269,21 @@ func TestAdminObjectsInstallTheConsolesRender(t *testing.T) { t.Errorf("before install: %+v", o) } } + if listed.DesktopsGuard != string(adminobjects.NotInstalled) { + t.Errorf("desktops guard before install = %q, want NotInstalled", listed.DesktopsGuard) + } rec = do(s, adminToken, http.MethodPost, "/api/admin-objects", "") wantStatus(t, rec, http.StatusOK) - for _, o := range decodeBody[model.AdminObjects](t, rec).Objects { + installed := decodeBody[model.AdminObjects](t, rec) + for _, o := range installed.Objects { if o.State != string(adminobjects.Installed) { t.Errorf("after install: %s %s is %s (%s)", o.Kind, o.Name, o.State, o.Detail) } } + if installed.DesktopsGuard != string(adminobjects.Installed) { + t.Errorf("desktops guard after install = %q, want Installed", installed.DesktopsGuard) + } got := seen() if _, ok := got["ClusterRoleBinding/rogue"]; ok { t.Error("the console applied an object from status") diff --git a/internal/api/handlers_people.go b/internal/api/handlers_people.go new file mode 100644 index 000000000..7ddc565c1 --- /dev/null +++ b/internal/api/handlers_people.go @@ -0,0 +1,261 @@ +package api + +import ( + "cmp" + "context" + "errors" + "fmt" + "net/http" + "slices" + "strings" + "time" + + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/epheo/dotvirt/internal/auth" + "github.com/epheo/dotvirt/internal/changeset" + "github.com/epheo/dotvirt/internal/cluster" + "github.com/epheo/dotvirt/internal/model" +) + +// peopleTTL is how long one caller's list of the cluster's users, or of its +// groups, answers that caller's searches and member counts: a burst of +// keystrokes costs one list of each. +const peopleTTL = 30 * time.Second + +var ( + ssarUsers = ssarRef{cluster.GVRUsers.Group, cluster.GVRUsers.Resource} + ssarGroups = ssarRef{cluster.GVRGroups.Group, cluster.GVRGroups.Resource} +) + +// personKinds are the kinds a person is, by what lists them. +var personKinds = map[string]struct { + gk schema.GroupKind + ssar ssarRef +}{ + "User": {schema.GroupKind{Group: cluster.GVRUsers.Group, Kind: "User"}, ssarUsers}, + "Group": {schema.GroupKind{Group: cluster.GVRGroups.Group, Kind: "Group"}, ssarGroups}, +} + +// handlePeople answers GET /api/people?namespace=: whom namespace's project +// grants in the platform repo, read from git and told per namespace to a +// caller who may list its role bindings, as the Configure tab tells whether +// desktops are on there; and whether the cluster's users and groups are +// searched. It asks the cluster nothing but cached reviews, save the +// caller's cached list of groups for their member counts. +func (s *Server) handlePeople(w http.ResponseWriter, r *http.Request) { + ns := r.URL.Query().Get("namespace") + if ns == "" { + fail(w, invalid(errors.New("name the namespace"))) + return + } + sc, ok := s.resolveProject(w, r, byNamespace(ns)) + if !ok { + return + } + ctx, id, c := r.Context(), sc.id, sc.cluster + out := model.People{Project: []model.Person{}} + out.Users, out.Groups = s.searchable(ctx, id, c, "User"), s.searchable(ctx, id, c, "Group") + full, ok := s.projectByName(sc.proj.Name) + if !ok || s.cfg.PlatformRepo == "" { + writeJSON(w, out) + return + } + acts := make([]action, len(full.Namespaces)) + for i, n := range full.Namespaces { + acts[i] = kindAction(verbList, model.KindRB, n) + } + var seen []string + for i, lists := range s.capableAll(ctx, id, c, acts) { + if lists { + seen = append(seen, full.Namespaces[i]) + } else { + out.Unseen = append(out.Unseen, full.Namespaces[i]) + } + } + if len(seen) > 0 { + grants, err := s.draft.Grants(s.platformProject(), seen) + if err != nil { + fail(w, err) + return + } + out.Project = granted(grants) + } + if out.Groups && slices.ContainsFunc(out.Project, func(p model.Person) bool { return p.Kind == "Group" }) { + // Counts are a nicety: a failed list leaves them out. + if groups, err := s.clusterPeople(ctx, id, c, "Group"); err == nil { + members := map[string]*int{} + for _, g := range groups { + members[g.Name] = g.Members + } + for i, p := range out.Project { + if p.Kind == "Group" { + out.Project[i].Members = members[p.Name] + } + } + } + } + writeJSON(w, out) +} + +// handlePeopleSearch answers GET /api/people/search?q=&kind=: the cluster's +// users and groups, of each kind asked (both by default), whose name or full +// name holds q, the closest first, at most model.PeopleCap. Each kind is +// read under the caller's own token, only where the cluster serves it and +// the caller may list it, from that caller's list cached for peopleTTL. +func (s *Server) handlePeopleSearch(w http.ResponseWriter, r *http.Request) { + id, c, err := s.userCluster(r) + if err != nil { + fail(w, unavailable(err)) + return + } + ctx := r.Context() + q := strings.TrimSpace(r.URL.Query().Get("q")) + if q == "" { + fail(w, invalid(errors.New("type part of a name"))) + return + } + kinds := r.URL.Query()["kind"] + if len(kinds) == 0 { + kinds = []string{"User", "Group"} + } + var all []model.Person + for _, k := range kinds { + pk, ok := personKinds[k] + switch { + case !ok: + fail(w, invalid(fmt.Errorf("a person is a User or a Group, not %q", k))) + return + case !s.serves(ctx, pk.gk): + fail(w, fmt.Errorf("%w: this cluster keeps no %s to search: type the name", model.ErrNotFound, strings.ToLower(k)+"s")) + return + case !s.capable(ctx, id, c, ask(verbList, pk.ssar, "")): + act := ask(verbList, pk.ssar, "") + fail(w, refused(act[0].String(), act)) + return + } + people, err := s.clusterPeople(ctx, id, c, k) + if err != nil { + fail(w, err) + return + } + all = append(all, people...) + } + writeJSON(w, matchPeople(all, q)) +} + +// searchable reports whether the cluster serves kind and the caller may list +// it: discovery's cached answer and a cached review. +func (s *Server) searchable(ctx context.Context, id auth.Identity, c *cluster.Client, kind string) bool { + pk := personKinds[kind] + return s.serves(ctx, pk.gk) && s.capable(ctx, id, c, ask(verbList, pk.ssar, "")) +} + +// serves reports whether discovery, as cached for every caller, found gk +// served. A failed read is no: the form then takes a typed name. +func (s *Server) serves(ctx context.Context, gk schema.GroupKind) bool { + x, err := s.servedKinds(ctx, []schema.GroupKind{gk}) + if err != nil { + return false + } + _, served, err := x.ref(gk) + return err == nil && served +} + +// clusterPeople is the cluster's users or groups as id's token lists them, +// cached per caller for peopleTTL; concurrent misses share one list. +func (s *Server) clusterPeople(ctx context.Context, id auth.Identity, c *cluster.Client, kind string) ([]model.Person, error) { + key := id.Key() + "\x00" + kind + if v, ok := s.people.Get(key); ok { + return v, nil + } + return s.people.Do(ctx, key, func(ctx context.Context) ([]model.Person, error) { + if v, ok := s.people.Get(key); ok { + return v, nil + } + at := time.Now() + v, err := c.People(ctx, kind) + if err != nil { + return nil, err + } + s.people.PutAt(key, v, at) + return v, nil + }) +} + +// matchPeople is those of all whose name or full name holds q, ignoring case: +// a name equal to q first, then one starting with it, then the rest, each by +// name; at most model.PeopleCap. +func matchPeople(all []model.Person, q string) model.PeopleFound { + q = strings.ToLower(q) + rank := func(p model.Person) int { + name := strings.ToLower(p.Name) + switch { + case name == q: + return 0 + case strings.HasPrefix(name, q): + return 1 + case strings.Contains(name, q), strings.Contains(strings.ToLower(p.FullName), q): + return 2 + } + return -1 + } + out := model.PeopleFound{Found: []model.Person{}} + var hits []model.Person + for _, p := range all { + if rank(p) >= 0 { + hits = append(hits, p) + } + } + slices.SortFunc(hits, func(a, b model.Person) int { + return cmp.Or(cmp.Compare(rank(a), rank(b)), cmp.Compare(a.Name, b.Name), cmp.Compare(a.Kind, b.Kind)) + }) + if len(hits) > model.PeopleCap { + hits, out.More = hits[:model.PeopleCap], true + } + out.Found = append(out.Found, hits...) + return out +} + +// roleRank orders a person's roles, the widest first. +var roleRank = map[string]int{"admin": 0, "edit": 1, "view": 2} + +// granted are the users and groups grants bind, each once with every role +// they hold, groups then users, by name. Accounts are not people: a +// ServiceAccount, or a user naming one, is left out. +func granted(grants []changeset.Grant) []model.Person { + byKey := map[[2]string]*model.Person{} + var out []*model.Person + for _, g := range grants { + for _, sub := range g.Subjects { + if sub.Kind != "User" && sub.Kind != "Group" || sub.Name == "" || strings.HasPrefix(sub.Name, "system:serviceaccount:") { + continue + } + k := [2]string{sub.Kind, sub.Name} + p := byKey[k] + if p == nil { + p = &model.Person{Kind: sub.Kind, Name: sub.Name} + byKey[k] = p + out = append(out, p) + } + if g.Role != "" && !slices.Contains(p.Roles, g.Role) { + p.Roles = append(p.Roles, g.Role) + } + } + } + rank := func(role string) int { + if r, ok := roleRank[role]; ok { + return r + } + return len(roleRank) + } + people := make([]model.Person, len(out)) + for i, p := range out { + slices.SortFunc(p.Roles, func(a, b string) int { return cmp.Or(cmp.Compare(rank(a), rank(b)), cmp.Compare(a, b)) }) + people[i] = *p + } + slices.SortFunc(people, func(a, b model.Person) int { + return cmp.Or(cmp.Compare(a.Kind, b.Kind), cmp.Compare(a.Name, b.Name)) + }) + return people +} diff --git a/internal/api/people_test.go b/internal/api/people_test.go new file mode 100644 index 000000000..c189637dd --- /dev/null +++ b/internal/api/people_test.go @@ -0,0 +1,309 @@ +package api + +import ( + "encoding/json" + "fmt" + "net/http" + "slices" + "strings" + "testing" + "time" + + authzv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/epheo/dotvirt/internal/changeset" + "github.com/epheo/dotvirt/internal/draft" + "github.com/epheo/dotvirt/internal/git" + "github.com/epheo/dotvirt/internal/model" + "github.com/epheo/dotvirt/internal/netgen" + "github.com/epheo/dotvirt/pkg/adminobjects" +) + +var ( + userKind = model.Kind{Kind: "User", Group: "user.openshift.io", Version: "v1", Plural: "users", ClusterScoped: true} + groupKind = model.Kind{Kind: "Group", Group: "user.openshift.io", Version: "v1", Plural: "groups", ClusterScoped: true} +) + +const ( + usersPath = "/apis/user.openshift.io/v1/users" + groupsPath = "/apis/user.openshift.io/v1/groups" +) + +// peopleServer serves project team-a over team-a-dev and team-a-prod, whose +// grants the platform repo declares: in team-a-dev the admin grant to alice +// and the project's sync account, the desktop grant following it, a viewer +// group and a grant to a user naming a ServiceAccount; in team-a-prod an +// operators group. A grant in team-b-dev names bob. served says the cluster +// serves OpenShift's users and groups: alice (Alice Martin), user-00 to +// user-24, and the groups team-a-viewers (3) and ops (1). lister may list +// team-a-dev's role bindings alone; searcher every namespace's, and the +// users and groups; outsider sees team-a-dev and may list none of them. +func peopleServer(t *testing.T, served bool) (*Server, *fakeCluster) { + t.Helper() + sa := netgen.ServiceAccountSubject("openshift-gitops", "dotvirt-p-team-a") + alice := netgen.Subject{Kind: "User", APIGroup: "rbac.authorization.k8s.io", Name: "alice"} + spec := netgen.RoleBindingSpec{Namespace: "team-a-dev", Project: "team-a", Kept: []netgen.Subject{alice}, SyncAccount: sa} + files := map[string]string{} + for _, render := range []func(netgen.RoleBindingSpec) (string, []byte, error){netgen.RoleBindingManifest, netgen.DesktopsManifest} { + path, content, err := render(spec) + if err != nil { + t.Fatal(err) + } + files[path] = string(content) + } + files["rbac/team-a-dev/team-a-dev-viewers.yaml"] = grantYAML("team-a-dev", "team-a-dev-viewers", "view", "Group", "team-a-viewers") + + "---\n" + grantYAML("team-a-dev", "team-a-dev-robot", "edit", "User", "system:serviceaccount:team-a-dev:robot") + files["rbac/team-a-prod/team-a-prod-ops.yaml"] = grantYAML("team-a-prod", "team-a-prod-ops", "edit", "Group", "ops") + files["rbac/team-b-dev.yaml"] = grantYAML("team-b-dev", "team-b-dev-admins", "admin", "User", "bob") + platform, _, _ := seedCommits(t, map[string]string{"side.yaml": "x: 1\n"}, files) + + fc := newFakeCluster(t) + fc.namespaces = append(fc.namespaces, corev1.Namespace{ObjectMeta: metav1.ObjectMeta{ + Name: "team-a-prod", Labels: map[string]string{"dotvirt.io/project": "team-a"}, Annotations: map[string]string{"dotvirt.io/repo": repoTeamA}, + }}) + fc.readsVMs = func(token, ns string) bool { return ns == "team-a-dev" } + lists := func(token string, a *authzv1.ResourceAttributes) bool { + bindings := a.Verb == verbList && a.Resource == "rolebindings" + people := a.Verb == verbList && a.Group == "user.openshift.io" && a.Namespace == "" + switch { + case token == "lister": + return bindings && a.Namespace == "team-a-dev" + case strings.HasPrefix(token, "searcher"): + return bindings || people + } + return false + } + fc.ssar = lists + kinds := []model.Kind{model.KindVdiPool, model.KindVdiInstance, model.KindVdiClass} + if served { + kinds = append(kinds, userKind, groupKind) + } + fc.serveKinds(kinds...) + item := func(kind, name string, fields map[string]any) map[string]any { + o := map[string]any{"apiVersion": "user.openshift.io/v1", "kind": kind, "metadata": map[string]any{"name": name}} + for k, v := range fields { + o[k] = v + } + return o + } + users := []any{item("User", "alice", map[string]any{"fullName": "Alice Martin"})} + for i := range 25 { + users = append(users, item("User", fmt.Sprintf("user-%02d", i), nil)) + } + groups := []any{ + item("Group", "team-a-viewers", map[string]any{"users": []any{"alice", "user-01", "user-02"}}), + item("Group", "ops", map[string]any{"users": []any{"user-03"}}), + } + for path, items := range map[string][]any{usersPath: users, groupsPath: groups} { + kind := map[string]string{usersPath: "UserList", groupsPath: "GroupList"}[path] + fc.on(http.MethodGet, path, func(w http.ResponseWriter, r *http.Request) { + if !lists(bearer(r), &authzv1.ResourceAttributes{Verb: verbList, Group: "user.openshift.io", Resource: strings.TrimPrefix(path, "/apis/user.openshift.io/v1/")}) { + writeStatus(w, http.StatusForbidden, metav1.StatusReasonForbidden) + return + } + writeObj(w, map[string]any{"apiVersion": "user.openshift.io/v1", "kind": kind, "metadata": map[string]any{}, "items": items}) + }) + } + + store, err := draft.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + repos := git.NewRepoSet(t.Context(), "", "", nil, false, nil, time.Hour) + co := changeset.New(store, repos, nil, nil, nil, nil, "main", "dotvirt/proposed").WithPlatformRepo(platform) + s := desktopsServerWith(t, fc, &desktopsSource{}, co, Config{BaseBranch: "main", PlatformRepo: platform}) + co.UseAuthorizer(s) + return s, fc +} + +func grantYAML(ns, name, role, kind, subject string) string { + return "apiVersion: rbac.authorization.k8s.io/v1\nkind: RoleBinding\nmetadata:\n name: " + name + "\n namespace: " + ns + + "\nroleRef:\n apiGroup: rbac.authorization.k8s.io\n kind: ClusterRole\n name: " + role + + "\nsubjects:\n- apiGroup: rbac.authorization.k8s.io\n kind: " + kind + "\n name: " + subject + "\n" +} + +// peopleListed counts the caller-token lists of path. +func peopleListed(fc *fakeCluster, path string) int { + n := 0 + for _, c := range fc.seen() { + if c == http.MethodGet+" "+path { + n++ + } + } + return n +} + +// A form offers whom the project's namespaces grant in the platform repo, +// each namespace's only to a caller who may list its role bindings, as +// kubectl would show them: people, not accounts, each once with the roles it +// holds, the widest first. Reading it lists nothing on the cluster; a caller +// who may list groups gets each one's member count from its own list. +func TestPeopleAreWhomTheProjectGrantsInGit(t *testing.T) { + s, fc := peopleServer(t, true) + people := func(token string) model.People { + t.Helper() + rec := do(s, token, http.MethodGet, "/api/people?namespace=team-a-dev", "") + wantStatus(t, rec, http.StatusOK) + return decodeBody[model.People](t, rec) + } + viewers := model.Person{Kind: "Group", Name: "team-a-viewers", Roles: []string{"view"}} + alice := model.Person{Kind: "User", Name: "alice", Roles: []string{"admin", "dotvirt-tenant-desktops"}} + + got := people("lister") + if want := []model.Person{viewers, alice}; !peopleEqual(got.Project, want) { + t.Errorf("lister's project = %+v, want %+v", got.Project, want) + } + if !slices.Equal(got.Unseen, []string{"team-a-prod"}) || got.Users || got.Groups { + t.Errorf("lister = unseen %v, users %v, groups %v; want team-a-prod unseen, no search", got.Unseen, got.Users, got.Groups) + } + if peopleListed(fc, usersPath)+peopleListed(fc, groupsPath) != 0 || slices.ContainsFunc(fc.seen(), func(c string) bool { return strings.Contains(c, "rolebindings") }) { + t.Errorf("reading who the project grants reached the cluster: %v", fc.seen()) + } + + if got := people("outsider"); len(got.Project) != 0 || !slices.Equal(got.Unseen, []string{"team-a-dev", "team-a-prod"}) { + t.Errorf("outsider = %+v, want nothing it may not list", got) + } + + got = people("searcher") + ops := model.Person{Kind: "Group", Name: "ops", Roles: []string{"edit"}, Members: new(1)} + viewers.Members = new(3) + if want := []model.Person{ops, viewers, alice}; !peopleEqual(got.Project, want) || len(got.Unseen) != 0 || !got.Users || !got.Groups { + t.Errorf("searcher = %+v, want %+v and the search", got, want) + } + if peopleListed(fc, groupsPath) != 1 || peopleListed(fc, usersPath) != 0 { + t.Errorf("member counts listed groups %d and users %d times, want 1 and 0", peopleListed(fc, groupsPath), peopleListed(fc, usersPath)) + } + + wantStatus(t, do(s, "lister", http.MethodGet, "/api/people?namespace=elsewhere", ""), http.StatusNotFound) + wantStatus(t, do(s, "lister", http.MethodGet, "/api/people", ""), http.StatusBadRequest) +} + +func peopleEqual(a, b []model.Person) bool { + x, _ := json.Marshal(a) + y, _ := json.Marshal(b) + return string(x) == string(y) +} + +// The cluster's users and groups are searched under the caller's own token, +// only where the cluster serves them and the caller may list them: an exact +// name first, then a name starting with what was typed, then the rest, a +// full name too, at most model.PeopleCap. A burst of searches lists each +// kind once. +func TestPeopleSearchIsGatedAndCached(t *testing.T) { + s, fc := peopleServer(t, true) + search := func(token, query string, code int) model.PeopleFound { + t.Helper() + rec := do(s, token, http.MethodGet, "/api/people/search?"+query, "") + wantStatus(t, rec, code) + if code != http.StatusOK { + return model.PeopleFound{} + } + return decodeBody[model.PeopleFound](t, rec) + } + names := func(f model.PeopleFound) []string { + var out []string + for _, p := range f.Found { + out = append(out, p.Kind+"/"+p.Name) + } + return out + } + + got := search("searcher", "q=user-1&kind=User", http.StatusOK) + var want []string + for i := range 10 { + want = append(want, fmt.Sprintf("User/user-%02d", 10+i)) + } + if !slices.Equal(names(got), want) || got.More { + t.Errorf("user-1 found %v (more %v), want %v", names(got), got.More, want) + } + if got := search("searcher", "q=USER-07&kind=User", http.StatusOK); !slices.Equal(names(got), []string{"User/user-07"}) { + t.Errorf("USER-07 found %v, want the one user", names(got)) + } + if got := search("searcher", "q=martin", http.StatusOK); !slices.Equal(names(got), []string{"User/alice"}) || got.Found[0].FullName != "Alice Martin" { + t.Errorf("martin found %+v, want alice by her full name", got.Found) + } + if got := search("searcher", "q=user", http.StatusOK); len(got.Found) != model.PeopleCap || !got.More { + t.Errorf("user found %d (more %v), want the cap and more", len(got.Found), got.More) + } + if got := search("searcher", "q=view&kind=Group", http.StatusOK); len(got.Found) != 1 || got.Found[0].Name != "team-a-viewers" || *got.Found[0].Members != 3 { + t.Errorf("view found %+v, want team-a-viewers of 3", got.Found) + } + if peopleListed(fc, usersPath) != 1 || peopleListed(fc, groupsPath) != 1 { + t.Errorf("five searches listed users %d and groups %d times, want each once", peopleListed(fc, usersPath), peopleListed(fc, groupsPath)) + } + + search("lister", "q=al&kind=User", http.StatusForbidden) + search("searcher", "q=al&kind=ServiceAccount", http.StatusBadRequest) + search("searcher", "q=+&kind=User", http.StatusBadRequest) + if peopleListed(fc, usersPath) != 1 { + t.Error("a refused search listed users") + } + + // Another caller's search reads its own list. + search("searcher-2", "q=al&kind=User", http.StatusOK) + if peopleListed(fc, usersPath) != 2 { + t.Errorf("a second caller listed users %d times in all, want its own list", peopleListed(fc, usersPath)) + } +} + +// A cluster that keeps no user or group objects is searched for neither: the +// form takes a typed name. +func TestPeopleSearchWaitsOnTheClusterServingThem(t *testing.T) { + s, fc := peopleServer(t, false) + rec := do(s, "searcher", http.MethodGet, "/api/people?namespace=team-a-dev", "") + wantStatus(t, rec, http.StatusOK) + if got := decodeBody[model.People](t, rec); got.Users || got.Groups || len(got.Project) != 3 { + t.Errorf("people = %+v, want the project's and no search", got) + } + wantStatus(t, do(s, "searcher", http.MethodGet, "/api/people/search?q=al", ""), http.StatusNotFound) + if peopleListed(fc, usersPath)+peopleListed(fc, groupsPath) != 0 { + t.Error("an unserved kind was listed") + } +} + +// The first class a form offers in one click is DeskuBe's own, staged into +// the platform repo by a class author as any new class is, and refused to +// another. +func TestFirstClassStagesDeskuBesOwn(t *testing.T) { + s := createServer(t, desktopKinds) + body, err := json.Marshal(model.DesktopClassCreate{Name: model.FirstDesktopClassName, Image: model.FirstDesktopClassImage, IdleTimeout: model.FirstDesktopClassIdle}) + if err != nil { + t.Fatal(err) + } + wantStatus(t, do(s, "author", http.MethodPost, "/api/desktopclasses", string(body)), http.StatusForbidden) + rec := do(s, "classes", http.MethodPost, "/api/desktopclasses", string(body)) + wantStatus(t, rec, http.StatusOK) + want := "apiVersion: vdi.desku.be/v1alpha1\nkind: VdiClass\nmetadata:\n name: desktop\nspec:\n idleTimeout: 1h\n image: ghcr.io/epheo/deskube-desktop:main\n" + v := decodeBody[model.DraftView](t, rec) + if !slices.ContainsFunc(v.Items, func(it model.DraftItem) bool { return it.Kind == "create" && it.YAML == want }) { + t.Fatalf("staged %+v, want the class:\n%s", v.Items, want) + } + rec = do(s, "classes", http.MethodPost, "/api/desktopclasses?dryRun=true", string(body)) + wantStatus(t, rec, http.StatusOK) + if p := decodeBody[model.StagePreview](t, rec); p.Project != "platform" { + t.Errorf("the class goes to %q, want the platform repo", p.Project) + } +} + +// The desktops guard reads as the worse of its policy and its binding. +func TestDesktopsGuardIsTheWorseOfItsPair(t *testing.T) { + for _, c := range []struct { + pair []adminobjects.State + want string + }{ + {[]adminobjects.State{adminobjects.Installed, adminobjects.Installed}, "Installed"}, + {[]adminobjects.State{adminobjects.Installed, adminobjects.Outdated}, "Outdated"}, + {[]adminobjects.State{adminobjects.Outdated, adminobjects.NotInstalled}, "NotInstalled"}, + {[]adminobjects.State{adminobjects.NotInstalled, adminobjects.Installed}, "NotInstalled"}, + } { + got := "" + for _, s := range c.pair { + got = worseState(got, s) + } + if got != c.want { + t.Errorf("%v = %q, want %q", c.pair, got, c.want) + } + } +} diff --git a/internal/api/routes.go b/internal/api/routes.go index 470b2f3b0..b939a9787 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -155,6 +155,10 @@ func (s *Server) routes(mux *http.ServeMux) { s.notRunning(desktops.GVRInstance, "desktop"))) mux.HandleFunc("POST /api/desktopclasses", s.platformCreate(model.KindVdiClass, draft.ResourceDesktopClass, s.notRunning(desktops.GVRClass, "desktop class"))) + // Who a pool's or a desktop's form offers: the project's grants in + // git, and the cluster's users and groups, searched on typing. + mux.HandleFunc("GET /api/people", s.handlePeople) + mux.HandleFunc("GET /api/people/search", s.handlePeopleSearch) } if s.replication != nil { mux.HandleFunc("GET /api/storage/replication", s.handleReplication) diff --git a/internal/changeset/grants.go b/internal/changeset/grants.go new file mode 100644 index 000000000..3bb1685ff --- /dev/null +++ b/internal/changeset/grants.go @@ -0,0 +1,97 @@ +package changeset + +import ( + "bytes" + "cmp" + "slices" + + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + + "github.com/epheo/dotvirt/internal/git" + "github.com/epheo/dotvirt/internal/model" + "github.com/epheo/dotvirt/internal/netgen" + "github.com/epheo/dotvirt/internal/project" +) + +// Grant is one RoleBinding the platform repo declares in a namespace: the +// role it binds, and to whom. +type Grant struct { + Namespace string + Name string + Role string + Subjects []netgen.Subject +} + +// Grants are the RoleBindings commitProj, the platform repo, declares on its +// base branch in each of namespaces, by namespace then name: the admin grant, +// the persona grants and the ones following it alike. Read from git alone, +// and parsed once per head. +func (c *Coordinator) Grants(commitProj project.ProjectInfo, namespaces []string) ([]Grant, error) { + read, err := c.read(commitProj) + if err != nil { + return nil, err + } + all, err := git.Memoized(read, "grants", c.baseBranch, func() (map[string][]Grant, error) { + idx, err := indexDeclared(read, c.baseBranch) + if err != nil { + return nil, err + } + files := map[string]bool{} + for ref, path := range idx.Files { + if ref.Kind == model.KindRB.Kind && ref.Namespace != "" { + files[path] = true + } + } + out := map[string][]Grant{} + for path := range files { + content, err := read.FileOnBranch(c.baseBranch, path) + if err != nil { + return nil, err + } + for _, g := range declaredGrants(content) { + // The file the index keeps for a binding two files declare. + if idx.Files[model.ObjectRef{Kind: model.KindRB.Kind, Namespace: g.Namespace, Name: g.Name}] == path { + out[g.Namespace] = append(out[g.Namespace], g) + } + } + } + for _, gs := range out { + slices.SortFunc(gs, func(a, b Grant) int { return cmp.Compare(a.Name, b.Name) }) + } + return out, nil + }) + if err != nil { + return nil, err + } + var out []Grant + for _, ns := range namespaces { + out = append(out, all[ns]...) + } + return out, nil +} + +// declaredGrants are the namespaced RoleBindings content declares, up to a +// document that does not parse. +func declaredGrants(content []byte) []Grant { + var out []Grant + dec := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(content), 4096) + for { + var rb struct { + Kind string `json:"kind"` + Metadata struct { + Name string `json:"name"` + Namespace string `json:"namespace"` + } `json:"metadata"` + RoleRef struct { + Name string `json:"name"` + } `json:"roleRef"` + Subjects []netgen.Subject `json:"subjects"` + } + if err := dec.Decode(&rb); err != nil { + return out + } + if rb.Kind == model.KindRB.Kind && rb.Metadata.Namespace != "" { + out = append(out, Grant{Namespace: rb.Metadata.Namespace, Name: rb.Metadata.Name, Role: rb.RoleRef.Name, Subjects: rb.Subjects}) + } + } +} diff --git a/internal/cluster/people.go b/internal/cluster/people.go new file mode 100644 index 000000000..18234d43c --- /dev/null +++ b/internal/cluster/people.go @@ -0,0 +1,47 @@ +package cluster + +import ( + "context" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/epheo/dotvirt/internal/model" +) + +// OpenShift keeps its users and groups as objects (user.openshift.io); other +// clusters name them only in tokens and bindings. +var ( + GVRUsers = schema.GroupVersionResource{Group: "user.openshift.io", Version: "v1", Resource: "users"} + GVRGroups = schema.GroupVersionResource{Group: "user.openshift.io", Version: "v1", Resource: "groups"} +) + +// People lists the cluster's users, or its groups with each one's member +// count, on the caller's client: one list. +func (c *Client) People(ctx context.Context, kind string) ([]model.Person, error) { + dyn, err := c.dynamic() + if err != nil { + return nil, err + } + gvr := GVRUsers + if kind == "Group" { + gvr = GVRGroups + } + list, err := dyn.Resource(gvr).List(ctx, metav1.ListOptions{}) + if err != nil { + return nil, err + } + out := make([]model.Person, 0, len(list.Items)) + for _, o := range list.Items { + p := model.Person{Kind: kind, Name: o.GetName()} + if kind == "Group" { + users, _, _ := unstructured.NestedStringSlice(o.Object, "users") + p.Members = new(len(users)) + } else { + p.FullName, _, _ = unstructured.NestedString(o.Object, "fullName") + } + out = append(out, p) + } + return out, nil +} diff --git a/internal/model/caps.go b/internal/model/caps.go index 64fc73f58..0520f1019 100644 --- a/internal/model/caps.go +++ b/internal/model/caps.go @@ -264,6 +264,10 @@ type AdminObjects struct { ArgoController string `json:"argoController"` Images []string `json:"images"` Objects []AdminObject `json:"objects"` + // DesktopsGuard is the state of the guard's policy keeping Argo CD's + // controllers from writing desktops, the worse of it and its binding's: + // until Installed, no repo declares a pool or a desktop. + DesktopsGuard string `json:"desktopsGuard,omitempty"` } // AdminObject is one of them, as read under the caller's token. diff --git a/internal/model/desktop.go b/internal/model/desktop.go index a2c2dd656..dfdef79c6 100644 --- a/internal/model/desktop.go +++ b/internal/model/desktop.go @@ -231,3 +231,13 @@ type DesktopClassCreate struct { Image string `json:"image"` IdleTimeout string `json:"idleTimeout,omitempty"` } + +const ( + // FirstDesktopClassName, its image and idle timeout are the class a form + // offers in one click where none exists: DeskuBe's own, as its README's + // Classes section and config/samples/vdi_v1alpha1_vdiclass.yaml declare + // it. dotvirt names no image of its own. + FirstDesktopClassName = "desktop" + FirstDesktopClassImage = "ghcr.io/epheo/deskube-desktop:main" + FirstDesktopClassIdle = "1h" +) diff --git a/internal/model/people.go b/internal/model/people.go new file mode 100644 index 000000000..34af5b72b --- /dev/null +++ b/internal/model/people.go @@ -0,0 +1,40 @@ +package model + +// People is GET /api/people?namespace=: who a pool's or a desktop's form +// offers, picked rather than typed. +type People struct { + // Project are the users and groups the platform repo grants in the + // project's namespaces, each namespace's told only to a caller who may + // list its role bindings, as kubectl would show them. + Project []Person `json:"project"` + // Unseen are the project's namespaces whose grants the caller may not + // list. + Unseen []string `json:"unseen,omitempty"` + // Users and Groups: the cluster serves that kind (OpenShift's + // user.openshift.io) and the caller may list it, so a search finds it. + // Elsewhere a name is typed, and nothing checks it. + Users bool `json:"users"` + Groups bool `json:"groups"` +} + +// Person is one User or Group. +type Person struct { + Kind string `json:"kind"` // User | Group + Name string `json:"name"` + // FullName is a user's, where the cluster keeps one. + FullName string `json:"fullName,omitempty"` + // Roles are those the project grants it, the widest first. + Roles []string `json:"roles,omitempty"` + // Members is a group's member count, where the caller may list groups. + Members *int `json:"members,omitempty"` +} + +// PeopleFound is GET /api/people/search?q=&kind=: the users and groups whose +// name holds q, at most PeopleCap of them, More saying others match too. +type PeopleFound struct { + Found []Person `json:"found"` + More bool `json:"more,omitempty"` +} + +// PeopleCap is the most a search answers. +const PeopleCap = 20 diff --git a/web/src/lib/model.gen.ts b/web/src/lib/model.gen.ts index 63b88ad9d..f964ea3b2 100644 --- a/web/src/lib/model.gen.ts +++ b/web/src/lib/model.gen.ts @@ -410,6 +410,12 @@ export interface AdminObjects { argoController: string; images: string[]; objects: AdminObject[]; + /** + * DesktopsGuard is the state of the guard's policy keeping Argo CD's + * controllers from writing desktops, the worse of it and its binding's: + * until Installed, no repo declares a pool or a desktop. + */ + desktopsGuard?: string; } /** * AdminObject is one of them, as read under the caller's token. @@ -727,6 +733,15 @@ export interface DesktopClassCreate { image: string; idleTimeout?: string; } +/** + * FirstDesktopClassName, its image and idle timeout are the class a form + * offers in one click where none exists: DeskuBe's own, as its README's + * Classes section and config/samples/vdi_v1alpha1_vdiclass.yaml declare + * it. dotvirt names no image of its own. + */ +export const FirstDesktopClassName = "desktop"; +export const FirstDesktopClassImage = "ghcr.io/epheo/deskube-desktop:main"; +export const FirstDesktopClassIdle = "1h"; ////////// // source: draft.go @@ -1973,6 +1988,65 @@ export interface StorageClass { default?: boolean; // the cluster's default class annotation } +////////// +// source: people.go + +/** + * People is GET /api/people?namespace=: who a pool's or a desktop's form + * offers, picked rather than typed. + */ +export interface People { + /** + * Project are the users and groups the platform repo grants in the + * project's namespaces, each namespace's told only to a caller who may + * list its role bindings, as kubectl would show them. + */ + project: Person[]; + /** + * Unseen are the project's namespaces whose grants the caller may not + * list. + */ + unseen?: string[]; + /** + * Users and Groups: the cluster serves that kind (OpenShift's + * user.openshift.io) and the caller may list it, so a search finds it. + * Elsewhere a name is typed, and nothing checks it. + */ + users: boolean; + groups: boolean; +} +/** + * Person is one User or Group. + */ +export interface Person { + kind: string; // User | Group + name: string; + /** + * FullName is a user's, where the cluster keeps one. + */ + fullName?: string; + /** + * Roles are those the project grants it, the widest first. + */ + roles?: string[]; + /** + * Members is a group's member count, where the caller may list groups. + */ + members?: number /* int */; +} +/** + * PeopleFound is GET /api/people/search?q=&kind=: the users and groups whose + * name holds q, at most PeopleCap of them, More saying others match too. + */ +export interface PeopleFound { + found: Person[]; + more?: boolean; +} +/** + * PeopleCap is the most a search answers. + */ +export const PeopleCap = 20; + ////////// // source: policy.go From aed1105be36a515d6446d65d57c6d4ff149744d0 Mon Sep 17 00:00:00 2001 From: Thibaut Lapierre Date: Mon, 30 Nov 2026 10:42:47 +0100 Subject: [PATCH 5/9] desktops: people picked, a first class in one click, Stage's one reason Assisted by LLM --- docs/personas.md | 3 + web/e2e/fixture/scenarios.mjs | 81 ++++++ web/e2e/fixture/server.mjs | 40 ++- web/e2e/ui/a11y.spec.ts | 8 +- web/e2e/ui/desktopscreate.spec.ts | 23 +- web/e2e/ui/desktopsingit.spec.ts | 2 + web/e2e/ui/desktopspeople.spec.ts | 205 +++++++++++++ web/src/lib/api.ts | 10 + web/src/lib/classoffer.svelte.ts | 46 +++ .../lib/components/AdminObjectsBanner.svelte | 23 +- .../create/DesktopClassField.svelte | 89 +++--- .../components/create/DesktopOneForm.svelte | 60 ++-- .../components/create/DesktopPoolForm.svelte | 99 ++++--- .../create/DesktopsGuardNotice.svelte | 40 +++ .../create/DesktopsOffNotice.svelte | 31 +- .../components/create/FirstClassNotice.svelte | 49 ++++ .../lib/components/create/PeoplePicker.svelte | 272 ++++++++++++++++++ web/src/lib/desktopstage.test.ts | 38 +++ web/src/lib/desktopstage.ts | 27 ++ web/src/lib/people.test.ts | 104 +++++++ web/src/lib/people.ts | 94 ++++++ web/src/lib/platformchange.svelte.ts | 44 +++ web/src/lib/state/adminobjects.svelte.ts | 50 ++++ .../workspace/desktops/DesktopsScope.svelte | 2 + web/src/routes/+layout.svelte | 2 + 25 files changed, 1284 insertions(+), 158 deletions(-) create mode 100644 web/e2e/ui/desktopspeople.spec.ts create mode 100644 web/src/lib/classoffer.svelte.ts create mode 100644 web/src/lib/components/create/DesktopsGuardNotice.svelte create mode 100644 web/src/lib/components/create/FirstClassNotice.svelte create mode 100644 web/src/lib/components/create/PeoplePicker.svelte create mode 100644 web/src/lib/desktopstage.test.ts create mode 100644 web/src/lib/desktopstage.ts create mode 100644 web/src/lib/people.test.ts create mode 100644 web/src/lib/people.ts create mode 100644 web/src/lib/platformchange.svelte.ts create mode 100644 web/src/lib/state/adminobjects.svelte.ts diff --git a/docs/personas.md b/docs/personas.md index 0975e6bdb..8930d7d67 100644 --- a/docs/personas.md +++ b/docs/personas.md @@ -147,6 +147,9 @@ A class's file goes to who may create classes; its apply error too, the other cl Adopting one asks create or update on its kind, and a repo that may declare it; until then a caller who could is told what holds it back. A new pool, or a desktop made one by one, is staged as a file of its own from its project's Desktops page, by whoever may create its kind there; a new class goes to the platform repo, by who may create classes. Each form says what DeskuBe would refuse before it sends, and refuses a name git declares or the cluster runs: its page changes that one. +A pool's subjects and a desktop's owner are picked, first from whom the platform repo grants in the project's namespaces, each namespace's shown to who may list its role bindings there. +A typed name searches the cluster's users and groups under the caller's own token, where the cluster serves them (OpenShift's `user.openshift.io`) and the caller may list them; elsewhere the name is typed, and dotvirt cannot check it. +Where the caller reads no class, a class author adds DeskuBe's own sample class, `desktop`, in one click; the others are told who can. No route deletes one, and no one adopts a pool's desktop. Staging one refuses, by field, what DeskuBe would refuse at sync: an owner git holds changed or removed, a pool's name, labels or owner reference, a restart request, and DeskuBe's rules on the spec, a class's included; restoring a version drops a restart it carried. A desktop's owner, and a pool's subjects, that git or the cluster does not hold yet ask their writer for what DeskuBe asks of whoever grants them: the project's account, which applies them, holds it all. diff --git a/web/e2e/fixture/scenarios.mjs b/web/e2e/fixture/scenarios.mjs index bd706f754..e28cdd584 100644 --- a/web/e2e/fixture/scenarios.mjs +++ b/web/e2e/fixture/scenarios.mjs @@ -2403,12 +2403,38 @@ const deskube = { ], unlisted: [{ namespace: 'batch-prod', resource: 'vdiinstances' }], }; +// Whom team-web grants in the platform repo, and the cluster's users and +// groups, which this caller may search. +const deskPeople = { + default: { + project: [ + { kind: 'Group', name: 'designers', roles: ['edit'], members: 4 }, + { kind: 'Group', name: 'web-admins', roles: ['admin'], members: 2 }, + { kind: 'User', name: 'alice', roles: ['admin'] }, + { kind: 'User', name: 'dana', roles: ['edit'] }, + ], + users: true, + groups: true, + }, +}; +const clusterPeople = [ + { kind: 'User', name: 'alice', fullName: 'Alice Martin' }, + { kind: 'User', name: 'carla', fullName: 'Carla Diaz' }, + { kind: 'User', name: 'carol', fullName: 'Carol Chen' }, + { kind: 'User', name: 'dana', fullName: 'Dana Ruiz' }, + { kind: 'User', name: 'oscar', fullName: 'Oscar Carver' }, + { kind: 'Group', name: 'cad-team', members: 3 }, + { kind: 'Group', name: 'designers', members: 4 }, + { kind: 'Group', name: 'ops', members: 1 }, +]; const desktops = { ...base, name: 'desktops', modules: { desktops: true }, inventory: { ...base.inventory, desktopsVersion: 1 }, desktops: deskube, + people: deskPeople, + clusterPeople, }; // A project persona: pools and claims where it may list them, never desktops // nor classes; in db-prod it may list nothing. @@ -2604,6 +2630,57 @@ const desktopsgitheld = { // A caller who writes pools and desktops in web-prod and may bind no one // there: a new owner or new subjects ask what it lacks. const desktopsunbound = { ...desktopsgit, name: 'desktopsunbound', desktopsUnbound: ['web-prod'] }; +// A cluster that keeps no user or group objects: whom the project grants is +// still read from git, and any other name is typed. +const desktopspeoplefree = { + ...desktopsgit, + name: 'desktopspeoplefree', + people: { default: { ...deskPeople.default, users: false, groups: false } }, +}; +// No class yet, to a class author. +const desktopsnoclass = { + ...desktopsgit, + name: 'desktopsnoclass', + desktops: { ...deskubeGit, classes: [] }, +}; +// No class yet, to a project admin who may not add one. +const desktopsnoclasstenant = { + ...desktopsnoclass, + name: 'desktopsnoclasstenant', + capabilities: { cluster: { desktopClass: { create: false, update: false, delete: false } } }, +}; +// A cluster admin on an install whose desktops guard is out of date, so +// Argo CD applies no desktop as the project's own account. +const desktopsguardstale = { + ...desktopsgitheld, + name: 'desktopsguardstale', + capabilities: { ...desktopsgitheld.capabilities, cluster: { adminObjects: true } }, + adminObjects: { + operator: 'system:serviceaccount:dotvirt-operator:dotvirt-operator-controller', + namespace: 'dotvirt', + argoNamespace: 'openshift-gitops', + argoController: 'openshift-gitops-argocd-application-controller', + images: [], + desktopsGuard: 'Outdated', + objects: [ + { + purpose: "Bounds Argo CD's application controllers", + kind: 'ValidatingAdmissionPolicy', + name: 'dotvirt-argo-desktops', + state: 'Outdated', + detail: 'ValidatingAdmissionPolicy dotvirt-argo-desktops was rendered by another version', + object: guardObject('ValidatingAdmissionPolicy', 'dotvirt-argo-desktops'), + }, + { + purpose: 'Enforces dotvirt-argo-desktops', + kind: 'ValidatingAdmissionPolicyBinding', + name: 'dotvirt-argo-desktops', + state: 'Installed', + object: guardObject('ValidatingAdmissionPolicyBinding', 'dotvirt-argo-desktops'), + }, + ], + }, +}; // de, a desktop git declares in web-prod that Argo CD could not create, and // design, a pool it has not applied yet. @@ -2951,6 +3028,10 @@ export const scenarios = { desktopsgitviewer, desktopsgitheld, desktopsunbound, + desktopspeoplefree, + desktopsnoclass, + desktopsnoclasstenant, + desktopsguardstale, desktopsoff, desktopsoffproposed, desktopsoffadmin, diff --git a/web/e2e/fixture/server.mjs b/web/e2e/fixture/server.mjs index a51eaf866..1fc14e29c 100644 --- a/web/e2e/fixture/server.mjs +++ b/web/e2e/fixture/server.mjs @@ -709,10 +709,12 @@ async function handleAPI(req, res, url) { 'forbidden: installing what the install needs takes a cluster admin', ); // Install applies the render; a stale object stays, to remove by hand. - if (req.method === 'POST') + if (req.method === 'POST') { s.adminObjects.objects = s.adminObjects.objects.map((o) => o.state === 'Stale' ? o : { ...o, state: 'Installed', detail: '' }, ); + if (s.adminObjects.desktopsGuard) s.adminObjects.desktopsGuard = 'Installed'; + } return sendJSON(res, 200, s.adminObjects); } if (path === '/api/inventory') return sendJSON(res, 200, s.inventory); @@ -739,6 +741,7 @@ async function handleAPI(req, res, url) { const none = { synced: true, classes: [], pools: [], desktops: [], claims: [], unlisted: [] }; return sendJSON(res, 200, { inGit: [], ...(s.desktops ?? none) }); } + if (path === '/api/people' || path === '/api/people/search') return handlePeople(res, url, s); if (path === '/api/storage/replication') return sendJSON(res, 200, s.replication); if (path === '/api/storage/protection') return sendJSON(res, 200, s.protection ?? []); if (path === '/api/networks') return sendJSON(res, 200, s.networks); @@ -1416,6 +1419,41 @@ async function handleRepair(req, res, path, url, s) { return false; } +// Whom a namespace's project grants (GET /api/people), and the cluster's +// users and groups (GET /api/people/search), as the Go routes answer them: +// the scenario's people says what the project grants and which kinds the +// caller may search; a search refuses any other kind, and finds by name or +// full name, the exact name first, then one starting with what was typed, +// at most 20. +function handlePeople(res, url, s) { + const none = { project: [], users: false, groups: false }; + const people = (ns) => s.people?.[ns] ?? s.people?.default ?? none; + if (url.pathname === '/api/people') { + const ns = url.searchParams.get('namespace'); + if (!ns) return sendText(res, 400, 'invalid request: name the namespace'); + if (!projectOf(ns)) return sendText(res, 404, 'namespace not found in any visible project'); + return sendJSON(res, 200, people(ns)); + } + const q = (url.searchParams.get('q') ?? '').trim().toLowerCase(); + if (!q) return sendText(res, 400, 'invalid request: type part of a name'); + const kinds = url.searchParams.getAll('kind'); + const asked = kinds.length ? kinds : ['User', 'Group']; + const may = people(''); + for (const k of asked) + if (!(k === 'User' ? may.users : may.groups)) + return sendText(res, 403, `forbidden: you may not list ${k.toLowerCase()}s`); + const rank = (p) => { + const name = p.name.toLowerCase(); + if (name === q) return 0; + if (name.startsWith(q)) return 1; + return name.includes(q) || p.fullName?.toLowerCase().includes(q) ? 2 : -1; + }; + const hits = (s.clusterPeople ?? []) + .filter((p) => asked.includes(p.kind) && rank(p) >= 0) + .sort((a, b) => rank(a) - rank(b) || a.name.localeCompare(b.name)); + return sendJSON(res, 200, { found: hits.slice(0, 20), more: hits.length > 20 || undefined }); +} + // A desktop act (POST /api/desktops/{namespace}/{name}/{act}), refused as the // server refuses it: while a watch it reads is down, on another desktop or // claim than the one the caller saw (by name and UID), on a claim not diff --git a/web/e2e/ui/a11y.spec.ts b/web/e2e/ui/a11y.spec.ts index cc456602e..ff59c54f0 100644 --- a/web/e2e/ui/a11y.spec.ts +++ b/web/e2e/ui/a11y.spec.ts @@ -93,12 +93,14 @@ test('the desktop create sheet is accessible, its refusals said', async ({ page await page.goto('/desktops/team-web/web-prod'); await page.locator('main').getByRole('button', { name: 'New pool' }).click(); const sheet = page.getByRole('dialog'); - await sheet.getByRole('button', { name: 'Add who may claim' }).click(); await sheet.getByLabel('Warm', { exact: true }).fill('3'); await expect(sheet.getByText(/Warm cannot exceed seats/).first()).toBeVisible(); - await checkA11y(page, 'pool sheet'); + await sheet.getByLabel('Who may claim one', { exact: true }).click(); + await sheet.getByRole('button', { name: 'Add group designers' }).click(); + await expect(sheet.getByRole('button', { name: 'Remove designers' })).toBeVisible(); + await checkA11y(page, 'pool sheet, its people picker open'); await sheet.locator('input[name="desktop-kind"][value="desktop"]').check(); - await expect(sheet.getByLabel('Owner (optional)')).toBeVisible(); + await expect(sheet.getByLabel('Owner', { exact: true })).toBeVisible(); await checkA11y(page, 'desktop sheet'); await sheet.locator('input[name="desktop-kind"][value="class"]').check(); await page.evaluate(() => (document.documentElement.dataset.theme = 'dark')); diff --git a/web/e2e/ui/desktopscreate.spec.ts b/web/e2e/ui/desktopscreate.spec.ts index ab0ca2432..039989bc6 100644 --- a/web/e2e/ui/desktopscreate.spec.ts +++ b/web/e2e/ui/desktopscreate.spec.ts @@ -26,7 +26,7 @@ test('a pool is made from its project, what DeskuBe refuses said first', async ( s.getByText(/A DNS label that starts with a letter, 40 characters/).first(), ).toBeVisible(); await s.getByLabel('Name', { exact: true }).fill('design'); - await s.getByLabel('Class', { exact: true }).fill('office'); + await s.getByLabel('Class', { exact: true }).selectOption('office'); await s.getByLabel('Seats', { exact: true }).fill('2'); await s.getByLabel('Warm', { exact: true }).fill('3'); await expect(s.getByText(/Warm cannot exceed seats/).first()).toBeVisible(); @@ -46,8 +46,8 @@ test('a pool is made from its project, what DeskuBe refuses said first', async ( await expect(stage).toBeDisabled(); await s.getByRole('radio', { name: /^Personal/ }).check(); - await s.getByRole('button', { name: 'Add who may claim' }).click(); - await s.getByLabel('Who may claim 1, name').fill('designers'); + await s.getByLabel('Who may claim one', { exact: true }).click(); + await s.getByRole('button', { name: 'Add group designers' }).click(); await expect(s.getByText('web-prod/desktop-pools/design.yaml')).toBeVisible(); await s.getByRole('button', { name: 'Show YAML' }).click(); await expect(s.getByLabel('YAML of web-prod/desktop-pools/design.yaml')).toContainText( @@ -84,10 +84,12 @@ test('a desktop says its owner is set once, and is made of a class or an image', ).toBeVisible(); const stage = s.getByRole('button', { name: 'Stage desktop' }); + await expect(s.getByRole('status')).toHaveText('Pick its owner'); + await s.getByLabel('Owner', { exact: true }).click(); + await s.getByRole('button', { name: 'Pick user dana' }).click(); await s.getByLabel('Name', { exact: true }).fill('carol-dev'); await expect(s.getByText('carol-dev is taken in web-prod')).toBeVisible(); await s.getByLabel('Name', { exact: true }).fill('dana-dev'); - await s.getByLabel('Owner (optional)').fill('dana'); await expect(s.getByText('A desktop is made of a class or an image.')).toBeVisible(); await expect(stage).toBeDisabled(); await s.getByLabel('An image').check(); @@ -114,16 +116,17 @@ test('an owner set by who may bind no one is refused, naming the right', async ( await page.locator('main').getByRole('button', { name: 'New desktop' }).click(); const s = sheet(page); await s.getByLabel('Name', { exact: true }).fill('dana-dev'); - await s.getByLabel('Owner (optional)').fill('dana'); - await s.getByLabel('Class', { exact: true }).fill('office'); + await s.getByLabel('Owner', { exact: true }).click(); + await s.getByRole('button', { name: 'Pick user dana' }).click(); + await s.getByLabel('Class', { exact: true }).selectOption('office'); await s.getByRole('button', { name: 'Stage desktop' }).click(); await expect(s.getByText(/you may not create rolebindings in web-prod/)).toBeVisible(); await expect(s).toBeVisible(); - // Without an owner it grants nothing, and stages. - await s.getByLabel('Owner (optional)').fill(''); - await s.getByRole('button', { name: 'Stage desktop' }).click(); - await expect(page.getByText(/Staged into Changes/)).toBeVisible(); + // The owner is picked, never left out: without one, Stage waits on it. + await s.getByRole('button', { name: 'Remove dana' }).click(); + await expect(s.getByRole('status')).toHaveText('Pick its owner'); + await expect(s.getByRole('button', { name: 'Stage desktop' })).toBeDisabled(); }); test('a class is made by a class author, in the platform repo', async ({ page }) => { diff --git a/web/e2e/ui/desktopsingit.spec.ts b/web/e2e/ui/desktopsingit.spec.ts index bc754d6f0..063f51b18 100644 --- a/web/e2e/ui/desktopsingit.spec.ts +++ b/web/e2e/ui/desktopsingit.spec.ts @@ -180,6 +180,8 @@ test('once desktops are on, a desktop Argo CD gave up on is resynced from its pa await expect(main(page).getByText('Argo CD has not applied it yet.')).toBeVisible(); await page.getByRole('button', { name: 'New', exact: true }).click(); const sheet = page.getByRole('dialog'); + await sheet.getByLabel('Who may claim one', { exact: true }).click(); + await sheet.getByRole('button', { name: 'Add group designers' }).click(); await sheet.getByLabel('Name', { exact: true }).fill('design'); await expect(sheet.getByRole('status')).toHaveText('design is taken in web-prod'); }); diff --git a/web/e2e/ui/desktopspeople.spec.ts b/web/e2e/ui/desktopspeople.spec.ts new file mode 100644 index 000000000..a4c51bbdd --- /dev/null +++ b/web/e2e/ui/desktopspeople.spec.ts @@ -0,0 +1,205 @@ +import { expect, login, setScenario, test } from './fx'; +import type { Page, Request } from '@playwright/test'; + +// Who may claim a pool, and a desktop's owner, are picked: whom the project +// grants in git first, then the cluster's users and groups as a name is +// typed, where the cluster serves them and the caller may list them, else a +// typed name said unchecked. With no class yet, a class author adds +// DeskuBe's own in one click. Stage says one reason when it waits: the +// guard, the place, a class, who, then the fields. + +const sheet = (page: Page) => page.getByRole('dialog'); +const posted = (page: Page, path: string) => + page.waitForRequest( + (r) => + r.method() === 'POST' && new URL(r.url()).pathname === path && !r.url().includes('dryRun'), + ); +const searches = (page: Page) => { + const seen: Request[] = []; + page.on('request', (r) => { + if (new URL(r.url()).pathname === '/api/people/search') seen.push(r); + }); + return seen; +}; + +async function newPool(page: Page) { + await page.goto('/desktops/team-web'); + await page.locator('main').getByRole('button', { name: 'New pool' }).click(); + await expect(sheet(page).getByRole('heading', { name: 'New desktop pool' })).toBeVisible(); + return sheet(page); +} + +test('who may claim one is picked from the project, then the cluster, as chips', async ({ + page, +}) => { + await setScenario(page, 'desktopsgit'); + await login(page); + const asked = searches(page); + const s = await newPool(page); + + const who = s.getByLabel('Who may claim one', { exact: true }); + await who.click(); + const project = s.getByRole('list', { name: 'In this project' }); + await expect(project.getByRole('button')).toHaveText([ + /designers\s*4 members, edit/, + /web-admins\s*2 members, admin/, + /alice\s*admin/, + /dana\s*edit/, + ]); + await s.getByRole('button', { name: 'Add group designers' }).click(); + const picked = s.getByRole('list', { name: 'Who may claim one: picked' }); + await expect(picked.getByRole('listitem')).toHaveText([/designers\s*4 members/]); + await expect(project.getByRole('button', { name: 'Add group designers' })).toHaveCount(0); + + // A burst of keys asks the cluster once, the closest names first. + await who.pressSequentially('car', { delay: 20 }); + const elsewhere = s.getByRole('list', { name: 'Elsewhere on the cluster' }); + await expect(elsewhere.getByRole('button')).toHaveText([ + /carla\s*Carla Diaz/, + /carol\s*Carol Chen/, + /oscar\s*Oscar Carver/, + ]); + expect(asked.map((r) => new URL(r.url()).search)).toEqual(['?q=car&kind=Group&kind=User']); + await elsewhere.getByRole('button', { name: 'Add user carol' }).click(); + await expect(who).toHaveValue(''); + await expect(picked.getByRole('listitem')).toHaveText([/designers/, /carol/]); + + await s.getByRole('button', { name: 'Remove designers' }).click(); + await expect(picked.getByRole('listitem')).toHaveText([/carol/]); + + await s.getByLabel('Name', { exact: true }).fill('design'); + await s.getByLabel('Class', { exact: true }).selectOption('office'); + const body = posted(page, '/api/desktoppools'); + await s.getByRole('button', { name: 'Stage pool' }).click(); + expect((await body).postDataJSON()).toMatchObject({ + subjects: [{ kind: 'User', name: 'carol' }], + }); + await expect(page.getByText(/Staged into Changes/)).toBeVisible(); +}); + +test("a desktop's owner is one user, a new pick replacing the last", async ({ page }) => { + await setScenario(page, 'desktopsgit'); + await login(page); + await page.goto('/desktops/team-web/web-prod'); + await page.locator('main').getByRole('button', { name: 'New desktop' }).click(); + const s = sheet(page); + const owner = s.getByLabel('Owner', { exact: true }); + await owner.click(); + await expect(s.getByRole('list', { name: 'In this project' }).getByRole('button')).toHaveText([ + /alice/, + /dana/, + ]); + await s.getByRole('button', { name: 'Pick user alice' }).click(); + await owner.fill('dan'); + await s.getByRole('button', { name: 'Pick user dana' }).click(); + const picked = s.getByRole('list', { name: 'Owner: picked' }); + await expect(picked.getByRole('listitem')).toHaveText([/dana/]); + await expect(s.getByText('dana owns it for good, and starts, stops and pairs it.')).toBeVisible(); +}); + +test('where the cluster keeps no users or groups, a name is typed and said unchecked', async ({ + page, +}) => { + await setScenario(page, 'desktopspeoplefree'); + await login(page); + const asked = searches(page); + const s = await newPool(page); + const who = s.getByLabel('Who may claim one', { exact: true }); + await who.click(); + await expect(s.getByRole('button', { name: 'Add group designers' })).toBeVisible(); + await expect( + s.getByText('Type a group or user name to add it: dotvirt cannot check this name here.'), + ).toBeVisible(); + + await who.fill('qa-team'); + await expect(s.getByText('Elsewhere on the cluster')).toHaveCount(0); + await expect(s.getByText('dotvirt cannot check this name here.', { exact: true })).toBeVisible(); + await expect(s.getByRole('list', { name: 'Typed' }).getByRole('button')).toHaveText([ + 'qa-team', + 'qa-team', + ]); + await who.press('Enter'); + await expect( + s.getByRole('list', { name: 'Who may claim one: picked' }).getByRole('listitem'), + ).toHaveText([/qa-team/]); + await expect(s.getByRole('button', { name: 'Remove qa-team' })).toBeVisible(); + expect(asked).toEqual([]); +}); + +test("with no class yet, a class author adds DeskuBe's own in one click", async ({ page }) => { + await setScenario(page, 'desktopsnoclass'); + await login(page); + const s = await newPool(page); + await expect(s.getByRole('status')).toHaveText('Add a class first'); + await expect(s.getByText('No desktop class yet.')).toBeVisible(); + + const body = posted(page, '/api/desktopclasses'); + await s.getByRole('button', { name: 'Add desktop' }).click(); + expect((await body).postDataJSON()).toEqual({ + name: 'desktop', + image: 'ghcr.io/epheo/deskube-desktop:main', + idleTimeout: '1h', + }); + await expect(s.getByLabel('Class', { exact: true })).toHaveValue('desktop'); + await expect( + s.getByText('desktop is staged in the platform draft: its desktops wait until it merges.'), + ).toBeVisible(); + await expect(s.getByRole('link', { name: 'Review and propose it' })).toHaveAttribute( + 'href', + '/changes?project=platform&item=desktopclass%3Acluster%2Fdesktop', + ); + await expect(s.getByRole('status')).toHaveText('Pick who may claim one'); +}); + +test('with no class yet, whoever may not add one is told who can', async ({ page }) => { + await setScenario(page, 'desktopsnoclasstenant'); + await login(page); + const s = await newPool(page); + await expect( + s.getByText('No desktop class yet: a platform admin adds one from Desktops, Classes.'), + ).toBeVisible(); + await expect(s.getByRole('button', { name: 'Add desktop' })).toHaveCount(0); + await expect(s.getByRole('status')).toHaveText('Add a class first'); + await expect(s.getByRole('button', { name: 'Stage pool' })).toBeDisabled(); +}); + +test('Stage says one reason, the class and who before the fields', async ({ page }) => { + await setScenario(page, 'desktopsgit'); + await login(page); + const s = await newPool(page); + const status = s.getByRole('status'); + await expect(status).toHaveText('Pick who may claim one'); + await s.getByLabel('Who may claim one', { exact: true }).click(); + await s.getByRole('button', { name: 'Add group designers' }).click(); + await expect(status).toHaveText('Name the pool'); + await s.getByLabel('Name', { exact: true }).fill('design'); + await expect(status).toHaveText('Name the class its desktops are made of.'); + await s.getByLabel('Class', { exact: true }).selectOption('cad'); + await expect(status).toHaveCount(0); + await expect(s.getByRole('button', { name: 'Stage pool' })).toBeEnabled(); +}); + +test('a stale guard comes first, reinstalled from the form in one click', async ({ page }) => { + await setScenario(page, 'desktopsguardstale'); + await login(page); + await page.goto('/desktops/team-web/web-prod'); + await expect(page.locator('main').getByText(/The operator guard is out of date/)).toBeVisible(); + await page.getByRole('button', { name: 'New', exact: true }).click(); + const s = sheet(page); + await expect(s.getByRole('heading', { name: 'New desktop pool' })).toBeVisible(); + await expect(s.getByRole('status')).toHaveText('Reinstall the guard first'); + await expect(s.getByText(/The operator guard is out of date/)).toBeVisible(); + + const install = posted(page, '/api/admin-objects'); + await s.getByRole('button', { name: 'Reinstall the guard' }).click(); + await install; + await expect(s.getByText(/The operator guard is out of date/)).toHaveCount(0); + // Then what still holds desktops back: the operator's next pass. + await expect(s.getByRole('status')).toHaveText( + /Argo CD does not apply desktops as their project's own account yet/, + ); + await sheet(page).locator('input[name="desktop-kind"][value="desktop"]').check(); + await expect(s.getByRole('status')).toHaveText( + /Argo CD does not apply desktops as their project's own account yet/, + ); +}); diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index bb374437b..d9e2ff23a 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -457,6 +457,16 @@ export const api = { // The acts on one desktop in namespace, and on claim, the claim holding it. desktopCapabilities: (namespace: string, desktop: string, claim = '') => get(`/api/capabilities${qs({ desktops: namespace, desktop, claim })}`), + // Whom namespace's project grants in git, and which kinds the cluster + // search finds: no cluster read beyond cached reviews. + people: (namespace: string) => get(`/api/people${qs({ namespace })}`), + // The cluster's users and groups of kinds whose name holds q, read under + // the caller's own token. + peopleSearch: (q: string, kinds: string[]) => { + const p = new URLSearchParams({ q }); + for (const k of kinds) p.append('kind', k); + return get(`/api/people/search?${p}`); + }, // Where every copy lives: answers only a caller who may list r-drbd's kinds. replication: () => get('/api/storage/replication'), // The standing of the caller's replicated disks, with no host named. diff --git a/web/src/lib/classoffer.svelte.ts b/web/src/lib/classoffer.svelte.ts new file mode 100644 index 000000000..981282e57 --- /dev/null +++ b/web/src/lib/classoffer.svelte.ts @@ -0,0 +1,46 @@ +import { CLASS_FIRST } from '#lib/desktopstage.js'; +import { CLUSTER_NS } from '#lib/gates.js'; +import { FirstDesktopClassName } from '#lib/model.gen.js'; +import { platformChange } from '#lib/platformchange.svelte.js'; +import { desktops } from '#lib/state/desktops.svelte.js'; + +// The classes a new pool's or desktop's form picks from: those the caller +// reads, by name, or null where it may not list them. Where it reads none, +// DeskuBe's own may be on its way, staged in the caller's platform draft or +// proposed in their PR: a pool or a desktop may name it already, as DeskuBe +// makes its desktops once the class exists. Call during component init. +export function classOffer() { + const known = $derived( + desktops.value?.synced && desktops.may?.classes + ? desktops.value.classes.map((c) => c.name) + : null, + ); + const empty = $derived(known?.length === 0); + const first = platformChange( + () => ({ resource: 'desktopclass', namespace: CLUSTER_NS, name: FirstDesktopClassName }), + () => empty, + ); + const coming = $derived(empty && (first.staged || !!first.proposed)); + return { + // What the Class picker lists; null types a name instead. + get names(): string[] | null { + return coming ? [FirstDesktopClassName] : known; + }, + // No class to pick, nor one on its way. + get none(): boolean { + return empty && !coming; + }, + // None to pick but DeskuBe's own, staged or proposed. + get coming(): boolean { + return coming; + }, + get first() { + return first; + }, + get reason(): string { + return empty && !coming ? CLASS_FIRST : ''; + }, + }; +} + +export type ClassOffer = ReturnType; diff --git a/web/src/lib/components/AdminObjectsBanner.svelte b/web/src/lib/components/AdminObjectsBanner.svelte index f4c737859..dac5fbd98 100644 --- a/web/src/lib/components/AdminObjectsBanner.svelte +++ b/web/src/lib/components/AdminObjectsBanner.svelte @@ -1,8 +1,8 @@ -{#if allowed && objects.data && pending.length} - {@const d = objects.data} +{#if objects && pending.length} + {@const d = objects} diff --git a/web/src/lib/components/create/DesktopClassField.svelte b/web/src/lib/components/create/DesktopClassField.svelte index 28e19eb25..4fef0a270 100644 --- a/web/src/lib/components/create/DesktopClassField.svelte +++ b/web/src/lib/components/create/DesktopClassField.svelte @@ -1,46 +1,71 @@
    - - {#if known} - - {#each known as c (c)}{/each} - - {/if} - {#if absent} - - No class {value} yet: its desktops wait until a platform admin offers one. - - {:else if !known} + {#if names === null} + A class a platform admin offers, by name. + {:else if offer.none} + + {:else} + + {#if offer.coming && offer.first.proposed} + {@const pr = offer.first.proposed} + + {FirstDesktopClassName} is proposed in + PR #{pr.prNumber}: its + desktops wait until it merges. + + {:else if offer.coming} + + {FirstDesktopClassName} is staged in the platform draft: its desktops wait until it merges. + + Review and propose it + + + {/if} {/if}
    diff --git a/web/src/lib/components/create/DesktopOneForm.svelte b/web/src/lib/components/create/DesktopOneForm.svelte index b7f4c6e61..2881aa713 100644 --- a/web/src/lib/components/create/DesktopOneForm.svelte +++ b/web/src/lib/components/create/DesktopOneForm.svelte @@ -1,9 +1,12 @@ + +{#if state === 'Outdated' || state === 'NotInstalled'} + {@const again = state === 'Outdated'} + + + The operator guard is {again ? 'out of date' : 'not installed'}: Argo CD applies no pool or + desktop as its project's own account until it is {again ? 'reinstalled' : 'installed'}. + + + +{/if} diff --git a/web/src/lib/components/create/DesktopsOffNotice.svelte b/web/src/lib/components/create/DesktopsOffNotice.svelte index 22294e7dd..18df57efc 100644 --- a/web/src/lib/components/create/DesktopsOffNotice.svelte +++ b/web/src/lib/components/create/DesktopsOffNotice.svelte @@ -1,13 +1,12 @@ + +{#if offer.none} + + {#if author} + No desktop class yet. + + + DeskuBe's own: {FirstDesktopClassImage}, stopping after {FirstDesktopClassIdle} + idle, staged in the platform draft. + + {:else} + No desktop class yet: a platform admin adds one from Desktops, Classes. + {/if} + +{/if} diff --git a/web/src/lib/components/create/PeoplePicker.svelte b/web/src/lib/components/create/PeoplePicker.svelte new file mode 100644 index 000000000..98f779cce --- /dev/null +++ b/web/src/lib/components/create/PeoplePicker.svelte @@ -0,0 +1,272 @@ + + +{#snippet icon(kind: string)} + {#if kind === 'Group'}
    +
    + + + Lets programs in its desktops build sandboxes of their own, as Chromium, Brave and Steam do: + each desktop runs in a user namespace of its own. + +
    {/snippet} {#snippet aside()} diff --git a/web/src/lib/components/create/DesktopOneForm.svelte b/web/src/lib/components/create/DesktopOneForm.svelte index 2881aa713..3cf7773d6 100644 --- a/web/src/lib/components/create/DesktopOneForm.svelte +++ b/web/src/lib/components/create/DesktopOneForm.svelte @@ -3,7 +3,6 @@ import { api, type DesktopCreate, type DesktopSubject } from '#lib/api.js'; import { classOffer } from '#lib/classoffer.svelte.js'; import { allDesktops } from '#lib/desktops.js'; - import { desktopRefusals } from '#lib/desktopspec.js'; import { guardReason, PICK_OWNER, stageReasons } from '#lib/desktopstage.js'; import { clusterGate, desktopGitGate, desktopPlaceHeld, desktopsOffPlace } from '#lib/gates.js'; import { adminObjects } from '#lib/state/adminobjects.svelte.js'; @@ -48,17 +47,17 @@ let name = $state(''); let owners = $state([]); - let from = $state<'class' | 'image'>('class'); let cls = $state(''); - let image = $state(''); let running = $state(true); const offer = classOffer(); + // Made of a class alone: a class carries what its image needs to run, + // which a bare image would leave unset. One made of an image is its + // manifest's, edited in place. const request = $derived.by((): DesktopCreate => { const req: DesktopCreate = { namespace, name, running }; if (owners.length) req.owner = owners[0].name; - if (from === 'class' && cls.trim()) req.class = cls.trim(); - if (from === 'image' && image.trim()) req.image = image.trim(); + if (cls.trim()) req.class = cls.trim(); return req; }); // A name that runs, or that git declares and the cluster does not run yet. @@ -80,11 +79,11 @@ else if (!validName(name)) fields.push('The name needs lowercase letters, digits and -'); else if (taken) fields.push(`${name} is taken in ${namespace}`); if (held === CHECKING) fields.push(held); - fields.push(...desktopRefusals(request).map((r) => r.why)); + if (!request.class) fields.push('Pick its class'); return stageReasons({ guard, place: held === CHECKING ? '' : held, - cls: from === 'class' ? offer.reason : '', + cls: offer.reason, who: request.owner ? '' : PICK_OWNER, fields, }); @@ -143,35 +142,8 @@ -
    - Made of -
    - - -
    -
    - {#if from === 'class'} - - - {:else} -
    - - -
    - {/if} + +