Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ data/
.DS_Store
tests/temp/
actions-runner/
benchmark.csv
benchmark.csv
tests/clients/opendal/target/
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ dist/
pnpm-lock.yaml
data/
install/
tests/clients/opendal/target/
83 changes: 83 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Changelog

## 9.8.0-backpressure.4 — unpublished candidate

### Correctness and authorization

- Publish only the exact capability-authenticated generation at complete whole
PUT or validated Azure Put Block List. Preserve canonical opaque block IDs,
submitted order, repeated references and omitted staged blocks. New immutable
physical revisions prevent concurrent or late writes from replacing selected
bytes. Body framing, actual sizes and optional Content-MD5 are checked.
- Key-only Twirp Finalize is a read-only repository/ref-scoped acknowledgment of
an immutable completion receipt, never a selector of pending successor bytes.
Completed-key replacement remains supported; generation immutability does not
mean first-writer-wins keys. Receipt retries cannot alter the published payload.
- With token verification enabled, store only the verified creator JWT expiration
on new reservations. Recheck it under the publication transaction after body
and storage I/O and before committing visibility. No bearer is persisted. The
supported clients retain their runtime bearer across Create and Finalize:
[Actions cache](https://github.com/actions/toolkit/tree/main/packages/cache),
[BuildKit 0.34.2](https://github.com/moby/buildkit/blob/v0.34.2/vendor/github.com/tonistiigi/go-actions-cache/cache_v2.go)
and [OpenDAL 0.55](https://github.com/apache/opendal/blob/v0.55.0/core/src/services/ghac/writer.rs).
This bounds capability publication; it does not claim live-upgrade equivalence
for historical unknown-expiry clients. Validation-disabled development mode has
no verified deadline and remains unsuitable for production.
- Give each unfinished write attempt a separately renewable 60-second lease,
renewed every ten seconds under the generation lock. Retransmission/completion
and idle cleanup settle only expired attempts as failed, never infer success
from objects or counters. A resumed expired owner cannot renew or settle its
fenced revision. Other workers' live attempts continue to fence publication
and cleanup. Payload streaming does not require buffering a whole cache.
- Requested-key metadata retirement applies only to unambiguous NULL-capability
reservations whose creation and last progress are over seven days old, with
settled attempts and no completed entry or shared location. Modern reservations
are not reclaimed here. Seven days exceeds the documented five-day self-hosted
job limit plus two days of margin, not a JWT-expiry assertion. Global cleanup
configuration, V1 passthrough, secrets and issuer settings are unchanged.

### Forward-only migration and explicit compatibility gate

`$9_authenticated_upload_completion` adds immutable attempt metadata, completion
receipts, ordered Part names and nullable publication deadlines. Existing completed
entries retain their numeric layout and remain readable. No historical deadline
or opaque block identity is manufactured from row age, counters or object names.

**A transparent rolling upgrade is not supported or approved.** Before any rollout,
a Security OWNER and service owner must approve a writer-fenced client drain or
maintenance/restart boundary for all pre-upgrade active reservations. In particular:

- Existing capability-bearing reservations have unknown verified expiry. With
verification enabled, their whole PUT and block-list publication fail closed
rather than gaining indefinite authority. Fresh key-only Finalize cannot publish
their raw or pending parts, and these reservations are not silently reclaimed.
- Pre-upgrade multipart blocks were stored under numeric names without an exact
opaque-ID/revision manifest. A cross-upgrade block list cannot safely commit
those old staged bytes. Clients must complete before the writer transition or
restart under the separately approved maintenance plan. Automatic re-reservation
of modern rows is deliberately not provided.
- Previously completed entries without receipts remain restorable; a delayed
Finalize cannot manufacture a receipt. New-generation Finalize remains read-only.

No compatible immutable-seal/fresh-JWT transition for all historical requests is
claimed. This drain/availability contract requires explicit owner approval; the
candidate remains draft and is not deployment-ready. This is not permission to
expand capability lifetime, disable validation, clear live rows or repair a cache.

The migration is **forward-only**: older binaries cannot read ordered immutable
Parts and reject the new migration ledger. Do not downgrade the image or drop new
metadata. An approved rollout requires a recoverable pre-migration database backup,
preserved payload storage and one fenced writer. Recovery is a separately reviewed
forward repair or explicitly approved pre-migration database/storage restoration;
restoring an older database can orphan newer payloads. No backup or migration is
performed by preparing this change.

### Qualification and release gates

Require the real backend CI matrix, supported-client cold-write/warm-read byte
parity, expiry-during-write and crash/late-writer regressions, current-head model
review and Security OWNER/service-owner approval. Actual Claude review remains
unexecuted under the explicit authentication HOLD; other independent reviews do
not replace it. No tag/image publication, merge, runtime operation, deployment or
release qualification is authorized. Recheck immutable version availability before
any separately approved patch-tag/OCI-archive publication.
5 changes: 4 additions & 1 deletion CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ The ordering value for Capacity-based Eviction: a cache payload's most recent Ca
_Avoid_: Cache age

**Upload**:
Cache data that is being received but has not yet become a Cache Entry.
Cache data that is being received but has not yet become a Cache Entry. An
authenticated whole-PUT or explicit block-list completion publishes its exact
immutable generation before its verified publication deadline; a key-only
Finalize only acknowledges completed data.

**Storage Location**:
The stored data belonging to a Cache Entry.
Expand Down
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ They require token validation: the server refuses to start with `SKIP_TOKEN_VALI
| `ACTIONS_TOKEN_AUDIENCE` | unset | Comma-separated `aud` values a token must carry; unset skips the check, an empty list is refused. |
| `UNSAFE_ALLOW_DIRECT_DOWNLOADS_WITHOUT_TOKEN_VALIDATION` | `false` | Allows direct downloads with `SKIP_TOKEN_VALIDATION=true`. Local testing only. |

## Unpublished authenticated-completion candidate

See [the patch changelog](CHANGELOG.md) for `9.8.0-backpressure.4`, its
forward-only migration, authorization-time boundary and required client drain.
This candidate remains Security OWNER/model-review gated, not approved for
tagging, publication or deployment.

## Documentation

👉 <https://gha-cache-server.falcondev.io/getting-started> 👈
50 changes: 50 additions & 0 deletions docs/adr/0013-upload-urls-carry-a-capability.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,53 @@ Twirp calls are authorized by the Actions runtime token (`getCacheScope`), but t
The capability lives in the query because every client we support treats the signed URL as an Azure SAS URL: `@actions/cache` and `go-actions-cache` keep the query and append `comp`/`blockid`, and OpenDAL (sccache) requires a query and re-sends it as the SAS. Only its SHA-256 is stored (`uploads.capabilityHash`), compared in constant time, so neither the database nor its debug query log can reproduce a working URL. Request logs record paths without their query string, and upload errors are logged by the route rather than left to Nitro, whose unhandled-error log includes the request URL. Upload URLs requested with a method other than `PUT` get `405` instead of falling through to the Results Passthrough, which would forward the capability upstream.

We rejected an HMAC over the Upload id: it needs a secret shared by every worker and kept across restarts, which this server has no place for, while a stored random value needs nothing new. Uploads created before the migration have no capability, so their URLs stop accepting Parts; they are short-lived and `cleanup:uploads` removes them once idle.

## Authenticated completion, not key-only publication

The capability must fence the complete payload, not just individual writes.
A whole Put Blob carries the upload ID and capability and declares one complete
HTTP body. A Put Block List carries that same generation and the client's exact
ordered manifest after staging. Publish only successfully persisted immutable
revisions referenced by that authenticated boundary. Opaque IDs are not numeric
indexes; repeated IDs repeat bytes and omitted staged blocks are not appended.
Reject truncated bodies, unavailable references and concurrent unfinished writes.

Twirp Finalize has only key/version/size plus repository/ref authorization, not an
upload generation. It is therefore a read-only acknowledgment of an existing
completion receipt. An old or same-token finalizer cannot delete an empty
successor, publish its first part, or choose arbitrary current staged data.
This uses existing GitHub/BuildKit/OpenDAL transports without a new client nonce.
When token verification is enabled, new generations retain only the verified
creator JWT expiration as `publicationExpiresAt`, never the bearer. Whole PUT
and manifest publication recheck that deadline under the generation transaction,
including after asynchronous storage and immediately before committing visibility.
The same fixed runtime bearer authorizes Create and Finalize in the supported
clients; capability possession must not extend publication beyond its verified
deadline. Receipt retries cannot publish new data after expiry.

Expiry-unknown pre-upgrade generations cannot safely acquire an invented
deadline. They fail closed with verification enabled and require the explicitly
approved drain/maintenance boundary in the changelog. This is not transparent
rolling-upgrade compatibility or security-owner approval. Validation-disabled
development mode still has no trusted JWT deadline; it must not be used in
production.

Completion receipts retain the generation's capability hash and completion
identity under the Storage Location lifecycle. Retries may acknowledge the same
immutable completion; a different payload or manifest cannot rewrite it.
Stage attempts use distinct physical revisions, so a late/retried writer cannot
overwrite a published Part. Key/ref/repository fences and V1 passthrough remain.

Each unfinished revision has its own 60-second renewable attempt lease. Writers
renew every ten seconds under the generation lock. Recovery settles only expired
attempts as failed, never promotes their objects, and never clears another live
worker. A resumed expired writer cannot renew or settle its removed revision;
retransmission uses a new immutable name. This lease fences storage attempts, not
JWT authority or reservation retirement.

Only an explicitly requested, unambiguous NULL-capability reservation idle for
more than seven days may be retired; modern and active reservations do not
expire through this path. It removes metadata only, not payloads or other keys.
This does not change the global cleanup-disable decision. The new ordered-Part
migration is forward-only and requires a separately approved writer/backup/client
drain boundary, as documented in the candidate patch notes.
24 changes: 24 additions & 0 deletions lib/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export const storageLocationSchema = z.object({
partsDeletedAt: z.number().nullable(),
lastDownloadedAt: z.number().nullable(),
sizeBytes: z.number().nullable(),
partNamesJson: z.string().nullable(),
})
export type StorageLocation = z.infer<typeof storageLocationSchema>

Expand Down Expand Up @@ -79,15 +80,38 @@ export const uploadSchema = z.object({
finishedPartUploadCount: z.number(),
folderName: z.string(),
capabilityHash: z.string().nullable(),
publicationExpiresAt: z.number().nullable(),
})
type Upload = z.infer<typeof uploadSchema>

export interface UploadPart {
id: string
uploadId: number
blockId: string | null
revision: number
partName: string
sizeBytes: number | null
digest: string | null
leaseExpiresAt: number
}

export interface UploadReceipt {
uploadId: number
capabilityHash: string
locationId: string
kind: 'whole' | 'blocks'
completionHash: string
sizeBytes: number
}

export interface Database {
cache_entries: CacheEntry
merge_leases: MergeLease
storage_reader_leases: StorageReaderLease
storage_locations: StorageLocation
uploads: Upload
upload_parts: UploadPart
upload_receipts: UploadReceipt
}

const dbLogger = logger.withTag('db')
Expand Down
51 changes: 51 additions & 0 deletions lib/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,5 +259,56 @@ export function migrations(
await db.schema.alterTable('uploads').dropColumn('capabilityHash').execute()
},
},
$9_authenticated_upload_completion: {
async up(db) {
const idType = driver === 'mysql' ? 'varchar(36)' : 'text'
// NULL means historical/unchecked authority, never a guessed JWT expiry.
await db.schema.alterTable('uploads').addColumn('publicationExpiresAt', 'bigint').execute()
await db.schema
.alterTable('storage_locations')
.addColumn('partNamesJson', driver === 'mysql' ? sql`longtext` : 'text')
.execute()
await db.schema
.createTable('upload_parts')
.addColumn('id', idType, (col) => col.primaryKey())
.addColumn('uploadId', 'bigint', (col) =>
col.notNull().references('uploads.id').onDelete('cascade'),
)
.addColumn('blockId', 'varchar(88)')
.addColumn('revision', 'integer', (col) => col.notNull())
.addColumn('partName', 'varchar(36)', (col) => col.notNull())
.addColumn('sizeBytes', 'bigint')
.addColumn('digest', 'varchar(64)')
.addColumn('leaseExpiresAt', 'bigint', (col) => col.notNull())
.execute()
await db.schema
.createIndex('idx_upload_parts_generation')
.on('upload_parts')
.columns(['uploadId', 'blockId', 'revision'])
.execute()
await db.schema
.createTable('upload_receipts')
.addColumn('uploadId', 'bigint', (col) => col.notNull())
.addColumn('capabilityHash', 'varchar(64)', (col) => col.notNull())
.addColumn('locationId', idType, (col) =>
col.notNull().references('storage_locations.id').onDelete('cascade'),
)
.addColumn('kind', 'varchar(8)', (col) => col.notNull())
.addColumn('completionHash', 'varchar(64)', (col) => col.notNull())
.addColumn('sizeBytes', 'bigint', (col) => col.notNull())
.addPrimaryKeyConstraint('pk_upload_receipts_generation', ['uploadId', 'capabilityHash'])
.execute()
await db.schema
.createIndex('idx_upload_receipts_location')
.on('upload_receipts')
.columns(['locationId'])
.execute()
},
async down() {
throw new Error(
'Authenticated upload completion is forward-only: older binaries cannot read ordered immutable Parts. Restore an explicitly approved pre-migration backup; do not drop the completion metadata.',
)
},
},
} satisfies Record<string, Migration>
}
2 changes: 2 additions & 0 deletions lib/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,5 +135,7 @@ export async function getCacheScope(event: H3Event) {
return {
scopes,
repoId,
// Never turn a decoded-but-unverified claim into delegated authority.
publicationExpiresAt: env.SKIP_TOKEN_VALIDATION ? null : decoded.exp! * 1000,
}
}
29 changes: 29 additions & 0 deletions lib/storage-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { StorageAdapter } from './storage'
import pLimit from 'p-limit'
import { env } from './env'
import { logger } from './logger'
import { recoverExpiredUploadParts } from './uploads'

export interface OrphanedStorageSummary {
inspectedFolders: number
Expand Down Expand Up @@ -115,6 +116,34 @@ export async function claimPartsDeletionIfUnread(
return Number(updated.numUpdatedRows) === 1
}

/** Recheck idle-upload selection under the same generation lock as publication. */
export async function deleteUploadIfIdle(
tx: Transaction<Database>,
uploadId: number,
cutoff: number,
) {
let query = tx.selectFrom('uploads').selectAll().where('id', '=', uploadId)
if (env.DB_DRIVER !== 'sqlite') query = query.forUpdate()
const upload = await query.executeTakeFirst()
if (
!upload ||
upload.createdAt >= cutoff ||
(upload.lastPartUploadedAt !== null && upload.lastPartUploadedAt >= cutoff)
)
return
const recovered = await recoverExpiredUploadParts(tx, uploadId)
const pending = await tx
.selectFrom('upload_parts')
.select('id')
.where('uploadId', '=', uploadId)
.where('sizeBytes', 'is', null)
.executeTakeFirst()
if (pending || upload.startedPartUploadCount !== upload.finishedPartUploadCount + recovered)
return
await tx.deleteFrom('uploads').where('id', '=', uploadId).execute()
return upload.folderName
}

export async function reconcileOrphanedStorage({
db,
adapter,
Expand Down
Loading
Loading