tea

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 33 Imported by: 0 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

tea-client-go

A Go client for the Transparency Exchange API (TEA) v1.0.0: typed calls generated from the pinned OpenAPI document, TEI parsing, discovery as the specification defines it, verified artifact downloads and a full-flow helper.

import tea "github.com/oolong-project/tea-client-go"

Three packages:

  • teaapi is generated from the pinned OpenAPI document (spec/openapi.yaml) by oapi-codegen: every spec type (teaapi.Product, teaapi.Collection, ...) and a low-level client. It is never edited by hand.
  • tea (the module root) is the API to use. It returns teaapi types and owns what the specification leaves to the client: the URL policy, limits, credentials, typed errors, discovery, checksum verification and the flow helper.
  • tei parses TEIs (tei://<domain>/<type>/<id>) exactly as written.

Install

go get github.com/oolong-project/tea-client-go

Go 1.26 or later.

Example

From example_test.go (ExampleClient_FullFlow):

c, err := tea.New()
t, err := tei.Parse("tei://demo.rearmhq.com/uuid/b9f115fb-6688-4a3f-a262-3acc04e1fc9e")
res, err := c.FullFlow(ctx, t, tea.FlowOptions{})
fmt.Println(*res.Release.ProductName, res.Release.Version)

FullFlow discovers the TEI, reads the product release at the server discovery names, its lifecycle (CLE) and each component (a pinned component release, or for an unpinned component its newest release by createdDate). A component that fails carries its error in FlowComponent.Err and the others are still read. When discovery returns several results, FullFlow returns *tea.AmbiguousError unless FlowOptions.Select chooses among the Candidates (each result with its server and product release); the library never prompts. More component refs than Limits.FlowComponents is ErrTooManyComponents, never a silent truncation.

Typed calls on a known API base:

base, err := tea.ParseAPIBase("https://demo.rearmhq.com/tea", "1.0.0")
api, err := c.API(base)
release, err := api.GetProductRelease(ctx, uuid.MustParse("b9f115fb-6688-4a3f-a262-3acc04e1fc9e"))
for p, err := range api.AllProducts(ctx, tea.ProductQuery{Page: tea.Page{PageSize: 50}}) {
	// ...
}

api.Generated() gives the generated client, on the same bounded, credential-aware transport, for anything not wrapped (it reads downloads into memory; use the download helpers below to stream).

Discovery
results, err := c.Discover(ctx, t)      // every result, in the server's order
base, err := c.SelectServer(results[0]) // a servers[] root, not the /discovery base

It fetches https://<domain>/.well-known/tea (or the base given with WithWellKnownLocation), tries its endpoints by the greatest supported version and then priority, and fails over on connection and TLS errors, timeouts, 5xx, a 404 that is not a TEA error and invalid answers, within WithDiscoveryAttempts attempts (every request counts, default 4) with backoff. A TEA 404 stops with *NotResolvedError; 400, 401 and 403 stop with *APIError; an exhausted bound gives *DiscoveryError listing each failed attempt. An answer with more than Limits.DiscoveryResults results is refused whole. DiscoverPURL asks one API base by PURL.

Verified downloads
ref := tea.ArtifactRef{UUID: art.Uuid, Version: art.Version}
res, err := api.DownloadArtifactToFile(ctx, ref, art.Formats[0], "sbom.json", tea.DownloadOptions{})
  • The bytes come from the format's external url when it has one (no credential is sent there, on any hop), else from the versioned endpoint /artifact/{uuid}/{version}/download?mediaType=..., so they belong to the revision whose checksums are checked. DownloadLatestArtifact reads the latest revision's metadata and downloads that version the same way.
  • They are hashed while streaming. Every listed checksum of a supported algorithm must match (*ChecksumError otherwise), and at least one must be strong. Supported: SHA-256/384/512, SHA3-256/384/512, BLAKE2b-256/384/512, and SHA-1, which alone is refused unless DownloadOptions.AllowSHA1Only is set. BLAKE3 is not supported (neither the standard library nor golang.org/x/crypto implements it): a format with only BLAKE3, only unknown algorithms or no checksum fails closed with ErrNoUsableChecksum, before any request. An algValue that is not lowercase hex of its algorithm's length is refused. Repr-Digest is not used.
  • Checksums cover the bytes before HTTP content coding: the transport's own gzip is decoded, and any other remaining Content-Encoding is ErrUnsupportedContentEncoding. Content-Disposition is ignored.
  • DownloadArtifact may have written bytes to its writer when it fails: discard them. DownloadArtifactToFile writes a temporary file (mode 0600) next to the target and renames it into place only after verification; on failure the target is untouched and nothing is left behind.
  • DownloadSignature fetches a format's detached signature (signatureUrl, or the signature endpoint). Signatures are not verified: the specification does not define the technology. A compromised TEA server can publish checksums that match forged bytes; the checksums protect against tampered mirrors, redirects and transport errors, not against the server itself.
  • VerifyChecksums applies the same rules to any reader.

Options

Option
WithHTTPClient(hc) send through a copy of hc (its CheckRedirect is replaced, its transport wrapped)
WithUserAgent(ua) replace the default tea-client-go/<version>
WithInsecureHTTPBase(url) allow plain http under url (repeatable; below)
WithWellKnownLocation(domain, url) fetch <url>/.well-known/tea for TEIs of domain
WithBearerToken(root, token) send a bearer token under root
WithAPIKey(root, id, secret) obtain a token with an API key when a server under root asks for one
WithLimits(l) byte, count and time limits (below)
WithDiscoveryAttempts(n, backoff) discovery attempt bound and first backoff
WithTrace(f) observe each request, response, failed discovery attempt and backoff (for debug output)
Limits and time bounds

Zero means the default. A negative duration disables that bound and leaves only your context; byte and count limits must not be negative.

Limits field Default Applies to
WellKnownBytes 64 KiB .well-known/tea
DiscoveryBytes 1 MiB /discovery
DiscoveryResults 32 results in one /discovery answer, and results given to Candidates
JSONBytes 16 MiB every other JSON response
ErrorBodyBytes 64 KiB non-2xx bodies (read to classify, then discarded) and /token
DownloadBytes 512 MiB artifact content (DownloadOptions.MaxBytes overrides it per call)
SignatureBytes 16 MiB signature content (DownloadOptions.MaxBytes overrides it per call)
Redirects 5 per request
Pages 1000 per iterator
FlowComponents 1000 component refs walked by the flow helper
AttemptTimeout 15 s each discovery attempt, headers and body
CallTimeout 30 s each other non-download request, headers and body
IdleTimeout 30 s downloads and signatures: the longest wait for the headers or the next body byte

Byte limits apply after the transport's decompression, and a Content-Length over the limit is refused before reading. The time bounds use the request context, so they hold with your own http.Client too; your context's deadline applies on top, and when it ends first you get its error, not ErrTimeout. A download that keeps sending is never cut off by IdleTimeout; there is no whole-download limit beyond your context.

Every server is untrusted

  • URLs. Every URL the client requests is https, or http under a base passed with WithInsecureHTTPBase. "Under" means the same scheme, host and port, and a path equal to the base's path or below it by whole segments (http://h:8086/tea covers /tea/v1.0.0/... but not /teapot; the origin http://h:8086 covers every path on it). There is no global switch, and nothing a server sends adds or widens an allowance: a base learned from a well-known document, a servers[] entry, a redirect or an artifact url is usable over http only when it is under an allowance you configured. URLs with userinfo or dot segments are refused. Redirects follow the same rules, at most Limits.Redirects of them. TLS verification is your http.Client's; the library has no option to turn it off.
  • Credentials. A credential is bound to one API root and the client's transport decides the Authorization header on every hop, redirects included: it sends the credential under the root and removes any Authorization header elsewhere. So a redirect to another host, port or subdomain, an external artifact URL, a well-known location or a servers[] root on another host never sees it.
    • WithBearerToken(root, token) sends the token under root.
    • WithAPIKey(root, id, secret) requests no token up front. When a GET under root is answered 401 with a Bearer challenge, the client posts the key, with the client_credentials grant and HTTP Basic credentials, to the /token of the API that made the request (it must be under root), caches the token (until its expires_in minus 30 s) and retries the request once. A 401 on a request that carried the cached token drops it and gets one fresh token. There is never more than one recovery per request, and none on 403.
    • API.RequestToken exchanges a key for a token explicitly.
    • Token requests follow no redirect: a 3xx from /token is an error and the key reaches exactly one URL.
    • A transport you pass with WithHTTPClient sits below the client's transport and so sees Authorization headers: use WithTrace for debug output, not a header-dumping transport. Trace events carry scheme, host, port and path only: no headers, query strings (presigned URLs carry secrets there) or credentials.
  • Limits. Every response is bounded in bytes and in time (above).
  • Errors. *APIError (with errors.Is sentinels such as ErrObjectUnknown, ErrNotImplemented, ErrSignatureNotFound, ErrUnauthorized), *UnexpectedResponseError, *URLPolicyError, *NotResolvedError, *DiscoveryError, *TokenError, *ChecksumError, *AmbiguousError, and the sentinels ErrResponseTooLarge, ErrTimeout, ErrNoUsableChecksum, ErrTooManyResults, ErrTooManyComponents. Errors never carry a credential or a response body beyond a sanitised, truncated server message and error code.
  • Server-side use. A TEI from an untrusted party makes the client fetch https URLs its documents choose, possibly internal addresses. A service resolving user-supplied TEIs should pass an http.Client whose dialer refuses private address ranges.

Legacy urn:tei: identifiers

tei.Parse refuses the old urn:tei:<type>:<domain>:<id> form. tei.ParseLegacyURN converts it explicitly (a migration aid; the result may not be the TEI the publisher prints, in which case discovery answers OBJECT_UNKNOWN), and tei.ParseCompat accepts both and reports which one it saw. The legacy types swid and gs1 have no TEA v1.0.0 registry entry and are refused with tei.ErrLegacyTypeUnsupported.

For the ReARM CLI

What the TEA commands of the ReARM CLI (cmd/tea.go) do today, and what replaces it here:

CLI today This library
urn:tei: input tei.ParseCompat, with a deprecation warning when legacy
--usehttp --useport P with O = "http://<domain>:P": WithWellKnownLocation(domain, O) and WithInsecureHTTPBase(O)
--useport P without --usehttp WithWellKnownLocation(domain, "https://<domain>:P"), no allowance
resolveTEI / discovery Client.Discover
prompt on stdin when discovery has several results *AmbiguousError and Client.Candidates; the prompt stays in the CLI
full_tea_flow Client.FullFlow; the printing stays in the CLI
getCle / printCLE the Get...CLE calls (typed teaapi.Cle)
debug=true prints of the URLs it requests WithTrace: print each TraceRequest's URL (and the TEI itself)
http.Client{Timeout: 30s} per call the defaults of CallTimeout (30 s), AttemptTimeout and IdleTimeout

With --usehttp, the allowance for the origin O also covers any endpoint url and servers[].rootUrl on that origin, whatever their path, so a local ReARM that serves http://localhost:8086/.well-known/tea listing http://localhost:8086/tea works as today. Two things are stricter than today: an http URL on any other host or port is refused (a second plain-http origin needs one more WithInsecureHTTPBase), and without --usehttp nothing is fetched over http. The flow reads an unpinned component's newest release (sorted by createdDate descending), where the CLI took the first of the default ascending listing, the oldest.

Regenerating teaapi

go generate ./...

runs oapi-codegen as pinned in tools.mod (a separate modfile, so the generator's dependencies never reach your build). Never edit teaapi/tea.gen.go; a regenerate is a commit of its own. To bump the generator: go get -modfile=tools.mod -tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@<version>, then regenerate. spec/SPEC_PIN.md says how spec/ is pinned.

Runtime dependencies: github.com/oapi-codegen/runtime (imported by the generated code), github.com/google/uuid, golang.org/x/crypto (BLAKE2b) and golang.org/x/mod (SemVer). The runtime module's own go.mod lists further modules; they enter your module graph as minimum versions (they are not compiled into your binary unless you import them).

Tests

gofmt -l .                # must print nothing
go vet ./...
go test ./...             # offline unit tests
go test -race ./...
go test -run '^$' -fuzz '^FuzzParse$' -fuzztime 30s ./tei   # and the other fuzz targets

Integration tests run against an oolong server (oolong-project/oolong):

# a server you already run, e.g. oolong/docker-compose.tea-interop.yml
OOLONG_BASE_URL=http://127.0.0.1:3005 go test -tags integration -run Integration ./...

# or let the tests start one (Node 24; npm ci && npm run build in oolong-server first)
OOLONG_SERVER_DIR=/path/to/oolong/oolong/oolong-server go test -tags integration -run Integration ./...

Without either variable the integration tests skip (set TEA_INTEGRATION_REQUIRED=1 to make that a failure). They create their data in temporary directories and send nothing off the machine (the one external artifact URL of the fixtures is answered in-process).

A live test runs against the public demo (https://demo.rearmhq.com) only when asked for, never in the default run:

TEA_LIVE=1 go test -tags live -run Live ./...

The repository has no CI workflow yet; run the checks above before sending a change.

Versioning

This module is tagged v0.x.y until the ReARM CLI has switched to it and the API has settled. Every exported identifier, teaapi's included, is public API.

  • In v0, a change that alters or removes an exported identifier (a spec re-pin or a generator bump that changes teaapi, or a change to tea) is a new minor version (v0.N+1.0), and "Changes" below names what broke. A regenerate that changes no exported identifier, and any fix that keeps the API, is a patch.
  • From v1.0.0, such a breaking change needs a new major version (module path /v2), so a re-pin to a TEA version with an incompatible schema is a major release; an additive regenerate is a minor one.

The default User-Agent is tea-client-go/<module version> (devel when the version is unknown); WithUserAgent replaces it.

Changes

None yet.

Licence

This module is MIT-licensed (LICENSE). The files in spec/ are copies of the TEA specification and are licensed under the Apache License 2.0 (spec/LICENSE). Package teaapi is generated from spec/openapi.yaml and includes text from it (its doc comments), so it includes Apache-2.0 material; see teaapi/doc.go.

Documentation

Overview

Package tea is a client for the Transparency Exchange API (TEA) v1.0.0.

import tea "github.com/oolong-project/tea-client-go"

The client is built in two layers. Package teaapi is generated from the pinned OpenAPI document (spec/openapi.yaml) and holds every spec type and a low-level client. This package is the API people use: it returns teaapi types and owns what the specification leaves to the client.

  • URL policy: every URL is https, or http under a base the caller configured with WithInsecureHTTPBase. Userinfo and dot segments are refused. Nothing a server sends widens the policy.
  • Credentials are bound to one API root (WithBearerToken, WithAPIKey) and decided by the client's transport on every hop, redirects included; they never leave their root.
  • Every response is bounded in bytes and in time (Limits), whatever http.Client the caller passes, and Generated() calls are bounded too.
  • Errors are typed (*APIError, *UnexpectedResponseError, *URLPolicyError) and match sentinels with errors.Is. No error carries a credential or a response body beyond a sanitised server message.
  • Discovery (Client.Discover) follows the specification, fails over within a bound and never prompts.
  • Downloads (API.DownloadArtifact, API.DownloadArtifactToFile) verify the published checksums while streaming and fail closed.
  • Client.FullFlow reads a TEI's product release, lifecycle and components, as the ReARM CLI's full_tea_flow does.

Every server is treated as untrusted. Every call that does I/O takes a context.Context, and the library's own time bounds apply inside it.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/google/uuid"

	tea "github.com/oolong-project/tea-client-go"
)

func main() {
	ctx := context.Background()
	c, err := tea.New()
	if err != nil {
		log.Fatal(err)
	}
	base, err := tea.ParseAPIBase("https://demo.rearmhq.com/tea", "1.0.0")
	if err != nil {
		log.Fatal(err)
	}
	api, err := c.API(base)
	if err != nil {
		log.Fatal(err)
	}
	release, err := api.GetProductRelease(ctx, uuid.MustParse("b9f115fb-6688-4a3f-a262-3acc04e1fc9e"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(release.Version, release.LatestCollection.Version)
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrChecksumMismatch: a listed checksum did not match the bytes
	// (*ChecksumError wraps it).
	ErrChecksumMismatch = errors.New("tea: checksum mismatch")
	// ErrNoUsableChecksum: the format lists no checksum this client can
	// verify with a strong algorithm (SHA-1 only counts with
	// DownloadOptions.AllowSHA1Only; BLAKE3 and unknown algorithms are not
	// supported), or no checksum at all.
	ErrNoUsableChecksum = errors.New("tea: no usable checksum")
	// ErrUnsupportedContentEncoding: a response kept a Content-Encoding other
	// than identity, so its bytes are not the bytes the checksums cover.
	ErrUnsupportedContentEncoding = errors.New("tea: unsupported content encoding")
)

Checksum verification errors.

View Source
var (
	ErrObjectUnknown      = errors.New("tea: object unknown")
	ErrNotImplemented     = errors.New("tea: not implemented")
	ErrSignatureNotFound  = errors.New("tea: signature not found")
	ErrNoAcceptableFormat = errors.New("tea: no acceptable format")
	ErrInvalidRequest     = errors.New("tea: invalid request")
	ErrInvalidPageToken   = errors.New("tea: invalid page token")
	ErrUnauthorized       = errors.New("tea: unauthorized (HTTP 401)")
	ErrForbidden          = errors.New("tea: forbidden (HTTP 403)")
	ErrServer             = errors.New("tea: server error (HTTP 5xx)")
)

Sentinels an *APIError matches with errors.Is.

View Source
var (
	// ErrResponseTooLarge: a response body was larger than the limit for its
	// kind of call (Limits), by Content-Length or while reading.
	ErrResponseTooLarge = errors.New("tea: response body exceeds the limit")
	// ErrInvalidArgument: a caller-supplied argument was refused before any request.
	ErrInvalidArgument = errors.New("tea: invalid argument")
	// ErrInvalidOption: New was given an option value it cannot use.
	ErrInvalidOption = errors.New("tea: invalid option")
	// ErrPageLimit: an iterator stopped after Limits.Pages pages.
	ErrPageLimit = errors.New("tea: page limit reached")
	// ErrTooManyComponents: a release has more component refs than Limits.FlowComponents.
	ErrTooManyComponents = errors.New("tea: too many components")
	// ErrTooManyResults: a discovery answer, or the results given to
	// Candidates, exceeded Limits.DiscoveryResults.
	ErrTooManyResults = errors.New("tea: too many discovery results")
	// ErrTimeout: one of the library's own time bounds (Limits.AttemptTimeout,
	// CallTimeout or IdleTimeout) fired while the caller's context was live.
	ErrTimeout = errors.New("tea: time bound exceeded")
	// ErrInsecureURL: a URL was refused by the URL policy (https only, plus
	// http under a WithInsecureHTTPBase allowance; no userinfo, no dot segments).
	ErrInsecureURL = errors.New("tea: URL refused by policy")
	// ErrRedirectLimit: more redirects than Limits.Redirects.
	ErrRedirectLimit = errors.New("tea: too many redirects")
)

Sentinels for failures the client itself detects.

View Source
var SupportedVersions = []string{"1.0.0"}

SupportedVersions are the TEA API versions this client implements.

Functions

func VerifyChecksums

func VerifyChecksums(r io.Reader, sums []teaapi.Checksum, o DownloadOptions) ([]teaapi.ChecksumType, error)

VerifyChecksums reads r to the end and verifies it against sums with the rules of DownloadArtifact: every listed checksum of a supported algorithm must match (*ChecksumError otherwise), at least one of them other than SHA-1 (or SHA-1 with o.AllowSHA1Only), else ErrNoUsableChecksum; an algValue that is not lowercase hex of its algorithm's length is refused (*UnexpectedResponseError). With o.MaxBytes > 0, reading stops with ErrResponseTooLarge past that many bytes. It returns the algorithms verified, in the order first listed.

Types

type API

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

API is the typed TEA API at one APIBase. It is safe for concurrent use. Every method returns teaapi types; errors are *APIError (non-2xx), *UnexpectedResponseError (a 2xx the client cannot use), *URLPolicyError, or wrap ErrResponseTooLarge, ErrTimeout, ErrInvalidArgument or the caller's context error.

func (*API) AllComponentReleaseCollectionsOf

func (a *API) AllComponentReleaseCollectionsOf(ctx context.Context, id uuid.UUID, p CollectionPage) iter.Seq2[teaapi.Collection, error]

AllComponentReleaseCollectionsOf iterates over every collection of one component release.

func (*API) AllComponentReleases

func (a *API) AllComponentReleases(ctx context.Context, q ReleaseQuery) iter.Seq2[teaapi.ComponentRelease, error]

AllComponentReleases iterates over every component release the query selects.

func (*API) AllComponentReleasesOf

func (a *API) AllComponentReleasesOf(ctx context.Context, id uuid.UUID, p ReleasePage) iter.Seq2[teaapi.ComponentRelease, error]

AllComponentReleasesOf iterates over every release of one component.

func (*API) AllComponents

func (a *API) AllComponents(ctx context.Context, q ComponentQuery) iter.Seq2[teaapi.Component, error]

AllComponents iterates over every component the query selects.

func (*API) AllProductReleaseCollectionsOf

func (a *API) AllProductReleaseCollectionsOf(ctx context.Context, id uuid.UUID, p CollectionPage) iter.Seq2[teaapi.Collection, error]

AllProductReleaseCollectionsOf iterates over every collection of one product release.

func (*API) AllProductReleases

func (a *API) AllProductReleases(ctx context.Context, q ReleaseQuery) iter.Seq2[teaapi.ProductRelease, error]

AllProductReleases iterates over every product release the query selects.

func (*API) AllProductReleasesOf

func (a *API) AllProductReleasesOf(ctx context.Context, id uuid.UUID, p ReleasePage) iter.Seq2[teaapi.ProductRelease, error]

AllProductReleasesOf iterates over every release of one product.

func (*API) AllProducts

func (a *API) AllProducts(ctx context.Context, q ProductQuery) iter.Seq2[teaapi.Product, error]

AllProducts iterates over every product the query selects.

Example
package main

import (
	"context"
	"fmt"
	"log"

	tea "github.com/oolong-project/tea-client-go"
)

func main() {
	ctx := context.Background()
	c, err := tea.New()
	if err != nil {
		log.Fatal(err)
	}
	base, err := tea.ParseAPIBase("https://demo.rearmhq.com/tea", "1.0.0")
	if err != nil {
		log.Fatal(err)
	}
	api, err := c.API(base)
	if err != nil {
		log.Fatal(err)
	}
	for p, err := range api.AllProducts(ctx, tea.ProductQuery{Page: tea.Page{PageSize: 50}}) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(p.Uuid, p.Name)
	}
}

func (*API) Base

func (a *API) Base() APIBase

Base returns the API base this API is bound to.

func (*API) DownloadArtifact

func (a *API) DownloadArtifact(ctx context.Context, ref ArtifactRef, f teaapi.ArtifactFormat, w io.Writer, o DownloadOptions) (DownloadResult, error)

DownloadArtifact streams the content of format f of artifact revision ref to w and verifies it against f's checksums while streaming.

The bytes come from f.Url when it is set (an external location: it must pass the URL policy, and no credential is sent to it on any hop), else from <base>/artifact/<uuid>/<version>/download?mediaType=<f.MediaType>, the versioned endpoint, so the bytes are those of the revision whose checksums f carries. Redirects follow the client's rules; the Authorization header is decided on every hop. Content-Disposition is ignored. Only 200 is accepted: a 406 wraps ErrNoAcceptableFormat, other statuses are *APIError or *UnexpectedResponseError. A Content-Encoding the transport did not remove (it decodes only the gzip it asked for) is ErrUnsupportedContentEncoding.

The checksums are checked before the request: an algValue that is not lowercase hex of its algorithm's length is *UnexpectedResponseError, and without a supported checksum other than SHA-1 (SHA-1 counts only with o.AllowSHA1Only) the call fails with ErrNoUsableChecksum and makes no request; BLAKE3 and unknown algorithms are not supported and are ignored. After the body, every supported checksum listed must match, else *ChecksumError. More than o.MaxBytes (default Limits.DownloadBytes) is ErrResponseTooLarge. No response headers, or no next body byte, for Limits.IdleTimeout fails the call with an error wrapping ErrTimeout; a download that keeps sending is never cut off. There is no other time limit than ctx.

When it returns an error, DownloadArtifact may already have written bytes to w: the caller must discard them. DownloadArtifactToFile does that.

func (*API) DownloadArtifactToFile

func (a *API) DownloadArtifactToFile(ctx context.Context, ref ArtifactRef, f teaapi.ArtifactFormat, path string, o DownloadOptions) (res DownloadResult, err error)

DownloadArtifactToFile downloads like DownloadArtifact into a temporary file (mode 0600) created in path's directory, verifies it, syncs it and renames it over path. On any error the temporary file is removed and path is not touched. The library never derives a file name from the server (Content-Disposition is ignored).

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/google/uuid"

	tea "github.com/oolong-project/tea-client-go"
)

func main() {
	ctx := context.Background()
	c, err := tea.New()
	if err != nil {
		log.Fatal(err)
	}
	base, err := tea.ParseAPIBase("https://demo.rearmhq.com/tea", "1.0.0")
	if err != nil {
		log.Fatal(err)
	}
	api, err := c.API(base)
	if err != nil {
		log.Fatal(err)
	}
	release, err := api.GetProductRelease(ctx, uuid.MustParse("b9f115fb-6688-4a3f-a262-3acc04e1fc9e"))
	if err != nil {
		log.Fatal(err)
	}
	for _, art := range release.LatestCollection.Artifacts {
		for _, f := range art.Formats {
			// Written to a temporary file, verified against the format's
			// checksums, then renamed into place; nothing is left on failure.
			res, err := api.DownloadArtifactToFile(ctx, tea.ArtifactRef{UUID: art.Uuid, Version: art.Version}, f, "sbom.json", tea.DownloadOptions{})
			if err != nil {
				log.Fatal(err)
			}
			fmt.Println(res.Bytes, res.Verified)
			return
		}
	}
}

func (*API) DownloadLatestArtifact

func (a *API) DownloadLatestArtifact(ctx context.Context, id uuid.UUID, mediaType string, w io.Writer, o DownloadOptions) (DownloadResult, error)

DownloadLatestArtifact reads the latest revision of artifact id (GetLatestArtifact), picks its format whose media type is mediaType (type and subtype compared case-insensitively, parameters exactly; none is an error wrapping ErrNoAcceptableFormat, with no download), and downloads that revision with DownloadArtifact. It does not use the latest download endpoint: the latest revision can change between reading the checksums and fetching the bytes.

func (*API) DownloadSignature

func (a *API) DownloadSignature(ctx context.Context, ref ArtifactRef, f teaapi.ArtifactFormat, w io.Writer, o DownloadOptions) (int64, error)

DownloadSignature streams the detached signature of format f of artifact revision ref to w and returns the number of bytes written. It uses f.SignatureUrl when set (external: no credential on any hop), else <base>/artifact/<uuid>/<version>/signature/download?mediaType=<f.MediaType>. The URL, redirect, status and content-coding rules of DownloadArtifact apply; more than o.MaxBytes (default Limits.SignatureBytes) is ErrResponseTooLarge, and Limits.IdleTimeout applies. A 404 SIGNATURE_NOT_FOUND wraps ErrSignatureNotFound. The bytes are not verified: the specification defines no signature technology. On error, bytes already written to w must be discarded.

func (*API) Generated

func (a *API) Generated() *teaapi.ClientWithResponses

Generated returns the generated client for operations this package does not wrap. It sends through the same bounded, auth-aware doer as the typed methods: the URL policy, the credential rules and the byte and time limits apply. Its requests carry no call kind, so each is classified by its path relative to the API base: /artifact/{uuid}/{latest|version}/download as a download (Limits.DownloadBytes, IdleTimeout), .../signature as a signature (SignatureBytes, IdleTimeout), /discovery as discovery (DiscoveryBytes, AttemptTimeout), and everything else as JSON (JSONBytes, CallTimeout).

The generated download operations read the whole body into memory, so a download through Generated can hold up to Limits.DownloadBytes (512 MiB by default); DownloadArtifact streams and verifies checksums instead.

The auth transport decides every Authorization header, so a header set by a request editor is removed off a credential root and replaced on one. In particular a token request made through Generated cannot carry HTTP Basic credentials; use RequestToken.

func (*API) GetArtifact

func (a *API) GetArtifact(ctx context.Context, id uuid.UUID, version int) (*teaapi.Artifact, error)

GetArtifact reads one revision of an artifact's metadata.

func (*API) GetComponent

func (a *API) GetComponent(ctx context.Context, id uuid.UUID) (*teaapi.Component, error)

GetComponent reads one component.

func (*API) GetComponentCLE

func (a *API) GetComponentCLE(ctx context.Context, id uuid.UUID) (*teaapi.Cle, error)

GetComponentCLE reads a component's lifecycle events.

func (*API) GetComponentRelease

func (a *API) GetComponentRelease(ctx context.Context, id uuid.UUID) (*teaapi.ComponentReleaseWithCollection, error)

GetComponentRelease reads one component release with its latest collection.

func (*API) GetComponentReleaseCLE

func (a *API) GetComponentReleaseCLE(ctx context.Context, id uuid.UUID) (*teaapi.Cle, error)

GetComponentReleaseCLE reads a component release's lifecycle events.

func (*API) GetComponentReleaseCollection

func (a *API) GetComponentReleaseCollection(ctx context.Context, id uuid.UUID, version int) (*teaapi.Collection, error)

GetComponentReleaseCollection reads one version of a component release's collection.

func (*API) GetLatestArtifact

func (a *API) GetLatestArtifact(ctx context.Context, id uuid.UUID) (*teaapi.Artifact, error)

GetLatestArtifact reads the latest revision of an artifact's metadata.

func (*API) GetLatestComponentReleaseCollection

func (a *API) GetLatestComponentReleaseCollection(ctx context.Context, id uuid.UUID) (*teaapi.Collection, error)

GetLatestComponentReleaseCollection reads a component release's latest collection.

func (*API) GetLatestProductReleaseCollection

func (a *API) GetLatestProductReleaseCollection(ctx context.Context, id uuid.UUID) (*teaapi.Collection, error)

GetLatestProductReleaseCollection reads a product release's latest collection.

func (*API) GetProduct

func (a *API) GetProduct(ctx context.Context, id uuid.UUID) (*teaapi.Product, error)

GetProduct reads one product.

func (*API) GetProductCLE

func (a *API) GetProductCLE(ctx context.Context, id uuid.UUID) (*teaapi.Cle, error)

GetProductCLE reads a product's lifecycle events.

func (*API) GetProductRelease

func (a *API) GetProductRelease(ctx context.Context, id uuid.UUID) (*teaapi.ProductReleaseWithCollection, error)

GetProductRelease reads one product release with its latest collection.

func (*API) GetProductReleaseCLE

func (a *API) GetProductReleaseCLE(ctx context.Context, id uuid.UUID) (*teaapi.Cle, error)

GetProductReleaseCLE reads a product release's lifecycle events.

func (*API) GetProductReleaseCollection

func (a *API) GetProductReleaseCollection(ctx context.Context, id uuid.UUID, version int) (*teaapi.Collection, error)

GetProductReleaseCollection reads one version of a product release's collection.

func (*API) ListComponentReleaseCollections

func (a *API) ListComponentReleaseCollections(ctx context.Context, id uuid.UUID, pg CollectionPage) (*teaapi.PaginatedCollectionResponse, error)

ListComponentReleaseCollections reads one page of a component release's collections.

func (*API) ListComponentReleases

func (a *API) ListComponentReleases(ctx context.Context, id uuid.UUID, pg ReleasePage) (*teaapi.PaginatedComponentReleaseResponse, error)

ListComponentReleases reads one page of a component's releases.

func (*API) ListProductReleaseCollections

func (a *API) ListProductReleaseCollections(ctx context.Context, id uuid.UUID, pg CollectionPage) (*teaapi.PaginatedCollectionResponse, error)

ListProductReleaseCollections reads one page of a product release's collections.

func (*API) ListProductReleases

func (a *API) ListProductReleases(ctx context.Context, id uuid.UUID, pg ReleasePage) (*teaapi.PaginatedProductReleaseResponse, error)

ListProductReleases reads one page of a product's releases.

func (*API) QueryComponentReleases

func (a *API) QueryComponentReleases(ctx context.Context, q ReleaseQuery) (*teaapi.PaginatedComponentReleaseResponse, error)

QueryComponentReleases reads one page of component releases.

func (*API) QueryComponents

func (a *API) QueryComponents(ctx context.Context, q ComponentQuery) (*teaapi.PaginatedComponentResponse, error)

QueryComponents reads one page of components.

func (*API) QueryProductReleases

func (a *API) QueryProductReleases(ctx context.Context, q ReleaseQuery) (*teaapi.PaginatedProductReleaseResponse, error)

QueryProductReleases reads one page of product releases.

func (*API) QueryProducts

func (a *API) QueryProducts(ctx context.Context, q ProductQuery) (*teaapi.PaginatedProductResponse, error)

QueryProducts reads one page of products.

func (*API) RequestToken

func (a *API) RequestToken(ctx context.Context, keyID, secret string) (*teaapi.TokenResponse, error)

RequestToken exchanges an API key for an access token with the client_credentials grant: one POST to <API base>/token, with the key id and secret each form-urlencoded before joining them for HTTP Basic (RFC 6749 section 2.3.1). The request follows no redirect: a 3xx answer is an *UnexpectedResponseError and no request reaches its Location, so the credentials reach exactly the URL built from this API's base. A configured bearer token is not sent on it. A 404 wraps ErrNotImplemented (the server has no authentication); a token-error-response is a *TokenError. The response is bounded by Limits.ErrorBodyBytes and the call by CallTimeout. Neither the key id nor the secret appears in any error or trace event.

type APIBase

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

APIBase is one TEA API: a root URL and the version used in paths. Build it with ParseAPIBase (or, in discovery, from a server the client selected).

func ParseAPIBase

func ParseAPIBase(rootURL, version string) (APIBase, error)

ParseAPIBase validates rootURL against the specification's rootUrl pattern (absolute http or https, no userinfo, query, fragment or trailing "/") and refuses dot segments with a *URLPolicyError; version must be a SemVer 2.0.0 version that is one of SupportedVersions once build metadata is ignored. The version is kept verbatim for paths. Whether an http root may be used is decided by Client.API, against the client's allowances.

func (APIBase) RootURL

func (b APIBase) RootURL() string

RootURL returns the root URL as given.

func (APIBase) String

func (b APIBase) String() string

String returns the API base: root + "/v" + version.

func (APIBase) Version

func (b APIBase) Version() string

Version returns the version as given (used verbatim in paths).

type APIError

type APIError struct {
	Operation string
	Status    int
	// TEA is true when the body was a TEA error-response: Content-Type
	// application/json and a JSON object with a string "error" property.
	TEA bool
	// Code is the error code when TEA, ErrorCodeUnknown for an unknown code.
	Code ErrorCode
	// RawCode is the code as received when it is unknown, sanitised and
	// truncated to 64 bytes.
	RawCode string
	// Message is the server's message, control characters removed and
	// truncated to 200 bytes. No other part of a body reaches an error.
	Message string
	// Challenge is the parsed WWW-Authenticate header of a 401, if any.
	Challenge *Challenge
}

APIError is a non-2xx answer from a TEA server.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is matches the sentinels: the six code sentinels by TEA code, ErrUnauthorized by status 401, ErrForbidden by 403 and ErrServer by 5xx.

type AmbiguousError

type AmbiguousError struct {
	Results []DiscoveryResult
}

AmbiguousError is a discovery with several results and no FlowOptions.Select. Results are in the server's order; Candidates loads them for a choice.

func (*AmbiguousError) Error

func (e *AmbiguousError) Error() string

type ArtifactRef

type ArtifactRef struct {
	UUID    uuid.UUID
	Version int
}

ArtifactRef names one revision of an artifact: the checksums a download verifies are those of this revision.

type Attempt

type Attempt struct {
	Stage  Stage  // StageWellKnown or StageAPIDiscovery
	URL    string // scheme, host, port and path: never the query (the TEI or PURL)
	Reason string // sanitised, at most 200 bytes; never response-body content
	Err    error  // the cause, e.g. wrapping ErrTimeout, ErrResponseTooLarge, ErrInsecureURL
}

Attempt is one failed discovery attempt.

type Candidate

type Candidate struct {
	Result  DiscoveryResult
	API     *API
	Release *teaapi.ProductReleaseWithCollection
}

Candidate is one discovery result with the API of its selected server and its product release, as Candidates loads it.

type Challenge

type Challenge struct {
	Scheme string // as received, e.g. "Bearer"
	Error  string // the error parameter, e.g. "invalid_token"; "" when absent
}

Challenge is a parsed WWW-Authenticate challenge of a 401 response.

type ChecksumError

type ChecksumError struct {
	Alg      teaapi.ChecksumType
	Expected string
	Actual   string
}

ChecksumError is a listed checksum that did not match. Expected and Actual are lowercase hex digests of Alg's length.

func (*ChecksumError) Error

func (e *ChecksumError) Error() string

func (*ChecksumError) Unwrap

func (e *ChecksumError) Unwrap() error

Unwrap returns ErrChecksumMismatch.

type Client

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

Client is a TEA client. It is safe for concurrent use.

func New

func New(opts ...Option) (*Client, error)

New builds a Client. It refuses an option value it cannot parse (ErrInvalidOption), including an http credential root or well-known location that no WithInsecureHTTPBase allowance covers.

func (*Client) API

func (c *Client) API(base APIBase) (*API, error)

API returns the typed API bound to base. An http base must be under a WithInsecureHTTPBase allowance (*URLPolicyError otherwise).

func (*Client) Candidates

func (c *Client) Candidates(ctx context.Context, results []DiscoveryResult) ([]Candidate, error)

Candidates loads, for each discovery result, the server SelectServer picks, its API and the product release there: one product-release request per result, in order. More than Limits.DiscoveryResults results (a caller may pass results it did not get from Discover) is ErrTooManyResults before any request. The first failure (a refused server, a failed request) is returned, naming the result's index.

func (*Client) Discover

func (c *Client) Discover(ctx context.Context, t tei.TEI) ([]DiscoveryResult, error)

Discover resolves a TEI as discovery/readme.md defines it: fetch https://<domain>/.well-known/tea (or the WithWellKnownLocation base for the domain), validate it, order its endpoints by the greatest mutually supported version and then priority, and ask each in turn for /v<version>/discovery?tei=<TEI>. It returns the results of the first valid answer, in the server's order; it never prompts.

A TEA 404 ends discovery with *NotResolvedError (no failover); 400, 401 and 403 end it with *APIError. Connection, TLS and DNS failures, an attempt exceeding Limits.AttemptTimeout, 5xx, a non-TEA 404, an invalid or oversized body, or more than Limits.DiscoveryResults results are failed attempts: the client backs off (250 ms doubling, capped at 4 s, by default) and tries the next candidate, cycling through the candidates, until WithDiscoveryAttempts' bound (default 4, counted across both stages, the well-known fetch included) is used up, which gives a *DiscoveryError. The caller's context ending ends Discover with its error. No credential is sent except to a configured credential root.

Example
package main

import (
	"context"
	"fmt"
	"log"

	tea "github.com/oolong-project/tea-client-go"
	"github.com/oolong-project/tea-client-go/tei"
)

func main() {
	ctx := context.Background()
	c, err := tea.New()
	if err != nil {
		log.Fatal(err)
	}
	t, err := tei.Parse("tei://demo.rearmhq.com/uuid/b9f115fb-6688-4a3f-a262-3acc04e1fc9e")
	if err != nil {
		log.Fatal(err)
	}
	results, err := c.Discover(ctx, t) // every result, in the server's order
	if err != nil {
		log.Fatal(err)
	}
	base, err := c.SelectServer(results[0]) // a servers[] root, not the /discovery base
	if err != nil {
		log.Fatal(err)
	}
	api, err := c.API(base)
	if err != nil {
		log.Fatal(err)
	}
	release, err := api.GetProductRelease(ctx, results[0].ProductReleaseUUID)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(release.Version)
}

func (*Client) DiscoverPURL

func (c *Client) DiscoverPURL(ctx context.Context, base APIBase, purl string) ([]DiscoveryResult, error)

DiscoverPURL resolves a PURL within the inventory of one known API base: /v<version>/discovery?purl=<PURL> at base. Classification, the attempt bound and backoff are those of Discover, with base as the only candidate. purl must start with "pkg:", be at most 2048 bytes of valid UTF-8 and have no control characters; it is sent as given, query-encoded once.

func (*Client) FlowFromRelease

func (c *Client) FlowFromRelease(ctx context.Context, a *API, release uuid.UUID, o FlowOptions) (*FlowResult, error)

FlowFromRelease reads product release release at a with its lifecycle and components. The release's CLE is nil when the server answers NOT_IMPLEMENTED or OBJECT_UNKNOWN; another CLE error, or any error on the release itself, is returned. More component refs than Limits.FlowComponents is ErrTooManyComponents before any component request (never a silent truncation). For each ref, in order: a pinned ref reads that component release; an unpinned one reads the component and its newest release (ListComponentReleases sorted by createdDate descending, page size 1; a component with no release fails with an error wrapping ErrObjectUnknown), then that release. Then the component release's CLE, as for the product release. A component's failure is recorded in its Err and the walk continues; the caller's context ending ends the walk with ctx.Err().

func (*Client) FullFlow

func (c *Client) FullFlow(ctx context.Context, t tei.TEI, o FlowOptions) (*FlowResult, error)

FullFlow resolves t and reads its product release with its lifecycle and components (the CLI's full_tea_flow): Discover; with one result the server SelectServer picks and FlowFromRelease. With several results and no o.Select it returns *AmbiguousError (and reads no product release); with o.Select it loads Candidates (at most Limits.DiscoveryResults product-release requests), lets Select choose (an index out of range wraps ErrInvalidArgument) and continues with the chosen candidate's API and release. Discovery errors are returned as Discover gives them.

Example
package main

import (
	"context"
	"fmt"
	"log"

	tea "github.com/oolong-project/tea-client-go"
	"github.com/oolong-project/tea-client-go/tei"
)

func main() {
	ctx := context.Background()
	c, err := tea.New()
	if err != nil {
		log.Fatal(err)
	}
	t, err := tei.Parse("tei://demo.rearmhq.com/uuid/b9f115fb-6688-4a3f-a262-3acc04e1fc9e")
	if err != nil {
		log.Fatal(err)
	}
	res, err := c.FullFlow(ctx, t, tea.FlowOptions{})
	if err != nil {
		log.Fatal(err) // *tea.AmbiguousError when discovery returned several results
	}
	fmt.Println(*res.Release.ProductName, res.Release.Version)
	for _, comp := range res.Components {
		if comp.Err != nil {
			fmt.Println("component", comp.Ref.Uuid, "failed:", comp.Err)
			continue
		}
		fmt.Println("component release", comp.Release.Uuid, comp.Release.Version)
	}
}

func (*Client) SelectServer

func (c *Client) SelectServer(r DiscoveryResult) (APIBase, error)

SelectServer chooses the API base for a discovery result with the rules of the well-known selection: servers with a version in SupportedVersions (build metadata ignored), ordered by the greatest such version, then priority (absent = 1) descending, then the order received. The chosen rootUrl must pass the URL policy: an http root is usable only under a WithInsecureHTTPBase allowance (*URLPolicyError otherwise). The base that answered /discovery is not used unless it is listed in Servers.

type CollectionPage

type CollectionPage struct {
	Page
	SortField CollectionSortField
}

CollectionPage pages through one release's collections (listProductReleaseCollections, listComponentReleaseCollections).

type CollectionSortField

type CollectionSortField string

CollectionSortField is the spec's sort-field-collection.

const CollectionSortVersion CollectionSortField = "version"

Collection sort fields.

func (CollectionSortField) Valid

func (f CollectionSortField) Valid() bool

Valid reports whether f is empty or one of the constants.

type ComponentQuery

type ComponentQuery struct {
	Page
	SortField ComponentSortField
	IDType    teaapi.IdentifierType
	IDValue   string
}

ComponentQuery selects components (queryComponents).

type ComponentSortField

type ComponentSortField string

ComponentSortField is the spec's sort-field-component.

const ComponentSortName ComponentSortField = "name"

Component sort fields.

func (ComponentSortField) Valid

func (f ComponentSortField) Valid() bool

Valid reports whether f is empty or one of the constants.

type DiscoveryError

type DiscoveryError struct {
	Stage    Stage
	Attempts []Attempt
}

DiscoveryError is a discovery that did not reach a result: the attempt bound was exhausted, or the well-known document offered no endpoint with a supported version. Stage is the stage it ended in.

func (*DiscoveryError) Error

func (e *DiscoveryError) Error() string

func (*DiscoveryError) Unwrap

func (e *DiscoveryError) Unwrap() []error

Unwrap returns each attempt's Err, so errors.Is(err, ErrTimeout), errors.Is(err, ErrTooManyResults) and the like see through a DiscoveryError.

type DiscoveryResult

type DiscoveryResult struct {
	// ProductReleaseUUID is the resolved product release. A server may send
	// any form google/uuid decodes; the value is canonical (String() is
	// lowercase).
	ProductReleaseUUID uuid.UUID
	// Servers are the API roots that serve the release, as received and
	// validated: non-empty, each rootUrl matching the specification's
	// pattern and allowed by the URL policy, each version SemVer, each
	// priority in [0, 1]. Use SelectServer to choose one.
	Servers []teaapi.ServerInfo
	// DiscoveredAt is the API base whose /discovery gave this result
	// (informational: later calls go to a server from Servers).
	DiscoveredAt APIBase
}

DiscoveryResult is one entry of a /discovery answer: a product release and the TEA servers that serve it.

type DownloadOptions

type DownloadOptions struct {
	// MaxBytes overrides the byte limit for this call: Limits.DownloadBytes
	// for artifact content, Limits.SignatureBytes for a signature. Zero
	// keeps the limit; negative is refused.
	MaxBytes int64
	// AllowSHA1Only accepts a format whose only supported checksum is
	// SHA-1. Off by default: such a format fails with ErrNoUsableChecksum.
	AllowSHA1Only bool
}

DownloadOptions adjusts one download.

type DownloadResult

type DownloadResult struct {
	// Bytes is the number of bytes written.
	Bytes int64
	// MediaType is the media type (type/subtype, lowercase, no parameters)
	// of the response's Content-Type, "" when absent or unparsable.
	MediaType string
	// Source is where the bytes came from.
	Source DownloadSource
	// Verified are the checksum algorithms verified, in the order first
	// listed in the format.
	Verified []teaapi.ChecksumType
}

DownloadResult describes a verified download.

type DownloadSource

type DownloadSource string

DownloadSource says where the bytes of a download came from.

const (
	// DownloadSourceServer: the TEA server's versioned download endpoint
	// (redirects it answered with included).
	DownloadSourceServer DownloadSource = "server"
	// DownloadSourceExternal: the format's external url.
	DownloadSourceExternal DownloadSource = "external"
)

Download sources.

type ErrorCode

type ErrorCode string

ErrorCode is the error code of a TEA error-response body. The six codes of the specification's unknown-error-type are known; any other code received maps to ErrorCodeUnknown and is kept, truncated, in APIError.RawCode.

const (
	ErrorCodeUnknown            ErrorCode = ""
	ErrorCodeObjectUnknown      ErrorCode = "OBJECT_UNKNOWN"
	ErrorCodeNotImplemented     ErrorCode = "NOT_IMPLEMENTED"
	ErrorCodeNoAcceptableFormat ErrorCode = "NO_ACCEPTABLE_FORMAT"
	ErrorCodeSignatureNotFound  ErrorCode = "SIGNATURE_NOT_FOUND"
	ErrorCodeInvalidRequest     ErrorCode = "INVALID_REQUEST"
	ErrorCodeInvalidPageToken   ErrorCode = "INVALID_PAGE_TOKEN"
)

Error codes of the TEA specification (unknown-error-type).

type FlowComponent

type FlowComponent struct {
	Ref teaapi.ComponentRef
	// Pinned is true when Ref.Release names the component release.
	Pinned bool
	// Component is fetched for an unpinned ref only.
	Component *teaapi.Component
	// Release is the pinned component release, or for an unpinned ref the
	// newest by createdDate.
	Release *teaapi.ComponentReleaseWithCollection
	// CLE is the component release's lifecycle; nil when NOT_IMPLEMENTED or
	// OBJECT_UNKNOWN, or with SkipCLE.
	CLE *teaapi.Cle
	// Err is this component's failure; the walk continues with the others.
	Err error
}

FlowComponent is one component ref of a product release, resolved.

type FlowOptions

type FlowOptions struct {
	// Select chooses among several discovery results. It is given every
	// candidate (each with its selected server and product release) and
	// returns the index of the one to continue with. nil: several results
	// are an *AmbiguousError. The library never prompts; a caller that
	// asks a person does it here or after an *AmbiguousError.
	Select func(ctx context.Context, cands []Candidate) (int, error)
	// SkipCLE skips every lifecycle (CLE) request.
	SkipCLE bool
}

FlowOptions adjusts FullFlow and FlowFromRelease.

type FlowResult

type FlowResult struct {
	// API is the API the release was read from.
	API *API
	// Release is the product release; its LatestCollection carries the
	// artifacts and their formats (the flow downloads nothing).
	Release *teaapi.ProductReleaseWithCollection
	// ReleaseCLE is nil when the server answers NOT_IMPLEMENTED or
	// OBJECT_UNKNOWN for it, or with SkipCLE.
	ReleaseCLE *teaapi.Cle
	// Components follow the release's component refs, in order.
	Components []FlowComponent
}

FlowResult is a product release with its lifecycle and components.

type Limits

type Limits struct {
	WellKnownBytes   int64 // .well-known/tea; default 64 KiB
	DiscoveryBytes   int64 // /discovery; default 1 MiB
	DiscoveryResults int   // results in one /discovery answer and given to Candidates; default 32
	JSONBytes        int64 // every other JSON response; default 16 MiB
	ErrorBodyBytes   int64 // non-2xx bodies (read to classify, then discarded) and /token; default 64 KiB
	DownloadBytes    int64 // artifact content; default 512 MiB
	SignatureBytes   int64 // signature content; default 16 MiB
	Redirects        int   // per request; default 5
	Pages            int   // per iterator; default 1000
	FlowComponents   int   // component refs walked by the flow helper; default 1000

	// AttemptTimeout bounds each discovery attempt (one well-known GET or one
	// /discovery GET, headers and body); default 15 s.
	AttemptTimeout time.Duration
	// CallTimeout bounds each non-download request (typed JSON calls,
	// /token, Generated() calls classified as JSON), headers and body;
	// default 30 s.
	CallTimeout time.Duration
	// IdleTimeout bounds downloads and signatures: the longest wait for the
	// response headers or for the next body byte. A download that keeps
	// sending is never cut off. Default 30 s.
	IdleTimeout time.Duration
}

Limits bounds what the client reads and how long it waits. The zero value of a field means its default. For the three durations, a negative value disables that bound and leaves only the caller's context; a byte or count limit must not be negative.

type NotResolvedError

type NotResolvedError struct {
	Base    APIBase
	Code    ErrorCode // the TEA error code, ErrorCodeUnknown for an unknown one
	RawCode string    // the code as received when unknown, sanitised, at most 64 bytes
}

NotResolvedError is a TEA error answer with status 404 from /discovery: the server at Base does not resolve the identifier. Discovery stops there and does not fail over (discovery/readme.md "Unresolved identifiers").

func (*NotResolvedError) Error

func (e *NotResolvedError) Error() string

func (*NotResolvedError) Is

func (e *NotResolvedError) Is(target error) bool

Is matches ErrObjectUnknown when Code is OBJECT_UNKNOWN.

type Option

type Option func(*options)

Option configures a Client.

func WithAPIKey

func WithAPIKey(rootURL, keyID, secret string) Option

WithAPIKey configures an API key (key id and secret) for rootURL (an API root, as in servers[].rootUrl). No token is requested up front: clients do not probe /token. When a GET under rootURL is answered 401 with a Bearer challenge, the client requests a token from the /token of the API that made the request (it must be under rootURL), with the client_credentials grant and HTTP Basic credentials, following no redirect; it caches the token (until expires_in minus 30 s, when given) and retries the request once with it. A 401 on a request that carried the cached token drops it, and the client obtains a fresh one and retries once. There is never more than one recovery per request, and none on a 403. The token is sent on requests under rootURL and nowhere else, like a WithBearerToken token. An http rootURL must be under a WithInsecureHTTPBase allowance. The key id, the secret and the token never appear in an error or a trace event.

When several credentials cover a URL, the one with the longest root applies (the first configured among equal roots).

Example
package main

import (
	"log"

	tea "github.com/oolong-project/tea-client-go"
)

func main() {
	// The key is exchanged for a token only when the server asks for one
	// (a 401 with a Bearer challenge under the root), and the token is sent
	// under that root only.
	c, err := tea.New(tea.WithAPIKey("https://tea.example.com/tea", "key-id", "key-secret"))
	if err != nil {
		log.Fatal(err)
	}
	_ = c
}

func WithBearerToken

func WithBearerToken(rootURL, token string) Option

WithBearerToken sends "Authorization: Bearer <token>" on requests under rootURL (an API root, as in servers[].rootUrl), and on no other request. An http rootURL must be under a WithInsecureHTTPBase allowance.

func WithDiscoveryAttempts

func WithDiscoveryAttempts(n int, firstBackoff time.Duration) Option

WithDiscoveryAttempts sets the total number of discovery attempts across the well-known and /discovery stages (default 4) and the first backoff (default 250 ms, doubling, capped at 4 s). Every request counts, the successful well-known fetch included, so Discover needs at least 2; DiscoverPURL makes no well-known request. A zero firstBackoff keeps the default.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient makes the client send through hc. The library copies hc and sets its own CheckRedirect (redirect limit and URL policy) and wraps its Transport (nil means http.DefaultTransport) in the auth transport. A transport passed here therefore sits below the auth transport and sees Authorization headers: use WithTrace for debug output, not a transport that dumps headers. hc.Timeout, if set, applies on top of the library's own time bounds.

func WithInsecureHTTPBase

func WithInsecureHTTPBase(rawURL string) Option

WithInsecureHTTPBase allows plain http for URLs under rawURL: same host and port, and a path equal to rawURL's path or below it by whole segments. rawURL is an absolute http URL without userinfo, query, fragment, trailing "/" or dot segment. Repeatable. There is no global switch, and nothing a server sends adds or widens an allowance.

Example
package main

import (
	"log"

	tea "github.com/oolong-project/tea-client-go"
)

func main() {
	// A local server over plain http: the allowance covers the origin and
	// every path under it, and nothing else.
	c, err := tea.New(
		tea.WithInsecureHTTPBase("http://localhost:8086"),
		tea.WithWellKnownLocation("localhost", "http://localhost:8086"),
		tea.WithBearerToken("http://localhost:8086/tea", "a-token"),
	)
	if err != nil {
		log.Fatal(err)
	}
	_ = c
}

func WithLimits

func WithLimits(l Limits) Option

WithLimits sets the limits; zero fields keep their defaults.

func WithTrace

func WithTrace(f func(TraceEvent)) Option

WithTrace registers an observer called synchronously, in request order, for every request the client makes (redirects included), every response, and each failed discovery attempt and backoff. Events never carry headers, bodies, query strings or credentials. A panic in f is not recovered.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent replaces the default User-Agent "tea-client-go/<version>".

func WithWellKnownLocation

func WithWellKnownLocation(domain, location string) Option

WithWellKnownLocation makes discovery fetch <location>/.well-known/tea for TEIs of domain, instead of https://<domain>/.well-known/tea. An http location also needs a WithInsecureHTTPBase allowance covering it.

type Page

type Page struct {
	PageSize  int
	PageToken string
	SortOrder SortOrder
}

Page carries the paging parameters every list operation takes. A zero field is omitted from the request (PageSize 0 is the server's default). PageToken is passed back verbatim; it is opaque.

type ProductQuery

type ProductQuery struct {
	Page
	SortField ProductSortField
	IDType    teaapi.IdentifierType
	IDValue   string
}

ProductQuery selects products (queryProducts).

type ProductSortField

type ProductSortField string

ProductSortField is the spec's sort-field-product.

const ProductSortName ProductSortField = "name"

Product sort fields.

func (ProductSortField) Valid

func (f ProductSortField) Valid() bool

Valid reports whether f is empty or one of the constants.

type ReleasePage

type ReleasePage struct {
	Page
	SortField ReleaseSortField
}

ReleasePage pages through one parent's releases (listProductReleases, listComponentReleases).

type ReleaseQuery

type ReleaseQuery struct {
	Page
	SortField ReleaseSortField
	IDType    teaapi.IdentifierType
	IDValue   string
}

ReleaseQuery selects product releases or component releases (queryProductReleases, queryComponentReleases).

type ReleaseSortField

type ReleaseSortField string

ReleaseSortField is the spec's sort-field-product-release and sort-field-component-release (the same set).

const (
	ReleaseSortCreatedDate ReleaseSortField = "createdDate"
	ReleaseSortReleaseDate ReleaseSortField = "releaseDate"
	ReleaseSortVersion     ReleaseSortField = "version"
)

Release sort fields.

func (ReleaseSortField) Valid

func (f ReleaseSortField) Valid() bool

Valid reports whether f is empty or one of the constants.

type SortOrder

type SortOrder string

SortOrder is the spec's sort-order.

const (
	SortAsc  SortOrder = "asc"
	SortDesc SortOrder = "desc"
)

Sort orders. The zero value omits the parameter (server default: asc).

func (SortOrder) Valid

func (o SortOrder) Valid() bool

Valid reports whether o is empty or one of the constants.

type Stage

type Stage string

Stage names the part of the protocol a request or an attempt belongs to.

const (
	StageWellKnown    Stage = "well-known"
	StageAPIDiscovery Stage = "api-discovery"
	StageAPI          Stage = "api"
	StageDownload     Stage = "download"
	StageToken        Stage = "token"
)

Stages.

type TokenError

type TokenError struct {
	Status      int
	Code        teaapi.TokenErrorResponseError
	Description string
}

TokenError is an OAuth 2.0 token-error-response (RFC 6749 section 5.2) from /token. Code is as received, sanitised and truncated to 64 bytes; Description is sanitised and truncated to 200 bytes.

func (*TokenError) Error

func (e *TokenError) Error() string

type TraceEvent

type TraceEvent struct {
	Kind   TraceKind
	Stage  Stage
	Method string
	URL    string        // scheme, host, port and path only: never query, fragment or userinfo
	Status int           // TraceResponse
	Reason string        // TraceAttemptFailed: same text as the Attempt in a discovery error
	Wait   time.Duration // TraceBackoff
}

TraceEvent is what a WithTrace observer receives. It never carries a header, a body, a query string or a credential.

type TraceKind

type TraceKind string

TraceKind is the kind of a TraceEvent.

const (
	TraceRequest       TraceKind = "request"
	TraceResponse      TraceKind = "response"
	TraceAttemptFailed TraceKind = "attempt-failed"
	TraceBackoff       TraceKind = "backoff"
)

Trace event kinds.

type URLPolicyError

type URLPolicyError struct {
	URL    string
	Reason string
	// contains filtered or unexported fields
}

URLPolicyError is a URL the client refused to request or follow. URL is redacted: scheme, host, port and path only, never userinfo or query.

func (*URLPolicyError) Error

func (e *URLPolicyError) Error() string

func (*URLPolicyError) Unwrap

func (e *URLPolicyError) Unwrap() error

Unwrap returns ErrInsecureURL or ErrRedirectLimit.

type UnexpectedResponseError

type UnexpectedResponseError struct {
	Operation string
	Status    int
	Reason    string
}

UnexpectedResponseError is a response the client cannot use: a 2xx body that is missing or does not decode to the declared type, a response that breaks a rule callers rely on (hasNext without nextPageToken), or a status the operation does not expect.

func (*UnexpectedResponseError) Error

func (e *UnexpectedResponseError) Error() string

Directories

Path Synopsis
internal
oolongtest
Package oolongtest starts an oolong TEA server (github.com/oolong-project/oolong, oolong/oolong-server) for integration tests.
Package oolongtest starts an oolong TEA server (github.com/oolong-project/oolong, oolong/oolong-server) for integration tests.
Package teaapi holds the models and the low-level client of the Transparency Exchange API (TEA) v1.0.0, generated by oapi-codegen (pinned in ../tools.mod) from ../spec/openapi.yaml, which is a byte copy of spec/openapi.yaml of CycloneDX/transparency-exchange-api at commit 962a0228af1bfcc1232ac3f79239317ff33fdb04 (see ../spec/SPEC_PIN.md).
Package teaapi holds the models and the low-level client of the Transparency Exchange API (TEA) v1.0.0, generated by oapi-codegen (pinned in ../tools.mod) from ../spec/openapi.yaml, which is a byte copy of spec/openapi.yaml of CycloneDX/transparency-exchange-api at commit 962a0228af1bfcc1232ac3f79239317ff33fdb04 (see ../spec/SPEC_PIN.md).
Package tei parses Transparency Exchange Identifiers (TEIs) as defined by the TEA discovery specification ("TEI syntax", discovery/readme.md of CycloneDX/transparency-exchange-api at the commit spec/SPEC_PIN.md names).
Package tei parses Transparency Exchange Identifiers (TEIs) as defined by the TEA discovery specification ("TEI syntax", discovery/readme.md of CycloneDX/transparency-exchange-api at the commit spec/SPEC_PIN.md names).

Jump to

Keyboard shortcuts

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