From c0b7ff15769d0d172ed85d343fba410250b20ed3 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 25 Sep 2026 22:25:44 +0900 Subject: [PATCH] fix(browser-transfer): allow maxClockSkewMs on session and capability lifetime ceilings (01-06) A server lifetime equal to the client ceiling was refused as soon as the device clock ran slightly behind, and the error did not read as a clock problem. Both ceilings now allow maxClockSkewMs (default 60 s), as image-cdn already does; the doc states the server-side lifetime conditions. Co-Authored-By: Claude Opus 5.5 --- .../presigned-transfer-and-image-cdn.md | 8 +++ .../presigned-capability-http-provider.ts | 14 ++++- .../resumable-upload/runtime-policy.ts | 9 +++ .../upload-response-validation.ts | 3 +- tests/unit/presigned-transfer-fixture.ts | 4 ++ tests/unit/presigned-transfer.test.ts | 28 +++++++++ .../unit/resumable-upload-runtime-fixture.ts | 1 + .../resumable-upload-runtime-recovery.test.ts | 59 +++++++++++++++++++ 8 files changed, 124 insertions(+), 2 deletions(-) diff --git a/docs/architecture/presigned-transfer-and-image-cdn.md b/docs/architecture/presigned-transfer-and-image-cdn.md index d729f8e7..168ea50b 100644 --- a/docs/architecture/presigned-transfer-and-image-cdn.md +++ b/docs/architecture/presigned-transfer-and-image-cdn.md @@ -164,6 +164,14 @@ URL을 발급하면 안 된다. - capability를 async 대기하는 동안 caller 입력과 dependency method를 snapshot한다. - 사용 전에 만료뿐 아니라 최소 잔여 lifetime도 검사한다. +- 기기 시계가 서버보다 `maxClockSkewMs`(기본 60초)까지 늦어도 수명 상한 검사는 + 거절하지 않는다. 서버는 session 수명을 `maxSessionLifetimeMs` 이하, capability + 수명을 `maxCapabilityTtlMs` 이하로 주면 된다(`upload-response-validation.ts` + `validateSession`, `presigned-capability-http-provider.ts` `maxClockSkewMs`). + 하한은 느슨하게 하지 않는다. 기기 시계가 빠르면 수명이 그만큼 짧아 보이므로 + 서버 capability 수명은 `minimumRemainingLifetimeMs + maxClockSkewMs`와 + `capabilityRefreshSkewMs + maxClockSkewMs`보다 길어야 한다. 기기 시계가 이보다 + 더 빠르면 그 기기에서는 capability가 만료로 보인다. - 만료/403은 임의 retry가 아니라 control plane의 새 capability 발급으로 복구한다. - ambiguous network failure 뒤 upload part를 새 bytes로 덮어쓰지 않는다. - client-side single-use map은 UX 최적화일 뿐이다. cross-tab/replay authority는 diff --git a/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts b/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts index d84343cb..3434a830 100644 --- a/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts +++ b/src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts @@ -87,6 +87,14 @@ export type PresignedCapabilityHttpProviderOptions = Readonly<{ * with a token that is predictably going to expire in flight. */ minimumRemainingLifetimeMs: number; + /** + * 01-06. How far the device clock may trail the server's. A capability is + * refused as too long-lived only past `maxCapabilityTtlMs` plus this. + * Default 60 s. The lower bound is not relaxed: a server lifetime must be at + * least `minimumRemainingLifetimeMs + maxClockSkewMs` to survive a device + * clock running that far ahead. + */ + maxClockSkewMs?: number; timeoutMs: number; maxCapabilityResponseBytes?: number; fetcher?: typeof fetch; @@ -143,6 +151,10 @@ export function createPresignedCapabilityHttpProvider( options.minimumRemainingLifetimeMs, "Presigned capability minimum remaining lifetime", ); + const maxClockSkewMs = options.maxClockSkewMs ?? 60_000; + if (!Number.isSafeInteger(maxClockSkewMs) || maxClockSkewMs < 0) { + throw new TypeError("Presigned capability clock skew is invalid."); + } if (minimumRemainingLifetimeMs > maxCapabilityTtlMs) { throw new TypeError( "Presigned capability minimum remaining lifetime exceeds its TTL.", @@ -267,7 +279,7 @@ export function createPresignedCapabilityHttpProvider( expected, hardMaxTransferBytes, hardMaxUploadResponseBytes, - maxCapabilityTtlMs, + maxCapabilityTtlMs: maxCapabilityTtlMs + maxClockSkewMs, minimumRemainingLifetimeMs, nowEpochMs: now(), allowedDataOrigins, diff --git a/src/adapters/browser-transfer/resumable-upload/runtime-policy.ts b/src/adapters/browser-transfer/resumable-upload/runtime-policy.ts index ef681ed6..926b444a 100644 --- a/src/adapters/browser-transfer/resumable-upload/runtime-policy.ts +++ b/src/adapters/browser-transfer/resumable-upload/runtime-policy.ts @@ -17,6 +17,11 @@ export type ResumableUploadRuntimePolicy = Readonly<{ maxRetryAfterMs: number; capabilityRefreshSkewMs: number; maxSessionLifetimeMs: number; + /** + * 01-06. How far the device clock may trail the server's. A session is + * refused only when it outlives `maxSessionLifetimeMs` by more than this. + */ + maxClockSkewMs: number; providerAttemptTimeoutMs: number; /** * 01-03. The slowest uplink a part PUT must survive. Its attempt deadline is @@ -48,6 +53,7 @@ const ABSOLUTE_LIMITS = Object.freeze({ maxRetryAfterMs: 60_000, maxCapabilityRefreshSkewMs: 5 * 60_000, maxSessionLifetimeMs: 7 * 24 * 60 * 60_000, + maxClockSkewMs: 5 * 60_000, maxProviderAttemptTimeoutMs: 2 * 60_000, }); @@ -67,6 +73,7 @@ const DEFAULT_POLICY: ResumableUploadRuntimePolicy = Object.freeze({ maxRetryAfterMs: 30_000, capabilityRefreshSkewMs: 5_000, maxSessionLifetimeMs: 24 * 60 * 60_000, + maxClockSkewMs: 60_000, providerAttemptTimeoutMs: 30_000, // 64 KiB/s (about 0.5 Mbit/s): a 5 MiB part gets 30 s + 80 s. minTransferBytesPerSecond: 64 * 1024, @@ -116,6 +123,8 @@ export function resolveResumableUploadRuntimePolicy( !positiveSafeInteger(policy.maxSessionLifetimeMs) || policy.maxSessionLifetimeMs > ABSOLUTE_LIMITS.maxSessionLifetimeMs || + !nonNegativeSafeInteger(policy.maxClockSkewMs) || + policy.maxClockSkewMs > ABSOLUTE_LIMITS.maxClockSkewMs || !positiveSafeInteger(policy.providerAttemptTimeoutMs) || policy.providerAttemptTimeoutMs > ABSOLUTE_LIMITS.maxProviderAttemptTimeoutMs || diff --git a/src/adapters/browser-transfer/resumable-upload/upload-response-validation.ts b/src/adapters/browser-transfer/resumable-upload/upload-response-validation.ts index 39cc537a..50651092 100644 --- a/src/adapters/browser-transfer/resumable-upload/upload-response-validation.ts +++ b/src/adapters/browser-transfer/resumable-upload/upload-response-validation.ts @@ -232,7 +232,8 @@ export function validateSession( if ( requireActiveExpiry && value.expiresAtEpochMs - now.value > - dependencies.policy.maxSessionLifetimeMs + dependencies.policy.maxSessionLifetimeMs + + dependencies.policy.maxClockSkewMs ) { return browserDataFailure("POLICY_REJECTED", "UPLOAD_SESSION"); } diff --git a/tests/unit/presigned-transfer-fixture.ts b/tests/unit/presigned-transfer-fixture.ts index 5ebc87eb..2a00bd8e 100644 --- a/tests/unit/presigned-transfer-fixture.ts +++ b/tests/unit/presigned-transfer-fixture.ts @@ -160,6 +160,7 @@ export function createHarness(input: Readonly<{ scheduler?: PresignedTransferExecutorOptions["scheduler"]; minTransferBytesPerSecond?: number; idleTimeoutMs?: number; + maxClockSkewMs?: number; observer?: Readonly<{ record(observation: BrowserDataObservation): void; }>; @@ -195,6 +196,9 @@ export function createHarness(input: Readonly<{ now, scheduler: input.scheduler, observer: input.observer, + ...(input.maxClockSkewMs === undefined + ? {} + : { maxClockSkewMs: input.maxClockSkewMs }), }); const executor = createPresignedTransferExecutor({ vault, diff --git a/tests/unit/presigned-transfer.test.ts b/tests/unit/presigned-transfer.test.ts index 34999ade..3468209e 100644 --- a/tests/unit/presigned-transfer.test.ts +++ b/tests/unit/presigned-transfer.test.ts @@ -69,6 +69,34 @@ describe("presigned transfer capability issuance and admission", () => { } }); + it.each([ + [500, true], + [501, false], + ] as const)( + "accepts a max-TTL capability from a server %i ms ahead: %s (01-06)", + async (skewMs, accepted) => { + const bytes = new Uint8Array([1, 2, 3]); + const payload = downloadCapabilityPayload(bytes, { + // The harness allows 60 s; the server clock runs `skewMs` ahead. + expiresAtEpochMs: NOW + skewMs + 60_000, + }); + const fetcher = vi.fn(async () => + jsonResponse(payload), + ) as unknown as typeof fetch; + const { provider } = createHarness({ fetcher, maxClockSkewMs: 500 }); + + const issued = await provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + + expect(issued.ok).toBe(accepted); + if (!accepted) { + expect(issued).toMatchObject({ error: { code: "POLICY_REJECTED" } }); + } + }, + ); + it("answers a refused capability envelope with a re-issuable recovery", async () => { // BT-PRE-04. A capability document the adapter will not accept is closed as // `POLICY_REJECTED`, and the caller's only way forward is a new capability. diff --git a/tests/unit/resumable-upload-runtime-fixture.ts b/tests/unit/resumable-upload-runtime-fixture.ts index 79e84b7d..23eb676b 100644 --- a/tests/unit/resumable-upload-runtime-fixture.ts +++ b/tests/unit/resumable-upload-runtime-fixture.ts @@ -209,6 +209,7 @@ export function runtimePolicy( maxRetryAfterMs: 100, capabilityRefreshSkewMs: 5, maxSessionLifetimeMs: 10_000, + maxClockSkewMs: 0, providerAttemptTimeoutMs: 100, ...overrides, }; diff --git a/tests/unit/resumable-upload-runtime-recovery.test.ts b/tests/unit/resumable-upload-runtime-recovery.test.ts index 66802b07..22e7a8e3 100644 --- a/tests/unit/resumable-upload-runtime-recovery.test.ts +++ b/tests/unit/resumable-upload-runtime-recovery.test.ts @@ -865,3 +865,62 @@ describe("upload() failure recovery maps to one caller action (01-05)", () => { if (!result.ok) expect(UPLOAD_ACTIONS.has(result.error.recovery)).toBe(true); }); }); + +describe("device clock skew on server lifetimes (01-06)", () => { + /** A server whose clock runs `skewMs` ahead and gives full-length sessions. */ + function skewedServer(skewMs: number, lifetimeMs: number) { + const harness = createControlHarness(); + const expiresAtEpochMs = 1_000 + skewMs + lifetimeMs; + const create = harness.control.createSession.bind(harness.control); + const status = harness.control.getStatus.bind(harness.control); + harness.control.createSession = async (input) => { + const created = await create(input); + return created.ok + ? browserDataSuccess({ ...created.value, expiresAtEpochMs }) + : created; + }; + harness.control.getStatus = async (input) => { + const read = await status(input); + return read.ok && read.value.state === "ACTIVE" + ? browserDataSuccess({ + ...read.value, + session: { ...read.value.session, expiresAtEpochMs }, + }) + : read; + }; + return harness; + } + + it.each([ + [500, true], + [501, false], + ] as const)( + "accepts a max-length session from a server %i ms ahead: %s", + async (skewMs, accepted) => { + const harness = skewedServer(skewMs, 10_000); + const runtime = createResumableUploadRuntime({ + controlPlane: harness.control, + partExecutor: executorFor(harness), + checkpoints: new MemoryCheckpointStore(), + mutationLock: noContentionLock, + crypto, + policy: runtimePolicy({ + maxRetries: 0, + maxSessionLifetimeMs: 10_000, + maxClockSkewMs: 500, + }), + now: () => 1_000, + sleep: async () => {}, + }); + + const result = await runtime.upload(request(`upload_key_skew_${skewMs}`)); + + expect(result.ok).toBe(accepted); + if (!accepted) { + expect(result).toMatchObject({ + error: { code: "POLICY_REJECTED", operation: "UPLOAD_SESSION" }, + }); + } + }, + ); +});