From 3d779dda58281f90527277a11b382eb76c8a6235 Mon Sep 17 00:00:00 2001 From: l-nmch Date: Sat, 14 Nov 2026 18:06:00 +0100 Subject: [PATCH] feat: Change a profile in place PATCH /v1/tenants/{t}/profiles/{name} changes the description, the CPU, the memory, the root disk, the secure boot and the SSH keys of a profile a user made, with the checks of the creation. What is absent is left alone; s, m and l are refused. What Incus cannot do in place is refused with a 409 and what to do, before anything is sent: a smaller disk while an instance has the profile, less memory while an instance that has it is running, and a size that takes the tenant over its limits. A change never starts, stops or restarts an instance. Closes #135 --- docs/reference/endpoints.md | 4 +- docs/reference/images-and-instances.md | 5 +- internal/api/compute_test.go | 30 ++++ internal/api/keyscopes_test.go | 1 + internal/api/profiles.go | 118 ++++++++++++++ internal/api/profiles_test.go | 214 +++++++++++++++++++++++-- internal/authz/authz.go | 2 +- internal/compute/compute_test.go | 61 +++++++ internal/compute/profile.go | 57 +++++++ internal/kube/profiles.go | 55 +++++++ internal/kube/profiles_test.go | 49 ++++++ internal/openapi/openapi.yaml | 84 ++++++++++ internal/quota/quota.go | 37 +++++ 13 files changed, 701 insertions(+), 16 deletions(-) diff --git a/docs/reference/endpoints.md b/docs/reference/endpoints.md index f35bc33..0a66803 100644 --- a/docs/reference/endpoints.md +++ b/docs/reference/endpoints.md @@ -1,7 +1,7 @@ --- type: reference audience: developer calling the API -verified: 2026-11-08 +verified: 2026-11-14 --- # Endpoints @@ -16,7 +16,7 @@ verified: 2026-11-08 | `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) | | `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` | +| `GET`, `POST /v1/tenants/{t}/profiles`, `GET`, `PATCH`, `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` | | `GET`, `POST /v1/tenants/{t}/networks`, `GET`, `PATCH`, `DELETE /v1/tenants/{t}/networks/{name}` | The networks of a tenant, which comes without one: read with a role (`viewer` and above) or `networks:read`, write with `operator` or `networks:write` | | `GET`, `POST /v1/tenants/{t}/memberships`, `GET`, `DELETE /v1/tenants/{t}/memberships/{name}` | The roles of the users: admins of the tenant, and the keys with `memberships:read` and `memberships:write` on it | | `GET /v1/apikeys/scopes` | The scopes a key can be given, `:`, with what each does. For a person, like the other routes of the keys | diff --git a/docs/reference/images-and-instances.md b/docs/reference/images-and-instances.md index f815ea8..0075138 100644 --- a/docs/reference/images-and-instances.md +++ b/docs/reference/images-and-instances.md @@ -1,7 +1,7 @@ --- type: reference audience: developer or operator who works with images and virtual machines through the API -verified: 2026-11-11 +verified: 2026-11-14 --- # Images and instances @@ -20,4 +20,5 @@ Both live in the namespace `t-` of the `phorge.fr` group. - **The size of an instance is a profile or its own values, never both.** `profile` is one of `GET /v1/tenants/{t}/profiles` (`s` 1 vCPU, 2 GiB, 64 GiB; `m` 2, 4, 128; `l` 4, 8, 256); the other way is `cpu`, `memoryMiB` and `diskGiB`, and what a request leaves out takes 1, 1024 and 10 (the Crossplane kind has no defaults, the API completes the size). A profile with a value is `422`, so is a profile that does not exist, and the answer lists the profiles. The body of an instance carries its `profile` and, in every case, the `cpu`, `memoryMiB` and `diskGiB` it comes to. `GET /v1/limits` has the bounds. - **A size changes in place**: `PATCH` with a `profile` moves the instance to it and removes its own values; an instance that has a profile leaves it by being given the three values together (a value alone is `422`, it would sit next to the profile). Incus applies it live on a stopped instance. - **The resources of every tenant hold two instances of the profile `s`, or one `m`**: 2 instances, 2 vCPU, 4 GiB of memory and 128 GiB of disk, the same for every tenant. An instance that asks for more than what is left is refused with the limit it passes, before Incus is asked (see [Limits and quotas](limits-and-quotas.md)). -- **A user makes their own profiles** (`POST /v1/tenants/{t}/profiles`): CPU, memory and disk, all three given, under a name of 1 to 32 characters (`s`, `m`, `l` and `default` are taken, `422`). They are listed after the three every tenant has, with a phase and what is wrong in words. An instance takes one as it takes `s`, `m` or `l`, and counts in the quota what it comes to. Deleting one is refused (`409`, `in_use`) while an instance has it, and names the instances; `s`, `m` and `l` are not changed nor deleted (`403`). A tenant holds at most 2 of them (the same for every tenant, a third is `409`, `quota_exceeded`, `this tenant has 2 profiles out of 2 allowed (s, m and l do not count): delete one first`). A profile may also say two settings of an instance, `secureBoot` and `sshPublicKeys` (up to 20, checked as the keys of an instance, see the item on SSH keys). They are written on the object only when the request gives them: a profile that does not say one has none, and the body shows none, so an absent `secureBoot` is not `false`. An empty list is the same as none. An instance takes the settings of its profile unless it says its own: keys given by the instance replace the profile's, they do not add to them. A profile never has a network nor `nesting` (Incus refuses nesting on a profile of a tenant project, so nesting stays a setting of the instance): a request with either is `400`, an unknown field. Changing a profile in place is not in the API: make another one and move the instances to it. +- **A user makes their own profiles** (`POST /v1/tenants/{t}/profiles`): CPU, memory and disk, all three given, under a name of 1 to 32 characters (`s`, `m`, `l` and `default` are taken, `422`). They are listed after the three every tenant has, with a phase and what is wrong in words. An instance takes one as it takes `s`, `m` or `l`, and counts in the quota what it comes to. Deleting one is refused (`409`, `in_use`) while an instance has it, and names the instances; `s`, `m` and `l` are not changed nor deleted (`403`). A tenant holds at most 2 of them (the same for every tenant, a third is `409`, `quota_exceeded`, `this tenant has 2 profiles out of 2 allowed (s, m and l do not count): delete one first`). A profile may also say two settings of an instance, `secureBoot` and `sshPublicKeys` (up to 20, checked as the keys of an instance, see the item on SSH keys). They are written on the object only when the request gives them: a profile that does not say one has none, and the body shows none, so an absent `secureBoot` is not `false`. An empty list is the same as none. An instance takes the settings of its profile unless it says its own: keys given by the instance replace the profile's, they do not add to them. A profile never has a network nor `nesting` (Incus refuses nesting on a profile of a tenant project, so nesting stays a setting of the instance): a request with either is `400`, an unknown field. A profile is changed in place, see the next item. +- **A profile is changed in place** (`PATCH /v1/tenants/{t}/profiles/{name}`): `description`, `cpu`, `memoryMiB`, `diskGiB`, `secureBoot` and `sshPublicKeys`, with the bounds and the checks of the creation; what the body leaves out is left alone, and `s`, `m` and `l` are `403`. An empty `description` goes back to the one made from the size, `secureBoot: null` removes the setting and `sshPublicKeys: []` removes the keys. The instances that have the profile follow the change, the ones that say their own value do not. Measured on the platform with a running VM: a higher memory is seen by the guest at once, a higher CPU or disk is applied by Incus and the guest sees it after a restart, and a change never starts, stops or restarts an instance. What cannot be done in place is refused with `409` and a sentence that says what to do, before anything is sent: **a smaller disk** while an instance has the profile (`in_use`, naming them: Incus saves the profile and the VM keeps its disk, "Block volumes cannot be shrunk", so the two differ; make another profile and create the instances again with it); **less memory** while an instance that has it is running (`running`, as for an instance: stop it, change the profile, start it again); **a size that takes the tenant over a limit** (`quota_exceeded`: every instance that has the profile counts what it comes to, and Incus refuses it and leaves the Profile in error, "Reached maximum aggregate value"). A smaller CPU, or a smaller memory while the instances are stopped, is accepted. diff --git a/internal/api/compute_test.go b/internal/api/compute_test.go index 0125dbc..7f4b852 100644 --- a/internal/api/compute_test.go +++ b/internal/api/compute_test.go @@ -182,6 +182,7 @@ type profileStore struct { data map[string]map[string]compute.Profile err error created []compute.CreateProfile + patched []compute.PatchProfile deleted []string } @@ -221,6 +222,35 @@ func (s *profileStore) Create(_ context.Context, tenant string, r compute.Create return p, nil } +// Patch applies what the patch gives, as the merge patch of the real store does. +func (s *profileStore) Patch(_ context.Context, tenant, name string, r compute.PatchProfile) (compute.Profile, error) { + p, err := s.Get(context.Background(), tenant, name) + if err != nil { + return p, err + } + s.patched = append(s.patched, r) + if r.Description != nil { + p.Description = *r.Description + } + if r.CPU != nil { + p.CPU = *r.CPU + } + if r.MemoryMiB != nil { + p.MemoryMiB = *r.MemoryMiB + } + if r.DiskGiB != nil { + p.DiskGiB = *r.DiskGiB + } + if r.SecureBoot.Present { + p.SecureBoot = r.SecureBoot.Value + } + if r.SSHPublicKeys != nil { + p.SSHPublicKeys = *r.SSHPublicKeys + } + s.put(tenant, p) + return p, nil +} + func (s *profileStore) Delete(_ context.Context, tenant, name string) error { p, err := s.Get(context.Background(), tenant, name) if err != nil { diff --git a/internal/api/keyscopes_test.go b/internal/api/keyscopes_test.go index a76a290..1ecea22 100644 --- a/internal/api/keyscopes_test.go +++ b/internal/api/keyscopes_test.go @@ -25,6 +25,7 @@ func TestAKeyWithTheScopesOfTheNetworksTheProfilesAndTheTenantPassesTheirRoutes( // the profiles {"GET", "/v1/tenants/demo/profiles", "", http.StatusOK}, {"POST", "/v1/tenants/demo/profiles", `{"name":"api","cpu":1,"memoryMiB":1024,"diskGiB":10}`, http.StatusAccepted}, + {"PATCH", "/v1/tenants/demo/profiles/api", `{"cpu":2}`, http.StatusOK}, {"DELETE", "/v1/tenants/demo/profiles/api", "", http.StatusAccepted}, // what the scopes do not give {"GET", "/v1/tenants/demo/instances", "", http.StatusForbidden}, diff --git a/internal/api/profiles.go b/internal/api/profiles.go index b61b8b5..25989c9 100644 --- a/internal/api/profiles.go +++ b/internal/api/profiles.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "slices" + "strings" "time" "github.com/phorge-fr/phorge-api/internal/auth" @@ -30,6 +31,7 @@ func (p *profileRoutes) register(s *server.Server, authn func(http.Handler) http s.Handle("GET "+collection, authn(p.guard(authz.ReadProfiles, http.HandlerFunc(p.list)))) s.Handle("POST "+collection, authn(p.guard(authz.WriteProfiles, http.HandlerFunc(p.create)))) s.Handle("GET "+item, authn(p.guard(authz.ReadProfiles, http.HandlerFunc(p.get)))) + s.Handle("PATCH "+item, authn(p.guard(authz.WriteProfiles, http.HandlerFunc(p.patch)))) s.Handle("DELETE "+item, authn(p.guard(authz.WriteProfiles, http.HandlerFunc(p.delete)))) } @@ -138,6 +140,122 @@ func (p *profileRoutes) create(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusAccepted, p.body(pr)) } +// patch changes a profile a user made, in place: the instances that have it follow, the ones that say their own value do not. +// Incus applies a higher memory, a higher disk and any CPU to a running VM, and the instances are never stopped or started by it: what +// Incus would refuse, or leave half done, is refused here with what to do (measured on the platform, see the reference page). +func (p *profileRoutes) patch(w http.ResponseWriter, r *http.Request) { + tenant, name := r.PathValue("t"), r.PathValue("name") + if compute.Taken(name) { + httperr.Write(w, http.StatusForbidden, "forbidden", "the profile "+name+" is one every tenant has: it is not changed nor deleted") + return + } + if !compute.ValidNewProfileName(name) { + httperr.Write(w, http.StatusNotFound, "not_found", "no such profile") + return + } + var req compute.PatchProfile + if !decode(w, r, &req) { + return + } + if err := req.Validate(); err != nil { + p.storeError(w, err, "profile") + return + } + current, err := p.store.Get(r.Context(), tenant, name) + if err != nil { + p.storeError(w, err, "profile") + return + } + instances, err := p.instances.List(r.Context(), tenant) + if err != nil { + p.storeError(w, err, "instance") + return + } + if refused := p.refuseWhileInUse(w, current, req, instances); refused { + return + } + // Bigger, the profile makes the tenant bigger: every instance that has it counts what it comes to. Incus refuses a profile that + // passes a limit of the project and leaves the Profile in error until it is put back, so it is said here. + if req.CPU != nil || req.MemoryMiB != nil || req.DiskGiB != nil { + made, err := p.store.List(r.Context(), tenant) + if err != nil { + p.storeError(w, err, "profile") + return + } + cpu, mem, disk := orElse(req.CPU, current.CPU), orElse(req.MemoryMiB, current.MemoryMiB), orElse(req.DiskGiB, current.DiskGiB) + if e := quota.CheckProfileSize(instances, made, name, cpu, mem, disk); e != nil { + quotaExceeded(w, e) + return + } + } + + pr, err := p.store.Patch(r.Context(), tenant, name, req) + if err != nil { + p.storeError(w, err, "profile") + return + } + id, _ := auth.FromContext(r.Context()) + p.log.Info("profile changed", "tenant", tenant, "profile", name, "by", id.Subject) + writeJSON(w, http.StatusOK, p.body(pr)) +} + +// refuseWhileInUse answers, and reports true, when the patch asks for what a profile that instances have cannot do: a smaller disk (Incus +// saves the profile and the VM keeps its disk: "Block volumes cannot be shrunk"), or less memory while a VM is running, as for an +// instance (the API never stops one). It does not say who may change what: the route already did. +func (p *profileRoutes) refuseWhileInUse(w http.ResponseWriter, current compute.Profile, req compute.PatchProfile, instances []compute.Instance) bool { + var users, running []string + for _, in := range instances { + if in.Profile != current.Name { + continue + } + users = append(users, in.Name) + if in.State == "Running" { + running = append(running, in.Name) + } + } + slices.Sort(users) + slices.Sort(running) + switch { + case len(users) > 0 && req.DiskGiB != nil && *req.DiskGiB < current.DiskGiB: + httperr.Write(w, http.StatusConflict, "in_use", "a disk cannot be made smaller: "+listOf(users)+" "+haveOrHas(users)+" this profile. "+ + "Make another profile with the disk you want and create the instances again with it") + return true + case len(running) > 0 && req.MemoryMiB != nil && *req.MemoryMiB < current.MemoryMiB: + httperr.Write(w, http.StatusConflict, "running", "the memory of a running instance can only be raised: to lower it, stop "+listOf(running)+ + ", change the profile, then start "+themOrIt(running)+" again") + return true + } + return false +} + +func orElse(v *int, otherwise int) int { + if v != nil { + return *v + } + return otherwise +} + +func listOf(names []string) string { + if len(names) == 1 { + return "the instance " + names[0] + } + return "the instances " + strings.Join(names, ", ") +} + +func haveOrHas(names []string) string { + if len(names) == 1 { + return "has" + } + return "have" +} + +func themOrIt(names []string) string { + if len(names) == 1 { + return "it" + } + return "them" +} + func (p *profileRoutes) delete(w http.ResponseWriter, r *http.Request) { tenant, name := r.PathValue("t"), r.PathValue("name") if compute.Taken(name) { diff --git a/internal/api/profiles_test.go b/internal/api/profiles_test.go index 81c5bc9..aa486b6 100644 --- a/internal/api/profiles_test.go +++ b/internal/api/profiles_test.go @@ -185,17 +185,17 @@ func TestProfilesWhoMayDoWhat(t *testing.T) { const coll, item = "/v1/tenants/demo/profiles", "/v1/tenants/demo/profiles/web" create := `{"name":"new","cpu":1,"memoryMiB":1024,"diskGiB":10}` tests := []struct { - who string - list, get, create, delete int + who string + list, get, create, patch, delete int }{ - {"viewer", 200, 200, 403, 403}, - {"user", 200, 200, 403, 403}, - {"operator", 200, 200, 202, 202}, - {"admin", 200, 200, 202, 202}, - {"svc", 403, 403, 403, 403}, - {"svc_mgr", 403, 403, 403, 403}, - {"mallory", 404, 404, 404, 404}, - {"", 401, 401, 401, 401}, + {"viewer", 200, 200, 403, 403, 403}, + {"user", 200, 200, 403, 403, 403}, + {"operator", 200, 200, 202, 200, 202}, + {"admin", 200, 200, 202, 200, 202}, + {"svc", 403, 403, 403, 403, 403}, + {"svc_mgr", 403, 403, 403, 403, 403}, + {"mallory", 404, 404, 404, 404, 404}, + {"", 401, 401, 401, 401, 401}, } for _, tt := range tests { t.Run(tt.who, func(t *testing.T) { @@ -205,7 +205,8 @@ func TestProfilesWhoMayDoWhat(t *testing.T) { method, path, body string want int }{ - {"GET", coll, "", tt.list}, {"GET", item, "", tt.get}, {"POST", coll, create, tt.create}, {"DELETE", item, "", tt.delete}, + {"GET", coll, "", tt.list}, {"GET", item, "", tt.get}, {"POST", coll, create, tt.create}, + {"PATCH", item, `{"cpu":2}`, tt.patch}, {"DELETE", item, "", tt.delete}, } { if got := call(t, e, c.method, c.path, tt.who, c.body); got != c.want { t.Errorf("%s %s: status %d, want %d", c.method, c.path, got, c.want) @@ -525,3 +526,194 @@ func TestAnInstanceMovesToAProfileTheUserMade(t *testing.T) { t.Errorf("patch = %+v", p) } } + +func patchProfile(t *testing.T, e *env, who, name, body string) *httptest.ResponseRecorder { + t.Helper() + return e.do(t, "PATCH", "/v1/tenants/demo/profiles/"+name, who, body) +} + +func TestPatchAProfileChangesOnlyWhatIsGiven(t *testing.T) { + e := newEnv(t) + e.profiles.put("demo", madeProfile("web", 1, 1024, 10)) + rec := patchProfile(t, e, "operator", "web", `{"cpu":2,"description":"for the web servers"}`) + if rec.Code != http.StatusOK { + t.Fatalf("status %d: %s", rec.Code, rec.Body) + } + var body profileBody + mustDecode(t, rec, &body) + if body.CPU != 2 || body.MemoryMiB != 1024 || body.DiskGiB != 10 || body.Description != "for the web servers" { + t.Errorf("body = %+v: the cpu and the description changed, the rest did not", body) + } + if len(e.profiles.patched) != 1 || e.profiles.patched[0].MemoryMiB != nil || e.profiles.patched[0].DiskGiB != nil { + t.Errorf("what reached the store: %+v", e.profiles.patched) + } +} + +func TestPatchTheSettingsOfAProfile(t *testing.T) { + e := newEnv(t) + p := madeProfile("web", 1, 1024, 10) + on := true + p.SecureBoot, p.SSHPublicKeys = &on, []string{sshKey} + e.profiles.put("demo", p) + + // false is a value, null removes the setting, absent leaves it + if rec := patchProfile(t, e, "operator", "web", `{"secureBoot":false}`); rec.Code != http.StatusOK { + t.Fatalf("secure boot false: %d %s", rec.Code, rec.Body) + } + got, _ := e.profiles.Get(t.Context(), "demo", "web") + if got.SecureBoot == nil || *got.SecureBoot || len(got.SSHPublicKeys) != 1 { + t.Errorf("false: secure boot %v, %d keys", got.SecureBoot, len(got.SSHPublicKeys)) + } + if rec := patchProfile(t, e, "operator", "web", `{"secureBoot":null,"sshPublicKeys":[]}`); rec.Code != http.StatusOK { + t.Fatalf("null and []: %d %s", rec.Code, rec.Body) + } + got, _ = e.profiles.Get(t.Context(), "demo", "web") + if got.SecureBoot != nil || len(got.SSHPublicKeys) != 0 { + t.Errorf("null and []: secure boot %v, keys %v: both removed", got.SecureBoot, got.SSHPublicKeys) + } + var body profileBody + mustDecode(t, e.do(t, "GET", "/v1/tenants/demo/profiles/web", "viewer", ""), &body) + if body.SecureBoot != nil || body.SSHPublicKeys != nil { + t.Errorf("the body shows what was removed: %+v", body) + } + if rec := patchProfile(t, e, "operator", "web", `{"sshPublicKeys":["`+sshKey+` leo@laptop"]}`); rec.Code != http.StatusOK { + t.Fatalf("a key: %d %s", rec.Code, rec.Body) + } + got, _ = e.profiles.Get(t.Context(), "demo", "web") + if len(got.SSHPublicKeys) != 1 || got.SecureBoot != nil { + t.Errorf("a key: %v, secure boot %v left alone", got.SSHPublicKeys, got.SecureBoot) + } +} + +func TestPatchAProfileRefusesWhatCannotBePatched(t *testing.T) { + e := newEnv(t) + e.profiles.put("demo", madeProfile("web", 1, 1024, 10)) + for name, tt := range map[string]struct { + profile, body string + want int + say string + }{ + "a profile every tenant has": {"m", `{"cpu":4}`, http.StatusForbidden, "every tenant has"}, + "default": {"default", `{"cpu":4}`, http.StatusForbidden, "every tenant has"}, + "a profile that is not there": {"ghost", `{"cpu":4}`, http.StatusNotFound, ""}, + "a name that is not a name": {"Web!", `{"cpu":4}`, http.StatusNotFound, ""}, + "nothing": {"web", `{}`, http.StatusUnprocessableEntity, "nothing to change"}, + "a cpu too high": {"web", `{"cpu":17}`, http.StatusUnprocessableEntity, "cpu"}, + "a memory too low": {"web", `{"memoryMiB":10}`, http.StatusUnprocessableEntity, "memoryMiB"}, + "a disk of 0": {"web", `{"diskGiB":0}`, http.StatusUnprocessableEntity, "diskGiB"}, + "a bad key": {"web", `{"sshPublicKeys":["ssh-ed25519\nruncmd"]}`, http.StatusUnprocessableEntity, "key"}, + "the name": {"web", `{"name":"other"}`, http.StatusBadRequest, ""}, + "a network": {"web", `{"network":"net"}`, http.StatusBadRequest, ""}, + "nesting": {"web", `{"nesting":true}`, http.StatusBadRequest, ""}, + "a secure boot that is text": {"web", `{"secureBoot":"yes"}`, http.StatusBadRequest, ""}, + "not JSON": {"web", `cpu=2`, http.StatusBadRequest, ""}, + } { + rec := patchProfile(t, e, "operator", tt.profile, tt.body) + if rec.Code != tt.want || !strings.Contains(rec.Body.String(), tt.say) { + t.Errorf("%s: status %d, want %d, saying %q: %s", name, rec.Code, tt.want, tt.say, rec.Body) + } + } + if len(e.profiles.patched) != 0 { + t.Errorf("something reached the store: %+v", e.profiles.patched) + } + if code := call(t, e, "PATCH", "/v1/tenants/ghost/profiles/web", "admin", `{"cpu":2}`); code != http.StatusNotFound { + t.Errorf("a tenant that does not exist: %d", code) + } +} + +// Incus saves a smaller disk on the profile and the VM keeps its own ("Block volumes cannot be shrunk"): the two would differ. +func TestAProfileThatInstancesHaveCannotGetASmallerDisk(t *testing.T) { + e := newEnv(t) + e.profiles.put("demo", madeProfile("web", 1, 1024, 20)) + e.instances.put("demo", compute.Instance{Name: "b", Profile: "web", State: "Stopped"}) + e.instances.put("demo", compute.Instance{Name: "a", Profile: "web", State: "Running"}) + e.instances.put("demo", compute.Instance{Name: "c", Profile: "s", State: "Running"}) + + rec := patchProfile(t, e, "operator", "web", `{"diskGiB":10}`) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), `"in_use"`) || !strings.Contains(rec.Body.String(), "the instances a, b have this profile") || + !strings.Contains(rec.Body.String(), "Make another profile") || strings.Contains(rec.Body.String(), ", c") { + t.Errorf("status %d: %s: the refusal names the instances that have it, stopped ones too, and says what to do", rec.Code, rec.Body) + } + if len(e.profiles.patched) != 0 { + t.Errorf("a smaller disk reached the store: %+v", e.profiles.patched) + } + // the same disk, or a bigger one, is fine + for _, body := range []string{`{"diskGiB":20}`, `{"diskGiB":21}`} { + if code := call(t, e, "PATCH", "/v1/tenants/demo/profiles/web", "operator", body); code != http.StatusOK { + t.Errorf("%s: status %d", body, code) + } + } + // nobody has this profile: nothing holds its disk + e.profiles.put("demo", madeProfile("free", 1, 1024, 20)) + if code := call(t, e, "PATCH", "/v1/tenants/demo/profiles/free", "operator", `{"diskGiB":5}`); code != http.StatusOK { + t.Errorf("a profile nobody has: status %d", code) + } +} + +// As for an instance, never stopping it: the API says what to do. +func TestAProfileThatARunningInstanceHasCanOnlyGetMoreMemory(t *testing.T) { + e := newEnv(t) + e.profiles.put("demo", madeProfile("web", 2, 1024, 10)) + e.instances.put("demo", compute.Instance{Name: "a", Profile: "web", State: "Running"}) + e.instances.put("demo", compute.Instance{Name: "b", Profile: "web", State: "Stopped"}) + + rec := patchProfile(t, e, "operator", "web", `{"memoryMiB":512}`) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), `"running"`) || !strings.Contains(rec.Body.String(), "stop the instance a,") || + strings.Contains(rec.Body.String(), "the instances") || !strings.Contains(rec.Body.String(), "start it again") { + t.Errorf("status %d: %s: only the running instance is named", rec.Code, rec.Body) + } + if len(e.profiles.patched) != 0 { + t.Errorf("less memory reached the store: %+v", e.profiles.patched) + } + // the same memory, more of it (two instances of 2 GiB are the 4 GiB of the tenant) and a smaller cpu are fine + for _, body := range []string{`{"memoryMiB":1024}`, `{"memoryMiB":2048}`, `{"cpu":1}`} { + if code := call(t, e, "PATCH", "/v1/tenants/demo/profiles/web", "operator", body); code != http.StatusOK { + t.Errorf("%s: status %d", body, code) + } + } + // no instance runs: the memory may go down, and a smaller CPU is fine while one runs + e.instances.put("demo", compute.Instance{Name: "a", Profile: "web", State: "Stopped"}) + if code := call(t, e, "PATCH", "/v1/tenants/demo/profiles/web", "operator", `{"memoryMiB":1024}`); code != http.StatusOK { + t.Errorf("less memory, every instance stopped: status %d", code) + } +} + +// Every instance that has a profile counts what it comes to, and Incus refuses a profile that passes a limit of the project and leaves the +// Profile in error: so the tenant's limits (2 vCPU, 4 GiB, 128 GiB) are checked first. +func TestABiggerProfileCannotTakeTheTenantOverItsLimits(t *testing.T) { + e := newEnv(t) + e.profiles.put("demo", madeProfile("web", 1, 1024, 10)) + e.instances.put("demo", compute.Instance{Name: "a", Profile: "web", State: "Running"}) + e.instances.put("demo", compute.Instance{Name: "b", Profile: "web", State: "Running"}) + + for name, tt := range map[string]struct{ body, say string }{ + "the vCPU": {`{"cpu":2}`, "4 vCPU out of 2 allowed"}, + "the memory": {`{"memoryMiB":2049}`, "4098 MiB of memory out of 4 GiB allowed"}, + "the disk": {`{"diskGiB":65}`, "130 GiB of disk out of 128 GiB allowed"}, + } { + rec := patchProfile(t, e, "operator", "web", tt.body) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), `"quota_exceeded"`) || !strings.Contains(rec.Body.String(), tt.say) || + !strings.Contains(rec.Body.String(), "the instances with this profile count what it comes to") { + t.Errorf("%s: status %d: %s", name, rec.Code, rec.Body) + } + } + if len(e.profiles.patched) != 0 { + t.Errorf("a profile over the limits reached the store: %+v", e.profiles.patched) + } + // up to the limits is fine: 2 x 1 vCPU, 2 x 2 GiB, 2 x 64 GiB + if code := call(t, e, "PATCH", "/v1/tenants/demo/profiles/web", "operator", `{"cpu":1,"memoryMiB":2048,"diskGiB":64}`); code != http.StatusOK { + t.Errorf("up to the limits: status %d", code) + } + // with one instance, the sentence says it in the singular; an instance that has another profile does not count for this one + one := newEnv(t) + one.profiles.put("demo", madeProfile("big", 1, 1024, 10)) + one.instances.put("demo", compute.Instance{Name: "c", Profile: "big", State: "Running"}) + one.instances.put("demo", compute.Instance{Name: "d", Profile: "s", State: "Stopped"}) + if code := call(t, one, "PATCH", "/v1/tenants/demo/profiles/big", "operator", `{"cpu":1}`); code != http.StatusOK { + t.Errorf("the same cpu: status %d", code) + } + rec := patchProfile(t, one, "operator", "big", `{"cpu":2}`) + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "3 vCPU out of 2 allowed") || !strings.Contains(rec.Body.String(), "the instance with this profile counts") { + t.Errorf("one instance: status %d: %s", rec.Code, rec.Body) + } +} diff --git a/internal/authz/authz.go b/internal/authz/authz.go index 718acf5..a8a5606 100644 --- a/internal/authz/authz.go +++ b/internal/authz/authz.go @@ -82,7 +82,7 @@ var scopeDescriptions = map[string]string{ "networks:read": "See the networks", "networks:write": "Deploy and delete networks", "profiles:read": "See the profiles", - "profiles:write": "Make and delete profiles", + "profiles:write": "Make, change and delete profiles", "memberships:read": "See who has a role on the tenant", "memberships:write": "Give and take away roles on the tenant", } diff --git a/internal/compute/compute_test.go b/internal/compute/compute_test.go index ea218cc..f3ab381 100644 --- a/internal/compute/compute_test.go +++ b/internal/compute/compute_test.go @@ -1,6 +1,7 @@ package compute import ( + "encoding/json" "errors" "strings" "testing" @@ -454,3 +455,63 @@ func TestAProfileTakesTheSSHKeysOfAnInstance(t *testing.T) { } } } + +// An absent field is left alone, a null removes the setting, a value sets it: a plain pointer cannot tell the first two apart. +func TestPatchProfileTellsAbsentFromNull(t *testing.T) { + for name, tt := range map[string]struct { + body string + present, hasData bool + value bool + }{ + "absent": {`{"cpu":2}`, false, false, false}, + "null": {`{"secureBoot":null}`, true, false, false}, + "false": {`{"secureBoot":false}`, true, true, false}, + "true": {`{"secureBoot":true}`, true, true, true}, + } { + var got PatchProfile + if err := json.Unmarshal([]byte(tt.body), &got); err != nil { + t.Fatalf("%s: %v", name, err) + } + if got.SecureBoot.Present != tt.present || (got.SecureBoot.Value != nil) != tt.hasData || (tt.hasData && *got.SecureBoot.Value != tt.value) { + t.Errorf("%s: %+v", name, got.SecureBoot) + } + } + var got PatchProfile + if err := json.Unmarshal([]byte(`{"secureBoot":"yes"}`), &got); err == nil { + t.Error("a secure boot that is not a boolean was accepted") + } +} + +func TestPatchProfileValidate(t *testing.T) { + for name, ok := range map[string]PatchProfile{ + "a cpu": {CPU: ptr(2)}, + "a description": {Description: ptr("web")}, + "an emptied description": {Description: ptr("")}, + "a secure boot": {SecureBoot: Setting[bool]{Present: true, Value: ptr(false)}}, + "a secure boot removed": {SecureBoot: Setting[bool]{Present: true}}, + "no keys": {SSHPublicKeys: &[]string{}}, + "a key": {SSHPublicKeys: &[]string{goodKey}}, + "the bounds, low": {CPU: ptr(MinCPU), MemoryMiB: ptr(MinMemory), DiskGiB: ptr(MinDisk)}, + "the bounds, high": {CPU: ptr(MaxCPU), MemoryMiB: ptr(MaxMemory), DiskGiB: ptr(MaxDisk)}, + } { + if err := ok.Validate(); err != nil { + t.Errorf("%s: %v", name, err) + } + } + for name, bad := range map[string]PatchProfile{ + "nothing": {}, + "a cpu of 0": {CPU: ptr(0)}, + "a cpu too high": {CPU: ptr(MaxCPU + 1)}, + "a memory too low": {MemoryMiB: ptr(MinMemory - 1)}, + "a memory too high": {MemoryMiB: ptr(MaxMemory + 1)}, + "a disk of 0": {DiskGiB: ptr(0)}, + "a disk too high": {DiskGiB: ptr(MaxDisk + 1)}, + "a description too long": {Description: ptr(strings.Repeat("a", MaxProfileDescription+1))}, + "a bad key": {SSHPublicKeys: &[]string{"ssh-ed25519\nruncmd"}}, + } { + var invalid *InvalidError + if err := bad.Validate(); !errors.As(err, &invalid) { + t.Errorf("%s was accepted: %v", name, err) + } + } +} diff --git a/internal/compute/profile.go b/internal/compute/profile.go index 9f18391..5d93cde 100644 --- a/internal/compute/profile.go +++ b/internal/compute/profile.go @@ -2,6 +2,7 @@ package compute import ( "context" + "encoding/json" "regexp" "slices" "strings" @@ -103,12 +104,68 @@ func (r CreateProfile) Validate() error { return p.err() } +// Setting is a field of a patch that tells three things apart: absent (Present is false, the field is left alone), null (Present +// and a nil Value: the setting is removed) and a value. A plain pointer cannot: absent and null both decode to nil. +type Setting[T any] struct { + Present bool + Value *T +} + +// UnmarshalJSON is called for a null too, which is how a null is told from an absent field. +func (s *Setting[T]) UnmarshalJSON(b []byte) error { + s.Present = true + if string(b) == "null" { + s.Value = nil + return nil + } + var v T + if err := json.Unmarshal(b, &v); err != nil { + return err + } + s.Value = &v + return nil +} + +// PatchProfile is what changes on a profile a user made: what is absent is left alone. The name cannot change, and the profiles every +// tenant has (s, m and l) are not changed at all. +type PatchProfile struct { + // Description set to an empty string goes back to the one made from the size. + Description *string `json:"description"` + CPU *int `json:"cpu"` + MemoryMiB *int `json:"memoryMiB"` + DiskGiB *int `json:"diskGiB"` + // SecureBoot null removes the setting: an instance then takes the default of Incus. SSHPublicKeys set to an empty list removes + // the keys, which is the same as none, as it is when an instance is created. + SecureBoot Setting[bool] `json:"secureBoot"` + SSHPublicKeys *[]string `json:"sshPublicKeys"` +} + +// Validate checks the patch with the rules of the creation, before anything is sent to the cluster. +func (r PatchProfile) Validate() error { + var p problems + if r.Description == nil && r.CPU == nil && r.MemoryMiB == nil && r.DiskGiB == nil && !r.SecureBoot.Present && r.SSHPublicKeys == nil { + p.add("nothing to change: give description, cpu, memoryMiB, diskGiB, secureBoot or sshPublicKeys") + } + if r.Description != nil && len(*r.Description) > MaxProfileDescription { + p.add("description must be at most %d characters", MaxProfileDescription) + } + checkBounds(&p, "cpu", r.CPU, MinCPU, MaxCPU) + checkBounds(&p, "memoryMiB", r.MemoryMiB, MinMemory, MaxMemory) + checkBounds(&p, "diskGiB", r.DiskGiB, MinDisk, MaxDisk) + if r.SSHPublicKeys != nil { + checkKeys(&p, *r.SSHPublicKeys) + } + return p.err() +} + // ProfileStore reads and writes the profiles a user made in a tenant. The three every tenant is created with are not objects of // the API: they are BuiltinProfiles. Delete is in the foreground, like every deletion. type ProfileStore interface { List(ctx context.Context, tenant string) ([]Profile, error) Get(ctx context.Context, tenant, name string) (Profile, error) Create(ctx context.Context, tenant string, r CreateProfile) (Profile, error) + // Patch changes what the patch gives, in place: Crossplane updates the Incus profile, and the instances that have it follow. + Patch(ctx context.Context, tenant, name string, r PatchProfile) (Profile, error) // Delete returns an *InUseError when an instance still has the profile. Delete(ctx context.Context, tenant, name string) error } diff --git a/internal/kube/profiles.go b/internal/kube/profiles.go index 0c86ac9..f4512b7 100644 --- a/internal/kube/profiles.go +++ b/internal/kube/profiles.go @@ -2,11 +2,13 @@ package kube import ( "context" + "encoding/json" "strings" 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" "github.com/phorge-fr/phorge-api/internal/compute" ) @@ -83,6 +85,59 @@ func (s *Profiles) Create(ctx context.Context, tenant string, req compute.Create return profileOf(obj), nil } +// Patch is a JSON merge patch of the fields that were given. A description that is emptied, a secure boot that is set to null and an +// empty list of keys are removed from the object, which is then as if it had never said them: the composition writes nothing for them. +func (s *Profiles) Patch(ctx context.Context, tenant, name string, req compute.PatchProfile) (compute.Profile, error) { + r, err := namespaced(s.conn, profilesGVR, tenant) + if err != nil { + return compute.Profile{}, err + } + spec := map[string]any{} + if req.Description != nil { + spec["description"] = nilIfEmpty(*req.Description) + } + if req.CPU != nil { + spec["cpu"] = int64(*req.CPU) + } + if req.MemoryMiB != nil { + spec["memoryMiB"] = int64(*req.MemoryMiB) + } + if req.DiskGiB != nil { + spec["diskGiB"] = int64(*req.DiskGiB) + } + if req.SecureBoot.Present { + if req.SecureBoot.Value != nil { + spec["secureBoot"] = *req.SecureBoot.Value + } else { + spec["secureBoot"] = nil + } + } + if req.SSHPublicKeys != nil { + if len(*req.SSHPublicKeys) > 0 { + spec["sshPublicKeys"] = toAny(*req.SSHPublicKeys) + } else { + spec["sshPublicKeys"] = nil + } + } + patch, err := json.Marshal(map[string]any{"spec": spec}) + if err != nil { + return compute.Profile{}, err + } + obj, err := r.Patch(ctx, name, types.MergePatchType, patch, metav1.PatchOptions{}) + if err != nil { + return compute.Profile{}, mapError(err) + } + return profileOf(obj), nil +} + +// nilIfEmpty is the value of a field of a merge patch that an empty string removes. +func nilIfEmpty(s string) any { + if s == "" { + return nil + } + return s +} + // Delete deletes a profile in the foreground. A profile that an instance has is refused by an admission webhook of Crossplane // ("in-use by 1 usage(s)"): that is a conflict, not a failure. func (s *Profiles) Delete(ctx context.Context, tenant, name string) error { diff --git a/internal/kube/profiles_test.go b/internal/kube/profiles_test.go index 7ee83ab..a6ed3ab 100644 --- a/internal/kube/profiles_test.go +++ b/internal/kube/profiles_test.go @@ -159,3 +159,52 @@ func TestProfileDeleteIsInTheForegroundAndInUseIsAConflict(t *testing.T) { t.Errorf("err = %v, want an InUseError", err) } } + +func TestProfilePatchChangesOnlyWhatWasGiven(t *testing.T) { + s, client := newProfileStore() + if _, err := s.Create(t.Context(), "demo", compute.CreateProfile{Name: "web", Description: "old", CPU: ptr(1), MemoryMiB: ptr(1024), DiskGiB: ptr(10), + SecureBoot: ptr(false), SSHPublicKeys: []string{"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl"}}); err != nil { + t.Fatal(err) + } + get := func() compute.Profile { + obj, err := client.Resource(profilesGVR).Namespace("t-demo").Get(t.Context(), "web", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + return profileOf(obj) + } + + got, err := s.Patch(t.Context(), "demo", "web", compute.PatchProfile{CPU: ptr(2), MemoryMiB: ptr(2048)}) + if err != nil { + t.Fatal(err) + } + if got.CPU != 2 || got.MemoryMiB != 2048 || got.DiskGiB != 10 || got.Description != "old" || got.SecureBoot == nil || len(got.SSHPublicKeys) != 1 { + t.Errorf("only the size was given: %+v", got) + } + + // an emptied description, a secure boot set to null and an empty list of keys leave the object, as if it had never said them + if _, err := s.Patch(t.Context(), "demo", "web", compute.PatchProfile{Description: ptr(""), SecureBoot: compute.Setting[bool]{Present: true}, SSHPublicKeys: &[]string{}}); err != nil { + t.Fatal(err) + } + obj, _ := client.Resource(profilesGVR).Namespace("t-demo").Get(t.Context(), "web", metav1.GetOptions{}) + for _, field := range []string{"description", "secureBoot", "sshPublicKeys"} { + if _, found, _ := unstructured.NestedFieldNoCopy(obj.Object, "spec", field); found { + t.Errorf("spec.%s is still there", field) + } + } + if p := get(); p.CPU != 2 || p.DiskGiB != 10 { + t.Errorf("the size changed with the settings: %+v", p) + } + + // a value sets what was removed + if _, err := s.Patch(t.Context(), "demo", "web", compute.PatchProfile{SecureBoot: compute.Setting[bool]{Present: true, Value: ptr(true)}}); err != nil { + t.Fatal(err) + } + if p := get(); p.SecureBoot == nil || !*p.SecureBoot { + t.Errorf("secure boot not set: %+v", p.SecureBoot) + } + + if _, err := s.Patch(t.Context(), "demo", "ghost", compute.PatchProfile{CPU: ptr(2)}); !errors.Is(err, compute.ErrNotFound) { + t.Errorf("a profile that does not exist: err = %v", err) + } +} diff --git a/internal/openapi/openapi.yaml b/internal/openapi/openapi.yaml index 0ee9161..d2bb04a 100644 --- a/internal/openapi/openapi.yaml +++ b/internal/openapi/openapi.yaml @@ -667,6 +667,58 @@ paths: $ref: "#/components/responses/NotFound" "503": $ref: "#/components/responses/Unavailable" + patch: + tags: + - Profiles + operationId: updateProfile + summary: Change a profile + description: | + Changes a profile a user made, in place: what the body leaves out is left alone, and `s`, `m` and `l` are not changed + (`403`). The instances that have the profile follow, except the ones that say their own value. Same checks as the creation. + `description` set to `""` goes back to the one made from the size, `secureBoot` set to `null` removes the setting, and + `sshPublicKeys` set to `[]` removes the keys. + + Incus applies a higher memory to a running VM at once, a higher disk once the VM has it, and a CPU that the guest sees after + a restart. A change never starts, stops or restarts an instance. What cannot be done in place is refused with `409`, and + the sentence says what to do: + + - **a smaller disk**, while an instance has the profile (code `in_use`, naming the instances): a disk cannot be made + smaller. Make another profile with the disk you want and create the instances again with it. + - **less memory**, while an instance that has the profile is running (code `running`): as for an instance, stop it, change + the profile, then start it again. + - **a size that takes the tenant over a limit** (code `quota_exceeded`): every instance that has the profile counts what + it comes to, so a bigger profile is a bigger tenant. + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ProfilePatch" + responses: + "200": + description: The profile, as it is now. Crossplane updates the Incus profile a moment later. + content: + application/json: + schema: + $ref: "#/components/schemas/Profile" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthenticated" + "403": + $ref: "#/components/responses/Forbidden" + "404": + $ref: "#/components/responses/NotFound" + "409": + $ref: "#/components/responses/Conflict" + "422": + $ref: "#/components/responses/Invalid" + "429": + $ref: "#/components/responses/TooManyRequests" + "503": + $ref: "#/components/responses/Unavailable" delete: tags: - Profiles @@ -1610,6 +1662,38 @@ components: base64 and, at most, a comment of one word made of letters, digits and `@._+=/-`. Nothing else is accepted. items: type: string + ProfilePatch: + type: object + additionalProperties: false + minProperties: 1 + description: What changes on a profile. What is absent is left alone. The name cannot change. + properties: + description: + type: string + maxLength: 200 + description: An empty string goes back to the description made from the size. + cpu: + type: integer + minimum: 1 + maximum: 16 + memoryMiB: + type: integer + minimum: 256 + maximum: 65536 + diskGiB: + type: integer + minimum: 1 + maximum: 500 + secureBoot: + type: boolean + nullable: true + description: '`null` removes the setting: the instances that have the profile then take the default.' + sshPublicKeys: + type: array + maxItems: 20 + description: The keys of the creation, checked the same way. `[]` removes them, which is the same as none. + items: + type: string ProfileList: type: object required: diff --git a/internal/quota/quota.go b/internal/quota/quota.go index 9387569..11658d6 100644 --- a/internal/quota/quota.go +++ b/internal/quota/quota.go @@ -87,6 +87,43 @@ func CheckInstance(used Used, cpu, memMiB, diskGiB int) *Error { return nil } +// CheckProfileSize returns an *Error when giving the profile called name the size cpu, memMiB, diskGiB would take the tenant over a +// limit: every instance that has the profile counts what the profile comes to, so a bigger profile is a bigger tenant. Only what the +// change raises is checked: a tenant that holds more than it may (an instance made before a limit was lowered) can still shrink a +// profile. The count of instances does not change. +func CheckProfileSize(instances []compute.Instance, user []compute.Profile, name string, cpu, memMiB, diskGiB int) *Error { + var have compute.Profile + var users int + for _, p := range user { + if p.Name == name { + have = p + } + } + for _, in := range instances { + if in.Profile == name { + users++ + } + } + if users == 0 { + return nil + } + used := UsedBy(instances, nil, user) + l := PerTenant + which := fmt.Sprintf("the %s with this profile count what it comes to", plural(users, "instance", "instances")) + if users == 1 { + which = "the instance with this profile counts what it comes to" + } + switch { + case cpu > have.CPU && used.VCPU+users*(cpu-have.CPU) > l.VCPU: + return &Error{"vcpu", fmt.Sprintf("this profile would bring the tenant to %d vCPU out of %d allowed: %s", used.VCPU+users*(cpu-have.CPU), l.VCPU, which)} + case memMiB > have.MemoryMiB && used.MemoryMiB+users*(memMiB-have.MemoryMiB) > l.MemoryMiB: + return &Error{"memoryMiB", fmt.Sprintf("this profile would bring the tenant to %s of memory out of %s allowed: %s", gib(used.MemoryMiB+users*(memMiB-have.MemoryMiB)), gib(l.MemoryMiB), which)} + case diskGiB > have.DiskGiB && used.DiskGiB+users*(diskGiB-have.DiskGiB) > l.DiskGiB: + return &Error{"diskGiB", fmt.Sprintf("this profile would bring the tenant to %d GiB of disk out of %d GiB allowed: %s", used.DiskGiB+users*(diskGiB-have.DiskGiB), l.DiskGiB, which)} + } + return nil +} + // CheckNetwork returns an *Error when one more network would pass the limit of the tenant. func CheckNetwork(used Used) *Error { if l := PerTenant; used.Networks+1 > l.Networks {