Manage people and the tenancy tree, from the web and the CLI

Nothing in the tree could be renamed, moved or removed, and an approved
person stayed in the project they were first put in — from the web or
the CLI. Now:

- /admin/users is the tree, each project opening onto its people and
  keys, with approve, move, suspend, reinstate and remove for people,
  revoke for keys, and add, rename, move and remove at every level,
  plus a search over every account. Forms post and get the page back,
  so it works with no script; htmx 2.0.11 (0BSD, embedded, checked
  against npm's integrity hash) swaps only the changed part, keeping
  open projects open.
- llmgw org tree/add/rename/move/remove, users move/delete, and
  keys list --all.
- Projects, teams and organizations are named by id, path
  (Acme/platform/gateway) or unique name; users by id or email. With a
  single project --project can be left out, instead of defaulting to
  "default", which a tree built from the web does not have.

Moving a person moves the keys they made; operator keys stay with the
project. Only empty things are removed, and never a project that had a
key, since usage history refers to it.

Also: keys init no longer reparents an existing team or project;
reinstating an account with no project is refused (a rejected signup
used to come back active and fail at its first key); rejecting a
signup removes it; keys limits --budget takes whole units like the
quotas page.

Checked in headless Chrome: a move from an open project updates the
page in place, keeps the project open, and the search still filters.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ilker ManapandClaude Opus 5.5 committed 2026-09-28 16:26:39 +02:00
1 parent 5141e4b138
commit 3104f4b706
21 files changed
+2081 -217

No files matched your search

+72 -16
View File
@@ -6,6 +6,7 @@ import (
"encoding/base32"
"errors"
"fmt"
"math"
"strings"
"text/tabwriter"
"time"
@@ -107,7 +108,11 @@ func newKeyCreateCmd(open opener) *cobra.Command {
}
defer s.Close()
secret, k, err := store.NewKey(randomID("key"), args[0], project)
p, err := resolveProject(cmd.Context(), s, project)
if err != nil {
return err
}
secret, k, err := store.NewKey(randomID("key"), args[0], p.ID)
if err != nil {
return err
}
@@ -117,8 +122,7 @@ func newKeyCreateCmd(open opener) *cobra.Command {
k.ExpiresAt = k.CreatedAt.Add(expires)
}
if err := s.CreateKey(cmd.Context(), k); err != nil {
return fmt.Errorf("creating the key (does project %q exist? run `llmgw keys init`): %w",
project, err)
return fmt.Errorf("creating the key in %s: %w", p.Path, err)
}
// The one output that matters goes to stdout and everything else to
@@ -141,13 +145,13 @@ func newKeyCreateCmd(open opener) *cobra.Command {
link := strings.TrimRight(baseURL, "/") + "/claim/" + token
fmt.Fprintln(out, link)
cmd.PrintErrf("\nid %s\nproject %s\nexpires %s\n",
k.ID, k.ProjectID, time.Now().Add(orDefault(claimTTL, store.ClaimTTL)).Format(time.RFC3339))
k.ID, p.Path, time.Now().Add(orDefault(claimTTL, store.ClaimTTL)).Format(time.RFC3339))
cmd.PrintErrln("\nSend the link. It works once, and the key is shown only to whoever opens it.")
return nil
}
fmt.Fprintln(out, secret)
cmd.PrintErrf("\nid %s\nproject %s\n", k.ID, k.ProjectID)
cmd.PrintErrf("\nid %s\nproject %s\n", k.ID, p.Path)
if !k.ExpiresAt.IsZero() {
cmd.PrintErrf("expires %s\n", k.ExpiresAt.Format(time.RFC3339))
}
@@ -155,7 +159,8 @@ func newKeyCreateCmd(open opener) *cobra.Command {
return nil
},
}
cmd.Flags().StringVar(&project, "project", "default", "project the key belongs to")
cmd.Flags().StringVar(&project, "project", "",
"project the key belongs to: id, path (Acme/platform/gateway) or unique name")
cmd.Flags().StringVar(&band, "band", "", "admission band; empty inherits")
cmd.Flags().StringVar(&profile, "profile", "", "routing profile; empty inherits")
cmd.Flags().DurationVar(&expires, "expires-in", 0, "lifetime; 0 never expires")
@@ -174,9 +179,10 @@ func orDefault(d, fallback time.Duration) time.Duration {
func newKeyListCmd(open opener) *cobra.Command {
var project string
var all bool
cmd := &cobra.Command{
Use: "list",
Short: "List a project's keys",
Short: "List a project's keys, or with --all every key and whose it is",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
s, err := open(cmd.Context())
@@ -185,12 +191,31 @@ func newKeyListCmd(open opener) *cobra.Command {
}
defer s.Close()
keys, err := s.Keys(cmd.Context(), project)
if all {
rows, err := s.AllKeys(cmd.Context())
if err != nil {
return err
}
w := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "ID\tNAME\tKEY\tPROJECT\tOWNER\tSTATE\tLAST USED")
now := time.Now()
for _, r := range rows {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", r.ID, r.Name, r.Prefix,
r.ProjectPath, dash(r.OwnerEmail), keyState(r.Key, now), ago(r.LastUsedAt, now))
}
return w.Flush()
}
p, err := resolveProject(cmd.Context(), s, project)
if err != nil {
return err
}
keys, err := s.Keys(cmd.Context(), p.ID)
if err != nil {
return err
}
if len(keys) == 0 {
fmt.Fprintf(cmd.OutOrStdout(), "no keys in project %q\n", project)
fmt.Fprintf(cmd.OutOrStdout(), "no keys in %s\n", p.Path)
return nil
}
@@ -204,7 +229,8 @@ func newKeyListCmd(open opener) *cobra.Command {
return w.Flush()
},
}
cmd.Flags().StringVar(&project, "project", "default", "project to list")
cmd.Flags().StringVar(&project, "project", "", "project to list: id, path or unique name")
cmd.Flags().BoolVar(&all, "all", false, "every key in every project, with its owner")
return cmd
}
@@ -235,7 +261,7 @@ func newKeyRevokeCmd(open opener) *cobra.Command {
func newLimitsCmd(open opener) *cobra.Command {
var scope, id, period string
var rpm, tpm int
var budget int64
var budget float64
var models []string
cmd := &cobra.Command{
@@ -252,7 +278,34 @@ func newLimitsCmd(open opener) *cobra.Command {
}
defer s.Close()
l := store.Limits{Scope: store.Scope(scope), ScopeID: id}
scopeID := id
switch store.Scope(scope) {
case store.ScopeOrg:
o, err := resolveOrg(cmd.Context(), s, id)
if err != nil {
return err
}
scopeID = o.ID
case store.ScopeTeam:
t, err := resolveTeam(cmd.Context(), s, id)
if err != nil {
return err
}
scopeID = t.ID
case store.ScopeProject:
p, err := resolveProject(cmd.Context(), s, id)
if err != nil {
return err
}
scopeID = p.ID
case store.ScopeKey:
if id == "" {
return errors.New("--scope key needs --id, the key's id")
}
default:
return fmt.Errorf("--scope is org, team, project or key, not %q", scope)
}
l := store.Limits{Scope: store.Scope(scope), ScopeID: scopeID}
if cmd.Flags().Changed("rpm") {
l.RPM = &rpm
}
@@ -260,7 +313,10 @@ func newLimitsCmd(open opener) *cobra.Command {
l.TPM = &tpm
}
if cmd.Flags().Changed("budget") {
l.Budget = &budget
// Whole units, as the quotas page takes them; stored as
// micro-units so repeated addition does not drift.
micros := int64(math.Round(budget * 1e6))
l.Budget = &micros
l.BudgetPeriod = store.Period(period)
}
if cmd.Flags().Changed("models") {
@@ -274,15 +330,15 @@ func newLimitsCmd(open opener) *cobra.Command {
if err := s.PutLimits(cmd.Context(), l); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "limits set on %s %s\n", scope, id)
fmt.Fprintf(cmd.OutOrStdout(), "limits set on %s %s\n", scope, scopeID)
return nil
},
}
cmd.Flags().StringVar(&scope, "scope", "project", "org | team | project | key")
cmd.Flags().StringVar(&id, "id", "default", "id at that scope")
cmd.Flags().StringVar(&id, "id", "", "which one: id, path or unique name (a key's id for --scope key)")
cmd.Flags().IntVar(&rpm, "rpm", 0, "requests per minute")
cmd.Flags().IntVar(&tpm, "tpm", 0, "tokens per minute")
cmd.Flags().Int64Var(&budget, "budget", 0, "budget per period, in micro-units")
cmd.Flags().Float64Var(&budget, "budget", 0, "budget per period, in whole units as the quotas page shows them")
cmd.Flags().StringVar(&period, "period", "month", "day | month")
cmd.Flags().StringSliceVar(&models, "models", nil, "allowed models; empty allows none")
return cmd
+7 -2
View File
@@ -42,7 +42,12 @@ func newMemoryCmd(open opener) *cobra.Command {
if off {
keep = 0
}
if err := s.SetMemoryRetention(cmd.Context(), project, keep); err != nil {
p, err := resolveProject(cmd.Context(), s, project)
if err != nil {
return err
}
project = p.Path
if err := s.SetMemoryRetention(cmd.Context(), p.ID, keep); err != nil {
return err
}
if keep == 0 {
@@ -55,7 +60,7 @@ func newMemoryCmd(open opener) *cobra.Command {
return nil
},
}
cmd.Flags().StringVar(&project, "project", "default", "project id")
cmd.Flags().StringVar(&project, "project", "", "project: id, path or unique name")
cmd.Flags().IntVar(&hours, "retain-hours", 0, "how long a note is kept after it was last written")
cmd.Flags().BoolVar(&off, "off", false, "stop keeping notes for this project")
return cmd
+334
View File
@@ -0,0 +1,334 @@
package cli
import (
"context"
"errors"
"fmt"
"io"
"github.com/spf13/cobra"
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
)
func newOrgCmd() *cobra.Command {
var sf storeFlags
cmd := &cobra.Command{
Use: "org",
Short: "Organizations, teams and projects: see, add, rename, move, remove",
Long: "The tenancy tree an account lives in. A person is in a project, a project\n" +
"in a team, a team in an organization, and limits can be set on any of them.\n\n" +
"Anything that takes one of them accepts its id, its path\n" +
"(\"Acme/platform/gateway\") or its name when that name is unique.",
}
sf.bind(cmd)
open := func(cmd *cobra.Command) (*store.DB, error) { return sf.open(cmd) }
cmd.AddCommand(newOrgTreeCmd(open), newOrgAddCmd(open), newOrgRenameCmd(open),
newOrgMoveCmd(open), newOrgRemoveCmd(open))
return cmd
}
type dbOpener func(*cobra.Command) (*store.DB, error)
func newOrgTreeCmd(open dbOpener) *cobra.Command {
var people bool
cmd := &cobra.Command{
Use: "tree",
Short: "Show the whole tree, with how many accounts and keys each project has",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
s, err := open(cmd)
if err != nil {
return err
}
defer s.Close()
tree, err := s.Tree(cmd.Context())
if err != nil {
return err
}
var byProject map[string][]store.User
if people {
users, err := s.Users(cmd.Context(), "")
if err != nil {
return err
}
byProject = map[string][]store.User{}
for _, u := range users {
byProject[u.ProjectID] = append(byProject[u.ProjectID], u)
}
}
printTree(cmd.OutOrStdout(), tree, byProject)
if people && len(byProject[""]) > 0 {
fmt.Fprintf(cmd.OutOrStdout(), "\nwaiting for approval\n")
for _, u := range byProject[""] {
fmt.Fprintf(cmd.OutOrStdout(), " %s %s %s\n", u.Email, u.State, u.ID)
}
}
return nil
},
}
cmd.Flags().BoolVar(&people, "people", false, "list the accounts in each project")
return cmd
}
func printTree(w io.Writer, tree []store.TreeOrg, people map[string][]store.User) {
if len(tree) == 0 {
fmt.Fprintln(w, "no organizations yet; `llmgw org add org <name>` starts one")
return
}
for _, o := range tree {
fmt.Fprintf(w, "%s (%s)\n", o.Name, o.ID)
if len(o.Teams) == 0 {
fmt.Fprintln(w, " no teams")
}
for _, t := range o.Teams {
fmt.Fprintf(w, " %s (%s)\n", t.Name, t.ID)
if len(t.Projects) == 0 {
fmt.Fprintln(w, " no projects")
}
for _, p := range t.Projects {
fmt.Fprintf(w, " %s (%s) %s, %s\n", p.Name, p.ID,
countOf(p.Users, "account"), keysOf(p))
for _, u := range people[p.ID] {
admin := ""
if u.IsAdmin {
admin = " admin"
}
fmt.Fprintf(w, " %s %s%s\n", u.Email, u.State, admin)
}
}
}
}
}
func keysOf(p store.TreeProject) string {
s := countOf(p.ActiveKeys, "key")
if revoked := p.Keys - p.ActiveKeys; revoked > 0 {
s += fmt.Sprintf(" (+%d revoked)", revoked)
}
return s
}
func countOf(n int, noun string) string {
if n == 1 {
return "1 " + noun
}
return fmt.Sprintf("%d %ss", n, noun)
}
func levelArg(arg string) (string, error) {
switch arg {
case "org", "organization":
return "org", nil
case "team", "project":
return arg, nil
}
return "", fmt.Errorf("%q is not org, team or project", arg)
}
func newOrgAddCmd(open dbOpener) *cobra.Command {
var in string
cmd := &cobra.Command{
Use: "add <org|team|project> <name>",
Short: "Add an organization, a team to one, or a project to a team",
Example: " llmgw org add org Acme\n" +
" llmgw org add team platform --in Acme\n" +
" llmgw org add project gateway --in Acme/platform",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
level, err := levelArg(args[0])
if err != nil {
return err
}
s, err := open(cmd)
if err != nil {
return err
}
defer s.Close()
ctx := cmd.Context()
var id, where string
switch level {
case "org":
id, err = s.CreateOrg(ctx, args[1])
case "team":
var o store.Org
if o, err = resolveOrg(ctx, s, in); err == nil {
id, err = s.CreateTeam(ctx, o.ID, args[1])
where = " in " + o.Name
}
case "project":
var t store.TeamPath
if t, err = resolveTeam(ctx, s, in); err == nil {
id, err = s.CreateProject(ctx, t.ID, args[1])
where = " in " + t.OrgName + " / " + t.Name
}
}
if errors.Is(err, store.ErrDuplicateName) {
return fmt.Errorf("there is already a %s named %q there", level, args[1])
}
if err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "%s %s%s (%s)\n", level, args[1], where, id)
return nil
},
}
cmd.Flags().StringVar(&in, "in", "", "the organization a team goes in, or the team a project goes in")
return cmd
}
func newOrgRenameCmd(open dbOpener) *cobra.Command {
return &cobra.Command{
Use: "rename <org|team|project> <which> <new name>",
Short: "Rename an organization, team or project; ids and everything under it stay",
Example: " llmgw org rename project Acme/platform/gateway api-gateway",
Args: cobra.ExactArgs(3),
RunE: func(cmd *cobra.Command, args []string) error {
level, err := levelArg(args[0])
if err != nil {
return err
}
s, err := open(cmd)
if err != nil {
return err
}
defer s.Close()
id, err := resolveLevel(cmd.Context(), s, level, args[1])
if err != nil {
return err
}
switch level {
case "org":
err = s.RenameOrg(cmd.Context(), id, args[2])
case "team":
err = s.RenameTeam(cmd.Context(), id, args[2])
case "project":
err = s.RenameProject(cmd.Context(), id, args[2])
}
if errors.Is(err, store.ErrDuplicateName) {
return fmt.Errorf("there is already a %s named %q beside it", level, args[2])
}
if err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "%s %s is now %q\n", level, id, args[2])
return nil
},
}
}
func newOrgMoveCmd(open dbOpener) *cobra.Command {
var to string
cmd := &cobra.Command{
Use: "move <team|project> <which> --to <parent>",
Short: "Put a team in another organization, or a project in another team",
Long: "Everything under it moves too: projects, accounts and keys. From then on it\n" +
"inherits the new parent's limits. Usage already recorded is not rewritten.",
Example: " llmgw org move project Acme/platform/gateway --to Scania/ml\n" +
" llmgw org move team platform --to Scania",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
s, err := open(cmd)
if err != nil {
return err
}
defer s.Close()
ctx := cmd.Context()
switch args[0] {
case "team":
t, err := resolveTeam(ctx, s, args[1])
if err != nil {
return err
}
o, err := resolveOrg(ctx, s, to)
if err != nil {
return err
}
if err := s.MoveTeam(ctx, t.ID, o.ID); err != nil {
return dupAs(err, "team", t.Name)
}
fmt.Fprintf(cmd.OutOrStdout(), "team %s is now in %s\n", t.Name, o.Name)
case "project":
p, err := resolveProject(ctx, s, args[1])
if err != nil {
return err
}
t, err := resolveTeam(ctx, s, to)
if err != nil {
return err
}
if err := s.MoveProject(ctx, p.ID, t.ID); err != nil {
return dupAs(err, "project", p.Path)
}
fmt.Fprintf(cmd.OutOrStdout(), "%s is now in %s / %s\n", p.Path, t.OrgName, t.Name)
default:
return fmt.Errorf("only a team or a project moves; to move an account, `llmgw users move`")
}
return nil
},
}
cmd.Flags().StringVar(&to, "to", "", "the organization or team it goes to")
_ = cmd.MarkFlagRequired("to")
return cmd
}
func dupAs(err error, level, name string) error {
if errors.Is(err, store.ErrDuplicateName) {
return fmt.Errorf("the destination already has a %s named like %s", level, name)
}
return err
}
func newOrgRemoveCmd(open dbOpener) *cobra.Command {
return &cobra.Command{
Use: "remove <org|team|project> <which>",
Short: "Remove an organization, team or project that nothing is in",
Long: "Only something empty is removed: an organization with no teams, a team with\n" +
"no projects, a project with no accounts and no keys. A project that ever had\n" +
"a key keeps it, revoked, because usage history refers to it; rename such a\n" +
"project instead. Its limits go with it.",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
level, err := levelArg(args[0])
if err != nil {
return err
}
s, err := open(cmd)
if err != nil {
return err
}
defer s.Close()
id, err := resolveLevel(cmd.Context(), s, level, args[1])
if err != nil {
return err
}
switch level {
case "org":
err = s.DeleteOrg(cmd.Context(), id)
case "team":
err = s.DeleteTeam(cmd.Context(), id)
case "project":
err = s.DeleteProject(cmd.Context(), id)
}
if err != nil {
return fmt.Errorf("%s %s was not removed: %w", level, args[1], err)
}
fmt.Fprintf(cmd.OutOrStdout(), "%s %s removed\n", level, id)
return nil
},
}
}
func resolveLevel(ctx context.Context, s *store.DB, level, arg string) (string, error) {
switch level {
case "org":
o, err := resolveOrg(ctx, s, arg)
return o.ID, err
case "team":
t, err := resolveTeam(ctx, s, arg)
return t.ID, err
default:
p, err := resolveProject(ctx, s, arg)
return p.ID, err
}
}
+124
View File
@@ -0,0 +1,124 @@
package cli
import (
"bytes"
"context"
"path/filepath"
"strings"
"testing"
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
)
// run executes the CLI against one store file and returns stdout.
func run(t *testing.T, db string, args ...string) (string, error) {
t.Helper()
cmd := Root()
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
// --config pointed nowhere, so a server.yaml on the test machine is never read.
cmd.SetArgs(append(args, "--store", db, "--config", ""))
err := cmd.ExecuteContext(context.Background())
return out.String(), err
}
func mustRun(t *testing.T, db string, args ...string) string {
t.Helper()
out, err := run(t, db, args...)
if err != nil {
t.Fatalf("%v: %v", args, err)
}
return out
}
func TestTheTreeIsManagedByNameNotId(t *testing.T) {
db := filepath.Join(t.TempDir(), "s.db")
mustRun(t, db, "org", "add", "org", "Acme")
mustRun(t, db, "org", "add", "org", "Scania")
mustRun(t, db, "org", "add", "team", "platform", "--in", "Acme")
mustRun(t, db, "org", "add", "team", "platform", "--in", "Scania")
// "platform" is in both, so a project needs the path.
_, err := run(t, db, "org", "add", "project", "gateway", "--in", "platform")
if err == nil || !strings.Contains(err.Error(), "more than one team") {
t.Fatalf("an ambiguous name was accepted: %v", err)
}
mustRun(t, db, "org", "add", "project", "gateway", "--in", "acme/Platform")
mustRun(t, db, "org", "add", "project", "research", "--in", "Scania / platform")
mustRun(t, db, "users", "create", "ayse@example.com", "--password", "correct horse battery", "--project", "Acme/platform/gateway")
mustRun(t, db, "keys", "create", "laptop", "--project", "gateway")
out := mustRun(t, db, "org", "tree", "--people")
for _, want := range []string{"Acme", "gateway", "1 account, 1 key", "ayse@example.com"} {
if !strings.Contains(out, want) {
t.Errorf("tree lacks %q:\n%s", want, out)
}
}
out = mustRun(t, db, "users", "move", "ayse@example.com", "--project", "research")
if !strings.Contains(out, "Scania / platform / research") {
t.Errorf("move said: %s", out)
}
mustRun(t, db, "org", "rename", "project", "research", "lab")
mustRun(t, db, "org", "move", "project", "Acme/platform/gateway", "--to", "Scania/platform")
// gateway still has the operator's key, so it stays.
if _, err := run(t, db, "org", "remove", "project", "gateway"); err == nil {
t.Error("a project with a key was removed")
}
mustRun(t, db, "org", "remove", "team", "Acme/platform")
mustRun(t, db, "org", "remove", "org", "Acme")
s, err := store.Open(context.Background(), db)
if err != nil {
t.Fatal(err)
}
defer s.Close()
paths, _ := s.AllProjects(context.Background())
var got []string
for _, p := range paths {
got = append(got, p.Path)
}
if strings.Join(got, "|") != "Scania / platform / gateway|Scania / platform / lab" {
t.Errorf("projects = %v", got)
}
}
func TestOneProjectNeedsNoFlag(t *testing.T) {
db := filepath.Join(t.TempDir(), "s.db")
mustRun(t, db, "org", "add", "org", "Acme")
mustRun(t, db, "org", "add", "team", "platform")
mustRun(t, db, "org", "add", "project", "gateway")
mustRun(t, db, "keys", "create", "laptop")
if out := mustRun(t, db, "keys", "list"); !strings.Contains(out, "laptop") {
t.Errorf("list: %s", out)
}
mustRun(t, db, "org", "add", "project", "search", "--in", "platform")
if _, err := run(t, db, "keys", "create", "other"); err == nil ||
!strings.Contains(err.Error(), "which project?") {
t.Errorf("two projects and no flag: %v", err)
}
}
func TestKeyBudgetsAreWholeUnits(t *testing.T) {
db := filepath.Join(t.TempDir(), "s.db")
mustRun(t, db, "org", "add", "org", "Acme")
mustRun(t, db, "org", "add", "team", "platform")
mustRun(t, db, "org", "add", "project", "gateway")
mustRun(t, db, "keys", "limits", "--scope", "project", "--id", "gateway", "--budget", "12.5")
s, err := store.Open(context.Background(), db)
if err != nil {
t.Fatal(err)
}
defer s.Close()
all, _ := s.AllLimits(context.Background())
for _, l := range all {
if l.Budget == nil || *l.Budget != 12_500_000 {
t.Errorf("budget stored as %v micro-units", l.Budget)
}
}
}
+131
View File
@@ -0,0 +1,131 @@
package cli
import (
"context"
"errors"
"fmt"
"strings"
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
)
// The tree can be built from the web, which mints ids like proj-3kq7..., or
// from `keys init`, which makes slugs. A command that wanted the id made the
// operator copy one off a page, and every --project defaulted to "default",
// which a tree built from the web does not have. These take what a person
// would type instead: an id, a path, or a name that is unique.
// normPath lowercases a path and spaces its separators the way the store joins
// them, so "acme/platform/gateway" matches "Acme / platform / gateway".
func normPath(p string) string {
parts := strings.Split(p, "/")
for i := range parts {
parts[i] = strings.ToLower(strings.TrimSpace(parts[i]))
}
return strings.Join(parts, " / ")
}
type candidate struct{ id, path string }
// pick finds the one candidate an argument names.
func pick(kind, arg string, all []candidate) (candidate, error) {
if arg == "" {
if len(all) == 1 {
return all[0], nil
}
if len(all) == 0 {
return candidate{}, fmt.Errorf("there is no %s yet; create one with `llmgw org add %s`", kind, kind)
}
return candidate{}, fmt.Errorf("which %s? give an id, a path or a name:\n%s", kind, listCandidates(all))
}
for _, c := range all {
if c.id == arg {
return c, nil
}
}
want := normPath(arg)
var matches []candidate
for _, c := range all {
full := normPath(c.path)
segs := strings.Split(full, " / ")
if full == want || segs[len(segs)-1] == want {
matches = append(matches, c)
}
}
switch len(matches) {
case 1:
return matches[0], nil
case 0:
return candidate{}, fmt.Errorf("no %s %q; there is:\n%s", kind, arg, listCandidates(all))
default:
return candidate{}, fmt.Errorf("%q names more than one %s; give its path:\n%s",
arg, kind, listCandidates(matches))
}
}
func listCandidates(cs []candidate) string {
var b strings.Builder
for _, c := range cs {
fmt.Fprintf(&b, " %-40s %s\n", c.path, c.id)
}
return strings.TrimRight(b.String(), "\n")
}
func resolveProject(ctx context.Context, s *store.DB, arg string) (store.ProjectPath, error) {
all, err := s.AllProjects(ctx)
if err != nil {
return store.ProjectPath{}, err
}
cs := make([]candidate, len(all))
for i, p := range all {
cs[i] = candidate{p.ID, p.Path}
}
c, err := pick("project", arg, cs)
return store.ProjectPath{ID: c.id, Path: c.path}, err
}
func resolveTeam(ctx context.Context, s *store.DB, arg string) (store.TeamPath, error) {
all, err := s.AllTeams(ctx)
if err != nil {
return store.TeamPath{}, err
}
cs := make([]candidate, len(all))
for i, t := range all {
cs[i] = candidate{t.ID, t.OrgName + " / " + t.Name}
}
c, err := pick("team", arg, cs)
if err != nil {
return store.TeamPath{}, err
}
for _, t := range all {
if t.ID == c.id {
return t, nil
}
}
return store.TeamPath{}, store.ErrNotFound
}
func resolveOrg(ctx context.Context, s *store.DB, arg string) (store.Org, error) {
all, err := s.AllOrgs(ctx)
if err != nil {
return store.Org{}, err
}
cs := make([]candidate, len(all))
for i, o := range all {
cs[i] = candidate{o.ID, o.Name}
}
c, err := pick("org", arg, cs)
return store.Org{ID: c.id, Name: c.path}, err
}
// resolveUser takes an account's id or its email.
func resolveUser(ctx context.Context, s *store.DB, arg string) (store.User, error) {
if u, err := s.UserByID(ctx, arg); err == nil {
return u, nil
}
u, err := s.UserByEmail(ctx, arg)
if errors.Is(err, store.ErrNotFound) {
return u, fmt.Errorf("no account with id or email %q; `llmgw users list` shows them", arg)
}
return u, err
}
+1
View File
@@ -42,6 +42,7 @@ func Root() *cobra.Command {
newCtlCmd(),
newTenancyCmd(),
newUsersCmd(),
newOrgCmd(),
newMirrorCmd(),
newSimEngineCmd(),
)
+7 -2
View File
@@ -50,7 +50,12 @@ func newThreadsCmd(open opener) *cobra.Command {
if off {
keep = 0
}
if err := s.SetThreadRetention(cmd.Context(), project, keep); err != nil {
p, err := resolveProject(cmd.Context(), s, project)
if err != nil {
return err
}
project = p.Path
if err := s.SetThreadRetention(cmd.Context(), p.ID, keep); err != nil {
return err
}
if keep == 0 {
@@ -63,7 +68,7 @@ func newThreadsCmd(open opener) *cobra.Command {
return nil
},
}
cmd.Flags().StringVar(&project, "project", "default", "project id")
cmd.Flags().StringVar(&project, "project", "", "project: id, path or unique name")
cmd.Flags().IntVar(&hours, "retain-hours", 0, "how long a conversation is kept after its last turn")
cmd.Flags().BoolVar(&off, "off", false, "stop keeping conversations for this project")
return cmd
+113 -23
View File
@@ -33,6 +33,7 @@ func newUsersCmd() *cobra.Command {
newUserStateCmd(open, "reinstate", store.UserActive,
"Let a suspended account work again"),
newUserCreateCmd(open), newUserResetPasswordCmd(open),
newUserMoveCmd(open), newUserDeleteCmd(open),
newUserAdminCmd(open, "promote", true, "Let an account see the cluster dashboard at /admin"),
newUserAdminCmd(open, "demote", false, "Take away access to the cluster dashboard"))
return cmd
@@ -88,7 +89,7 @@ func newUserListCmd(open userOpener) *cobra.Command {
func newUserApproveCmd(open userOpener) *cobra.Command {
var project, by string
cmd := &cobra.Command{
Use: "approve <user-id>",
Use: "approve <user>",
Short: "Let an account sign in and issue its own keys",
Long: "The project is required: it decides which limits this person's keys\n" +
"inherit. An account approved into no project would pass every check and\n" +
@@ -101,27 +102,31 @@ func newUserApproveCmd(open userOpener) *cobra.Command {
}
defer s.Close()
if err := s.ApproveUser(cmd.Context(), args[0], project, by, time.Now()); err != nil {
return fmt.Errorf("approving %s: %w", args[0], err)
}
u, err := s.UserByID(cmd.Context(), args[0])
u, err := resolveUser(cmd.Context(), s, args[0])
if err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "%s approved into project %s\n", u.Email, project)
p, err := resolveProject(cmd.Context(), s, project)
if err != nil {
return err
}
if err := s.ApproveUser(cmd.Context(), u.ID, p.ID, by, time.Now()); err != nil {
return fmt.Errorf("approving %s: %w", u.Email, err)
}
fmt.Fprintf(cmd.OutOrStdout(), "%s approved into %s\n", u.Email, p.Path)
cmd.PrintErrln("They can sign in and create their own keys from /profile.")
return nil
},
}
cmd.Flags().StringVar(&project, "project", "default", "project the person's keys belong to")
cmd.Flags().StringVar(&project, "project", "",
"project the person's keys belong to: id, path (Acme/platform/gateway) or unique name")
cmd.Flags().StringVar(&by, "by", "", "who approved, for the record")
_ = cmd.MarkFlagRequired("project")
return cmd
}
func newUserStateCmd(open userOpener, verb string, state store.UserState, short string) *cobra.Command {
return &cobra.Command{
Use: verb + " <user-id>",
Use: verb + " <user>",
Short: short,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
@@ -131,18 +136,22 @@ func newUserStateCmd(open userOpener, verb string, state store.UserState, short
}
defer s.Close()
if err := s.SetUserState(cmd.Context(), args[0], state); err != nil {
u, err := resolveUser(cmd.Context(), s, args[0])
if err != nil {
return err
}
if err := s.SetUserState(cmd.Context(), u.ID, state); err != nil {
return err
}
if state == store.UserSuspended {
// Otherwise the person stays signed in and suspension is
// advisory until their session happens to expire.
if err := s.DeleteUserSessions(cmd.Context(), args[0]); err != nil {
if err := s.DeleteUserSessions(cmd.Context(), u.ID); err != nil {
return err
}
cmd.PrintErrln("Their sessions were closed. Their API keys still work — revoke those separately.")
}
fmt.Fprintf(cmd.OutOrStdout(), "%s is now %s\n", args[0], state)
fmt.Fprintf(cmd.OutOrStdout(), "%s is now %s\n", u.Email, state)
return nil
},
}
@@ -150,7 +159,7 @@ func newUserStateCmd(open userOpener, verb string, state store.UserState, short
func newUserAdminCmd(open userOpener, verb string, admin bool, short string) *cobra.Command {
return &cobra.Command{
Use: verb + " <user-id>",
Use: verb + " <user>",
Short: short,
Long: "The dashboard is read-only, so this grants looking and nothing else.\n" +
"Everything that changes the cluster or issues a credential stays here on\n" +
@@ -164,11 +173,11 @@ func newUserAdminCmd(open userOpener, verb string, admin bool, short string) *co
}
defer s.Close()
if err := s.SetAdmin(cmd.Context(), args[0], admin); err != nil {
u, err := resolveUser(cmd.Context(), s, args[0])
if err != nil {
return err
}
u, err := s.UserByID(cmd.Context(), args[0])
if err != nil {
if err := s.SetAdmin(cmd.Context(), u.ID, admin); err != nil {
return err
}
if admin {
@@ -186,7 +195,7 @@ func newUserAdminCmd(open userOpener, verb string, admin bool, short string) *co
func newUserResetPasswordCmd(open userOpener) *cobra.Command {
var password string
cmd := &cobra.Command{
Use: "reset-password <user-id>",
Use: "reset-password <user>",
Short: "Set a new password for someone who lost theirs",
Long: "There is no self-service reset, because this gateway sends no email and\n" +
"a reset link with nowhere to send it is not a reset. Set one here, tell\n" +
@@ -208,13 +217,17 @@ func newUserResetPasswordCmd(open userOpener) *cobra.Command {
if err != nil {
return err
}
if err := s.SetPassword(cmd.Context(), args[0], hash); err != nil {
u, err := resolveUser(cmd.Context(), s, args[0])
if err != nil {
return err
}
if err := s.DeleteUserSessions(cmd.Context(), args[0]); err != nil {
if err := s.SetPassword(cmd.Context(), u.ID, hash); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "password set for %s\n", args[0])
if err := s.DeleteUserSessions(cmd.Context(), u.ID); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "password set for %s\n", u.Email)
cmd.PrintErrln("Their sessions were closed. Their API keys still work.")
return nil
},
@@ -241,6 +254,10 @@ func newUserCreateCmd(open userOpener) *cobra.Command {
}
defer s.Close()
p, err := resolveProject(cmd.Context(), s, project)
if err != nil {
return err
}
hash, err := account.HashPassword(password)
if err != nil {
return err
@@ -253,15 +270,88 @@ func newUserCreateCmd(open userOpener) *cobra.Command {
if err := s.CreateUser(cmd.Context(), u); err != nil {
return err
}
if err := s.ApproveUser(cmd.Context(), id, project, "cli", time.Now()); err != nil {
if err := s.ApproveUser(cmd.Context(), id, p.ID, "cli", time.Now()); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "%s\n", id)
cmd.PrintErrf("%s created and approved into project %s\n", args[0], project)
cmd.PrintErrf("%s created and approved into %s\n", args[0], p.Path)
return nil
},
}
cmd.Flags().StringVar(&project, "project", "default", "project the person's keys belong to")
cmd.Flags().StringVar(&project, "project", "",
"project the person's keys belong to: id, path or unique name (optional when there is one)")
cmd.Flags().StringVar(&password, "password", "", "initial password")
return cmd
}
func newUserMoveCmd(open userOpener) *cobra.Command {
var project string
cmd := &cobra.Command{
Use: "move <user> --project <project>",
Short: "Put an approved account in another project, with the keys it made",
Long: "The person's own keys go with them, so they stop spending the old project's\n" +
"budget. Keys an operator issued in the old project stay there. Usage already\n" +
"recorded is not rewritten. A running server picks the change up when its key\n" +
"cache expires (auth.cache_ttl).",
Example: " llmgw users move ayse@example.com --project Acme/ml/research",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
s, err := open(cmd)
if err != nil {
return err
}
defer s.Close()
u, err := resolveUser(cmd.Context(), s, args[0])
if err != nil {
return err
}
p, err := resolveProject(cmd.Context(), s, project)
if err != nil {
return err
}
moved, err := s.MoveUser(cmd.Context(), u.ID, p.ID)
if err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "%s is now in %s (%s moved with them)\n",
u.Email, p.Path, countOf(moved, "key"))
return nil
},
}
cmd.Flags().StringVar(&project, "project", "", "where they go: id, path or unique name")
_ = cmd.MarkFlagRequired("project")
return cmd
}
func newUserDeleteCmd(open userOpener) *cobra.Command {
var yes bool
cmd := &cobra.Command{
Use: "delete <user>",
Short: "Remove an account for good",
Long: "Signs them out, revokes every key they made, and removes the account. The\n" +
"keys are kept, revoked and ownerless, because usage history refers to them.\n" +
"To stop an account working and keep it, use suspend.",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
s, err := open(cmd)
if err != nil {
return err
}
defer s.Close()
u, err := resolveUser(cmd.Context(), s, args[0])
if err != nil {
return err
}
if !yes {
return fmt.Errorf("this removes %s and revokes their keys; run again with --yes", u.Email)
}
if err := s.DeleteUser(cmd.Context(), u.ID, time.Now()); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "%s removed\n", u.Email)
return nil
},
}
cmd.Flags().BoolVar(&yes, "yes", false, "confirm")
return cmd
}