cinc

package module
v0.18.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 39 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 GetTarget / SetTargetPermission / Grant / Revoke on an ACLTarget (ObjectACL, OrgACL, UserACL); Get / SetPermission, GetOrg / SetOrgPermission and 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 (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
c.DataBags /data List / Create / Delete; per-bag Items handle for CRUD plus GetDecrypted / CreateEncrypted / UpdateEncrypted; DataBagItem.Encrypt/Decrypt/IsEncrypted for the Chef encrypted-data-bag format (writes v3 AES-256-GCM, reads v1/v2/v3)
c.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; CookbookArtifactListEntry.Has(identifier)
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 / AddMembers / RemoveMembers
c.Keys /users/U/keys, /clients/C/keys User(name) / Client(name) → List / Get / Create / Update / Delete
c.License /license Get (node-license usage)
c.Nodes /nodes List / Get / Create / Update / Modify / Delete
c.Orgs /organizations (top-level) List / Get / Create / Update / Delete
c.Policies /policies List / Get / Delete / GetRevision / CreateRevision / DeleteRevision / PushRevision / MissingArtifacts
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/WithPartialPaths), All (iter.Seq2 over rows, one page in memory at a time), Nodes (rows decoded as *Node), PartialNodes (a partial search yielding *PartialNode: name plus the projected paths, with Scalar/LastCheckin), DataBagItems (rows unwrapped to DataBagItem), 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 / SetPassword / Authenticate
c.Do / c.Fetch any path / any URL Do sends a signed request to an absolute path and returns the body byte-for-byte (no decode); WithServerAPIVersion(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

Configurable via options: WithHTTPClient, WithUserAgent, WithChefVersion, WithSkipTLSVerify, WithRootCAs, WithMaxRetries, WithTransferTimeout. WithRootCAs(pool) verifies the server against a private CA while keeping the default client and its 30-second timeout; with WithHTTPClient it applies to a copy of that client's transport. Idempotent GETs are retried on 5xx and network errors, but not on a failed TLS certificate check. Any other request is retried only on 503 Service Unavailable, which means the server did not process it (a Chef Server under load answers POST /users and POST /clients this way); a Retry-After header on the 503 is honoured, up to 10 seconds. Signed requests never follow redirects, since that would hand the signature to the redirect target: a 3xx comes back as an *ErrorResponse naming the Location. NewClient applies this to a copy of the http.Client, so one passed with WithHTTPClient is left as it was. 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).
  • FormatServerURL(serverURL, org) — the inverse of ParseServerURL: join them back into https://host/organizations/<org>, escaping the org.
  • Client.ServerURL() / Org() / ClientName() — the identity a client was built with, so callers need not keep their own copy.
  • Response.ServerAPIVersion() — parse the X-Ops-Server-API-Version header every Chef Server response carries (supported min/max, and the requested and answered versions); Client.ServerAPIVersion(ctx) probes GET /server_api_version for the same when no other response is at hand, returning ErrNoServerAPIVersion (never a version of 0) when the answer reports no range.
  • ErrorResponse.ServerMessage() — just the server's error message(s), joined with ; , without Error()'s cinc: METHOD PATH: CODE: prefix or the 401 hint ("" when the server sent none).
  • 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, Attribute/AttributeString/AttributeScalar (precedence-aware lookup, dotted paths; a one-element array reads as its element, and a map or null is not a scalar, so AttributeString gives "" and AttributeScalar reports false rather than Go's map[...] text), LastCheckin() (from automatic.ohai_time), and EnvironmentName() (_default when unset).
  • NormalizeRunListItem(item) / NormalizeRunList(items) — the run-list form erchef stores: a bare nginx becomes recipe[nginx], then exact duplicates are dropped in order. Node and Role AddRunListItems/RemoveRunListItems compare and write normalized entries, so nginx and recipe[nginx] are the same item.
  • ValidateRunListItem(item) — erchef's run-list entry check (role[NAME], or COOKBOOK[::RECIPE][@VERSION], bare or in recipe[...]), wrapping ErrInvalidRunListItem, so a malformed entry such as recipe[ is refused before the server answers the save with a 400. NormalizeRunList does not validate; call this on user input first.
  • Nodes.Modify(name, fn) — read-modify-write: get the node, apply fn, and PUT it only if its encoding changed (a rename is refused). Nodes 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. 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).
  • ParsePolicyfileLock(data) / LoadPolicyfileLock(path) — parse a Policyfile.lock.json into a PolicyRevision.
  • CompareCookbookVersions(a, b) orders cookbook versions the way Chef does (numeric x.y[.z], so 10.0.0 is newer than 9.0.0); anything that is not a valid version sorts below every valid one. Every version list the client returns (Cookbooks.List/ListVersions/GetVersions, Environments.ListCookbooks/GetCookbook) is sorted newest-first with it and trimmed to num_versions, whatever the server sent, and an invalid num_versions is rejected before a request is made. LatestVersion is the _latest version alias. Policyfile.lock.json into a PolicyRevision. The policy name, revision id, cookbook lock names and identifiers are checked against the patterns Chef Server validates them with, so a returned name is safe to use in a path or generated config.
  • CookbookLock accessors — Origin() (classify a lock's source_options as path/artifactserver/git/chef_server and return its location), PinnedVersion() (the source_options version, falling back to the lock's top-level version), DottedIdentifier() (the dotted-decimal identifier, falling back to the identifier), GitRef() (the git revision, falling back to ref, tag, branch) and GitSubdir() (the git rel).
  • 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. Encrypt refuses an item that already holds an encrypted value (ErrAlreadyEncrypted) rather than encrypting the ciphertext again.
  • Items(bag).GetDecrypted(id, secret) / CreateEncrypted(item, secret) / UpdateEncrypted(item, secret) — the encrypted read and write paths in one call each; an edit is GetDecrypted, a change, then UpdateEncrypted.
  • LoadDataBagSecret(path) / ParseDataBagSecret(data) — read a shared secret file exactly as Chef's EncryptedDataBagItem.load_secret does: leading and trailing NUL and ASCII whitespace stripped, UTF-8 required (ErrInvalidDataBagSecret), an empty secret refused (ErrEmptyDataBagSecret). Chef's remote (URL) secrets are not supported.
  • DataBagItem.Validate() — the non-empty string id check Create, Update and Encrypt apply (ErrMissingDataBagItemID), for vetting an edited item up front. DataBagItem.Content() — the item without id and the chef_type/data_bag keys a server adds to echoes and search rows.
  • Policies.PushRevision(lockJSON, group, cookbooks) — the server-side half of chef push: upload each pinned cookbook as an artifact under its lock name, 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. cookbooks needs an entry only for the artifacts the server lacks; a lock with no cookbook is an error only if the server lacks its artifact. It returns a PushResult: the Revision, and the sorted lock names it Uploaded and found AlreadyPresent. A cookbook whose metadata names a different cookbook, or whose version differs from the lock's, is refused before anything is uploaded.
  • Policies.MissingArtifacts(lock): the sorted cookbook-lock names whose artifacts the server lacks, so a caller fetches only those cookbooks before PushRevision.
  • 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 (which it falls back to, resolved first so . is named after the working directory).
  • LoadCookbookMetadata(dir) / ParseMetadataJSON(data) / ParseMetadataRb(data) — read a cookbook's metadata into a CookbookMetadata, preferring metadata.json over metadata.rb as Chef's loader does. metadata.rb is Ruby and is never evaluated: only calls whose arguments are all literals are read (name, version, description, long_description, maintainer, maintainer_email, license, source_url, issues_url, depends, supports, provides, chef_version, ohai_version, gem, recipe, privacy, eager_load_libraries), normalized as Chef::Cookbook::Metadata stores them (version '1.2' is 1.2.0, depends 'apt', '1.2' is = 1.2), and a call Chef would raise on (a bad constraint, a self-dependency, a wrong argument type) is an error. Other calls are skipped, except a computed version, which returns ErrMetadataVersionNotLiteral alongside the rest of the metadata rather than silently becoming 0.0.0.
  • CookbookMetadata.CompiledJSON() — the metadata.json Chef compiles (knife cookbook metadata, a Supermarket upload, a chef export): every field Chef::Cookbook::Metadata#to_h writes, with Chef's defaults (license "All rights reserved", version "0.0.0", eager_load_libraries true, empty strings, {} and []) for anything unset. A name is required.
  • LocalCookbookFromDir(dir, version) — load a cookbook for Cookbooks.Upload / CookbookArtifacts.Upload. LocalCookbook.Metadata (a CookbookMetadata: name, version, description, maintainer, license, dependencies, platforms, chef/ohai versions, …) is sent as the manifest's metadata block, which Chef Server requires and chef-client reads. It is filled by LoadCookbookMetadata, so anything computed in metadata.rb needs a metadata.json or an edit to Metadata. An empty version uses the metadata's version (an error if metadata.rb computes it); one that disagrees with it is an error.
  • UnwrapSearchRow(row) — the object a search row describes: the data of a partial-search row ({"url", "data"}), the raw_data of the Chef::DataBagItem envelope a full data bag search wraps each item in, and any other row unchanged. WithPartialPaths("kernel.release", ...) builds a partial search from dotted paths, keyed by the path itself.
  • Groups.AddMembers(group, kind, names...) / RemoveMembers(...) — change one kind of member (MemberUser, MemberClient, MemberGroup; ParseMemberKind reads "user"/"users" and so on) with a read, a PUT that is skipped when nothing changes, and a read-back. The returned MemberChange splits the names into Changed, Unchanged (already as asked) and Dropped: the server accepts a group PUT naming an actor that does not exist and silently leaves it out, so a successful PUT alone does not mean the member was added.
  • Group decodes both of the server's shapes: members in top-level users/clients/groups arrays (GET) or nested under an actors object (the PUT body, which erchef echoes back). The flat actors array a GET also carries is ignored, since the typed lists already hold its names. disagrees with it is an error. LocalCookbookFromDir(dir, version, SkipChefignore()) keeps the files chefignore would drop (every other selection rule still applies), for packaging a cookbook as-is; chef-cli always applies chefignore, so such a cookbook's Identifiers() are not the ones a Policyfile.lock.json should carry.
  • LocalCookbook.Files() / LocalCookbook.Identifiers() — the files LocalCookbookFromDir selected (cookbook-relative Path, DiskPath, MD5 Checksum), sorted by path, for callers that archive or copy a cookbook; and the Policyfile content identifier and dotted-decimal identifier over exactly those files, as chef-cli computes them for Policyfile.lock.json (SHA-1 of the sorted path:md5 lines), so a lock always names the files an upload sends.
  • 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.
  • ACL targets and grant/revoke — ObjectACL(cinc.ACLNodes, "web01"), OrgACL() and UserACL("alice") name the object whose ACL is read or written; the ACL* constants (ACLDataBags is "data", and so on, listed in ACLObjectTypes) are the object types erchef serves _acl on. ACLs.Grant/Revoke(ctx, target, perm, actors, groups) take a permission or "all", read the ACL once, write only the permissions that change, and return those; a write that fails part way returns the permissions already changed and an *ACLChangeError naming the one that failed. A member the server cannot resolve is a 400, ErrBadRequest. erchef's refusal to take the admins group off grant (only the superuser may) matches ErrAdminsRequiredOnGrant as well as ErrForbidden.

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

View Source
const (
	ACLClients           = "clients"
	ACLContainers        = "containers"
	ACLCookbooks         = "cookbooks"
	ACLCookbookArtifacts = "cookbook_artifacts"
	ACLDataBags          = "data"
	ACLEnvironments      = "environments"
	ACLGroups            = "groups"
	ACLNodes             = "nodes"
	ACLPolicies          = "policies"
	ACLPolicyGroups      = "policy_groups"
	ACLRoles             = "roles"
)

Object-type URL segments for the org-scoped objects erchef serves an _acl endpoint on, for use with ObjectACL. Most are the object's collection name; data bags are the exception, served under "data".

View Source
const LatestVersion = "_latest"

LatestVersion is the version the Chef Server resolves to the highest version of a cookbook, e.g. Cookbooks.Get(ctx, "nginx", LatestVersion).

View Source
const SuperuserName = "pivotal"

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 server-admin: creating organizations, POST /authenticate_user, and associating a user with an org without an invitation. Its key lives on the server (/etc/opscode/pivotal.pem on erchef).

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)")
	// ErrAlreadyEncrypted means Encrypt was handed an item that already
	// holds an encrypted value. Encrypting it again would wrap the
	// ciphertext a second time, and the stored item would then decrypt to
	// encryption wrappers instead of the plaintext.
	ErrAlreadyEncrypted = errors.New("cinc: data bag item is already encrypted")
)

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")
	// ErrBadRequest is a 400: the server refused the request as malformed or
	// naming something that does not exist, such as an unknown actor or group
	// in an ACL write.
	ErrBadRequest = errors.New("cinc: bad request")
	// ErrAdminsRequiredOnGrant is erchef refusing to take the admins group
	// off an object's grant permission, which only the superuser may do. The
	// server answers 403, so the error also matches ErrForbidden, but it says
	// nothing about the caller's own grant permission: erchef checks this
	// rule before it checks authorization. ACLs.Revoke reports it.
	ErrAdminsRequiredOnGrant = errors.New("cinc: the admins group cannot be removed from the grant permission")
)

Sentinel errors for use with errors.Is.

ACLObjectTypes lists every object-type segment above, sorted. A cookbook's ACL is shared by all its versions, so it is addressed by name alone, as is a cookbook artifact's and a policy's.

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.

View Source
var ErrEmptyDataBagSecret = errors.New("cinc: data bag secret is empty")

ErrEmptyDataBagSecret means an encrypted data bag secret has nothing left once its surrounding whitespace is stripped. Chef refuses such a secret ("invalid zero length secret"), and so do LoadDataBagSecret and ParseDataBagSecret.

View Source
var ErrInvalidDataBagSecret = errors.New("cinc: data bag secret is not valid UTF-8, which Chef cannot read")

ErrInvalidDataBagSecret means an encrypted data bag secret is not valid UTF-8. Chef reads the secret as UTF-8 text and cannot use such a file, so LoadDataBagSecret and ParseDataBagSecret refuse it too.

View Source
var ErrInvalidRunListItem = errors.New("cinc: invalid run list item")

ErrInvalidRunListItem means a run-list entry is not one a Chef Server accepts; ValidateRunListItem wraps it.

View Source
var ErrMetadataVersionNotLiteral = errors.New("version is not a string literal, so it can't be read without running Ruby")

ErrMetadataVersionNotLiteral reports a metadata.rb whose version is set by something other than a string literal (a method call, interpolation, a conditional). Its value can only be known by running the Ruby, which this package never does. ParseMetadataRb returns it, wrapped with the line, alongside the rest of the metadata, whose Version is left empty; without the check the cookbook would silently take Chef's default of 0.0.0.

View Source
var ErrMissingDataBagItemID = errors.New("cinc: data bag item requires a non-empty string \"id\"")

ErrMissingDataBagItemID means a data bag item has no "id", or its "id" is not a non-empty string. A Chef Server stores and indexes items by it.

View Source
var ErrNoServerAPIVersion = errors.New("cinc: the server did not report which API versions it supports")

ErrNoServerAPIVersion means GET /server_api_version succeeded but reported no API version range, in neither its body nor its X-Ops-Server-API-Version header, as from a proxy or a server that is not a Chef Server.

Functions

func CompareCookbookVersions added in v0.15.0

func CompareCookbookVersions(a, b string) int

CompareCookbookVersions compares two cookbook versions the way Chef does, numerically by major, minor and patch ("x.y" is "x.y.0"), and returns -1, 0 or +1 as a is older than, equal to or newer than b.

A string that is not a valid cookbook version ("x.y" or "x.y.z") is older than every valid one, and two such strings compare as strings, so the ordering is total: sorting with it is deterministic whatever a server sends.

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 FormatServerURL added in v0.15.0

func FormatServerURL(serverURL, org string) string

FormatServerURL joins a base server URL and an organization into the combined https://host[:port]/organizations/<org> form that Chef's credentials files and CHEF_SERVER_URL use. It is the inverse of ParseServerURL: trailing slashes on serverURL are trimmed and org is path-escaped.

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 LoadDataBagSecret added in v0.15.0

func LoadDataBagSecret(path string) ([]byte, error)

LoadDataBagSecret reads an encrypted data bag secret file the way Chef's EncryptedDataBagItem.load_secret does, so a secret file behaves the same for this package, knife and chef-client. See ParseDataBagSecret for how the contents are interpreted. A read error is returned wrapped (so errors.Is(err, fs.ErrNotExist) works); an empty or non-UTF-8 secret wraps ErrEmptyDataBagSecret or ErrInvalidDataBagSecret and names the file.

Chef's load_secret also accepts a URL ("https://host/secret") and fetches the secret from it. LoadDataBagSecret does not: path is always a local file. Fetch a remote secret yourself and pass it to ParseDataBagSecret.

func LoadKeyFile

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

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

func NormalizeRunList added in v0.15.0

func NormalizeRunList(items []string) []string

NormalizeRunList returns the run list a Chef Server would store for items: each entry normalized with NormalizeRunListItem, then exact duplicates dropped, keeping the first occurrence and the original order. Semantic duplicates such as "recipe[nginx]" and "recipe[nginx::default]" are kept. The result is never nil, so it encodes as a JSON array, and items is not modified.

This mirrors erchef's chef_object_base:normalize_run_list/1, which erchef applies to a node's run_list (chef_node.erl) and to a role's run_list and each of its env_run_lists (chef_role.erl) on every save.

func NormalizeRunListItem added in v0.15.0

func NormalizeRunListItem(item string) string

NormalizeRunListItem returns a run-list entry in the explicit form a Chef Server stores: "role[...]" and "recipe[...]" are returned unchanged, and anything else is taken to be a recipe and wrapped, so "nginx" becomes "recipe[nginx]" and "nginx::server" becomes "recipe[nginx::server]".

This mirrors erchef's chef_object_base:normalize_item/1 (chef-server/src/oc_erchef/apps/chef_objects/src/chef_object_base.erl), which, like this function, assumes the item has already been validated.

func ParseDataBagSecret added in v0.15.0

func ParseDataBagSecret(data []byte) ([]byte, error)

ParseDataBagSecret interprets the contents of an encrypted data bag secret file as Chef does (IO.read(path).strip):

  • Leading and trailing NUL bytes and ASCII whitespace (space, \t, \n, \v, \f, \r) are removed, as Ruby's String#strip removes them. Inner whitespace, and Unicode whitespace at either end, is kept.
  • The contents must be valid UTF-8. Chef reads the file as UTF-8 text and String#strip raises on an invalid byte sequence, so knife and chef-client cannot use such a file. It is refused with ErrInvalidDataBagSecret.
  • A secret that is empty once stripped is refused with ErrEmptyDataBagSecret.

The returned bytes are the secret itself (the AES key is derived from them by Encrypt and Decrypt) and never alias data. A secret given literally on a command line, as knife's --secret, is used exactly as given and needs no parsing.

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.

func UnwrapSearchRow added in v0.15.0

func UnwrapSearchRow(row json.RawMessage) json.RawMessage

UnwrapSearchRow returns the object a search row describes. Search returns two kinds of row that wrap the object in an envelope:

  • A partial search row (WithPartial, WithPartialPaths) is an object with exactly two keys, a string "url" and an object "data"; the projection is "data".
  • A full search of a data bag index returns each item as a Chef::DataBagItem, {"name": "data_bag_item_<bag>_<id>", "json_class": "Chef::DataBagItem", "chef_type": "data_bag_item", "data_bag": <bag>, "raw_data": {...}}; the item is "raw_data". A row is taken to be one when it has that json_class, that chef_type and an object "raw_data".

Any other row (a full node, role, client or environment, or anything that is not an object) is returned unchanged. Neither test misfires on a real object: every indexed object has more keys than url and data (nodes, roles, clients and environments a name, a data bag item an id), and the server unwraps a Chef::DataBagItem envelope on write, so no stored item keeps one.

func ValidateRunListItem added in v0.15.1

func ValidateRunListItem(item string) error

ValidateRunListItem reports whether item is a run-list entry a Chef Server accepts, so a caller can refuse a malformed one (such as "recipe[") before the server answers the whole save with a 400. As erchef does, it picks the pattern by prefix: "role[NAME]"; "recipe[...]" around a recipe; and anything else is a bare recipe, "COOKBOOK" or "COOKBOOK::RECIPE", either optionally followed by "@VERSION" with two or three numeric parts. Names use only ASCII letters, digits, '_', '-' and '.'. A failure wraps ErrInvalidRunListItem and names the item.

This mirrors erchef's chef_json_validator:valid_run_list_item/1 (chef-server/src/oc_erchef/apps/chef_objects/src/chef_json_validator.erl, with the regexes in chef_regex.erl) and cinc-server-ng's validRunList. NormalizeRunList does not call it; validate entries first when they come from a user.

func WithServerAPIVersion added in v0.18.0

func WithServerAPIVersion(ctx context.Context, v string) context.Context

WithServerAPIVersion returns a context whose requests ask for, and sign, server API version v instead of the client's default. Use it with Do for endpoints whose shape depends on the version.

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 ACLChangeError added in v0.15.0

type ACLChangeError struct {
	Target  ACLTarget
	Perm    string   // the permission whose write failed
	Changed []string // permissions already written, in ACLPerms order
	Err     error
}

ACLChangeError reports a Grant or Revoke that stopped part way. The server has no multi-permission write, so each permission is its own PUT: the ones in Changed were applied before the write of Perm failed, and the ones after Perm were not attempted. Err is the server's error, so errors.Is(err, ErrBadRequest) and friends see through it.

func (*ACLChangeError) Error added in v0.15.0

func (e *ACLChangeError) Error() string

func (*ACLChangeError) Unwrap added in v0.15.0

func (e *ACLChangeError) Unwrap() error

type ACLTarget added in v0.15.0

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

ACLTarget identifies the object whose ACL is read or written. Build one with ObjectACL, OrgACL or UserACL; the zero value names nothing and every method that takes it returns an error. ACLTarget is comparable.

func ObjectACL added in v0.15.0

func ObjectACL(objectType, name string) ACLTarget

ObjectACL targets the ACL of one org-scoped object. objectType is its URL segment, normally one of the ACL* constants.

func OrgACL added in v0.15.0

func OrgACL() ACLTarget

OrgACL targets the ACL of the organization object itself (the client's configured org), served at /organizations/ORG/organizations/_acl.

func UserACL added in v0.15.0

func UserACL(name string) ACLTarget

UserACL targets the ACL of a global user. User ACLs are top-level (/users/NAME/_acl), not org-scoped, and hold users only: erchef refuses a client in them.

func (ACLTarget) Name added in v0.15.0

func (t ACLTarget) Name() string

Name returns the object's name, or "" for OrgACL.

func (ACLTarget) ObjectType added in v0.15.0

func (t ACLTarget) ObjectType() string

ObjectType returns the target's URL segment: the object type for ObjectACL, "organizations" for OrgACL and "users" for UserACL.

func (ACLTarget) String added in v0.15.0

func (t ACLTarget) String() string

String renders the target for messages: "nodes/web01", "organization" or "users/alice".

type ACLsService

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

ACLsService accesses the per-object ACL endpoints. Every Chef object that has identity exposes an _acl subresource; ACLTarget says which one.

func (*ACLsService) Get

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

Get returns the full ACL of one org-scoped object. It is GetTarget(ctx, ObjectACL(objectType, name)).

func (*ACLsService) GetOrg

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

GetOrg returns the ACL of the organization object itself. It is GetTarget(ctx, OrgACL()).

func (*ACLsService) GetTarget added in v0.15.0

func (s *ACLsService) GetTarget(ctx context.Context, t ACLTarget) (*ACL, *Response, error)

GetTarget returns the full five-permission ACL of the target. Each ACE's Actors lists the clients and users together, as erchef reports them.

func (*ACLsService) GetUser

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

GetUser returns the ACL of a global user object. It is GetTarget(ctx, UserACL(name)).

func (*ACLsService) Grant added in v0.15.0

func (s *ACLsService) Grant(ctx context.Context, t ACLTarget, perm string, actors, groups []string) (changed []string, err error)

Grant adds actors (users and clients, by name) and groups to perm on the target, where perm is one of ACLPerms or "all". It reads the ACL once and writes only the permissions the members were missing from, returning those in ACLPerms order; nil means every member already held perm and nothing was sent.

A failed read is returned unchanged, with nothing written. A failed write returns the permissions already changed and an *ACLChangeError naming the one that failed. A member that does not exist is refused with a 400 (ErrBadRequest).

Grant is a read-modify-write: a concurrent change to the same permission between the read and the write is overwritten.

func (*ACLsService) Revoke added in v0.15.0

func (s *ACLsService) Revoke(ctx context.Context, t ACLTarget, perm string, actors, groups []string) (changed []string, err error)

Revoke removes actors and groups from perm on the target, where perm is one of ACLPerms or "all". It follows Grant's rules: one read, a write for each permission that held one of the members, and the permissions changed returned in order (nil if none held any).

erchef refuses to take the admins group off the grant permission unless the caller is the superuser, with a 403 that has nothing to do with the caller's own grant permission. Revoke reports that refusal as an error matching both ErrAdminsRequiredOnGrant and ErrForbidden.

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. It is SetTargetPermission(ctx, OrgACL(), perm, ace).

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 org-scoped object. It is SetTargetPermission(ctx, ObjectACL(objectType, name), perm, ace).

func (*ACLsService) SetTargetPermission added in v0.15.0

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

SetTargetPermission rewrites one permission's ACE on the target. 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, or use Grant and Revoke.

Nil Actors/Groups slices are coerced to empty arrays so the server does not reject the request for a null member list. The server refuses a member that does not exist with a 400 (ErrBadRequest).

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. It is SetTargetPermission(ctx, UserACL(name), perm, ace).

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.

func (*Client) ClientName added in v0.15.0

func (c *Client) ClientName() string

ClientName returns the client or user name requests are signed as.

func (*Client) Do added in v0.18.0

func (c *Client) Do(ctx context.Context, method, path string, body []byte) ([]byte, *Response, error)

Do sends a signed request to path and returns the response body exactly as the server sent it. path is absolute from the server root and may carry a query string, e.g. "/users" or "/organizations/acme/nodes/web01"; it is not prefixed with the client's organization. body, when non-nil, is sent as is with Content-Type application/json.

Do is the escape hatch for callers that must not lose anything to a decode and re-encode — key order, number formatting, fields the typed services do not model — such as backup and restore tools. It retries exactly as the typed services do. A non-2xx response returns the body and the Response alongside an *ErrorResponse, so errors.Is(err, ErrNotFound) and friends work as usual.

path must start with a single "/": the request URL is the server URL with path appended, and anything else ("@host/x", "//host/x") could send the signed request to a different host.

func (*Client) Fetch added in v0.18.0

func (c *Client) Fetch(ctx context.Context, url string, handle func(body io.Reader) error) error

Fetch GETs an absolute URL without Chef signing, such as the pre-signed bookshelf URL in a cookbook manifest, and passes the response body to handle. Transient failures are retried as cookbook downloads are, including a body that is cut off mid-stream: each attempt calls handle again with a fresh reader from the start of the body, so handle must not keep state from an earlier, failed call. An error handle returns is retried only if it wraps a read error from the body; any other error (a full disk, a checksum mismatch) is returned as is.

func (*Client) Org added in v0.15.0

func (c *Client) Org() string

Org returns the organization the client's org-scoped requests go to.

func (*Client) ServerAPIVersion added in v0.15.0

func (c *Client) ServerAPIVersion(ctx context.Context) (*ServerAPIVersion, *Response, error)

ServerAPIVersion asks the server which API versions it supports, with a GET of the top-level /server_api_version, the cheapest request that reports it (erchef accepts it from any authenticated requestor). The range comes from the body, or from the response header when the body lacks it; Request and Response come from the header, falling back to the body. A response with no range in either is ErrNoServerAPIVersion, never a version of 0, matching the false Response.ServerAPIVersion reports for it.

Every response carries the same header, so a caller that has just made another request can read it from that Response instead.

func (*Client) ServerURL added in v0.15.0

func (c *Client) ServerURL() string

ServerURL returns the base server URL the client was built with (scheme://host[:port], any trailing slash trimmed). Pair it with Org and FormatServerURL for the combined https://host/organizations/<org> form.

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.

func (CookbookArtifactListEntry) Has added in v0.15.0

func (e CookbookArtifactListEntry) Has(identifier string) bool

Has reports whether identifier is among the entry's versions. Paired with CookbookArtifacts.List it tells whether the server already holds an artifact a Policyfile lock pins.

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) DottedIdentifier added in v0.15.0

func (l CookbookLock) DottedIdentifier() string

DottedIdentifier returns the lock's dotted_decimal_identifier (the identifier rendered as a cookbook version, e.g. "1234.5678.9012"), falling back to its identifier when the lock has none. It names the directory a cookbook occupies in a legacy-layout policy export, cookbooks/NAME-DOTTED_IDENTIFIER; chef-cli's current layout is cookbook_artifacts/NAME-IDENTIFIER.

func (CookbookLock) GitRef added in v0.15.0

func (l CookbookLock) GitRef() string

GitRef returns the git revision to check out for a git-sourced lock: the first non-empty string among the source_options "revision" (the resolved commit, which chef-cli always records), "ref", "tag" and "branch". It returns "" when there is none.

func (CookbookLock) GitSubdir added in v0.15.0

func (l CookbookLock) GitSubdir() string

GitSubdir returns the source_options "rel": the cookbook's directory within its git repository, or "" when the cookbook is the repository root. It comes from an untrusted lock, so confine it to the checkout before use.

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"`

	// EagerLoadLibraries is true, false, or a glob string or list naming the
	// libraries chef-client loads eagerly; nil leaves Chef's default (true).
	// ParseMetadataRb stores a list as []string, JSON decoding as []any.
	EagerLoadLibraries any `json:"eager_load_libraries,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.

func LoadCookbookMetadata added in v0.15.0

func LoadCookbookMetadata(dir string) (*CookbookMetadata, error)

LoadCookbookMetadata reads the cookbook metadata in dir. Like Chef's CookbookVersionLoader, metadata.json takes precedence over metadata.rb; see ParseMetadataJSON and ParseMetadataRb. With neither file the error wraps fs.ErrNotExist. As ParseMetadataRb does, it returns the metadata together with an error wrapping ErrMetadataVersionNotLiteral when metadata.rb computes its version.

Values are returned as the file sets them: nothing is defaulted, so an unset Name or Version is empty (see CompiledJSON for Chef's defaults).

func ParseMetadataJSON added in v0.15.0

func ParseMetadataJSON(data []byte) (*CookbookMetadata, error)

ParseMetadataJSON decodes a compiled metadata.json. Its dependencies are read the way Chef's Metadata#from_hash does (handle_incorrect_constraints): a legacy one-element constraint array ({"apt": [">= 1.0"]}) is unwrapped. Chef turns an empty or multi-element array into [], which the server rejects, so that is an error here. Every other value is kept as written, as from_hash keeps it.

func ParseMetadataRb added in v0.15.0

func ParseMetadataRb(data []byte) (*CookbookMetadata, error)

ParseMetadataRb statically extracts metadata from a metadata.rb. It is Ruby and is never evaluated, so only calls whose arguments are all literals are recognized, with the arguments Chef::Cookbook::Metadata's DSL accepts:

name, description, long_description, maintainer,
maintainer_email, license, source_url, issues_url   'string'
version                                             'x.y.z' | 'x.y'
depends, supports, provides                         'name'[, 'constraint']
chef_version, ohai_version                          'requirement'[, ...]
gem                                                 'name'[, 'requirement', ...]
recipe                                              'name', 'description'
privacy                                             true | false
eager_load_libraries                                true | false | 'glob' | ['glob', ...]

Arguments may be parenthesized; strings may be single-quoted, or double-quoted without interpolation or escapes other than \" and \\; a symbol (:apt, :"apt") reads as its name; a # comment may end any line. A call may continue onto following lines after a trailing comma or an open parenthesis or bracket, as Ruby reads it (see metadataRbStatements).

A statement whose arguments are not all literals (a computed value, interpolation, a trailing conditional) is skipped, as is any other method, which Chef's method_missing ignores too; metadata.json is the way to supply metadata this cannot see. The one exception is version: a version that is set but cannot be read returns the metadata parsed, with Version empty, and an error wrapping ErrMetadataVersionNotLiteral, since treating it as unset would publish the cookbook as 0.0.0. A later literal version call replaces a computed one, as it would in Ruby.

Recognized values are normalized as Chef::Cookbook::Metadata stores them (version "1.2" is "1.2.0", constraint "1.2" is "= 1.2", requirement "16" is "= 16"), and a call Chef would raise on is an error: a malformed version or constraint, more than one constraint, a literal argument of the wrong type or number, or depends naming the cookbook itself (compared, as Chef does, with the name declared so far).

func (*CookbookMetadata) CompiledJSON added in v0.15.0

func (md *CookbookMetadata) CompiledJSON() ([]byte, error)

CompiledJSON returns md as the metadata.json Chef compiles from a metadata.rb: what `knife cookbook metadata` writes, what a cookbook shared to Supermarket carries, and what chef-cli writes into an exported Policyfile repository. It has every field Chef::Cookbook::Metadata#to_h writes, in that order, and fills anything unset with Chef's default: license "All rights reserved", version "0.0.0", eager_load_libraries true, empty strings, and {} or [] for the maps and lists. Values are otherwise written as they are, so metadata parsed by ParseMetadataRb comes out normalized as Chef would write it. Attributes and Groupings, which Chef no longer reads or writes, are left out.

Chef requires a name (Metadata#valid?), so an empty Name is an error; knife uses the cookbook's directory name when metadata.rb sets none. The output is indented by two spaces and ends in a newline. Unlike Go's default, <, > and & are not escaped, as Chef's encoder does not; map keys are sorted, where Chef keeps the order metadata.rb declared them in.

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 its files to destDir (see DownloadFiles). version may be LatestVersion. To learn the resolved version before choosing destDir, Get the manifest and pass it to DownloadFiles instead, which saves fetching it twice.

func (*CookbooksService) DownloadFiles added in v0.15.0

func (s *CookbooksService) DownloadFiles(ctx context.Context, cb *Cookbook, destDir string) error

DownloadFiles writes every file of an already-fetched cookbook manifest (a Cookbooks.Get or CookbookArtifacts.Get result) to destDir, recreating the path hierarchy. File content is fetched from the manifest's pre-signed bookshelf URLs using a plain (unsigned) HTTP GET, matching the upload path in sandboxes.go; no API request is made. Each file is verified against the manifest's MD5 checksum and written atomically; files already in destDir with a matching checksum are skipped.

Nothing is written outside destDir. Besides rejecting manifest paths that leave it, writes go through an os.Root on destDir: a symlink already under destDir may point elsewhere inside it, but one pointing out of it fails the download (a directory) or is replaced by the downloaded file (a file).

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: "" or "all" for every version, or "n" for the n newest; anything else is rejected before a request is sent. erchef ignores num_versions on this endpoint, so the client applies the limit. Versions are newest-first.

func (*CookbooksService) List

List returns every cookbook with only its latest version (GET /cookbooks). It is ListVersions(ctx, ""): the Chef Server lists one version per cookbook unless asked for more.

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) ListVersions added in v0.15.0

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

ListVersions returns every cookbook with up to numVersions of its versions (GET /cookbooks?num_versions=N): "all" for every version, "n" for the n newest, or "" for the server default of one. Anything else is rejected before a request is sent. Each entry's versions are newest-first, compared with CompareCookbookVersions, whatever order the server sent them in.

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) Content added in v0.15.0

func (i DataBagItem) Content() map[string]any

Content returns a copy of the item's own values: every key except "id" and the plaintext "chef_type"/"data_bag" keys a Chef Server adds to the items it echoes back or returns from search. An encrypted value under one of those two names is kept, as Decrypt keeps it. Use it to show or compare what an item holds without its bookkeeping.

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 ErrMissingDataBagItemID error if the item fails Validate, and ErrAlreadyEncrypted if any non-"id" value is already a well-formed encryption wrapper (see IsEncrypted for what counts as one). The second check is deliberately wider than IsEncrypted, which needs every value to be a wrapper: an encrypted item with one plaintext key added would otherwise have its ciphertext encrypted again. A plaintext value cannot trip it by accident, since a wrapper is a map with a numeric version of 1, 2, or 3, string "encrypted_data" and "iv", and the version's "hmac" or "auth_tag".

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.

func (DataBagItem) Validate added in v0.15.0

func (i DataBagItem) Validate() error

Validate reports whether the item can be written to a Chef Server: it returns ErrMissingDataBagItemID unless the item has a non-empty string "id". Create, Update and Encrypt run the same check; call Validate to vet an item (say, one a user just edited) before doing anything else with it.

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. It returns an ErrMissingDataBagItemID error, without sending anything, if the item fails Validate.

func (*DataBagItemsService) CreateEncrypted added in v0.15.0

func (s *DataBagItemsService) CreateEncrypted(ctx context.Context, item DataBagItem, secret []byte) (DataBagItem, *Response, error)

CreateEncrypted encrypts a plaintext item with secret (see DataBagItem.Encrypt) and adds it to the bag. The item is not modified. Nothing is sent if the item fails Validate or is already encrypted (ErrAlreadyEncrypted). The returned item is the server's echo, which is the encrypted item as stored.

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) GetDecrypted added in v0.15.0

func (s *DataBagItemsService) GetDecrypted(ctx context.Context, id string, secret []byte) (DataBagItem, *Response, error)

GetDecrypted retrieves an encrypted item and decrypts it with secret (see DataBagItem.Decrypt). A plaintext item yields an ErrNotEncrypted error and a wrong secret an ErrDataBagAuth error; the item is nil in both cases, and the Response is the GET's.

func (*DataBagItemsService) List

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

func (*DataBagItemsService) Update

Update replaces an existing item. It returns an ErrMissingDataBagItemID error, without sending anything, if the item fails Validate.

func (*DataBagItemsService) UpdateEncrypted added in v0.15.0

func (s *DataBagItemsService) UpdateEncrypted(ctx context.Context, item DataBagItem, secret []byte) (DataBagItem, *Response, error)

UpdateEncrypted encrypts a plaintext item with secret and replaces the stored item with it, like CreateEncrypted does for a new one. An edit is GetDecrypted, a change to the plaintext, then UpdateEncrypted.

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. numVersions is as for ListCookbooks, except that "" means every version (the server default here). Versions are newest-first.

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 of one, "all" for every version, or "n" for the n newest; anything else is rejected before a request is sent. Versions are newest-first.

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) ServerMessage added in v0.15.1

func (e *ErrorResponse) ServerMessage() string

ServerMessage returns what the server said, its Messages joined with "; ", without Error's "cinc: METHOD PATH: CODE:" prefix or the 401 hint. It is "" when the server sent no message (or e is nil), so a caller can fall back to its own wording.

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.

func (*Group) UnmarshalJSON added in v0.15.0

func (g *Group) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a group in either shape the server uses. A GET response lists members in top-level users/clients/groups arrays; a PUT body (and erchef's reply to a PUT, which echoes it) nests them in an "actors" object instead. Members found in both places are merged, without duplicates, so a group file written in the PUT shape round-trips through Update instead of emptying the group.

When "actors" is an array it is the flat list a GET adds alongside the typed lists (clients and users on erchef, every member on cinc-server-ng). It cannot be split back by kind and says nothing the typed lists do not, so it is ignored.

type GroupsService

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

GroupsService accesses the /groups endpoints.

func (*GroupsService) AddMembers added in v0.15.0

func (s *GroupsService) AddMembers(ctx context.Context, group string, kind MemberKind, names ...string) (*MemberChange, error)

AddMembers adds names, all of one kind, to group. It reads the group, PUTs it back with the missing names added (skipping the PUT when every name is already a member), then reads it again to report which names the server kept and which it dropped: a name that does not resolve to an existing user, client or group is accepted and silently discarded, so a successful PUT alone does not mean the member was added. A dropped name is not an error; check MemberChange.Dropped.

The update replaces the group's whole membership, so a change another writer makes between the read and the PUT is lost; the Chef API offers no way to make it conditional.

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) RemoveMembers added in v0.15.0

func (s *GroupsService) RemoveMembers(ctx context.Context, group string, kind MemberKind, names ...string) (*MemberChange, error)

RemoveMembers removes names, all of one kind, from group, with the same read, PUT and read-back as AddMembers. Names that are not members are reported Unchanged, and a PUT is skipped when none are.

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. KeyScope.Create
	// sends it whenever PublicKey is empty.
	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. Unless k.PublicKey is set, the server generates the keypair and the response's PrivateKey carries the private half: erchef requires one of public_key or create_key, so create_key is sent whenever no public key is. It also requires expiration_date, so an empty k.ExpirationDate is sent as "infinity". k is not modified.

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

	// Metadata is sent as the manifest's metadata block, which Chef Server
	// requires and chef-client reads (dependencies, chef_version, …).
	// LocalCookbookFromDir fills it from the cookbook's metadata; callers may
	// amend it before uploading. Its Name and Version may be left empty — the
	// manifest fills them from Name and Version — but if set they must match,
	// since the server rejects metadata that disagrees with the URL.
	Metadata CookbookMetadata
	// contains filtered or unexported fields
}

LocalCookbook is a cookbook assembled from disk, ready to upload. It records each file's path and checksum, not its content, so the files must still be on disk, unchanged, when it is uploaded; a file edited in between fails the upload's Content-MD5 check rather than sending new bytes under the old checksum. 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, opts ...LocalCookbookOption) (*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;
  • a symlink to a regular file inside the cookbook is kept under its own path; any other symlink, and any special file, is skipped (see cookbookSymlinkTarget).

Metadata comes from LoadCookbookMetadata: metadata.json when present (complete, as compiled by knife or Berkshelf), and otherwise a static parse of metadata.rb that recognizes only literal calls — see ParseMetadataRb for exactly which. Supply a metadata.json, or amend Metadata on the result, for anything computed in Ruby.

The cookbook name is the metadata's name, falling back to the base name of dir made absolute, so "." names the cookbook after the working directory (Policies.PushRevision replaces that fallback with the cookbook lock's name). version is the version to upload as; when empty the metadata's version is used, and failing that Chef's default of "0.0.0". A version that differs from the one the metadata declares is an error, since the server would reject the mismatch, and so, when version is empty, is a metadata.rb that computes its version (ErrMetadataVersionNotLiteral), which would otherwise upload as 0.0.0. Every remaining regular file is checksummed as it is read; its content is not kept, but streamed from disk again by the upload. An empty directory is an error. The selected files are available from Files, and the Policyfile identifier over them from Identifiers. The SkipChefignore option keeps the files chefignore would drop.

func (*LocalCookbook) Files added in v0.15.0

func (cb *LocalCookbook) Files() []LocalCookbookFile

Files returns the cookbook's files, sorted by Path (byte order), as LocalCookbookFromDir selected them; see there for the rules. Callers that archive, copy or fingerprint a cookbook should use this set, so that what they produce matches what an upload sends. The slice is a copy.

func (*LocalCookbook) Identifiers added in v0.15.0

func (cb *LocalCookbook) Identifiers() (identifier, dottedDecimal string)

Identifiers returns the cookbook's Policyfile content identifier and its dotted-decimal form, as chef-cli's CookbookProfiler::Identifiers computes them for a Policyfile.lock.json: identifier is the SHA-1 hex of one "path:md5\n" line per file, sorted by path; dottedDecimal reads that hex as three integers of 14, 14 and 12 digits joined by "." (the cookbook_artifacts slug older Chef Servers need). The identifier is computed over Files, so it always describes the files an upload of cb sends.

type LocalCookbookFile added in v0.15.0

type LocalCookbookFile struct {
	// Path is the file's path relative to the cookbook root, with forward
	// slashes (e.g. recipes/default.rb). It is the path the file is uploaded,
	// archived and fingerprinted under.
	Path string
	// DiskPath is where the file is read from. For a symlink inside the
	// cookbook it is the link, not its target.
	DiskPath string
	// Checksum is the hex MD5 of the file's content when the cookbook was
	// loaded.
	Checksum string
}

LocalCookbookFile is one file of a LocalCookbook: exactly the files an upload sends and the Policyfile identifier covers.

type LocalCookbookOption added in v0.15.0

type LocalCookbookOption func(*localCookbookOptions)

LocalCookbookOption configures LocalCookbookFromDir.

func SkipChefignore added in v0.15.0

func SkipChefignore() LocalCookbookOption

SkipChefignore makes LocalCookbookFromDir ignore chefignore: no chefignore is read, and files it would exclude are kept. Every other selection rule (root dot-directories, the chef-zero sentinel, symlinks, special files) still applies.

Chef's loader always applies chefignore, and chef-cli has no way to turn it off, so the Identifiers of a cookbook loaded this way are not the Policyfile identifiers chef-cli would compute for it whenever chefignore excludes anything; do not write them into a Policyfile.lock.json. The option is for packaging a cookbook as-is, such as a Supermarket tarball.

type MemberChange added in v0.15.0

type MemberChange struct {
	// Changed names the members the server now has (add) or no longer has
	// (remove), confirmed by reading the group back.
	Changed []string
	// Unchanged names those already as asked before the change: already a
	// member for an add, not a member for a remove. They are not sent.
	Unchanged []string
	// Dropped names the changes the server accepted but did not apply, seen
	// when the group is read back. On an add these are names the server
	// could not resolve: erchef (and cinc-server-ng) answer a PUT naming an
	// actor or group that does not exist with success and silently leave it
	// out. On a remove these are members still present afterwards, which
	// only a concurrent writer re-adding them should cause.
	Dropped []string
}

MemberChange reports what AddMembers or RemoveMembers did with each name it was given. Every name lands in exactly one list, in the order given, with repeats counted once.

type MemberKind added in v0.15.0

type MemberKind string

MemberKind selects one of a group's three member lists.

const (
	MemberUser   MemberKind = "user"
	MemberClient MemberKind = "client"
	MemberGroup  MemberKind = "group"
)

The member kinds a group holds.

func ParseMemberKind added in v0.15.0

func ParseMemberKind(s string) (MemberKind, error)

ParseMemberKind reads a member kind from its singular or plural name ("user" or "users", and so on).

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 entries to the node's run list, preserving existing entries and their order. The result is normalized the way the Chef Server stores it (see NormalizeRunList), so "nginx" is not added beside a stored "recipe[nginx]", and bare entries already in the list are qualified.

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) AttributeScalar added in v0.15.1

func (n *Node) AttributeScalar(name string) (string, bool)

AttributeScalar resolves Attribute and reports its value as a string when it is a scalar: a string is returned as-is, a bool or number is formatted (a JSON number without an exponent, so 1700000000 stays "1700000000"), and a non-empty array yields its first element under the same rules. It returns ("", false) when the attribute is absent, null, a map, an empty array, or an array whose first element is none of those scalars, so a caller can tell "cloud" (an object) from a usable host name instead of receiving Go's "map[...]" text.

func (*Node) AttributeString

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

AttributeString resolves Attribute and coerces the result to a string with AttributeScalar's rules, returning "" when the attribute is absent or is not a scalar (a map, null, or an array that does not lead with a scalar). This mirrors how Chef tooling reads a single scalar attribute (e.g. fqdn) that may be stored as a one-element array.

func (*Node) EnvironmentName added in v0.15.0

func (n *Node) EnvironmentName() string

EnvironmentName returns the node's chef_environment, or "_default" when it is unset, which is the environment the Chef Server assigns such a node.

func (*Node) LastCheckin added in v0.15.0

func (n *Node) LastCheckin() (time.Time, bool)

LastCheckin returns when the node last completed a chef-client run, read from automatic.ohai_time (Unix seconds as a float, set by Ohai on each run). It accepts the value as any JSON-decoded numeric shape (float64, json.Number, int, int64) and reports false when the attribute is absent, not a number, or not positive, as on a node that has never checked in.

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 entries from the node's run list, comparing normalized forms, so "nginx" removes a stored "recipe[nginx]" and vice versa. The remaining list is normalized as well.

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) Modify added in v0.15.0

func (s *NodesService) Modify(ctx context.Context, name string, fn func(*Node) error) (*Node, bool, error)

Modify fetches the named node, applies fn to it, and saves the result, returning the node the server holds afterwards and whether a PUT was sent.

When fn leaves the node's JSON encoding unchanged, no PUT is sent and the fetched node is returned with false. fn must not rename the node: Modify returns an error without saving if Name changed. An error from fn aborts Modify before the PUT and is returned as-is. A PUT that fails still reports true, since the server may have applied it.

The Chef Server has no optimistic concurrency control on nodes: there is no revision or ETag to make the PUT conditional, so a write that lands between the GET and the PUT (a chef-client run finishing, say, which saves the whole node) is overwritten, and vice versa.

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 how many times a failed request is retried: a GET after a 5xx or a network error, any other method after a 503. The default is 2.

func WithRootCAs added in v0.15.0

func WithRootCAs(pool *x509.CertPool) Option

WithRootCAs verifies the server's certificate against pool instead of the system roots, for a server behind a private CA or with a self-signed certificate. To trust extra CAs as well as the system ones, start the pool from x509.SystemCertPool. A nil pool is ignored.

Unlike building your own client for WithHTTPClient, it keeps the client the library would otherwise use, 30s timeout included. With WithHTTPClient it applies to a copy of that client's transport, keeping its tuning and TLS settings (a RoundTripper that is not an *http.Transport is replaced by a copy of http.DefaultTransport, as with WithSkipTLSVerify); the caller's client is not modified. With WithSkipTLSVerify(true) both are set, and as nothing is verified the pool has no effect. Cookbook file transfers trust the pool too.

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 PartialNode added in v0.18.0

type PartialNode struct {
	Name string
	URL  string
	Data map[string]any
}

PartialNode is one row of a partial node search (SearchService.PartialNodes): the node's name and the values projected for it, without the rest of the node.

Data is keyed by the dotted paths asked for. Each value is read from the node's merged attributes, the view the server indexes, so it is the value chef-client would see whatever precedence level set it. An attribute the node lacks is present with a nil value. Numbers decode as json.Number, so large integers and ohai_time keep their exact value.

func (*PartialNode) LastCheckin added in v0.18.0

func (p *PartialNode) LastCheckin() (time.Time, bool)

LastCheckin is Node.LastCheckin for a partial row: when the node last completed a chef-client run, read from the projected "ohai_time". Project "ohai_time" to use it; it reports false when that was not projected or the node has never checked in.

func (*PartialNode) Scalar added in v0.18.0

func (p *PartialNode) Scalar(path string) (string, bool)

Scalar returns the projected value for path as a string, with the rules of Node.AttributeScalar: a string as is, a number or bool formatted, an array by its first element. It reports false when path was not projected or the value is null, a map, or another non-scalar.

func (*PartialNode) Value added in v0.18.0

func (p *PartialNode) Value(path string) (any, bool)

Value returns the projected value for path, one of the paths passed to PartialNodes. It reports false only when path was not projected.

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) MissingArtifacts added in v0.17.0

func (s *PoliciesService) MissingArtifacts(ctx context.Context, lock *PolicyRevision) ([]string, *Response, error)

MissingArtifacts returns the sorted names of lock's cookbook locks whose artifacts the server does not hold under the locked identifier: the cookbooks a caller must fetch and pass to PushRevision. It lists the server's artifacts once, and makes no request for a lock with no cookbook locks. A cookbook lock with no identifier is an error before any request. The slice is never nil when err is nil.

func (*PoliciesService) PushRevision

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

PushRevision deploys a Policyfile lock to a policy group: it uploads each cookbook the lock pins that the server lacks as a cookbook artifact (under the lock's name and 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 (and validated, see ParsePolicyfileLock) to discover the policy name and cookbook locks, and sent verbatim to the server so no lock fields are lost. A cookbook lock with no identifier is an error before anything is sent.

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. cookbooks maps a cookbook-lock name to the on-disk cookbook to upload for it, and needs an entry only for the locks whose artifacts the server lacks: one the server already holds may be missing or nil, so a caller can ask MissingArtifacts first and fetch only those cookbooks from the lock's sources. A lock the server lacks with no cookbook supplied is an error. The caller's LocalCookbooks are not modified.

Each artifact is uploaded under its cookbook-lock name, since that is the name chef-client resolves the lock's run list against. A cookbook whose name LocalCookbookFromDir took from its directory (its metadata declares none) is renamed to the lock's; one whose name or metadata name is a different cookbook is an error, as is one whose version differs from the lock's, since the lock would then pin an artifact that is not the cookbook it describes. Every cookbook to be uploaded is checked after the artifact list and before the first upload, so a failed check changes nothing on the server.

A 409 from a concurrent pusher is treated as already present, since the identifier is a content hash. The PushResult says which were which. 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.

It rejects a lock the server would refuse for its names: the policy name and a non-empty revision_id must be 1 to 255 of A-Z, a-z, 0-9, _, -, : and .; each cookbook lock name must be A-Z, a-z, 0-9, _, - and . only; and a non-empty cookbook lock identifier follows the policy name rule. A missing revision_id or identifier is left for the server (or PushRevision) to refuse, so a partial lock can still be inspected.

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 PushResult added in v0.15.0

type PushResult struct {
	// Revision is the server's answer to the policy group association.
	Revision *PolicyRevision
	// Uploaded names the cookbook locks whose artifacts this push uploaded,
	// sorted. It is never nil.
	Uploaded []string
	// AlreadyPresent names the cookbook locks whose artifacts the server
	// already held under the locked identifier, including one a concurrent
	// push stored first (answered with 409), sorted. It is never nil.
	AlreadyPresent []string
}

PushResult reports what PoliciesService.PushRevision did.

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.

func (*Response) ServerAPIVersion added in v0.15.0

func (r *Response) ServerAPIVersion() (ServerAPIVersion, bool)

ServerAPIVersion parses the X-Ops-Server-API-Version header a Chef Server sets on every response, a failed request's included, e.g.

{"min_version":"0","max_version":"2","request_version":"1","response_version":"1"}

It reports false when the header is missing or has no usable min_version and max_version, as from a proxy or a server that is not a Chef Server.

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) AddRunListItems added in v0.15.0

func (r *Role) AddRunListItems(items ...string)

AddRunListItems appends entries to the role's run list, normalized the way the Chef Server stores it (see NormalizeRunList), so an entry already present under either spelling is not duplicated. EnvRunLists is untouched.

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.

func (*Role) RemoveRunListItems added in v0.15.0

func (r *Role) RemoveRunListItems(items ...string)

RemoveRunListItems removes entries from the role's run list, comparing normalized forms, so "nginx" removes "recipe[nginx]". The remaining list is normalized as well. EnvRunLists is untouched.

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 a partial search: each row comes back as {"url": ..., "data": {key: value}}, with each value read from the object at its attribute path (key -> path). Node paths address the merged attributes (["kernel", "release"], not ["automatic", "kernel", "release"]), because the server projects from the same merged view it indexes. Use UnwrapSearchRow to get at the projected data.

Projection options accumulate: WithPartial and WithPartialPaths each add their keys to the projection, and a later option replaces an earlier one's path for the same key. The caller's map is copied, never modified.

func WithPartialPaths added in v0.15.0

func WithPartialPaths(paths ...string) SearchOption

WithPartialPaths requests a partial search of dotted attribute paths. Each path is its own result key, split on "." into the attribute path, so WithPartialPaths("kernel.release") projects {"kernel.release": ["kernel", "release"]}. An empty string is skipped. It composes with WithPartial as described there; use WithPartial for a key other than the path itself or for an attribute name that contains a dot.

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) DataBagItems added in v0.15.0

func (s *SearchService) DataBagItems(ctx context.Context, bag, query string, opts ...SearchOption) iter.Seq2[DataBagItem, error]

DataBagItems returns an iterator over every item in data bag bag matching query. Each row is passed through UnwrapSearchRow, so a full search yields the items themselves rather than their Chef::DataBagItem envelopes, and a partial search yields each item's projected keys (which hold the id only if the projection asks for it). Paging and errors behave as in Nodes.

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) Nodes added in v0.15.0

func (s *SearchService) Nodes(ctx context.Context, query string, opts ...SearchOption) iter.Seq2[*Node, error]

Nodes returns an iterator over every node matching query, decoded as a *Node. It pages like All and ends the same way on a failed page, and also ends on a row that does not decode as a node, yielding that error.

A partial search returns projections rather than nodes, so Nodes refuses WithPartial and WithPartialPaths: it yields one error without sending a request.

func (*SearchService) PartialNodes added in v0.18.0

func (s *SearchService) PartialNodes(ctx context.Context, query string, paths []string, opts ...SearchOption) iter.Seq2[*PartialNode, error]

PartialNodes returns an iterator over every node matching query, each carrying only the attribute paths given (dotted, as in WithPartialPaths; "name" and "ohai_time" are paths like any other). It is the partial-search counterpart of Nodes, for callers that need a few fields of many nodes, as knife status does: the server sends only the projection, not the whole node.

opts may add paging (WithRows, WithStart) or further projections (WithPartial for a key other than the path). Paging and errors behave as in Nodes. With no paths and no WithPartial it yields one error without sending a request. A row that is not a partial-search row ends the iteration with an error.

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 ServerAPIVersion added in v0.15.0

type ServerAPIVersion struct {
	// Min and Max bound the API versions the server supports.
	Min, Max int
	// Request is the version the request asked for: 0 when it sent none, -1
	// when the server could not parse it.
	Request int
	// Response is the version the server answered with, -1 when it refused
	// the request as not acceptable (406).
	Response int
}

ServerAPIVersion is a Chef Server's API version negotiation: the range of X-Ops-Server-API-Version values it accepts and what it made of a request.

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.
	// Create sends it whenever PublicKey is empty, so it need not be 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. Unless u.PublicKey is set, the server generates the user's "default" keypair and the result's ChefKey.PrivateKey carries the private half, the only chance to capture it: under server API v1 a user created with neither create_key nor public_key gets no key at all, so create_key is sent whenever no public key is. u is not modified.

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) SetPassword added in v0.15.0

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

SetPassword sets a user's password. erchef's user PUT requires display_name and (for a locally authenticated user) email, and replaces the email with whatever it is sent, so a password alone is not a valid update: this GETs the user and PUTs back everything the server returned, less key fields, with the new password. It is not atomic, so a concurrent update to the same user between the two calls is overwritten. Erchef wants at least six characters.

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