From 81e20d826c90acc578a77373f2f5a2e4407639ba Mon Sep 17 00:00:00 2001 From: l-nmch Date: Sat, 14 Nov 2026 18:10:05 +0100 Subject: [PATCH] feat!: A tenant has one name The display name leaves the body of a tenant and the creation, and with it the only thing a PATCH of a tenant could change: the route is gone (405). The name is a slug, it is the namespace, the Incus project and the key of the rights, and the owner is an OpenFGA tuple; nothing about a tenant changes afterwards. A body that still gives displayName is refused as any field the API does not know (400). The tenants:write scope now only deletes. Closes #118 --- docs/explanation/authorization.md | 4 +- docs/reference/endpoints.md | 2 +- docs/reference/tenants.md | 4 +- internal/api/keyscopes_test.go | 6 +-- internal/api/quota_test.go | 8 +-- internal/api/selfservice_test.go | 15 +----- internal/api/tenants.go | 27 ++-------- internal/api/tenants_integration_test.go | 16 ++---- internal/api/tenants_test.go | 69 ++++++++---------------- internal/authz/authz.go | 4 +- internal/kube/tenants.go | 28 ---------- internal/kube/tenants_test.go | 37 ++----------- internal/openapi/openapi.yaml | 57 ++------------------ internal/tenants/tenants.go | 44 +++------------ internal/tenants/tenants_test.go | 37 ++----------- 15 files changed, 62 insertions(+), 296 deletions(-) diff --git a/docs/explanation/authorization.md b/docs/explanation/authorization.md index f215f4f..2118c0d 100644 --- a/docs/explanation/authorization.md +++ b/docs/explanation/authorization.md @@ -1,7 +1,7 @@ --- type: explanation audience: developer who needs to understand how the API decides what a caller may do -verified: 2026-10-28 +verified: 2026-11-14 --- # How the API authorizes a request @@ -16,7 +16,7 @@ Authentication tells who calls, OpenFGA decides what they may do (`internal/auth | write images | `can_write_images` | `images:write` | | read, write networks | `can_read_networks`, `can_write_networks` | `networks:read`, `networks:write` | | read, write profiles | `can_read_profiles`, `can_write_profiles` | `profiles:read`, `profiles:write` | -| rename and delete the tenant | `can_write_tenant` | `tenants:write` | +| delete the tenant | `can_write_tenant` | `tenants:write` | | read, write memberships, and keys | `can_read_memberships`, `can_write_memberships` | `memberships:read`, `memberships:write` | A user gets those through a role (`admin` over `operator` over `user` over `viewer`). A key gets them from tuples of its own, `key__` on the tenant, one per scope and tenant, each with the condition `not_expired`: the API sends the current time (UTC) with every `Check` and `ListObjects`, and past its date OpenFGA itself refuses the key, with nothing deleted. No role is derived for a key, and no table in the API widens what its tuples say (`instances:write` does not give `instances:read`). `Authorizer.Require(action, ...)` is the middleware of a route: `404` when the caller cannot read the tenant (a tenant that is not yours is not shown to exist), `403` when it can but may not do this, `503` when OpenFGA cannot answer. A decision that cannot be taken is never an "allowed". Creating a tenant for oneself is not an OpenFGA question: any person with an email may, and the owner then becomes the `admin` of the tenant through the tuple the composition writes. There is no platform-administrators group in the API: whoever runs the platform acts on Kubernetes and Incus directly, and a user who needs a special case asks them. Changing the name of a tenant and deleting it is the relation `can_write_tenant` of the model, which the `admin` role holds; a key can be given it with the scope `tenants:write`, on a tenant its creator administers. `GET /v1/whoami` says whether the caller may write tenants. diff --git a/docs/reference/endpoints.md b/docs/reference/endpoints.md index f35bc33..84cb0eb 100644 --- a/docs/reference/endpoints.md +++ b/docs/reference/endpoints.md @@ -13,7 +13,7 @@ verified: 2026-11-08 | `GET /v1/whoami` | Who the credential stands for | | `GET /v1/limits` | What the API enforces on a request: the bounds of an instance and the value each takes when a request leaves it out, the longest names, and the ceilings of the deployment (profiles and images per tenant, tenants per person). Any credential; nothing about a tenant | | `GET /v1/tenants`, `GET /v1/tenants/{t}` | The tenants you hold a role on | -| `POST /v1/tenants`, `PATCH /v1/tenants/{t}`, `DELETE /v1/tenants/{t}` | Create a tenant for yourself (every tenant has the same limits), rename and delete it (its admins, the owner among them) | +| `POST /v1/tenants`, `DELETE /v1/tenants/{t}` | Create a tenant for yourself (one name, and every tenant has the same limits), and delete it (its admins, the owner among them) | | `GET`, `POST /v1/tenants/{t}/images`, `GET`, `DELETE /v1/tenants/{t}/images/{name}` | The images of a tenant: read with a role or a key tuple (`images:read`), write with `operator` or `images:write` | | `GET /v1/tenants/{t}/quota` | What a tenant may hold (instances, vCPU, memory, disk, networks, profiles; the same for every tenant) and what it holds. Read with the right of the instances | | `GET`, `POST /v1/tenants/{t}/profiles`, `GET`, `DELETE /v1/tenants/{t}/profiles/{name}` | The sizes an instance can take: the profiles `s`, `m` and `l` every tenant is created with, and the ones its users make. Read with any role or `profiles:read`, write with `operator` or `profiles:write` | diff --git a/docs/reference/tenants.md b/docs/reference/tenants.md index a4705c5..4d7b462 100644 --- a/docs/reference/tenants.md +++ b/docs/reference/tenants.md @@ -9,7 +9,7 @@ verified: 2026-11-14 A tenant is a `Tenant` object of the `phorge.fr` group in `phorge-system` (`internal/kube/tenants.go`); Crossplane makes its namespace `t-`, its Incus project, and its network. - **Create** is for any person signed in with Authentik, for themselves: the owner is the caller (`owner` is left out or is their own email, another one is `403`), every tenant has the same limits (2 instances, 2 vCPU, 4 GiB of memory, 128 GiB of disk, 2 networks and 2 profiles, see [Limits and quotas](limits-and-quotas.md)), and a person owns at most `MAX_TENANTS_PER_USER` tenants (`409`, `quota_exceeded`, counted by owner, whoever created them). A key never creates a tenant. `GET /v1/whoami` says `canCreateTenants`. It answers `202` with a `Location`: poll it until `phase` is `Ready`. `phase` is `Provisioning`, `Ready`, `Deleting`, or `Failed` when the tenant has not become ready for 3 minutes and either `problems` says what is wrong in words made for the user (a limit that is reached, or that the platform could not complete a step yet) or the platform could not apply what makes the tenant for 3 minutes (the same rule holds for every kind: an object whose composition fails is `Failed` with a sentence that the platform administrators can see why, instead of staying `Provisioning`). It never carries what Crossplane, a provider or Incus report: those stay in `status.problems` of the object, for the administrators. -- **Patch** changes `displayName`: the admins of the tenant, the owner among them, do. A key never patches a tenant unless it holds `tenants:write`. The owner cannot change (it is an OpenFGA tuple): a body that holds it is refused. To hand a tenant over, give the new person the `admin` role with a membership. +- **A tenant has one name**, the slug of `name` (2 to 28 characters: lowercase letters, digits and hyphens, starting with a letter), which is also the name of its Incus project. There is no display name, and a body that gives `displayName` is `400`, like any field the API does not know. Nothing about a tenant can change afterwards, so there is no `PATCH` (`405`): the name is the namespace, the Incus project and the key of the rights, and the owner is an OpenFGA tuple that cannot be edited. To hand a tenant over, give the new person the `admin` role with a membership. - **Delete** is for the admins of the tenant, the owner among them. It removes what the tenant holds first (its instances, then its memberships, then its networks, then the profiles its users made, then its images), then the tenant, all in the foreground: `202`, then the tenant stays as `Deleting` until everything it is made of is gone (about two minutes, longer with a virtual machine to stop), and a `404` on a later get means the person no longer sees the tenant: it is gone or about to be, since the rights of the person (the owner tuple) go with the tenant a little before its last resources do (measured: the `404` came while the tenant was still `Deleting`). Stop polling on it, and do not take it for proof that Incus is empty. It destroys the virtual machines of the tenant. The order is not cosmetic: the platform deletes what a tenant holds in its namespace only while the namespace exists, so the tenant waits for them (see the Hangar issue 185). - Whoever cannot read a tenant is told it does not exist (`404`), whoever can but may not do this gets `403`. Bodies are JSON only, 64 KiB at most, with no field the API does not know. -- **There is no plan.** Every tenant has the same limits. A body that gives a `plan`, to create or to change a tenant, is `400`, like any field the API does not know. +- **There is no plan.** Every tenant has the same limits. A body that gives a `plan` is `400`, like any field the API does not know. diff --git a/internal/api/keyscopes_test.go b/internal/api/keyscopes_test.go index 7460425..25c03e3 100644 --- a/internal/api/keyscopes_test.go +++ b/internal/api/keyscopes_test.go @@ -37,9 +37,8 @@ func TestAKeyWithTheScopesOfTheNetworksTheProfilesAndTheTenantPassesTheirRoutes( {"GET", "/v1/apikeys", "", http.StatusForbidden}, {"GET", "/v1/tenants/other/networks", "", http.StatusNotFound}, {"POST", "/v1/tenants/other/networks", `{"name":"x"}`, http.StatusNotFound}, - // the tenant: rename it; there is no plan to give - {"PATCH", "/v1/tenants/demo", `{"displayName":"renamed"}`, http.StatusOK}, - {"PATCH", "/v1/tenants/demo", `{"plan":"large"}`, http.StatusBadRequest}, + // the tenant: it has nothing to patch + {"PATCH", "/v1/tenants/demo", `{"displayName":"renamed"}`, http.StatusMethodNotAllowed}, {"POST", "/v1/tenants", `{"name":"fresh","owner":"x@example.org"}`, http.StatusForbidden}, {"DELETE", "/v1/tenants/demo", "", http.StatusAccepted}, } { @@ -65,7 +64,6 @@ func TestAKeyThatOnlyReadsTheNetworksCannotWriteThem(t *testing.T) { {"POST", "/v1/tenants/demo/networks", `{"name":"two"}`, http.StatusForbidden}, {"DELETE", "/v1/tenants/demo/networks/lan", "", http.StatusForbidden}, {"GET", "/v1/tenants/demo/profiles", "", http.StatusForbidden}, - {"PATCH", "/v1/tenants/demo", `{"displayName":"renamed"}`, http.StatusForbidden}, {"DELETE", "/v1/tenants/demo", "", http.StatusForbidden}, } { if got := call(t, e, c.method, c.path, "svc_netro", c.body); got != c.want { diff --git a/internal/api/quota_test.go b/internal/api/quota_test.go index 72dcc20..07b7871 100644 --- a/internal/api/quota_test.go +++ b/internal/api/quota_test.go @@ -183,11 +183,11 @@ func TestACallerThatWritesTooMuchIsSlowedDown(t *testing.T) { s.RateLimitPerMinute, s.RateLimitBurst = 60, 3 e := newEnvWith(t, s) for i := 0; i < 3; i++ { - if code := call(t, e, "PATCH", "/v1/tenants/demo", "admin", `{"displayName":"x"}`); code == http.StatusTooManyRequests { + if code := call(t, e, "DELETE", "/v1/tenants/demo/networks/ghost", "admin", ""); code == http.StatusTooManyRequests { t.Fatalf("request %d of the burst was limited", i+1) } } - rec := e.do(t, "PATCH", "/v1/tenants/demo", "admin", `{"displayName":"x"}`) + rec := e.do(t, "DELETE", "/v1/tenants/demo/networks/ghost", "admin", "") if rec.Code != http.StatusTooManyRequests { t.Fatalf("the 4th: status %d: %s", rec.Code, rec.Body) } @@ -203,7 +203,7 @@ func TestACallerThatWritesTooMuchIsSlowedDown(t *testing.T) { t.Fatalf("a read was limited: %d", code) } } - if code := call(t, e, "PATCH", "/v1/tenants/demo", "admin2", `{"displayName":"x"}`); code == http.StatusTooManyRequests { + if code := call(t, e, "DELETE", "/v1/tenants/demo/networks/ghost", "admin2", ""); code == http.StatusTooManyRequests { t.Error("another caller was slowed down") } } @@ -211,7 +211,7 @@ func TestACallerThatWritesTooMuchIsSlowedDown(t *testing.T) { func TestWithoutALimitNothingIsSlowedDown(t *testing.T) { e := newEnv(t) // RateLimitPerMinute is 0 for i := 0; i < 50; i++ { - if code := call(t, e, "PATCH", "/v1/tenants/demo", "admin", `{"displayName":"x"}`); code == http.StatusTooManyRequests { + if code := call(t, e, "DELETE", "/v1/tenants/demo/networks/ghost", "admin", ""); code == http.StatusTooManyRequests { t.Fatal("limited with no limit set") } } diff --git a/internal/api/selfservice_test.go b/internal/api/selfservice_test.go index 6ded8ca..462dd21 100644 --- a/internal/api/selfservice_test.go +++ b/internal/api/selfservice_test.go @@ -18,7 +18,7 @@ func usersMay() Settings { func TestAPersonCreatesATenantForThemselves(t *testing.T) { e := newEnvWith(t, usersMay()) - rec := e.do(t, "POST", "/v1/tenants", "mallory", `{"name":"mine","displayName":"Mine"}`) + rec := e.do(t, "POST", "/v1/tenants", "mallory", `{"name":"mine"}`) if rec.Code != http.StatusAccepted { t.Fatalf("status %d: %s", rec.Code, rec.Body) } @@ -134,20 +134,9 @@ func TestWhoamiSaysWhetherTheCallerMayCreateATenant(t *testing.T) { } } -func TestTheAdminsOfATenantChangeAndDeleteIt(t *testing.T) { +func TestTheAdminsOfATenantDeleteIt(t *testing.T) { e := newEnvWith(t, usersMay()) e.store.tenants["demo"] = tenants.Tenant{Name: "demo", Owner: "alice@example.org", Ready: true, NotReadySince: now} - for who, want := range map[string]int{"alice": 200, "tadmin": 200, "operator": 403, "user": 403, "viewer": 403, "mallory": 404, "svc": 403, "": 401} { - if code := call(t, e, "PATCH", "/v1/tenants/demo", who, `{"displayName":"renamed"}`); code != want { - t.Errorf("rename by %q: status %d, want %d", who, code, want) - } - } - // there is no plan to change: the field is unknown, whoever asks - for who, want := range map[string]int{"alice": 400, "tadmin": 400, "admin": 400, "viewer": 403} { - if code := call(t, e, "PATCH", "/v1/tenants/demo", who, `{"plan":"large"}`); code != want { - t.Errorf("plan by %q: status %d, want %d", who, code, want) - } - } for who, want := range map[string]int{"operator": 403, "mallory": 404, "svc": 403, "alice": 202} { if code := call(t, e, "DELETE", "/v1/tenants/demo", who, ""); code != want { t.Errorf("delete by %q: status %d, want %d", who, code, want) diff --git a/internal/api/tenants.go b/internal/api/tenants.go index 2ea8df7..ecc719b 100644 --- a/internal/api/tenants.go +++ b/internal/api/tenants.go @@ -17,8 +17,8 @@ import ( // tenantRoutes are the routes of the tenants. // // Seeing a tenant takes a right on it (a role; for a key, the scope tenants:read too). Any person creates a tenant for themselves: -// they own it, and the number of tenants a person owns is limited (MAX_TENANTS_PER_USER). Changing the -// name of a tenant and deleting it is for its admins, the owner among them. Every tenant has the same limits (internal/quota). +// they own it, and the number of tenants a person owns is limited (MAX_TENANTS_PER_USER). Deleting +// a tenant is for its admins, the owner among them. A tenant has one name and nothing else to change: its owner cannot change either. Every tenant has the same limits (internal/quota). // A key never creates, changes or deletes a tenant. type tenantRoutes struct { base @@ -30,7 +30,6 @@ func (t *tenantRoutes) register(s *server.Server, authn func(http.Handler) http. s.Handle("GET /v1/tenants", authn(http.HandlerFunc(t.list))) s.Handle("POST /v1/tenants", authn(t.mayCreate(http.HandlerFunc(t.create)))) s.Handle("GET /v1/tenants/{t}", authn(t.visible(http.HandlerFunc(t.get)))) - s.Handle("PATCH /v1/tenants/{t}", authn(t.visible(t.adminOfTheTenant(http.HandlerFunc(t.patch))))) s.Handle("DELETE /v1/tenants/{t}", authn(t.visible(t.adminOfTheTenant(http.HandlerFunc(t.delete))))) } @@ -67,7 +66,6 @@ func (t *tenantRoutes) adminOfTheTenant(next http.Handler) http.Handler { // tenantBody is how a tenant is shown. type tenantBody struct { Name string `json:"name"` - DisplayName string `json:"displayName,omitempty"` Owner string `json:"owner"` Phase tenants.Phase `json:"phase"` Problems string `json:"problems,omitempty"` @@ -79,7 +77,7 @@ type tenantBody struct { func (t *tenantRoutes) body(tn tenants.Tenant) tenantBody { return tenantBody{ - Name: tn.Name, DisplayName: tn.DisplayName, Owner: tn.Owner, Phase: tn.PhaseAt(t.now()), + Name: tn.Name, Owner: tn.Owner, Phase: tn.PhaseAt(t.now()), Problems: tn.MessageAt(t.now()), Namespace: tn.Namespace, IncusProject: tn.IncusProject, CreatedAt: tn.CreatedAt, CreatedBy: tn.CreatedBy, } } @@ -170,25 +168,6 @@ func (t *tenantRoutes) checkOwnedTenants(r *http.Request, email string) *quota.E return quota.CheckCount("tenants", owned, max, "you own too many tenants") } -func (t *tenantRoutes) patch(w http.ResponseWriter, r *http.Request) { - var req tenants.PatchRequest - if !decode(w, r, &req) { - return - } - if err := req.Validate(); err != nil { - t.storeError(w, err, "tenant") - return - } - tn, err := t.store.Patch(r.Context(), r.PathValue("t"), req) - if err != nil { - t.storeError(w, err, "tenant") - return - } - id, _ := auth.FromContext(r.Context()) - t.log.Info("tenant changed", "tenant", tn.Name, "by", id.Subject) - writeJSON(w, http.StatusOK, t.body(tn)) -} - func (t *tenantRoutes) delete(w http.ResponseWriter, r *http.Request) { name := r.PathValue("t") if err := t.store.Delete(r.Context(), name); err != nil { diff --git a/internal/api/tenants_integration_test.go b/internal/api/tenants_integration_test.go index 0f33e61..78dcada 100644 --- a/internal/api/tenants_integration_test.go +++ b/internal/api/tenants_integration_test.go @@ -74,7 +74,7 @@ func TestTenantLifecycleOnTheRealCluster(t *testing.T) { }) t.Log("create", name) - rec := e.do(t, http.MethodPost, "/v1/tenants", "owner", `{"name":"`+name+`","displayName":"created by the API tests"}`) + rec := e.do(t, http.MethodPost, "/v1/tenants", "owner", `{"name":"`+name+`"}`) if rec.Code != http.StatusAccepted { t.Fatalf("create: status %d: %s", rec.Code, rec.Body.String()) } @@ -101,23 +101,13 @@ func TestTenantLifecycleOnTheRealCluster(t *testing.T) { if code := e.do(t, http.MethodGet, "/v1/tenants/"+name, "stranger", "").Code; code != http.StatusNotFound { t.Errorf("a stranger gets %d, want 404", code) } - if code := e.do(t, http.MethodPatch, "/v1/tenants/"+name, "owner", `{"plan":"large"}`).Code; code != http.StatusBadRequest { - t.Errorf("the owner giving a plan gets %d, want 400: there is no plan", code) + if code := e.do(t, http.MethodPatch, "/v1/tenants/"+name, "owner", `{"plan":"large"}`).Code; code != http.StatusMethodNotAllowed { + t.Errorf("patching a tenant gets %d, want 405: it has one name and nothing else to change", code) } if listed := names(t, e.do(t, http.MethodGet, "/v1/tenants", "owner", "")); !slices.Equal(listed, []string{name}) { t.Errorf("the owner sees %v, want only %s", listed, name) } - // Rename. - rec = e.do(t, http.MethodPatch, "/v1/tenants/"+name, "owner", `{"displayName":"resized"}`) - if rec.Code != http.StatusOK { - t.Fatalf("patch: status %d: %s", rec.Code, rec.Body.String()) - } - waitFor(t, 3*time.Minute, "the renamed tenant to be Ready again", func() bool { - mustDecode(t, e.do(t, http.MethodGet, "/v1/tenants/"+name, "owner", ""), &got) - return got.DisplayName == "resized" && got.Phase == tenants.Ready - }) - // Delete, in the foreground: it is Deleting until everything is gone, and then it is not found. rec = e.do(t, http.MethodDelete, "/v1/tenants/"+name, "owner", "") if rec.Code != http.StatusAccepted { diff --git a/internal/api/tenants_test.go b/internal/api/tenants_test.go index 5ecc6e4..173c92c 100644 --- a/internal/api/tenants_test.go +++ b/internal/api/tenants_test.go @@ -28,7 +28,6 @@ var now = time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) type store struct { tenants map[string]tenants.Tenant created []tenants.CreateRequest - patched []string deleted []string err error } @@ -63,24 +62,11 @@ func (s *store) Create(_ context.Context, r tenants.CreateRequest) (tenants.Tena return tenants.Tenant{}, tenants.ErrExists } s.created = append(s.created, r) - t := tenants.Tenant{Name: r.Name, Owner: r.Owner, DisplayName: r.DisplayName, CreatedBy: r.CreatedBy, CreatedAt: now, NotReadySince: now} + t := tenants.Tenant{Name: r.Name, Owner: r.Owner, CreatedBy: r.CreatedBy, CreatedAt: now, NotReadySince: now} s.tenants[r.Name] = t return t, nil } -func (s *store) Patch(_ context.Context, name string, r tenants.PatchRequest) (tenants.Tenant, error) { - t, err := s.Get(context.Background(), name) - if err != nil { - return t, err - } - if r.DisplayName != nil { - t.DisplayName = *r.DisplayName - } - s.tenants[name] = t - s.patched = append(s.patched, name) - return t, nil -} - func (s *store) Delete(_ context.Context, name string) error { t, err := s.Get(context.Background(), name) if err != nil { @@ -429,7 +415,7 @@ func TestACrossplaneConditionNeverReachesTheClient(t *testing.T) { func TestCreate(t *testing.T) { e := newEnv(t) - rec := e.do(t, http.MethodPost, "/v1/tenants", "alice", `{"name":"newone","displayName":"New one"}`) + rec := e.do(t, http.MethodPost, "/v1/tenants", "alice", `{"name":"newone"}`) if rec.Code != http.StatusAccepted { t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) } @@ -506,40 +492,30 @@ func TestCreateRefusesABadRequest(t *testing.T) { } } -func TestPatch(t *testing.T) { +// A tenant has one name, which cannot change, and an owner, which cannot either: there is nothing left to patch, so the route is gone. +func TestATenantHasOneNameAndCannotBePatched(t *testing.T) { e := newEnv(t) - rec := e.do(t, http.MethodPatch, "/v1/tenants/demo", "admin", `{"displayName":"Production"}`) - if rec.Code != http.StatusOK { - t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) - } - var got tenantBody - mustDecode(t, rec, &got) - if got.DisplayName != "Production" || got.Owner != "alice@example.org" { - t.Errorf("body: %+v", got) - } - - for name, tt := range map[string]struct { - token, path, body string - want int - }{ - "the owner cannot be changed": {"admin", "/v1/tenants/demo", `{"owner":"mallory@example.org"}`, http.StatusBadRequest}, - "nor the name": {"admin", "/v1/tenants/demo", `{"name":"x"}`, http.StatusBadRequest}, - "an empty patch": {"admin", "/v1/tenants/demo", `{}`, http.StatusUnprocessableEntity}, - "a plan, there is none": {"admin", "/v1/tenants/demo", `{"plan":"large"}`, http.StatusBadRequest}, - "a tenant that does not exist": {"admin", "/v1/tenants/ghost", `{"displayName":"x"}`, http.StatusNotFound}, - "a member who sees the tenant": {"viewer", "/v1/tenants/demo", `{"displayName":"x"}`, http.StatusForbidden}, - "a stranger does not see it": {"mallory", "/v1/tenants/demo", `{"displayName":"x"}`, http.StatusNotFound}, - "a key without the scope": {"svc", "/v1/tenants/demo", `{"displayName":"x"}`, http.StatusForbidden}, - "nobody": {"", "/v1/tenants/demo", `{"displayName":"x"}`, http.StatusUnauthorized}, - } { - before := len(e.store.patched) - if rec := e.do(t, http.MethodPatch, tt.path, tt.token, tt.body); rec.Code != tt.want { - t.Errorf("%s: status %d, want %d (%.200s)", name, rec.Code, tt.want, rec.Body.String()) + for _, who := range []string{"admin", "viewer", "mallory", "svc", ""} { + if code := call(t, e, http.MethodPatch, "/v1/tenants/demo", who, `{"displayName":"Production"}`); code != http.StatusMethodNotAllowed { + t.Errorf("patch by %q: status %d, want 405", who, code) } - if tt.want != http.StatusOK && len(e.store.patched) != before { - t.Errorf("%s: the tenant was patched", name) + } + // and there is no display name to give when creating one either: the field is unknown, whatever the value + for _, body := range []string{`{"name":"newone","displayName":"New one"}`, `{"name":"newone","displayName":""}`} { + if code := call(t, e, http.MethodPost, "/v1/tenants", "alice", body); code != http.StatusBadRequest { + t.Errorf("%s: status %d, want 400", body, code) } } + if len(e.store.created) != 0 { + t.Errorf("a tenant was created: %+v", e.store.created) + } + var got tenantBody + mustDecode(t, e.do(t, http.MethodGet, "/v1/tenants/demo", "admin", ""), &got) + var raw map[string]any + mustDecode(t, e.do(t, http.MethodGet, "/v1/tenants/demo", "admin", ""), &raw) + if _, ok := raw["displayName"]; ok { + t.Errorf("the body of a tenant carries a display name: %v", raw) + } } func TestDelete(t *testing.T) { @@ -621,7 +597,6 @@ func TestAServiceKeyDoesWhatOpenFGAHoldsForIt(t *testing.T) { {"is refused what it has no tuple for", http.MethodGet, "/v1/tenants/demo/images", "", http.StatusForbidden}, {"lists the tenants it can read", http.MethodGet, "/v1/tenants", "", http.StatusOK}, {"cannot create a tenant", http.MethodPost, "/v1/tenants", `{"name":"newone"}`, http.StatusForbidden}, - {"cannot change a tenant", http.MethodPatch, "/v1/tenants/demo", `{"displayName":"x"}`, http.StatusForbidden}, {"cannot create a key", http.MethodPost, "/v1/apikeys", `{"displayName":"x","expiresAt":"2026-12-31T00:00:00Z","grants":[{"tenant":"demo","scopes":["tenants:read"]}]}`, http.StatusForbidden}, } { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/authz/authz.go b/internal/authz/authz.go index 718acf5..3407ee4 100644 --- a/internal/authz/authz.go +++ b/internal/authz/authz.go @@ -32,7 +32,7 @@ const ( WriteProfiles Action = "write_profiles" ReadMemberships Action = "read_memberships" WriteMemberships Action = "write_memberships" - // WriteTenant is changing and deleting the tenant that the caller administers: the admin role of the tenant, which the owner + // WriteTenant is deleting the tenant that the caller administers: the admin role of the tenant, which the owner // holds. A key has no scope for it yet. WriteTenant Action = "write_tenant" ) @@ -74,7 +74,7 @@ var keyScopes = map[string]Action{ // :, and a console groups them by resource. var scopeDescriptions = map[string]string{ "tenants:read": "See the tenant and what it holds", - "tenants:write": "Rename the tenant and delete it, which destroys its virtual machines", + "tenants:write": "Delete the tenant, which destroys its virtual machines", "instances:read": "See the instances", "instances:write": "Create, change, start, stop and delete instances", "images:read": "See the images", diff --git a/internal/kube/tenants.go b/internal/kube/tenants.go index 4bb9383..22d4772 100644 --- a/internal/kube/tenants.go +++ b/internal/kube/tenants.go @@ -2,7 +2,6 @@ package kube import ( "context" - "encoding/json" "fmt" "github.com/phorge-fr/phorge-api/internal/status" "strings" @@ -12,7 +11,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/dynamic" "github.com/phorge-fr/phorge-api/internal/tenants" @@ -86,9 +84,6 @@ func (s *Tenants) Create(ctx context.Context, req tenants.CreateRequest) (tenant return tenants.Tenant{}, err } spec := map[string]any{"owner": req.Owner} - if req.DisplayName != "" { - spec["displayName"] = req.DisplayName - } meta := map[string]any{"name": req.Name, "namespace": TenantNamespace} if req.CreatedBy != "" { meta["annotations"] = map[string]any{CreatedByAnnotation: req.CreatedBy} @@ -105,27 +100,6 @@ func (s *Tenants) Create(ctx context.Context, req tenants.CreateRequest) (tenant return tenantOf(obj), nil } -// Patch changes the display name, with a JSON merge patch on the fields that were given. -func (s *Tenants) Patch(ctx context.Context, name string, req tenants.PatchRequest) (tenants.Tenant, error) { - r, err := s.resource() - if err != nil { - return tenants.Tenant{}, err - } - spec := map[string]any{} - if req.DisplayName != nil { - spec["displayName"] = *req.DisplayName - } - patch, err := json.Marshal(map[string]any{"spec": spec}) - if err != nil { - return tenants.Tenant{}, err - } - obj, err := r.Patch(ctx, name, types.MergePatchType, patch, metav1.PatchOptions{}) - if err != nil { - return tenants.Tenant{}, mapError(err) - } - return tenantOf(obj), nil -} - // Delete deletes a tenant. What it holds goes first: the instances, then the memberships, the networks and the profiles of the user, then the images, each in the // foreground and without waiting for it, and then the Tenant itself, in the foreground too: the object stays, with a deletion // timestamp, until every resource it composed is gone (a Tenant was gone after 1 s in the background mode, its resources @@ -194,14 +168,12 @@ func mapError(err error) error { func tenantOf(obj *unstructured.Unstructured) tenants.Tenant { // A field of the wrong type reads as empty. owner, _, _ := unstructured.NestedString(obj.Object, "spec", "owner") - displayName, _, _ := unstructured.NestedString(obj.Object, "spec", "displayName") problems, _, _ := unstructured.NestedString(obj.Object, "status", "problems") namespace, _, _ := unstructured.NestedString(obj.Object, "status", "namespace") project, _, _ := unstructured.NestedString(obj.Object, "status", "incusProject") t := tenants.Tenant{ Name: obj.GetName(), - DisplayName: displayName, Owner: owner, CreatedAt: obj.GetCreationTimestamp().Time, CreatedBy: obj.GetAnnotations()[CreatedByAnnotation], diff --git a/internal/kube/tenants_test.go b/internal/kube/tenants_test.go index bc704d8..340a140 100644 --- a/internal/kube/tenants_test.go +++ b/internal/kube/tenants_test.go @@ -28,12 +28,12 @@ func TestCreateWritesTheObject(t *testing.T) { s, client := newTenantStore() got, err := s.Create(t.Context(), tenants.CreateRequest{ - Name: "demo", Owner: "Alice@Example.org", DisplayName: "Demo", CreatedBy: "user:admin@example.org", + Name: "demo", Owner: "Alice@Example.org", CreatedBy: "user:admin@example.org", }) if err != nil { t.Fatal(err) } - if got.Name != "demo" || got.Owner != "Alice@Example.org" || got.DisplayName != "Demo" || got.CreatedBy != "user:admin@example.org" { + if got.Name != "demo" || got.Owner != "Alice@Example.org" || got.CreatedBy != "user:admin@example.org" { t.Errorf("unexpected tenant: %+v", got) } @@ -60,7 +60,7 @@ func TestCreateLeavesOutWhatWasNotAsked(t *testing.T) { } obj, _ := client.Resource(tenantsGVR).Namespace(TenantNamespace).Get(t.Context(), "demo", metav1.GetOptions{}) if _, found, _ := unstructured.NestedString(obj.Object, "spec", "displayName"); found { - t.Error("an empty display name was sent") + t.Error("a display name was sent: a tenant has one name") } } @@ -95,39 +95,10 @@ func TestGetAndListAndNotFound(t *testing.T) { if err := s.Delete(t.Context(), "ghost"); !errors.Is(err, tenants.ErrNotFound) { t.Errorf("delete: err = %v, want ErrNotFound", err) } - if _, err := s.Patch(t.Context(), "ghost", tenants.PatchRequest{DisplayName: ptr("x")}); !errors.Is(err, tenants.ErrNotFound) { - t.Errorf("patch: err = %v, want ErrNotFound", err) - } } func ptr[T any](v T) *T { return &v } -func TestPatchChangesOnlyWhatWasGiven(t *testing.T) { - s, client := newTenantStore() - if _, err := s.Create(t.Context(), tenants.CreateRequest{Name: "demo", Owner: "a@b", DisplayName: "Old"}); err != nil { - t.Fatal(err) - } - - got, err := s.Patch(t.Context(), "demo", tenants.PatchRequest{DisplayName: ptr("New")}) - if err != nil { - t.Fatal(err) - } - if got.DisplayName != "New" || got.Owner != "a@b" { - t.Errorf("after the rename: %+v", got) - } - - if _, err := s.Patch(t.Context(), "demo", tenants.PatchRequest{DisplayName: ptr("")}); err != nil { - t.Fatal(err) - } - obj, _ := client.Resource(tenantsGVR).Namespace(TenantNamespace).Get(t.Context(), "demo", metav1.GetOptions{}) - if name, _, _ := unstructured.NestedString(obj.Object, "spec", "displayName"); name != "" { - t.Errorf("display name = %q, want it cleared", name) - } - if owner, _, _ := unstructured.NestedString(obj.Object, "spec", "owner"); owner != "a@b" { - t.Errorf("owner = %q, a patch of the display name changed it", owner) - } -} - func TestDeleteIsInTheForeground(t *testing.T) { s, client := newTenantStore() if _, err := s.Create(t.Context(), tenants.CreateRequest{Name: "demo", Owner: "a@b"}); err != nil { @@ -245,7 +216,7 @@ func TestTenantOfReadsTheStatus(t *testing.T) { "name": "demo", "namespace": "phorge-system", "creationTimestamp": created.Format(time.RFC3339), "annotations": map[string]any{CreatedByAnnotation: "user:admin@example.org"}, }, - "spec": map[string]any{"owner": "a@b", "displayName": "Demo"}, + "spec": map[string]any{"owner": "a@b"}, "status": map[string]any{ "namespace": "t-demo", "incusProject": "t-demo", "problems": "Alias 'x' doesn't exist", "conditions": []any{ diff --git a/internal/openapi/openapi.yaml b/internal/openapi/openapi.yaml index c027322..7467535 100644 --- a/internal/openapi/openapi.yaml +++ b/internal/openapi/openapi.yaml @@ -112,6 +112,9 @@ paths: and 2 profiles), so there is nothing to choose and no `plan`: a body that gives one is `400`. A person owns a limited number of tenants: past it the answer is `409` with the code `quota_exceeded`. A key never creates a tenant. + A tenant has one name, the slug of `name`: there is no display name, and nothing else to change afterwards (the owner + cannot change either), so there is no `PATCH`. To hand a tenant over, give the new person the `admin` role with a membership. + The answer is `202`: the tenant exists but Crossplane takes about a minute to make its namespace, its Incus project and the three profiles `s`, `m` and `l`. It comes without a network: deploy one in it. Poll the `Location` until `phase` is `Ready`. A `phase` of `Failed` comes with `problems`, what is wrong in words made for you; the details of the platform are not shown. @@ -172,43 +175,6 @@ paths: $ref: "#/components/responses/NotFound" "503": $ref: "#/components/responses/Unavailable" - patch: - tags: - - Tenants - operationId: updateTenant - summary: Change the display name - description: | - The admins of the tenant, the owner among them, change its display name. The name and the owner cannot change: to - hand a tenant over, give the new person the `admin` role with a membership. - security: - - bearerAuth: [] - requestBody: - required: true - content: - application/json: - schema: - $ref: "#/components/schemas/TenantPatch" - responses: - "200": - description: The tenant. - content: - application/json: - schema: - $ref: "#/components/schemas/Tenant" - "400": - $ref: "#/components/responses/BadRequest" - "401": - $ref: "#/components/responses/Unauthenticated" - "403": - $ref: "#/components/responses/Forbidden" - "404": - $ref: "#/components/responses/NotFound" - "422": - $ref: "#/components/responses/Invalid" - "429": - $ref: "#/components/responses/TooManyRequests" - "503": - $ref: "#/components/responses/Unavailable" delete: tags: - Tenants @@ -2049,7 +2015,7 @@ components: type: string description: | What an API key may do on a tenant, named `:`. `instances:write` does not give `instances:read`. - `tenants:read` reads the tenant, `tenants:write` renames it and deletes it (which destroys its virtual machines). + `tenants:read` reads the tenant, `tenants:write` deletes it (which destroys its virtual machines). A key never creates a tenant. The list is also `GET /v1/apikeys/scopes`. enum: @@ -2241,10 +2207,8 @@ components: properties: name: type: string + description: The one name of the tenant. It is a slug, it cannot change, and it is the name of its Incus project too. example: demo - displayName: - type: string - maxLength: 100 owner: type: string description: Email of the owner, who is `admin` of the tenant. It cannot change. @@ -2293,17 +2257,6 @@ components: Email of the owner, exactly as it is in Authentik (case included). Leave it out: it is the caller's own email, and another one is `403`. example: alice@example.org - displayName: - type: string - maxLength: 100 - TenantPatch: - type: object - additionalProperties: false - minProperties: 1 - properties: - displayName: - type: string - maxLength: 100 Identity: type: object required: diff --git a/internal/tenants/tenants.go b/internal/tenants/tenants.go index a97c999..c887a7c 100644 --- a/internal/tenants/tenants.go +++ b/internal/tenants/tenants.go @@ -4,18 +4,13 @@ package tenants import ( "context" - "fmt" "time" - "unicode/utf8" "github.com/phorge-fr/phorge-api/internal/auth" "github.com/phorge-fr/phorge-api/internal/resource" "github.com/phorge-fr/phorge-api/internal/status" ) -// MaxDisplayName is the limit of the XRD (characters, not bytes). -const MaxDisplayName = 100 - // Phase is where a tenant is, for a client that polls it. type Phase = status.Phase @@ -32,11 +27,10 @@ const FailedAfter = status.FailedAfter // Tenant is a Tenant object as the API presents it. type Tenant struct { - Name string - DisplayName string - Owner string - CreatedAt time.Time - CreatedBy string + Name string + Owner string + CreatedAt time.Time + CreatedBy string // Namespace and IncusProject are set once the composition has made them. Namespace string @@ -64,20 +58,13 @@ func (t Tenant) MessageAt(now time.Time) string { // CreateRequest is what creating a tenant asks for. type CreateRequest struct { - Name string `json:"name"` - Owner string `json:"owner"` - DisplayName string `json:"displayName"` + Name string `json:"name"` + Owner string `json:"owner"` // CreatedBy is the subject of the caller, recorded on the object. Not part of the request body. CreatedBy string `json:"-"` } -// PatchRequest is what changes on a tenant. The name and the owner cannot: the owner is an OpenFGA tuple, which cannot be -// edited, and to hand a tenant over a Membership with the admin role is created. -type PatchRequest struct { - DisplayName *string `json:"displayName"` -} - // InvalidError lists what is wrong with a request, field by field. type InvalidError = resource.InvalidError @@ -90,24 +77,6 @@ func (r CreateRequest) Validate() error { if !auth.SafeEmail(r.Owner) { problems = append(problems, "owner must be an email address") } - if utf8.RuneCountInString(r.DisplayName) > MaxDisplayName { - problems = append(problems, fmt.Sprintf("displayName must be at most %d characters", MaxDisplayName)) - } - if len(problems) > 0 { - return &InvalidError{Problems: problems} - } - return nil -} - -// Validate checks the patch. -func (r PatchRequest) Validate() error { - var problems []string - if r.DisplayName == nil { - problems = append(problems, "nothing to change: give displayName") - } - if r.DisplayName != nil && utf8.RuneCountInString(*r.DisplayName) > MaxDisplayName { - problems = append(problems, fmt.Sprintf("displayName must be at most %d characters", MaxDisplayName)) - } if len(problems) > 0 { return &InvalidError{Problems: problems} } @@ -126,6 +95,5 @@ type Store interface { List(ctx context.Context) ([]Tenant, error) Get(ctx context.Context, name string) (Tenant, error) Create(ctx context.Context, r CreateRequest) (Tenant, error) - Patch(ctx context.Context, name string, r PatchRequest) (Tenant, error) Delete(ctx context.Context, name string) error } diff --git a/internal/tenants/tenants_test.go b/internal/tenants/tenants_test.go index e693ce6..ffa5259 100644 --- a/internal/tenants/tenants_test.go +++ b/internal/tenants/tenants_test.go @@ -35,12 +35,12 @@ func TestPhaseAt(t *testing.T) { } func TestCreateRequestValidate(t *testing.T) { - good := CreateRequest{Name: "demo", Owner: "alice@example.org", DisplayName: "Demo"} + good := CreateRequest{Name: "demo", Owner: "alice@example.org"} if err := good.Validate(); err != nil { t.Fatal(err) } if err := (CreateRequest{Name: "demo", Owner: "alice@example.org"}).Validate(); err != nil { - t.Errorf("the display name is optional: %v", err) + t.Errorf("the owner keeps its case: %v", err) } if err := (CreateRequest{Name: "ab", Owner: "Alice@Example.org"}).Validate(); err != nil { t.Errorf("the owner keeps its case, a two letters name is fine: %v", err) @@ -58,7 +58,6 @@ func TestCreateRequestValidate(t *testing.T) { "an owner that is a wildcard": {Name: "demo", Owner: "*"}, "an owner with a relation": {Name: "demo", Owner: "a@b#admin"}, "an owner with a space": {Name: "demo", Owner: "a @b"}, - "a display name too long": {Name: "demo", Owner: "a@b", DisplayName: strings.Repeat("é", MaxDisplayName+1)}, } { t.Run(name, func(t *testing.T) { var invalid *InvalidError @@ -68,37 +67,9 @@ func TestCreateRequestValidate(t *testing.T) { }) } - // Characters are counted, not bytes: 100 accents are 200 bytes. - if err := (CreateRequest{Name: "demo", Owner: "a@b", DisplayName: strings.Repeat("é", MaxDisplayName)}).Validate(); err != nil { - t.Errorf("100 characters were refused: %v", err) - } - - err := CreateRequest{Name: "D", Owner: "x", DisplayName: strings.Repeat("a", MaxDisplayName+1)}.Validate() + err := CreateRequest{Name: "D", Owner: "x"}.Validate() var invalid *InvalidError - if !errors.As(err, &invalid) || len(invalid.Problems) != 3 { + if !errors.As(err, &invalid) || len(invalid.Problems) != 2 { t.Errorf("every problem is reported at once: %v", err) } } - -func TestPatchRequestValidate(t *testing.T) { - name := "Production" - long := strings.Repeat("a", MaxDisplayName+1) - empty := "" - - for name, ok := range map[string]PatchRequest{ - "a display name": {DisplayName: &name}, - "an empty name clears": {DisplayName: &empty}, - } { - if err := ok.Validate(); err != nil { - t.Errorf("%s: %v", name, err) - } - } - for name, req := range map[string]PatchRequest{ - "nothing": {}, - "a display name too long": {DisplayName: &long}, - } { - if err := req.Validate(); err == nil { - t.Errorf("%s was accepted", name) - } - } -}