supermarket

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: Apache-2.0 Imports: 19 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-supermarket-api

A Go client for the Chef Supermarket API.

Install

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

Usage

Read endpoints are anonymous:

c, _ := supermarket.NewClient(supermarket.Config{})
cb, _, _ := c.Cookbooks.Get(context.Background(), "apache2")

Write endpoints (share, delete) use the Chef mixlib-authentication signed-header protocol (version 1.1, SHA-1 — the version the public Supermarket accepts). The credentials are the Supermarket username and the RSA private key registered on that user's Supermarket profile:

key, _ := supermarket.LoadKeyFile("/home/me/.chef/me.pem")
c, _ := supermarket.NewClient(supermarket.Config{
    Username: "me",
    Key:      key,
})
c.Cookbooks.Share(ctx, "apache2", "Web Servers", tarball)

A Client with no credentials refuses write calls with ErrUnauthenticatedWrite without contacting the server.

Version helpers work on the version strings cookbooks return, without a full semver dependency: CompareVersions(a, b) orders two versions, LatestVersion(versions) picks the newest, and VersionFromURL(u) pulls the dotted version out of a /versions/<v> URL (Supermarket encodes the dots as underscores).

Coverage

Resource Endpoint Method
Cookbook GET /api/v1/cookbooks List
Cookbook GET /api/v1/cookbooks/:name Get
Cookbook GET /api/v1/cookbooks/:name/contingent Contingent
Cookbook GET /api/v1/cookbooks/:name/versions/:v GetVersion
Cookbook GET /api/v1/cookbooks/:name/versions/:v/download Download
Cookbook POST /api/v1/cookbooks (signed, multipart) Share
Cookbook DELETE /api/v1/cookbooks/:name (signed) Delete
Cookbook DELETE /api/v1/cookbooks/:name/versions/:v (signed) DeleteVersion
Search GET /api/v1/search Cookbooks
Tools GET /api/v1/tools List
Tools GET /api/v1/tools/:slug Get
Tools GET /api/v1/tools-search Search
Users GET /api/v1/users/:username Get
Universe GET /universe Get
Universe GET /universe (streaming) GetStream
Health GET /api/v1/health Status
Health GET /api/v1/metrics Metrics

Errors

Non-2xx responses are wrapped in an *ErrorResponse that decodes Supermarket's {error_messages, error_code} envelope. Use errors.Is(err, supermarket.ErrNotFound) (and friends) to check the class of failure without dealing with the fact that Supermarket returns 400 with error_code=NOT_FOUND rather than 404.

Testing

go test ./... runs the unit suite: it's fast, deterministic, and needs neither network nor Ruby. It includes:

  • An always-on signing-version guard (internal/signing) asserting we sign with a version the public Supermarket verifier accepts (1.0/1.1). This is the cheap insurance against the v1.3-class bug where every signed upload 401'd: a 1.3 signature is valid mixlib output, but the server won't accept it.
  • A contract replay suite that decodes recorded production responses under testdata/contract/ through the public types, so a decoder regression fails CI deterministically.

Two extra layers reach for outside resources and are gated so the default run stays fast:

  • Gem-backed verifier test (internal/signing): runs our signed headers through mixlib-authentication's real server-side SignatureVerification (the gold standard) and proves a synthetic v1.3 request is rejected. It needs Ruby plus the mixlib-authentication gem (gem install mixlib-authentication); without them it skips cleanly rather than failing.

  • Live contract suite — the drift alarm against the real API:

    go test -tags contract ./...
    

    It needs network access to https://supermarket.chef.io and hits the anonymous read endpoints (list + pagination, search, cookbook show, a specific version, /universe, tools, and a user record) through the actual client. It asserts on shape, types, and required fields — not volatile values — and fails (naming the field) if production drifts from what the client depends on. It is intentionally excluded from the default suite.

    Coverage boundary: the live suite covers anonymous reads; the signed write path (share/delete) is guarded deterministically by the version guard and the mixlib verifier test. A true live signed upload still needs a Supermarket account or a local instance — future work.

License

Licensed under the Apache License 2.0.

Documentation

Overview

Package supermarket is a Go client for the Chef Supermarket API.

Read endpoints (cookbooks, search, tools, users, /universe, health) are anonymous; build a Client with no credentials:

c, _ := supermarket.NewClient(supermarket.Config{})
cb, _, _ := c.Cookbooks.Get(context.Background(), "apache2")

Write endpoints (share, delete) use the Chef mixlib-authentication signed-header protocol (version 1.1, SHA-1 — the version the public Supermarket accepts). The credentials are the Supermarket username and the RSA private key whose public half is registered on that user's Supermarket profile:

key, _ := supermarket.LoadKeyFile("/home/me/.chef/me.pem")
c, _ := supermarket.NewClient(supermarket.Config{
    Username: "me",
    Key:      key,
})
c.Cookbooks.Share(ctx, "apache2", "Web Servers", tarball)

All list and search endpoints share a paginated envelope; the generic Page[T] type carries the items along with Start/Items/Total for cursoring.

Index

Constants

View Source
const DefaultBaseURL = "https://supermarket.chef.io"

DefaultBaseURL is the public Supermarket instance hosted by Progress.

Variables

View Source
var (
	ErrNotFound             = errors.New("supermarket: not found")
	ErrUnauthorized         = errors.New("supermarket: unauthorized")
	ErrForbidden            = errors.New("supermarket: forbidden")
	ErrInvalidData          = errors.New("supermarket: invalid data")
	ErrUnauthenticatedWrite = errors.New("supermarket: write requires Username and Key")
	// ErrInvalidArgument is returned locally, without contacting the server,
	// when a caller passes a blank value for a required path segment such as
	// a cookbook name or version.
	ErrInvalidArgument = errors.New("supermarket: invalid argument")
)

Sentinel errors for use with errors.Is. Supermarket returns 400 for "not found" rather than 404; Unwrap normalizes both into ErrNotFound using the response's error_code field.

Functions

func CompareVersions

func CompareVersions(a, b string) int

CompareVersions compares two cookbook version strings using a relaxed semver ordering and returns -1, 0, or 1 in the usual sense (a<b, a==b, a>b).

Numeric base segments are compared numerically (so 1.10.0 > 1.2.0), missing trailing segments are treated as zero (1.0 == 1.0.0), and an empty string sorts below everything. A base segment that is not numeric is compared lexically and ranks above a numeric one, so a malformed version such as 1.0.x is ordered consistently rather than collapsing onto 1.0.0. A clean release outranks any pre-release of the same base; pre-release identifiers are compared per semver §11 (dot-separated, all-numeric identifiers compared numerically and ranking below alphanumeric ones, with a larger set of fields winning when all earlier ones are equal). Build metadata (everything after '+') is ignored. Supermarket versions are overwhelmingly plain "X.Y.Z", so this avoids pulling in a full semver dependency while still ordering the occasional pre-release sensibly.

func LatestVersion

func LatestVersion(versions []string) string

LatestVersion returns the highest version in versions per CompareVersions, or "" when versions is empty.

func LoadKeyFile

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

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

func ParseKey

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

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

func VersionFromURL

func VersionFromURL(s string) string

VersionFromURL extracts the version segment from a Supermarket version URL like https://supermarket.chef.io/api/v1/cookbooks/nginx/versions/12_0_4 (optionally followed by /download or a query), returning "12.0.4". Supermarket encodes dots as underscores in these paths; either form is tolerated, so a bare "12.0.4" or "12_0_4" passes through unchanged.

Input that is not a version returns "". Previously the underscore-to-dot rewrite was applied unconditionally to whatever was left after trimming, which turned "my_cookbook" into "my.cookbook" and a URL with no /versions/ segment into "https:" — plausible-looking values that were never versions.

Types

type Client

type Client struct {

	// Services.
	Cookbooks *CookbooksService
	Search    *SearchService
	Tools     *ToolsService
	Users     *UsersService
	Universe  *UniverseService
	Health    *HealthService
	// contains filtered or unexported fields
}

Client is a Chef Supermarket API client. It is safe for concurrent use.

A Client with no Username/Key may call only the anonymous read endpoints; write endpoints (share, delete) return ErrUnauthenticatedWrite without contacting the server.

func NewClient

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

NewClient builds a Client from cfg and optional Options.

type Config

type Config struct {
	BaseURL  string          // http or https URL; defaults to DefaultBaseURL
	Username string          // Supermarket username (write endpoints only)
	Key      *rsa.PrivateKey // RSA private key registered on the user's profile (write endpoints only)
}

Config holds the parameters for constructing a Client. Username and Key are only needed for the write endpoints (share / delete); read endpoints work with an empty Config.

type Cookbook

type Cookbook struct {
	Name          string          `json:"name"`
	Maintainer    string          `json:"maintainer"`
	Description   string          `json:"description"`
	Category      string          `json:"category"`
	LatestVersion string          `json:"latest_version"`
	ExternalURL   string          `json:"external_url"`
	SourceURL     string          `json:"source_url"`
	IssuesURL     string          `json:"issues_url"`
	AverageRating *float64        `json:"average_rating"`
	CreatedAt     time.Time       `json:"created_at"`
	UpdatedAt     time.Time       `json:"updated_at"`
	Deprecated    bool            `json:"deprecated"`
	UpForAdoption bool            `json:"up_for_adoption"`
	Versions      []string        `json:"versions"`
	Metrics       CookbookMetrics `json:"metrics"`
}

Cookbook is the full cookbook representation returned by GET /cookbooks/:name.

type CookbookMetrics

type CookbookMetrics struct {
	Downloads     Downloads `json:"downloads"`
	Followers     int       `json:"followers"`
	Collaborators int       `json:"collaborators"`
}

CookbookMetrics is the metrics sub-object of a Cookbook.

type CookbookSummary

type CookbookSummary struct {
	Name        string `json:"cookbook_name"`
	Description string `json:"cookbook_description"`
	URL         string `json:"cookbook"`
	Maintainer  string `json:"cookbook_maintainer"`
}

CookbookSummary is the lighter shape returned by list and search.

type CookbookVersion

type CookbookVersion struct {
	Version       string            `json:"version"`
	License       string            `json:"license"`
	TarballSize   int64             `json:"tarball_file_size"`
	AverageRating *float64          `json:"average_rating"`
	PublishedAt   time.Time         `json:"published_at"`
	Cookbook      string            `json:"cookbook"` // URL of the cookbook
	File          string            `json:"file"`     // URL of the tarball
	Dependencies  map[string]string `json:"dependencies"`
	// Supports maps platform name to a version constraint. The API
	// returns this under the "supports" key (mirroring metadata.rb).
	Supports       map[string]string `json:"supports"`
	QualityMetrics []QualityMetric   `json:"quality_metrics"`
}

CookbookVersion is the full version representation returned by GET /cookbooks/:name/versions/:version.

type CookbooksService

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

CookbooksService accesses the /cookbooks endpoints.

func (*CookbooksService) Contingent

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

Contingent returns cookbooks that depend on the named cookbook.

func (*CookbooksService) Delete

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

Delete removes an entire cookbook from Supermarket. The caller must own the cookbook (or be a Supermarket admin).

func (*CookbooksService) DeleteVersion

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

DeleteVersion removes a single version of a cookbook.

func (*CookbooksService) Download

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

Download fetches the gzipped tarball for a cookbook version. The caller owns closing the returned body. Like GetVersion the version may be "latest" or any Semver form.

The download is not subject to the client's total-transaction timeout, which would otherwise truncate a large tarball mid-read. Bound it with ctx.

func (*CookbooksService) Get

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

Get returns the full record for a single cookbook by name.

func (*CookbooksService) GetVersion

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

GetVersion returns a single cookbook version. The version may be "latest" or a Semver string in either dotted ("1.2.3") or underscore ("1_2_3") form; the dotted form is converted automatically.

func (*CookbooksService) List

List paginates the cookbook index.

func (*CookbooksService) Share

func (s *CookbooksService) Share(ctx context.Context, name, category string, tarball io.Reader) (*Cookbook, *Response, error)

Share uploads a new cookbook version. tarball is the gzipped tar of the cookbook directory (must contain metadata.json at its root); category is the Supermarket category string (e.g. "Web Servers"). Requires Username and Key on the Client.

type Downloads

type Downloads struct {
	Total    int            `json:"total"`
	Versions map[string]int `json:"versions"`
}

Downloads splits a cookbook's download counter into the all-time total and a per-version breakdown.

type ErrorResponse

type ErrorResponse struct {
	Method     string   // request method
	Path       string   // request path
	StatusCode int      // HTTP status code
	Code       string   // server-supplied error_code (e.g. NOT_FOUND)
	Messages   []string // server-supplied error_messages
}

ErrorResponse describes a non-2xx response from Supermarket.

func (*ErrorResponse) Error

func (e *ErrorResponse) Error() string

func (*ErrorResponse) Unwrap

func (e *ErrorResponse) Unwrap() error

Unwrap maps the error_code (preferred) or HTTP status to a sentinel error for errors.Is.

type Health

type Health struct {
	Status string `json:"status"`
}

Health is the small status object returned by /health (and the /status alias).

type HealthService

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

HealthService accesses the health / metrics endpoints.

func (*HealthService) Metrics

func (s *HealthService) Metrics(ctx context.Context) (map[string]any, *Response, error)

Metrics hits /api/v1/metrics and returns the raw decoded JSON. The shape is server-version-specific so callers receive map[string]any.

func (*HealthService) Status

func (s *HealthService) Status(ctx context.Context) (*Health, *Response, error)

Status hits /api/v1/health and returns the parsed status object.

type ListOptions

type ListOptions struct {
	Start int
	Items int
	// Order, when set, is one of: recently_updated, recently_added,
	// most_downloaded, most_followed.
	Order string
	// User, when set, restricts the result set to cookbooks owned by
	// that Supermarket username.
	User string
}

ListOptions configures GET /cookbooks.

type Option

type Option func(*options)

Option customizes a Client.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets a custom *http.Client. A nil client is ignored.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets the retry count for idempotent (GET) requests.

func WithSkipTLSVerify

func WithSkipTLSVerify(skip bool) Option

WithSkipTLSVerify disables TLS certificate verification (testing only).

It requires the client's transport to be an *http.Transport, since that is where the TLS config lives. Combining it with a custom RoundTripper is a NewClient error rather than a silent downgrade to http.DefaultTransport.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent header.

type Page

type Page[T any] struct {
	Start int `json:"start"`
	Total int `json:"total"`
	Items []T `json:"items"`
}

Page is the envelope every Supermarket list/search response uses. Items carries the actual result rows; Start and Total describe where this slice sits inside the full result set.

func (Page[T]) HasMore

func (p Page[T]) HasMore() bool

HasMore reports whether the server has more results past this page. A page that carries no items is always terminal, even if Total claims otherwise — otherwise NextStart would not advance and a caller's pagination loop would spin forever.

func (Page[T]) NextStart

func (p Page[T]) NextStart() int

NextStart returns the Start offset a caller should pass to fetch the page that immediately follows p. Returns 0 when HasMore is false.

type QualityMetric

type QualityMetric struct {
	Name     string `json:"name"`
	Failed   bool   `json:"failed"`
	Feedback string `json:"feedback"`
}

QualityMetric is one entry in a cookbook version's quality_metrics array: the Fieri/cookstyle evaluation results shown on the version page (collaborator count, version tag, cookstyle, no-binaries, etc.).

type Response

type Response struct {
	HTTPResponse *http.Response
	StatusCode   int
}

Response wraps the raw HTTP response returned by an API call. The body has already been consumed and closed by the time the caller sees the Response.

type SearchOptions

type SearchOptions struct {
	Q     string
	Start int
	Items int
}

SearchOptions configures a search query. Q is required; Start and Items follow the same convention as ListOptions.

type SearchService

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

SearchService accesses the fuzzy-search endpoints.

func (*SearchService) Cookbooks

Cookbooks runs a fuzzy search over cookbook name, description, and maintainer.

type Tool

type Tool struct {
	Name         string `json:"name"`
	Slug         string `json:"slug"`
	Type         string `json:"type"`
	SourceURL    string `json:"source_url"`
	Description  string `json:"description"`
	Instructions string `json:"instructions"` // markdown
	Owner        string `json:"owner"`
}

Tool is the full record returned by GET /tools/:slug.

type ToolSummary

type ToolSummary struct {
	Name        string `json:"tool_name"`
	Type        string `json:"tool_type"`
	SourceURL   string `json:"tool_source_url"`
	Description string `json:"tool_description"`
	Owner       string `json:"tool_owner"`
	URL         string `json:"tool"`
}

ToolSummary is the lighter shape returned by list and search.

type ToolsListOptions

type ToolsListOptions struct {
	Start int
	Items int
	// Order, when set, is one of: recently_added.
	Order string
}

ToolsListOptions configures GET /tools.

type ToolsService

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

ToolsService accesses the /tools endpoints.

func (*ToolsService) Get

func (s *ToolsService) Get(ctx context.Context, slug string) (*Tool, *Response, error)

Get returns a single tool by slug.

func (*ToolsService) List

List paginates the tools index.

func (*ToolsService) Search

Search runs a fuzzy search over the tools index.

type Universe

type Universe map[string]map[string]UniverseVersion

Universe is the full dependency graph of every cookbook version on the server. It is keyed by cookbook name then by version string.

type UniverseService

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

UniverseService accesses the /universe endpoint.

func (*UniverseService) Get

Get returns the entire universe in one shot. The payload can be tens of megabytes; prefer GetStream when memory pressure matters.

func (*UniverseService) GetStream

func (s *UniverseService) GetStream(ctx context.Context) (io.ReadCloser, *Response, error)

GetStream returns the universe body as a raw io.ReadCloser so the caller can decode it incrementally with json.Decoder. The caller owns closing the body.

Streaming responses are not subject to the client's total-transaction timeout — a multi-megabyte universe would otherwise be truncated mid-read. Bound the download with ctx.

type UniverseVersion

type UniverseVersion struct {
	LocationPath string            `json:"location_path"`
	LocationType string            `json:"location_type"` // "supermarket"
	Dependencies map[string]string `json:"dependencies"`
}

UniverseVersion is one entry in the universe graph.

type User

type User struct {
	Username  string        `json:"username"`
	Name      string        `json:"name"`
	Company   string        `json:"company"`
	GitHub    []string      `json:"github"`
	Twitter   string        `json:"twitter"`
	Slack     string        `json:"slack"`
	Cookbooks UserCookbooks `json:"cookbooks"`
	Tools     UserTools     `json:"tools"`
}

User is the profile representation returned by GET /users/:username.

type UserCookbooks

type UserCookbooks struct {
	Owns         map[string]string `json:"owns"`
	Collaborates map[string]string `json:"collaborates"`
	Follows      map[string]string `json:"follows"`
}

UserCookbooks groups the cookbook relationships on a user profile.

Supermarket serializes each relationship as a JSON object mapping the cookbook name to its API URL (e.g. {"apache2": ".../cookbooks/apache2"}), NOT as an array of cookbook records — and it omits a relationship key entirely when it's empty, so an absent group decodes to a nil map. The contract suite (contract_live_test.go) is what pins this shape against the live API.

type UserTools

type UserTools struct {
	Owns map[string]string `json:"owns"`
}

UserTools groups the tool relationships on a user profile. Like UserCookbooks, Supermarket maps each tool name to its API URL and omits the key when there are none.

type UsersService

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

UsersService accesses the /users endpoints.

func (*UsersService) Get

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

Get returns a user profile by username.

Directories

Path Synopsis
internal
signing
Package signing implements the Chef mixlib-authentication signed-header protocol used by Supermarket's write endpoints.
Package signing implements the Chef mixlib-authentication signed-header protocol used by Supermarket's write endpoints.

Jump to

Keyboard shortcuts

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