go-common

module
v0.116.5 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0

README

go-common

Shared Go primitives for the fleet's services: the HTTP server bootstrap, the SSRF-safe client, typed config and errors, the API-key client, and the small coordination clients (rate limits, backoff, locks of a sort) that every service would otherwise write for itself.

import "github.com/baditaflorin/go-common/safehttp"

Module github.com/baditaflorin/go-common, Go 1.26. This repository is public: nothing sensitive belongs in it.

Change go-common, not the consumers. When a fix would touch every service, fix it here and bump the dependency. That only works if releases are trustworthy, which is what the API policy and the CI gates below are for.

Which package do I use?

I need to... Use
Start an HTTP service with the fleet middleware, /health, /selftest, graceful drain server with config and env
Call the public internet safehttp.NewClient (refuses internal addresses, DNS-rebind safe)
Call a sibling fleet service on the private mesh meshclient: you must choose fail-open or fail-closed, and in fail-open it adds "<primitive>-down" to the request's degraded list. safehttp rejects private IPs by design, so it cannot be used here
Fetch a page through the fleet fetch cache fleetfetch
Send a browser through an upstream proxy that needs credentials egressproxy with proxysupplier
Verify an API key, or protect a handler apikey, middleware
Read environment variables env; declare the ones your package owns in its registry so they are listed in docs/ENV.md, checked at start-up and shown redacted on the debug server
Write structured logs with the service, version and trace id logx: set LOG_FORMAT=json (or pass server.WithStructuredLogs()); off by default
Return JSON, typed errors, pages response, errors, pagination
Decode and validate a request body validate
Retry, or protect a slow upstream resilience (retries limited by a budget, plus a breaker and a load-shed gate), built from retry, circuitbreaker and loadshed; also backoffcoord, ratecoord
Decide which result type to return docs/outcomes.md: errors, meshresult, degraded, nullify and what each is for
Decide which observability package to use docs/observability.md: what promx, metrics, reqstats, logx, telemetry, graph and obs each emit, what server.New wires by default, and what each costs per request
Fake time or an upstream in a test clock (testhelpers/testclock), testhelpers/httpmock
Test a URL or host guard against known SSRF bypasses, or fail a test that leaks goroutines testhelpers/ssrfcorpus, testhelpers/leakcheck

client.Client, client.New and client.Post are deprecated in favour of safehttp.NewClient or meshclient; the client.Fetch and JSProxy* helpers have no replacement and are not deprecated. shutdown is deprecated in favour of server's graceful drain. How many repositories import each package: docs/package-usage.md. What the small packages may import: docs/dependencies.md.

Runnable examples (checked by go test) are in example_test.go next to the packages above. The full list of packages is in docs/PACKAGES.md, generated from the packages' own doc comments.

Using go-common in a service

  • Pin a recent version and bump it when a release lands; the changelog says what changed and whether it can break you (CHANGELOG.md).
  • Lint with the shared config so deprecated API and the common HTTP mistakes show up in your CI: see lint/README.md.
  • What a release promises (and what it does not): docs/api-policy.md.
  • Check that your pin has go-common's security fixes: go run github.com/baditaflorin/go-common/scripts/compatcheck@latest -gomod go.mod (the floor and the fixes behind it are in compat/compat.json; see docs/releasing.md for backports to old lines).

Working on go-common

Every change to the module has to pass, in CI (Woodpecker, .woodpecker.yml):

Gate What it catches
gofmt, go vet, go build, go test The basics
go test -race Data races
golangci-lint (new findings only) Bugs and dead code; legacy findings do not block
scripts/vuln-check.sh (govulncheck) A reachable known vulnerability that is not in the reviewed, expiring allowlist scripts/govulncheck-allow.txt
scripts/forward-compat.sh A behaviour change Go makes for a newer go line (GODEBUG defaults): vet and the tests are run on a copy with the line raised, see docs/releasing.md
scripts/apidiff-check.sh An incompatible API change that the changelog does not call BREAKING
scripts/bench-gate.sh A hot-path benchmark that started allocating more (allocs/op, against the merge base)
scripts/release-check.sh A CHANGELOG version that is malformed, already tagged, or not the next free one
scripts/fuzz-changed.sh (short smoke of the packages the change touches; a push to main runs scripts/fuzz.sh, every target) Panics and hangs on hostile input in the parsers
scripts/coverage-ratchet.sh (pushes to main only; run it by hand on a pull request) A package whose statement coverage fell below its floor in coverage/floors.txt, or a tested package with no floor
go run ./scripts/pkgindex -check A stale package index, or a package with no doc comment
go run ./scripts/envdoc -check A stale docs/ENV.md, or a package that declares environment variables but is not imported by the generator
lint/selftest.sh The shared lint config no longer firing

The steps run side by side in stages (depends_on in .woodpecker.yml; Woodpecker starts a stage when the one before it has finished), so a pipeline takes about as long as the slowest step of each stage, not the sum of all of them.

Most of these are CPU-heavy. Run them in CI or on a build host rather than a laptop. scripts/fuzz.sh 2m is the long version of the fuzz smoke, meant for a nightly job; a crashing input it finds must be fixed and then committed under testdata/fuzz/ so plain go test replays it forever.

Every release needs a CHANGELOG.md entry. A change that removes or alters exported API, or changes a default or an environment variable, leads that entry with BREAKING:; see docs/api-policy.md. A new package needs a package comment, or the index check fails.

License

Apache License 2.0, see LICENSE. Use it commercially if you like: keep the license text and the NOTICE attribution with what you distribute. This covers every release, including the ones tagged before v0.111.1, which were published without a license file (see NOTICE).

Directories

Path Synopsis
Package agent defines the machine-readable "agent contract" that every fleet service can advertise so an AI agent (Claude, Codex, OpenCode, an MCP server, the catalog hub) can call it correctly without guessing the input shape, auth model, or output envelope.
Package agent defines the machine-readable "agent contract" that every fleet service can advertise so an AI agent (Claude, Codex, OpenCode, an MCP server, the catalog hub) can call it correctly without guessing the input shape, auth model, or output envelope.
Package apikey is the canonical client for the fleet's keystore service (baditaflorin/go-apikey-service).
Package apikey is the canonical client for the fleet's keystore service (baditaflorin/go-apikey-service).
Package backoffcoord is the fleet client for go-fleet-backoff-coordinator (ADR-0013).
Package backoffcoord is the fleet client for go-fleet-backoff-coordinator (ADR-0013).
Package bootgate is an opt-in primitive for "do not start heavy boot-time work all at once": it spreads a service's first heavy cycle out in time and backs off while the host is overloaded.
Package bootgate is an opt-in primitive for "do not start heavy boot-time work all at once": it spreads a service's first heavy cycle out in time and backs off while the host is overloaded.
Package botwall recognises the interstitial pages a bot-protection vendor answers a client it distrusts with: a captcha, a "checking your browser" wait, an "Access Denied" page.
Package botwall recognises the interstitial pages a bot-protection vendor answers a client it distrusts with: a captcha, a "checking your browser" wait, an "Access Denied" page.
Package browserheaders generates a coherent set of browser-typical HTTP request headers for outbound calls that need to evade trivial bot detection.
Package browserheaders generates a coherent set of browser-typical HTTP request headers for outbound calls that need to evade trivial bot detection.
Package cache provides a generic, concurrency-safe LRU+TTL cache.
Package cache provides a generic, concurrency-safe LRU+TTL cache.
Package cgroup reads resource counters and limits for the current Linux cgroup.
Package cgroup reads resource counters and limits for the current Linux cgroup.
Package chromeguard keeps a Chromium process tree from taking its container down: it reads per-process memory from /proc, raises the OOM score of the browser's children so the kernel kills a renderer first, kills a renderer that grew past a limit, tells the service when a whole browser grew past another, and derives how many browsers and tabs a container can afford from its cgroup limits.
Package chromeguard keeps a Chromium process tree from taking its container down: it reads per-process memory from /proc, raises the OOM score of the browser's children so the kernel kills a renderer first, kills a renderer that grew past a limit, tells the service when a whole browser grew past another, and derives how many browsers and tabs a container can afford from its cgroup limits.
Package circuitbreaker is a small, in-process circuit-breaker that every safehttp consumer's degraded[]-fallback was hand-rolling.
Package circuitbreaker is a small, in-process circuit-breaker that every safehttp consumer's degraded[]-fallback was hand-rolling.
Package client provides low-level HTTP client abstractions: capability negotiation, URL proxying helpers (JSProxy, FetchProxy), and network property extraction.
Package client provides low-level HTTP client abstractions: capability negotiation, URL proxying helpers (JSProxy, FetchProxy), and network property extraction.
Package clock provides a Clock interface with a real implementation (backed by time.Now) and a controllable mock implementation for deterministic tests.
Package clock provides a Clock interface with a real implementation (backed by time.Now) and a controllable mock implementation for deterministic tests.
Package compat says whether a go-common version is old enough to be missing a security fix that go-common itself shipped.
Package compat says whether a go-common version is old enough to be missing a security fix that go-common itself shipped.
Package config loads service configuration from service.yaml and environment variables.
Package config loads service configuration from service.yaml and environment variables.
Package credentiallease is a task-bound client for a credential broker.
Package credentiallease is a task-bound client for a credential broker.
broker
Package broker provides the fail-closed HTTP core for credentiallease v1.
Package broker provides the fail-closed HTTP core for credentiallease v1.
Package credfile reads a credential (an API key) from a file and keeps it current: a renewed key that is atomically written over the file is picked up without a restart, a callee's 401 triggers one immediate re-read, and a file that briefly goes missing leaves the last good value in use.
Package credfile reads a credential (an API key) from a file and keeps it current: a renewed key that is atomically written over the file is picked up without a restart, a callee's 401 triggers one immediate re-read, and a file that briefly goes missing leaves the last good value in use.
Package dataformat provides bidirectional conversion primitives between the structured data formats commonly seen across the fleet: JSON, CSV, XML, YAML and TOML.
Package dataformat provides bidirectional conversion primitives between the structured data formats commonly seen across the fleet: JSON, CSV, XML, YAML and TOML.
Package dbx is the common, context-aware database entry point for Go Common.
Package dbx is the common, context-aware database entry point for Go Common.
Package degraded is the canonical "primitive X is not working right now" signal that every fleet service appends to a per-request slice and surfaces in its response envelope.
Package degraded is the canonical "primitive X is not working right now" signal that every fleet service appends to a per-request slice and surfaces in its response envelope.
Package depcheck is the fleet's dependency-health registry.
Package depcheck is the fleet's dependency-health registry.
Package deploymentauthorization defines the signed deployment-decision contract shared by the authority and fleet runner.
Package deploymentauthorization defines the signed deployment-decision contract shared by the authority and fleet runner.
Package deploymentintent defines and validates the versioned deployment intent exchanged by fleet deployment control-plane components.
Package deploymentintent defines and validates the versioned deployment intent exchanged by fleet deployment control-plane components.
Package deploymentlease is the shared fail-closed client for the Fleet Deployment Authority's mTLS authorization and target-lease API.
Package deploymentlease is the shared fail-closed client for the Fleet Deployment Authority's mTLS authorization and target-lease API.
Package egress decides whether an outbound request goes through the environment's egress proxy (HTTP_PROXY / HTTPS_PROXY / NO_PROXY).
Package egress decides whether an outbound request goes through the environment's egress proxy (HTTP_PROXY / HTTPS_PROXY / NO_PROXY).
Package egressproxy is a credential-injecting forward proxy that listens on loopback only, so a browser that cannot authenticate to an upstream proxy can still be forced through one.
Package egressproxy is a credential-injecting forward proxy that listens on loopback only, so a browser that cannot authenticate to an upstream proxy can still be forced through one.
Package env provides typed, zero-dependency helpers for reading environment variables with defaults, required-or-fatal semantics, and common Go types (bool, int, duration, slice).
Package env provides typed, zero-dependency helpers for reading environment variables with defaults, required-or-fatal semantics, and common Go types (bool, int, duration, slice).
Package errors defines a typed Error value that carries an HTTP status code, a stable machine-readable error code, a human message, and an optional cause.
Package errors defines a typed Error value that carries an HTTP status code, a stable machine-readable error code, a human message, and an optional cause.
Package fleetfetch is the canonical caller-side client for go-infrastructure-fetch-cache.0exec.com — the fleet-wide HTTP fetch cache.
Package fleetfetch is the canonical caller-side client for go-infrastructure-fetch-cache.0exec.com — the fleet-wide HTTP fetch cache.
Package graph instruments fleet-wide service-to-service calls and emits them to go-fleet-graph.
Package graph instruments fleet-wide service-to-service calls and emits them to go-fleet-graph.
Package header defines canonical HTTP header name constants used across the fleet.
Package header defines canonical HTTP header name constants used across the fleet.
internal
privatehost
Package privatehost answers one question for the proxy-aware transports: can this hostname only mean something inside our own network?
Package privatehost answers one question for the proxy-aware transports: can this hostname only mean something inside our own network?
strictjson
Package strictjson decodes one JSON value while rejecting duplicate object keys, unknown struct fields, and trailing values.
Package strictjson decodes one JSON value while rejecting duplicate object keys, unknown struct fields, and trailing values.
Package jsbundle recovers JavaScript source maps from minified bundles.
Package jsbundle recovers JavaScript source maps from minified bundles.
Package ledger is the canonical client for the fleet's token ledger (baditaflorin/go-fleet-token-ledger, ADR-0033).
Package ledger is the canonical client for the fleet's token ledger (baditaflorin/go-fleet-token-ledger, ADR-0033).
Package loadshed provides a non-blocking concurrency gate ("load shedder") for bounding the number of in-flight calls a service makes to a slow, saturatable shared upstream.
Package loadshed provides a non-blocking concurrency gate ("load shedder") for bounding the number of in-flight calls a service makes to a slow, saturatable shared upstream.
Package logx is the fleet's structured logger: slog JSON on stdout, with the service, version and node on every line, the trace id when the call is inside a traced request, and credentials redacted before they are written.
Package logx is the fleet's structured logger: slog JSON on stdout, with the service, version and node on every line, the trace id when the call is inside a traced request, and credentials redacted before they are written.
Package meshclient is the HTTP client for calls to sibling fleet services on the private mesh: a base URL, a timeout, a bounded and strictly decoded JSON body, and one explicit answer to the question every such call has to settle: if the sibling is down, does the caller go on without it, or stop?
Package meshclient is the HTTP client for calls to sibling fleet services on the private mesh: a base URL, a timeout, a bounded and strictly decoded JSON body, and one explicit answer to the question every such call has to settle: if the sibling is down, does the caller go on without it, or stop?
Package meshresult is the fleet-wide canonical classification of an enricher's result, plus the HTTP-status mapping its consumer (domainscope) keys on.
Package meshresult is the fleet-wide canonical classification of an enricher's result, plus the HTTP-status mapping its consumer (domainscope) keys on.
Package metrics provides a lightweight, in-process request statistics collector for JSON-served snapshots at /metrics/json.
Package metrics provides a lightweight, in-process request statistics collector for JSON-served snapshots at /metrics/json.
Package middleware provides composable HTTP middleware for fleet services.
Package middleware provides composable HTTP middleware for fleet services.
Package nullify is the canonical "I checked and found nothing" helper for enrichers writing a verdict/classification column to Postgres.
Package nullify is the canonical "I checked and found nothing" helper for enrichers writing a verdict/classification column to Postgres.
Package obs provides fleet-canonical runtime observability: a localhost-only debug server exposing net/http/pprof plus a /metrics mirror, and a helper to (idempotently) register the Go runtime + process Prometheus collectors.
Package obs provides fleet-canonical runtime observability: a localhost-only debug server exposing net/http/pprof plus a /metrics mirror, and a helper to (idempotently) register the Go runtime + process Prometheus collectors.
Package openapi provides types and helpers for building OpenAPI 3.0.3 specification documents that fleet services expose at /openapi.json.
Package openapi provides types and helpers for building OpenAPI 3.0.3 specification documents that fleet services expose at /openapi.json.
Package pagination provides canonical types and helpers for cursor-based and offset-based paginated API responses.
Package pagination provides canonical types and helpers for cursor-based and offset-based paginated API responses.
Package pentest provides security-testing helpers: a bounded-concurrency worker pool for concurrent payload delivery and a result aggregator.
Package pentest provides security-testing helpers: a bounded-concurrency worker pool for concurrent payload delivery and a result aggregator.
Package policyeval is a pure-Go rule engine for in-process policy evaluation.
Package policyeval is a pure-Go rule engine for in-process policy evaluation.
Package profiling provides opt-in continuous Go profiling through Grafana Pyroscope.
Package profiling provides opt-in continuous Go profiling through Grafana Pyroscope.
Package promx provides fleet-wide Prometheus collectors and a single-call AutoWire function that installs all observers.
Package promx provides fleet-wide Prometheus collectors and a single-call AutoWire function that installs all observers.
Package proxysupplier resolves the upstream egress-proxy URL for outbound HTTP requests.
Package proxysupplier resolves the upstream egress-proxy URL for outbound HTTP requests.
Package qrterm turns a short piece of content — a URL, an id, a token — into a QR code an operator can scan straight off a terminal, or an image/png a browser/client can render.
Package qrterm turns a short piece of content — a URL, an id, a token — into a QR code an operator can scan straight off a terminal, or an image/png a browser/client can render.
Package ratecoord provides a distributed rate-limit coordination client.
Package ratecoord provides a distributed rate-limit coordination client.
Package reqstats emits per-request resource stats on every HTTP response: a W3C Server-Timing header (human/devtools) and an X-Request-Stats JSON header (machine/cost-engine).
Package reqstats emits per-request resource stats on every HTTP response: a W3C Server-Timing header (human/devtools) and an X-Request-Stats JSON header (machine/cost-engine).
Package resilience composes the fleet's outbound-call protections into one policy: a load-shed gate, a circuit breaker, and retries limited by a budget.
Package resilience composes the fleet's outbound-call protections into one policy: a load-shed gate, a circuit breaker, and retries limited by a budget.
Package response provides the canonical fleet HTTP response envelope.
Package response provides the canonical fleet HTTP response envelope.
Package retry provides context-aware retry logic with configurable backoff strategies.
Package retry provides context-aware retry logic with configurable backoff strategies.
Package runtimetune applies conservative, container-aware Go runtime memory/GC tuning at process start.
Package runtimetune applies conservative, container-aware Go runtime memory/GC tuning at process start.
Package safehttp is the HTTP client for the PUBLIC internet: an *http.Client that refuses to connect to internal addresses (SSRF), plus the URL and IP checks it is built from.
Package safehttp is the HTTP client for the PUBLIC internet: an *http.Client that refuses to connect to internal addresses (SSRF), plus the URL and IP checks it is built from.
scripts
compatcheck command
Command compatcheck reports whether a service's go.mod pins a go-common version that is missing a security fix go-common shipped.
Command compatcheck reports whether a service's go.mod pins a go-common version that is missing a security fix go-common shipped.
envdoc command
Command envdoc generates docs/ENV.md, the list of environment variables that go-common packages declare in the env registry.
Command envdoc generates docs/ENV.md, the list of environment variables that go-common packages declare in the env registry.
linkcheck/service command
Command service is the reference binary of scripts/linkcheck.sh: the smallest fleet service, which loads its config, builds the default server stack with server.New and serves it.
Command service is the reference binary of scripts/linkcheck.sh: the smallest fleet service, which loads its config, builds the default server stack with server.New and serves it.
pkgindex command
Command pkgindex generates docs/PACKAGES.md, the index of every importable go-common package, from the packages' own doc comments.
Command pkgindex generates docs/PACKAGES.md, the index of every importable go-common package, from the packages' own doc comments.
whatchanged command
Command whatchanged prints the behaviour changes between two go-common releases and maintains the feed they are read from.
Command whatchanged prints the behaviour changes between two go-common releases and maintains the feed they are read from.
Package secrets is the canonical client for go-fleet-secrets, the fleet vault.
Package secrets is the canonical client for go-fleet-secrets, the fleet vault.
Package selftest gives every fleet service ONE canonical way to declare and serve a /selftest endpoint.
Package selftest gives every fleet service ONE canonical way to declare and serve a /selftest endpoint.
Package server provides the canonical fleet HTTP server bootstrap.
Package server provides the canonical fleet HTTP server bootstrap.
Package shutdown provides a single-call graceful shutdown helper for net/http servers.
Package shutdown provides a single-call graceful shutdown helper for net/http servers.
Package spiffe adapts the SPIFFE Workload API to credentiallease identities.
Package spiffe adapts the SPIFFE Workload API to credentiallease identities.
Package spiffeauth authenticates incoming requests by SPIFFE identity (an X.509-SVID over mTLS or an audience-scoped JWT-SVID) next to the API key, in dual mode: a request without a SPIFFE identity is handled exactly as before.
Package spiffeauth authenticates incoming requests by SPIFFE identity (an X.509-SVID over mTLS or an audience-scoped JWT-SVID) next to the API key, in dual mode: a request without a SPIFFE identity is handled exactly as before.
Package telemetry installs W3C trace propagation, creates privacy-conscious inbound/outbound HTTP spans, and exports them with OTLP/HTTP when configured.
Package telemetry installs W3C trace propagation, creates privacy-conscious inbound/outbound HTTP spans, and exports them with OTLP/HTTP when configured.
testhelpers
fakeexec
Package fakeexec provides an in-memory fake for the command-runner seam used across the fleet to shell out to git / go / docker:
Package fakeexec provides an in-memory fake for the command-runner seam used across the fleet to shell out to git / go / docker:
fakegraph
Package fakegraph captures graph.Event values for use in tests.
Package fakegraph captures graph.Event values for use in tests.
fakekey
Package fakekey provides an in-memory implementation of the apikey.Verifier interface for use in tests.
Package fakekey provides an in-memory implementation of the apikey.Verifier interface for use in tests.
httpmock
Package httpmock provides canonical httptest.Server factories for common fleet upstream patterns.
Package httpmock provides canonical httptest.Server factories for common fleet upstream patterns.
leakcheck
Package leakcheck fails a test that leaves goroutines running.
Package leakcheck fails a test that leaves goroutines running.
promxtest
Package promxtest tests that a Prometheus collector cannot be made to create an unbounded number of series: it drives hostile label values through the collector and counts what the registry would hand Prometheus.
Package promxtest tests that a Prometheus collector cannot be made to create an unbounded number of series: it drives hostile label values through the collector and counts what the registry would hand Prometheus.
ssrfcorpus
Package ssrfcorpus is one shared table of server-side-request-forgery probe targets, for testing any code that decides whether a host may be contacted: safehttp's guard, egressproxy's guard, a fetcher's default client.
Package ssrfcorpus is one shared table of server-side-request-forgery probe targets, for testing any code that decides whether a host may be contacted: safehttp's guard, egressproxy's guard, a fetcher's default client.
testclock
Package testclock re-exports clock.NewMock and clock.Mock for use in tests without importing the full clock package.
Package testclock re-exports clock.NewMock and clock.Mock for use in tests without importing the full clock package.
Package ua builds the fleet User-Agent header value.
Package ua builds the fleet User-Agent header value.
Package validate provides struct-tag-driven JSON request decoding and validation.
Package validate provides struct-tag-driven JSON request decoding and validation.
Package version exposes build identity variables that are injected at link time via -ldflags.
Package version exposes build identity variables that are injected at link time via -ldflags.
Package wordbound is the canonical fix for a Go regexp footgun that has independently bitten at least two fleet services: `\b` (word boundary) is ASCII-only — per the regexp/syntax docs, a "word" character for `\b` purposes is exactly [0-9A-Za-z_].
Package wordbound is the canonical fix for a Go regexp footgun that has independently bitten at least two fleet services: `\b` (word boundary) is ASCII-only — per the regexp/syntax docs, a "word" character for `\b` purposes is exactly [0-9A-Za-z_].
Package workpool provides a bounded-concurrency worker pool backed by a semaphore and a WaitGroup.
Package workpool provides a bounded-concurrency worker pool backed by a semaphore and a WaitGroup.

Jump to

Keyboard shortcuts

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