diff --git a/AGENTS.md b/AGENTS.md index 0cb1697..00cf7c9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,6 +70,12 @@ 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` + (`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. - **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 6d66665..97f672f 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ following endpoint families are implemented: | -------------------- | ------------------------------------- | -------------------------------------------------------------------- | | `c.ACLs` | `///_acl` | Get / SetPermission / Grant / Revoke on an `ACLTarget` (`ObjectACL`, `OrgACL`, `UserACL`); users and clients kept apart (`detail=granular`) | | `c.Associations` | `/organizations/O/users`, `/association_requests`, `/users/U/...` | Members (ListMembers/GetMember/AddMember/RemoveMember), org invites (ListInvites/Invite/RescindInvite), user invites (ListUserInvites/UserInviteCount/AcceptInvite/RejectInvite) and ListUserOrgs | -| `c.Clients` | `/clients` | List / Get / Create / Update / Delete / Reregister | +| `c.Clients` | `/clients` | List / Get / Create / Update (can rename) / Delete / Reregister (in place) | | `c.Containers` | `/containers` | List / Get / Create / Delete | | `c.Cookbooks` | `/cookbooks` | List (latest version of each) / ListVersions (every cookbook, `num_versions`) / GetVersions (one cookbook, `num_versions`) / Get (with metadata) / Delete / Upload (sandbox flow) / Download / DownloadFiles (from a fetched manifest) / ListLatest / ListRecipes | | `c.CookbookArtifacts`| `/cookbook_artifacts` | List / GetVersions (one artifact) / Get (with metadata) / Delete / Upload; `CookbookArtifactListEntry.Has(identifier)` | @@ -58,7 +58,7 @@ following endpoint families are implemented: | `c.Stats` | `/_stats` (top-level, Basic auth) | Get (Erchef/PostgreSQL/VM metrics; not Chef-signed) | | `c.Status` | `/_status` | Get (server health + keygen pool) | | `c.Universe` | `/universe` | Get (known cookbooks + dependencies) | -| `c.Users` | `/users` (top-level) | List / Get / Create / Update / Delete / SetPassword / Authenticate | +| `c.Users` | `/users` (top-level) | List / Get / Create / Update (can rename) / Delete / SetPassword / Authenticate | | `c.Do` / `c.Fetch` / `c.Upload` | any path / any URL | `Do` sends a signed request to an absolute path and returns the body byte-for-byte (no decode); `ContextWithServerAPIVersion(ctx, v)` picks the API version per request. `Fetch` makes an unsigned GET (e.g. a bookshelf URL) and hands the body to a callback, retrying a truncated body with a fresh reader. `Upload` PUTs a file to a pre-signed sandbox URL (unsigned, Content-MD5, explicit length), reopening the body per attempt | Configurable via options: `WithHTTPClient`, `WithUserAgent`, @@ -125,16 +125,26 @@ model, so callers don't re-encode server conventions: have no optimistic concurrency, so a concurrent write in between (such as a chef-client run) is overwritten. - `Clients.Create` and `Users.Create` ask the server to generate the - `default` keypair (returned in `ChefKey.PrivateKey`) unless a `PublicKey` is - set; under API v1 the server would otherwise create them without a key. + `default` keypair unless a `PublicKey` is set; under API v1 the server + would otherwise create them without a key. Each returns its own result + (`ClientCreateResult`, `UserCreateResult`) carrying the new `URI` and the + key as `ChefKey`, whose `PrivateKey` is the only copy of a generated key. `KeyScope.Create` does the same for an added key, and sends an empty `ExpirationDate` as `"infinity"`, since the server requires one. - `Users.SetPassword(name, password)` — change a password. The server's user 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.Reregister(name)` — regenerate a client's `default` key and return - the new private key (creating one if the client has none). +- `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). + 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 + (one `PUT .../keys/default` with `create_key`) and return the new pair, + keeping the key's expiration; a client with no default key gets one + created. A client cannot reregister the key it signs with: the server + answers 403. - `ParsePolicyfileLock(data)` / `LoadPolicyfileLock(path)` — parse a `Policyfile.lock.json` into a `PolicyRevision`. The policy name, revision id, cookbook lock names and identifiers are checked against the patterns diff --git a/clients.go b/clients.go index c1a25f5..208acc8 100644 --- a/clients.go +++ b/clients.go @@ -3,7 +3,6 @@ package cinc import ( "context" "errors" - "fmt" ) // APIClient is a Chef API client (node or validator identity). It is named @@ -17,8 +16,14 @@ type APIClient struct { // Only Create sends it; Update does not, because the server rejects key // fields on update — manage keys with Keys.Client(name). PublicKey string `json:"public_key,omitempty"` +} - // ChefKey is populated only on the Create response. It is never sent. +// ClientCreateResult is the response from POST /clients: the new client's URI +// and its "default" key. Unless the APIClient carried a PublicKey, +// ChefKey.PrivateKey holds the server-generated private key. The server keeps +// no copy: capture it before the response is dropped. +type ClientCreateResult struct { + URI string `json:"uri,omitempty"` ChefKey ChefKey `json:"chef_key,omitzero"` } @@ -39,14 +44,6 @@ type clientUpdateRequest struct { Validator bool `json:"validator"` } -// ChefKey holds key material returned when a client is created. -type ChefKey struct { - Name string `json:"name,omitempty"` - PublicKey string `json:"public_key,omitempty"` - PrivateKey string `json:"private_key,omitempty"` - ExpirationDate string `json:"expiration_date,omitempty"` -} - // ClientsService accesses the /clients endpoints. type ClientsService struct{ client *Client } @@ -63,22 +60,35 @@ func (s *ClientsService) Get(ctx context.Context, name string) (*APIClient, *Res // Create creates a new client. Unless cl.PublicKey is set, the server generates // the client's "default" keypair and the result's ChefKey.PrivateKey carries // the private half — the only chance to capture it. -func (s *ClientsService) Create(ctx context.Context, cl *APIClient) (*APIClient, *Response, error) { +func (s *ClientsService) Create(ctx context.Context, cl *APIClient) (*ClientCreateResult, *Response, error) { req := clientCreateRequest{ Name: cl.Name, Validator: cl.Validator, PublicKey: cl.PublicKey, CreateKey: cl.PublicKey == "", } - created, resp, err := s.res().create(ctx, req) - return ptrOrNil(created, err), resp, err + r, resp, err := do[ClientCreateResult](ctx, s.client, "POST", s.res().coll(), req) + return ptrOrNil(r, err), resp, err } -// Update replaces an existing client's name and validator flag. Key fields on -// cl are not sent; manage keys with Keys.Client(name). -func (s *ClientsService) Update(ctx context.Context, cl *APIClient) (*APIClient, *Response, error) { +// Update replaces the named client's name and validator flag with cl's and +// returns the client as stored. To rename the client, set cl.Name to the new +// name: the server then answers 201 with the new location. An empty cl.Name +// keeps the current one. Key fields on cl are not sent; manage keys with +// Keys.Client(name). +// +// Chef Server keeps no keys across a client rename: the renamed client has +// none and cannot authenticate until it gets one, for example from +// Reregister, which creates a default key for a client that has none. +func (s *ClientsService) Update(ctx context.Context, name string, cl *APIClient) (*APIClient, *Response, error) { + if name == "" { + return nil, nil, errors.New("cinc: Clients.Update needs the client's current name") + } req := clientUpdateRequest{Name: cl.Name, Validator: cl.Validator} - updated, resp, err := s.res().update(ctx, cl.Name, req) + if req.Name == "" { + req.Name = name + } + updated, resp, err := s.res().update(ctx, name, req) return ptrOrNil(updated, err), resp, err } @@ -92,28 +102,18 @@ func (s *ClientsService) List(ctx context.Context) (map[string]string, *Response return s.res().list(ctx) } -// Reregister regenerates the named client's "default" key, invalidating the -// old private key and returning the new one (in the result's PrivateKey). +// Reregister regenerates the named client's "default" key in place, +// invalidating the old private key, and returns the new pair (PrivateKey and +// PublicKey). The key keeps its expiration date. A client with no default key +// gets one created, with no expiration. // -// The keys API has no in-place regenerate, so this deletes the existing -// "default" key and creates a fresh one with the server generating the pair. -// A client with no default key (the delete 404s) simply gets one created. -// The two calls are not atomic: if the create fails after the delete, the -// client is briefly left without a default key, and the returned error says so -// — recover by adding a key with Keys.Client(name).Create. +// The server will not regenerate the key a request is signed with, so a client +// cannot reregister itself; it answers 403 and the key is unchanged. func (s *ClientsService) Reregister(ctx context.Context, name string) (*Key, *Response, error) { keys := s.client.Keys.Client(name) - _, err := keys.Delete(ctx, "default") - if err != nil && !errors.Is(err, ErrNotFound) { - return nil, nil, err - } - deleted := err == nil - created, resp, err := keys.Create(ctx, &Key{Name: "default", CreateKey: true, ExpirationDate: "infinity"}) - if err != nil && !deleted { - return nil, resp, err - } - if err != nil { - return nil, resp, fmt.Errorf("cinc: reregister %q deleted the old default key but could not create a new one (add one with Keys.Client(%q).Create): %w", name, name, err) + k, resp, err := keys.Update(ctx, "default", &Key{Name: "default", CreateKey: true}) + if errors.Is(err, ErrNotFound) { + return keys.Create(ctx, &Key{Name: "default"}) } - return created, resp, nil + return k, resp, err } diff --git a/clients_test.go b/clients_test.go index 089c6e3..f9551e3 100644 --- a/clients_test.go +++ b/clients_test.go @@ -11,13 +11,27 @@ import ( "github.com/cinc-project/cinc-api/internal/cinctest" ) +// erchefClientCreateBody is erchef's answer to POST /clients under API v1: +// only the new client's uri, with the default key embedded as chef_key +// (oc_chef_wm_base:create_from_json, oc_chef_wm_key_base:create_object and +// finalize_create_body). The client's name and validator flag are not echoed. +const erchefClientCreateBody = `{ + "uri": "https://chef.example/organizations/o/clients/node2", + "chef_key": { + "name": "default", + "public_key": "-----BEGIN PUBLIC KEY-----\nPUB\n-----END PUBLIC KEY-----\n", + "expiration_date": "infinity", + "uri": "https://chef.example/organizations/o/clients/node2/keys/default", + "private_key": "-----BEGIN RSA PRIVATE KEY-----\nPRIV\n-----END RSA PRIVATE KEY-----\n" + } +}` + func TestClients_CRUD(t *testing.T) { srv := cinctest.New(t) srv.Handle("GET /organizations/o/clients/node1", cinctest.Route{Body: `{"name":"node1","validator":false}`}) srv.Handle("POST /organizations/o/clients", - cinctest.Route{Status: 201, - Body: `{"uri":"http://x/clients/node2","chef_key":{"private_key":"-----BEGIN"}}`}) + cinctest.Route{Status: 201, Body: erchefClientCreateBody}) srv.Handle("DELETE /organizations/o/clients/node1", cinctest.Route{Body: `{}`}) srv.Handle("GET /organizations/o/clients", cinctest.Route{Body: `{"node1":"http://x/clients/node1"}`}) @@ -30,8 +44,21 @@ func TestClients_CRUD(t *testing.T) { t.Fatalf("Get: %+v %v", cl, err) } created, _, err := c.Clients.Create(ctx, &APIClient{Name: "node2"}) - if err != nil || created.ChefKey.PrivateKey == "" { - t.Fatalf("Create: %+v %v", created, err) + if err != nil { + t.Fatalf("Create: %v", err) + } + want := ClientCreateResult{ + URI: "https://chef.example/organizations/o/clients/node2", + ChefKey: ChefKey{ + Name: "default", + PublicKey: "-----BEGIN PUBLIC KEY-----\nPUB\n-----END PUBLIC KEY-----\n", + PrivateKey: "-----BEGIN RSA PRIVATE KEY-----\nPRIV\n-----END RSA PRIVATE KEY-----\n", + ExpirationDate: "infinity", + URI: "https://chef.example/organizations/o/clients/node2/keys/default", + }, + } + if *created != want { + t.Fatalf("Create = %+v, want %+v", *created, want) } if _, err := c.Clients.Delete(ctx, "node1"); err != nil { t.Fatalf("Delete: %v", err) @@ -59,7 +86,7 @@ func TestClients_Create_RequestBody(t *testing.T) { srv := cinctest.New(t) srv.Handle("POST /organizations/o/clients", cinctest.Route{ Status: 201, - Body: `{"uri":"http://x/clients/web01","chef_key":{"name":"default","private_key":"-----BEGIN"}}`, + Body: erchefClientCreateBody, Assert: func(t *testing.T, _ *http.Request, body []byte) { m := decodeBody(t, body) if m["create_key"] != true { @@ -90,7 +117,8 @@ func TestClients_Create_RequestBody(t *testing.T) { srv := cinctest.New(t) srv.Handle("POST /organizations/o/clients", cinctest.Route{ Status: 201, - Body: `{"uri":"http://x/clients/web02","chef_key":{"name":"default","public_key":"PUB"}}`, + // With a supplied public key there is no private_key to embed. + Body: `{"uri":"https://chef.example/organizations/o/clients/web02","chef_key":{"name":"default","public_key":"PUB","expiration_date":"infinity","uri":"https://chef.example/organizations/o/clients/web02/keys/default"}}`, Assert: func(t *testing.T, _ *http.Request, body []byte) { m := decodeBody(t, body) if m["public_key"] != "PUB" { @@ -105,11 +133,28 @@ func TestClients_Create_RequestBody(t *testing.T) { }) c := newTestClient(t, srv.Server) - if _, _, err := c.Clients.Create(context.Background(), - &APIClient{Name: "web02", PublicKey: "PUB"}); err != nil { + got, _, err := c.Clients.Create(context.Background(), + &APIClient{Name: "web02", PublicKey: "PUB"}) + if err != nil { t.Fatalf("Create: %v", err) } + if got.ChefKey.PrivateKey != "" || got.ChefKey.PublicKey != "PUB" || got.URI == "" { + t.Errorf("Create = %+v, want the supplied public key and no private key", got) + } + }) +} + +// erchefClientPutBody is erchef's answer to a client PUT: the request body it +// validated, with name and clientname both set (chef_client:destination_name), +// validator filled in from the stored client when absent, plus json_class and +// chef_type (oc_chef_wm_base:update_from_json; chef_wm_named_client has no +// finalize_update_body). +func erchefClientPutBody(name string, validator bool) string { + b, _ := json.Marshal(map[string]any{ + "name": name, "clientname": name, "validator": validator, + "json_class": "Chef::ApiClient", "chef_type": "client", }) + return string(b) } func TestClients_Update_OmitsKeyFields(t *testing.T) { @@ -117,7 +162,7 @@ func TestClients_Update_OmitsKeyFields(t *testing.T) { // key_management_not_supported; keys are managed via the keys API. srv := cinctest.New(t) srv.Handle("PUT /organizations/o/clients/web01", cinctest.Route{ - Body: `{"name":"web01","validator":true}`, + Body: erchefClientPutBody("web01", true), Assert: func(t *testing.T, _ *http.Request, body []byte) { m := decodeBody(t, body) for _, k := range []string{"create_key", "public_key", "private_key", "chef_key"} { @@ -132,9 +177,8 @@ func TestClients_Update_OmitsKeyFields(t *testing.T) { }) c := newTestClient(t, srv.Server) - cl := &APIClient{Name: "web01", Validator: true, PublicKey: "PUB", - ChefKey: ChefKey{Name: "default", PrivateKey: "-----BEGIN"}} - if _, _, err := c.Clients.Update(context.Background(), cl); err != nil { + cl := &APIClient{Name: "web01", Validator: true, PublicKey: "PUB"} + if _, _, err := c.Clients.Update(context.Background(), "web01", cl); err != nil { t.Fatalf("Update: %v", err) } } @@ -142,22 +186,61 @@ func TestClients_Update_OmitsKeyFields(t *testing.T) { func TestClients_Update(t *testing.T) { srv := cinctest.New(t) srv.Handle("PUT /organizations/o/clients/monkeypants", - cinctest.Route{ - Body: `{"name":"monkeypants","clientname":"monkeypants","validator":true,"json_class":"Chef::ApiClient","chef_type":"client"}`, - }) + cinctest.Route{Body: erchefClientPutBody("monkeypants", true)}) c := newTestClient(t, srv.Server) - ctx := context.Background() + updated, _, err := c.Clients.Update(context.Background(), "monkeypants", + &APIClient{Name: "monkeypants", Validator: true}) + if err != nil { + t.Fatalf("Update: %v", err) + } + if updated.Name != "monkeypants" || !updated.Validator { + t.Fatalf("Update = %+v, want name=monkeypants validator=true", updated) + } +} - updated, _, err := c.Clients.Update(ctx, &APIClient{Name: "monkeypants", Validator: true}) +// A PUT whose body names a different client renames it: erchef answers 201 +// with a Location for the new name (oc_chef_wm_base:update_from_json -> +// handle_rename) and echoes the body. +func TestClients_Update_Rename(t *testing.T) { + srv := cinctest.New(t) + srv.Handle("PUT /organizations/o/clients/old", cinctest.Route{ + Status: 201, + Body: erchefClientPutBody("new", false), + Assert: func(t *testing.T, _ *http.Request, body []byte) { + if m := decodeBody(t, body); m["name"] != "new" { + t.Errorf("body = %s, want name=new", body) + } + }, + }) + + c := newTestClient(t, srv.Server) + updated, resp, err := c.Clients.Update(context.Background(), "old", &APIClient{Name: "new"}) if err != nil { t.Fatalf("Update: %v", err) } - if updated.Name != "monkeypants" { - t.Fatalf("Update: expected name=monkeypants, got %q", updated.Name) + if updated.Name != "new" || resp.StatusCode != http.StatusCreated { + t.Fatalf("Update = %+v (status %d), want name=new and 201", updated, resp.StatusCode) + } +} + +func TestClients_Update_EmptyBodyNameKeepsName(t *testing.T) { + srv := cinctest.New(t) + srv.Handle("PUT /organizations/o/clients/web01", cinctest.Route{ + Body: erchefClientPutBody("web01", true), + Assert: func(t *testing.T, _ *http.Request, body []byte) { + if m := decodeBody(t, body); m["name"] != "web01" { + t.Errorf("body = %s, want name=web01 from the path", body) + } + }, + }) + c := newTestClient(t, srv.Server) + cl := &APIClient{Validator: true} + if _, _, err := c.Clients.Update(context.Background(), "web01", cl); err != nil { + t.Fatalf("Update: %v", err) } - if !updated.Validator { - t.Fatalf("Update: expected validator=true, got false") + if cl.Name != "" { + t.Errorf("Update modified its argument: %+v", cl) } } @@ -167,117 +250,111 @@ func TestClients_Update_Errors(t *testing.T) { srv.Handle("PUT /organizations/o/clients/ghost", cinctest.Route{Status: 404, Body: `{"error":["client 'ghost' not found"]}`}) c := newTestClient(t, srv.Server) - _, _, err := c.Clients.Update(context.Background(), &APIClient{Name: "ghost"}) + _, _, err := c.Clients.Update(context.Background(), "ghost", &APIClient{Name: "ghost"}) if !errors.Is(err, ErrNotFound) { t.Fatalf("err = %v, want ErrNotFound", err) } }) + t.Run("empty name is refused before any request", func(t *testing.T) { + srv := cinctest.New(t) + c := newTestClient(t, srv.Server) + if _, _, err := c.Clients.Update(context.Background(), "", &APIClient{Name: "x"}); err == nil { + t.Fatal("Update with an empty name succeeded") + } + }) } +// erchefRegenerateBody is erchef's answer to PUT .../keys/default with +// {"name":"default","create_key":true}: the request body less create_key, plus +// the generated pair (oc_chef_wm_named_key:finalize_update_body). There is no +// uri and no expiration_date; the stored expiration is kept +// (chef_key:update_from_ejson). +const erchefRegenerateBody = `{"name":"default","private_key":"-----BEGIN RSA PRIVATE KEY-----\nNEW\n-----END RSA PRIVATE KEY-----\n","public_key":"-----BEGIN PUBLIC KEY-----\nNEWPUB\n-----END PUBLIC KEY-----\n"}` + func TestClients_Reregister(t *testing.T) { - t.Run("deletes then recreates the default key", func(t *testing.T) { + refuseCreate := cinctest.Route{ + Status: 201, Body: `{}`, + Assert: func(t *testing.T, _ *http.Request, _ []byte) { t.Error("Reregister POSTed a new key") }, + } + + t.Run("regenerates the default key in place", func(t *testing.T) { srv := cinctest.New(t) - var deleted, created bool - srv.Handle("DELETE /organizations/o/clients/node/keys/default", - cinctest.Route{Body: `{"name":"default"}`, Assert: func(*testing.T, *http.Request, []byte) { deleted = true }}) - srv.Handle("POST /organizations/o/clients/node/keys", cinctest.Route{ - Status: 201, - Body: `{"uri":"http://x/clients/node/keys/default","private_key":"-----BEGIN RSA PRIVATE KEY-----\nNEW\n-----END RSA PRIVATE KEY-----\n"}`, + srv.Handle("PUT /organizations/o/clients/node/keys/default", cinctest.Route{ + Body: erchefRegenerateBody, Assert: func(t *testing.T, _ *http.Request, body []byte) { - created = true - var k Key - if err := json.Unmarshal(body, &k); err != nil { - t.Fatalf("decode POST: %v", err) - } - if k.Name != "default" || !k.CreateKey || k.ExpirationDate != "infinity" { - t.Errorf("POST body = %+v, want name=default create_key=true expiration=infinity", k) + m := decodeBody(t, body) + if m["create_key"] != true || m["name"] != "default" || len(m) != 2 { + t.Errorf("PUT body = %s, want only name=default and create_key=true", body) } }, }) + srv.Handle("POST /organizations/o/clients/node/keys", refuseCreate) c := newTestClient(t, srv.Server) - got, _, err := c.Clients.Reregister(context.Background(), "node") + got, resp, err := c.Clients.Reregister(context.Background(), "node") if err != nil { t.Fatalf("Reregister: %v", err) } - if !deleted || !created { - t.Errorf("calls: deleted=%v created=%v, want both true", deleted, created) - } - if got.PrivateKey == "" { - t.Errorf("Reregister returned no private key: %+v", got) + if got.PrivateKey == "" || got.PublicKey == "" || got.Name != "default" || resp.StatusCode != http.StatusOK { + t.Errorf("Reregister = %+v (status %d), want the new pair", got, resp.StatusCode) } }) - t.Run("missing default key is created without a delete", func(t *testing.T) { + t.Run("missing default key is created", func(t *testing.T) { // A client created under API v1 without create_key or public_key has - // no "default" key, so the DELETE 404s; Reregister must still mint one. + // no "default" key, so the PUT 404s (oc_chef_wm_named_key:auth_info, + // key_not_found_response); Reregister must still mint one. srv := cinctest.New(t) - srv.Handle("DELETE /organizations/o/clients/keyless/keys/default", - cinctest.Route{Status: 404, Body: `{"error":["not found"]}`}) + srv.Handle("PUT /organizations/o/clients/keyless/keys/default", + cinctest.Route{Status: 404, Body: `{"error":["Could not find key 'default' for client 'keyless'"]}`}) srv.Handle("POST /organizations/o/clients/keyless/keys", cinctest.Route{ Status: 201, - Body: `{"uri":"http://x/clients/keyless/keys/default","private_key":"-----BEGIN RSA PRIVATE KEY-----\nNEW\n-----END RSA PRIVATE KEY-----\n"}`, + Body: `{"uri":"https://chef.example/organizations/o/clients/keyless/keys/default","private_key":"-----BEGIN RSA PRIVATE KEY-----\nNEW\n-----END RSA PRIVATE KEY-----\n"}`, + Assert: func(t *testing.T, _ *http.Request, body []byte) { + var k Key + if err := json.Unmarshal(body, &k); err != nil { + t.Fatalf("decode POST: %v", err) + } + if k.Name != "default" || !k.CreateKey || k.ExpirationDate != "infinity" { + t.Errorf("POST body = %+v, want name=default create_key=true expiration=infinity", k) + } + }, }) c := newTestClient(t, srv.Server) - got, _, err := c.Clients.Reregister(context.Background(), "keyless") + got, resp, err := c.Clients.Reregister(context.Background(), "keyless") if err != nil { t.Fatalf("Reregister: %v", err) } - if got.PrivateKey == "" { - t.Errorf("Reregister returned no private key: %+v", got) + if got.PrivateKey == "" || resp.StatusCode != http.StatusCreated { + t.Errorf("Reregister = %+v (status %d), want the created key", got, resp.StatusCode) } }) - t.Run("missing client reports ErrNotFound without claiming a delete", func(t *testing.T) { + t.Run("missing client reports ErrNotFound", func(t *testing.T) { srv := cinctest.New(t) - srv.Handle("DELETE /organizations/o/clients/ghost/keys/default", - cinctest.Route{Status: 404, Body: `{"error":["not found"]}`}) + srv.Handle("PUT /organizations/o/clients/ghost/keys/default", + cinctest.Route{Status: 404, Body: `{"error":["Cannot load client ghost"]}`}) srv.Handle("POST /organizations/o/clients/ghost/keys", - cinctest.Route{Status: 404, Body: `{"error":["not found"]}`}) + cinctest.Route{Status: 404, Body: `{"error":["Cannot load client ghost"]}`}) c := newTestClient(t, srv.Server) - _, _, err := c.Clients.Reregister(context.Background(), "ghost") - if !errors.Is(err, ErrNotFound) { + if _, _, err := c.Clients.Reregister(context.Background(), "ghost"); !errors.Is(err, ErrNotFound) { t.Fatalf("err = %v, want ErrNotFound", err) } - if contains(err.Error(), "deleted the old default key") { - t.Errorf("error %q claims a key was deleted when none existed", err.Error()) - } }) - t.Run("delete failure aborts before create", func(t *testing.T) { + t.Run("other PUT failures are returned without a create", func(t *testing.T) { + // erchef refuses with 403 when the request is signed with the key + // being regenerated (oc_chef_wm_named_key:auth_info, key_in_use). srv := cinctest.New(t) - var created bool - srv.Handle("DELETE /organizations/o/clients/node/keys/default", - cinctest.Route{Status: 403, Body: `{"error":["forbidden"]}`}) - srv.Handle("POST /organizations/o/clients/node/keys", - cinctest.Route{Status: 201, Body: `{}`, Assert: func(*testing.T, *http.Request, []byte) { created = true }}) + srv.Handle("PUT /organizations/o/clients/node/keys/default", + cinctest.Route{Status: 403, Body: `{"error":"The key 'default' was used to authenticate this request and cannot be modified or deleted."}`}) + srv.Handle("POST /organizations/o/clients/node/keys", refuseCreate) c := newTestClient(t, srv.Server) - _, _, err := c.Clients.Reregister(context.Background(), "node") - if !errors.Is(err, ErrForbidden) { - t.Fatalf("err = %v, want ErrForbidden from the delete", err) - } - if created { - t.Error("create was attempted after the delete failed") - } - }) - - t.Run("create failure is wrapped with recovery guidance", func(t *testing.T) { - srv := cinctest.New(t) - srv.Handle("DELETE /organizations/o/clients/node/keys/default", - cinctest.Route{Body: `{"name":"default"}`}) - srv.Handle("POST /organizations/o/clients/node/keys", - cinctest.Route{Status: 500, Body: `{"error":["boom"]}`}) - - c := newTestClient(t, srv.Server) - _, _, err := c.Clients.Reregister(context.Background(), "node") - if err == nil { - t.Fatal("expected an error when the recreate fails") - } - if !contains(err.Error(), "deleted the old default key") { - t.Errorf("error %q should explain the non-atomic recovery path", err.Error()) + if _, _, err := c.Clients.Reregister(context.Background(), "node"); !errors.Is(err, ErrForbidden) { + t.Fatalf("err = %v, want ErrForbidden from the PUT", err) } }) } diff --git a/integration/cincserverng/cincserverng_test.go b/integration/cincserverng/cincserverng_test.go index dc01342..6a01c5c 100644 --- a/integration/cincserverng/cincserverng_test.go +++ b/integration/cincserverng/cincserverng_test.go @@ -139,6 +139,10 @@ func startTarget(name string, opts server.Options, hc *http.Client) (suite.Targe // Not a server difference: erchef also lets the superuser take // admins off a grant ACE, and this target's admin is the superuser. "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", }, Client: func(t *testing.T) *cinc.Client { t.Helper() diff --git a/integration/suite/clients.go b/integration/suite/clients.go index 066f922..997b869 100644 --- a/integration/suite/clients.go +++ b/integration/suite/clients.go @@ -2,6 +2,7 @@ package suite import ( "context" + "errors" "testing" cinc "github.com/cinc-project/cinc-api" @@ -19,11 +20,11 @@ func testClientLifecycle(t *testing.T, _ Target, c *cinc.Client) { if err != nil { t.Fatalf("Create: %v", err) } - if created.ChefKey.PrivateKey == "" { - t.Fatalf("Create returned no private key: %+v", created) + if created.ChefKey.PrivateKey == "" || created.URI == "" || created.ChefKey.Name != "default" { + t.Fatalf("Create = %+v, want a uri and a generated default key", created) } - if _, _, err := c.Clients.Update(ctx, &cinc.APIClient{Name: name, Validator: true}); err != nil { + if _, _, err := c.Clients.Update(ctx, name, &cinc.APIClient{Name: name, Validator: true}); err != nil { t.Fatalf("Update: %v", err) } if got, _, err := c.Clients.Get(ctx, name); err != nil || !got.Validator { @@ -38,3 +39,98 @@ func testClientLifecycle(t *testing.T, _ Target, c *cinc.Client) { t.Fatal("Reregister did not return a fresh private key") } } + +// testClientRename renames a client through Update: the body carries the new +// name, the path the old one. The client keeps its key under the new name. +func testClientRename(t *testing.T, tgt Target, c *cinc.Client) { + ctx := t.Context() + oldName, newName := uniqueName(t, "client"), uniqueName(t, "client") + for _, n := range []string{oldName, newName} { + cleanup(t, "client "+n, func(ctx context.Context) error { + _, err := c.Clients.Delete(ctx, n) + return err + }) + } + if _, _, err := c.Clients.Create(ctx, &cinc.APIClient{Name: oldName}); err != nil { + t.Fatalf("Create: %v", err) + } + + updated, _, err := c.Clients.Update(ctx, oldName, &cinc.APIClient{Name: newName}) + if err != nil { + t.Fatalf("Update to rename: %v", err) + } + if updated.Name != newName { + t.Fatalf("Update = %+v, want name %s", updated, newName) + } + if _, _, err := c.Clients.Get(ctx, oldName); !errors.Is(err, cinc.ErrNotFound) { + t.Fatalf("Get old name after rename: err = %v, want ErrNotFound", err) + } + if got, _, err := c.Clients.Get(ctx, newName); err != nil || got.Name != newName { + t.Fatalf("Get new name after rename: %+v %v", got, err) + } + // erchef keeps no keys across a client rename (observed on CINC Server + // 15.10.125: the renamed client lists no keys and neither name + // authenticates), so Reregister, which creates a missing default key, + // is how a renamed client gets a working one. + key, _, err := c.Clients.Reregister(ctx, newName) + if err != nil { + t.Fatalf("Reregister after rename: %v", err) + } + as := clientAs(t, tgt, newName, key.PrivateKey) + if _, _, err := as.Nodes.List(ctx); err != nil { + t.Fatalf("list nodes as the renamed client with its new key: %v", err) + } +} + +// testClientReregisterKeepsClientUsable regenerates a client's default key and +// signs a request with the new one; the old one no longer authenticates. +func testClientReregisterKeepsClientUsable(t *testing.T, tgt Target, c *cinc.Client) { + ctx := t.Context() + name := uniqueName(t, "client") + cleanup(t, "client "+name, func(ctx context.Context) error { + _, err := c.Clients.Delete(ctx, name) + return err + }) + created, _, err := c.Clients.Create(ctx, &cinc.APIClient{Name: name}) + if err != nil { + t.Fatalf("Create: %v", err) + } + + key, _, err := c.Clients.Reregister(ctx, name) + if err != nil { + t.Fatalf("Reregister: %v", err) + } + if key.PrivateKey == "" || key.PrivateKey == created.ChefKey.PrivateKey { + t.Fatalf("Reregister = %+v, want a fresh private key", key) + } + if _, _, err := clientAs(t, tgt, name, key.PrivateKey).Nodes.List(ctx); err != nil { + t.Fatalf("list nodes with the regenerated key: %v", err) + } + if _, _, err := clientAs(t, tgt, name, created.ChefKey.PrivateKey).Nodes.List(ctx); !errors.Is(err, cinc.ErrUnauthorized) { + t.Fatalf("list nodes with the old key: err = %v, want ErrUnauthorized", err) + } + keys, _, err := c.Keys.Client(name).List(ctx) + if err != nil { + t.Fatalf("list keys: %v", err) + } + if len(keys) != 1 || keys[0].Name != "default" { + t.Fatalf("keys = %+v, want just default", keys) + } +} + +// testClientReregisterKeyless reregisters a client created without a key, +// which gets a default key created. +func testClientReregisterKeyless(t *testing.T, tgt Target, c *cinc.Client) { + ctx := t.Context() + name := newClient(t, c) + if _, err := c.Keys.Client(name).Delete(ctx, "default"); err != nil { + t.Fatalf("delete default key: %v", err) + } + key, _, err := c.Clients.Reregister(ctx, name) + if err != nil { + t.Fatalf("Reregister: %v", err) + } + if _, _, err := clientAs(t, tgt, name, key.PrivateKey).Nodes.List(ctx); err != nil { + t.Fatalf("list nodes with the created key: %v", err) + } +} diff --git a/integration/suite/suite.go b/integration/suite/suite.go index b4017b7..3b39a12 100644 --- a/integration/suite/suite.go +++ b/integration/suite/suite.go @@ -57,6 +57,9 @@ var cases = []testCase{ {"nodes/run-list-edit-normalized", testNodeRunListEditNormalized}, {"search/query", testSearchQuery}, {"clients/lifecycle", testClientLifecycle}, + {"clients/rename", testClientRename}, + {"clients/reregister-keeps-client-usable", testClientReregisterKeepsClientUsable}, + {"clients/reregister-keyless", testClientReregisterKeyless}, {"cookbooks/upload-download", testCookbookUploadDownload}, {"cookbook-artifacts/upload", testCookbookArtifactUpload}, {"policies/push-revision-two-groups", testPushRevisionToTwoGroups}, @@ -109,6 +112,7 @@ var cases = []testCase{ {"cookbooks/rejects-invalid-num-versions", testRejectsInvalidNumVersions}, {"clients/rejects-key-field-on-update", testRejectsKeyFieldOnClientUpdate}, {"users/lifecycle", testUserLifecycle}, + {"users/rename", testUserRename}, {"users/authenticate", testUserAuthenticate}, {"users/create-key-default", testUserCreateKeyDefault}, {"users/set-password", testUserSetPassword}, diff --git a/integration/suite/users.go b/integration/suite/users.go index 557caca..3807823 100644 --- a/integration/suite/users.go +++ b/integration/suite/users.go @@ -32,7 +32,7 @@ func testUserLifecycle(t *testing.T, _ Target, c *cinc.Client) { // is checked through a fresh Get rather than Update's return value. got.DisplayName = "Renamed " + name got.LastName = "Updated" - if _, err := c.Users.Update(ctx, got); err != nil { + if _, err := c.Users.Update(ctx, name, got); err != nil { t.Fatalf("Update: %v", err) } again, _, err := c.Users.Get(ctx, name) @@ -51,6 +51,36 @@ func testUserLifecycle(t *testing.T, _ Target, c *cinc.Client) { } } +// testUserRename renames a user through Update: the body carries the new +// username, the path the old one. The user keeps its key and password. +func testUserRename(t *testing.T, tgt Target, c *cinc.Client) { + ctx := t.Context() + oldName, key := newUser(t, c) + newName := uniqueName(t, "user") + cleanup(t, "user "+newName, func(ctx context.Context) error { + _, err := c.Users.Delete(ctx, newName) + return err + }) + got, _, err := c.Users.Get(ctx, oldName) + if err != nil { + t.Fatalf("Get: %v", err) + } + got.Username = newName + if _, err := c.Users.Update(ctx, oldName, got); err != nil { + t.Fatalf("Update to rename: %v", err) + } + if _, _, err := c.Users.Get(ctx, oldName); !errors.Is(err, cinc.ErrNotFound) { + t.Fatalf("Get old name after rename: err = %v, want ErrNotFound", err) + } + again, _, err := c.Users.Get(ctx, newName) + if err != nil || again.Username != newName || again.Email != got.Email { + t.Fatalf("Get new name after rename: %+v %v", again, err) + } + if _, _, err := clientAs(t, tgt, newName, key).Users.Get(ctx, newName); err != nil { + t.Fatalf("Get as the renamed user with its original key: %v", err) + } +} + // testUserAuthenticate checks a user's password through /authenticate_user. func testUserAuthenticate(t *testing.T, _ Target, c *cinc.Client) { ctx := t.Context() diff --git a/keys.go b/keys.go index 237958d..90bb75a 100644 --- a/keys.go +++ b/keys.go @@ -27,6 +27,17 @@ type Key struct { Expired bool `json:"expired,omitempty"` } +// ChefKey is the "default" key the server embeds as chef_key in its answer to +// creating a client or user (ClientCreateResult, UserCreateResult). +// PrivateKey is set only when the server generated the pair. +type ChefKey struct { + Name string `json:"name,omitempty"` + PublicKey string `json:"public_key,omitempty"` + PrivateKey string `json:"private_key,omitempty"` + ExpirationDate string `json:"expiration_date,omitempty"` + URI string `json:"uri,omitempty"` +} + // KeysService is the entry point for the Chef Server keys API. The same API // shape is reachable via two different paths: per-user at /users/USER/keys // (not org-scoped) and per-client at /organizations/ORG/clients/CLIENT/keys. diff --git a/orgs.go b/orgs.go index c8c5825..b1fe24d 100644 --- a/orgs.go +++ b/orgs.go @@ -11,9 +11,11 @@ type Org struct { GUID string `json:"guid,omitempty"` } -// OrgCreateResult is the response from POST /organizations. The PrivateKey -// is the generated validator client's RSA key and is returned **only** at -// creation time — store it before the response is dropped. +// OrgCreateResult is the response from POST /organizations: the new org's +// URI, the name of its generated validator client, and that client's +// server-generated private key (top-level here, where client and user creates +// embed it in ChefKey). The server keeps no copy: capture it before the +// response is dropped. type OrgCreateResult struct { URI string `json:"uri,omitempty"` ClientName string `json:"clientname,omitempty"` diff --git a/users.go b/users.go index 59add2c..d222273 100644 --- a/users.go +++ b/users.go @@ -1,6 +1,9 @@ package cinc -import "context" +import ( + "context" + "errors" +) // SuperuserName is the Chef Server's built-in superuser, "pivotal". Some // server-wide operations are reserved to it rather than to any org admin or @@ -32,13 +35,13 @@ type User struct { PublicKey string `json:"public_key,omitempty"` } -// UserCreateResult is the response from POST /users. ChefKey.PrivateKey holds -// the server-generated private key, which Create asks for unless the User -// carries a PublicKey. The server keeps no copy: capture it before the -// response is dropped. +// UserCreateResult is the response from POST /users: the new user's URI and +// its "default" key. Unless the User carried a PublicKey, ChefKey.PrivateKey +// holds the server-generated private key. The server keeps no copy: capture +// it before the response is dropped. type UserCreateResult struct { URI string `json:"uri,omitempty"` - ChefKey ChefKey `json:"chef_key"` + ChefKey ChefKey `json:"chef_key,omitzero"` } // UsersService accesses the top-level /users endpoints. @@ -70,14 +73,22 @@ func (s *UsersService) Create(ctx context.Context, u *User) (*UserCreateResult, return ptrOrNil(r, err), resp, err } -// Update replaces a user's metadata. Use Username as the lookup key; other -// fields are the new values. +// Update replaces the named user's metadata with u's. To rename the user, +// set u.Username to the new name: the server then answers 201 with the new +// location. An empty u.Username keeps the current one. u is not modified. // // The server answers with only the user's URI (unlike clients, orgs and // groups, whose PUT echoes the object), so there is nothing to return but // the response; Get the user to read back what was stored. -func (s *UsersService) Update(ctx context.Context, u *User) (*Response, error) { - _, resp, err := do[map[string]any](ctx, s.client, "PUT", "/users/"+esc(u.Username), u) +func (s *UsersService) Update(ctx context.Context, name string, u *User) (*Response, error) { + if name == "" { + return nil, errors.New("cinc: Users.Update needs the user's current name") + } + req := *u + if req.Username == "" { + req.Username = name + } + _, resp, err := do[map[string]any](ctx, s.client, "PUT", "/users/"+esc(name), &req) return resp, err } diff --git a/users_test.go b/users_test.go index d6c3bc9..6d1c95d 100644 --- a/users_test.go +++ b/users_test.go @@ -107,7 +107,7 @@ func TestUsers_Update(t *testing.T) { }, }) c := newTestClient(t, srv.Server) - resp, err := c.Users.Update(context.Background(), &User{ + resp, err := c.Users.Update(context.Background(), "alice", &User{ Username: "alice", DisplayName: "Alice Renamed", Email: "alice@example.com", }) if err != nil { @@ -118,6 +118,64 @@ func TestUsers_Update(t *testing.T) { } } +// A PUT whose body carries a different username renames the user: erchef +// answers 201 with a Location for the new name (oc_chef_wm_base:handle_rename) +// and a body of just the new uri (oc_chef_wm_named_user:finalize_update_body). +func TestUsers_Update_Rename(t *testing.T) { + srv := cinctest.New(t) + srv.Handle("PUT /users/alice", cinctest.Route{ + Status: 201, + Body: `{"uri":"https://chef.example.com/users/alicia"}`, + Assert: func(t *testing.T, _ *http.Request, body []byte) { + var got map[string]any + json.Unmarshal(body, &got) + if got["username"] != "alicia" { + t.Errorf("PUT body username = %v, want alicia", got["username"]) + } + }, + }) + c := newTestClient(t, srv.Server) + resp, err := c.Users.Update(context.Background(), "alice", &User{ + Username: "alicia", DisplayName: "Alicia", Email: "alice@example.com", + }) + if err != nil { + t.Fatalf("Update: %v", err) + } + if resp.StatusCode != http.StatusCreated { + t.Errorf("status = %d, want 201", resp.StatusCode) + } +} + +func TestUsers_Update_EmptyUsernameKeepsName(t *testing.T) { + srv := cinctest.New(t) + srv.Handle("PUT /users/alice", cinctest.Route{ + Body: `{"uri":"https://chef.example.com/users/alice"}`, + Assert: func(t *testing.T, _ *http.Request, body []byte) { + var got map[string]any + json.Unmarshal(body, &got) + if got["username"] != "alice" { + t.Errorf("PUT body username = %v, want alice from the path", got["username"]) + } + }, + }) + c := newTestClient(t, srv.Server) + u := &User{DisplayName: "Alice", Email: "alice@example.com"} + if _, err := c.Users.Update(context.Background(), "alice", u); err != nil { + t.Fatalf("Update: %v", err) + } + if u.Username != "" { + t.Errorf("Update modified its argument: %+v", u) + } +} + +func TestUsers_Update_EmptyName(t *testing.T) { + srv := cinctest.New(t) + c := newTestClient(t, srv.Server) + if _, err := c.Users.Update(context.Background(), "", &User{Username: "x"}); err == nil { + t.Fatal("Update with an empty name succeeded") + } +} + func TestUsers_Delete(t *testing.T) { srv := cinctest.New(t) srv.Handle("DELETE /users/alice", cinctest.Route{Body: `{}`})