From 7d45be8712d5a87aa9f21442169d83784e145c62 Mon Sep 17 00:00:00 2001 From: Sterister Date: Mon, 19 Oct 2026 00:31:06 +0200 Subject: [PATCH] fix(media): an uploader checks the relay's upload status before trusting it A chunk of 0 looped forever, a huge chunk held the film in memory and a huge window opened a request (a thread on Kotlin) per piece. statusProblem checks chunk, window, received and landed; the client window is capped at 16. Same in MediaUploader, with tests on both sides. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 4 ++ .../no/zyon/shade/media/MediaUploader.kt | 32 +++++++++-- .../kotlin/no/zyon/shade/MediaUploaderTest.kt | 55 +++++++++++++++++++ packages/shade-media/src/client.ts | 12 +++- packages/shade-media/src/index.ts | 2 +- packages/shade-media/src/upload.ts | 17 ++++++ packages/shade-media/tests/upload.test.ts | 20 +++++++ 7 files changed, 133 insertions(+), 9 deletions(-) create mode 100644 android/shade-android/src/test/kotlin/no/zyon/shade/MediaUploaderTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 11599d0..8d0d2f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -132,6 +132,10 @@ New package **`@shade/media`** — see `docs/media.md`. ### Fixed +- An uploader (TS and Kotlin) trusted the relay's upload status: a `chunk` of + 0 looped forever, a huge one held the film in memory, a huge `window` opened + a request (a thread, on Kotlin) per piece. The status is now checked + (`statusProblem`) and the window capped at 16. - `shade media get` used the sealed file's `meta.name` as the output path, so whoever sealed a file chose where it was written (`../../.bashrc`). Names are now reduced to one safe path component. diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaUploader.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaUploader.kt index 428919c..3f4bcff 100644 --- a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaUploader.kt +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaUploader.kt @@ -16,6 +16,10 @@ import java.util.concurrent.Executors /** Files up to this size go up in one PUT; larger ones in pieces (mirror of `@shade/media` upload.ts). */ const val DEFAULT_CHUNK_BYTES = 16L * 1024 * 1024 const val OFFSET_HEADER = "x-shade-offset" +const val MAX_PIECE_BYTES = 64L * 1024 * 1024 + +/** Most pieces kept in flight, whatever window a relay offers. */ +const val MAX_CLIENT_WINDOW = 16 /** Failed tries in a row before a resumable upload gives up. */ private const val MAX_TRIES = 8 @@ -166,15 +170,33 @@ class MediaUploader( private val body: RangeSource, private val onProgress: ((Long, Long) -> Unit)?, ) { + /** + * How far the relay got. Checked before it is trusted (mirror of TS + * `statusProblem`): a zero chunk would never get through the file, a + * huge one would hold it all in memory, a huge window a thread per piece. + */ private inner class Status(json: JSONObject) { - val chunk = json.getLong("chunk") - val window = json.optInt("window", 1).coerceAtLeast(1) - val received = json.getLong("received") - val landed: Set = json.optJSONArray("landed")?.let { a -> (0 until a.length()).map { a.getLong(it) }.toSet() } ?: emptySet() val complete = json.optBoolean("complete", false) + val chunk = if (complete) 0L else json.optLong("chunk", -1) + val window = json.optInt("window", 1) + val received = if (complete) size else json.optLong("received", -1) + val landed: Set = if (complete) emptySet() else json.optJSONArray("landed")?.let { a -> + (0 until a.length()).map { i -> (a.opt(i) as? Number)?.toLong()?.takeIf { it >= 0 } ?: unusable("landed is not a list of piece numbers") }.toSet() + } ?: emptySet() + + init { + if (!complete) { + if (chunk < 1024 * 1024 || chunk > MAX_PIECE_BYTES) unusable("chunk $chunk out of range") + if (window < 1) unusable("window $window out of range") + if (received < 0 || received > size) unusable("received $received out of range") + } + } + fun has(offset: Long) = offset < received || (offset / chunk) in landed } + private fun unusable(why: String): Nothing = throw MediaUploadException("upload failed: the relay's upload status is unusable: $why") + /** A request that got no answer (refused, reset, timed out) is worth repeating. */ private fun send(method: String, headers: Map, body: ByteArray?): Answer = try { @@ -257,7 +279,7 @@ class MediaUploader( return } chunk = opened.chunk - val window = opened.window + val window = opened.window.coerceAtMost(MAX_CLIENT_WINDOW) var acked = 0L var complete = false val todo = ArrayDeque() diff --git a/android/shade-android/src/test/kotlin/no/zyon/shade/MediaUploaderTest.kt b/android/shade-android/src/test/kotlin/no/zyon/shade/MediaUploaderTest.kt new file mode 100644 index 0000000..667fa9e --- /dev/null +++ b/android/shade-android/src/test/kotlin/no/zyon/shade/MediaUploaderTest.kt @@ -0,0 +1,55 @@ +package no.zyon.shade + +import com.sun.net.httpserver.HttpServer +import no.zyon.shade.media.ByteArraySource +import no.zyon.shade.media.DEFAULT_CHUNK_BYTES +import no.zyon.shade.media.MediaOwner +import no.zyon.shade.media.MediaSealer +import no.zyon.shade.media.MediaUploadException +import no.zyon.shade.media.MediaUploader +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test +import java.net.InetSocketAddress +import java.util.concurrent.atomic.AtomicInteger + +/** What the uploader does with a relay that answers nonsense; the real conversation is `MediaLiveTest`. */ +class MediaUploaderTest { + + private fun relay(answer: String, calls: AtomicInteger): HttpServer = + HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/") { ex -> + calls.incrementAndGet() + ex.requestBody.readBytes() + val b = answer.toByteArray() + ex.responseHeaders.add("content-type", "application/json") + ex.sendResponseHeaders(201, b.size.toLong()) + ex.responseBody.use { it.write(b) } + } + start() + } + + @Test + fun anUnusableUploadStatusIsRefusedAtOnceNotLoopedOn() { + val (sealed, result) = MediaSealer.sealBytes(ByteArray(DEFAULT_CHUNK_BYTES.toInt() + 4096)) + for (bad in listOf( + """{"chunk":0,"received":0}""", + """{"chunk":${64L * 1024 * 1024 * 4},"received":0}""", + """{"chunk":${DEFAULT_CHUNK_BYTES},"received":-1}""", + """{"chunk":${DEFAULT_CHUNK_BYTES},"received":0,"window":0}""", + """{"chunk":${DEFAULT_CHUNK_BYTES},"received":0,"landed":["x"]}""", + )) { + val calls = AtomicInteger() + val server = relay(bad, calls) + try { + val up = MediaUploader("http://127.0.0.1:${server.address.port}", MediaOwner.generate()) + val e = assertThrows(MediaUploadException::class.java) { up.putSealed(result, ByteArraySource(sealed)) } + assertTrue(bad, e.message!!.contains("unusable")) + assertEquals(bad, 1, calls.get()) + } finally { + server.stop(0) + } + } + } +} diff --git a/packages/shade-media/src/client.ts b/packages/shade-media/src/client.ts index 7293e07..897cdd9 100644 --- a/packages/shade-media/src/client.ts +++ b/packages/shade-media/src/client.ts @@ -14,7 +14,7 @@ import type { OwnerKey } from './owner.js'; import { MediaReader, sealMediaBytes } from './sealed.js'; import type { MediaMeta, ReaderOptions, SealOptions, SealResult } from './sealed.js'; import { HttpRangeSource } from './source.js'; -import { DEFAULT_CHUNK_BYTES, OFFSET_HEADER } from './upload.js'; +import { DEFAULT_CHUNK_BYTES, MAX_CLIENT_WINDOW, OFFSET_HEADER, statusProblem } from './upload.js'; export function mediaUrl(server: string, mediaId: Uint8Array): string { return `${server.replace(/\/$/, '')}/v1/media/${toHex(mediaId)}`; @@ -162,7 +162,13 @@ export class MediaClient { }, }); if (res.status !== 200 && res.status !== 201) return fail(res, 'start'); - return (await res.json()) as Status; + const st = (await res.json().catch(() => { + throw new Transient("start: the relay's answer is not JSON"); + })) as Status; + if (st.complete === true) return st; + const problem = statusProblem(st, size); + if (problem !== null) throw new Error(`upload failed: the relay's upload status is unusable: ${problem}`); + return st; }; const has = (st: Status, offset: number) => offset < st.received || (st.landed ?? []).includes(offset / st.chunk); @@ -172,7 +178,7 @@ export class MediaClient { return; } const { chunk } = opened; - const window = Math.max(1, opened.window ?? 1); + const window = Math.min(MAX_CLIENT_WINDOW, Math.max(1, opened.window ?? 1)); let acked = 0; let complete = false; const todo: number[] = []; diff --git a/packages/shade-media/src/index.ts b/packages/shade-media/src/index.ts index cd18d21..078fcad 100644 --- a/packages/shade-media/src/index.ts +++ b/packages/shade-media/src/index.ts @@ -24,7 +24,7 @@ export { MediaClient, openGrant, openAlbum, readAlbum, mediaUrl } from './client export { ALBUM_KIND, ALBUM_MIME, MAX_ALBUM_ITEMS, encodeAlbum, parseAlbum, isAlbum, albumMeta, isMediaGrant } from './album.js'; export type { Album } from './album.js'; export type { PutOptions } from './client.js'; -export { MAX_PIECE_BYTES, DEFAULT_CHUNK_BYTES, MAX_UPLOAD_BYTES, OFFSET_HEADER, UPLOAD_WINDOW, chunkFor } from './upload.js'; +export { MAX_PIECE_BYTES, DEFAULT_CHUNK_BYTES, MAX_UPLOAD_BYTES, MAX_CLIENT_WINDOW, OFFSET_HEADER, UPLOAD_WINDOW, chunkFor, statusProblem } from './upload.js'; export { LivePublisher, LiveSubscriber, epochKeys, chainStep, MAX_SKIP, MAX_SKIPPED_KEYS } from './live/channel.js'; export type { FrameOptions, PublisherOptions, GrantOptions, ReceivedFrame } from './live/channel.js'; export { encodeContent, decodeContent, decodeFrame, FLAG_STICKY, FLAG_KEYFRAME, FLAG_END } from './live/frame.js'; diff --git a/packages/shade-media/src/upload.ts b/packages/shade-media/src/upload.ts index daad005..8fcbc9a 100644 --- a/packages/shade-media/src/upload.ts +++ b/packages/shade-media/src/upload.ts @@ -40,6 +40,23 @@ export const OFFSET_HEADER = 'x-shade-offset'; /** Pieces past `received` a relay takes at once — what an upload holds in its memory, at most. */ export const UPLOAD_WINDOW = 4; +/** Most pieces a client keeps in flight, whatever window a relay offers. */ +export const MAX_CLIENT_WINDOW = 16; + +/** + * Why a relay's upload status cannot be used, or null. A client checks it + * before trusting it: a zero chunk would never get through the file, a huge + * one would hold it all in memory, a huge window opens a request per piece. + */ +export function statusProblem(st: { chunk?: unknown; window?: unknown; received?: unknown; landed?: unknown }, size: number): string | null { + const int = (v: unknown) => typeof v === 'number' && Number.isSafeInteger(v); + if (!int(st.chunk) || (st.chunk as number) < MiB || (st.chunk as number) > MAX_PIECE_BYTES) return `chunk ${String(st.chunk)} out of range`; + if (st.window !== undefined && (!int(st.window) || (st.window as number) < 1)) return `window ${String(st.window)} out of range`; + if (!int(st.received) || (st.received as number) < 0 || (st.received as number) > size) return `received ${String(st.received)} out of range`; + if (st.landed !== undefined && (!Array.isArray(st.landed) || !st.landed.every((n) => int(n) && n >= 0))) return 'landed is not a list of piece numbers'; + return null; +} + /** The piece size for a file of `size` bytes: the default, or larger so it fits in 10 000 pieces. */ export function chunkFor(size: number): number { const need = Math.ceil(size / MAX_PIECES / MiB) * MiB; diff --git a/packages/shade-media/tests/upload.test.ts b/packages/shade-media/tests/upload.test.ts index 42858d0..840df64 100644 --- a/packages/shade-media/tests/upload.test.ts +++ b/packages/shade-media/tests/upload.test.ts @@ -202,6 +202,26 @@ describe('pieces', () => { expect((await piece(4 * chunk)).status).toBe(404); }); + test('a relay whose upload status is unusable is refused at once, not looped on', async () => { + const bytes = new Uint8Array(DEFAULT_CHUNK_BYTES + 4096); + const { result, bytes: sealed } = await sealMediaBytes(bytes); + for (const bad of [ + { chunk: 0, received: 0 }, + { chunk: MAX_PIECE_BYTES * 4, received: 0 }, + { chunk: DEFAULT_CHUNK_BYTES, received: -1 }, + { chunk: DEFAULT_CHUNK_BYTES, received: 0, window: 0 }, + { chunk: DEFAULT_CHUNK_BYTES, received: 0, landed: ['x'] }, + ]) { + let calls = 0; + const relay = (async () => { + calls++; + return Response.json({ id: 'x', size: result.sealedSize, ...bad }, { status: 201 }); + }) as unknown as typeof fetch; + await expect(new MediaClient('http://relay', OwnerKey.generate(), { fetch: relay }).putSealed(result, sealed)).rejects.toThrow(/unusable/); + expect(calls).toBe(1); + } + }); + test('a single PUT holds one piece at most; bigger files are told to go up in pieces', async () => { const { app } = serve(new MemoryMediaStore()); const owner = OwnerKey.generate();