diff --git a/.gitignore b/.gitignore index 42a7f357..61ccf7d5 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,5 @@ data/ .DS_Store tests/temp/ actions-runner/ -benchmark.csv \ No newline at end of file +benchmark.csv +tests/clients/opendal/target/ \ No newline at end of file diff --git a/.prettierignore b/.prettierignore index d8990589..a8b09029 100644 --- a/.prettierignore +++ b/.prettierignore @@ -6,3 +6,4 @@ dist/ pnpm-lock.yaml data/ install/ +tests/clients/opendal/target/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..e44a20a0 --- /dev/null +++ b/CHANGELOG.md @@ -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. diff --git a/CONTEXT.md b/CONTEXT.md index 761c24cd..6dc92dcb 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -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. diff --git a/README.md b/README.md index 38da3399..c4362970 100644 --- a/README.md +++ b/README.md @@ -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 👉 👈 diff --git a/docs/adr/0013-upload-urls-carry-a-capability.md b/docs/adr/0013-upload-urls-carry-a-capability.md index d7bebcc4..6585742a 100644 --- a/docs/adr/0013-upload-urls-carry-a-capability.md +++ b/docs/adr/0013-upload-urls-carry-a-capability.md @@ -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. diff --git a/lib/db.ts b/lib/db.ts index e9ab7d6d..54a0541f 100644 --- a/lib/db.ts +++ b/lib/db.ts @@ -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 @@ -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 +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') diff --git a/lib/migrations.ts b/lib/migrations.ts index aa05dbba..f8a0d270 100644 --- a/lib/migrations.ts +++ b/lib/migrations.ts @@ -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 } diff --git a/lib/scope.ts b/lib/scope.ts index 3b611edc..c9ca0880 100644 --- a/lib/scope.ts +++ b/lib/scope.ts @@ -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, } } diff --git a/lib/storage-lifecycle.ts b/lib/storage-lifecycle.ts index 98c49cd1..88ebd4ce 100644 --- a/lib/storage-lifecycle.ts +++ b/lib/storage-lifecycle.ts @@ -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 @@ -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, + 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, diff --git a/lib/storage.ts b/lib/storage.ts index f0c83893..491dafa9 100644 --- a/lib/storage.ts +++ b/lib/storage.ts @@ -4,8 +4,9 @@ import type { Writable } from 'node:stream' import type { Database, StorageLocation } from './db' import type { MergeKind, S3Pool } from './metrics' import type { Env } from './schemas' -import { Buffer } from 'node:buffer' -import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto' +import type { BlockReference, UploadIdentity } from './upload-protocol' +import type { UploadPublication } from './uploads' +import { randomUUID } from 'node:crypto' import { createReadStream, createWriteStream } from 'node:fs' import fs from 'node:fs/promises' import { Agent as HttpAgent } from 'node:http' @@ -35,9 +36,14 @@ import { chunk } from 'remeda' import { match } from 'ts-pattern' import { getDatabase, retryOnLockConflict } from './db' import { env } from './env' -import { generateNumberId } from './helpers' import { logger } from './logger' -import { cacheMergesSkippedTotal, instrumentS3Agent, observeS3Request, trackMerge } from './metrics' +import { + cacheMergesSkippedTotal, + cacheUploadsTotal, + instrumentS3Agent, + observeS3Request, + trackMerge, +} from './metrics' import { acquireMergeLease, createReaderLease, @@ -49,6 +55,13 @@ import { renewReaderLease, } from './storage-leases' import { deleteStorageLocationIfUnread, noActiveReaderLease } from './storage-lifecycle' +import * as uploads from './uploads' + +function partNames(location: Pick): string[] { + return location.partNamesJson === null + ? Array.from({ length: location.partCount }, (_, index) => String(index)) + : JSON.parse(location.partNamesJson) +} // Bounds the self-heal retry when matching keeps surfacing Dangling Cache // Entries for the same prefix — caps a pathological scan (ADR-0005). @@ -150,16 +163,6 @@ export class Storage { this.db = db } - private async abandonUpload(uploadId: number, folderName: string, reason: Error): Promise { - await this.db.deleteFrom('uploads').where('id', '=', uploadId).execute() - try { - await this.adapter.deleteFolder(folderName) - } catch (err) { - throw new AggregateError([reason, err], reason.message) - } - throw reason - } - private protectDownloadStream(stream: Readable, readerLeaseId: string) { const renewalTimer = setInterval(() => { void renewReaderLease(this.db, readerLeaseId) @@ -186,9 +189,16 @@ export class Storage { } private async ensurePartsExist(location: StorageLocation) { - const partsFolder = `${location.folderName}/parts` - const actualPartCount = await this.adapter.countFilesInFolder(partsFolder) - if (actualPartCount < location.partCount) throw new ObjectNotFoundError(partsFolder) + if (location.partNamesJson === null) { + const count = await this.adapter.countFilesInFolder(`${location.folderName}/parts`) + if (count < location.partCount) throw new ObjectNotFoundError(location.folderName) + } else { + const names = new Set(partNames(location)) + if (names.size === 0) return + const stored = await this.adapter.listFolder(`${location.folderName}/parts`) + for (const part of stored) names.delete(part.name) + if (names.size > 0) throw new ObjectNotFoundError(`${location.folderName}/parts`) + } } private async downloadFromCacheEntryLocation(location: StorageLocation, signal?: AbortSignal) { @@ -230,9 +240,9 @@ export class Storage { private async *streamParts(location: StorageLocation, signal?: AbortSignal) { if (location.partsDeletedAt) throw new Error('No parts to feed for location with deleted parts') - for (let i = 0; i < location.partCount; i++) { + for (const name of partNames(location)) { const partStream = await this.adapter.createDownloadStream( - `${location.folderName}/parts/${i}`, + `${location.folderName}/parts/${name}`, signal, ) @@ -256,14 +266,17 @@ export class Storage { partCount: number mergedAt: number | null partsDeletedAt: number | null + partNamesJson: string | null }) { if (location.mergedAt) return this.adapter.objectExists(`${location.folderName}/merged`) - if (location.partsDeletedAt || location.partCount === 0) return false - // ponytail: single-part HEAD, not a full LIST of parts. External drift wipes - // the whole folder and the server never produces partial Part loss, so - // Part 0's absence is a sufficient proxy. Won't catch surgical deletion of - // an interior Part. See ADR-0005. - return this.adapter.objectExists(`${location.folderName}/parts/0`) + if (location.partsDeletedAt) return false + if (location.partNamesJson !== null) { + const names = partNames(location) + return ( + names.length === 0 || this.adapter.objectExists(`${location.folderName}/parts/${names[0]}`) + ) + } + return location.partCount !== 0 && this.adapter.objectExists(`${location.folderName}/parts/0`) } private async purgeDanglingCacheEntry(cacheEntryId: string, locationId: string) { @@ -399,6 +412,7 @@ export class Storage { private async mergeEagerly(location: StorageLocation, partSizes: number[]) { const compose = this.adapter.composeParts const composable = + partSizes.length > 0 && compose && partSizes.length <= compose.maxParts && partSizes.every( @@ -408,7 +422,7 @@ export class Storage { ) await this.startMerge(location, composable ? 'compose' : 'stream', () => composable - ? compose.run(location.folderName, location.partCount) + ? compose.run(location.folderName, partNames(location)) : this.adapter.uploadStream( `${location.folderName}/merged`, Readable.from(this.streamParts(location)), @@ -416,176 +430,52 @@ export class Storage { ) } + private async finishUpload(result: UploadPublication) { + if (result.location) { + cacheUploadsTotal.inc() + try { + await this.enforceStorageBudget() + } catch (err) { + logger.warn('Capacity-based Eviction failed after upload completion', { error: err }) + } + if (env.EAGER_MERGE) { + try { + await this.mergeEagerly(result.location, result.sizes) + } catch (err) { + logger.warn('Eager Merge failed to start after upload completion', { error: err }) + } + } + } + return result.receipt + } waitForOngoingMerges() { return Promise.all(this.mergeStreamPromises) } - /** - * Whether `capability` is the one issued with the Upload. Upload URLs are not - * covered by the Actions runtime token, so this is their only authorization. - * Unknown Uploads and missing or wrong capabilities are indistinguishable. - */ - async authorizeUpload(uploadId: number, capability: string | undefined) { - const upload = await this.db - .selectFrom('uploads') - .where('id', '=', uploadId) - .select('capabilityHash') - .executeTakeFirst() - if (!upload?.capabilityHash || !capability) return false - - return timingSafeEqual( - Buffer.from(upload.capabilityHash, 'hex'), - createHash('sha256').update(capability).digest(), - ) + authorizeUpload(uploadId: number, capability: string | undefined) { + return uploads.authorizeUpload(this.db, uploadId, capability) } - async uploadPart(uploadId: number, partIndex: number, stream: Readable) { - const upload = await this.db - .selectFrom('uploads') - .where('id', '=', uploadId) - .select(['folderName']) - .executeTakeFirst() - if (!upload) return - - await this.db - .updateTable('uploads') - .set({ - startedPartUploadCount: sql`${sql.ref('startedPartUploadCount')} + 1`, - }) - .where('id', '=', uploadId) - .execute() - - await this.adapter.uploadStream(`${upload.folderName}/parts/${partIndex}`, stream) - - await this.db - .updateTable('uploads') - .set({ - lastPartUploadedAt: Date.now(), - finishedPartUploadCount: sql`${sql.ref('finishedPartUploadCount')} + 1`, - }) - .where('id', '=', uploadId) - .execute() + stageBlock(uploadId: number, capability: string | undefined, blockId: string, stream: Readable) { + return uploads.stageBlock(this.db, this.adapter, uploadId, capability, blockId, stream) } - async completeUpload({ - key, - version, - scope, - repoId, - }: { - key: string - version: string - scope: string - repoId: string - }) { - const upload = await this.db - .selectFrom('uploads') - .where('key', '=', key) - .where('version', '=', version) - .where('scope', '=', scope) - .where('repoId', '=', repoId) - .selectAll() - .executeTakeFirst() - if (!upload) return - - if (upload.finishedPartUploadCount === 0) { - return this.abandonUpload( - upload.id, - upload.folderName, - new Error('No parts have been uploaded'), - ) - } - - if (upload.startedPartUploadCount !== upload.finishedPartUploadCount) { - return this.abandonUpload( - upload.id, - upload.folderName, - new Error( - `Not all parts have been uploaded (only ${upload.finishedPartUploadCount} of ${upload.startedPartUploadCount} parts uploaded)`, - ), - ) - } - - const parts = await this.adapter.listFolder(`${upload.folderName}/parts`) - const partCount = parts.length - if (partCount !== upload.finishedPartUploadCount) { - return this.abandonUpload( - upload.id, - upload.folderName, - new Error( - `Uploaded part count does not match actual part count in storage (expected ${upload.finishedPartUploadCount} but found ${partCount})`, - ), - ) - } - - const partSizes = parts - .toSorted((a, b) => Number(a.name) - Number(b.name)) - .map(({ bytes }) => bytes) - const location: StorageLocation = { - id: randomUUID(), - folderName: upload.folderName, - partCount, - mergedAt: null, - mergeStartedAt: null, - partsDeletedAt: null, - lastDownloadedAt: null, - sizeBytes: parts.reduce((sum, { bytes }) => sum + bytes, 0), - } - - await this.db.transaction().execute(async (tx) => { - await tx.insertInto('storage_locations').values(location).execute() - - const existingCacheEntry = await tx - .selectFrom('cache_entries') - .where('key', '=', key) - .where('version', '=', version) - .where('scope', '=', scope) - .where('repoId', '=', repoId) - .innerJoin('storage_locations', 'storage_locations.id', 'cache_entries.locationId') - .select(['cache_entries.id', 'cache_entries.locationId']) - .executeTakeFirst() - - if (existingCacheEntry) { - await tx - .updateTable('cache_entries') - .set({ - updatedAt: Date.now(), - locationId: location.id, - }) - .where('id', '=', existingCacheEntry.id) - .execute() - } else - await tx - .insertInto('cache_entries') - .values({ - key: upload.key, - version: upload.version, - id: randomUUID(), - updatedAt: Date.now(), - locationId: location.id, - scope, - repoId, - }) - .execute() - - await tx.deleteFrom('uploads').where('id', '=', upload.id).execute() - }) - - try { - await this.enforceStorageBudget() - } catch (err) { - logger.warn('Capacity-based Eviction failed after upload completion', { error: err }) - } + async putBlob(uploadId: number, capability: string | undefined, stream: Readable) { + return this.finishUpload( + await uploads.putBlob(this.db, this.adapter, uploadId, capability, stream), + ) + } - if (env.EAGER_MERGE) { - try { - await this.mergeEagerly(location, partSizes) - } catch (err) { - logger.warn('Eager Merge failed to start after upload completion', { error: err }) - } - } + async commitBlockList( + uploadId: number, + capability: string | undefined, + blocks: BlockReference[], + ) { + return this.finishUpload(await uploads.commitBlockList(this.db, uploadId, capability, blocks)) + } - return upload + acknowledgeUpload(identity: UploadIdentity) { + return uploads.acknowledgeUpload(this.db, identity) } async enforceStorageBudget() { @@ -708,49 +598,8 @@ export class Storage { } } - async createUpload({ - key, - version, - scope, - repoId, - }: { - key: string - version: string - scope: string - repoId: string - }) { - const existingUpload = await this.db - .selectFrom('uploads') - .where('key', '=', key) - .where('version', '=', version) - .where('scope', '=', scope) - .where('repoId', '=', repoId) - .select('id') - .executeTakeFirst() - if (existingUpload) return - - const uploadId = generateNumberId() - // Only the hash is stored, so neither the database nor its query log can - // reproduce a working upload URL. - const capability = randomBytes(32).toString('hex') - await this.db - .insertInto('uploads') - .values({ - id: uploadId, - folderName: uploadId.toString(), - createdAt: Date.now(), - key, - version, - scope, - repoId, - lastPartUploadedAt: null, - finishedPartUploadCount: 0, - startedPartUploadCount: 0, - capabilityHash: createHash('sha256').update(capability).digest('hex'), - }) - .execute() - - return { id: uploadId, capability } + createUpload(identity: UploadIdentity & { publicationExpiresAt?: number | null }) { + return uploads.createUpload(this.db, identity) } async matchCacheEntry({ @@ -813,7 +662,7 @@ export class Storage { const location = await this.db .selectFrom('storage_locations') .where('id', '=', cacheEntry.match.locationId) - .select(['id', 'folderName', 'partCount', 'mergedAt', 'partsDeletedAt']) + .select(['id', 'folderName', 'partCount', 'mergedAt', 'partsDeletedAt', 'partNamesJson']) .executeTakeFirst() if (!location || !(await this.storageHasData(location))) { @@ -896,16 +745,15 @@ export interface StorageAdapter { createDownloadUrl?(objectName: string, expiresAt: number): Promise getFilesystemUsage?(): Promise<{ capacityBytes: number; usedBytes: number }> /** - * Server-side Merge: copies `${folderName}/parts/0..partCount-1` into - * `${folderName}/merged` inside the backend. Only applicable when every Part - * satisfies the limits; the caller checks them before calling `run`. + * Server-side Merge copies the ordered immutable Part names into `merged`. + * Repeated names repeat those bytes, exactly as in the authenticated manifest. */ composeParts?: { /** Every Part but the last must be at least this large. */ minPartBytes: number maxPartBytes: number maxParts: number - run(folderName: string, partCount: number): Promise + run(folderName: string, partNames: string[]): Promise } clear(): Promise } @@ -1030,7 +878,7 @@ export class S3Adapter implements StorageAdapter { minPartBytes: 5 * 1024 * 1024, maxPartBytes: 5 * 1024 ** 3, maxParts: 10_000, - run: async (folderName: string, partCount: number) => { + run: async (folderName: string, partNames: string[]) => { const Bucket = this.bucket const Key = `${this.keyPrefix}/${folderName}/merged` const { UploadId } = await this.clients.writes.send( @@ -1039,14 +887,14 @@ export class S3Adapter implements StorageAdapter { if (!UploadId) throw new Error('S3 did not return an UploadId') try { const Parts = [] - for (let PartNumber = 1; PartNumber <= partCount; PartNumber++) { + for (let PartNumber = 1; PartNumber <= partNames.length; PartNumber++) { const copy = await this.clients.writes.send( new UploadPartCopyCommand({ Bucket, Key, UploadId, PartNumber, - CopySource: `${Bucket}/${this.keyPrefix}/${folderName}/parts/${PartNumber - 1}`, + CopySource: `${Bucket}/${this.keyPrefix}/${folderName}/parts/${partNames[PartNumber - 1]}`, }), ) Parts.push({ PartNumber, ETag: copy.CopyPartResult?.ETag }) @@ -1432,9 +1280,9 @@ class GcsAdapter implements StorageAdapter { minPartBytes: 0, maxPartBytes: 5 * 1024 ** 4, maxParts: Infinity, - run: async (folderName: string, partCount: number) => { - const sources = Array.from({ length: partCount }, (_, index) => - this.bucket.file(`${this.keyPrefix}/${folderName}/parts/${index}`), + run: async (folderName: string, partNames: string[]) => { + const sources = partNames.map((name) => + this.bucket.file(`${this.keyPrefix}/${folderName}/parts/${name}`), ) // Folds batches into a top-level temp object (reclaimed as Orphaned // Storage if we crash) so `merged` only ever appears in one final, @@ -1450,7 +1298,7 @@ class GcsAdapter implements StorageAdapter { this.bucket.file(`${this.keyPrefix}/${folderName}/merged`), ) } finally { - if (partCount > 32) await temp.delete({ ignoreNotFound: true }) + if (partNames.length > 32) await temp.delete({ ignoreNotFound: true }) } }, } diff --git a/lib/twirp.ts b/lib/twirp.ts index d8b025d0..ce97c32b 100644 --- a/lib/twirp.ts +++ b/lib/twirp.ts @@ -72,9 +72,10 @@ export async function readTwirpRequest( export function sendTwirpResponse(event: H3Event, data: object, messageType: protobuf.Type) { if (!isProtobuf(event)) return data - const err = messageType.verify(data) + const message = messageType.fromObject(data) + const err = messageType.verify(message) if (err) throw createError({ statusCode: 500, statusMessage: `Invalid Twirp response: ${err}` }) setResponseHeader(event, 'content-type', PROTOBUF_CONTENT_TYPE) - return Buffer.from(messageType.encode(messageType.fromObject(data)).finish()) + return Buffer.from(messageType.encode(message).finish()) } diff --git a/lib/upload-protocol.ts b/lib/upload-protocol.ts new file mode 100644 index 00000000..90f9ca35 --- /dev/null +++ b/lib/upload-protocol.ts @@ -0,0 +1,138 @@ +import type { IncomingMessage } from 'node:http' +import type { Readable as ReadableType } from 'node:stream' +import { Buffer } from 'node:buffer' +import { createHash } from 'node:crypto' +import { Readable } from 'node:stream' +import { StringDecoder } from 'node:string_decoder' +import { SaxesParser } from 'saxes' + +export interface UploadIdentity { + key: string + version: string + scope: string + repoId: string +} + +export interface BlockReference { + id: string + source: 'Latest' | 'Uncommitted' | 'Committed' +} + +export class UploadProtocolError extends Error { + constructor( + readonly statusCode: number, + message: string, + ) { + super(message) + this.name = 'UploadProtocolError' + } +} + +export function validateBlockId(id: string) { + if (id.length < 4 || id.length > 88) + throw new UploadProtocolError(400, 'Block IDs must encode 1 to 64 opaque bytes') + const bytes = Buffer.from(id, 'base64') + if (bytes.length === 0 || bytes.length > 64 || bytes.toString('base64') !== id) + throw new UploadProtocolError( + 400, + 'Block IDs must be canonical Base64 encoding 1 to 64 opaque bytes', + ) + return bytes.length +} + +/** EOF of an aborted/truncated HTTP body is never an authenticated completion. */ +export function requestBody(request: IncomingMessage) { + const length = request.headers['content-length'] + if (length !== undefined && !/^\d+$/.test(length)) + throw new UploadProtocolError(400, 'Invalid Content-Length') + const expected = length === undefined ? undefined : Number(length) + if (expected !== undefined && !Number.isSafeInteger(expected)) + throw new UploadProtocolError(400, 'Invalid Content-Length') + const md5 = request.headers['content-md5'] + if ( + md5 !== undefined && + (Array.isArray(md5) || + Buffer.from(md5, 'base64').length !== 16 || + Buffer.from(md5, 'base64').toString('base64') !== md5) + ) + throw new UploadProtocolError(400, 'Invalid Content-MD5') + const checksum = md5 === undefined ? undefined : createHash('md5') + return Readable.from( + (async function* () { + let size = 0 + for await (const chunk of request) { + size += chunk.length + checksum?.update(chunk) + yield chunk + } + if (!request.complete || (expected !== undefined && size !== expected)) + throw new UploadProtocolError(400, 'Incomplete upload request body') + if (checksum && checksum.digest('base64') !== md5) + throw new UploadProtocolError(400, 'Content-MD5 does not match') + })(), + ) +} + +function fail() { + throw new UploadProtocolError(400, 'Invalid Azure block-list manifest') +} +/** Azure's ordered block manifest, not counters or a numeric block-ID suffix. */ +export async function parseBlockList(body: ReadableType) { + const blocks: BlockReference[] = [] + const sources = new Map() + const decoder = new StringDecoder('utf8') + const parser = new SaxesParser() + let depth = 0 + let root = false + let source: BlockReference['source'] | undefined + let value = '' + let idLength: number | undefined + let bytes = 0 + parser.on('doctype', fail) + parser.on('error', fail) + parser.on('opentag', (tag) => { + if (Object.keys(tag.attributes).length > 0) fail() + if (depth === 0) { + if (root || tag.name !== 'BlockList') fail() + root = true + } else if (depth === 1 && ['Latest', 'Uncommitted', 'Committed'].includes(tag.name)) { + source = tag.name as BlockReference['source'] + value = '' + } else fail() + depth++ + }) + const text = (chunk: string) => { + if (depth === 2) { + value += chunk + if (value.length > 128) fail() + } else if (chunk.trim()) fail() + } + parser.on('text', text) + parser.on('cdata', text) + parser.on('closetag', () => { + if (depth === 2) { + const id = value.trim() + const length = validateBlockId(id) + if (idLength !== undefined && idLength !== length) fail() + idLength = length + if (!source || (sources.has(id) && sources.get(id) !== source)) fail() + sources.set(id, source!) + blocks.push({ id, source: source! }) + // Azure allows repeated IDs in one source list; each occurrence repeats + // those exact bytes at that position. It caps the committed list at 50k. + if (blocks.length > 50_000) fail() + source = undefined + } + depth-- + }) + for await (const chunk of body) { + bytes += chunk.length + // 50k maximum IDs of 88 Base64 bytes plus bounded XML framing/whitespace. + if (bytes > 50_000 * 128 + 1024) + throw new UploadProtocolError(413, 'Azure block-list manifest is too large') + parser.write(decoder.write(chunk)) + } + parser.write(decoder.end()).close() + if (!root || depth !== 0) fail() + return blocks +} diff --git a/lib/uploads.ts b/lib/uploads.ts new file mode 100644 index 00000000..a8aad3e2 --- /dev/null +++ b/lib/uploads.ts @@ -0,0 +1,532 @@ +import type { Kysely, Transaction } from 'kysely' +import type { Readable } from 'node:stream' +import type { Database, StorageLocation, UploadPart, UploadReceipt } from './db' +import type { StorageAdapter } from './storage' +import type { BlockReference, UploadIdentity } from './upload-protocol' +import { Buffer } from 'node:buffer' +import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto' +import { Readable as NodeReadable } from 'node:stream' +import { sql } from 'kysely' +import { retryOnLockConflict } from './db' +import { env } from './env' +import { generateNumberId } from './helpers' +import { UploadProtocolError, validateBlockId } from './upload-protocol' + +// GitHub documents a five-day self-hosted job limit. Seven days adds two days +// of retirement margin; it is NOT a generic lease or a JWT-expiry assertion. +// https://docs.github.com/en/actions/reference/limits +const LEGACY_RETIREMENT_MS = 7 * 24 * 60 * 60 * 1000 +const ATTEMPT_LEASE_MS = 60_000 +const ATTEMPT_RENEW_MS = 10_000 + +function assertPublicationAuthorized(upload: { publicationExpiresAt: number | null }) { + if (upload.publicationExpiresAt === null) { + if (!env.SKIP_TOKEN_VALIDATION) + throw new UploadProtocolError(403, 'Upload requires the approved pre-upgrade drain boundary') + } else if ( + !Number.isFinite(upload.publicationExpiresAt) || + Date.now() >= upload.publicationExpiresAt + ) + throw new UploadProtocolError(403, 'Upload publication authorization expired') +} + +/** Caller holds the upload lock. Expiry fences the exact attempt, not other workers. */ +export async function recoverExpiredUploadParts(tx: Transaction, uploadId: number) { + const removed = await tx + .deleteFrom('upload_parts') + .where('uploadId', '=', uploadId) + .where('sizeBytes', 'is', null) + .where('leaseExpiresAt', '<=', Date.now()) + .executeTakeFirst() + const count = Number(removed.numDeletedRows) + if (count > 0) + await tx + .updateTable('uploads') + .set({ finishedPartUploadCount: sql`${sql.ref('finishedPartUploadCount')} + ${count}` }) + .where('id', '=', uploadId) + .execute() + return count +} + +export interface UploadPublication { + receipt: UploadReceipt + location?: StorageLocation + sizes: number[] +} + +function capabilityDigest(capability: string | undefined) { + if (!capability) throw new UploadProtocolError(403, 'Forbidden') + return createHash('sha256').update(capability).digest('hex') +} + +function sameCapability(stored: string | null, digest: string) { + return stored !== null && timingSafeEqual(Buffer.from(stored, 'hex'), Buffer.from(digest, 'hex')) +} + +function receipt(db: Kysely, uploadId: number, digest: string) { + return db + .selectFrom('upload_receipts') + .selectAll() + .where('uploadId', '=', uploadId) + .where('capabilityHash', '=', digest) + .executeTakeFirst() +} + +async function lockUpload(tx: Transaction, uploadId: number, digest: string) { + let query = tx.selectFrom('uploads').selectAll().where('id', '=', uploadId) + if (env.DB_DRIVER !== 'sqlite') query = query.forUpdate() + const upload = await query.executeTakeFirst() + if (!upload || !sameCapability(upload.capabilityHash, digest)) + throw new UploadProtocolError(403, 'Forbidden') + return upload +} + +export async function authorizeUpload( + db: Kysely, + uploadId: number, + capability: string | undefined, +) { + if (!capability) return false + const digest = capabilityDigest(capability) + const upload = await db + .selectFrom('uploads') + .select('capabilityHash') + .where('id', '=', uploadId) + .executeTakeFirst() + if (upload && sameCapability(upload.capabilityHash, digest)) return true + return !!(await receipt(db, uploadId, digest)) +} + +async function receivePart( + db: Kysely, + adapter: StorageAdapter, + uploadId: number, + digest: string, + blockId: string | null, + stream: Readable, +) { + const { upload, part } = await retryOnLockConflict(() => + db + .transaction() + // The generation row lock serializes claims; a stale PG snapshot only aborts them. + .setIsolationLevel(env.DB_DRIVER === 'sqlite' ? 'serializable' : 'read committed') + .execute(async (tx) => { + if (await receipt(tx, uploadId, digest)) + throw new UploadProtocolError(409, 'Upload is already committed') + const upload = await lockUpload(tx, uploadId, digest) + assertPublicationAuthorized(upload) + await recoverExpiredUploadParts(tx, uploadId) + if (blockId !== null) { + const first = await tx + .selectFrom('upload_parts') + .select('blockId') + .where('uploadId', '=', uploadId) + .where('blockId', 'is not', null) + .executeTakeFirst() + if (first?.blockId && validateBlockId(first.blockId) !== validateBlockId(blockId)) + throw new UploadProtocolError( + 400, + 'Block IDs in one upload must have the same decoded length', + ) + } + const part: UploadPart = { + id: randomUUID(), + uploadId, + blockId, + revision: upload.startedPartUploadCount + 1, + partName: randomUUID(), + sizeBytes: null, + digest: null, + leaseExpiresAt: Date.now() + ATTEMPT_LEASE_MS, + } + await tx.insertInto('upload_parts').values(part).execute() + await tx + .updateTable('uploads') + .set({ startedPartUploadCount: part.revision }) + .where('id', '=', uploadId) + .execute() + return { upload, part } + }), + ) + let sizeBytes = 0 + const hash = blockId === null ? createHash('sha256') : undefined + const measured = NodeReadable.from( + (async function* () { + for await (const chunk of stream) { + sizeBytes += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength + hash?.update(chunk) + yield chunk + } + })(), + ) + let renewal: Promise | undefined + const leaseTimer = setInterval(() => { + renewal ??= retryOnLockConflict(() => + db.transaction().execute(async (tx) => { + await lockUpload(tx, uploadId, digest) + const now = Date.now() + const updated = await tx + .updateTable('upload_parts') + .set({ leaseExpiresAt: now + ATTEMPT_LEASE_MS }) + .where('id', '=', part.id) + .where('uploadId', '=', uploadId) + .where('sizeBytes', 'is', null) + .where('leaseExpiresAt', '>', now) + .executeTakeFirst() + if (Number(updated.numUpdatedRows) !== 1) + throw new UploadProtocolError(409, 'Upload attempt lease expired') + }), + ) + .catch((err: unknown) => { + measured.destroy( + err instanceof Error ? err : new Error('Upload attempt lease renewal failed'), + ) + }) + .finally(() => { + renewal = undefined + }) + }, ATTEMPT_RENEW_MS) + leaseTimer.unref() + const stopRenewal = async () => { + clearInterval(leaseTimer) + await renewal + } + try { + await adapter.uploadStream(`${upload.folderName}/parts/${part.partName}`, measured) + await stopRenewal() + const finished = { ...part, sizeBytes, digest: hash?.digest('hex') ?? null } + await retryOnLockConflict(() => + db.transaction().execute(async (tx) => { + assertPublicationAuthorized(await lockUpload(tx, uploadId, digest)) + const updated = await tx + .updateTable('upload_parts') + .set({ sizeBytes, digest: finished.digest }) + .where('id', '=', part.id) + .where('uploadId', '=', uploadId) + .where('sizeBytes', 'is', null) + .where('leaseExpiresAt', '>', Date.now()) + .executeTakeFirst() + if (Number(updated.numUpdatedRows) !== 1) + throw new UploadProtocolError(409, 'Upload attempt lease expired') + await tx + .updateTable('uploads') + .set({ + lastPartUploadedAt: Date.now(), + finishedPartUploadCount: sql`${sql.ref('finishedPartUploadCount')} + 1`, + }) + .where('id', '=', uploadId) + .execute() + }), + ) + return finished + } catch (err) { + await stopRenewal() + measured.destroy() + // An unsuccessful immutable revision is not eligible for a manifest. + // Physical debris remains under the existing orphan/parts lifecycle. + try { + await retryOnLockConflict(() => + db.transaction().execute(async (tx) => { + await lockUpload(tx, uploadId, digest) + const deleted = await tx + .deleteFrom('upload_parts') + .where('id', '=', part.id) + .where('sizeBytes', 'is', null) + .executeTakeFirst() + if (Number(deleted.numDeletedRows) === 1) + // Settled attempts are not completion proof; only the explicit + // manifest's successfully persisted revisions can be published. + await tx + .updateTable('uploads') + .set({ + lastPartUploadedAt: Date.now(), + finishedPartUploadCount: sql`${sql.ref('finishedPartUploadCount')} + 1`, + }) + .where('id', '=', uploadId) + .execute() + }), + ) + } catch (err_) { + throw new AggregateError([err, err_], 'Upload and attempt settlement failed') + } + throw err + } +} + +export async function stageBlock( + db: Kysely, + adapter: StorageAdapter, + uploadId: number, + capability: string | undefined, + blockId: string, + stream: Readable, +) { + validateBlockId(blockId) + await receivePart(db, adapter, uploadId, capabilityDigest(capability), blockId, stream) +} + +export async function putBlob( + db: Kysely, + adapter: StorageAdapter, + uploadId: number, + capability: string | undefined, + stream: Readable, +): Promise { + const digest = capabilityDigest(capability) + const prior = await receipt(db, uploadId, digest) + if (prior) { + const hash = createHash('sha256') + let size = 0 + for await (const chunk of stream) { + size += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength + hash.update(chunk) + } + if ( + prior.kind !== 'whole' || + prior.sizeBytes !== size || + prior.completionHash !== hash.digest('hex') + ) + throw new UploadProtocolError(409, 'Completed upload is immutable') + return { receipt: prior, sizes: [] } + } + const part = await receivePart(db, adapter, uploadId, digest, null, stream) + return publishUpload(db, uploadId, digest, 'whole', part.digest!, [], part.id) +} + +export async function commitBlockList( + db: Kysely, + uploadId: number, + capability: string | undefined, + blocks: BlockReference[], +) { + if (blocks.length > 50_000) throw new UploadProtocolError(400, 'Too many blocks') + const sources = new Map() + let length: number | undefined + for (const block of blocks) { + const size = validateBlockId(block.id) + if (length !== undefined && size !== length) + throw new UploadProtocolError(400, 'Block IDs must have the same decoded length') + if (sources.has(block.id) && sources.get(block.id) !== block.source) + throw new UploadProtocolError(400, 'Repeated block IDs must use the same source list') + sources.set(block.id, block.source) + length = size + } + const hash = createHash('sha256') + .update(JSON.stringify(blocks.map(({ id }) => id))) + .digest('hex') + return publishUpload(db, uploadId, capabilityDigest(capability), 'blocks', hash, blocks) +} + +async function publishUpload( + db: Kysely, + uploadId: number, + digest: string, + kind: UploadReceipt['kind'], + completionHash: string, + blocks: BlockReference[], + wholePartId?: string, +): Promise { + return retryOnLockConflict(() => + db + .transaction() + .setIsolationLevel('serializable') + .execute(async (tx) => { + const prior = await receipt(tx, uploadId, digest) + if (prior) { + if (prior.kind !== kind || prior.completionHash !== completionHash) + throw new UploadProtocolError(409, 'Completed upload is immutable') + return { receipt: prior, sizes: [] } + } + const upload = await lockUpload(tx, uploadId, digest) + // Recheck after all body/storage I/O, under the visibility transaction. + assertPublicationAuthorized(upload) + await recoverExpiredUploadParts(tx, uploadId) + const staged = await tx + .selectFrom('upload_parts') + .selectAll() + .where('uploadId', '=', uploadId) + .orderBy('revision', 'desc') + .execute() + if (staged.some((part) => part.sizeBytes === null)) + throw new UploadProtocolError(409, 'Part writes are still in progress') + const latest = new Map() + for (const part of staged) + if (part.blockId !== null && !latest.has(part.blockId)) latest.set(part.blockId, part) + const selected: UploadPart[] = [] + if (kind === 'whole') { + const part = staged.find(({ id }) => id === wholePartId) + if (!part || part.blockId !== null || part.digest !== completionHash) + throw new UploadProtocolError(409, 'Whole upload revision is unavailable') + selected.push(part) + } else + for (const block of blocks) { + const part = latest.get(block.id) + if (!part || block.source === 'Committed') + throw new UploadProtocolError(400, 'Manifest references an unavailable block') + selected.push(part) + } + const sizes = selected.map(({ sizeBytes }) => sizeBytes!) + const location: StorageLocation = { + id: randomUUID(), + folderName: upload.folderName, + partCount: selected.length, + partNamesJson: JSON.stringify(selected.map(({ partName }) => partName)), + mergedAt: null, + mergeStartedAt: null, + partsDeletedAt: null, + lastDownloadedAt: null, + sizeBytes: sizes.reduce((sum, size) => sum + size, 0), + } + if (!Number.isSafeInteger(location.sizeBytes)) + throw new UploadProtocolError(400, 'Completed upload is too large') + await tx.insertInto('storage_locations').values(location).execute() + const existing = await tx + .selectFrom('cache_entries') + .select('id') + .where('key', '=', upload.key) + .where('version', '=', upload.version) + .where('scope', '=', upload.scope) + .where('repoId', '=', upload.repoId) + .executeTakeFirst() + if (existing) + await tx + .updateTable('cache_entries') + .set({ updatedAt: Date.now(), locationId: location.id }) + .where('id', '=', existing.id) + .execute() + else + await tx + .insertInto('cache_entries') + .values({ + id: randomUUID(), + key: upload.key, + version: upload.version, + scope: upload.scope, + repoId: upload.repoId, + updatedAt: Date.now(), + locationId: location.id, + }) + .execute() + const completed: UploadReceipt = { + uploadId, + capabilityHash: digest, + locationId: location.id, + kind, + completionHash, + sizeBytes: location.sizeBytes!, + } + await tx.insertInto('upload_receipts').values(completed).execute() + await tx.deleteFrom('uploads').where('id', '=', uploadId).execute() + assertPublicationAuthorized(upload) + return { receipt: completed, location, sizes } + }), + ) +} + +/** Key-only Finalize is read-only: it cannot touch a pending generation. */ +export function acknowledgeUpload( + db: Kysely, + { key, version, scope, repoId }: UploadIdentity, +) { + return db + .selectFrom('cache_entries') + .innerJoin('upload_receipts', 'upload_receipts.locationId', 'cache_entries.locationId') + .select(['upload_receipts.uploadId', 'upload_receipts.sizeBytes']) + .where('key', '=', key) + .where('version', '=', version) + .where('scope', '=', scope) + .where('repoId', '=', repoId) + .executeTakeFirst() +} + +export async function createUpload( + db: Kysely, + { + key, + version, + scope, + repoId, + publicationExpiresAt = null, + }: UploadIdentity & { + publicationExpiresAt?: number | null + }, +) { + return retryOnLockConflict(() => + db + .transaction() + .setIsolationLevel('serializable') + .execute(async (tx) => { + const now = Date.now() + const matches = await tx + .selectFrom('uploads') + .selectAll() + .where('key', '=', key) + .where('version', '=', version) + .where('scope', '=', scope) + .where('repoId', '=', repoId) + .limit(2) + .execute() + if (matches.length > 1) return + const existing = matches[0] + if (existing) { + // Requested-key legacy recovery, NOT global cleanup or modern expiry. + // NULL-capability URLs cannot write; read-only Finalize cannot mutate + // their successor. Do not confuse global cleanup's 60s idle scan with + // safe retirement of a client's reservation. + if ( + existing.capabilityHash !== null || + existing.createdAt >= now - LEGACY_RETIREMENT_MS || + (existing.lastPartUploadedAt !== null && + existing.lastPartUploadedAt >= now - LEGACY_RETIREMENT_MS) || + existing.startedPartUploadCount !== existing.finishedPartUploadCount + ) + return + const completed = await tx + .selectFrom('cache_entries') + .select('id') + .where('key', '=', key) + .where('version', '=', version) + .where('scope', '=', scope) + .where('repoId', '=', repoId) + .executeTakeFirst() + const location = await tx + .selectFrom('storage_locations') + .select('id') + .where('folderName', '=', existing.folderName) + .executeTakeFirst() + const pending = await tx + .selectFrom('upload_parts') + .select('id') + .where('uploadId', '=', existing.id) + .where('sizeBytes', 'is', null) + .executeTakeFirst() + if (completed || location || pending) return + await tx + .deleteFrom('uploads') + .where('id', '=', existing.id) + .where('capabilityHash', 'is', null) + .execute() + } + const id = generateNumberId() + const capability = randomBytes(32).toString('hex') + await tx + .insertInto('uploads') + .values({ + id, + folderName: `${id}-${randomUUID()}`, + createdAt: now, + key, + version, + scope, + repoId, + lastPartUploadedAt: null, + finishedPartUploadCount: 0, + startedPartUploadCount: 0, + capabilityHash: capabilityDigest(capability), + publicationExpiresAt, + }) + .execute() + return { id, capability } + }), + ) +} diff --git a/package.json b/package.json index dbb1d0ee..d01794e0 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@falcondev-oss/github-actions-cache-server", "type": "module", - "version": "9.8.0", + "version": "9.8.0-backpressure.4", "private": true, "engines": { "node": "^26.13.0" @@ -53,6 +53,7 @@ "prom-client": "^15.1.3", "protobufjs": "^8.7.0", "remeda": "^2.39.0", + "saxes": "6.0.0", "ts-pattern": "^5.9.0", "typescript": "^6", "zod": "^4.4.3" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fb8a8075..701be9a9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -303,6 +303,9 @@ importers: remeda: specifier: ^2.39.0 version: 2.39.0 + saxes: + specifier: 6.0.0 + version: 6.0.0 ts-pattern: specifier: ^5.9.0 version: 5.9.0 @@ -1690,6 +1693,9 @@ packages: '@smithy/core@3.29.3': resolution: {integrity: sha512-L+Ys6ecjk5vwPMAKHBpPKlJ3DkqwNcnfEISXBZIsVvWG/XKXfsAP8mwIYlTeLcd2ElHdesPI8OuOmJSFAPhm6A==} engines: {node: '>=18.0.0'} + deprecated: |- + Deprecated due to a bug in custom logger data redaction. Upgrade to the latest version. If you used a custom logger with this + version, review your logs and rotate any credentials or other secrets. See https://github.com/aws/aws-sdk-js-v3/issues/8393. '@smithy/credential-provider-imds@4.4.8': resolution: {integrity: sha512-q9J7JTiXrAhB8sDp4px97uEPT7CwKH61Co78grdNQvU8QZAdiuaSRhP0tUVf2ogy36RZTrlMU1rBmDEH+cnkiA==} @@ -4793,6 +4799,7 @@ packages: prom-client@15.1.3: resolution: {integrity: sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==} engines: {node: ^16 || ^18 || >=20} + deprecated: prom-client has been replaced by @prometheus-io/client prop-types@15.8.1: resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==} @@ -4990,6 +4997,10 @@ packages: safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + scslre@0.3.0: resolution: {integrity: sha512-3A6sD0WYP7+QrjbfNA2FN3FsOaGGFoekCVgTyypy53gPxhbkCIjtO6YWgdrfM+n/8sI8JeXZOIxsHjMTNxQ4nQ==} engines: {node: ^14.0.0 || >=16.0.0} @@ -5798,6 +5809,9 @@ packages: resolution: {integrity: sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ==} engines: {node: '>=16.0.0'} + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + xtend@4.0.2: resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} engines: {node: '>=0.4'} @@ -11395,6 +11409,10 @@ snapshots: safer-buffer@2.1.2: {} + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + scslre@0.3.0: dependencies: '@eslint-community/regexpp': 4.12.2 @@ -12300,6 +12318,8 @@ snapshots: xml-naming@0.3.0: {} + xmlchars@2.2.0: {} + xtend@4.0.2: {} y18n@5.0.8: {} diff --git a/routes/devstoreaccount1/upload/[uploadId].put.ts b/routes/devstoreaccount1/upload/[uploadId].put.ts index 7f5a0733..ccf4461c 100644 --- a/routes/devstoreaccount1/upload/[uploadId].put.ts +++ b/routes/devstoreaccount1/upload/[uploadId].put.ts @@ -1,13 +1,13 @@ -import { Buffer } from 'node:buffer' import { randomUUID } from 'node:crypto' import { z } from 'zod' import { logger } from '~/lib/logger' import { getStorage } from '~/lib/storage' +import { parseBlockList, requestBody, UploadProtocolError } from '~/lib/upload-protocol' const pathParamsSchema = z.object({ - uploadId: z.coerce.number(), + uploadId: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER), }) export default defineEventHandler(async (event) => { @@ -24,55 +24,29 @@ export default defineEventHandler(async (event) => { // and append their own parameters, as they do with an Azure SAS. const capability = typeof query.sig === 'string' ? query.sig : undefined - // A blocklist commits the blocks already stored; there is no part to write. - let chunkIndex: number | undefined - if (query.comp !== 'blocklist') { - const blockId = query.blockid as string - // if no block id, upload smaller than chunk size - chunkIndex = blockId ? getChunkIndexFromBlockId(blockId) : 0 - if (chunkIndex === undefined) - throw createError({ - statusCode: 400, - statusMessage: `Invalid block id: ${blockId}`, - }) - } - - let authorized: boolean try { const storage = await getStorage() - authorized = await storage.authorizeUpload(uploadId, capability) - // Not h3's `getRequestWebStream`: it enqueues every `data` event and never pauses - // the request, so a body arriving faster than storage accepts it is buffered in - // memory in full. Reading `req` directly lets storage pace the client over TCP. - if (authorized && chunkIndex !== undefined) - await storage.uploadPart(uploadId, chunkIndex, event.node.req) + if (!(await storage.authorizeUpload(uploadId, capability))) + throw new UploadProtocolError(403, 'Forbidden') + if (query.comp === 'blocklist') { + const blocks = await parseBlockList(requestBody(event.node.req)) + await storage.commitBlockList(uploadId, capability, blocks) + } else if (query.comp === 'block' && typeof query.blockid === 'string') { + await storage.stageBlock(uploadId, capability, query.blockid, requestBody(event.node.req)) + } else if (query.comp === undefined && query.blockid === undefined) { + await storage.putBlob(uploadId, capability, requestBody(event.node.req)) + } else { + throw new UploadProtocolError(400, 'Unsupported Azure upload operation') + } } catch (err) { - // Logged here and rethrown as handled: Nitro logs unhandled errors with the - // request URL, which carries the capability. + // Never let Nitro log an upload URL carrying its capability. + if (err instanceof UploadProtocolError) + throw createError({ statusCode: err.statusCode, statusMessage: err.message }) logger.error(`Failed to store upload ${uploadId}`, err) throw createError({ statusCode: 500, statusMessage: 'Failed to store upload' }) } - if (!authorized) throw createError({ statusCode: 403, statusMessage: 'Forbidden' }) // prevent random EOF error with in tonistiigi/go-actions-cache caused by missing request id setHeader(event, 'x-ms-request-id', randomUUID()) setResponseStatus(event, 201) }) - -function getChunkIndexFromBlockId(blockIdBase64: string) { - const base64Decoded = Buffer.from(blockIdBase64, 'base64') - - // 64 bytes used by docker buildx - // 48 bytes used by everything else - if (base64Decoded.length === 64) return base64Decoded.readUInt32BE(16) - - if (base64Decoded.length === 48) { - const decoded = base64Decoded.toString('utf8') - - // slice off uuid and convert to number - const index = Number.parseInt(decoded.slice(36)) - if (Number.isNaN(index)) return - - return index - } -} diff --git a/routes/twirp/github.actions.results.api.v1.CacheService/CreateCacheEntry.post.ts b/routes/twirp/github.actions.results.api.v1.CacheService/CreateCacheEntry.post.ts index dc70056b..7e98e35a 100644 --- a/routes/twirp/github.actions.results.api.v1.CacheService/CreateCacheEntry.post.ts +++ b/routes/twirp/github.actions.results.api.v1.CacheService/CreateCacheEntry.post.ts @@ -10,7 +10,7 @@ const bodySchema = z.object({ }) export default defineEventHandler(async (event) => { - const { scopes, repoId } = await getCacheScope(event) + const { scopes, repoId, publicationExpiresAt } = await getCacheScope(event) const { key, version } = await readTwirpRequest( event, @@ -23,7 +23,13 @@ export default defineEventHandler(async (event) => { if (!writeScope) throw createError({ statusCode: 403, message: 'No scope with write permission found' }) - const upload = await storage.createUpload({ key, version, scope: writeScope.Scope, repoId }) + const upload = await storage.createUpload({ + key, + version, + scope: writeScope.Scope, + repoId, + publicationExpiresAt, + }) return sendTwirpResponse( event, diff --git a/routes/twirp/github.actions.results.api.v1.CacheService/FinalizeCacheEntryUpload.ts b/routes/twirp/github.actions.results.api.v1.CacheService/FinalizeCacheEntryUpload.ts index 5dc20338..5c9a7124 100644 --- a/routes/twirp/github.actions.results.api.v1.CacheService/FinalizeCacheEntryUpload.ts +++ b/routes/twirp/github.actions.results.api.v1.CacheService/FinalizeCacheEntryUpload.ts @@ -1,5 +1,4 @@ import { z } from 'zod' -import { cacheUploadsTotal } from '~/lib/metrics' import { CACHE_PERMISSION_WRITE, getCacheScope } from '~/lib/scope' import { getStorage } from '~/lib/storage' import { readTwirpRequest, sendTwirpResponse, TwirpMessage } from '~/lib/twirp' @@ -7,12 +6,13 @@ import { readTwirpRequest, sendTwirpResponse, TwirpMessage } from '~/lib/twirp' const bodySchema = z.object({ key: z.string().min(1), version: z.string().min(1), + size_bytes: z.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(), }) export default defineEventHandler(async (event) => { const { scopes, repoId } = await getCacheScope(event) - const { key, version } = await readTwirpRequest( + const { key, version, size_bytes } = await readTwirpRequest( event, bodySchema, TwirpMessage.FinalizeCacheEntryUploadRequest, @@ -23,18 +23,19 @@ export default defineEventHandler(async (event) => { if (!writeScope) throw createError({ statusCode: 403, message: 'No scope with write permission found' }) - const upload = await storage.completeUpload({ key, version, scope: writeScope.Scope, repoId }) + const upload = await storage.acknowledgeUpload({ key, version, scope: writeScope.Scope, repoId }) if (!upload) throw createError({ statusCode: 404, - statusMessage: 'Upload not found', + statusMessage: 'Completed upload not found', }) - cacheUploadsTotal.inc() + if (size_bytes !== undefined && size_bytes !== upload.sizeBytes) + throw createError({ statusCode: 409, statusMessage: 'Completed upload size does not match' }) return sendTwirpResponse( event, - { ok: true, entry_id: upload.id.toString() }, + { ok: true, entry_id: upload.uploadId.toString() }, TwirpMessage.FinalizeCacheEntryUploadResponse, ) }) diff --git a/tasks/cleanup/uploads.ts b/tasks/cleanup/uploads.ts index d7e3e8fa..04d0fab0 100644 --- a/tasks/cleanup/uploads.ts +++ b/tasks/cleanup/uploads.ts @@ -1,7 +1,7 @@ import { getDatabase } from '~/lib/db' import { env } from '~/lib/env' import { getStorage } from '~/lib/storage' -import { CleanupAggregateError, runCleanupTask } from '~/lib/storage-lifecycle' +import { CleanupAggregateError, deleteUploadIfIdle, runCleanupTask } from '~/lib/storage-lifecycle' const itemsPerPage = 10 @@ -39,16 +39,44 @@ export default defineTask({ eb('createdAt', '<', oneMinuteAgo), ]), ) + .where((eb) => + eb.or([ + eb('startedPartUploadCount', '=', eb.ref('finishedPartUploadCount')), + eb.exists( + eb + .selectFrom('upload_parts') + .select('id') + .whereRef('upload_parts.uploadId', '=', 'uploads.id') + .where('sizeBytes', 'is', null) + .where('leaseExpiresAt', '<=', Date.now()), + ), + ]), + ) + .where((eb) => + eb.not( + eb.exists( + eb + .selectFrom('upload_parts') + .select('id') + .whereRef('upload_parts.uploadId', '=', 'uploads.id') + .where('sizeBytes', 'is', null) + .where('leaseExpiresAt', '>', Date.now()), + ), + ), + ) .select(['id', 'folderName']) .limit(itemsPerPage) .execute() if (uploads.length === 0) break for (const upload of uploads) { - await db.deleteFrom('uploads').where('id', '=', upload.id).execute() + const folder = await db + .transaction() + .execute((tx) => deleteUploadIfIdle(tx, upload.id, oneMinuteAgo)) + if (!folder) continue result.deletedUploads++ try { - const reclaimed = await storage.adapter.deleteFolder(upload.folderName) + const reclaimed = await storage.adapter.deleteFolder(folder) result.deletedObjects += reclaimed.objects result.deletedBytes += reclaimed.bytes } catch (err) { diff --git a/tests/authenticated-upload-completion.test.ts b/tests/authenticated-upload-completion.test.ts new file mode 100644 index 00000000..9f717b15 --- /dev/null +++ b/tests/authenticated-upload-completion.test.ts @@ -0,0 +1,764 @@ +import type { Kysely } from 'kysely' +import type { Database } from '~/lib/db' +import { Buffer } from 'node:buffer' +import { createHash, randomUUID } from 'node:crypto' +import { once } from 'node:events' +import net from 'node:net' +import { PassThrough, Readable } from 'node:stream' +import { SignJWT } from 'jose' +import { describe, expect, test, vi } from 'vitest' +import { z } from 'zod' +import { getDatabase } from '~/lib/db' +import { getStorage, Storage } from '~/lib/storage' +import { deleteUploadIfIdle } from '~/lib/storage-lifecycle' + +const API = 'http://localhost:3000/twirp/github.actions.results.api.v1.CacheService' +const createdSchema = z.object({ ok: z.literal(true), signed_upload_url: z.url() }) +const restoredSchema = z.object({ ok: z.literal(true), signed_download_url: z.url() }) +const creationOutcomeSchema = z.object({ ok: z.boolean() }) +interface Fixture { + db: Kysely + storage: Storage + identity: { key: string; version: string; scope: string; repoId: string } + token: string + url: URL + id: number + capability: string +} + +async function responseStatus(response: Promise) { + const result = await response + return result.status +} + +async function creationOk(response: Response) { + const result = creationOutcomeSchema.parse(await response.json()) + return result.ok +} + +async function token(repoId: string, scope: string) { + return new SignJWT({ + repository_id: repoId, + ac: JSON.stringify([{ Scope: scope, Permission: 3 }]), + jti: randomUUID(), + }) + .setProtectedHeader({ alg: 'HS256' }) + .sign(Buffer.from('fixture-only-not-a-production-key')) +} + +function rpc(method: string, bearer: string, body: object) { + return fetch(`${API}/${method}`, { + method: 'POST', + headers: { 'authorization': `Bearer ${bearer}`, 'content-type': 'application/json' }, + body: JSON.stringify(body), + }) +} + +async function fixture(key = randomUUID(), repoId = 'completion-tests', scope = 'refs/heads/main') { + const identity = { key, version: 'v1', scope, repoId } + const bearer = await token(repoId, scope) + const response = await rpc('CreateCacheEntry', bearer, identity) + expect(response.status).toBe(200) + const created = createdSchema.parse(await response.json()) + expect(created.ok).toBe(true) + const url = new URL(created.signed_upload_url) + return { + db: await getDatabase(), + storage: await getStorage(), + identity, + token: bearer, + url, + id: Number(url.pathname.split('/').at(-1)), + capability: url.searchParams.get('sig')!, + } satisfies Fixture +} + +function blockId(value: number) { + return Buffer.alloc(16, value).toString('base64') +} + +function blockUrl(state: Fixture, id: string) { + const url = new URL(state.url) + url.searchParams.set('comp', 'block') + url.searchParams.set('blockid', id) + return url +} + +function commit(state: Fixture, ids: string[], xml?: string) { + const url = new URL(state.url) + url.searchParams.set('comp', 'blocklist') + return fetch(url, { + method: 'PUT', + body: xml ?? `${ids.map((id) => `${id}`).join('')}`, + }) +} + +async function restored(state: Fixture) { + const response = await rpc('GetCacheEntryDownloadURL', state.token, state.identity) + const result = restoredSchema.parse(await response.json()) + expect(result.ok).toBe(true) + const download = await fetch(result.signed_download_url) + expect(download.status).toBe(200) + return Buffer.from(await download.arrayBuffer()) +} + +async function restoredText(state: Fixture) { + const body = await restored(state) + return body.toString() +} + +async function assertPending(state: Fixture) { + expect( + await state.db.selectFrom('uploads').select('id').where('id', '=', state.id).executeTakeFirst(), + ).toBeDefined() + expect( + await state.db + .selectFrom('cache_entries') + .select('id') + .where('key', '=', state.identity.key) + .where('scope', '=', state.identity.scope) + .where('repoId', '=', state.identity.repoId) + .execute(), + ).toHaveLength(0) +} + +async function makeLegacy( + state: Fixture, + changes: { + createdAt?: number + lastPartUploadedAt?: number | null + startedPartUploadCount?: number + } = {}, +) { + await state.db + .updateTable('uploads') + .set({ + capabilityHash: null, + createdAt: Date.now() - 25 * 86_400_000, + lastPartUploadedAt: Date.now() - 25 * 86_400_000, + ...changes, + }) + .where('id', '=', state.id) + .execute() +} + +describe('authenticated complete-payload publication', () => { + test('whole PUT publishes exact bytes, read-only acknowledgment, cold/warm restore and idempotent retry', async () => { + const state = await fixture() + expect(await responseStatus(fetch(state.url, { method: 'PUT', body: 'whole-payload' }))).toBe( + 201, + ) + expect(await restoredText(state)).toBe('whole-payload') + await state.storage.waitForOngoingMerges() + expect(await restoredText(state)).toBe('whole-payload') + const before = await state.db + .selectFrom('cache_entries') + .selectAll() + .where('key', '=', state.identity.key) + .execute() + expect( + await responseStatus( + rpc('FinalizeCacheEntryUpload', state.token, { ...state.identity, size_bytes: 13 }), + ), + ).toBe(200) + expect( + await responseStatus( + rpc('FinalizeCacheEntryUpload', state.token, { ...state.identity, size_bytes: 2 }), + ), + ).toBe(409) + expect(await responseStatus(fetch(state.url, { method: 'PUT', body: 'whole-payload' }))).toBe( + 201, + ) + expect(await responseStatus(fetch(state.url, { method: 'PUT', body: 'replacement' }))).toBe(409) + expect( + await responseStatus(fetch(blockUrl(state, blockId(1)), { method: 'PUT', body: 'late' })), + ).toBe(409) + expect( + await state.db + .selectFrom('cache_entries') + .selectAll() + .where('key', '=', state.identity.key) + .execute(), + ).toEqual(before) + expect( + await state.db + .selectFrom('upload_receipts') + .select('uploadId') + .where('uploadId', '=', state.id) + .execute(), + ).toHaveLength(1) + }) + + test('opaque 16-byte IDs, manifest order, repeated references, latest revisions and omitted extra blocks', async () => { + const state = await fixture() + const a = blockId(2) + const b = blockId(1) + const extra = blockId(3) + for (const [id, body] of [ + [b, 'B'], + [a, 'old-A'], + [extra, 'EXCLUDED'], + [a, 'A'], + ]) + expect(await responseStatus(fetch(blockUrl(state, id), { method: 'PUT', body }))).toBe(201) + expect(await responseStatus(commit(state, [a, b, a]))).toBe(201) + expect(await restoredText(state)).toBe('ABA') + await state.storage.waitForOngoingMerges() + expect(await restoredText(state)).toBe('ABA') + expect(await responseStatus(commit(state, [a, b, a]))).toBe(201) + expect(await responseStatus(commit(state, [b, a]))).toBe(409) + }) + + test('missing blocks, malformed/DTD manifests and mixed duplicate sources cannot publish or discard pending data', async () => { + const state = await fixture() + const id = blockId(4) + expect(await responseStatus(fetch(blockUrl(state, id), { method: 'PUT', body: 'kept' }))).toBe( + 201, + ) + expect(await responseStatus(commit(state, [id, blockId(5)]))).toBe(400) + for (const xml of [ + '', + '', + '', + `${id}${id}`, + `invalid`, + ]) { + expect(await responseStatus(commit(state, [], xml))).toBe(400) + await assertPending(state) + } + expect(await responseStatus(commit(state, [id]))).toBe(201) + expect(await restoredText(state)).toBe('kept') + }) + + test('an empty authenticated payload is a real zero-byte cache, not a dangling entry', async () => { + for (const mode of ['whole', 'blocks']) { + const state = await fixture() + const response = + mode === 'whole' + ? await fetch(state.url, { method: 'PUT', body: '' }) + : await commit(state, []) + expect(response.status).toBe(201) + expect(await restored(state)).toHaveLength(0) + } + }) + + test('concurrent stage writes fence completion; delayed finalizers never publish a partial successor', async () => { + const state = await fixture() + const id = blockId(6) + const stream = new PassThrough() + const staged = state.storage.stageBlock(state.id, state.capability, id, stream) + await vi.waitFor(async () => { + expect( + await state.db + .selectFrom('upload_parts') + .select('id') + .where('uploadId', '=', state.id) + .where('sizeBytes', 'is', null) + .execute(), + ).toHaveLength(1) + }) + expect(await responseStatus(commit(state, [id]))).toBe(409) + expect(await responseStatus(rpc('FinalizeCacheEntryUpload', state.token, state.identity))).toBe( + 404, + ) + await assertPending(state) + stream.end('complete-after-stream-end') + await staged + const responses = await Promise.all([commit(state, [id]), commit(state, [id])]) + expect(responses.map(({ status }) => status)).toEqual([201, 201]) + expect(await restoredText(state)).toBe('complete-after-stream-end') + expect( + await state.db + .selectFrom('cache_entries') + .select('id') + .where('key', '=', state.identity.key) + .execute(), + ).toHaveLength(1) + expect( + await state.db + .selectFrom('upload_receipts') + .select('uploadId') + .where('uploadId', '=', state.id) + .execute(), + ).toHaveLength(1) + }) + + test('truncated HTTP bodies are never published', async () => { + const state = await fixture() + const socket = net.createConnection({ host: 'localhost', port: 3000 }) + await once(socket, 'connect') + socket.end( + `PUT ${state.url.pathname}${state.url.search} HTTP/1.1\r\nHost: localhost:3000\r\nContent-Length: 100\r\nConnection: close\r\n\r\nshort`, + ) + socket.resume() + await once(socket, 'close') + await vi.waitFor(async () => { + expect( + await state.db + .selectFrom('upload_parts') + .select('id') + .where('uploadId', '=', state.id) + .execute(), + ).toHaveLength(0) + }) + await assertPending(state) + expect( + await state.db + .selectFrom('upload_receipts') + .select('uploadId') + .where('uploadId', '=', state.id) + .execute(), + ).toHaveLength(0) + }) + + test('wrong capability, ID, repository and scope cannot publish or acknowledge another generation', async () => { + const state = await fixture() + const other = await fixture() + const copied = new URL(other.url) + copied.searchParams.set('sig', state.capability) + expect(await responseStatus(fetch(copied, { method: 'PUT', body: 'forged' }))).toBe(403) + expect(await responseStatus(fetch(state.url, { method: 'PUT', body: 'owned' }))).toBe(201) + for (const bearer of [ + await token('another-repo', state.identity.scope), + await token(state.identity.repoId, 'refs/heads/another'), + ]) + expect(await responseStatus(rpc('FinalizeCacheEntryUpload', bearer, state.identity))).toBe( + 404, + ) + expect(await restoredText(state)).toBe('owned') + await assertPending(other) + }) +}) + +describe('requested-key legacy recovery without global cleanup', () => { + test('same-token legacy finalizers and old upload URLs cannot touch a successor, including between its parts', async () => { + const state = await fixture() + const oldUrl = new URL(state.url) + const oldId = state.id + await makeLegacy(state) + const created = await rpc('CreateCacheEntry', state.token, state.identity) + const result = createdSchema.parse(await created.json()) + expect(result.ok).toBe(true) + state.url = new URL(result.signed_upload_url) + state.id = Number(state.url.pathname.split('/').at(-1)) + state.capability = state.url.searchParams.get('sig')! + expect(state.id).not.toBe(oldId) + expect(await responseStatus(fetch(oldUrl, { method: 'PUT', body: 'old' }))).toBe(403) + const before = await state.db + .selectFrom('uploads') + .selectAll() + .where('id', '=', state.id) + .executeTakeFirstOrThrow() + expect(await responseStatus(rpc('FinalizeCacheEntryUpload', state.token, state.identity))).toBe( + 404, + ) + expect( + await state.db + .selectFrom('uploads') + .selectAll() + .where('id', '=', state.id) + .executeTakeFirst(), + ).toEqual(before) + const a = blockId(7) + const b = blockId(8) + expect(await responseStatus(fetch(blockUrl(state, a), { method: 'PUT', body: 'first' }))).toBe( + 201, + ) + expect(await responseStatus(rpc('FinalizeCacheEntryUpload', state.token, state.identity))).toBe( + 404, + ) + await assertPending(state) + expect(await responseStatus(fetch(blockUrl(state, b), { method: 'PUT', body: 'second' }))).toBe( + 201, + ) + expect(await responseStatus(commit(state, [a, b]))).toBe(201) + const published = await state.db + .selectFrom('cache_entries') + .selectAll() + .where('key', '=', state.identity.key) + .execute() + expect(await responseStatus(rpc('FinalizeCacheEntryUpload', state.token, state.identity))).toBe( + 200, + ) + expect( + await state.db + .selectFrom('cache_entries') + .selectAll() + .where('key', '=', state.identity.key) + .execute(), + ).toEqual(published) + expect(await restoredText(state)).toBe('firstsecond') + }) + + test('modern, recently active and unequal-counter legacy reservations remain untouched', async () => { + for (const kind of ['modern', 'recent-created', 'recent-part', 'inflight']) { + const state = await fixture() + if (kind === 'modern') + await state.db + .updateTable('uploads') + .set({ createdAt: 1, lastPartUploadedAt: 1 }) + .where('id', '=', state.id) + .execute() + else + await makeLegacy( + state, + kind === 'recent-created' + ? { createdAt: Date.now() } + : kind === 'recent-part' + ? { lastPartUploadedAt: Date.now() } + : { startedPartUploadCount: 1 }, + ) + const before = await state.db + .selectFrom('uploads') + .selectAll() + .where('id', '=', state.id) + .executeTakeFirstOrThrow() + const response = await rpc('CreateCacheEntry', state.token, state.identity) + expect(await creationOk(response)).toBe(false) + expect( + await state.db + .selectFrom('uploads') + .selectAll() + .where('id', '=', state.id) + .executeTakeFirst(), + ).toEqual(before) + } + }) + + test('completed entries and unrelated scopes/repositories survive requested-key recovery', async () => { + const state = await fixture() + expect(await responseStatus(fetch(state.url, { method: 'PUT', body: 'completed' }))).toBe(201) + const pending = await fixture(state.identity.key, state.identity.repoId, state.identity.scope) + await makeLegacy(pending) + const response = await rpc('CreateCacheEntry', state.token, state.identity) + expect(await creationOk(response)).toBe(false) + expect(await restoredText(state)).toBe('completed') + const otherRepo = await fixture(state.identity.key, 'unrelated-repo') + const otherScope = await fixture( + state.identity.key, + state.identity.repoId, + 'refs/heads/unrelated', + ) + const unrelated = await state.db + .selectFrom('uploads') + .selectAll() + .where('id', 'in', [otherRepo.id, otherScope.id]) + .execute() + const recoverable = await fixture() + await makeLegacy(recoverable) + const outcomes = await Promise.all([ + rpc('CreateCacheEntry', recoverable.token, recoverable.identity), + rpc('CreateCacheEntry', recoverable.token, recoverable.identity), + ]) + const results = await Promise.all(outcomes.map(creationOk)) + expect(results.filter(Boolean)).toHaveLength(1) + expect( + await state.db + .selectFrom('uploads') + .selectAll() + .where('id', 'in', [otherRepo.id, otherScope.id]) + .execute(), + ).toEqual(unrelated) + }) +}) + +describe('generation integrity and retirement boundaries', () => { + test.each([16, 48, 64])( + 'preserves opaque %i-byte client block IDs and manifest order', + async (length) => { + const state = await fixture() + const ids = [0, 1].map((index) => { + if (length === 48) + return Buffer.from(`${randomUUID()}${String(index).padStart(12, '0')}`).toString('base64') + const value = Buffer.alloc(length) + Buffer.from(randomUUID().replaceAll('-', ''), 'hex').copy(value) + if (length === 64) value.writeUInt32BE(index, 16) + return value.toString('base64') + }) + expect( + await responseStatus(fetch(blockUrl(state, ids[0]!), { method: 'PUT', body: 'first' })), + ).toBe(201) + expect( + await responseStatus(fetch(blockUrl(state, ids[1]!), { method: 'PUT', body: 'second' })), + ).toBe(201) + expect(await responseStatus(commit(state, [ids[1]!, ids[0]!]))).toBe(201) + expect(await restoredText(state)).toBe('secondfirst') + }, + ) + + test('body checksum failure cannot publish and a legitimate retry remains usable', async () => { + const state = await fixture() + expect( + await responseStatus( + fetch(state.url, { + method: 'PUT', + body: 'payload', + headers: { 'content-md5': Buffer.alloc(16).toString('base64') }, + }), + ), + ).toBe(400) + await assertPending(state) + expect( + await state.db + .selectFrom('upload_parts') + .select('id') + .where('uploadId', '=', state.id) + .execute(), + ).toHaveLength(0) + const checksum = createHash('md5').update('payload').digest('base64') + expect( + await responseStatus( + fetch(state.url, { + method: 'PUT', + body: 'payload', + headers: { 'content-md5': checksum }, + }), + ), + ).toBe(201) + expect(await restoredText(state)).toBe('payload') + expect( + await state.db + .selectFrom('upload_parts') + .select('id') + .where('uploadId', '=', state.id) + .execute(), + ).toHaveLength(0) + }) + + test('failed and active streaming attempts are not completion proof or idle-cleanup targets', async () => { + const state = await fixture() + const ancient = Date.now() - 25 * 86_400_000 + await state.db + .updateTable('uploads') + .set({ createdAt: ancient, lastPartUploadedAt: ancient }) + .where('id', '=', state.id) + .execute() + const stream = new PassThrough() + const attempt = state.storage.stageBlock(state.id, state.capability, blockId(12), stream) + await vi.waitFor(async () => { + expect( + await state.db + .selectFrom('upload_parts') + .select('id') + .where('uploadId', '=', state.id) + .where('sizeBytes', 'is', null) + .execute(), + ).toHaveLength(1) + }) + const removed = await state.db + .transaction() + .execute((tx) => deleteUploadIfIdle(tx, state.id, Date.now() + 1000)) + expect(removed).toBeUndefined() + expect(await creationOk(await rpc('CreateCacheEntry', state.token, state.identity))).toBe(false) + expect(await responseStatus(rpc('FinalizeCacheEntryUpload', state.token, state.identity))).toBe( + 404, + ) + stream.destroy(new Error('interrupted fixture stream')) + await expect(attempt).rejects.toThrow('interrupted fixture stream') + expect(await responseStatus(commit(state, [blockId(12)]))).toBe(400) + await assertPending(state) + expect( + await responseStatus(fetch(blockUrl(state, blockId(12)), { method: 'PUT', body: 'retry' })), + ).toBe(201) + expect(await responseStatus(commit(state, [blockId(12)]))).toBe(201) + expect(await restoredText(state)).toBe('retry') + }) + + test('competing completion manifests publish only one immutable generation', async () => { + const state = await fixture() + const a = blockId(13) + const b = blockId(14) + expect(await responseStatus(fetch(blockUrl(state, a), { method: 'PUT', body: 'A' }))).toBe(201) + expect(await responseStatus(fetch(blockUrl(state, b), { method: 'PUT', body: 'B' }))).toBe(201) + const statuses = await Promise.all([ + responseStatus(commit(state, [a])), + responseStatus(commit(state, [b])), + ]) + expect(statuses.toSorted((left, right) => left - right)).toEqual([201, 409]) + expect(await restoredText(state)).toMatch(/^[AB]$/) + expect( + await state.db + .selectFrom('cache_entries') + .select('id') + .where('key', '=', state.identity.key) + .execute(), + ).toHaveLength(1) + expect( + await state.db + .selectFrom('upload_receipts') + .select('uploadId') + .where('uploadId', '=', state.id) + .execute(), + ).toHaveLength(1) + }) + + test('legacy retirement exceeds a five-day job and refuses ambiguous duplicate reservations', async () => { + const recent = await fixture() + const sixDaysAgo = Date.now() - 6 * 86_400_000 + await makeLegacy(recent, { createdAt: sixDaysAgo, lastPartUploadedAt: sixDaysAgo }) + const original = await recent.db + .selectFrom('uploads') + .selectAll() + .where('id', '=', recent.id) + .executeTakeFirstOrThrow() + expect(await creationOk(await rpc('CreateCacheEntry', recent.token, recent.identity))).toBe( + false, + ) + expect( + await recent.db + .selectFrom('uploads') + .selectAll() + .where('id', '=', recent.id) + .executeTakeFirst(), + ).toEqual(original) + const duplicate = await fixture() + await makeLegacy(duplicate) + const legacy = await duplicate.db + .selectFrom('uploads') + .selectAll() + .where('id', '=', duplicate.id) + .executeTakeFirstOrThrow() + await duplicate.db + .insertInto('uploads') + .values({ + ...legacy, + id: legacy.id + 100_000_000_000, + folderName: `${legacy.folderName}-duplicate`, + }) + .execute() + const before = await duplicate.db + .selectFrom('uploads') + .selectAll() + .where('key', '=', duplicate.identity.key) + .execute() + expect( + await creationOk(await rpc('CreateCacheEntry', duplicate.token, duplicate.identity)), + ).toBe(false) + expect( + await duplicate.db + .selectFrom('uploads') + .selectAll() + .where('key', '=', duplicate.identity.key) + .execute(), + ).toEqual(before) + }) + + test('a reconstructed writer recovers only expired crashed attempts before exact retransmission', async () => { + const state = await fixture() + // Persist the crash boundary directly: no running promise/catch handler exists. + await state.db + .insertInto('upload_parts') + .values({ + id: randomUUID(), + uploadId: state.id, + blockId: blockId(15), + revision: 1, + partName: randomUUID(), + sizeBytes: null, + digest: null, + leaseExpiresAt: Date.now() - 1, + }) + .execute() + await state.db + .updateTable('uploads') + .set({ startedPartUploadCount: 1 }) + .where('id', '=', state.id) + .execute() + const restarted = await Storage.fromEnv() + await restarted.stageBlock( + state.id, + state.capability, + blockId(15), + Readable.from('retransmitted'), + ) + expect(await responseStatus(commit(state, [blockId(15)]))).toBe(201) + expect(await restoredText(state)).toBe('retransmitted') + }) + + test('an expired writer resuming after recovery cannot settle or overwrite a new immutable revision', async () => { + const state = await fixture() + const stream = new PassThrough() + const pending = state.storage.stageBlock(state.id, state.capability, blockId(16), stream) + // Attach rejection handling before deliberately fencing the attempt. + const outcome = pending.then( + () => undefined, + (err: unknown) => err, + ) + await vi.waitFor(async () => { + expect( + await state.db + .selectFrom('upload_parts') + .select('id') + .where('uploadId', '=', state.id) + .where('sizeBytes', 'is', null) + .execute(), + ).toHaveLength(1) + }) + await state.db + .updateTable('upload_parts') + .set({ leaseExpiresAt: Date.now() - 1 }) + .where('uploadId', '=', state.id) + .where('sizeBytes', 'is', null) + .execute() + const restarted = await Storage.fromEnv() + await restarted.stageBlock( + state.id, + state.capability, + blockId(16), + Readable.from('authoritative'), + ) + expect(await responseStatus(commit(state, [blockId(16)]))).toBe(201) + stream.end('late-abandoned-bytes') + expect(await outcome).toBeInstanceOf(Error) + expect(await restoredText(state)).toBe('authoritative') + }) + + test('idle cleanup settles expired attempts but never deletes another live owner', async () => { + const state = await fixture() + const ancient = Date.now() - 25 * 86_400_000 + await state.db + .updateTable('uploads') + .set({ createdAt: ancient, lastPartUploadedAt: ancient, startedPartUploadCount: 2 }) + .where('id', '=', state.id) + .execute() + const liveId = randomUUID() + for (const [id, leaseExpiresAt] of [ + [randomUUID(), Date.now() - 1], + [liveId, Date.now() + 60_000], + ] as const) + await state.db + .insertInto('upload_parts') + .values({ + id, + uploadId: state.id, + blockId: blockId(17), + revision: id === liveId ? 2 : 1, + partName: randomUUID(), + sizeBytes: null, + digest: null, + leaseExpiresAt, + }) + .execute() + expect( + await state.db.transaction().execute((tx) => deleteUploadIfIdle(tx, state.id, Date.now())), + ).toBeUndefined() + expect( + await state.db + .selectFrom('upload_parts') + .select('id') + .where('uploadId', '=', state.id) + .execute(), + ).toEqual([{ id: liveId }]) + await state.db + .updateTable('upload_parts') + .set({ leaseExpiresAt: Date.now() - 1 }) + .where('id', '=', liveId) + .execute() + expect( + await state.db.transaction().execute((tx) => deleteUploadIfIdle(tx, state.id, Date.now())), + ).toBeTypeOf('string') + expect( + await state.db.selectFrom('uploads').select('id').where('id', '=', state.id).execute(), + ).toHaveLength(0) + }) +}) diff --git a/tests/authenticated-upload-migration.test.ts b/tests/authenticated-upload-migration.test.ts new file mode 100644 index 00000000..71561759 --- /dev/null +++ b/tests/authenticated-upload-migration.test.ts @@ -0,0 +1,108 @@ +import type { Database } from '~/lib/db' +import SQLite from 'better-sqlite3' +import { createHooks } from 'hookable' +import { Kysely, SqliteDialect } from 'kysely' +import { Migrator } from 'kysely/migration' +import { expect, test } from 'vitest' +import { migrations } from '~/lib/migrations' + +test('completion migration preserves legacy data, adds empty generation metadata and refuses unsafe downgrade', async () => { + const sqlite = new SQLite(':memory:') + const db = new Kysely({ + dialect: new SqliteDialect({ database: sqlite }), + }) + const all = migrations('sqlite', createHooks()) + const migrator = new Migrator({ + db, + provider: { + async getMigrations() { + return all + }, + }, + }) + try { + const baseline = await migrator.migrateTo('$8_upload_capability_hash') + expect(baseline.error).toBeUndefined() + await db + .insertInto('uploads') + .values({ + id: 42, + key: 'legacy', + version: 'v1', + scope: 'refs/heads/main', + repoId: 'repo', + createdAt: 1, + lastPartUploadedAt: 2, + folderName: '42', + startedPartUploadCount: 1, + finishedPartUploadCount: 1, + capabilityHash: null, + }) + .execute() + await db + .insertInto('storage_locations') + .values({ + id: 'old-location', + folderName: 'old-payload', + partCount: 1, + mergedAt: null, + mergeStartedAt: null, + partsDeletedAt: null, + lastDownloadedAt: null, + sizeBytes: 3, + }) + .execute() + await db + .insertInto('cache_entries') + .values({ + id: 'old-cache', + key: 'complete', + version: 'v1', + scope: 'refs/heads/main', + repoId: 'repo', + updatedAt: 1, + locationId: 'old-location', + }) + .execute() + const upload = await db.selectFrom('uploads').selectAll().executeTakeFirstOrThrow() + const upgraded = await migrator.migrateToLatest() + expect(upgraded.error).toBeUndefined() + expect(await db.selectFrom('uploads').selectAll().executeTakeFirst()).toEqual({ + ...upload, + publicationExpiresAt: null, + }) + const preserved = await db.selectFrom('storage_locations').selectAll().executeTakeFirstOrThrow() + expect(preserved.partNamesJson).toBeNull() + expect(await db.selectFrom('cache_entries').select('id').execute()).toEqual([ + { id: 'old-cache' }, + ]) + expect(await db.selectFrom('upload_parts').selectAll().execute()).toHaveLength(0) + expect(await db.selectFrom('upload_receipts').selectAll().execute()).toHaveLength(0) + expect(sqlite.pragma('index_list(upload_receipts)')).toEqual( + expect.arrayContaining([expect.objectContaining({ name: 'idx_upload_receipts_location' })]), + ) + const down = await migrator.migrateTo('$8_upload_capability_hash') + expect(String(down.error)).toContain('forward-only') + const tables = await db.introspection.getTables() + expect( + tables.find(({ name }) => name === 'storage_locations')?.columns.map(({ name }) => name), + ).toContain('partNamesJson') + const oldProvider = new Migrator({ + db, + provider: { + async getMigrations() { + const { $9_authenticated_upload_completion: _, ...old } = all + return old + }, + }, + }) + const oldBinary = await oldProvider.migrateToLatest() + expect(oldBinary.error).toBeDefined() + expect(await db.selectFrom('uploads').selectAll().executeTakeFirst()).toEqual({ + ...upload, + publicationExpiresAt: null, + }) + } finally { + await db.destroy() + } +}) diff --git a/tests/cache-entry-matching.test.ts b/tests/cache-entry-matching.test.ts index 2d006fb6..53c16e95 100644 --- a/tests/cache-entry-matching.test.ts +++ b/tests/cache-entry-matching.test.ts @@ -235,7 +235,9 @@ describe('cache entry matching', () => { .all() as { name: string }[] ).map((row) => row.name) try { - await expect(migrator.migrateToLatest()).resolves.not.toHaveProperty('error') + await expect( + migrator.migrateTo('$7_cache_entries_lookup_indexes'), + ).resolves.not.toHaveProperty('error') expect(indexes()).toEqual(['idx_cache_entries_lookup', 'idx_cache_entries_lookup_prefix']) // Explicit targets: later migrations sit above `$7`, so a single step down would not reach it. await expect( @@ -246,6 +248,10 @@ describe('cache entry matching', () => { migrator.migrateTo('$7_cache_entries_lookup_indexes'), ).resolves.not.toHaveProperty('error') expect(indexes()).toEqual(['idx_cache_entries_lookup', 'idx_cache_entries_lookup_prefix']) + await expect(migrator.migrateToLatest()).resolves.not.toHaveProperty('error') + const downgrade = await migrator.migrateTo('$7_cache_entries_lookup_indexes') + expect(String(downgrade.error)).toContain('forward-only') + expect(indexes()).toEqual(['idx_cache_entries_lookup', 'idx_cache_entries_lookup_prefix']) } finally { await db.destroy() } diff --git a/tests/cleanup-lifecycle.test.ts b/tests/cleanup-lifecycle.test.ts index ef0c1dac..ca736f2a 100644 --- a/tests/cleanup-lifecycle.test.ts +++ b/tests/cleanup-lifecycle.test.ts @@ -6,6 +6,7 @@ import { getDatabase } from '~/lib/db' import { env } from '~/lib/env' import { Storage } from '~/lib/storage' import { DIRECT_DOWNLOAD_LEASE_MARGIN_MS } from '~/lib/storage-leases' +import { completeFixtureUpload, stageFixturePart } from './upload-fixture' describe('cleanup lifecycle', () => { beforeAll(() => { @@ -37,8 +38,8 @@ describe('cleanup lifecycle', () => { const upload = await storage.createUpload(entry) expect(upload).toBeDefined() for (const [partIndex, part] of entry.parts.entries()) - await storage.uploadPart(upload!.id, partIndex, Readable.from(part)) - await storage.completeUpload(entry) + await stageFixturePart(storage, upload!, partIndex, Readable.from(part)) + await completeFixtureUpload(storage, upload!) const cache = await storage.matchCacheEntry({ keys: [entry.key], version: entry.version, @@ -178,16 +179,14 @@ describe('cleanup lifecycle', () => { scope: 'refs/heads/main', repoId: '123', }) - await storage.uploadPart(upload!.id, 0, Readable.from('payload')) + await stageFixturePart(storage, upload!, 0, Readable.from('payload')) const deleteFolder = vi .spyOn(storage.adapter, 'deleteFolder') .mockRejectedValue(new Error('no')) try { env.CACHE_MAX_SIZE_BYTES = 1 - await expect( - storage.completeUpload({ key, version: 'v1', scope: 'refs/heads/main', repoId: '123' }), - ).resolves.toBeDefined() + await expect(completeFixtureUpload(storage, upload!)).resolves.toBeDefined() } finally { env.CACHE_MAX_SIZE_BYTES = originalBudget deleteFolder.mockRestore() @@ -548,7 +547,7 @@ describe('cleanup lifecycle', () => { } }) - test('failed upload finalization removes the upload folder after its database record', async () => { + test('key-only finalization cannot delete a pending upload or its data', async () => { const storage = await Storage.fromEnv() const key = randomUUID() const upload = await storage.createUpload({ @@ -558,11 +557,19 @@ describe('cleanup lifecycle', () => { repoId: '123', }) expect(upload).toBeDefined() - await storage.adapter.uploadStream(`${upload!.id}/untracked`, Readable.from('partial')) - + const db = await getDatabase() + const before = await db + .selectFrom('uploads') + .selectAll() + .where('id', '=', upload!.id) + .executeTakeFirstOrThrow() + await storage.adapter.uploadStream(`${before.folderName}/untracked`, Readable.from('partial')) await expect( - storage.completeUpload({ key, version: 'v1', scope: 'refs/heads/main', repoId: '123' }), - ).rejects.toThrow('No parts have been uploaded') - expect(await storage.adapter.countFilesInFolder(upload!.id.toString())).toBe(0) + storage.acknowledgeUpload({ key, version: 'v1', scope: 'refs/heads/main', repoId: '123' }), + ).resolves.toBeUndefined() + expect( + await db.selectFrom('uploads').selectAll().where('id', '=', upload!.id).executeTakeFirst(), + ).toEqual(before) + expect(await storage.adapter.countFilesInFolder(before.folderName)).toBe(1) }) }) diff --git a/tests/clients/opendal/Cargo.lock b/tests/clients/opendal/Cargo.lock new file mode 100644 index 00000000..2aec9727 --- /dev/null +++ b/tests/clients/opendal/Cargo.lock @@ -0,0 +1,1901 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "backon" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" +dependencies = [ + "fastrand", + "gloo-timers", + "tokio", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cache-opendal-client-fixture" +version = "0.1.0" +dependencies = [ + "bytes", + "opendal", + "tokio", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "ghac" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a10bd5b898cac1a4de4a882a754b2ccaafead449348cfb420b48cd5c00ffd08b" +dependencies = [ + "prost", +] + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jiff" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" +dependencies = [ + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opendal" +version = "0.55.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d075ab8a203a6ab4bc1bce0a4b9fe486a72bf8b939037f4b78d95386384bc80a" +dependencies = [ + "anyhow", + "backon", + "base64 0.22.1", + "bytes", + "futures", + "getrandom 0.2.17", + "ghac", + "http", + "http-body", + "jiff", + "log", + "md-5", + "percent-encoding", + "prost", + "quick-xml", + "reqsign", + "reqwest", + "serde", + "serde_json", + "sha2", + "tokio", + "url", + "uuid", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "quick-xml" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "reqsign" +version = "0.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43451dbf3590a7590684c25fb8d12ecdcc90ed3ac123433e500447c7d77ed701" +dependencies = [ + "anyhow", + "async-trait", + "base64 0.22.1", + "chrono", + "form_urlencoded", + "getrandom 0.2.17", + "hex", + "hmac", + "home", + "http", + "log", + "percent-encoding", + "rand 0.8.8", + "reqwest", + "serde", + "serde_json", + "sha1", + "sha2", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tests/clients/opendal/Cargo.toml b/tests/clients/opendal/Cargo.toml new file mode 100644 index 00000000..62f17aa4 --- /dev/null +++ b/tests/clients/opendal/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "cache-opendal-client-fixture" +version = "0.1.0" +edition = "2024" +rust-version = "1.85" +publish = false + +[dependencies] +bytes = "1" +opendal = { version = "=0.55.0", features = ["services-ghac"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } diff --git a/tests/clients/opendal/src/main.rs b/tests/clients/opendal/src/main.rs new file mode 100644 index 00000000..207543e6 --- /dev/null +++ b/tests/clients/opendal/src/main.rs @@ -0,0 +1,83 @@ +use bytes::{Buf, Bytes}; +use opendal::{Operator, services::Ghac}; + +async fn verify(operator: &Operator, key: &str, expected: &[u8]) -> opendal::Result<()> { + for _ in 0..2 { + let mut body = operator.read(key).await?; + assert_eq!(body.remaining(), expected.len(), "wrong restored size"); + let mut offset = 0; + while body.has_remaining() { + let chunk = body.chunk(); + assert!( + chunk == &expected[offset..offset + chunk.len()], + "wrong restored bytes" + ); + offset += chunk.len(); + let size = chunk.len(); + body.advance(size); + } + } + Ok(()) +} + +async fn roundtrip() -> opendal::Result<()> { + let endpoint = std::env::var("FIXTURE_ENDPOINT").expect("FIXTURE_ENDPOINT is required"); + let address = endpoint.strip_prefix("http://") + .and_then(|value| value.strip_suffix('/')) + .and_then(|value| value.parse::().ok()); + assert!(address.is_some_and(|value| value.ip().is_loopback()), "fixture only permits a loopback endpoint"); + let token = std::env::var("FIXTURE_TOKEN").expect("FIXTURE_TOKEN is required"); + let prefix = std::env::var("FIXTURE_PREFIX").expect("FIXTURE_PREFIX is required"); + let operator = Operator::new( + Ghac::default() + .version("authenticated-completion-client-fixture") + .endpoint(&endpoint) + .runtime_token(&token), + )? + .finish(); + let chunk_size = 64 * 1024; + let payload = Bytes::from( + (0..chunk_size * 3) + .map(|offset| b'A' + (offset / chunk_size) as u8) + .collect::>(), + ); + let whole_key = format!("{prefix}-whole"); + operator.write(&whole_key, payload.slice(..1024)).await?; + verify(&operator, &whole_key, &payload[..1024]).await?; + + let blocks_key = format!("{prefix}-blocks"); + let mut writer = operator + .writer_with(&blocks_key) + .chunk(chunk_size) + .concurrent(3) + .await?; + for index in 0..3 { + writer + .write(payload.slice(index * chunk_size..(index + 1) * chunk_size)) + .await?; + } + writer.close().await?; + verify(&operator, &blocks_key, &payload).await?; + println!("{{\"whole\":true,\"multipart\":true,\"coldWarmExact\":true}}"); + Ok(()) +} + +#[tokio::main] +async fn main() { + if let Err(error) = roundtrip().await { + // Preserve diagnostics but never print a bearer or signed URL query. + let token = std::env::var("FIXTURE_TOKEN").unwrap_or_default(); + let message = error.to_string(); + let safe = if token.is_empty() { + message + } else { + message.replace(&token, "[redacted]") + }; + eprint!("OpenDAL roundtrip failed:"); + for word in safe.split_whitespace() { + eprint!(" {}", word.split_once('?').map_or(word, |(path, _)| path)); + } + eprintln!(); + std::process::exit(1); + } +} diff --git a/tests/direct-download-auth.test.ts b/tests/direct-download-auth.test.ts index fc038079..0f30c3bb 100644 --- a/tests/direct-download-auth.test.ts +++ b/tests/direct-download-auth.test.ts @@ -5,12 +5,14 @@ import type { AddressInfo } from 'node:net' import { generateKeyPairSync, randomBytes, randomUUID } from 'node:crypto' import { createServer } from 'node:http' +import { Readable } from 'node:stream' import { setTimeout as sleep } from 'node:timers/promises' import { type } from 'arkenv' import { execa } from 'execa' import { exportJWK, SignJWT } from 'jose' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' +import { getDatabase } from '~/lib/db' import { assertDirectDownloadsRequireTokenValidation, envBaseSchema, @@ -163,13 +165,21 @@ async function twirp(method: string, token: string | undefined, body: object) { async function save(token: string, key: string, data: Buffer) { const created = await twirp('CreateCacheEntry', token, { key, version: 'v1' }) expect(created.status).toBe(200) - const uploadUrl = created.json.signed_upload_url as string - const part = await fetch(uploadUrl, { method: 'PUT', body: new Uint8Array(data) }) + const uploadUrl = created.json.signed_upload_url + if (typeof uploadUrl !== 'string') throw new Error('Create did not return an upload URL') + const id = Buffer.from('signed-auth-part').toString('base64') + const partUrl = new URL(uploadUrl) + partUrl.searchParams.set('comp', 'block') + partUrl.searchParams.set('blockid', id) + const part = await fetch(partUrl, { method: 'PUT', body: new Uint8Array(data) }) expect(part.status).toBe(201) - // The signed URL already has a query (the upload capability), so append to it. + // Keep the signed URL's capability on the authenticated completion request. const blocklistUrl = new URL(uploadUrl) blocklistUrl.searchParams.set('comp', 'blocklist') - const blocklist = await fetch(blocklistUrl, { method: 'PUT' }) + const blocklist = await fetch(blocklistUrl, { + method: 'PUT', + body: `${id}`, + }) expect(blocklist.status).toBe(201) const finalized = await twirp('FinalizeCacheEntryUpload', token, { key, @@ -347,6 +357,137 @@ describe('token validation and direct downloads', () => { expect(finalize.status).toBe(401) }) + test.each(['whole', 'blocks'])( + 'verified creator expiry fences %s publication without changing an existing entry', + async (mode) => { + const db = await getDatabase() + const key = `expiry-${randomUUID()}` + const fresh = await track(mint(claimsFor(repoA))) + await save(fresh, key, Buffer.from('preserved')) + const previous = await db + .selectFrom('cache_entries') + .selectAll() + .where('key', '=', key) + .execute() + const exp = Math.floor(Date.now() / 1000) + 2 + const bearer = await track(mint(claimsFor(repoA), { exp })) + const created = await twirp('CreateCacheEntry', bearer, { key, version: 'v1' }) + expect(created.status).toBe(200) + const url = new URL(String(created.json.signed_upload_url)) + const id = Number(url.pathname.split('/').at(-1)) + const upload = await db + .selectFrom('uploads') + .select('publicationExpiresAt') + .where('id', '=', id) + .executeTakeFirstOrThrow() + expect(upload.publicationExpiresAt).toBe(exp * 1000) + const blockId = Buffer.from('expiry-proof').toString('base64') + if (mode === 'blocks') { + const staged = new URL(url) + staged.searchParams.set('comp', 'block') + staged.searchParams.set('blockid', blockId) + const part = await fetch(staged, { method: 'PUT', body: 'replacement' }) + expect(part.status).toBe(201) + url.searchParams.set('comp', 'blocklist') + } + await sleep(Math.max(0, exp * 1000 - Date.now() + 25)) + const refused = await fetch(url, { + method: 'PUT', + body: + mode === 'whole' ? 'replacement' : `${blockId}`, + }) + expect(refused.status).toBe(403) + expect( + await db.selectFrom('cache_entries').selectAll().where('key', '=', key).execute(), + ).toEqual(previous) + const finalized = await twirp('FinalizeCacheEntryUpload', bearer, { key, version: 'v1' }) + expect(finalized.status).toBe(401) + }, + ) + + test('creator expiry during asynchronous body/storage cannot publish its completed bytes', async () => { + const db = await getDatabase() + const key = `stream-expiry-${randomUUID()}` + const exp = Math.floor(Date.now() / 1000) + 3 + const bearer = await track(mint(claimsFor(repoA), { exp })) + const created = await twirp('CreateCacheEntry', bearer, { key, version: 'v1' }) + const url = new URL(String(created.json.signed_upload_url)) + const id = Number(url.pathname.split('/').at(-1)) + const release = Promise.withResolvers() + const response = fetch(url, { + method: 'PUT', + body: Readable.toWeb( + Readable.from( + (async function* () { + yield 'first' + await release.promise + yield 'last' + })(), + ), + ) as BodyInit, + duplex: 'half', + } as RequestInit) + try { + await vi.waitFor(async () => { + expect( + await db + .selectFrom('upload_parts') + .select('id') + .where('uploadId', '=', id) + .where('sizeBytes', 'is', null) + .execute(), + ).toHaveLength(1) + }) + await sleep(Math.max(0, exp * 1000 - Date.now() + 25)) + } finally { + release.resolve() + } + const completed = await response + expect(completed.status).toBe(403) + expect( + await db.selectFrom('cache_entries').select('id').where('key', '=', key).execute(), + ).toHaveLength(0) + expect( + await db + .selectFrom('upload_receipts') + .select('uploadId') + .where('uploadId', '=', id) + .execute(), + ).toHaveLength(0) + }) + + test('expiry-unknown pre-upgrade modern URLs fail closed without guessing expiry or consuming the reservation', async () => { + const db = await getDatabase() + const key = `unknown-expiry-${randomUUID()}` + const bearer = await track(mint(claimsFor(repoA))) + const created = await twirp('CreateCacheEntry', bearer, { key, version: 'v1' }) + const url = new URL(String(created.json.signed_upload_url)) + const id = Number(url.pathname.split('/').at(-1)) + await db + .updateTable('uploads') + .set({ publicationExpiresAt: null }) + .where('id', '=', id) + .execute() + const original = await db + .selectFrom('uploads') + .selectAll() + .where('id', '=', id) + .executeTakeFirst() + const whole = await fetch(url, { method: 'PUT', body: 'not-authorized' }) + expect(whole.status).toBe(403) + url.searchParams.set('comp', 'blocklist') + const manifest = await fetch(url, { method: 'PUT', body: '' }) + expect(manifest.status).toBe(403) + const finalized = await twirp('FinalizeCacheEntryUpload', bearer, { key, version: 'v1' }) + expect(finalized.status).toBe(404) + expect( + await db.selectFrom('uploads').selectAll().where('id', '=', id).executeTakeFirst(), + ).toEqual(original) + expect( + await db.selectFrom('cache_entries').select('id').where('key', '=', key).execute(), + ).toHaveLength(0) + }) + test( 'a forged token gets no URL for an existing entry, direct or proxied', { timeout: 30_000 }, diff --git a/tests/download-client-gone.test.ts b/tests/download-client-gone.test.ts index 624912bb..8fcdd275 100644 --- a/tests/download-client-gone.test.ts +++ b/tests/download-client-gone.test.ts @@ -13,6 +13,7 @@ import * as h3 from 'h3' import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' import { getDatabase } from '~/lib/db' import { getStorage, S3Adapter } from '~/lib/storage' +import { completeFixtureUpload, stageFixturePart } from './upload-fixture' /** * A stand-in for the object store: answers every GET with an unending body, so @@ -84,8 +85,8 @@ async function createMergedEntry() { const entry = { key, version: 'v1', scope: 'refs/heads/main', repoId: '123' } const upload = await storage.createUpload(entry) if (!upload) throw new Error('createUpload returned nothing') - await storage.uploadPart(upload.id, 0, Readable.from('payload')) - await storage.completeUpload(entry) + await stageFixturePart(storage, upload, 0, Readable.from('payload')) + await completeFixtureUpload(storage, upload!) const cacheEntry = await db .selectFrom('cache_entries') .where('key', '=', key) diff --git a/tests/download-merge-backpressure.test.ts b/tests/download-merge-backpressure.test.ts index d15b4100..f30ffb14 100644 --- a/tests/download-merge-backpressure.test.ts +++ b/tests/download-merge-backpressure.test.ts @@ -52,6 +52,7 @@ describe('download merge backpressure', () => { partCount: PART_COUNT, mergedAt: null, partsDeletedAt: null, + partNamesJson: null, } const deadline = new Promise<'timeout'>((res) => setTimeout(res, 5000, 'timeout')) diff --git a/tests/download-merge-sink-gone.test.ts b/tests/download-merge-sink-gone.test.ts index 17023529..adf20739 100644 --- a/tests/download-merge-sink-gone.test.ts +++ b/tests/download-merge-sink-gone.test.ts @@ -6,6 +6,7 @@ import { setTimeout as sleep } from 'node:timers/promises' import { afterEach, describe, expect, test, vi } from 'vitest' import { getDatabase } from '~/lib/db' import { getStorage } from '~/lib/storage' +import { completeFixtureUpload, stageFixturePart } from './upload-fixture' const PART_COUNT = 3 const PART_BYTES = 1024 * 1024 @@ -18,8 +19,8 @@ async function createUnmergedEntry() { const upload = await storage.createUpload(entry) if (!upload) throw new Error('createUpload returned nothing') for (let i = 0; i < PART_COUNT; i++) - await storage.uploadPart(upload.id, i, Readable.from([Buffer.alloc(PART_BYTES, i)])) - await storage.completeUpload(entry) + await stageFixturePart(storage, upload, i, Readable.from([Buffer.alloc(PART_BYTES, i)])) + await completeFixtureUpload(storage, upload!) return db .selectFrom('cache_entries') .where('key', '=', key) diff --git a/tests/e2e.test.ts b/tests/e2e.test.ts index a5e523e9..0138d1a8 100644 --- a/tests/e2e.test.ts +++ b/tests/e2e.test.ts @@ -1,4 +1,5 @@ import crypto from 'node:crypto' +import { createReadStream } from 'node:fs' import fs from 'node:fs/promises' import path from 'node:path' @@ -34,12 +35,18 @@ describe(`save and restore cache with @actions/cache package`, () => { await saveCache([testFilePath], 'cache-key') await fs.rm(testFilePath) - // restore - const cacheHitKey = await restoreCache([testFilePath], 'cache-key') - expect(cacheHitKey).toBe('cache-key') - - // check contents - const restoredContents = await fs.readFile(testFilePath) - expect(restoredContents.compare(expectedContents)).toBe(0) + // Both the first restore and a warm restore must return the exact bytes. + // Stream the comparison so the 512MiB case does not copy another archive. + for (const phase of ['cold', 'warm']) { + const cacheHitKey = await restoreCache([testFilePath], 'cache-key') + expect(cacheHitKey, phase).toBe('cache-key') + let offset = 0 + for await (const chunk of createReadStream(testFilePath)) { + expect(chunk.compare(expectedContents, offset, offset + chunk.length), phase).toBe(0) + offset += chunk.length + } + expect(offset, phase).toBe(expectedContents.length) + await fs.rm(testFilePath) + } }) }) diff --git a/tests/eager-merge.test.ts b/tests/eager-merge.test.ts index 64cf33af..0087fc29 100644 --- a/tests/eager-merge.test.ts +++ b/tests/eager-merge.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' import { getDatabase } from '~/lib/db' import { env } from '~/lib/env' import { Storage } from '~/lib/storage' +import { completeFixtureUpload, stageFixturePart } from './upload-fixture' const scope = { version: 'v1', scope: 'refs/heads/main', repoId: '123' } @@ -12,8 +13,8 @@ async function uploadParts(storage: Storage, parts: Buffer[]) { const key = randomUUID() const upload = await storage.createUpload({ key, ...scope }) for (const [index, part] of parts.entries()) - await storage.uploadPart(upload!.id, index, Readable.from(part)) - await storage.completeUpload({ key, ...scope }) + await stageFixturePart(storage, upload!, index, Readable.from(part)) + await completeFixtureUpload(storage, upload!) const db = await getDatabase() return db .selectFrom('storage_locations') @@ -112,4 +113,43 @@ describe('eager merge', () => { } }, ) + + test.skipIf((process.env.VITEST_STORAGE_DRIVER ?? 'filesystem') === 'filesystem')( + 'server-side composition preserves duplicate references and omits unselected staged parts', + { timeout: 60_000 }, + async () => { + const storage = await Storage.fromEnv() + const key = randomUUID() + const upload = await storage.createUpload({ key, ...scope }) + if (!upload) throw new Error('createUpload returned nothing') + const a = Buffer.from('opaque-a').toString('base64') + const b = Buffer.from('opaque-b').toString('base64') + const extra = Buffer.from('unused-x').toString('base64') + const payload = Buffer.alloc(5 * 1024 * 1024, 'A') + await storage.stageBlock(upload.id, upload.capability, a, Readable.from(payload)) + await storage.stageBlock(upload.id, upload.capability, b, Readable.from('B')) + await storage.stageBlock(upload.id, upload.capability, extra, Readable.from('EXCLUDED')) + const compose = vi.spyOn(storage.adapter.composeParts!, 'run') + await storage.commitBlockList( + upload.id, + upload.capability, + [a, a, b].map((id) => ({ id, source: 'Latest' })), + ) + await storage.waitForOngoingMerges() + expect(compose).toHaveBeenCalledOnce() + const db = await getDatabase() + const location = await db + .selectFrom('storage_locations') + .innerJoin('cache_entries', 'cache_entries.locationId', 'storage_locations.id') + .selectAll('storage_locations') + .where('cache_entries.key', '=', key) + .executeTakeFirstOrThrow() + const actual = await mergedBytes(storage, location.folderName) + expect(actual.length).toBe(payload.length * 2 + 1) + expect(actual.subarray(0, payload.length).equals(payload)).toBe(true) + expect(actual.subarray(payload.length, payload.length * 2).equals(payload)).toBe(true) + expect(actual.at(-1)).toBe('B'.codePointAt(0)) + compose.mockRestore() + }, + ) }) diff --git a/tests/merge-concurrency.test.ts b/tests/merge-concurrency.test.ts index bbfd12ed..2bd6ca79 100644 --- a/tests/merge-concurrency.test.ts +++ b/tests/merge-concurrency.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, test } from 'vitest' import { getDatabase } from '~/lib/db' import { env } from '~/lib/env' import { Storage } from '~/lib/storage' +import { completeFixtureUpload, stageFixturePart } from './upload-fixture' const scope = { version: 'v1', scope: 'refs/heads/main', repoId: '123' } @@ -12,8 +13,8 @@ async function uploadEntry(storage: Storage, parts: Buffer[]) { const key = `merge-cap-${randomUUID()}` const upload = await storage.createUpload({ key, ...scope }) for (const [index, part] of parts.entries()) - await storage.uploadPart(upload!.id, index, Readable.from(part)) - await storage.completeUpload({ key, ...scope }) + await stageFixturePart(storage, upload!, index, Readable.from(part)) + await completeFixtureUpload(storage, upload!) const db = await getDatabase() return db .selectFrom('cache_entries') diff --git a/tests/merge-socket-pool.test.ts b/tests/merge-socket-pool.test.ts index 629f224d..5cd5fb28 100644 --- a/tests/merge-socket-pool.test.ts +++ b/tests/merge-socket-pool.test.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, test } from 'vitest' import { getDatabase } from '~/lib/db' import { env } from '~/lib/env' import { Storage } from '~/lib/storage' +import { completeFixtureUpload, stageFixturePart } from './upload-fixture' const MiB = 1024 * 1024 const POOL = 4 @@ -16,8 +17,8 @@ async function uploadEntry(storage: Storage, parts: Buffer[]) { const key = `merge-pool-${randomUUID()}` const upload = await storage.createUpload({ key, ...scope }) for (const [index, part] of parts.entries()) - await storage.uploadPart(upload!.id, index, Readable.from(part)) - await storage.completeUpload({ key, ...scope }) + await stageFixturePart(storage, upload!, index, Readable.from(part)) + await completeFixtureUpload(storage, upload!) const db = await getDatabase() return db .selectFrom('cache_entries') diff --git a/tests/opendal-client.test.ts b/tests/opendal-client.test.ts new file mode 100644 index 00000000..73eda3b8 --- /dev/null +++ b/tests/opendal-client.test.ts @@ -0,0 +1,130 @@ +import type { AddressInfo } from 'node:net' +import { Buffer } from 'node:buffer' +import { randomUUID } from 'node:crypto' +import http from 'node:http' +import path from 'node:path' +import { execa } from 'execa' +import { SignJWT } from 'jose' +import { expect, test } from 'vitest' +import { getDatabase } from '~/lib/db' + +/** A real pinned OpenDAL client, not an emulated sequence of upload requests. */ +test( + 'openDAL 0.55 whole/multipart cold writes and warm reads use authenticated exact completion', + { timeout: 600_000 }, + async () => { + const manifest = path.join(import.meta.dirname, 'clients/opendal/Cargo.toml') + const cargo = process.env.CARGO ?? 'cargo' + await execa(cargo, ['build', '--locked', '--manifest-path', manifest]) + const lengths: number[] = [] + let whole = 0 + let manifests = 0 + const failures: string[] = [] + const requests: { method: string | undefined; path: string; status?: number }[] = [] + const proxy = http.createServer((incoming, outgoing) => { + const target = new URL(incoming.url!, 'http://127.0.0.1:3000') + const record = { + method: incoming.method, + path: target.pathname, + status: undefined as number | undefined, + } + requests.push(record) + if (!['localhost', '127.0.0.1'].includes(target.hostname) || target.port !== '3000') { + failures.push('Client attempted a non-fixture target') + outgoing.writeHead(502).end() + return + } + if (incoming.method === 'PUT' && /\/upload\/\d+$/.test(target.pathname)) { + const operation = target.searchParams.get('comp') + if (operation === 'block') + lengths.push(Buffer.from(target.searchParams.get('blockid')!, 'base64').byteLength) + else if (operation === 'blocklist') manifests++ + else whole++ + } + const upstream = http.request( + target, + { method: incoming.method, headers: { ...incoming.headers, host: target.host } }, + (response) => { + record.status = response.statusCode + outgoing.writeHead(response.statusCode!, response.headers) + response.pipe(outgoing) + }, + ) + upstream.on('error', () => { + failures.push('Fixture proxy upstream failed') + outgoing.writeHead(502).end() + }) + incoming.pipe(upstream) + }) + const listening = Promise.withResolvers() + proxy.once('error', listening.reject) + proxy.listen(0, '127.0.0.1', listening.resolve) + await listening.promise + try { + const proxyUrl = `http://127.0.0.1:${(proxy.address() as AddressInfo).port}` + const token = await new SignJWT({ + repository_id: 'opendal-client-proof', + ac: JSON.stringify([{ Scope: 'refs/heads/main', Permission: 3 }]), + }) + .setProtectedHeader({ alg: 'HS256' }) + .sign(Buffer.from('fixture-only-key')) + const executable = path.join( + import.meta.dirname, + 'clients/opendal/target/debug', + process.platform === 'win32' + ? 'cache-opendal-client-fixture.exe' + : 'cache-opendal-client-fixture', + ) + const result = await execa(executable, { + env: { + FIXTURE_ENDPOINT: 'http://127.0.0.1:3000/', + FIXTURE_TOKEN: token, + FIXTURE_PREFIX: randomUUID(), + ACTIONS_CACHE_SERVICE_V2: 'true', + GITHUB_SERVER_URL: 'https://github.com', + HTTP_PROXY: proxyUrl, + HTTPS_PROXY: proxyUrl, + ALL_PROXY: proxyUrl, + http_proxy: proxyUrl, + https_proxy: proxyUrl, + all_proxy: proxyUrl, + NO_PROXY: '', + no_proxy: '', + }, + }).catch((err) => { + console.error('OpenDAL fixture transport (no queries or credentials)', requests) + throw err + }) + expect(JSON.parse(result.stdout)).toEqual({ + whole: true, + multipart: true, + coldWarmExact: true, + }) + expect(failures).toEqual([]) + expect( + requests.every(({ status }) => status !== undefined && status >= 200 && status < 300), + ).toBe(true) + expect(whole).toBe(1) + expect(manifests).toBe(1) + expect(lengths.length).toBeGreaterThanOrEqual(2) + expect(lengths.every((length) => length === 16)).toBe(true) + const db = await getDatabase() + const published = await db + .selectFrom('cache_entries') + .innerJoin('upload_receipts', 'upload_receipts.locationId', 'cache_entries.locationId') + .innerJoin('storage_locations', 'storage_locations.id', 'cache_entries.locationId') + .select(['kind', 'partNamesJson', 'upload_receipts.sizeBytes']) + .where('repoId', '=', 'opendal-client-proof') + .execute() + expect(published).toHaveLength(2) + expect(published.find(({ kind }) => kind === 'whole')?.sizeBytes).toBe(1024) + const blocks = published.find(({ kind }) => kind === 'blocks')! + expect(blocks.sizeBytes).toBe(3 * 64 * 1024) + expect(JSON.parse(blocks.partNamesJson!).length).toBeGreaterThanOrEqual(2) + } finally { + const closed = Promise.withResolvers() + proxy.close((error) => (error ? closed.reject(error) : closed.resolve())) + await closed.promise + } + }, +) diff --git a/tests/request-logging.test.ts b/tests/request-logging.test.ts index 2c832374..efc963b8 100644 --- a/tests/request-logging.test.ts +++ b/tests/request-logging.test.ts @@ -96,9 +96,17 @@ test('upload capabilities stay out of request and error logs', async () => { expect(rejected.status).toBe(403) // Storage failing mid-upload (e.g. the backend is unreachable) is logged as an error. + const pending = await storage.createUpload({ + key: `request-logging-failure-${randomUUID()}`, + version: 'v1', + scope: 'refs/heads/main', + repoId: '123', + }) + if (!pending) throw new Error('createUpload returned nothing') + const pendingUrl = `http://localhost:${port}/upload/${pending.id}?sig=${pending.capability}` vi.spyOn(storage.adapter, 'uploadStream').mockRejectedValue(new Error('storage unavailable')) const blockId = Buffer.from(`${randomUUID()}000000000001`).toString('base64') - const failed = await fetch(`${url}&comp=block&blockid=${encodeURIComponent(blockId)}`, { + const failed = await fetch(`${pendingUrl}&comp=block&blockid=${encodeURIComponent(blockId)}`, { method: 'PUT', body: 'part', }) @@ -125,5 +133,6 @@ test('upload capabilities stay out of request and error logs', async () => { expect(logged).toContain('storage unavailable') expect(logged).not.toContain('sig=') expect(logged).not.toContain(created.capability) + expect(logged).not.toContain(pending.capability) expect(logged).not.toContain(forged) }) diff --git a/tests/storage-lifecycle.test.ts b/tests/storage-lifecycle.test.ts index 7201cc01..6721b62c 100644 --- a/tests/storage-lifecycle.test.ts +++ b/tests/storage-lifecycle.test.ts @@ -122,21 +122,45 @@ describe('storage lifecycle reconciliation', () => { await adapter.uploadStream(`${authorizedFolder}/parts/0`, Readable.from('authorized')) await adapter.uploadStream(`${orphanedFolder}/parts/0`, Readable.from('orphaned')) + // Other failure-path fixtures may leave real orphans. Check the exact + // complete inventory, rather than assuming only our two folders exist. + const inventory = await adapter.listStorageFolders() + const locations = await db.selectFrom('storage_locations').select('folderName').execute() + const uploads = await db.selectFrom('uploads').select('folderName').execute() + const owners = new Set([...locations, ...uploads].map(({ folderName }) => folderName)) + const now = Date.now() + 25 * 60 * 60 * 1000 + const expectedOrphans = inventory.filter( + ({ folderName, updatedAt }) => + !owners.has(folderName) && updatedAt <= now - 24 * 60 * 60 * 1000, + ) + const expectedNames = new Set(expectedOrphans.map(({ folderName }) => folderName)) + expect(expectedNames.has(orphanedFolder)).toBe(true) + expect(expectedNames.has(authorizedFolder)).toBe(false) + const result = await reconcileOrphanedStorage({ db, adapter, gracePeriodHours: 24, - now: Date.now() + 25 * 60 * 60 * 1000, + now, }) expect(result).toMatchObject({ - inspectedFolders: expect.any(Number), - deletedFolders: 1, - deletedObjects: 1, + inspectedFolders: inventory.length, + deletedFolders: expectedOrphans.length, + deletedObjects: expectedOrphans.reduce((sum, folder) => sum + folder.objectCount, 0), + deletedBytes: expectedOrphans.reduce((sum, folder) => sum + folder.bytes, 0), failures: 0, }) expect(await adapter.countFilesInFolder(`${authorizedFolder}/parts`)).toBe(1) expect(await adapter.countFilesInFolder(`${orphanedFolder}/parts`)).toBe(0) + const after = await adapter.listStorageFolders() + expect(new Set(after.map(({ folderName }) => folderName))).toEqual( + new Set( + inventory + .filter(({ folderName }) => !expectedNames.has(folderName)) + .map(({ folderName }) => folderName), + ), + ) } finally { await db.deleteFrom('uploads').where('id', '=', uploadId).execute() await adapter.deleteFolder(authorizedFolder) diff --git a/tests/twirp-protobuf.test.ts b/tests/twirp-protobuf.test.ts index bb8727ec..c301ab02 100644 --- a/tests/twirp-protobuf.test.ts +++ b/tests/twirp-protobuf.test.ts @@ -15,6 +15,7 @@ const root = protobuf.parse( message CreateCacheEntryRequest { CacheMetadata metadata = 1; string key = 2; string version = 3; } message CreateCacheEntryResponse { bool ok = 1; string signed_upload_url = 2; string message = 3; } message FinalizeCacheEntryUploadRequest { CacheMetadata metadata = 1; string key = 2; int64 size_bytes = 3; string version = 4; } + message FinalizeCacheEntryUploadResponse { bool ok = 1; int64 entry_id = 2; } message GetCacheEntryDownloadURLRequest { CacheMetadata metadata = 1; string key = 2; repeated string restore_keys = 3; string version = 4; } message GetCacheEntryDownloadURLResponse { bool ok = 1; string signed_download_url = 2; string matched_key = 3; } `, @@ -24,6 +25,7 @@ const root = protobuf.parse( const CreateReq = root.lookupType('CreateCacheEntryRequest') const CreateRes = root.lookupType('CreateCacheEntryResponse') const FinalizeReq = root.lookupType('FinalizeCacheEntryUploadRequest') +const FinalizeRes = root.lookupType('FinalizeCacheEntryUploadResponse') const GetReq = root.lookupType('GetCacheEntryDownloadURLRequest') const GetRes = root.lookupType('GetCacheEntryDownloadURLResponse') @@ -95,3 +97,32 @@ test('protobuf FinalizeCacheEntryUpload decodes the body (missing upload → 404 // 404 (not 400) proves the protobuf body parsed and validated successfully. expect(response.status).toBe(404) }) + +test('protobuf acknowledgment returns the completed exact generation and restores its nonempty payload', async () => { + const key = `protobuf-complete-${crypto.randomUUID()}` + const created = await decode<{ signed_upload_url: string }>( + await post('CreateCacheEntry', CreateReq, { key, version: 'v1' }), + CreateRes, + ) + const url = new URL(created.signed_upload_url) + const stored = await fetch(url, { method: 'PUT', body: 'protobuf-payload' }) + expect(stored.status).toBe(201) + const response = await post('FinalizeCacheEntryUpload', FinalizeReq, { + key, + version: 'v1', + size_bytes: String(Buffer.byteLength('protobuf-payload')), + }) + expect(response.status).toBe(200) + expect(response.headers.get('content-type')).toContain('application/protobuf') + expect(await decode(response, FinalizeRes)).toEqual({ + ok: true, + entry_id: url.pathname.split('/').at(-1), + }) + const lookup = await decode<{ ok: boolean; signed_download_url: string }>( + await post('GetCacheEntryDownloadURL', GetReq, { key, version: 'v1' }), + GetRes, + ) + expect(lookup.ok).toBe(true) + const download = await fetch(lookup.signed_download_url) + expect(await download.text()).toBe('protobuf-payload') +}) diff --git a/tests/upload-authorization.test.ts b/tests/upload-authorization.test.ts index d37a65fb..0d7e4757 100644 --- a/tests/upload-authorization.test.ts +++ b/tests/upload-authorization.test.ts @@ -137,12 +137,18 @@ describe('upload URL authorization', () => { const key = `upload-auth-${crypto.randomUUID()}` const url = await createUpload(token, key) const chunks = [crypto.randomBytes(2048), crypto.randomBytes(1024)] + const ids = chunks.map((_, index) => blockId(index)) for (const [index, chunk] of chunks.entries()) { - const response = await put(withParams(url, { comp: 'block', blockid: blockId(index) }), chunk) + const response = await put(withParams(url, { comp: 'block', blockid: ids[index]! }), chunk) expect(response.status).toBe(201) } - expect(await put(withParams(url, { comp: 'blocklist' }))).toMatchObject({ status: 201 }) + const manifest = Buffer.from( + `${ids.map((id) => `${id}`).join('')}`, + ) + expect(await put(withParams(url, { comp: 'blocklist' }), manifest)).toMatchObject({ + status: 201, + }) expect(await finalize(token, key)).toBe(200) const downloaded = await downloadEntry(token, key) diff --git a/tests/upload-capability-migration.test.ts b/tests/upload-capability-migration.test.ts index ba78da40..0ce2183e 100644 --- a/tests/upload-capability-migration.test.ts +++ b/tests/upload-capability-migration.test.ts @@ -30,7 +30,7 @@ test('the upload capability migration adds and removes its column', async () => } try { - const latest = await migrator.migrateToLatest() + const latest = await migrator.migrateTo(MIGRATION) expect(latest.error).toBeUndefined() expect(await uploadColumns()).toContain('capabilityHash') diff --git a/tests/upload-fixture.ts b/tests/upload-fixture.ts new file mode 100644 index 00000000..ea07797d --- /dev/null +++ b/tests/upload-fixture.ts @@ -0,0 +1,37 @@ +import type { Readable } from 'node:stream' +import type { Storage } from '~/lib/storage' +import { Buffer } from 'node:buffer' +import { getDatabase } from '~/lib/db' + +export interface FixtureUpload { + id: number + capability: string +} + +/** Fixed-width opaque IDs give existing storage fixtures an explicit order. */ +export function stageFixturePart( + storage: Storage, + upload: FixtureUpload, + index: number, + body: Readable, +) { + const id = Buffer.from(String(index).padStart(12, '0')).toString('base64') + return storage.stageBlock(upload.id, upload.capability, id, body) +} + +export async function completeFixtureUpload(storage: Storage, upload: FixtureUpload) { + const db = await getDatabase() + const staged = await db + .selectFrom('upload_parts') + .select('blockId') + .where('uploadId', '=', upload.id) + .execute() + const ids = [...new Set(staged.map(({ blockId }) => blockId!))].toSorted((a, b) => + Buffer.from(a, 'base64').compare(Buffer.from(b, 'base64')), + ) + return storage.commitBlockList( + upload.id, + upload.capability, + ids.map((id) => ({ id, source: 'Latest' })), + ) +}