From fc1b47976d7295922e4da6c9f58e898282d980fa Mon Sep 17 00:00:00 2001 From: Ilker Manap Date: Sun, 27 Sep 2026 12:36:13 +0200 Subject: [PATCH] Let an admin build the tenancy tree, instead of sending them to a shell MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An account is approved into a project, a project belongs to a team, a team to an organization — and until now the only way to make any of them was `llmgw keys init` on the control plane. So the first thing to do after installing was leave the interface you were already in, and an approval form with an empty dropdown gave no hint why. The accounts page now creates all three. Creating a container is not granting access: nobody can use one until an account is approved into it, which is the step already on this page. Quotas stay on the CLI. Making somewhere to put people is structural; raising what they may spend is financial, and a stolen admin session should be able to do the first and not the second. Ids are random now instead of slugs of the name, which fixes a bug that only appears when you have a second organization — which is exactly what this feature invites. Team ids were slugs in one flat namespace and PutTeam upserts on id, so creating "platform" under a second organization moved the first one's team into it. Nothing failed. The team changed owner. Create* is separate from Put* rather than replacing it. The upserts exist so `keys init` can be re-run while provisioning a machine; a person filling in a form means something else by a name that already exists, and gets told. A duplicate is refused among siblings only. Two companies both having a "platform" team is ordinary, and refusing the second would be the flat namespace again wearing a better error message. Co-Authored-By: Claude Opus 5 (1M context) --- internal/store/tenancy.go | 122 +++++++++++++++++ internal/store/tenancy_test.go | 132 ++++++++++++++++++ internal/web/admin_tenancy_test.go | 171 ++++++++++++++++++++++++ internal/web/admin_users.go | 85 ++++++++++++ internal/web/templates/admin_users.html | 61 ++++++++- 5 files changed, 566 insertions(+), 5 deletions(-) create mode 100644 internal/store/tenancy.go create mode 100644 internal/store/tenancy_test.go create mode 100644 internal/web/admin_tenancy_test.go diff --git a/internal/store/tenancy.go b/internal/store/tenancy.go new file mode 100644 index 0000000..1bfa359 --- /dev/null +++ b/internal/store/tenancy.go @@ -0,0 +1,122 @@ +package store + +import ( + "context" + "crypto/rand" + "database/sql" + "encoding/base32" + "errors" + "fmt" + "strings" +) + +// ErrDuplicateName means a sibling of that name is already there. +var ErrDuplicateName = errors.New("something of that name is already here") + +// NewID mints an identifier with a readable prefix. +// +// Random rather than a slug of the name, which is what the tenancy tree used +// and what made two organizations impossible to have: team ids were slugs in +// one flat namespace, PutTeam upserts on id, so creating "platform" under a +// second organization moved the first one's team into it. Nothing failed. The +// team simply changed owner. +func NewID(prefix string) string { + var buf [10]byte + _, _ = rand.Read(buf[:]) + return prefix + strings.ToLower( + base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(buf[:])) +} + +// TeamPath is a team with the organization it belongs to, for a chooser. +type TeamPath struct { + ID, Name, OrgID, OrgName string +} + +// AllOrgs lists the organizations, by name. +func (s *DB) AllOrgs(ctx context.Context) ([]Org, error) { + return queryAll(ctx, s.db, `SELECT id, name FROM organizations ORDER BY name`, + nil, func(rows *sql.Rows) (Org, error) { + var o Org + return o, rows.Scan(&o.ID, &o.Name) + }) +} + +// AllTeams lists the teams with their organization. +func (s *DB) AllTeams(ctx context.Context) ([]TeamPath, error) { + return queryAll(ctx, s.db, ` + SELECT t.id, t.name, o.id, o.name + FROM teams t JOIN organizations o ON o.id = t.org_id + ORDER BY o.name, t.name`, nil, func(rows *sql.Rows) (TeamPath, error) { + var t TeamPath + return t, rows.Scan(&t.ID, &t.Name, &t.OrgID, &t.OrgName) + }) +} + +// CreateOrg adds an organization and returns its id. +// +// Create rather than Put. The Put* calls upsert by id so `keys init` can be run +// again without duplicating, which is right for provisioning and wrong for a +// person filling in a form: there, a name that already exists is a mistake +// being made, not a line being re-run. +func (s *DB) CreateOrg(ctx context.Context, name string) (string, error) { + name = strings.TrimSpace(name) + if name == "" { + return "", fmt.Errorf("an organization needs a name") + } + if err := s.nameIsFree(ctx, + `SELECT COUNT(*) FROM organizations WHERE name = ?`, name); err != nil { + return "", err + } + id := NewID("org-") + return id, s.PutOrg(ctx, Org{ID: id, Name: name}) +} + +// CreateTeam adds a team to an organization. +// +// Unique within its organization, not globally: two companies both having a +// "platform" team is ordinary, and refusing the second would be the flat +// namespace back again wearing a better error message. +func (s *DB) CreateTeam(ctx context.Context, orgID, name string) (string, error) { + name = strings.TrimSpace(name) + if orgID == "" || name == "" { + return "", fmt.Errorf("a team needs an organization and a name") + } + if err := s.nameIsFree(ctx, + `SELECT COUNT(*) FROM teams WHERE org_id = ? AND name = ?`, orgID, name); err != nil { + return "", err + } + id := NewID("team-") + return id, s.PutTeam(ctx, Team{ID: id, OrgID: orgID, Name: name}) +} + +// CreateProject adds a project to a team. +func (s *DB) CreateProject(ctx context.Context, teamID, name string) (string, error) { + name = strings.TrimSpace(name) + if teamID == "" || name == "" { + return "", fmt.Errorf("a project needs a team and a name") + } + if err := s.nameIsFree(ctx, + `SELECT COUNT(*) FROM projects WHERE team_id = ? AND name = ?`, teamID, name); err != nil { + return "", err + } + id := NewID("proj-") + return id, s.PutProject(ctx, Project{ID: id, TeamID: teamID, Name: name}) +} + +// nameIsFree refuses a duplicate among siblings. +// +// Checked rather than left to a constraint because there is no unique index to +// lean on: names were never unique, the ids were, and the ids were slugs of the +// names. A query and a race is the honest state of it — two admins creating the +// same team in the same second get two teams, which is visible and fixable, +// where the old behaviour silently reparented somebody else's. +func (s *DB) nameIsFree(ctx context.Context, q string, args ...any) error { + var n int + if err := s.db.QueryRowContext(ctx, q, args...).Scan(&n); err != nil { + return err + } + if n > 0 { + return ErrDuplicateName + } + return nil +} diff --git a/internal/store/tenancy_test.go b/internal/store/tenancy_test.go new file mode 100644 index 0000000..97ae1e0 --- /dev/null +++ b/internal/store/tenancy_test.go @@ -0,0 +1,132 @@ +package store + +import ( + "context" + "errors" + "path/filepath" + "testing" +) + +func tenancyStore(t *testing.T) *DB { + t.Helper() + s, err := OpenSQLite(context.Background(), filepath.Join(t.TempDir(), "ten.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func TestTwoOrganizationsCanBothHaveAPlatformTeam(t *testing.T) { + s := tenancyStore(t) + a, err := s.CreateOrg(t.Context(), "Acme") + if err != nil { + t.Fatal(err) + } + b, err := s.CreateOrg(t.Context(), "Scania") + if err != nil { + t.Fatal(err) + } + + ta, err := s.CreateTeam(t.Context(), a, "platform") + if err != nil { + t.Fatal(err) + } + tb, err := s.CreateTeam(t.Context(), b, "platform") + if err != nil { + t.Fatal(err) + } + + // Ids were slugs of the name in one flat namespace, and PutTeam upserts on + // id — so the second of these moved the first organization's team into the + // second. Nothing failed; the team changed owner. + if ta == tb { + t.Fatal("both teams got the same id, so one overwrote the other") + } + teams, err := s.AllTeams(t.Context()) + if err != nil { + t.Fatal(err) + } + if len(teams) != 2 { + t.Fatalf("expected a team in each organization, got %+v", teams) + } + for _, team := range teams { + if team.OrgName == "" { + t.Errorf("a team should come back with its organization: %+v", team) + } + } +} + +func TestTheSameNameTwiceInOneOrganizationIsRefused(t *testing.T) { + s := tenancyStore(t) + org, _ := s.CreateOrg(t.Context(), "Acme") + if _, err := s.CreateTeam(t.Context(), org, "platform"); err != nil { + t.Fatal(err) + } + + // Two identically named teams under one organization is somebody making a + // mistake in a form, not a script being re-run. + _, err := s.CreateTeam(t.Context(), org, "platform") + if !errors.Is(err, ErrDuplicateName) { + t.Errorf("expected a duplicate to be refused, got %v", err) + } +} + +func TestADuplicateOrganizationIsRefused(t *testing.T) { + s := tenancyStore(t) + if _, err := s.CreateOrg(t.Context(), "Acme"); err != nil { + t.Fatal(err) + } + if _, err := s.CreateOrg(t.Context(), "Acme"); !errors.Is(err, ErrDuplicateName) { + t.Errorf("expected a duplicate organization to be refused, got %v", err) + } +} + +func TestAProjectNeedsATeamAndANameThatIsNotBlank(t *testing.T) { + s := tenancyStore(t) + if _, err := s.CreateProject(t.Context(), "", "gateway"); err == nil { + t.Error("a project with no team should be refused") + } + org, _ := s.CreateOrg(t.Context(), "Acme") + team, _ := s.CreateTeam(t.Context(), org, "platform") + // Whitespace is not a name; it would produce a row nobody can point at. + if _, err := s.CreateProject(t.Context(), team, " "); err == nil { + t.Error("a blank name should be refused") + } +} + +func TestANewProjectShowsItsWholePath(t *testing.T) { + s := tenancyStore(t) + org, _ := s.CreateOrg(t.Context(), "Acme") + team, _ := s.CreateTeam(t.Context(), org, "platform") + if _, err := s.CreateProject(t.Context(), team, "gateway"); err != nil { + t.Fatal(err) + } + + paths, err := s.AllProjects(t.Context()) + if err != nil { + t.Fatal(err) + } + // The chooser on the approval form shows this string, and an id alone + // would make two projects named "gateway" indistinguishable. + if len(paths) != 1 || paths[0].Path != "Acme / platform / gateway" { + t.Errorf("expected the full path, got %+v", paths) + } +} + +func TestIdsAreNotDerivedFromTheName(t *testing.T) { + s := tenancyStore(t) + id, err := s.CreateOrg(t.Context(), "Acme") + if err != nil { + t.Fatal(err) + } + // A renamed organization keeping an id that spells its old name is the + // smaller half; the real reason is that a slug of a name is not unique and + // these are primary keys. + if id == "acme" || id == "Acme" { + t.Errorf("the id should not be the name; got %q", id) + } + if len(id) < 8 { + t.Errorf("the id looks too short to be random: %q", id) + } +} diff --git a/internal/web/admin_tenancy_test.go b/internal/web/admin_tenancy_test.go new file mode 100644 index 0000000..5b7c451 --- /dev/null +++ b/internal/web/admin_tenancy_test.go @@ -0,0 +1,171 @@ +package web + +import ( + "context" + "errors" + "io" + "log/slog" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "gitea.mynodes.xyz/ilker/llmgw/internal/store" +) + +// fakeAdmin is the store half of the accounts page. +type fakeAdmin struct { + orgs []store.Org + teams []store.TeamPath + projects []store.ProjectPath + + createdOrg [1]string + createdTeam [2]string + createdProject [2]string + err error +} + +func (f *fakeAdmin) Users(context.Context, store.UserState) ([]store.User, error) { + return nil, nil +} +func (f *fakeAdmin) UserByID(context.Context, string) (store.User, error) { + return store.User{}, errors.New("no") +} + +func (f *fakeAdmin) ApproveUser(context.Context, string, string, string, time.Time) error { + return nil +} +func (f *fakeAdmin) SetUserState(context.Context, string, store.UserState) error { return nil } +func (f *fakeAdmin) DeleteUserSessions(context.Context, string) error { return nil } + +func (f *fakeAdmin) AllProjects(context.Context) ([]store.ProjectPath, error) { + return f.projects, nil +} +func (f *fakeAdmin) AllOrgs(context.Context) ([]store.Org, error) { return f.orgs, nil } +func (f *fakeAdmin) AllTeams(context.Context) ([]store.TeamPath, error) { return f.teams, nil } + +func (f *fakeAdmin) CreateOrg(_ context.Context, name string) (string, error) { + f.createdOrg = [1]string{name} + return "org-1", f.err +} + +func (f *fakeAdmin) CreateTeam(_ context.Context, orgID, name string) (string, error) { + f.createdTeam = [2]string{orgID, name} + return "team-1", f.err +} + +func (f *fakeAdmin) CreateProject(_ context.Context, teamID, name string) (string, error) { + f.createdProject = [2]string{teamID, name} + return "proj-1", f.err +} + +func tenancyPage(t *testing.T, s *fakeAdmin, admin bool) *http.ServeMux { + t.Helper() + a := fakeAccounts{user: store.User{ID: "u1", Email: "a@example.com", IsAdmin: admin}} + p := NewAccountPages(a, nil, nil, "v0", slog.New(slog.NewTextHandler(io.Discard, nil))) + mux := http.NewServeMux() + p.RegisterAdminUsers(mux, s) + return mux +} + +func TestAnAdminCanMakeSomewhereToPutPeople(t *testing.T) { + s := &fakeAdmin{} + mux := tenancyPage(t, s, true) + + // Creating the tree used to need a shell — `llmgw keys init` — so the first + // thing to do after installing was leave the interface you were in. + body := mirrorPost(t, mux, "/admin/tenancy/org", + url.Values{"csrf": {"tok"}, "name": {"Scania"}}).Body.String() + if s.createdOrg[0] != "Scania" { + t.Errorf("the organization name did not arrive: %q", s.createdOrg[0]) + } + if !strings.Contains(body, "created") { + t.Errorf("the page should confirm it; got %s", body) + } +} + +func TestATeamIsCreatedInsideTheOrganizationChosen(t *testing.T) { + s := &fakeAdmin{orgs: []store.Org{{ID: "org-1", Name: "Scania"}}} + mirrorPost(t, tenancyPage(t, s, true), "/admin/tenancy/team", + url.Values{"csrf": {"tok"}, "name": {"platform"}, "org": {"org-1"}}) + + if s.createdTeam != [2]string{"org-1", "platform"} { + t.Errorf("the team's parent did not arrive intact: %v", s.createdTeam) + } +} + +func TestATeamWithNoOrganizationIsRefusedBeforeTheStore(t *testing.T) { + s := &fakeAdmin{} + body := mirrorPost(t, tenancyPage(t, s, true), "/admin/tenancy/team", + url.Values{"csrf": {"tok"}, "name": {"platform"}}).Body.String() + + if s.createdTeam[1] != "" { + t.Error("nothing should have reached the store") + } + if !strings.Contains(body, "organization") { + t.Errorf("the error should say what is missing; got %s", body) + } +} + +func TestADuplicateIsReportedInPlainWords(t *testing.T) { + s := &fakeAdmin{err: store.ErrDuplicateName} + body := mirrorPost(t, tenancyPage(t, s, true), "/admin/tenancy/org", + url.Values{"csrf": {"tok"}, "name": {"Scania"}}).Body.String() + + if !strings.Contains(body, "already one of those") { + t.Errorf("a duplicate should read as a mistake, not a constraint; got %s", body) + } +} + +func TestCreatingTheTreeNeedsTheCSRFToken(t *testing.T) { + s := &fakeAdmin{} + w := mirrorPost(t, tenancyPage(t, s, true), "/admin/tenancy/org", + url.Values{"name": {"Scania"}}) + + if w.Code != http.StatusBadRequest { + t.Errorf("expected 400 without a CSRF token, got %d", w.Code) + } + if s.createdOrg[0] != "" { + t.Error("nothing should have been created") + } +} + +func TestSomebodyWhoIsNotAnAdminCannotCreateAnything(t *testing.T) { + s := &fakeAdmin{} + w := mirrorPost(t, tenancyPage(t, s, false), "/admin/tenancy/org", + url.Values{"csrf": {"tok"}, "name": {"Scania"}}) + + // 404 rather than 403, like every other page under /admin: a 403 confirms + // the endpoint is there. + if w.Code != http.StatusNotFound { + t.Errorf("expected 404 for a non-admin, got %d", w.Code) + } + if s.createdOrg[0] != "" { + t.Error("nothing should have been created") + } +} + +func TestThePageSaysWhatToDoWhenTheTreeIsEmpty(t *testing.T) { + body := mirrorGet(t, tenancyPage(t, &fakeAdmin{}, true), "/admin/users").Body.String() + + // An empty tree means no account can be approved at all, and the reason is + // not guessable from an approval form with an empty dropdown. + if !strings.Contains(body, "No organizations yet") { + t.Errorf("the empty case should say what to do first; got %s", body) + } +} + +func TestQuotasAreStillNotSettableFromTheBrowser(t *testing.T) { + body := mirrorGet(t, tenancyPage(t, &fakeAdmin{}, true), "/admin/users").Body.String() + + // Making somewhere to put people is structural; raising what they may spend + // is financial. A stolen admin session should be able to do the first and + // not the second, and the page says so. + if !strings.Contains(body, "llmgw keys limits") { + t.Error("the page should still send quota changes to the shell") + } + if strings.Contains(body, `name="budget"`) { + t.Error("a budget field has appeared on the accounts page") + } +} diff --git a/internal/web/admin_users.go b/internal/web/admin_users.go index ffc23d5..f1c9d2b 100644 --- a/internal/web/admin_users.go +++ b/internal/web/admin_users.go @@ -17,12 +17,23 @@ type AccountAdmin interface { SetUserState(ctx context.Context, id string, state store.UserState) error DeleteUserSessions(ctx context.Context, userID string) error AllProjects(ctx context.Context) ([]store.ProjectPath, error) + + // The tenancy tree an account is approved into. Creating it used to need a + // shell — `llmgw keys init` — so the first thing an operator had to do + // after installing was leave the interface they were already in. + AllOrgs(ctx context.Context) ([]store.Org, error) + AllTeams(ctx context.Context) ([]store.TeamPath, error) + CreateOrg(ctx context.Context, name string) (string, error) + CreateTeam(ctx context.Context, orgID, name string) (string, error) + CreateProject(ctx context.Context, teamID, name string) (string, error) } type adminUsersData struct { Pending []store.User Active []store.User Projects []store.ProjectPath + Orgs []store.Org + Teams []store.TeamPath Message string Error string CSRF string @@ -75,6 +86,45 @@ func (p *AccountPages) RegisterAdminUsers(mux *http.ServeMux, s AccountAdmin) { return "suspended, and signed out everywhere", nil })) + // The tenancy tree. Creating a container is not granting access: nobody can + // use one until an account is approved into it, which is the step above and + // already lives here. What is still not here is limits — raising a budget + // is a financial act, and a stolen session must not be able to perform one. + mux.HandleFunc("POST /admin/tenancy/org", p.tenancyAction(s, + func(ctx context.Context, r *http.Request) (string, error) { + id, err := s.CreateOrg(ctx, r.FormValue("name")) + if err != nil { + return "", err + } + return "organization " + r.FormValue("name") + " created as " + id, nil + })) + + mux.HandleFunc("POST /admin/tenancy/team", p.tenancyAction(s, + func(ctx context.Context, r *http.Request) (string, error) { + org := r.FormValue("org") + if org == "" { + return "", errors.New("choose the organization this team belongs to") + } + id, err := s.CreateTeam(ctx, org, r.FormValue("name")) + if err != nil { + return "", err + } + return "team " + r.FormValue("name") + " created as " + id, nil + })) + + mux.HandleFunc("POST /admin/tenancy/project", p.tenancyAction(s, + func(ctx context.Context, r *http.Request) (string, error) { + team := r.FormValue("team") + if team == "" { + return "", errors.New("choose the team this project belongs to") + } + id, err := s.CreateProject(ctx, team, r.FormValue("name")) + if err != nil { + return "", err + } + return "project " + r.FormValue("name") + " created as " + id, nil + })) + mux.HandleFunc("POST /admin/users/{id}/reinstate", p.adminAction(s, func(ctx context.Context, _ store.User, id string, _ *http.Request) (string, error) { if err := s.SetUserState(ctx, id, store.UserActive); err != nil { @@ -84,6 +134,35 @@ func (p *AccountPages) RegisterAdminUsers(mux *http.ServeMux, s AccountAdmin) { })) } +// tenancyAction wraps a change to the tree: admin session, CSRF, audit, render. +// +// Its own wrapper rather than adminAction because that one is about a subject +// account and looks its email up to name it in the log. There is no subject +// here, and passing an empty id through it would write audit lines about +// nobody. +func (p *AccountPages) tenancyAction(s AccountAdmin, + do func(ctx context.Context, r *http.Request) (string, error), +) http.HandlerFunc { + return p.adminOnly(func(w http.ResponseWriter, r *http.Request, admin store.User) { + sess, _, _ := p.session(r) + if !p.accounts.CheckCSRF(sess, r.FormValue("csrf")) { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + msg, err := do(r.Context(), r) + if err != nil { + if errors.Is(err, store.ErrDuplicateName) { + err = errors.New("there is already one of those here") + } + p.log.Warn("a tenancy change was refused", "admin", admin.Email, "err", err) + p.renderUsers(w, r, s, "", err.Error()) + return + } + p.log.Info("the tenancy tree was changed", "admin", admin.Email, "what", msg) + p.renderUsers(w, r, s, msg, "") + }) +} + // adminOnly is the guard every page under /admin shares. func (p *AccountPages) adminOnly( next func(w http.ResponseWriter, r *http.Request, admin store.User), @@ -162,5 +241,11 @@ func (p *AccountPages) renderUsers(w http.ResponseWriter, r *http.Request, if d.Projects, err = s.AllProjects(r.Context()); err != nil { p.log.Error("could not list projects", "err", err) } + if d.Orgs, err = s.AllOrgs(r.Context()); err != nil { + p.log.Error("could not list organizations", "err", err) + } + if d.Teams, err = s.AllTeams(r.Context()); err != nil { + p.log.Error("could not list teams", "err", err) + } render(w, "admin_users", d) } diff --git a/internal/web/templates/admin_users.html b/internal/web/templates/admin_users.html index 9b0f9cd..cf0c99b 100644 --- a/internal/web/templates/admin_users.html +++ b/internal/web/templates/admin_users.html @@ -60,11 +60,62 @@ {{end}} {{else}}

No accounts yet.

{{end}} -

Three things are deliberately not here. Making someone an admin, -resetting a password and issuing keys on another person's behalf all need a -shell on the control plane — llmgw users promote, -reset-password, llmgw keys. A stolen admin session can -approve and suspend; it cannot hand itself more access or take over an account.

+

Organizations, teams and projects

+

Where an account lives. A person is approved into a project, a +project belongs to a team, and a team to an organization — and a quota can be +written on any of the three, so the shape here is the shape the bill takes.

+ +
+
+ + + +
+ +
+ + + + +
+ +
+ + + + +
+
+ +{{if not .Orgs}} +

No organizations yet. Create one, then a team in it, then a +project in the team — an account can only be approved into a project.

+{{else}} +{{/* One path column, not three: the store returns the chain already joined, + which is the string the approval chooser shows, and three headers over one + value line up with nothing. */}} + +{{range .Projects}}{{end}} +{{if not .Projects}}{{end}} +
Organization / team / projectID
{{.Path}}{{.ID}}
No projects yet, so nobody can be approved.
+{{end}} + +

Four things are deliberately not here. Making someone an admin, +resetting a password, issuing keys on another +person's behalf and setting any quota all need a shell on the control plane — llmgw users promote, +reset-password, llmgw keys, llmgw keys limits. +A stolen admin session can approve, suspend and make somewhere to put people; it +cannot hand itself more access, take over an account, or raise what anybody is +allowed to spend.

{{end}}