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
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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
22 changes: 16 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ following endpoint families are implemented:
| -------------------- | ------------------------------------- | -------------------------------------------------------------------- |
| `c.ACLs` | `/<object>/<name>/_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)` |
Expand All @@ -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`,
Expand Down Expand Up @@ -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
Expand Down
74 changes: 37 additions & 37 deletions clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cinc
import (
"context"
"errors"
"fmt"
)

// APIClient is a Chef API client (node or validator identity). It is named
Expand All @@ -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"`
}

Expand All @@ -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 }

Expand All @@ -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
}

Expand All @@ -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
}
Loading
Loading