A small, self-contained GitHub Actions cache server: one static binary that serves both the legacy artifactcache v1 REST API (what Forgejo act_runner speaks) and the v2 Twirp CacheService API (what the GitHub Actions toolkit and docker buildx --cache-to type=gha speak) over just two ports: one serves the runner-facing endpoints, the other serves the clustering needs (see Clustering).
- One or more named storage instances hold blobs: local
fsroots, OS-mounted SMB/NFS/WebDAV, or native S3, Azure Blob, WebDAV, FTP, SFTP and copyparty backends. Namespaces route to instances; metadata and usage accounting live in one SQLite control database per server - schema-versioned, with verified migrations and a refuse-newer-than-binary check on upgrade. - Auth comes from the CREDENTIAL, not the request: Forgejo HMAC headers, bearer tokens, optional OIDC bearer JWTs and forge runtime tokens. Opt in to multi-tenancy and one cachette serves many forges, each tenant isolated in its own storage namespace with its own quota.
- Optional peer-to-peer clustering discovers nodes, tracks capacity, and places a cache write on the least-loaded healthy owner. The peer wire carries the tenant namespace and refuses a mixed protocol version.
Dogfooded. cachette serves cachette: this project's own CI uses a live deployment as the
docker buildxlayer cache and theactions/cachebackend for every build (see CI & releases).
- Dual protocol on the cache port. v1
/_apis/artifactcache/*and v2/twirp/github.actions.results.api.v1.CacheService/*(plus the v2 Azure block-blob upload emulation) are served by the same binary. - Chunked, resumable uploads. v1
PATCHchunks are staged and committed; abandoned reservations are reaped on a timer. - Capacity model with eviction.
lru,oldest, ornone, driven by amin_freefree-space floor that accepts a fraction, a percent, or a byte size. - Signed capability URLs. Downloads are authorized by a short-lived
?id&exp&macHMAC token; there is no anonymous read path. - Cluster placement. Seed peers by address and pin their certificate fingerprints; the entry node streams a v1 upload to the least-loaded healthy owner over pinned mTLS (the blob bytes never touch the entry node).
- Self-signed node identity. First boot mints an Ed25519 keypair and certificate; the fingerprint is stable across restarts and storage wipes.
- Content-defined chunk dedup (opt-in).
[storage.cdc]splits uploads with a FastCDC-style Gear splitter (algo pinnedgear-fastcdc-v1, default 128 KiB average chunk) so overlapping cache entries share chunk storage. Off by default and byte-identical to the v1.0 layout when off; a background backfill walker converges existing whole-blob entries when you flip it on. - OIDC bearer auth.
[auth.oidc]verifies RS256 bearer JWTs against your IdP's JWKS: kid routing, periodic prefetch + lazy singleflight on unknown kids, per-issuer HTTPS, structural rejections fail closed. Each issuer is its own block ([auth.oidc."<issuer>"]) with its own audiences, claim pins, trust roots and clock skew - one deployment can trust many IdPs. - Multi-tenant namespaces (opt-in). An accepted OIDC or forge-runtime token's tenant selects a storage namespace; the same key in two namespaces is two isolated entries. Admin mappings in
[storage.namespaces]can fold several identities into one shared namespace. Capability URLs MAC-bind the namespace, so a URL minted for one tenant cannot be replayed into another. Single-tenant deployments are byte-identical: every credential resolves to the legacy namespace until a tenant-yielding plane is enabled. - Per-namespace quotas.
[storage.quotas]limits each namespace independently, with exact or tenant-side wildcard rules and a requireddefault. An over-quota namespace is evicted first (worst excess first, LRU within it), before the globalmin_freefloor reclaims anything. - Forge runtime tokens.
[auth.runtime."<forge>"]verifies HS256 tokens signed by a forge's general token secret (a file path, read at boot), with an optional scope allow-list and claim pins. Runtime tokens are tried before OIDC; a tenant-yielding plane requiresauth.mode = "bearer". - Namespace-aware cluster wire. Every key-bearing peer request carries the resolved namespace and
x-cachette-peer-protocol: 3; a missing or different version is refused with426 Upgrade Requiredbefore hello/heartbeat can refresh health. Multi-tenant clusters are supported; a mixed cluster drains to "no healthy peer" rather than merging tenants' rows. - Multiple storage instances.
[[storage.instances]]declares named roots;[storage.routes]maps namespaces by exact match, longest glob,*and thendefault. Routes and[[quota]]rules reload on SIGHUP; the instance set is boot-only. One server owns one control database; instances are isolated by namespace and accounting keys. - Backend capabilities.
StorageBackend::capabilities()drives validation instead of switching ontype. CDC stays onfs/mount instances; remote whole-blob stores use a sparse local read-through cache. S3 and Azure sign requests in-process, copyparty speaks native up2k, and SFTP can pin its host key withknown_hosts_file. HTTPS endpoints require an explicitca_pem. - Per-forge auth.
[auth.forge."<label>"]carries HMAC, runtime-token and OIDC settings together, soauth.mode = "merge"stays valid next to the tenant-yielding planes. Legacy auth tables keep working with a boot-time deprecation warning. - Cluster quota consensus. Quota rules and per-instance usage ride on heartbeats; local rules win, otherwise a plurality vote per target supplies the fallback (at least two agreeing peers). An instance-scoped rule with consensus becomes a soft cluster budget: summed peer usage, with a freshness window and growth margin, clamps the window a tenant sees and can refuse owner-side reserves. Local namespace quotas stay authoritative; gossip lag can still allow a small overshoot.
- Offline migration.
doctor --migrate-configplans or writes a v1.3 config anddoctor --migratemoves state with verified BLAKE3 snapshots.state restore/retag/delete-sourceare separate explicit commands with typed confirmations. A legacy config still boots unchanged. - Rich cluster status.
cachette cluster statusrenders duf-style tables for peers and per-instance usage with themes (--theme), multi-column sort (--sort) and per-instance dedup figures.
-
Build (or download) the
cachettebinary. The only runtime requirement is the binary itself; the filesystem storage backend and SQLite index are built in. -
Write a config file. At minimum, set a storage path and an auth secret of at least 16 characters:
[server] listen = "0.0.0.0:8080" # Set this to your public URL when a proxy terminates TLS for you, so the # archive/capability URLs handed to clients are absolute and correct: external_url = "https://cache.example.com" [storage.fs] path = "/var/lib/cachette" [auth] mode = "merge" secret = "change-me-to-16-plus-chars"
-
Start it:
./cachette --config /etc/cachette/cachette.toml
On the first boot the server mints a node identity under the storage path (or
cluster.cert_path), then prints a readiness line:cachette listening on http://0.0.0.0:8080With
[cluster] enabled, the boot log adds a second readiness line for the peer port -cachette cluster listening on https://0.0.0.0:8081- which peers dial; runners never see it. -
Check liveness. The main listener is plain HTTP unless a
[server] tls_cert/tls_keypair is configured:curl http://127.0.0.1:8080/health # {"version":"1.3.0","node_id":"<64-hex fingerprint>"}GET /metricson the same listener returns the Prometheus text-format counters (requests_total{route,code},bytes_in,bytes_out,evictions_total,reservations_active,storage_used_bytes):curl http://127.0.0.1:8080/metrics
If TLS is enabled on the listener, probe it with
curl -k https://...(supply a CA-trusted certificate throughserver.tls_cert/server.tls_keyfor real clients); see docs/tls.md. -
Point your runner at it. See docs/forgejo.md for Forgejo
act_runner, docs/clients.md for the GitHub toolkit anddocker buildx --cache-to type=gha, and compose.yaml for a container sample.
Configuration is a single TOML file. Every key is denied if unknown: a typo or a key from a newer release is a hard startup error, not a silent default.
When --config is not passed, cachette looks for cachette.toml in a platform-specific directory. An explicit --config <path> always overrides the default (and a missing explicit path is an error rather than a silent fallback).
| Platform | Directory | File |
|---|---|---|
| Linux / BSD / macOS | /etc/cachette |
/etc/cachette/cachette.toml |
| Windows | %APPDATA%\cachette |
%APPDATA%\cachette\cachette.toml |
| Docker image | /config |
/config/cachette.toml |
If no default file is present, cachette starts on the built-in defaults (and still refuses to serve until auth.secret is set). A ready-to-edit file with every key and its default is cachette.example.toml.
Compact view; docs/configuration.md has the full reference, valid-value notes, and examples.
| Section | Key | Value | Default |
|---|---|---|---|
server |
listen |
host:port (IPv6 as [::1]:8080) |
0.0.0.0:8080 |
server |
data_path |
DB/identity directory, or a .db file |
config file's parent |
server |
external_url |
absolute URL advertised to clients | derived from listen as http://<host>:<port> (wildcard host becomes loopback) |
server |
max_size, eviction, key_case |
capacity ceiling, lru/oldest/none, lower/preserve |
0, lru, preserve |
server |
reservation_ttl_seconds, max_chunk_bytes, drain_grace_seconds |
seconds / bytes / seconds | 3600, 67108864, 30 |
server |
tls_cert, tls_key |
PEM paths, set together | unset (listener is plain HTTP) |
storage.fs |
path, min_free |
blob root; fraction, percent or bytesize | /var/lib/cachette, 0.2 |
storage.cdc |
enabled, avg_chunk_bytes, backfill, backfill_delay_ms |
CDC on/off, target size, convergence, pace | false, 131072, true, 100 |
storage.routes |
namespace pattern -> instance | exact, longest glob, *, then default |
{} |
storage.instances |
name, type, path (plus backend fields) |
repeated instance table | one default fs instance |
quota |
scope, target, limit |
repeated rule: namespace/instance, glob, bytesize |
unset |
auth |
mode |
hmac, bearer, merge |
merge |
auth |
secret, secret_file |
16+ character HMAC key, or file path; exclusive | unset |
auth |
tokens |
list of static bearer tokens | [] |
auth |
hmac_max_age_seconds, signed_url_ttl_seconds |
seconds (0 disables staleness) |
600, 900 |
auth |
jwt_secret, jwt_secret_file, jwt_ttl_seconds |
Twirp HS256 key (or file; exclusive) and TTL | falls back to auth.secret, 300 |
auth.forge."<label>" |
hmac_secret/hmac_secret_file, runtime_secret, oidc_* |
all planes for one forge in one block | unset |
cluster |
enabled, node_id, listen, advertise_addr |
standalone flag, label, mTLS peer listener, dial address | false, unset, 0.0.0.0:8081, cluster.listen |
cluster |
mdns, seeds, seed_fingerprints, tiebreak |
discovery, pins, placement tie-break | true, [], {}, random |
cluster |
cert_path, heartbeat_interval_seconds, peer_timeout_seconds |
identity dir, cadence, staleness | <storage.fs.path>/identity, 5, 15 |
log |
level, format, file |
info, text, optional log path |
info, text, unset |
Every key can be set or overridden by an environment variable; environment values win over the file. The convention is CACHETTE__SECTION__KEY (double underscore between segments), and names are case-insensitive:
export CACHETTE__SERVER__LISTEN="0.0.0.0:8080"
export CACHETTE__AUTH__MODE="merge"
export CACHETTE__AUTH__SECRET="change-me-to-16-plus-chars"
./cachette --print-config- Scalars are written as text (
CACHETTE__CACHE__MAX_SIZE="1024"). Booleans aretrue/false; unsigned integers must parse as an unsigned integer. - Lists are comma-separated, with surrounding spaces trimmed and empty items dropped:
CACHETTE__AUTH__TOKENS="token-one, token-two"andCACHETTE__CLUSTER__SEEDS="cache-a:8080,cache-b:8080". - Maps are a JSON object of string values:
CACHETTE__CLUSTER__SEED_FINGERPRINTS='{"cache-a":"AA11","cache-b":"BB22"}'. - Bare keys without a section prefix-match a unique field name, e.g.
CACHETTE__LISTENandCACHETTE__ENABLED. - A
CACHETTE__*variable that maps to no known key is a hard error that names the offending variable; non-CACHETTEvariables are ignored.
cachette serve re-reads the config file on SIGHUP (Unix) without dropping connections. Reloadable: the [auth] policy and forge blocks, the [server] admission knobs (max_size, eviction, key_case, reservation_ttl_seconds, max_chunk_bytes, drain_grace_seconds), [storage.routes], [[quota]] rules, and [log] level. Boot-only: the listener, data directory and instance set, cluster wiring, and the boot-installed OIDC and runtime verifiers (a changed verifier section warns until restart). A malformed file is rejected and the previous config stays in effect. See docs/configuration.md.
cachette [OPTIONS] [COMMAND]
Commands:
identity Print the node fingerprint and identity certificate path
identity rotate Renew the certificate for the same key (fingerprint unchanged)
verify Recompute every published entry's digest and report mismatches
cache list List finalized cache entries (--json for machine output)
cache prune Delete entries not accessed within --older-than <dur>
gc Run the reservation reaper + orphan-blob sweep once, then exit
doctor Check config, storage, SQLite, identity, seeds, and disk
token mint
hmac Print a Forgejo artifactcache HMAC token for the secret
buildx-jwt Print a JWT to use with buildx cache exports
cluster status Print duf-style peer + per-instance tables from a running server
cluster peer list Inspect the live peer table (--watch[=INTERVAL])
cluster peer add/remove/edit
Mutate the live peer table through the admin endpoint
state migrate/restore/retag/delete-source
Offline state migration with typed confirmations
config example Print the generated example config (secrets masked)
Options:
--config <path> Path to a TOML config file (overrides the platform default)
--print-config Print the resolved configuration (secrets masked) and exit
-h, --help Print help
-V, --version Print version
cachette --print-configresolves the file plus environment, then prints the effective configuration as JSON with every secret field masked as***. It succeeds even whenauth.secretis unset.cachette identityprints the node fingerprint and the identity certificate path, minting the identity on first run. Use it to collectcluster.seed_fingerprintsvalues.cachette identity rotatere-issues the identity certificate for the same key with a refreshed validity window, then prints the (unchanged) fingerprint and cert path. Because a pin is the key's SPKI fingerprint — not the certificate, whose validity window peers ignore — every existingcluster.seed_fingerprintsentry stays valid: no re-seed, no cluster coordination. It exits non-zero when the identity is missing; it never mints a new key, which would change the fingerprint.cachette verifyre-hashes every published blob against the digest recorded at publish time (plan task 50) and exits non-zero, naming each corrupt / missing / size-mismatched entry.cachette cache list [--json]andcachette cache prune --older-than 7dinspect and selectively evict entries through the same storage path the server uses.--dry-runreports without deleting.cachette gcruns one TTL-reaper + orphan-blob sweep (the same pass the server runs periodically) and exits.cachette doctoris a read-only health check: config, writable data dir, SQLitePRAGMA integrity_check, identity fingerprint, seed reachability, and disk headroom. It exits non-zero when any check fails.cachette token mint --scope read|write [--repo owner/repo] [--run N]prints theForgejo-Cache-*header values for the configuredauth.secret, so an operator never hand-rolls the HMAC.cachette cluster status [--sort <keys>] [--theme <name>]reads the live member table from a running server over a loopback admin endpoint. It renders duf-style peer and per-instance tables;--sort node,-usedorders one or more columns and--theme auto|none|dark|light|ansipicks the palette (autofollows the terminal andNO_COLOR). Thecluster peerandcluster statussubcommands are the ones that need a live server.verify,cache, andgctake an exclusive lock on the data directory and refuse with a clear message while a server (or another ops command) holds it.doctorandtoken mintnever touch the data directory and do not lock.cachette --versionprintscachette 1.3.0.- A configuration error exits with status
2.
Requests never fall through to anonymous access: a missing or invalid credential is 401 {"error":"authentication required"}.
auth.mode |
v1 /_apis/artifactcache/* |
v2 Twirp CacheService |
Capability URLs (/v2/upload, /v2/artifacts) |
|---|---|---|---|
hmac |
Forgejo-Cache-* HMAC headers only |
static/dynamic bearer tokens; self-minted JWT rejected | signed ?id&exp&mac |
bearer |
Authorization: Bearer <token> — static, dynamic, or a self-minted JWT verified by signature |
static/dynamic bearer token, or a self-minted HS256 JWT | signed ?id&exp&mac |
merge |
HMAC headers or bearer token — static, dynamic, or a self-minted JWT verified by signature | static/dynamic bearer token, or a self-minted HS256 JWT | signed ?id&exp&mac |
Notes:
- A static token is any string in
[auth] tokens; a dynamic token is registered at runtime throughPOST /_internal/register?token=<token>and revoked withPOST /_internal/revoke?token=<token>. A self-minted JWT is whatcachette token mint buildx-jwtprints (HS256 keyed toauth.secret): the bearer gate verifies the signature, so it needs no listing. Those admin routes acceptAuthorization: Bearer <auth.secret>, or are loopback-only while cluster mode is disabled. - OIDC (when
[auth.oidc]is set): a bearer JWT from a configured issuer is accepted after RS256 verification against that issuer's JWKS, with audience overlap required;alg/kid/issuer mismatches fail closed. The v1 gate's chain is static -> dynamic -> self-minted JWT -> runtime token -> OIDC. See docs/oidc.md. - Forge runtime tokens (when
[auth.runtime."<forge>"]is enabled) are HS256 tokens signed by that forge's general token secret. They are verified before OIDC so an HS256 token never reaches the RS256 verifier; a missing tenant claim is a structural rejection, never a default tenant. See docs/shared-cache.md. - Multi-tenant boots require
auth.mode = "bearer"when OIDC or a runtime plane is enabled: HMAC's repo/run fields are client-asserted and cannot express a tenant. Cluster mode is allowed — peers carry the namespace (see docs/shared-cache.md). - The v2 capability URLs (
/v2/upload/{id},/v2/artifacts/{id}) are authorized only by their signed URL, never by a bearer token. - Artifact downloads on v1 are likewise authorized by the signed
archiveLocation; both real clients fetch it with noAuthorizationheader.
A signed URL carries ?id=<id>&exp=<unix>&mac=<hex>, where mac = HMAC-SHA256(auth.secret, "{path}|{id}|{exp}") (with |{ns} appended when a tenant namespace is bound). The resource path is bound into the MAC, so any change to the path, id, or expiry fails with 403 {"error":"invalid or expired url"}. The optional ns parameter is MAC-bound too: stripping or swapping it is a mismatch, while URLs minted before namespaces (no ns) still resolve to the legacy namespace.
- Two TTL knobs govern validity:
v1.signed_url_ttl_seconds(default900) covers both the v1archiveLocationand the v2 capability URLs;v2.jwt_ttl_seconds(default300) covers the Twirp JWT. - Expiry is checked when the request starts; a transfer already in progress runs to completion.
- To revoke outstanding URLs and JWTs, rotate
auth.secret(andv2.jwt_secretif you set one separately). Static bearer tokens in[auth] tokensare unaffected unless you also change the list; a token only signed by the old secret stops verifying with the rotation.
Keep the TTL short and rotate the secret if a URL leaks.
The main listener is plaintext HTTP unless a [server] tls_cert/tls_key pair is configured: no implicit TLS to fight with, and a reverse proxy that terminates the public TLS can forward to plain HTTP. When the pair is set, the listener serves that certificate and clients need it CA-trusted (or a trust override). Peers have their own dedicated listener — [cluster] listen (default 0.0.0.0:8081, bound only when [cluster] enabled), which always terminates TLS with the self-signed node identity certificate; peer trust is a fingerprint pin, not a CA chain. Recipes for nginx, Traefik, ssh -L/-R, WireGuard, and proxy-level rate limiting are in docs/tls.md.
Set [cluster] enabled = true, list peers in seeds, and pin their fingerprints in seed_fingerprints. Nodes discover each other, heartbeat their capacity, and place each v1 cache write on the least-loaded healthy owner, which streams the blob straight to that owner over pinned mTLS. Peers connect on the dedicated [cluster] listen port (default 0.0.0.0:8081), which always serves the self-signed identity certificate — it is never the runner-facing port. cluster.mdns advertises on the local link by default (disable it on a VPS with no usable multicast interface). See docs/cluster.md.
- CONTRIBUTING.md - contribution flow, attribution and workflow validation.
- docs/configuration.md - full configuration reference, environment overrides, validation, and logging.
- docs/forgejo.md - wiring a Forgejo
act_runnercache proxy (v1 + HMAC). - docs/clients.md - the GitHub Actions toolkit,
docker buildx --cache-to type=gha, and GitHub/Gitea bearer auth. - docs/cluster.md - enable clustering, seeds, mDNS, pinning and trust-on-first-use, and placement.
- docs/tls.md - TLS edge recipes (nginx, Traefik, SSH tunnel, WireGuard) and rate limiting at the proxy.
- docs/encrypted-storage.md - encrypting the storage volume with LUKS, ZFS, or BitLocker.
- docs/cdc.md - content-defined chunking: layouts, dedup, backfill migration, GC, and rollout.
- docs/oidc.md - OIDC bearer auth: issuers, audiences, JWKS wiring, and the acceptance chain.
- docs/shared-cache.md - multi-tenant design: credential planes, namespaces, quotas/eviction, admin mappings and the peer wire.
- docs/multi-storage.md - multiple storage instances, routing, quotas, the state directory and migration.
- docs/hmac-tenancy.md - per-forge auth blocks and tenant-yielding HMAC.
- docs/image-stitching.md - assembling multi-arch images with the cache in the loop.
Three Forgejo workflows (.forgejo/workflows/) take a commit from lint to published artifact. push-checks.yml (every branch push) and pr-checks.yml (pull requests to release) run the same gates: rustfmt/clippy, the workspace tests including the v1 + v2 real-client round-trips (node/npm/go must be present or the job fails), the example-config/compose lint, and the multi-node cluster suites - followed by the docker job: a registry-published multi-arch image (linux/amd64 + linux/arm64) on EVERY branch push - release carries the bare-semver tags 1.3.0/1.3/1 + latest + release read from Cargo.toml, other branches carry the regexY-style dev scheme (dev/latest/<version>-dev + truncations, with latest tracking dev between releases), and PR runs publish a flyweight pr-<number> tag. Both legs share a buildkit layer cache served by cachette itself (docker buildx type=gha against the acc.nixthedev.ru cache; an unset CACHETTE_BUILDX_JWT only means cache misses, never failures). The actions/cache@v6 steps (rustup toolchains, the cargo registry/target cache, the xwin SDK) ride a cachette-served cache endpoint as well. release.yml runs on v* tags and on pushes to the release branch: it cross-compiles the eight targets (linux gnu+musl, windows gnu/msvc/gnullvm; amd64+arm64), writes SHA256SUMS, and attaches the binaries + checksums to a release tagged v<version> - the pushed tag on a tag build, or Cargo.toml's package version on a release-branch build. Merging a feat/* pull request into release therefore fires both pipelines at once: the image publish and the release cut.
These are intentionally out of scope for this version; cachette does not advertise or require them:
- Server-side (on-the-fly) compression of blob contents.
- Application-level encryption of blobs (transport is TLS, not the Noise protocol). Encrypt the storage volume instead (see docs/encrypted-storage.md).
- Tenant-scoped payload directory layout and its offline conversion; the hashed
blobs/parts/chunkslayout is unchanged on upgrade. - An enforced cluster-wide storage budget: quota rules are consensus across peers, not a summed admission control.
- Replication of cache entries between nodes: each entry lives on the single node that owns it.
cachette is MIT licensed - the full text is in LICENSE.