Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/personas.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions internal/api/fakecluster_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
13 changes: 13 additions & 0 deletions internal/api/handlers_adminobjects.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
}
9 changes: 8 additions & 1 deletion internal/api/handlers_adminobjects_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
264 changes: 264 additions & 0 deletions internal/api/handlers_people.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading