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
11 changes: 6 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>` 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
Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down
52 changes: 30 additions & 22 deletions groups.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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.
Expand Down Expand Up @@ -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
}

Expand Down
2 changes: 1 addition & 1 deletion groups_members_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
109 changes: 87 additions & 22 deletions groups_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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)
}
}
Expand All @@ -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)
}
}
}
5 changes: 3 additions & 2 deletions integration/cincserverng/cincserverng_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
38 changes: 36 additions & 2 deletions integration/suite/groups.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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)
Expand All @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions integration/suite/suite.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down