diff --git a/AGENTS.md b/AGENTS.md index 862c484..484bc8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,12 +71,13 @@ file new ones at cinc-project/cinc-server-ng): - **cinc-server-ng** accepts and stores `run_list: null` on a node, where a real Chef Server is stricter. That is why `run_list` always serializes as `[]`. -- **cinc-server-ng** does not rename a client or user whose PUT body names - a different one: it answers 200 and stores the new body under the old - name. erchef renames and answers 201 with a `Location` +- **cinc-server-ng** does not rename a client, user or group whose PUT body + names a different one: it answers 200 and stores the new body under the + old name. erchef renames and answers 201 with a `Location` (`oc_chef_wm_base:update_from_json` → `handle_rename`), which is what - `Clients.Update(name, cl)` and `Users.Update(name, u)` rely on; the - `clients/rename` and `users/rename` cases are gaps there. + `Clients.Update(name, cl)`, `Users.Update(name, u)` and + `Groups.Update(name, g)` rely on; the `clients/rename`, `users/rename` and + `groups/rename` cases are gaps there. - **cinc-server-ng** answers `PUT /users/` with the whole user; erchef sends only `{"uri"}` (`oc_chef_wm_named_user:finalize_update_body`), which is why `Users.Update` returns no `*User`. Client, org and group PUTs echo diff --git a/README.md b/README.md index 2150896..8f987bd 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ following endpoint families are implemented: | `c.CookbookArtifacts`| `/cookbook_artifacts` | List / GetVersions (one artifact) / Get (with metadata) / Delete / Upload; `CookbookArtifactListEntry.Has(identifier)` | | `c.DataBags` | `/data` | List / Create / Delete; per-bag Items handle for CRUD plus GetDecrypted / CreateEncrypted / UpdateEncrypted; `DataBagItem.Encrypt`/`Decrypt`/`IsEncrypted` for the Chef encrypted-data-bag format (writes v3 AES-256-GCM, reads v1/v2/v3) | | `c.Environments` | `/environments` | List / Get / Create / Update / Delete / ListCookbooks / GetCookbook / CookbookVersions / ListNodes / ListRecipes / RoleRunList | -| `c.Groups` | `/groups` | List / Get / Create / Update / Delete / AddMembers / RemoveMembers | +| `c.Groups` | `/groups` | List / Get / Create / Update (can rename) / Delete / AddMembers / RemoveMembers | | `c.Keys` | `/users/U/keys`, `/clients/C/keys` | `User(name)` / `Client(name)` → List / Get / Create / Update / Delete | | `c.License` | `/license` | Get (node-license usage) | | `c.Nodes` | `/nodes` | List / Get / Create / Update / Modify / Delete | @@ -138,9 +138,10 @@ model, so callers don't re-encode server conventions: PUT is a full update, so this re-sends the user's current fields with it. - `SuperuserName` — `"pivotal"`, the built-in superuser that creating orgs, `/authenticate_user` and invitation-free org membership are reserved to. -- `Clients.Update(name, cl)` and `Users.Update(name, u)` — the path is the - current name and the body the new values, so setting a different - `Name`/`Username` renames the client or user (the server answers 201). +- `Clients.Update(name, cl)`, `Users.Update(name, u)` and + `Groups.Update(name, g)` — the path is the current name and the body the + new values, so setting a different `Name`/`Username` (for a group, `Name` + or `GroupName`) renames the client, user or group (the server answers 201). Chef Server keeps no keys across a client rename; `Reregister` gives the renamed client a new `default` key. - `Clients.Reregister(name)` — regenerate a client's `default` key in place diff --git a/groups.go b/groups.go index c389fed..4ae55f5 100644 --- a/groups.go +++ b/groups.go @@ -139,20 +139,34 @@ func (s *GroupsService) Create(ctx context.Context, name string) (*Response, err return resp, err } -// Update replaces a group's members. The path segment is the group's name, -// taken from Name or, when that is empty, GroupName; the body is emitted in -// the {groupname, actors:{users,clients,groups}} shape the server requires on -// PUT. Nil member slices become empty JSON arrays rather than null. +// Update replaces the named group's members with g's and returns the group +// as the server echoes it. The body is emitted in the {groupname, +// actors:{users,clients,groups}} shape the server requires on PUT; nil member +// slices become empty JSON arrays rather than null. g is not modified. // -// A group with neither field set is an error rather than a PUT to the -// collection endpoint. -func (s *GroupsService) Update(ctx context.Context, g *Group) (*Group, *Response, error) { - name := g.name() +// To rename the group, set g.Name or g.GroupName to the new name (either +// one, so a group read with Get, which carries its name in both, can be +// renamed by changing one): the server then answers 201 with the new +// location. A field that is empty or holds the current name keeps it; the two +// naming different new names is an error. +func (s *GroupsService) Update(ctx context.Context, name string, g *Group) (*Group, *Response, error) { if name == "" { - return nil, nil, errors.New("cinc: group requires a Name or GroupName to update") + return nil, nil, errors.New("cinc: Groups.Update needs the group's current name") } + newName := name + for _, n := range []string{g.Name, g.GroupName} { + if n == "" || n == name || n == newName { + continue + } + if newName != name { + return nil, nil, fmt.Errorf("cinc: Groups.Update: Name %q and GroupName %q name different new names", g.Name, g.GroupName) + } + newName = n + } + // erchef takes the new name from "groupname" only + // (oc_chef_group:update_from_ejson), so that is the key sent. body := map[string]any{ - "groupname": name, + "groupname": newName, "actors": map[string]any{ "users": nonNil(g.Users), "clients": nonNil(g.Clients), @@ -161,17 +175,11 @@ func (s *GroupsService) Update(ctx context.Context, g *Group) (*Group, *Response } updated, resp, err := do[Group](ctx, s.client, "PUT", s.client.orgPath("/groups/"+esc(name)), body) - return ptrOrNil(updated, err), resp, err -} - -// name is the group's identifier. Chef identifies a group by "groupname"; -// "name" is a courtesy field carrying the same value that not every server -// populates, so prefer it but fall back. -func (g *Group) name() string { - if g.Name != "" { - return g.Name + if err == nil && updated.Name == "" { + // erchef echoes the PUT body, which carries no "name". + updated.Name = updated.GroupName } - return g.GroupName + return ptrOrNil(updated, err), resp, err } // Delete removes a group by name. @@ -252,8 +260,8 @@ func (s *GroupsService) changeMembers(ctx context.Context, group string, kind Me } else { removeMembers(list, sent) } - current.Name = group - if _, _, err := s.Update(ctx, current); err != nil { + current.Name, current.GroupName = "", "" // keep the name: never a rename + if _, _, err := s.Update(ctx, group, current); err != nil { return nil, err } diff --git a/groups_members_test.go b/groups_members_test.go index 7bc87dd..c56221c 100644 --- a/groups_members_test.go +++ b/groups_members_test.go @@ -80,7 +80,7 @@ func TestGroups_Update_DecodesEchoedPutBody(t *testing.T) { Body: `{"groupname":"devs","actors":{"users":["alice"],"clients":[],"groups":[]}}`, }) c := newTestClient(t, srv.Server) - got, _, err := c.Groups.Update(context.Background(), &Group{Name: "devs", Users: []string{"alice"}}) + got, _, err := c.Groups.Update(context.Background(), "devs", &Group{Users: []string{"alice"}}) if err != nil { t.Fatalf("Update: %v", err) } diff --git a/groups_test.go b/groups_test.go index 60dabcf..11366c0 100644 --- a/groups_test.go +++ b/groups_test.go @@ -110,7 +110,7 @@ func TestGroups_Update_WiresActorsFormat(t *testing.T) { Clients: []string{"node1"}, Groups: []string{"billing-admins"}, } - if _, _, err := c.Groups.Update(context.Background(), g); err != nil { + if _, _, err := c.Groups.Update(context.Background(), "devs", g); err != nil { t.Fatalf("Update: %v", err) } } @@ -139,7 +139,7 @@ func TestGroups_Update_NilSlicesBecomeEmptyArrays(t *testing.T) { }, }) c := newTestClient(t, srv.Server) - if _, _, err := c.Groups.Update(context.Background(), &Group{Name: "empty"}); err != nil { + if _, _, err := c.Groups.Update(context.Background(), "empty", &Group{}); err != nil { t.Fatalf("Update: %v", err) } } @@ -165,38 +165,103 @@ func TestGroups_NotFound(t *testing.T) { } // Chef identifies a group by "groupname"; "name" is a courtesy field not every -// server populates. Update must not depend on the courtesy field. -func TestGroupsUpdate_FallsBackToGroupName(t *testing.T) { - var path string - var req map[string]any +// server populates. With Name empty, GroupName is the name to send. +func TestGroups_Update_FallsBackToGroupName(t *testing.T) { srv := cinctest.New(t) srv.Handle("PUT /organizations/o/groups/admins", cinctest.Route{ - Body: `{"groupname":"admins"}`, - Assert: func(t *testing.T, r *http.Request, body []byte) { - path = r.URL.Path - if err := json.Unmarshal(body, &req); err != nil { - t.Fatalf("decode PUT: %v", err) + Body: `{"groupname":"admins","actors":{"users":["alice"],"clients":[],"groups":[]}}`, + Assert: func(t *testing.T, _ *http.Request, body []byte) { + if m := decodeBody(t, body); m["groupname"] != "admins" { + t.Errorf("body = %s, want groupname=admins", body) } }, }) c := newTestClient(t, srv.Server) g := &Group{GroupName: "admins", Users: []string{"alice"}} - if _, _, err := c.Groups.Update(context.Background(), g); err != nil { + if _, _, err := c.Groups.Update(context.Background(), "admins", g); err != nil { t.Fatalf("Update: %v", err) } - if path != "/organizations/o/groups/admins" { - t.Errorf("PUT path = %q", path) - } - if req["groupname"] != "admins" { - t.Errorf("groupname = %v, want admins", req["groupname"]) - } } -// With neither field set the old code PUT to /groups/ with groupname:"". -func TestGroupsUpdate_RequiresAName(t *testing.T) { +// A PUT whose groupname differs from the path renames the group: erchef +// answers 201 with a Location for the new name (oc_chef_wm_base: +// update_from_json -> handle_rename) and echoes the request body, since +// oc_chef_wm_named_group has no finalize_update_body. Only "groupname" is +// read for the new name (oc_chef_group:update_from_ejson); "name" is not. +func TestGroups_Update_Rename(t *testing.T) { srv := cinctest.New(t) + srv.Handle("PUT /organizations/o/groups/devs", cinctest.Route{ + Status: 201, + Body: `{"groupname":"ops","actors":{"users":["alice"],"clients":[],"groups":[]}}`, + Assert: func(t *testing.T, _ *http.Request, body []byte) { + m := decodeBody(t, body) + if m["groupname"] != "ops" { + t.Errorf("body = %s, want groupname=ops", body) + } + if _, ok := m["name"]; ok { + t.Errorf("body = %s, want no name key", body) + } + }, + }) + c := newTestClient(t, srv.Server) + for _, g := range []*Group{ + {Name: "ops", Users: []string{"alice"}}, + {GroupName: "ops", Users: []string{"alice"}}, + {Name: "ops", GroupName: "ops", Users: []string{"alice"}}, + } { + before := *g + updated, resp, err := c.Groups.Update(context.Background(), "devs", g) + if err != nil { + t.Fatalf("Update(%+v): %v", before, err) + } + if resp.StatusCode != http.StatusCreated || updated.Name != "ops" || updated.GroupName != "ops" || + !reflect.DeepEqual(updated.Users, []string{"alice"}) { + t.Errorf("Update(%+v) = %+v (status %d), want ops with alice and 201", before, updated, resp.StatusCode) + } + if !reflect.DeepEqual(*g, before) { + t.Errorf("Update modified the caller's group: %+v, was %+v", *g, before) + } + } +} + +func TestGroups_Update_Errors(t *testing.T) { + srv := cinctest.New(t) // no routes: neither call may reach the server c := newTestClient(t, srv.Server) - if _, _, err := c.Groups.Update(context.Background(), &Group{Users: []string{"alice"}}); err == nil { - t.Fatal("Update with no name returned nil error; want an error and no request") + if _, _, err := c.Groups.Update(context.Background(), "", &Group{Name: "devs"}); err == nil { + t.Error("Update with no current name returned nil error") + } + // Two different new names are ambiguous: refuse rather than guess. + if _, _, err := c.Groups.Update(context.Background(), "devs", &Group{Name: "ops", GroupName: "qa"}); err == nil { + t.Error("Update with Name and GroupName naming different new names returned nil error") + } +} + +// A group read with Get carries its name in both Name and GroupName; changing +// either one renames it, so a caller need not know which field is sent. +func TestGroups_Update_RenameFromAFetchedGroup(t *testing.T) { + for _, g := range []*Group{ + {Name: "ops", GroupName: "devs"}, + {Name: "devs", GroupName: "ops"}, + {Name: "ops", GroupName: "ops"}, + } { + srv := cinctest.New(t) + var sent string + srv.Handle("PUT /organizations/o/groups/devs", cinctest.Route{ + Status: 201, + Body: `{"groupname":"ops","actors":{"users":[],"clients":[],"groups":[]}}`, + Assert: func(t *testing.T, _ *http.Request, body []byte) { + var b struct { + GroupName string `json:"groupname"` + } + json.Unmarshal(body, &b) + sent = b.GroupName + }, + }) + if _, _, err := newTestClient(t, srv.Server).Groups.Update(context.Background(), "devs", g); err != nil { + t.Fatalf("%+v: %v", g, err) + } + if sent != "ops" { + t.Errorf("%+v: sent groupname %q, want ops", g, sent) + } } } diff --git a/integration/cincserverng/cincserverng_test.go b/integration/cincserverng/cincserverng_test.go index 6a01c5c..4863658 100644 --- a/integration/cincserverng/cincserverng_test.go +++ b/integration/cincserverng/cincserverng_test.go @@ -141,8 +141,9 @@ func startTarget(name string, opts server.Options, hc *http.Client) (suite.Targe "acls/revoke-keeps-admins-on-grant": "the admin here is the pivotal superuser, which erchef also exempts from this check", // erchef renames when a PUT body names a different object // (oc_chef_wm_base:update_from_json -> handle_rename, 201 with Location). - "clients/rename": "cinc-server-ng v0.22.0 answers a renaming client PUT with 200 and stores the new body under the old name; the old name still resolves and the new one 404s", - "users/rename": "cinc-server-ng v0.22.0 answers a renaming user PUT with 200 and stores the new body under the old name; the old name still resolves and the new one 404s", + "clients/rename": "cinc-server-ng v0.22.0 answers a renaming client PUT with 200 and stores the new body under the old name; the old name still resolves and the new one 404s: https://github.com/cinc-project/cinc-server-ng/issues/303", + "users/rename": "cinc-server-ng v0.22.0 answers a renaming user PUT with 200 and stores the new body under the old name; the old name still resolves and the new one 404s: https://github.com/cinc-project/cinc-server-ng/issues/303", + "groups/rename": "cinc-server-ng v0.22.0 answers a renaming group PUT with 200 and stores the new body under the old name; the old name still resolves and the new one 404s: https://github.com/cinc-project/cinc-server-ng/issues/303", }, Client: func(t *testing.T) *cinc.Client { t.Helper() diff --git a/integration/suite/groups.go b/integration/suite/groups.go index 74b593d..10de4ed 100644 --- a/integration/suite/groups.go +++ b/integration/suite/groups.go @@ -32,7 +32,7 @@ func testGroupLifecycle(t *testing.T, _ Target, c *cinc.Client) { t.Fatalf("%s missing from group list", group) } - updated, _, err := c.Groups.Update(ctx, &cinc.Group{Name: group, Clients: []string{client}, Groups: []string{inner}}) + updated, _, err := c.Groups.Update(ctx, group, &cinc.Group{Clients: []string{client}, Groups: []string{inner}}) if err != nil { t.Fatalf("Update (add members): %v", err) } @@ -49,7 +49,7 @@ func testGroupLifecycle(t *testing.T, _ Target, c *cinc.Client) { t.Fatalf("after update: group = %+v, want client %s and group %s", again, client, inner) } - if _, _, err := c.Groups.Update(ctx, &cinc.Group{Name: group}); err != nil { + if _, _, err := c.Groups.Update(ctx, group, &cinc.Group{}); err != nil { t.Fatalf("Update (remove members): %v", err) } emptied, _, err := c.Groups.Get(ctx, group) @@ -68,6 +68,40 @@ func testGroupLifecycle(t *testing.T, _ Target, c *cinc.Client) { } } +// testGroupRename renames a group through Update: the path carries the old +// name, the body's groupname the new one. The members move with it. +func testGroupRename(t *testing.T, _ Target, c *cinc.Client) { + ctx := t.Context() + client := newClient(t, c) + oldName := newGroup(t, c) + newName := uniqueName(t, "group") + cleanup(t, "group "+newName, func(ctx context.Context) error { + _, err := c.Groups.Delete(ctx, newName) + return err + }) + if _, _, err := c.Groups.Update(ctx, oldName, &cinc.Group{Clients: []string{client}}); err != nil { + t.Fatalf("Update (add member): %v", err) + } + + renamed, _, err := c.Groups.Update(ctx, oldName, &cinc.Group{Name: newName, Clients: []string{client}}) + if err != nil { + t.Fatalf("Update to rename: %v", err) + } + if renamed.Name != newName { + t.Fatalf("Update = %+v, want name %s", renamed, newName) + } + if _, _, err := c.Groups.Get(ctx, oldName); !errors.Is(err, cinc.ErrNotFound) { + t.Fatalf("Get old name after rename: err = %v, want ErrNotFound", err) + } + got, _, err := c.Groups.Get(ctx, newName) + if err != nil { + t.Fatalf("Get new name after rename: %v", err) + } + if got.Name != newName || !reflect.DeepEqual(got.Clients, []string{client}) { + t.Fatalf("after rename: group = %+v, want %s with client %s", got, newName, client) + } +} + // testGroupMemberAddRemove changes each kind of member through AddMembers and // RemoveMembers, and checks that a repeat is reported unchanged. func testGroupMemberAddRemove(t *testing.T, _ Target, c *cinc.Client) { diff --git a/integration/suite/suite.go b/integration/suite/suite.go index e403ee1..898e7ee 100644 --- a/integration/suite/suite.go +++ b/integration/suite/suite.go @@ -78,6 +78,7 @@ var cases = []testCase{ {"keys/rename", testKeyRename}, {"keys/create-defaults", testKeyCreateDefaults}, {"groups/lifecycle", testGroupLifecycle}, + {"groups/rename", testGroupRename}, {"groups/member-add-remove", testGroupMemberAddRemove}, {"groups/member-add-drops-unknown", testGroupMemberAddDropsUnknown}, {"containers/lifecycle", testContainerLifecycle},