cinc

package module
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 33 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cinc-api

A modern, idiomatic Go client for the Chef Infra / CINC Server API.

Install

go get github.com/cinc-project/cinc-api

Usage

key, _ := cinc.LoadKeyFile("/etc/chef/client.pem")
c, err := cinc.NewClient(cinc.Config{
    ServerURL:  "https://chef.example.com",
    Org:        "myorg",
    ClientName: "node1",
    Key:        key,
})
node, _, err := c.Nodes.Get(context.Background(), "web01")

Status

Authentication uses the Chef v1.3 SHA-256 signed-header protocol. The following endpoint families are implemented:

Service Path Methods
c.ACLs /<object>/<name>/_acl Get / SetPermission; org-level (GetOrg/SetOrgPermission) and global-user (GetUser/SetUserPermission)
c.Associations /organizations/O/users, /association_requests, /users/U/... Members (ListMembers/GetMember/AddMember/RemoveMember), org invites (ListInvites/Invite/RescindInvite), user invites (ListUserInvites/UserInviteCount/RespondInvite) and ListUserOrgs
c.Clients /clients List / Get / Create / Update / Delete / Reregister
c.Containers /containers List / Get / Create / Delete
c.Cookbooks /cookbooks List / GetVersions (one cookbook, num_versions) / Get (with metadata) / Delete / Upload (sandbox flow) / Download / ListLatest / ListRecipes
c.CookbookArtifacts /cookbook_artifacts List / GetVersions (one artifact) / Get (with metadata) / Delete / Upload
c.DataBags /data List / Create / Delete; per-bag Items handle for CRUD; 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
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 / Delete
c.Orgs /organizations (top-level) List / Get / Create / Update / Delete
c.Policies /policies List / Get / Delete / GetRevision / CreateRevision / DeleteRevision / PushRevision
c.PolicyGroups /policy_groups List / Get / Delete / GetPolicy / PutPolicy / DeletePolicy
c.Principals /principals/<name> Get (public key(s) + type for a user/client)
c.RequiredRecipe /required_recipe Get (returns Ruby text/plain)
c.Roles /roles List / Get / Create / Update / Delete / Environments / EnvironmentRunList
c.Search /search/INDEX Query (with WithStart/WithRows/WithPartial), All (iter.Seq2 over rows, one page in memory at a time), SearchAll, Indexes
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 (org + top-level) Get / GetGlobal (known cookbooks + dependencies)
c.Users /users (top-level) List / Get / Create / Update / Delete / Authenticate

Configurable via options: WithHTTPClient, WithUserAgent, WithChefVersion, WithSkipTLSVerify, WithMaxRetries, WithTransferTimeout. Idempotent GETs are retried on 5xx and network errors. Cookbook file transfers to and from the pre-signed bookshelf URLs (the sandbox PUTs of an upload, the GETs of a download) are retried the same way; the PUTs are safe to repeat because they are addressed by content checksum. Those transfers are bounded by WithTransferTimeout (default 10 minutes per attempt, 0 for no limit beyond the context) instead of the http.Client timeout, so a large file on a slow link is not cut off by the 30-second API timeout.

Helpers

Standalone helpers for working with Chef/CINC identities and the node object model, so callers don't re-encode server conventions:

  • ParseServerURL(raw) — split https://host/organizations/<org> into the base server URL and org (the inverse of NewClient's ServerURL/Org).
  • GenerateKeyPair() — mint a 2048-bit RSA key pair as PEM (the generation counterpart to ParseKey/LoadKeyFile).
  • Node accessors — Tags/SetTags/AddTags/RemoveTags (stored at normal.tags), AddRunListItems/RemoveRunListItems, and Attribute/AttributeString (precedence-aware lookup, dotted paths).
  • Clients.Create asks the server to generate the client's default keypair (returned in ChefKey.PrivateKey) unless APIClient.PublicKey is set.
  • Clients.Reregister(name) — regenerate a client's default key and return the new private key (creating one if the client has none).
  • ParsePolicyfileLock(data) / LoadPolicyfileLock(path) — parse a Policyfile.lock.json into a PolicyRevision.
  • CookbookLock accessors — Origin() (classify a lock's source_options as path/artifactserver/git/chef_server and return its location) and PinnedVersion() (the source_options version, falling back to the lock's top-level version).
  • DataBagItem.Encrypt(secret) / Decrypt(secret) / IsEncrypted() — the Chef encrypted-data-bag-item codec. Encrypt boxes every value except id in a version-3 (AES-256-GCM) wrapper; Decrypt reads versions 1, 2, and 3 and is byte-for-byte compatible with knife/chef-client. The AES key is sha256(secret); values round-trip through Chef's json_wrapper boxing.
  • Policies.PushRevision(lockJSON, group, cookbooks) — the server-side half of chef push: upload each pinned cookbook as an artifact, then associate the revision with a policy group. The lock bytes are sent verbatim so no fields are lost. Artifacts the server already has are skipped, so the same lock can be pushed to several groups and a failed push can be retried.
  • LoadChefignore(dir) / Chefignore.Ignores(relPath) — Chef's chefignore handling: the nearest chefignore in dir or any parent (so a chef-repo's cookbooks/chefignore applies), with each pattern matched against the cookbook-relative path exactly as Ruby's File.fnmatch? does. Cookbook uploads, archives, and identifier computation agree on which files belong to a cookbook. LocalCookbookFromDir honors it, and like Chef's loader also skips dot-directories at the cookbook root and takes the cookbook name from metadata.json / metadata.rb rather than the directory name.
  • ACL/ACE merge helpers — ACL.ACEFor(perm) selects the ACE for one permission, ACE.AddMembers/RemoveMembers dedupe-add or remove actors and groups (reporting whether anything changed), and ExpandPerm("all") expands to the five standard permissions — the reusable core of an ACL grant/revoke.

License

Licensed under the Apache License 2.0.

Documentation

Overview

Package cinc is a Go client for the Chef Infra / CINC Server API.

Construct a Client with NewClient, then call methods on its service fields:

key, _ := cinc.LoadKeyFile("/etc/chef/client.pem")
c, _ := cinc.NewClient(cinc.Config{
	ServerURL:  "https://chef.example.com",
	Org:        "myorg",
	ClientName: "node1",
	Key:        key,
})
node, _, err := c.Nodes.Get(context.Background(), "web01")

Requests are authenticated with the Chef v1.3 signed-header protocol.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotEncrypted means a value (or item) is not a well-formed
	// encryption wrapper — typically the item simply isn't encrypted.
	ErrNotEncrypted = errors.New("cinc: data bag item is not encrypted")
	// ErrDataBagAuth means decryption failed authentication: a wrong
	// secret, a tampered ciphertext, or a bad v2 HMAC.
	ErrDataBagAuth = errors.New("cinc: data bag item failed authentication (wrong secret or tampered data)")
)

Sentinel errors for encrypted data bag handling, for use with errors.Is.

View Source
var (
	ErrNotFound     = errors.New("cinc: not found")
	ErrConflict     = errors.New("cinc: conflict")
	ErrForbidden    = errors.New("cinc: forbidden")
	ErrUnauthorized = errors.New("cinc: unauthorized")
)

Sentinel errors for use with errors.Is.

View Source
var ACLPerms = []string{"create", "read", "update", "delete", "grant"}

ACLPerms are the five standard Chef permissions, in the order Chef lists them. The pseudo-permission "all" expands to this whole set.

Functions

func ExpandPerm

func ExpandPerm(perm string) ([]string, error)

ExpandPerm turns a permission argument into the concrete permissions it targets: "all" expands to every standard permission; a single valid permission returns just itself; anything else is an error.

func GenerateKeyPair

func GenerateKeyPair() (privatePEM, publicPEM string, err error)

GenerateKeyPair generates a 2048-bit RSA key pair and returns it PEM-encoded: the private key as PKCS#1 ("RSA PRIVATE KEY") and the public key as PKIX ("PUBLIC KEY"). It is the generation counterpart to ParseKey/LoadKeyFile, used to mint a new client identity — for example, registering a node's client by handing the server the public key while keeping the private key.

func LoadKeyFile

func LoadKeyFile(path string) (*rsa.PrivateKey, error)

LoadKeyFile reads and parses an RSA private key from a file path.

func ParseKey

func ParseKey(pemBytes []byte) (*rsa.PrivateKey, error)

ParseKey parses a PEM-encoded RSA private key (PKCS#1 or PKCS#8).

func ParseServerURL

func ParseServerURL(raw string) (serverURL, org string, err error)

ParseServerURL splits a Chef/CINC Server URL of the form https://host[:port]/organizations/<org> into its base server URL (scheme://host[:port]) and organization name.

It is the parsing counterpart to NewClient, which takes the base ServerURL and Org separately: callers that hold a single combined URL (as Chef's credentials files and CHEF_SERVER_URL store it) use this to derive the two.

Types

type ACE

type ACE struct {
	Actors []string `json:"actors"`
	Groups []string `json:"groups"`
}

ACE is a single access-control entry: the actors (users/clients by name) and groups granted one permission on one object.

func (*ACE) AddMembers

func (a *ACE) AddMembers(actors, groups []string) (changed bool)

AddMembers adds each actor and group to the ACE in place, skipping any that are already present, and reports whether the ACE changed. It is the "grant" half of an ACL read-modify-write.

func (*ACE) RemoveMembers

func (a *ACE) RemoveMembers(actors, groups []string) (changed bool)

RemoveMembers removes each actor and group from the ACE in place, ignoring any that are absent, and reports whether the ACE changed. It is the "revoke" half of an ACL read-modify-write.

type ACL

type ACL struct {
	Create ACE `json:"create"`
	Read   ACE `json:"read"`
	Update ACE `json:"update"`
	Delete ACE `json:"delete"`
	Grant  ACE `json:"grant"`
}

ACL is the complete permission set for a Chef object — five ACEs, one per standard Chef permission: create, read, update, delete, grant.

func (*ACL) ACEFor

func (a *ACL) ACEFor(perm string) (*ACE, error)

ACEFor returns a pointer to the ACE governing one permission, so a caller can read or mutate it in place. perm must be one of the five standard permissions; "all" and unknown values are an error.

type ACLsService

type ACLsService struct {
	// contains filtered or unexported fields
}

ACLsService accesses the per-object ACL endpoints. Every Chef object that has identity (nodes, clients, groups, containers, cookbooks, data_bags, environments, policies, policy_groups, roles, ...) exposes an _acl subresource at the same path shape, so the object kind is a string.

func (*ACLsService) Get

func (s *ACLsService) Get(ctx context.Context, objectType, name string) (*ACL, *Response, error)

Get returns the full five-permission ACL of one object.

objectType is the URL segment that identifies the kind ("nodes", "clients", "groups", "containers", "cookbooks", "data", "environments", "policies", "policy_groups", "roles", ...).

func (*ACLsService) GetOrg

func (s *ACLsService) GetOrg(ctx context.Context) (*ACL, *Response, error)

GetOrg returns the ACL of the organization object itself, served at /organizations/ORG/organizations/_acl.

func (*ACLsService) GetUser

func (s *ACLsService) GetUser(ctx context.Context, name string) (*ACL, *Response, error)

GetUser returns the ACL of a global user object. User ACLs are top-level (/users/USER/_acl), not org-scoped.

func (*ACLsService) SetOrgPermission

func (s *ACLsService) SetOrgPermission(ctx context.Context, perm string, ace *ACE) error

SetOrgPermission rewrites one permission's ACE on the organization object, at /organizations/ORG/organizations/_acl/PERM.

func (*ACLsService) SetPermission

func (s *ACLsService) SetPermission(ctx context.Context, objectType, name, perm string, ace *ACE) error

SetPermission rewrites one permission's ACE on one object. The Chef API requires the request body to wrap the new ACE under the permission name, e.g. {"update":{"actors":[],"groups":["admins"]}}.

perm must be one of the five standard permissions. The pseudo-permission "all" is rejected: it has no endpoint, so callers expand it with ExpandPerm and set each resulting permission.

Nil Actors/Groups slices are coerced to empty arrays so the server does not reject the request for a null member list.

func (*ACLsService) SetUserPermission

func (s *ACLsService) SetUserPermission(ctx context.Context, name, perm string, ace *ACE) error

SetUserPermission rewrites one permission's ACE on a global user object.

type APIClient

type APIClient struct {
	Name      string `json:"name"`
	Validator bool   `json:"validator"`

	// PublicKey, if set on Create, registers this PEM public key as the
	// client's "default" key instead of having the server generate a keypair.
	// 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.
	ChefKey ChefKey `json:"chef_key,omitzero"`
}

APIClient is a Chef API client (node or validator identity). It is named APIClient to avoid colliding with the package's own Client type.

type AssociationsService

type AssociationsService struct {
	// contains filtered or unexported fields
}

AssociationsService manages the link between users and organizations: membership at /organizations/ORG/users (distinct from the top-level /users handled by UsersService) and invitations at the org-side /organizations/ORG/association_requests and the user-side /users/USER/association_requests.

func (*AssociationsService) AddMember

func (s *AssociationsService) AddMember(ctx context.Context, username string) (*Response, error)

AddMember immediately associates an existing user with the organization. This is a superuser-only operation; most callers should use Invite instead.

func (*AssociationsService) GetMember

func (s *AssociationsService) GetMember(ctx context.Context, name string) (*OrgUser, *Response, error)

GetMember returns one organization member's record.

func (*AssociationsService) Invite

func (s *AssociationsService) Invite(ctx context.Context, username string) (*InviteResult, *Response, error)

Invite creates an invitation for username to join the organization.

func (*AssociationsService) ListInvites

func (s *AssociationsService) ListInvites(ctx context.Context) ([]Invitation, *Response, error)

ListInvites returns the organization's pending invitations.

func (*AssociationsService) ListMembers

func (s *AssociationsService) ListMembers(ctx context.Context) ([]string, *Response, error)

ListMembers returns the usernames of every user associated with the org.

func (*AssociationsService) ListUserInvites

func (s *AssociationsService) ListUserInvites(ctx context.Context, username string) ([]Invitation, *Response, error)

ListUserInvites returns the invitations pending for the named global user. This is the user-side view at /users/USER/association_requests, so the invitations carry OrgName rather than Username.

func (*AssociationsService) ListUserOrgs

func (s *AssociationsService) ListUserOrgs(ctx context.Context, username string) ([]Org, *Response, error)

ListUserOrgs returns the organizations the named global user belongs to.

func (*AssociationsService) RemoveMember

func (s *AssociationsService) RemoveMember(ctx context.Context, name string) (*OrgUser, *Response, error)

RemoveMember removes a user's association with the organization and returns the user's end state.

func (*AssociationsService) RescindInvite

func (s *AssociationsService) RescindInvite(ctx context.Context, id string) (*Response, error)

RescindInvite cancels a pending organization invitation by its ID.

func (*AssociationsService) RespondInvite

func (s *AssociationsService) RespondInvite(ctx context.Context, username, id string, accept bool) (*Response, error)

RespondInvite accepts (accept=true) or rejects (accept=false) one of the user's pending invitations.

func (*AssociationsService) UserInviteCount

func (s *AssociationsService) UserInviteCount(ctx context.Context, username string) (int, *Response, error)

UserInviteCount returns the number of invitations pending for the user.

type Attributes

type Attributes map[string]any

Attributes is a free-form Chef attribute tree. It marshals as a plain JSON object and preserves any keys it does not interpret.

func (Attributes) Dig

func (a Attributes) Dig(path ...string) (any, bool)

Dig walks nested maps along path and returns the value at the leaf.

It traverses both map[string]any (what encoding/json produces) and Attributes (what a tree built in Go holds).

func (Attributes) GetString

func (a Attributes) GetString(path ...string) string

GetString returns the string at path, or "" if absent or not a string.

type ChefKey

type ChefKey struct {
	Name       string `json:"name,omitempty"`
	PublicKey  string `json:"public_key,omitempty"`
	PrivateKey string `json:"private_key,omitempty"`
	ExpiresAt  string `json:"expiration_date,omitempty"`
}

ChefKey holds key material returned when a client is created.

type Chefignore

type Chefignore struct {
	// contains filtered or unexported fields
}

Chefignore holds the glob patterns parsed from a `chefignore` file and reports whether a cookbook-relative path should be excluded from upload or packaging. It mirrors Chef::Cookbook::Chefignore: cookbook uploads, cookbook archives, and Policyfile content-identifier computation all match files through one Chefignore so they agree on exactly which files belong to a cookbook.

func LoadChefignore

func LoadChefignore(cookbookDir string) (*Chefignore, error)

LoadChefignore finds the chefignore that applies to cookbookDir and returns its parsed patterns. Like Chef, it looks in cookbookDir first and then in each parent directory up to the filesystem root, using the first file named `chefignore` it finds; files are never merged. That covers both a standalone cookbook and a chef-repo, whose single chefignore lives in `cookbooks/`.

Finding no chefignore is not an error — the returned Chefignore ignores nothing, as it does when the first `chefignore` found is not a regular file.

func (*Chefignore) Ignores

func (c *Chefignore) Ignores(relPath string) bool

Ignores reports whether relPath — a forward-slash, cookbook-relative file path — is excluded by any chefignore pattern. It matches Chef exactly: each pattern is tested against the whole relative path with Ruby's File.fnmatch? and no flags. So `*` and `?` also match "/" (`spec/*` excludes everything under spec/, `*.bak` excludes a .bak file at any depth), a wildcard never matches a leading "." of the path, and a pattern is never tested against a basename or an ancestor directory on its own (`Vagrantfile` excludes only the root Vagrantfile, not files/default/Vagrantfile).

A nil receiver, no patterns, or an empty/"." path all ignore nothing.

func (*Chefignore) Patterns

func (c *Chefignore) Patterns() []string

Patterns returns the chefignore globs, in file order. The result is a copy; mutating it does not affect the Chefignore.

type Client

type Client struct {

	// Services.
	Nodes             *NodesService
	Roles             *RolesService
	Environments      *EnvironmentsService
	Clients           *ClientsService
	DataBags          *DataBagsService
	Search            *SearchService
	Cookbooks         *CookbooksService
	CookbookArtifacts *CookbookArtifactsService
	Keys              *KeysService
	Groups            *GroupsService
	Status            *StatusService
	License           *LicenseService
	Policies          *PoliciesService
	PolicyGroups      *PolicyGroupsService
	Orgs              *OrgsService
	Users             *UsersService
	Containers        *ContainersService
	ACLs              *ACLsService
	RequiredRecipe    *RequiredRecipeService
	Associations      *AssociationsService
	Principals        *PrincipalsService
	Universe          *UniverseService
	Stats             *StatsService
	// contains filtered or unexported fields
}

Client is a Chef/CINC Server API client. It is safe for concurrent use.

func NewClient

func NewClient(cfg Config, opts ...Option) (*Client, error)

NewClient builds a Client from cfg and optional Options.

type ClientsService

type ClientsService struct {
	// contains filtered or unexported fields
}

ClientsService accesses the /clients endpoints.

func (*ClientsService) Create

func (s *ClientsService) Create(ctx context.Context, cl *APIClient) (*APIClient, *Response, error)

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 (*ClientsService) Delete

func (s *ClientsService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a client by name.

func (*ClientsService) Get

func (s *ClientsService) Get(ctx context.Context, name string) (*APIClient, *Response, error)

Get retrieves a client by name.

func (*ClientsService) List

func (s *ClientsService) List(ctx context.Context) (map[string]string, *Response, error)

List returns the client name->URL index.

func (*ClientsService) Reregister

func (s *ClientsService) Reregister(ctx context.Context, name string) (*Key, *Response, error)

Reregister regenerates the named client's "default" key, invalidating the old private key and returning the new one (in the result's PrivateKey).

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.

func (*ClientsService) Update

func (s *ClientsService) Update(ctx context.Context, cl *APIClient) (*APIClient, *Response, error)

Update replaces an existing client's name and validator flag. Key fields on cl are not sent; manage keys with Keys.Client(name).

type Config

type Config struct {
	ServerURL  string          // e.g. https://chef.example.com
	Org        string          // organization short name
	ClientName string          // Chef client or user name
	Key        *rsa.PrivateKey // RSA private key for request signing
}

Config holds the required parameters for constructing a Client.

type Container

type Container struct {
	Name string `json:"containername,omitempty"`
	Path string `json:"containerpath,omitempty"`
}

Container is an ACL container — a grouping object that owns the "create" permission for new objects of one kind (nodes, clients, etc.). Chef returns containername and containerpath; they are almost always the same value, but the wire shape uses both keys.

type ContainersService

type ContainersService struct {
	// contains filtered or unexported fields
}

ContainersService accesses the /containers endpoints.

func (*ContainersService) Create

func (s *ContainersService) Create(ctx context.Context, name string) (*Response, error)

Create creates a new container. The Chef Server uses the same value for containername and containerpath, so a single name argument suffices.

func (*ContainersService) Delete

func (s *ContainersService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a container by name.

func (*ContainersService) Get

Get retrieves a single container by name.

func (*ContainersService) List

List returns the container name->URL index.

type Cookbook

type Cookbook struct {
	CookbookName string `json:"cookbook_name"`
	Name         string `json:"name"`
	Version      string `json:"version"`

	// Metadata is the cookbook's compiled metadata (description, maintainer,
	// license, dependencies, …), returned by the server alongside the file
	// manifest. omitzero keeps an empty block out of any re-encoded manifest,
	// since omitempty does not elide a zero-valued nested struct.
	Metadata CookbookMetadata `json:"metadata,omitzero"`

	// AllFilesManifest is the flat "all_files" file list. Cookbooks uploaded by
	// this client use it, and modern servers return it on Get.
	AllFilesManifest []CookbookFileRef `json:"all_files,omitempty"`

	// Per-segment slices (classic cookbook_version layout).
	Files       []CookbookFileRef `json:"files"`
	Definitions []CookbookFileRef `json:"definitions"`
	Libraries   []CookbookFileRef `json:"libraries"`
	Attributes  []CookbookFileRef `json:"attributes"`
	Recipes     []CookbookFileRef `json:"recipes"`
	Providers   []CookbookFileRef `json:"providers"`
	Resources   []CookbookFileRef `json:"resources"`
	RootFiles   []CookbookFileRef `json:"root_files"`
	Templates   []CookbookFileRef `json:"templates"`
}

Cookbook is a single cookbook version's manifest as returned by the server. A server returns files in one of two shapes: the per-segment slices (the classic cookbook_version layout) or the flat AllFilesManifest ("all_files", used by Policyfile-era cookbook and cookbook_artifact manifests). AllFiles merges whichever the server populated.

func (*Cookbook) AllFiles

func (cb *Cookbook) AllFiles() []CookbookFileRef

AllFiles flattens the flat all_files manifest and all nine per-segment slices into a single slice, deduplicated by path.

Most servers populate one shape or the other, but nothing guarantees it, and a file listed in both must still yield one entry: callers turn each entry into work (Download turns it into a file to fetch and write), so a duplicate means two writers for one path. The all_files entry wins, and within the per-segment slices the first occurrence does.

type CookbookArtifactListEntry

type CookbookArtifactListEntry struct {
	URL      string                    `json:"url"`
	Versions []CookbookArtifactVersion `json:"versions"`
}

CookbookArtifactListEntry is the list response value for one artifact name.

type CookbookArtifactVersion

type CookbookArtifactVersion struct {
	Identifier string `json:"identifier"`
	URL        string `json:"url"`
}

CookbookArtifactVersion is one identifier entry in an artifact list.

type CookbookArtifactsService

type CookbookArtifactsService struct {
	// contains filtered or unexported fields
}

CookbookArtifactsService accesses the /cookbook_artifacts endpoints. These are the Policyfile-mode, content-addressed cookbook variant.

func (*CookbookArtifactsService) Delete

func (s *CookbookArtifactsService) Delete(ctx context.Context, name, identifier string) (*Response, error)

Delete removes a single cookbook artifact.

func (*CookbookArtifactsService) Get

func (s *CookbookArtifactsService) Get(ctx context.Context, name, identifier string) (*Cookbook, *Response, error)

Get retrieves a single cookbook artifact by name and identifier.

func (*CookbookArtifactsService) GetVersions

GetVersions returns the available identifiers of a single cookbook artifact (GET /cookbook_artifacts/NAME), unwrapped from the server's single-key {name: {url, versions}} envelope.

func (*CookbookArtifactsService) List

List returns all cookbook artifacts and their identifiers.

func (*CookbookArtifactsService) Upload

func (s *CookbookArtifactsService) Upload(ctx context.Context, cb *LocalCookbook, identifier string) error

Upload uploads a LocalCookbook as a cookbook artifact using the sandbox/checksum protocol, then PUTs the artifact manifest at PUT /organizations/NAME/cookbook_artifacts/NAME/IDENTIFIER.

type CookbookFileRef

type CookbookFileRef struct {
	Name        string `json:"name"`
	Path        string `json:"path"`
	Specificity string `json:"specificity"`
	Checksum    string `json:"checksum"`
	URL         string `json:"url"`
}

CookbookFileRef is one file reference in a cookbook version manifest.

type CookbookListEntry

type CookbookListEntry struct {
	URL      string            `json:"url"`
	Versions []CookbookVersion `json:"versions"`
}

CookbookListEntry is the list response value for one cookbook name.

type CookbookLock

type CookbookLock struct {
	Version                 string          `json:"version,omitempty"`
	Identifier              string          `json:"identifier,omitempty"`
	DottedDecimalIdentifier string          `json:"dotted_decimal_identifier,omitempty"`
	Source                  string          `json:"source,omitempty"`
	CacheKey                string          `json:"cache_key,omitempty"`
	SCMInfo                 json.RawMessage `json:"scm_info,omitempty"`
	SourceOptions           map[string]any  `json:"source_options,omitempty"`
}

CookbookLock is a single cookbook pinning inside a PolicyRevision.

func (CookbookLock) Origin

func (l CookbookLock) Origin() (SourceKind, string, error)

Origin reports how the locked cookbook is sourced and the associated location — a filesystem path, a git URL, an artifactserver URL, or a chef server URL — read from source_options. When more than one source key is present they are preferred in the order path, artifactserver, git, chef_server. It returns an error if no recognized source key is present or its value is not a string.

func (CookbookLock) PinnedVersion

func (l CookbookLock) PinnedVersion() string

PinnedVersion returns the version the lock pins: the source_options "version" when present and non-empty, otherwise the lock's top-level Version.

type CookbookMetadata

type CookbookMetadata struct {
	Name            string `json:"name,omitempty"`
	Version         string `json:"version,omitempty"`
	Description     string `json:"description,omitempty"`
	LongDescription string `json:"long_description,omitempty"`
	Maintainer      string `json:"maintainer,omitempty"`
	MaintainerEmail string `json:"maintainer_email,omitempty"`
	License         string `json:"license,omitempty"`
	SourceURL       string `json:"source_url,omitempty"`
	IssuesURL       string `json:"issues_url,omitempty"`
	Privacy         bool   `json:"privacy,omitempty"`

	// Constraint maps: key -> version constraint string (e.g. ">= 1.0.0").
	Dependencies map[string]string `json:"dependencies,omitempty"`
	Platforms    map[string]string `json:"platforms,omitempty"`
	Providing    map[string]string `json:"providing,omitempty"`
	// Recipes maps a recipe name to its human description.
	Recipes map[string]string `json:"recipes,omitempty"`

	// Attributes and Groupings are free-form nested structures kept as-is so
	// no information is lost; their inner shape is cookbook-defined.
	Attributes map[string]any `json:"attributes,omitempty"`
	Groupings  map[string]any `json:"groupings,omitempty"`

	// Version-constraint lists, each an array of constraint tokens
	// (e.g. [[">= 13.0", "< 19.0"]] for chef_versions).
	ChefVersions [][]string `json:"chef_versions,omitempty"`
	OhaiVersions [][]string `json:"ohai_versions,omitempty"`
	Gems         [][]string `json:"gems,omitempty"`
}

CookbookMetadata is the cookbook's metadata block, as compiled from its metadata.rb/metadata.json and returned inside a cookbook version manifest. Every field is optional — older cookbooks and trimmed server responses may populate only some of them.

type CookbookVersion

type CookbookVersion struct {
	Version string `json:"version"`
	URL     string `json:"url"`
}

CookbookVersion is one version entry in a cookbook list.

type CookbooksService

type CookbooksService struct {
	// contains filtered or unexported fields
}

CookbooksService accesses the /cookbooks endpoints.

func (*CookbooksService) Delete

func (s *CookbooksService) Delete(ctx context.Context, name, version string) (*Response, error)

Delete removes a single cookbook version.

func (*CookbooksService) Download

func (s *CookbooksService) Download(ctx context.Context, name, version, destDir string) error

Download fetches a cookbook version manifest and writes every file in all nine segments to destDir, recreating the path hierarchy. version may be the literal string "_latest". File content is fetched from pre-signed bookshelf URLs using a plain (unsigned) HTTP GET, matching the upload path in sandboxes.go. Each file is verified against the manifest's MD5 checksum and written atomically; files already in destDir with a matching checksum are skipped.

func (*CookbooksService) Get

func (s *CookbooksService) Get(ctx context.Context, name, version string) (*Cookbook, *Response, error)

Get retrieves a single cookbook version manifest.

func (*CookbooksService) GetVersions

func (s *CookbooksService) GetVersions(ctx context.Context, name, numVersions string) (*CookbookListEntry, *Response, error)

GetVersions returns the available versions of a single cookbook (GET /cookbooks/NAME), unwrapped from the server's single-key {name: {url, versions}} envelope. numVersions limits the versions returned ("" for the server default of one, "all" for every version, or "n"); versions come back newest-first.

func (*CookbooksService) List

List returns all cookbooks and their available versions.

func (*CookbooksService) ListLatest

func (s *CookbooksService) ListLatest(ctx context.Context) (map[string]string, *Response, error)

ListLatest returns the name->URL index of the latest version of each cookbook (GET /cookbooks/_latest).

func (*CookbooksService) ListRecipes

func (s *CookbooksService) ListRecipes(ctx context.Context) ([]string, *Response, error)

ListRecipes returns every recipe in the latest version of each cookbook (GET /cookbooks/_recipes).

func (*CookbooksService) Upload

func (s *CookbooksService) Upload(ctx context.Context, cb *LocalCookbook) error

Upload uploads a LocalCookbook: sandbox -> file PUTs -> version manifest PUT.

type DataBagItem

type DataBagItem map[string]any

DataBagItem is a single data bag item. It must contain an "id" key.

func (DataBagItem) Decrypt

func (i DataBagItem) Decrypt(secret []byte) (DataBagItem, error)

Decrypt returns a new DataBagItem in which "id" is copied verbatim and every other top-level value is treated as an encryption wrapper and decrypted. It reads wrapper versions 1, 2, and 3. The receiver is not modified.

Plaintext "chef_type" and "data_bag" values (added by a Chef Server to the items it echoes back) are dropped rather than rejected, as Chef does; an encrypted value under either name is decrypted like any other.

A value that is not a valid wrapper yields an ErrNotEncrypted error (so a caller can distinguish "this item isn't encrypted"); a failed authentication (wrong secret, tampering, bad HMAC) yields an ErrDataBagAuth error.

func (DataBagItem) Encrypt

func (i DataBagItem) Encrypt(secret []byte) (DataBagItem, error)

Encrypt returns a new DataBagItem in which the "id" value is copied verbatim (in cleartext) and every other top-level value is replaced by a version-3 (AES-256-GCM) encrypted wrapper. The receiver is not modified. It returns an error if the item has no non-empty string "id".

func (DataBagItem) ID

func (i DataBagItem) ID() string

ID returns the item's "id" field.

func (DataBagItem) IsEncrypted

func (i DataBagItem) IsEncrypted() bool

IsEncrypted reports whether every non-"id" top-level value is a well-formed encryption wrapper. An empty item, or one containing only "id", is not considered encrypted. Plaintext "chef_type" and "data_bag" values, which a Chef Server adds to the items it echoes back, are ignored, as Chef does.

type DataBagItemsService

type DataBagItemsService struct {
	// contains filtered or unexported fields
}

DataBagItemsService accesses the items within a single data bag.

func (*DataBagItemsService) Create

Create adds a new item to the bag. The item must contain an "id".

func (*DataBagItemsService) Delete

func (s *DataBagItemsService) Delete(ctx context.Context, id string) (*Response, error)

Delete removes an item by id.

func (*DataBagItemsService) Get

Get retrieves a data bag item by id.

func (*DataBagItemsService) List

List returns the item id->URL index for the bag.

func (*DataBagItemsService) Update

Update replaces an existing item.

type DataBagsService

type DataBagsService struct {
	// contains filtered or unexported fields
}

DataBagsService accesses the /data endpoints.

func (*DataBagsService) Create

func (s *DataBagsService) Create(ctx context.Context, name string) (*Response, error)

Create creates an empty data bag.

func (*DataBagsService) Delete

func (s *DataBagsService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a data bag and all its items.

func (*DataBagsService) Items

Items returns a handle to the items of one data bag.

func (*DataBagsService) List

func (s *DataBagsService) List(ctx context.Context) (map[string]string, *Response, error)

List returns the data bag name->URL index.

type Environment

type Environment struct {
	Name               string            `json:"name"`
	Description        string            `json:"description,omitempty"`
	CookbookVersions   map[string]string `json:"cookbook_versions,omitempty"`
	DefaultAttributes  Attributes        `json:"default_attributes,omitempty"`
	OverrideAttributes Attributes        `json:"override_attributes,omitempty"`
}

Environment is a Chef environment object.

type EnvironmentsService

type EnvironmentsService struct {
	// contains filtered or unexported fields
}

EnvironmentsService accesses the /environments endpoints.

func (*EnvironmentsService) CookbookVersions

func (s *EnvironmentsService) CookbookVersions(ctx context.Context, env string, runList []string) (map[string]Cookbook, *Response, error)

CookbookVersions solves the given run list against the environment and returns the cookbook versions (including dependencies) required to satisfy it, keyed by cookbook name.

func (*EnvironmentsService) Create

Create creates a new environment.

The Chef Server answers POST /environments with {"uri":...} rather than the created object, so there is nothing to return but the response and any error.

func (*EnvironmentsService) Delete

func (s *EnvironmentsService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes an environment by name.

func (*EnvironmentsService) Get

Get retrieves an environment by name.

func (*EnvironmentsService) GetCookbook

func (s *EnvironmentsService) GetCookbook(ctx context.Context, env, name, numVersions string) (map[string]CookbookListEntry, *Response, error)

GetCookbook returns the versions of one cookbook available to the environment, filtered by the environment's version constraints.

func (*EnvironmentsService) List

List returns the environment name->URL index.

func (*EnvironmentsService) ListCookbooks

func (s *EnvironmentsService) ListCookbooks(ctx context.Context, env, numVersions string) (map[string]CookbookListEntry, *Response, error)

ListCookbooks returns the cookbooks (and versions) available to the environment, keyed by cookbook name. numVersions limits the versions per cookbook ("" for the server default, "all" for every version, or "n").

func (*EnvironmentsService) ListNodes

func (s *EnvironmentsService) ListNodes(ctx context.Context, env string) (map[string]string, *Response, error)

ListNodes returns the name->URL index of nodes in the environment.

func (*EnvironmentsService) ListRecipes

func (s *EnvironmentsService) ListRecipes(ctx context.Context, env string) ([]string, *Response, error)

ListRecipes returns the recipes available to the environment.

func (*EnvironmentsService) RoleRunList

func (s *EnvironmentsService) RoleRunList(ctx context.Context, env, role string) ([]string, *Response, error)

RoleRunList returns the role's run list as scoped to the environment: the role's env_run_lists[env], or its default run_list for the _default environment.

func (*EnvironmentsService) Update

Update replaces an existing environment.

type ErrorResponse

type ErrorResponse struct {
	Method     string   // request method
	Path       string   // request path
	StatusCode int      // HTTP status code
	Messages   []string // server-reported error messages
}

ErrorResponse describes a non-2xx response from the Chef server.

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

func (*ErrorResponse) Unwrap

func (e *ErrorResponse) Unwrap() error

Unwrap maps the status code to a sentinel error for errors.Is.

type Group

type Group struct {
	Name      string   `json:"name,omitempty"`
	GroupName string   `json:"groupname,omitempty"`
	OrgName   string   `json:"orgname,omitempty"`
	Users     []string `json:"users,omitempty"`
	Clients   []string `json:"clients,omitempty"`
	Groups    []string `json:"groups,omitempty"`
}

Group is a Chef ACL group. The shape mirrors the server's GET response. On Update the Users/Clients/Groups slices are rewrapped into the nested "actors" object the server requires on PUT.

type GroupsService

type GroupsService struct {
	// contains filtered or unexported fields
}

GroupsService accesses the /groups endpoints.

func (*GroupsService) Create

func (s *GroupsService) Create(ctx context.Context, name string) (*Response, error)

Create creates an empty group with the given name. Use Update to populate its members. The server identifies the new group by "groupname" (a "name" key is rejected with a 400).

func (*GroupsService) Delete

func (s *GroupsService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a group by name.

func (*GroupsService) Get

func (s *GroupsService) Get(ctx context.Context, name string) (*Group, *Response, error)

Get retrieves a single group by name, including its members.

func (*GroupsService) List

func (s *GroupsService) List(ctx context.Context) (map[string]string, *Response, error)

List returns the group name->URL index.

func (*GroupsService) Update

func (s *GroupsService) Update(ctx context.Context, g *Group) (*Group, *Response, error)

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.

A group with neither field set is an error rather than a PUT to the collection endpoint.

type Invitation

type Invitation struct {
	ID       string `json:"id,omitempty"`
	Username string `json:"username,omitempty"`
	OrgName  string `json:"orgname,omitempty"`
}

Invitation is a pending organization invitation (association request). The org-side listing populates ID and Username; the user-side listing populates ID and OrgName.

type InviteResult

type InviteResult struct {
	URI string `json:"uri,omitempty"`
}

InviteResult is the response from creating an organization invitation.

type Key

type Key struct {
	Name           string `json:"name,omitempty"`
	PublicKey      string `json:"public_key,omitempty"`
	ExpirationDate string `json:"expiration_date,omitempty"` // "infinity" or ISO-8601 UTC

	// CreateKey, when true on a create request, asks the server to generate
	// the keypair. The response will then carry PrivateKey.
	CreateKey bool `json:"create_key,omitempty"`

	// PrivateKey is populated only on the response to a server-generated
	// create. It is never sent on a request.
	PrivateKey string `json:"private_key,omitempty"`

	// URI is populated by list and create responses.
	URI string `json:"uri,omitempty"`

	// Expired is populated by list responses.
	Expired bool `json:"expired,omitempty"`
}

Key is one entry in the Chef Server keys API. The same struct serves as the GET response, the create/update request body, and the create response. Most fields are populated in only a subset of those contexts — they are tagged omitempty so requests stay minimal.

type KeyScope

type KeyScope struct {
	// contains filtered or unexported fields
}

KeyScope is a handle to one collection of keys (either a user's or a client's). Its CRUD methods all operate against that collection.

func (*KeyScope) Create

func (s *KeyScope) Create(ctx context.Context, k *Key) (*Key, *Response, error)

Create adds a new key. Set k.CreateKey to have the server generate the keypair; the response's PrivateKey will then be set.

func (*KeyScope) Delete

func (s *KeyScope) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a key by name.

func (*KeyScope) Get

func (s *KeyScope) Get(ctx context.Context, name string) (*Key, *Response, error)

Get fetches a single key by name.

func (*KeyScope) List

func (s *KeyScope) List(ctx context.Context) ([]Key, *Response, error)

List returns every key in the scope.

func (*KeyScope) Update

func (s *KeyScope) Update(ctx context.Context, name string, k *Key) (*Key, *Response, error)

Update replaces an existing key by name. To rename a key, set k.Name to the new name; the path segment is the existing name.

type KeygenStatus

type KeygenStatus struct {
	Keys              int     `json:"keys"`
	Max               int     `json:"max"`
	MaxWorkers        int     `json:"max_workers"`
	CurMaxWorkers     int     `json:"cur_max_workers"`
	Inflight          int     `json:"inflight"`
	AvgCreationTimeMS float64 `json:"avg_creation_time_in_ms"`
}

KeygenStatus reports on the server's pre-generated keypair pool.

type KeysService

type KeysService struct {
	// contains filtered or unexported fields
}

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. User and Client return scoped handles for each.

func (*KeysService) Client

func (s *KeysService) Client(name string) *KeyScope

Client returns a handle to the keys of the named org client.

func (*KeysService) User

func (s *KeysService) User(name string) *KeyScope

User returns a handle to the keys of the named global user.

type License

type License struct {
	LimitExceeded bool   `json:"limit_exceeded"`
	NodeLicense   int    `json:"node_license"`
	NodeCount     int    `json:"node_count"`
	UpgradeURL    string `json:"upgrade_url,omitempty"`
}

License is the response from GET /license. It reports node-license usage for the Chef Server installation.

type LicenseService

type LicenseService struct {
	// contains filtered or unexported fields
}

LicenseService accesses the top-level /license endpoint.

func (*LicenseService) Get

func (s *LicenseService) Get(ctx context.Context) (*License, *Response, error)

Get returns the server's node-license usage.

type LocalCookbook

type LocalCookbook struct {
	Name       string
	Version    string
	Identifier string // set for cookbook artifact uploads
	// contains filtered or unexported fields
}

LocalCookbook is a cookbook assembled from disk, ready to upload. When Identifier is set the manifest is emitted as a cookbook artifact version (chef_type "cookbook_artifact_version") rather than a plain version.

func LocalCookbookFromDir

func LocalCookbookFromDir(dir, version string) (*LocalCookbook, error)

LocalCookbookFromDir walks a cookbook directory into a LocalCookbook ready to pass to CookbooksService.Upload (or, with an identifier, CookbookArtifactsService.Upload). It selects files the way Chef's CookbookVersionLoader does:

  • directories at the cookbook root whose names begin with "." (.git, .kitchen, …) are skipped; dotfiles, and dot-directories deeper down, are kept;
  • chef-zero's .uploaded-cookbook-version.json is skipped;
  • files excluded by the applicable chefignore (see LoadChefignore, which also searches parent directories) are skipped.

The cookbook name is the `name` from metadata.json, or else from a literal `name '...'` line in metadata.rb, falling back to the base name of dir when neither provides one. Every remaining regular file is read and checksummed. An empty directory is an error.

type Node

type Node struct {
	Name        string     `json:"name"`
	Environment string     `json:"chef_environment,omitempty"`
	RunList     []string   `json:"run_list"`
	Normal      Attributes `json:"normal,omitempty"`
	Default     Attributes `json:"default,omitempty"`
	Override    Attributes `json:"override,omitempty"`
	Automatic   Attributes `json:"automatic,omitempty"`
	PolicyName  string     `json:"policy_name,omitempty"`
	PolicyGroup string     `json:"policy_group,omitempty"`
}

Node is a Chef node object.

func (*Node) AddRunListItems

func (n *Node) AddRunListItems(items ...string)

AddRunListItems appends run-list entries that are not already present, preserving existing entries and their order.

func (*Node) AddTags

func (n *Node) AddTags(tags ...string)

AddTags adds tags that are not already present, preserving the order of the existing tags and appending new ones.

func (*Node) Attribute

func (n *Node) Attribute(name string) (any, bool)

Attribute looks up an attribute by name across the node's precedence levels, returning the first match in Chef read-precedence order — automatic → override → normal → default (automatic, the highest precedence, wins). The name may be a dot-separated path into nested attributes (e.g. "network.default_gateway").

func (*Node) AttributeString

func (n *Node) AttributeString(name string) string

AttributeString resolves Attribute and coerces the result to a string: a string is returned as-is, a non-empty array yields its first element (coerced), and any other value is formatted with fmt.Sprint. It returns "" when the attribute is absent. This mirrors how Chef tooling reads a single scalar attribute (e.g. fqdn) that may be stored as a one-element array.

func (Node) MarshalJSON

func (n Node) MarshalJSON() ([]byte, error)

MarshalJSON encodes the node with run_list always present as an array. Chef's object validator requires an array there, and a nil slice with no omitempty would encode as null.

func (*Node) RemoveRunListItems

func (n *Node) RemoveRunListItems(items ...string)

RemoveRunListItems removes the given entries from the node's run list.

func (*Node) RemoveTags

func (n *Node) RemoveTags(tags ...string)

RemoveTags drops the given tags from the node.

func (*Node) SetTags

func (n *Node) SetTags(tags []string)

SetTags replaces the node's tags, allocating the normal attribute map if the node has none yet. Nil becomes an empty array rather than a JSON null, which is what Chef stores for a node with no tags.

func (*Node) Tags

func (n *Node) Tags() []string

Tags returns the node's tags. Chef stores them as a string array under the node's normal attributes (normal.tags); this tolerates the JSON-decoded shapes that value can take ([]string or []any of strings) and returns nil when there are none.

type NodesService

type NodesService struct {
	// contains filtered or unexported fields
}

NodesService accesses the /nodes endpoints.

func (*NodesService) Create

func (s *NodesService) Create(ctx context.Context, n *Node) (*Response, error)

Create creates a new node.

The Chef Server answers POST /nodes with {"uri":...} rather than the created object, so there is nothing to return but the response and any error.

func (*NodesService) Delete

func (s *NodesService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a node by name.

func (*NodesService) Get

func (s *NodesService) Get(ctx context.Context, name string) (*Node, *Response, error)

Get retrieves a node by name.

func (*NodesService) List

func (s *NodesService) List(ctx context.Context) (map[string]string, *Response, error)

List returns the node name->URL index.

func (*NodesService) Update

func (s *NodesService) Update(ctx context.Context, n *Node) (*Node, *Response, error)

Update replaces an existing node.

type Option

type Option func(*options)

Option customizes a Client.

func WithChefVersion

func WithChefVersion(v string) Option

WithChefVersion sets the X-Chef-Version header.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets a custom *http.Client.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the retry count for idempotent requests.

func WithSkipTLSVerify

func WithSkipTLSVerify(skip bool) Option

WithSkipTLSVerify disables TLS certificate verification (testing only).

func WithTransferTimeout added in v0.14.0

func WithTransferTimeout(d time.Duration) Option

WithTransferTimeout bounds each attempt at a cookbook file transfer (the unsigned bookshelf GETs and sandbox PUTs behind Cookbooks.Upload/Download and CookbookArtifacts.Upload), including reading or sending the whole body. It replaces the http.Client's own Timeout for those requests only; API calls keep it. The default is 10 minutes; 0 removes the limit, leaving the request context as the only bound. Negative values are ignored.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent header.

type Org

type Org struct {
	Name     string `json:"name,omitempty"`
	FullName string `json:"full_name,omitempty"`
	GUID     string `json:"guid,omitempty"`
}

Org is the top-level Chef Server organization. These endpoints live at /organizations (not under any one org) and are typically reserved for the pivotal superuser identity.

type OrgCreateResult

type OrgCreateResult struct {
	URI        string `json:"uri,omitempty"`
	ClientName string `json:"clientname,omitempty"`
	PrivateKey string `json:"private_key,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.

type OrgUser

type OrgUser struct {
	Username    string `json:"username,omitempty"`
	Email       string `json:"email,omitempty"`
	DisplayName string `json:"display_name,omitempty"`
	FirstName   string `json:"first_name,omitempty"`
	LastName    string `json:"last_name,omitempty"`
	PublicKey   string `json:"public_key,omitempty"`
}

OrgUser is an organization member's record as returned by the org-scoped /organizations/ORG/users endpoints. It is a projection of the global user object limited to the fields the membership API returns.

type OrgsService

type OrgsService struct {
	// contains filtered or unexported fields
}

OrgsService accesses the top-level /organizations endpoints.

func (*OrgsService) Create

func (s *OrgsService) Create(ctx context.Context, o *Org) (*OrgCreateResult, *Response, error)

Create creates a new organization. The response contains the generated validator client name and its private key — capture the key, it is not retrievable later.

func (*OrgsService) Delete

func (s *OrgsService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes an organization.

func (*OrgsService) Get

func (s *OrgsService) Get(ctx context.Context, name string) (*Org, *Response, error)

Get retrieves one organization's metadata.

func (*OrgsService) List

func (s *OrgsService) List(ctx context.Context) (map[string]string, *Response, error)

List returns the name -> URL index of every organization.

func (*OrgsService) Update

func (s *OrgsService) Update(ctx context.Context, o *Org) (*Org, *Response, error)

Update replaces an organization's metadata (typically FullName).

type PoliciesService

type PoliciesService struct {
	// contains filtered or unexported fields
}

PoliciesService accesses the /policies endpoints.

func (*PoliciesService) CreateRevision

func (s *PoliciesService) CreateRevision(ctx context.Context, name string, doc any) (*PolicyRevision, *Response, error)

CreateRevision uploads a new revision of a policy. The body is passed through as-is, so callers may supply a *PolicyRevision, a map, or any other JSON-marshallable value matching the Policyfile schema.

func (*PoliciesService) Delete

func (s *PoliciesService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a policy and every revision under it.

func (*PoliciesService) DeleteRevision

func (s *PoliciesService) DeleteRevision(ctx context.Context, name, revisionID string) (*Response, error)

DeleteRevision removes a single revision of a policy.

func (*PoliciesService) Get

Get returns the set of revisions known for a single policy name.

func (*PoliciesService) GetRevision

func (s *PoliciesService) GetRevision(ctx context.Context, name, revisionID string) (*PolicyRevision, *Response, error)

GetRevision fetches a single revision of a policy.

func (*PoliciesService) List

List returns every policy and its revision ids.

func (*PoliciesService) PushRevision

func (s *PoliciesService) PushRevision(ctx context.Context, lockJSON []byte, group string, cookbooks map[string]*LocalCookbook) (*PolicyRevision, *Response, error)

PushRevision deploys a Policyfile lock to a policy group: it uploads each cookbook the lock pins as a cookbook artifact (under the identifier the lock records), then associates the resulting revision with group. This is the server-side half of `chef push`.

lockJSON is the raw Policyfile.lock.json; it is parsed to discover the policy name and cookbook locks, and sent verbatim to the server so no lock fields are lost. cookbooks maps each cookbook-lock name to the on-disk cookbook to upload for it — callers fetch these from the lock's sources first (see ParsePolicyfileLock).

Chef Server rejects a PUT of an existing artifact identifier with 409, so, like chef-cli, PushRevision lists the server's artifacts once and uploads only the identifiers it lacks; a 409 from a concurrent pusher is treated as already uploaded, since the identifier is a content hash. The artifact uploads and the group association are not atomic, but this makes a failed push safe to retry and lets one lock be pushed to several groups.

type PolicyAssignment

type PolicyAssignment struct {
	RevisionID string `json:"revision_id"`
}

PolicyAssignment is the per-policy value inside a PolicyGroup — it pins one policy name to a specific revision id.

type PolicyGroup

type PolicyGroup struct {
	URI      string                      `json:"uri,omitempty"`
	Policies map[string]PolicyAssignment `json:"policies,omitempty"`
}

PolicyGroup is the response from GET /policy_groups/NAME. The Policies map shows which revision of each policy is currently active in the group.

type PolicyGroupsService

type PolicyGroupsService struct {
	// contains filtered or unexported fields
}

PolicyGroupsService accesses the /policy_groups endpoints.

func (*PolicyGroupsService) Delete

func (s *PolicyGroupsService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a policy group and all of its policy pinnings.

func (*PolicyGroupsService) DeletePolicy

func (s *PolicyGroupsService) DeletePolicy(ctx context.Context, group, policy string) (*Response, error)

DeletePolicy removes the pinning of one policy from a group, without deleting the underlying revision.

func (*PolicyGroupsService) Get

Get returns one group's pinned policy revisions.

func (*PolicyGroupsService) GetPolicy

func (s *PolicyGroupsService) GetPolicy(ctx context.Context, group, policy string) (*PolicyRevision, *Response, error)

GetPolicy returns the policy revision currently active in group for the named policy.

func (*PolicyGroupsService) List

List returns every policy group and the policy revisions pinned in it.

func (*PolicyGroupsService) PutPolicy

func (s *PolicyGroupsService) PutPolicy(ctx context.Context, group, policy string, doc any) (*PolicyRevision, *Response, error)

PutPolicy uploads a policy revision and pins it into group as the active revision of policy. This is the primary way to associate a revision with a group, and creates the group implicitly if it does not exist. The doc body may be a *PolicyRevision, a map, or any JSON-marshallable Policyfile.

type PolicyListEntry

type PolicyListEntry struct {
	URI       string                     `json:"uri"`
	Revisions map[string]json.RawMessage `json:"revisions"`
}

PolicyListEntry is the per-policy value in the /policies index. The Revisions map's keys are revision identifiers; values are intentionally empty objects in the wire format.

type PolicyRevision

type PolicyRevision struct {
	RevisionID           string                  `json:"revision_id,omitempty"`
	Name                 string                  `json:"name,omitempty"`
	RunList              []string                `json:"run_list,omitempty"`
	NamedRunLists        map[string][]string     `json:"named_run_lists,omitempty"`
	CookbookLocks        map[string]CookbookLock `json:"cookbook_locks,omitempty"`
	DefaultAttributes    map[string]any          `json:"default_attributes,omitempty"`
	OverrideAttributes   map[string]any          `json:"override_attributes,omitempty"`
	SolutionDependencies json.RawMessage         `json:"solution_dependencies,omitempty"`
	IncludedPolicyLocks  []json.RawMessage       `json:"included_policy_locks,omitempty"`
}

PolicyRevision is a single Policyfile document. The shape mirrors the well-known top-level fields; unknown fields are preserved through the Extra map when round-tripping.

func LoadPolicyfileLock

func LoadPolicyfileLock(path string) (*PolicyRevision, []byte, error)

LoadPolicyfileLock reads and parses a Policyfile.lock.json from disk. It returns the parsed lock alongside the original bytes, which callers pass verbatim to Policies.PushRevision so no lock fields are lost on the round trip.

func ParsePolicyfileLock

func ParsePolicyfileLock(data []byte) (*PolicyRevision, error)

ParsePolicyfileLock unmarshals the bytes of a Policyfile.lock.json into a PolicyRevision, which models the lock's structure (name, run lists, cookbook locks, attributes, solution dependencies). Use it to inspect a lock — for example to discover which cookbooks must be fetched before a push.

To deploy a lock, prefer Policies.PushRevision with the original bytes: a lock can carry fields PolicyRevision does not model (such as a cookbook lock's "origin"), so re-marshalling a parsed value would drop them.

type PolicyRevisions

type PolicyRevisions struct {
	Revisions map[string]json.RawMessage `json:"revisions"`
}

PolicyRevisions is the body returned by GET /policies/NAME.

type Principal

type Principal struct {
	Name      string `json:"name,omitempty"`
	Type      string `json:"type,omitempty"` // "user" or "client"
	PublicKey string `json:"public_key,omitempty"`
	AuthzID   string `json:"authz_id,omitempty"`
	OrgMember bool   `json:"org_member"`
}

Principal is one identity entry returned by the principals endpoint: the public key and metadata for a user or client. A single name may resolve to more than one principal (e.g. a client and a user sharing a name), which is why the endpoint returns a list.

type PrincipalsService

type PrincipalsService struct {
	// contains filtered or unexported fields
}

PrincipalsService accesses /organizations/ORG/principals/NAME, the endpoint used to look up the public key(s) and type of a user or client so that a request's signature can be verified.

func (*PrincipalsService) Get

func (s *PrincipalsService) Get(ctx context.Context, name string) ([]Principal, *Response, error)

Get returns the principals (public keys + metadata) registered under name.

type RequiredRecipeService

type RequiredRecipeService struct {
	// contains filtered or unexported fields
}

RequiredRecipeService accesses the /required_recipe endpoint. Unlike the rest of the API this endpoint returns a Ruby recipe as text/plain rather than JSON, so it bypasses the generic do[T] helper.

func (*RequiredRecipeService) Get

Get returns the configured required recipe (Ruby text). The endpoint returns 404 when none is configured; callers can branch with errors.Is(err, ErrNotFound).

type Response

type Response struct {
	HTTPResponse *http.Response // the underlying response (body already closed)
	StatusCode   int            // convenience copy of HTTPResponse.StatusCode
}

Response wraps the raw HTTP response returned by an API call.

type Role

type Role struct {
	Name               string              `json:"name"`
	Description        string              `json:"description,omitempty"`
	RunList            []string            `json:"run_list"`
	DefaultAttributes  Attributes          `json:"default_attributes,omitempty"`
	OverrideAttributes Attributes          `json:"override_attributes,omitempty"`
	EnvRunLists        map[string][]string `json:"env_run_lists,omitempty"`
}

Role is a Chef role object.

func (Role) MarshalJSON

func (r Role) MarshalJSON() ([]byte, error)

MarshalJSON encodes the role with run_list always present as an array, for the same reason as Node.MarshalJSON.

type RolesService

type RolesService struct {
	// contains filtered or unexported fields
}

RolesService accesses the /roles endpoints.

func (*RolesService) Create

func (s *RolesService) Create(ctx context.Context, r *Role) (*Response, error)

Create creates a new role.

The Chef Server answers POST /roles with {"uri":...} rather than the created object, so there is nothing to return but the response and any error.

func (*RolesService) Delete

func (s *RolesService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a role by name.

func (*RolesService) EnvironmentRunList

func (s *RolesService) EnvironmentRunList(ctx context.Context, role, env string) ([]string, *Response, error)

EnvironmentRunList returns the role's run list for one environment (env_run_lists[env], or the default run_list when env is "_default").

func (*RolesService) Environments

func (s *RolesService) Environments(ctx context.Context, role string) ([]string, *Response, error)

Environments lists the environments for which the role has an environment-specific run list (always including "_default").

func (*RolesService) Get

func (s *RolesService) Get(ctx context.Context, name string) (*Role, *Response, error)

Get retrieves a role by name.

func (*RolesService) List

func (s *RolesService) List(ctx context.Context) (map[string]string, *Response, error)

List returns the role name->URL index.

func (*RolesService) Update

func (s *RolesService) Update(ctx context.Context, r *Role) (*Role, *Response, error)

Update replaces an existing role.

type SearchOption

type SearchOption func(*searchParams)

SearchOption customizes a search query.

func WithPartial

func WithPartial(keys map[string][]string) SearchOption

WithPartial requests partial search projection (key -> attribute path).

func WithRows

func WithRows(n int) SearchOption

WithRows sets the page size.

func WithStart

func WithStart(n int) SearchOption

WithStart sets the result offset.

type SearchResult

type SearchResult struct {
	Total int               `json:"total"`
	Start int               `json:"start"`
	Rows  []json.RawMessage `json:"rows"`
}

SearchResult is one page of search results.

type SearchService

type SearchService struct {
	// contains filtered or unexported fields
}

SearchService accesses the /search endpoints.

func (*SearchService) All added in v0.14.0

func (s *SearchService) All(ctx context.Context, index, query string, opts ...SearchOption) iter.Seq2[json.RawMessage, error]

All returns an iterator over every row matching query, fetching one page at a time so only the current page is held in memory:

for row, err := range c.Search.All(ctx, "node", "*:*") {
	if err != nil {
		return err
	}
	// decode row
}

Breaking out of the loop stops further page requests. A failed page request (including ctx cancellation) is yielded once as a nil row with a non-nil error, after which iteration ends. Options and paging behave as in SearchAll.

func (*SearchService) Indexes

func (s *SearchService) Indexes(ctx context.Context) (map[string]string, *Response, error)

Indexes returns the name->URL index of available search indexes (node, role, client, environment, and one per data bag).

func (*SearchService) Query

func (s *SearchService) Query(ctx context.Context, index, query string, opts ...SearchOption) (*SearchResult, *Response, error)

Query runs a single search against index with the given query string.

func (*SearchService) SearchAll

func (s *SearchService) SearchAll(ctx context.Context, index, query string, opts ...SearchOption) ([]json.RawMessage, error)

SearchAll pages through every result, returning all rows. WithStart(n) is respected as the absolute offset of the first row to fetch; subsequent pages advance the offset by the number of rows received per page.

SearchAll holds the whole result set in memory; use All to process rows page by page instead.

type ServerStatus

type ServerStatus struct {
	Status    string            `json:"status"`
	Upstreams map[string]string `json:"upstreams,omitempty"`
	Keygen    KeygenStatus      `json:"keygen"`
}

ServerStatus is the response from GET /_status. The endpoint is typically unauthenticated and is used by load balancers as a health probe.

type SourceKind

type SourceKind string

SourceKind identifies how a Policyfile cookbook lock is sourced. The values match the source_options keys Chef writes into a Policyfile.lock.json.

const (
	SourcePath           SourceKind = "path"
	SourceArtifactserver SourceKind = "artifactserver"
	SourceGit            SourceKind = "git"
	SourceChefServer     SourceKind = "chef_server"
)

The source kinds a cookbook lock can name, one per source_options key.

type Stat

type Stat struct {
	Name    string       `json:"name"`
	Type    string       `json:"type"`
	Help    string       `json:"help"`
	Metrics []StatMetric `json:"metrics"`
}

Stat is one metric family reported by the /_stats endpoint.

type StatMetric

type StatMetric struct {
	Value  string            `json:"value"`
	Labels map[string]string `json:"labels,omitempty"`
}

StatMetric is one measured value within a Stat, optionally carrying Prometheus-style labels.

type StatsService

type StatsService struct {
	// contains filtered or unexported fields
}

StatsService accesses the top-level /_stats endpoint, which reports connection-pool, PostgreSQL, and Erlang VM statistics.

Unlike every other endpoint, /_stats authenticates with HTTP Basic auth (default user "statsuser") rather than the Chef signing protocol, so its requests are NOT Chef-signed.

func (*StatsService) Get

func (s *StatsService) Get(ctx context.Context, user, password string) ([]Stat, *Response, error)

Get fetches the server statistics as JSON, authenticating with the given Basic-auth credentials (the stats user and its password, available from `chef-server-ctl show-service-credentials`).

type StatusService

type StatusService struct {
	// contains filtered or unexported fields
}

StatusService accesses the top-level /_status endpoint.

func (*StatusService) Get

Get returns the server's health and keygen pool status.

type Universe

type Universe map[string]map[string]UniverseEntry

Universe is the known collection of cookbooks, keyed by cookbook name and then by version string. It feeds Berkshelf/Supermarket dependency resolution.

type UniverseEntry

type UniverseEntry struct {
	LocationPath string            `json:"location_path,omitempty"`
	LocationType string            `json:"location_type,omitempty"`
	Dependencies map[string]string `json:"dependencies,omitempty"`
}

UniverseEntry describes one cookbook version in the universe: where to fetch it and what it depends on.

type UniverseService

type UniverseService struct {
	// contains filtered or unexported fields
}

UniverseService accesses the /universe endpoint, which exists both org-scoped and at the top level.

func (*UniverseService) Get

Get returns the org-scoped universe (/organizations/ORG/universe).

func (*UniverseService) GetGlobal

func (s *UniverseService) GetGlobal(ctx context.Context) (Universe, *Response, error)

GetGlobal returns the top-level universe (/universe), aggregated across the whole server rather than one organization.

type User

type User struct {
	UserName    string `json:"username,omitempty"`
	DisplayName string `json:"display_name,omitempty"`
	Email       string `json:"email,omitempty"`
	FirstName   string `json:"first_name,omitempty"`
	MiddleName  string `json:"middle_name,omitempty"`
	LastName    string `json:"last_name,omitempty"`

	// Password is sent only on create/update; never returned.
	Password string `json:"password,omitempty"`

	// CreateKey, when true on create, asks the server to generate the user's
	// default keypair. The response then carries ChefKey with PrivateKey set.
	CreateKey bool `json:"create_key,omitempty"`

	// PublicKey may be supplied on create to set the default key without
	// having the server generate one. Mutually exclusive with CreateKey.
	PublicKey string `json:"public_key,omitempty"`
}

User is a global Chef Server user account. These live at /users (not under any one org) and represent humans who can be added to organizations.

type UserCreateResult

type UserCreateResult struct {
	URI     string  `json:"uri,omitempty"`
	ChefKey ChefKey `json:"chef_key"`
}

UserCreateResult is the response from POST /users. The ChefKey.PrivateKey is returned **only** when the user is created with CreateKey=true; capture it before the response is dropped.

type UsersService

type UsersService struct {
	// contains filtered or unexported fields
}

UsersService accesses the top-level /users endpoints.

func (*UsersService) Authenticate

func (s *UsersService) Authenticate(ctx context.Context, username, password string) (*Response, error)

Authenticate verifies a user's username and password against the top-level /authenticate_user endpoint. A nil error means the credentials are valid; a 401 is reported as an error wrapping ErrUnauthorized.

func (*UsersService) Create

func (s *UsersService) Create(ctx context.Context, u *User) (*UserCreateResult, *Response, error)

Create creates a new user. With CreateKey=true the response carries the generated private key, which is the only chance to capture it.

func (*UsersService) Delete

func (s *UsersService) Delete(ctx context.Context, name string) (*Response, error)

Delete removes a user.

func (*UsersService) Get

func (s *UsersService) Get(ctx context.Context, name string) (*User, *Response, error)

Get retrieves a single user's metadata by name.

func (*UsersService) List

func (s *UsersService) List(ctx context.Context) (map[string]string, *Response, error)

List returns the username -> URL index of every user. Typically restricted to the pivotal superuser identity.

func (*UsersService) Update

func (s *UsersService) Update(ctx context.Context, u *User) (*User, *Response, error)

Update replaces a user's metadata. Use UserName as the lookup key; other fields are the new values.

Directories

Path Synopsis
internal
cinctest
Package cinctest provides an httptest-based fake Chef server for tests.
Package cinctest provides an httptest-based fake Chef server for tests.
signing
Package signing implements the Chef v1.3 (SHA-256) signed-header protocol.
Package signing implements the Chef v1.3 (SHA-256) signed-header protocol.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL