diff --git a/docs/personas.md b/docs/personas.md index 0975e6bd..b736bb70 100644 --- a/docs/personas.md +++ b/docs/personas.md @@ -147,6 +147,12 @@ 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. +A name the search does not find is still used on a click, marked not found: someone not signed in yet, or a group not made yet; only its syntax is checked. +Where the caller reads no class, a class author adds DeskuBe's own sample class, `desktop`, in one click, with the nested sandboxes its image's Chromium needs; the others are told who can. +The form makes a desktop of a class, which carries what its image needs; one of an image alone is written in its manifest. +Where DeskuBe says an image needs a field its class, or its manifest without one, does not set, the desktop's page opens that manifest to whoever may change it, else says 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/internal/api/api.go b/internal/api/api.go index b0b5d735..7addab14 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 4e065608..2ad515b9 100644 --- a/internal/api/fakecluster_test.go +++ b/internal/api/fakecluster_test.go @@ -760,6 +760,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), d.desktopsErr } + +// 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 09791b9d..b720a090 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 8c4fb9df..9c29d632 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 00000000..1ed75fb6 --- /dev/null +++ b/internal/api/handlers_people.go @@ -0,0 +1,264 @@ +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) + } + // A namespace hidden from the caller is never named: its grants count + // where it lists their role bindings, and nothing is said where not. + var seen []string + for i, lists := range s.capableAll(ctx, id, c, acts) { + switch n := full.Namespaces[i]; { + case lists: + seen = append(seen, n) + case slices.Contains(sc.proj.Namespaces, n): + out.Unseen = append(out.Unseen, n) + } + } + 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 00000000..95bc77eb --- /dev/null +++ b/internal/api/people_test.go @@ -0,0 +1,324 @@ +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). Every caller sees +// team-a-dev alone. lister may list team-a-dev's role bindings alone, +// prodlister team-a-prod's alone; searcher every namespace's, and the users +// and groups; outsider 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 token == "prodlister": + return bindings && a.Namespace == "team-a-prod" + 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) + // Every caller sees team-a-dev alone: team-a-prod is never named to one. + 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) + if strings.Contains(rec.Body.String(), "team-a-prod") { + t.Errorf("%s was told of a namespace hidden from it: %s", token, rec.Body.String()) + } + 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"}} + ops := model.Person{Kind: "Group", Name: "ops", Roles: []string{"edit"}} + + 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 len(got.Unseen) != 0 || got.Users || got.Groups { + t.Errorf("lister = unseen %v, users %v, groups %v; want none 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"}) { + t.Errorf("outsider = %+v, want nothing it may not list, team-a-dev unseen", got) + } + + // The role bindings of a namespace hidden from the caller still count + // where it may list them, unnamed. + if got := people("prodlister"); !peopleEqual(got.Project, []model.Person{ops}) || !slices.Equal(got.Unseen, []string{"team-a-dev"}) { + t.Errorf("prodlister = %+v, want ops and team-a-dev unseen", got) + } + + got = people("searcher") + ops.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, with the +// nested sandboxes its image's Chromium needs, 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, + NestedSandboxes: model.FirstDesktopClassNestedSandboxes}) + 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: " + model.FirstDesktopClassImage + "\n nestedSandboxes: true\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 470b2f3b..b939a978 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 00000000..3bb1685f --- /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 00000000..18234d43 --- /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/deskgen/deskgen.go b/internal/deskgen/deskgen.go index 58c62c70..86dcc5c6 100644 --- a/internal/deskgen/deskgen.go +++ b/internal/deskgen/deskgen.go @@ -68,6 +68,9 @@ func ClassManifest(s model.DesktopClassCreate) (path string, content []byte, err if s.IdleTimeout != "" { spec["idleTimeout"] = s.IdleTimeout } + if s.NestedSandboxes { + spec["nestedSandboxes"] = true + } return manifest(model.KindVdiClass, "", s.Name, spec) } diff --git a/internal/model/caps.go b/internal/model/caps.go index 5589ea9f..6d193673 100644 --- a/internal/model/caps.go +++ b/internal/model/caps.go @@ -267,6 +267,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 a2c2dd65..7e9da86f 100644 --- a/internal/model/desktop.go +++ b/internal/model/desktop.go @@ -230,4 +230,24 @@ type DesktopClassCreate struct { Name string `json:"name"` Image string `json:"image"` IdleTimeout string `json:"idleTimeout,omitempty"` + // NestedSandboxes lets programs in its desktops build sandboxes of their + // own, each desktop in a user namespace of its own (DeskuBe's + // spec.nestedSandboxes). + NestedSandboxes bool `json:"nestedSandboxes,omitempty"` } + +const ( + // FirstDesktopClassName, its idle timeout and nested sandboxes 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. Its nested sandboxes are what its image's Chromium needs, + // as DeskuBe and the deskube-images README say. + FirstDesktopClassName = "desktop" + FirstDesktopClassIdle = "1h" + FirstDesktopClassNestedSandboxes = true +) + +// FirstDesktopClassImage is DeskuBe's default desktop image, the one place +// dotvirt names it, pinned by digest. From DeskuBe 0.2.0 on it follows the +// "Desktop images tested with this release" of DeskuBe's release notes. +const FirstDesktopClassImage = "ghcr.io/epheo/deskube-desktop:sha-68b8792@sha256:0c04f573e565ddf9bbd39caee8d55f1f428dacc0b4659a1419d1bed4326df644" diff --git a/internal/model/people.go b/internal/model/people.go new file mode 100644 index 00000000..6101d426 --- /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 shown to the caller whose grants + // it may not list. One hidden from it is never named. + 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/e2e/fixture/create.mjs b/web/e2e/fixture/create.mjs index f1c81573..a26c0806 100644 --- a/web/e2e/fixture/create.mjs +++ b/web/e2e/fixture/create.mjs @@ -484,7 +484,11 @@ const ROUTES = { apiVersion: 'vdi.desku.be/v1alpha1', kind: 'VdiClass', metadata: { name: b.name }, - spec: { idleTimeout: b.idleTimeout, image: b.image }, + spec: { + idleTimeout: b.idleTimeout, + image: b.image, + nestedSandboxes: b.nestedSandboxes || undefined, + }, }), }, ]; diff --git a/web/e2e/fixture/scenarios.mjs b/web/e2e/fixture/scenarios.mjs index 669a9abd..eb6da44e 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,101 @@ 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 } }, +}; +// Images that need a class field nothing they are made of sets: carol-dev's +// class office, and brave-dev, made of an image alone. +const needsUnmet = (fields) => ({ + type: 'PodReady', + status: 'False', + reason: 'ImageNeedsUnmet', + message: `the image needs ${fields}, which its class does not set`, +}); +const desktopsneeds = { + ...desktopsgit, + name: 'desktopsneeds', + desktops: { + ...deskubeGit, + desktops: [ + ...deskubeGit.desktops.map((d) => + d.name === 'carol-dev' ? { ...d, conditions: [needsUnmet('nestedSandboxes')] } : d, + ), + desk('web-prod', 'brave-dev', { + class: undefined, + image: 'quay.io/example/desktop-brave:1', + owner: 'dana', + ...gitOf('web-prod/desktops/brave-dev.yaml'), + conditions: [needsUnmet('nestedSandboxes')], + }), + ], + }, +}; +// The same, to a project viewer. +const desktopsneedsviewer = { + ...desktopsgitviewer, + name: 'desktopsneedsviewer', + desktops: { ...desktopsneeds.desktops, classes: desktopsgitviewer.desktops.classes }, +}; +// No class yet, to a class author. +const desktopsnoclass = { + ...desktopsgit, + name: 'desktopsnoclass', + desktops: { ...deskubeGit, classes: [] }, +}; +// A project admin who may not list the classes, cluster-scoped as they are. +const desktopsclassesunread = { + ...desktopsgit, + name: 'desktopsclassesunread', + desktops: { + ...deskubeGit, + classes: [], + unlisted: [...deskubeGit.unlisted, { namespace: '', resource: 'vdiclasses' }], + }, + capabilities: { cluster: { desktopClass: { create: false, update: false, delete: false } } }, +}; +// 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. @@ -2955,6 +3076,13 @@ export const scenarios = { desktopsgitviewer, desktopsgitheld, desktopsunbound, + desktopspeoplefree, + desktopsneeds, + desktopsneedsviewer, + desktopsnoclass, + desktopsclassesunread, + desktopsnoclasstenant, + desktopsguardstale, desktopsoff, desktopsoffproposed, desktopsoffadmin, diff --git a/web/e2e/fixture/server.mjs b/web/e2e/fixture/server.mjs index a51eaf86..8b84a9b6 100644 --- a/web/e2e/fixture/server.mjs +++ b/web/e2e/fixture/server.mjs @@ -237,6 +237,16 @@ const OWN_DOCUMENTS = { own: 'apiVersion: vdi.desku.be/v1alpha1\nkind: VdiPool\nmetadata:\n name: eng\n namespace: web-prod\nspec:\n className: office\n seats: 4\n', rest: '', }, + 'objects/desktopclass/cluster/office': { + file: 'desktop-classes/office.yaml', + own: 'apiVersion: vdi.desku.be/v1alpha1\nkind: VdiClass\nmetadata:\n name: office\nspec:\n image: quay.io/example/desktop-office:1.4\n', + rest: '', + }, + 'objects/desktop/web-prod/brave-dev': { + file: 'web-prod/desktops/brave-dev.yaml', + own: 'apiVersion: vdi.desku.be/v1alpha1\nkind: VdiInstance\nmetadata:\n name: brave-dev\n namespace: web-prod\nspec:\n image: quay.io/example/desktop-brave:1\n owner: dana\n running: true\n', + rest: '', + }, 'objects/networkpolicy/web-prod/allow-https': { file: 'policies/allow-https.yaml', own: allowHTTPS(443), @@ -709,10 +719,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 +751,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 +1429,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 cc456602..ff59c54f 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 ab0ca243..14466d71 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( @@ -70,9 +70,7 @@ test('a pool is made from its project, what DeskuBe refuses said first', async ( await expect(s).toBeHidden(); }); -test('a desktop says its owner is set once, and is made of a class or an image', async ({ - page, -}) => { +test('a desktop says its owner is set once, and is made of a class', async ({ page }) => { await setScenario(page, 'desktopsgit'); await login(page); await page.goto('/desktops/team-web/web-prod'); @@ -84,14 +82,17 @@ 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(s.getByRole('status')).toHaveText('Pick its class'); await expect(stage).toBeDisabled(); - await s.getByLabel('An image').check(); - await s.getByLabel('Image', { exact: true }).fill('quay.io/example/desktop:3'); + // A class carries what its image needs: no bare image is offered. + await expect(s.getByLabel('Image', { exact: true })).toHaveCount(0); + await s.getByLabel('Class', { exact: true }).selectOption('office'); await s.getByLabel('Running', { exact: true }).uncheck(); await expect(s.getByText('It stays off until git turns it on.')).toBeVisible(); @@ -101,7 +102,7 @@ test('a desktop says its owner is set once, and is made of a class or an image', namespace: 'web-prod', name: 'dana-dev', owner: 'dana', - image: 'quay.io/example/desktop:3', + class: 'office', running: false, }); await expect(page.getByText(/Staged into Changes/)).toBeVisible(); @@ -114,16 +115,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 }) => { @@ -145,6 +147,7 @@ test('a class is made by a class author, in the platform repo', async ({ page }) await s.getByLabel('Image', { exact: true }).fill('quay.io/example/desktop-kiosk:1'); await expect(s.getByText('desktop-classes/kiosk.yaml')).toBeVisible(); await expect(s.getByText('New file in the')).toContainText('platform'); + await s.getByLabel('Nested sandboxes').check(); const body = posted(page, '/api/desktopclasses'); await s.getByRole('button', { name: 'Stage class' }).click(); @@ -152,6 +155,7 @@ test('a class is made by a class author, in the platform repo', async ({ page }) name: 'kiosk', image: 'quay.io/example/desktop-kiosk:1', idleTimeout: '2h', + nestedSandboxes: true, }); await expect(page.getByText(/Staged into Changes/)).toBeVisible(); }); diff --git a/web/e2e/ui/desktopsingit.spec.ts b/web/e2e/ui/desktopsingit.spec.ts index 1493deb4..27757c3a 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/desktopsneeds.spec.ts b/web/e2e/ui/desktopsneeds.spec.ts new file mode 100644 index 00000000..4fdc1260 --- /dev/null +++ b/web/e2e/ui/desktopsneeds.spec.ts @@ -0,0 +1,51 @@ +import { expect, login, setScenario, test } from './fx'; + +// An image that needs a class field nothing it is made of sets: DeskuBe says +// so on PodReady (ImageNeedsUnmet), and the desktop's page names where the +// field goes, its class or its own manifest, opened in the editor for +// whoever may change it, else who can. + +test("a desktop whose class lacks what its image needs opens the class's manifest", async ({ + page, +}) => { + await setScenario(page, 'desktopsneeds'); + await login(page); + await page.goto('/desktops/team-web/web-prod/desktop/carol-dev'); + const main = page.locator('main'); + await expect(main.getByText('Its image needs what class office does not set.')).toBeVisible(); + await expect( + main.getByText( + 'DeskuBe reports: the image needs nestedSandboxes, which its class does not set', + ), + ).toBeVisible(); + await main.getByRole('button', { name: 'Edit class office' }).click(); + await expect(page.getByRole('dialog').getByLabel('Manifest')).toHaveValue(/kind: VdiClass/); +}); + +test('a desktop made of an image alone opens its own manifest', async ({ page }) => { + await setScenario(page, 'desktopsneeds'); + await login(page); + await page.goto('/desktops/team-web/web-prod/desktop/brave-dev'); + const main = page.locator('main'); + await expect(main.getByText('Its image needs what its manifest does not set.')).toBeVisible(); + await main.getByRole('button', { name: 'Edit its manifest' }).click(); + await expect(page.getByRole('dialog').getByLabel('Manifest')).toHaveValue( + /image: quay.io\/example\/desktop-brave:1/, + ); +}); + +test('a reader who may change neither is told who can', async ({ page }) => { + await setScenario(page, 'desktopsneedsviewer'); + await login(page); + await page.goto('/desktops/team-web/web-prod/desktop/carol-dev'); + const main = page.locator('main'); + await expect(main.getByText('Its image needs what class office does not set.')).toBeVisible(); + await expect(main.getByRole('button', { name: 'Edit class office' })).toHaveCount(0); + await expect(main.getByRole('link', { name: 'class office' })).toHaveAttribute( + 'href', + '/desktops?tab=classes&class=office', + ); + await page.goto('/desktops/team-web/web-prod/desktop/brave-dev'); + await expect(main.getByText('A project admin sets it in its manifest.')).toBeVisible(); + await expect(main.getByRole('button', { name: 'Edit its manifest' })).toHaveCount(0); +}); diff --git a/web/e2e/ui/desktopspeople.spec.ts b/web/e2e/ui/desktopspeople.spec.ts new file mode 100644 index 00000000..46b204b6 --- /dev/null +++ b/web/e2e/ui/desktopspeople.spec.ts @@ -0,0 +1,266 @@ +import { expect, login, setScenario, test } from './fx'; +import type { Page, Request } from '@playwright/test'; +import { FirstDesktopClassImage } from '../../src/lib/model.gen'; + +// 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(); + + // An owner named before their first sign-in: no user of that name yet. + await owner.fill('newhire'); + const unfound = s.getByRole('list', { name: 'Not found on this cluster' }); + await expect(unfound.getByRole('button')).toHaveText([ + /Use newhire anyway\s*not found on this cluster: they may not have signed in yet/, + ]); + await unfound.getByRole('button', { name: 'Use user newhire anyway' }).click(); + await expect(picked.getByRole('listitem')).toHaveText([/newhire\s*not found on this cluster/]); + await expect( + s.getByText('newhire owns it for good, and starts, stops and pairs it.'), + ).toBeVisible(); +}); + +test('one the search does not find is used anyway, on a deliberate click', async ({ page }) => { + await setScenario(page, 'desktopsgit'); + await login(page); + const s = await newPool(page); + const who = s.getByLabel('Who may claim one', { exact: true }); + await who.click(); + await who.fill('zoe'); + const unfound = s.getByRole('list', { name: 'Not found on this cluster' }); + await expect(unfound.getByRole('button')).toHaveText([ + /Use zoe anyway\s*not found on this cluster: it may not exist yet/, + /Use zoe anyway\s*not found on this cluster: they may not have signed in yet/, + ]); + // Enter takes no name the search did not find. + await who.press('Enter'); + const picked = s.getByRole('list', { name: 'Who may claim one: picked' }); + await expect(picked).toHaveCount(0); + await unfound.getByRole('button', { name: 'Use group zoe anyway' }).click(); + await expect(picked.getByRole('listitem')).toHaveText([/zoe\s*not found on this cluster/]); + + // A name no user or group could carry is said, never offered. + await who.fill('ops:eu'); + await expect(s.getByText('A group name holds no :.')).toBeVisible(); + await expect(s.getByRole('list', { name: 'Not found on this cluster' })).toHaveCount(0); + + 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: 'Group', name: 'zoe' }], + }); +}); + +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: FirstDesktopClassImage, + idleTimeout: '1h', + nestedSandboxes: true, + }); + 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('whoever may not list the classes types one, told whom to ask', async ({ page }) => { + await setScenario(page, 'desktopsclassesunread'); + await login(page); + const s = await newPool(page); + await expect( + s.getByText( + 'A class a platform admin offers, by name. Ask a platform admin for the class names.', + ), + ).toBeVisible(); + await expect(s.getByText(/No desktop class yet/)).toHaveCount(0); + await s.getByLabel('Class', { exact: true }).fill('office'); + await expect(s.getByLabel('Class', { exact: true })).toHaveValue('office'); +}); + +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 bb374437..d9e2ff23 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 00000000..981282e5 --- /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 f4c73785..dac5fbd9 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 28e19eb2..1b94af57 100644 --- a/web/src/lib/components/create/DesktopClassField.svelte +++ b/web/src/lib/components/create/DesktopClassField.svelte @@ -1,46 +1,73 @@
- - {#if known} - - {#each known as c (c)}{/each} - - {/if} - {#if absent} - - No class {value} yet: its desktops wait until a platform admin offers one. + {#if names === null} + + + A class a platform admin offers, by name. Ask a platform admin for the class names. - {:else if !known} - 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/DesktopClassForm.svelte b/web/src/lib/components/create/DesktopClassForm.svelte index 15dd10bd..6357fbd6 100644 --- a/web/src/lib/components/create/DesktopClassForm.svelte +++ b/web/src/lib/components/create/DesktopClassForm.svelte @@ -21,10 +21,12 @@ let name = $state(''); let image = $state(''); let idleTimeout = $state(''); + let nestedSandboxes = $state(false); const request = $derived.by((): DesktopClassCreate => { const req: DesktopClassCreate = { name, image: image.trim() }; if (idleTimeout.trim()) req.idleTimeout = idleTimeout.trim(); + if (nestedSandboxes) req.nestedSandboxes = true; return req; }); const refusals = $derived(classRefusals(request)); @@ -101,6 +103,16 @@ /> The container image its desktops run. +
+ + + 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 b7f4c6e6..3cf7773d 100644 --- a/web/src/lib/components/create/DesktopOneForm.svelte +++ b/web/src/lib/components/create/DesktopOneForm.svelte @@ -1,9 +1,11 @@ + +{#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 22294e7d..18df57ef 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}, with the + nested sandboxes its Chromium needs, 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 00000000..f0a7394f --- /dev/null +++ b/web/src/lib/components/create/PeoplePicker.svelte @@ -0,0 +1,331 @@ + + +{#snippet icon(kind: string)} + {#if kind === 'Group'}