vomebook commited on
Commit ·
da87c58
1
Parent(s): 325a518
Allow Reader PDF documents up to 2 GiB
Browse filesFiles changed (10)
- Dockerfile+1
- backend/app.py+11-9
- static/reader/core/reader-security.js+3-2
- static/reader/pdf/reader-pdf-engine.mjs+6-6
- static/reader/pdf/reader-v3.mjs+2-1
- tests/test_async_proxy.py+67-47
- tests/test_dataset_primary_policy.mjs+4-1
- tests/test_reader_pdf_range_transport.mjs+15-1
- tests/test_static_contract.py+1
- typings/reader-globals.d.ts+1-1
48 unmodified lines49505152535448 unmodified lines&& node scripts/check_search_filter_equality_baseline.mjs \&& node scripts/check_search_folder_merge_baseline.mjs \&& node --test tests/test_tap_contracts.mjs \&& node scripts/check_download_controller_coverage.mjs \&& printf 'static gate tests passed\n' >/check/static-gate-test-ok48 unmodified lines4950515253545548 unmodified lines&& node scripts/check_search_filter_equality_baseline.mjs \&& node scripts/check_search_folder_merge_baseline.mjs \&& node --test tests/test_tap_contracts.mjs \&& node tests/test_dataset_primary_policy.mjs \&& node scripts/check_download_controller_coverage.mjs \&& printf 'static gate tests passed\n' >/check/static-gate-test-ok
1621 unmodified lines162216231624162516261627162816291630401 unmodified lines2032203320342035203620372038342 unmodified lines23812382238323842385238661 unmodified lines2448244924502451245224532 unmodified lines2456245724582459246024612462246324642465246639 unmodified lines25062507250825092510251125121621 unmodified lines"X-Content-Type-Options": "nosniff",}READER_DOCUMENT_MAX_BYTES = 512 * 1024 * 1024# Total size accepted for a PDF whose bounded Range reads are proxied. Each# response body still obeys READER_DOCUMENT_MAX_BYTES; complete bodies keep it.READER_PDF_RANGE_MAX_BYTES = 1024 * 1024 * 1024READER_RESOURCE_MAX_ARCHIVE_BYTES = 512 * 1024 * 1024READER_RESOURCE_MAX_BYTES = 64 * 1024 * 1024READER_BUCKET_CACHE_TTL_SECONDS = 3600401 unmodified linesvalidation_scope=(validate_reader_bucket_redirect_url, source_url),cache_control=reader_bucket_cache_control(resource_path),max_bytes=(None if media_type.startswith(("audio/", "video/")) elseREADER_DOCUMENT_MAX_BYTES if suffix in {"pdf", "djvu"} else READER_RESOURCE_MAX_BYTES),media_type=media_type,**integrity,)342 unmodified linesexcept ValueError as exc:return JSONResponse({"error": str(exc)}, status_code=403)source_type = READER_RESOURCE_TYPES.get(unquote(urlparse(target_url).path).rsplit(".", 1)[-1].lower(), "")if source_type.startswith(("audio/", "video/")):return await stream_reader_document(request, target_url, media_type=source_type)return await stream_reader_document(request, target_url)61 unmodified lines# Native media is streamed, not parsed or buffered as a complete document.# Bound transport memory and idle time instead of rejecting large recordings.is_media_stream = bool(media_type and media_type.startswith(("audio/", "video/")))if max_bytes is None and not is_media_stream:max_bytes = READER_DOCUMENT_MAX_BYTESforwarded_headers = {2 unmodified linesif name in request.headers}range_header = forwarded_headers.get("Range")bounded_range = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_header or "")total_limit = max_bytesif (max_bytes is not None and bounded_range and not is_media_streamand (urlparse(target_url).path.lower().endswith(".pdf") or media_type == "application/pdf")):total_limit = max(max_bytes, READER_PDF_RANGE_MAX_BYTES)# Conditional requests must reach the origin: a cached partial body cannot# represent a 200/304 decision made against a different validator.has_conditionals = any(39 unmodified linesupstream = lease.response = await open_download_response(app.state.http_session,target_url,aiohttp.ClientTimeout(total=None if is_media_stream else 180, connect=15, sock_read=60),method=request.method,request_headers=forwarded_headers,url_validator=url_validator,1621 unmodified lines162216231624162516261627162816291630401 unmodified lines20322033203420352036203720382039342 unmodified lines2382238323842385238623872388238961 unmodified lines24512452245324542455245624572 unmodified lines246024612462246324642465246639 unmodified lines2506250725082509251025112512251325141621 unmodified lines"X-Content-Type-Options": "nosniff",}READER_DOCUMENT_MAX_BYTES = 512 * 1024 * 1024# PDFs have their own limit for both complete bodies and range totals. Other# document formats retain their existing limits.READER_PDF_MAX_BYTES = 2 * 1024 * 1024 * 1024READER_RESOURCE_MAX_ARCHIVE_BYTES = 512 * 1024 * 1024READER_RESOURCE_MAX_BYTES = 64 * 1024 * 1024READER_BUCKET_CACHE_TTL_SECONDS = 3600401 unmodified linesvalidation_scope=(validate_reader_bucket_redirect_url, source_url),cache_control=reader_bucket_cache_control(resource_path),max_bytes=(None if media_type.startswith(("audio/", "video/")) elseREADER_PDF_MAX_BYTES if suffix == "pdf" elseREADER_DOCUMENT_MAX_BYTES if suffix == "djvu" else READER_RESOURCE_MAX_BYTES),media_type=media_type,**integrity,)342 unmodified linesexcept ValueError as exc:return JSONResponse({"error": str(exc)}, status_code=403)source_type = READER_RESOURCE_TYPES.get(unquote(urlparse(target_url).path).rsplit(".", 1)[-1].lower(), "")if source_type == "application/pdf":return await stream_reader_document(request, target_url, max_bytes=READER_PDF_MAX_BYTES)if source_type.startswith(("audio/", "video/")):return await stream_reader_document(request, target_url, media_type=source_type)return await stream_reader_document(request, target_url)61 unmodified lines# Native media is streamed, not parsed or buffered as a complete document.# Bound transport memory and idle time instead of rejecting large recordings.is_media_stream = bool(media_type and media_type.startswith(("audio/", "video/")))is_pdf = media_type == "application/pdf" or unquote(urlparse(target_url).path).lower().endswith(".pdf")if max_bytes is None and not is_media_stream:max_bytes = READER_DOCUMENT_MAX_BYTESforwarded_headers = {2 unmodified linesif name in request.headers}range_header = forwarded_headers.get("Range")total_limit = max_bytes# Conditional requests must reach the origin: a cached partial body cannot# represent a 200/304 decision made against a different validator.has_conditionals = any(39 unmodified linesupstream = lease.response = await open_download_response(app.state.http_session,target_url,# A fixed 180-second total can truncate a valid multi-gigabyte PDF# on a slow connection; retain connect and idle-read timeouts.aiohttp.ClientTimeout(total=None if is_media_stream or is_pdf else 180, connect=15, sock_read=60),method=request.method,request_headers=forwarded_headers,url_validator=url_validator,
1 unmodified line234567891 unmodified line"use strict";const LIMITS = Object.freeze({documentBytes: 512 * 1024 * 1024,// PDF.js range transport only: demanded chunks are read, not the body.pdfRangeDocumentBytes: 1024 * 1024 * 1024,archiveCompressedBytes: 512 * 1024 * 1024,archiveExpandedBytes: 1536 * 1024 * 1024,archiveEntries: 20000,1 unmodified line23456789101 unmodified line"use strict";const LIMITS = Object.freeze({documentBytes: 512 * 1024 * 1024,// PDF is distinct from DjVu and other document formats. Range reads remain// preferred for large files to avoid downloading the entire body at once.pdfDocumentBytes: 2 * 1024 * 1024 * 1024,archiveCompressedBytes: 512 * 1024 * 1024,archiveExpandedBytes: 1536 * 1024 * 1024,archiveEntries: 20000,
26 unmodified lines2728293031323334200 unmodified lines23523623723823924024124245 unmodified lines28828929029129229329429526 unmodified linesconst documentOptions = options(url);readerContext.openPdfRangeTask(pdfjs, documentOptions, {signal:owner.signal, readBytes:VoiceOfMLReaderSecurity.readBytes, initial,limit:VoiceOfMLReaderSecurity.LIMITS.documentBytes,rangeLimit:VoiceOfMLReaderSecurity.LIMITS.pdfRangeDocumentBytes,boundedMetadata: !!documentOptions.worker?.readerFirstPageWorker,ratePriority: (begin,end) => readerContext.pdfFetchPolicy?.prioritizeRange?.(begin,end,url),canPrefetchOpening: () => !!readerContext.pdfV3Manifest && readerContext.readerRestorationLoaded &&200 unmodified lines// Keep it owned while engine preparation is pending and consume it only once.let initial = readerContext.preparePdfInitialRange({url:proxyUrl, rangeChunkSize:262144}, {signal:AbortSignal.any([owner.signal, readerContext.readerAbortController.signal]),readBytes:VoiceOfMLReaderSecurity.readBytes, limit:VoiceOfMLReaderSecurity.LIMITS.documentBytes,rangeLimit:VoiceOfMLReaderSecurity.LIMITS.pdfRangeDocumentBytes,canPrefetchFirstPage: () => pageOneKnown && !owner.signal.aborted &&navigation === readerContext.readerRuntime?.currentGeneration("navigation")});45 unmodified linesif (initial !== pending) return null;initial = readerContext.preparePdfInitialRange({url:proxyUrl, rangeChunkSize:262144}, {signal:AbortSignal.any([owner.signal, readerContext.readerAbortController.signal]),readBytes:VoiceOfMLReaderSecurity.readBytes, limit:VoiceOfMLReaderSecurity.LIMITS.documentBytes,rangeLimit:VoiceOfMLReaderSecurity.LIMITS.pdfRangeDocumentBytes,canPrefetchFirstPage: () => pageOneKnown && !owner.signal.aborted &&navigation === readerContext.readerRuntime?.currentGeneration("navigation")});26 unmodified lines2728293031323334200 unmodified lines23523623723823924024124245 unmodified lines28828929029129229329429526 unmodified linesconst documentOptions = options(url);readerContext.openPdfRangeTask(pdfjs, documentOptions, {signal:owner.signal, readBytes:VoiceOfMLReaderSecurity.readBytes, initial,limit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,rangeLimit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,boundedMetadata: !!documentOptions.worker?.readerFirstPageWorker,ratePriority: (begin,end) => readerContext.pdfFetchPolicy?.prioritizeRange?.(begin,end,url),canPrefetchOpening: () => !!readerContext.pdfV3Manifest && readerContext.readerRestorationLoaded &&200 unmodified lines// Keep it owned while engine preparation is pending and consume it only once.let initial = readerContext.preparePdfInitialRange({url:proxyUrl, rangeChunkSize:262144}, {signal:AbortSignal.any([owner.signal, readerContext.readerAbortController.signal]),readBytes:VoiceOfMLReaderSecurity.readBytes, limit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,rangeLimit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,canPrefetchFirstPage: () => pageOneKnown && !owner.signal.aborted &&navigation === readerContext.readerRuntime?.currentGeneration("navigation")});45 unmodified linesif (initial !== pending) return null;initial = readerContext.preparePdfInitialRange({url:proxyUrl, rangeChunkSize:262144}, {signal:AbortSignal.any([owner.signal, readerContext.readerAbortController.signal]),readBytes:VoiceOfMLReaderSecurity.readBytes, limit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,rangeLimit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,canPrefetchFirstPage: () => pageOneKnown && !owner.signal.aborted &&navigation === readerContext.readerRuntime?.currentGeneration("navigation")});
25 unmodified lines2627282930313225 unmodified linesref.path.split("/").some(part => !part || part === "." || part === "..") ||/[\\%?#\x00-\x1f\x7f\p{Cs}]/u.test(ref.path) || !/\.(?:pdf|djvu)$/i.test(ref.path) ||typeof ref.revision !== "string" || !/^[0-9a-f]{40}$/.test(ref.revision) ||!sha(ref.sha256) || !integer(ref.bytes) || ref.bytes > 512 * 1024 * 1024 ||(sourceKey !== undefined && sourceKey !== ref.repo + "\0" + ref.path) ||(sourceSha !== undefined && sourceSha !== ref.sha256) ||(expectedKind !== undefined && !ref.path.toLowerCase().endsWith("." + expectedKind))) invalid();25 unmodified lines262728293031323325 unmodified linesref.path.split("/").some(part => !part || part === "." || part === "..") ||/[\\%?#\x00-\x1f\x7f\p{Cs}]/u.test(ref.path) || !/\.(?:pdf|djvu)$/i.test(ref.path) ||typeof ref.revision !== "string" || !/^[0-9a-f]{40}$/.test(ref.revision) ||!sha(ref.sha256) || !integer(ref.bytes) ||ref.bytes > (/\.pdf$/i.test(ref.path) ? 2 * 1024 * 1024 * 1024 : 512 * 1024 * 1024) ||(sourceKey !== undefined && sourceKey !== ref.repo + "\0" + ref.path) ||(sourceSha !== undefined && sourceSha !== ref.sha256) ||(expectedKind !== undefined && !ref.path.toLowerCase().endsWith("." + expectedKind))) invalid();
1125 unmodified lines1126112711281129113011311132113310 unmodified lines114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188529 unmodified lines17181719172017211722172317246 unmodified lines173117321733173417351736173717387 unmodified lines174617471748174917501751175217531754175517561757175817596 unmodified lines17661767176817691770177117721125 unmodified linespath = "derived/test/" + "a" * 32 + "/document.pdf"for status, headers, expected in ((206, {"Content-Range": "invalid"}, 502),(206, {"Content-Range": f"bytes 0-1/{app.READER_DOCUMENT_MAX_BYTES + 1}"}, 413),(200, {"Content-Length": str(app.READER_DOCUMENT_MAX_BYTES + 1)}, 413),(200, {"Content-Encoding": "gzip"}, 502),(404, {}, 404),):10 unmodified linesawait app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={}))self.assertEqual(semaphore._value, 1)async def test_large_pdf_admits_bounded_ranges_but_not_complete_bodies(self):# PDF.js range transport reads demanded chunks of a large original PDF;# complete or open-ended bodies keep the document bound.large = app.READER_DOCUMENT_MAX_BYTES + 100over = app.READER_PDF_RANGE_MAX_BYTES + 1url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large.pdf"for forwarded, status, headers, expected in (({"Range": "bytes=0-1"}, 206, {"Content-Length": "2", "Content-Range": f"bytes 0-1/{large}"}, 206),({"Range": f"bytes={large - 2}-{large - 1}"}, 206,{"Content-Length": "2", "Content-Range": f"bytes {large - 2}-{large - 1}/{large}"}, 206),({"Range": "bytes=0-1"}, 206, {"Content-Length": "2", "Content-Range": f"bytes 0-1/{over}"}, 413),({"Range": "bytes=0-"}, 206, {"Content-Length": "2", "Content-Range": f"bytes 0-1/{large}"}, 413),({}, 200, {"Content-Length": str(large)}, 413),):for source in ("bucket", "original"):with self.subTest(range=forwarded, total=headers.get("Content-Range"), source=source):upstream = FakeResponse(status, headers, chunks=(b"ab",))app.app.state.http_session = FakeSession([upstream])semaphore = app.app.state.upstream_semaphore = asyncio.Semaphore(1)app.app.state.reader_range_cache = OrderedDict()app.app.state.reader_range_cache_bytes = 0request = SimpleNamespace(method="GET", headers=forwarded)if source == "bucket":response = await app.api_reader_bucket_resource("derived/test/" + "a" * 32 + "/document.pdf", request)else:response = await app.api_reader_content(request, url=url, id=None)self.assertEqual(response.status_code, expected)if expected == 206:self.assertEqual(b"".join([chunk async for chunk in response.body_iterator]), b"ab")self.assertEqual(response.headers["Cache-Control"], "no-store")self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)# Non-PDF documents retain the ordinary total bound for ranges too.upstream = FakeResponse(206, {"Content-Length": "2", "Content-Range": f"bytes 0-1/{large}"}, chunks=(b"ab",))app.app.state.http_session = FakeSession([upstream])app.app.state.upstream_semaphore = asyncio.Semaphore(1)response = await app.api_reader_content(SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"}),url="https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large.txt", id=None)self.assertEqual(response.status_code, 413)async def test_bucket_pdf_redirect_cannot_switch_to_another_hf_source(self):path = "derived/test/" + "a" * 32 + "/document.pdf"529 unmodified linesself.assertEqual(semaphore._value, 1)async def test_reader_content_rejects_oversized_content_length_before_streaming(self):upstream = FakeResponse(200, {"Content-Length": str(app.READER_DOCUMENT_MAX_BYTES + 1)}, chunks=(b"not-read",))semaphore = asyncio.Semaphore(1)app.app.state.http_session = FakeSession([upstream])app.app.state.upstream_semaphore = semaphore6 unmodified linesself.assertEqual(semaphore._value, 1)async def test_reader_content_rejects_oversized_range_total(self):old_limit = app.READER_DOCUMENT_MAX_BYTESapp.READER_DOCUMENT_MAX_BYTES = 3upstream = FakeResponse(206, {"Content-Length": "1","Content-Range": "bytes 0-0/4",7 unmodified lines"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf",)finally:app.READER_DOCUMENT_MAX_BYTES = old_limitself.assertEqual(response.status_code, 413)self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)async def test_reader_content_enforces_actual_stream_limit_and_releases(self):old_limit = app.READER_DOCUMENT_MAX_BYTESapp.READER_DOCUMENT_MAX_BYTES = 3upstream = FakeResponse(200, {}, chunks=(b"ab", b"cd"))semaphore = asyncio.Semaphore(1)app.app.state.http_session = FakeSession([upstream])6 unmodified lineswith self.assertRaises(app.ReaderDocumentLimitError):[chunk async for chunk in response.body_iterator]finally:app.READER_DOCUMENT_MAX_BYTES = old_limitself.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)1125 unmodified lines1126112711281129113011311132113310 unmodified lines11441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208529 unmodified lines17381739174017411742174317446 unmodified lines175117521753175417551756175717587 unmodified lines176617671768176917701771177217731774177517761777177817796 unmodified lines17861787178817891790179117921125 unmodified linespath = "derived/test/" + "a" * 32 + "/document.pdf"for status, headers, expected in ((206, {"Content-Range": "invalid"}, 502),(206, {"Content-Range": f"bytes 0-1/{app.READER_PDF_MAX_BYTES + 1}"}, 413),(200, {"Content-Length": str(app.READER_PDF_MAX_BYTES + 1)}, 413),(200, {"Content-Encoding": "gzip"}, 502),(404, {}, 404),):10 unmodified linesawait app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={}))self.assertEqual(semaphore._value, 1)async def test_pdf_limit_for_body_head_and_all_range_forms(self):limit = 2 * 1024 * 1024 * 1024self.assertEqual(app.READER_PDF_MAX_BYTES, limit)url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large.pdf"for total in (1_610_000_000, limit, limit + 1):allowed = total <= limitfor method, forwarded, status, headers in (("HEAD", {}, 200, {"Content-Length": str(total)}),("GET", {}, 200, {"Content-Length": str(total)}),("GET", {"Range": "bytes=0-1"}, 206,{"Content-Length": "2", "Content-Range": f"bytes 0-1/{total}"}),("GET", {"Range": f"bytes={total - 2}-"}, 206,{"Content-Length": "2", "Content-Range": f"bytes {total - 2}-{total - 1}/{total}"}),("GET", {"Range": "bytes=-2"}, 206,{"Content-Length": "2", "Content-Range": f"bytes {total - 2}-{total - 1}/{total}"}),("GET", {"Range": f"bytes={total}-"}, 416,{"Content-Length": "0", "Content-Range": f"bytes */{total}"}),):for source in ("bucket", "original"):with self.subTest(total=total, method=method, range=forwarded, source=source):upstream = FakeResponse(status, headers, chunks=(b"a", b"b") if status != 416 else ())session = app.app.state.http_session = FakeSession([upstream])semaphore = app.app.state.upstream_semaphore = asyncio.Semaphore(1)app.app.state.reader_range_cache = OrderedDict()app.app.state.reader_range_cache_bytes = 0request = SimpleNamespace(method=method, headers=forwarded)if source == "bucket":response = await app.api_reader_bucket_resource("derived/test/" + "a" * 32 + "/document.pdf", request)else:response = await app.api_reader_content(request, url=url, id=None)self.assertEqual(response.status_code, status if allowed else 413)self.assertIsNone(session.urls[0][1]["timeout"].total)self.assertEqual(session.urls[0][1]["timeout"].sock_read, 60)if allowed and method == "GET":self.assertEqual(b"".join([chunk async for chunk in response.body_iterator]),b"" if status == 416 else b"ab")self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)# Other document types do not inherit the PDF allowance.for suffix in ("djvu", "txt"):total = app.READER_DOCUMENT_MAX_BYTES + 1upstream = FakeResponse(206, {"Content-Length": "2", "Content-Range": f"bytes 0-1/{total}"})app.app.state.http_session = FakeSession([upstream])app.app.state.upstream_semaphore = asyncio.Semaphore(1)response = await app.api_reader_content(SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"}),url=f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large.{suffix}", id=None)self.assertEqual(response.status_code, 413)self.assertTrue(upstream.released)# Bucket DjVu and page images retain their own lower body bounds too.for path, size in ((f"objects/aa/{'a' * 64}/{'b' * 16}/document.djvu", app.READER_DOCUMENT_MAX_BYTES + 1),(f"objects/aa/{'a' * 64}/{'b' * 16}/pages/page-000002.webp", app.READER_RESOURCE_MAX_BYTES + 1)):upstream = FakeResponse(200, {"Content-Length": str(size)})app.app.state.http_session = FakeSession([upstream])semaphore = app.app.state.upstream_semaphore = asyncio.Semaphore(1)response = await app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={}))self.assertEqual(response.status_code, 413)self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)async def test_bucket_pdf_redirect_cannot_switch_to_another_hf_source(self):path = "derived/test/" + "a" * 32 + "/document.pdf"529 unmodified linesself.assertEqual(semaphore._value, 1)async def test_reader_content_rejects_oversized_content_length_before_streaming(self):upstream = FakeResponse(200, {"Content-Length": str(app.READER_PDF_MAX_BYTES + 1)}, chunks=(b"not-read",))semaphore = asyncio.Semaphore(1)app.app.state.http_session = FakeSession([upstream])app.app.state.upstream_semaphore = semaphore6 unmodified linesself.assertEqual(semaphore._value, 1)async def test_reader_content_rejects_oversized_range_total(self):old_limit = app.READER_PDF_MAX_BYTESapp.READER_PDF_MAX_BYTES = 3upstream = FakeResponse(206, {"Content-Length": "1","Content-Range": "bytes 0-0/4",7 unmodified lines"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf",)finally:app.READER_PDF_MAX_BYTES = old_limitself.assertEqual(response.status_code, 413)self.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)async def test_reader_content_enforces_actual_stream_limit_and_releases(self):old_limit = app.READER_PDF_MAX_BYTESapp.READER_PDF_MAX_BYTES = 3upstream = FakeResponse(200, {}, chunks=(b"ab", b"cd"))semaphore = asyncio.Semaphore(1)app.app.state.http_session = FakeSession([upstream])6 unmodified lineswith self.assertRaises(app.ReaderDocumentLimitError):[chunk async for chunk in response.body_iterator]finally:app.READER_PDF_MAX_BYTES = old_limitself.assertTrue(upstream.released)self.assertEqual(semaphore._value, 1)
21 unmodified lines222324252627283 unmodified lines32333435363721 unmodified lines{repo:'Other/books'}, {repo:'VoiceOfML/../evil'}, {repo:'VoiceOfML/..'}, {revision:'main'}, {revision:'f'.repeat(39)},{path:'../book.'+ext}, {path:'中文/%2e%2e/book.'+ext}, {path:'/book.'+ext},{path:'中文/book.'+ext+'?x'}, {path:'中文/book.html'}, {role:'provenance'},{bytes:0}, {bytes:512*1024*1024+1}, {sha256:'f'.repeat(64)}, {bucket:'vomebook/pdf-pages-v2'},{path:'中文/\ud800.'+ext}]) {const bad=reading(ext);Object.assign(bad.primary.resource,mutation);3 unmodified linesassert.throws(()=>validateReadingManifest(wrongKey,100),/PDF_V3_INVALID/);const mismatch=reading(ext);mismatch.primary.kind=ext==='pdf'?'djvu':'pdf';assert.throws(()=>validateReadingManifest(mismatch,100),/PDF_V3_INVALID/);}const tooMany=reading('djvu');tooMany.page_count=tooMany.preview.page_count=10001;assert.throws(()=>validateReadingManifest(tooMany,20000),/PDF_V3_INVALID/);21 unmodified lines22232425262728293 unmodified lines333435363738394021 unmodified lines{repo:'Other/books'}, {repo:'VoiceOfML/../evil'}, {repo:'VoiceOfML/..'}, {revision:'main'}, {revision:'f'.repeat(39)},{path:'../book.'+ext}, {path:'中文/%2e%2e/book.'+ext}, {path:'/book.'+ext},{path:'中文/book.'+ext+'?x'}, {path:'中文/book.html'}, {role:'provenance'},{bytes:0}, {bytes:(ext==='pdf'?2*1024*1024*1024:512*1024*1024)+1},{sha256:'f'.repeat(64)}, {bucket:'vomebook/pdf-pages-v2'},{path:'中文/\ud800.'+ext}]) {const bad=reading(ext);Object.assign(bad.primary.resource,mutation);3 unmodified linesassert.throws(()=>validateReadingManifest(wrongKey,100),/PDF_V3_INVALID/);const mismatch=reading(ext);mismatch.primary.kind=ext==='pdf'?'djvu':'pdf';assert.throws(()=>validateReadingManifest(mismatch,100),/PDF_V3_INVALID/);const atLimit=reading(ext);atLimit.primary.resource.bytes=(ext==='pdf'?2:0.5)*1024*1024*1024;assert.equal(validateReadingManifest(atLimit,100),atLimit);}const tooMany=reading('djvu');tooMany.page_count=tooMany.preview.page_count=10001;assert.throws(()=>validateReadingManifest(tooMany,20000),/PDF_V3_INVALID/);
326 unmodified lines327328329330331332333326 unmodified linesawait assert.rejects(openPdfRangeTask(pdfjs,options,{signal:new AbortController().signal,readBytes,limit:64,rangeLimit:128,rangeCache:null}),/READER_RESOURCE_LIMIT/,'a complete body keeps the body limit');assert.equal(globalThis.VoiceOfMLReaderSecurity.LIMITS.documentBytes,512*1024*1024);assert.equal(globalThis.VoiceOfMLReaderSecurity.LIMITS.pdfRangeDocumentBytes,1024*1024*1024);}await assert.rejects(open(async()=>new Response('missing',{status:404})),error=>error.status===404);326 unmodified lines327328329330331332333334335336337338339340341342343344345346347326 unmodified linesawait assert.rejects(openPdfRangeTask(pdfjs,options,{signal:new AbortController().signal,readBytes,limit:64,rangeLimit:128,rangeCache:null}),/READER_RESOURCE_LIMIT/,'a complete body keeps the body limit');assert.equal(globalThis.VoiceOfMLReaderSecurity.LIMITS.documentBytes,512*1024*1024);assert.equal(globalThis.VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,2*1024*1024*1024);const pdfLimit=globalThis.VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes;for (const total of [1_610_000_000,pdfLimit,pdfLimit+1]) {globalThis.fetch=async()=>response([1,2,3,4],[0,3,total]);const task=()=>openPdfRangeTask(pdfjs,options,{signal:new AbortController().signal,readBytes,limit:pdfLimit,rangeLimit:pdfLimit,rangeCache:null});if (total>pdfLimit) await assert.rejects(task(),/READER_RESOURCE_LIMIT/);else {const opened=await task();assert.equal((await opened.promise).range.length,total);await opened.destroy();}}let cancelled=false;globalThis.fetch=async()=>({ok:true,status:200,headers:new Headers({'Content-Length':String(pdfLimit+1)}),body:{cancel:async()=>{cancelled=true;}}});await assert.rejects(openPdfRangeTask(pdfjs,options,{signal:new AbortController().signal,readBytes,limit:pdfLimit,rangeLimit:pdfLimit,rangeCache:null}),/READER_RESOURCE_LIMIT/);assert.ok(cancelled,'oversized complete response must release its body');}await assert.rejects(open(async()=>new Response('missing',{status:404})),error=>error.status===404);
451 unmodified lines452453454455456457451 unmodified linesself.assertIn("node scripts/check_search_response_validation_coverage.mjs", dockerfile)self.assertIn("node scripts/check_search_result_identity_coverage.mjs", dockerfile)self.assertIn("node --test tests/test_tap_contracts.mjs", dockerfile)self.assertIn("node scripts/check_download_controller_coverage.mjs", dockerfile)self.assertIn("node scripts/check_search_filter_equality_baseline.mjs", dockerfile)self.assertIn("node scripts/check_search_folder_merge_baseline.mjs", dockerfile)451 unmodified lines452453454455456457458451 unmodified linesself.assertIn("node scripts/check_search_response_validation_coverage.mjs", dockerfile)self.assertIn("node scripts/check_search_result_identity_coverage.mjs", dockerfile)self.assertIn("node --test tests/test_tap_contracts.mjs", dockerfile)self.assertIn("node tests/test_dataset_primary_policy.mjs", dockerfile)self.assertIn("node scripts/check_download_controller_coverage.mjs", dockerfile)self.assertIn("node scripts/check_search_filter_equality_baseline.mjs", dockerfile)self.assertIn("node scripts/check_search_folder_merge_baseline.mjs", dockerfile)
23 unmodified lines2425262728293023 unmodified linesinterface ReaderSecurityApi {readonly LIMITS: Readonly<{documentBytes: number; pdfRangeDocumentBytes: number; archiveCompressedBytes: number;archiveExpandedBytes: number; archiveEntries: number; archiveRatio: number;manifestBytes: number; pdfPages: number; chapters: number; chapterBytes: number;chapterTotalBytes: number;23 unmodified lines2425262728293023 unmodified linesinterface ReaderSecurityApi {readonly LIMITS: Readonly<{documentBytes: number; pdfDocumentBytes: number; archiveCompressedBytes: number;archiveExpandedBytes: number; archiveEntries: number; archiveRatio: number;manifestBytes: number; pdfPages: number; chapters: number; chapterBytes: number;chapterTotalBytes: number;
Dockerfile+1
backend/app.py+11-9
static/reader/core/reader-security.js+3-2
static/reader/pdf/reader-pdf-engine.mjs+6-6
static/reader/pdf/reader-v3.mjs+2-1
tests/test_async_proxy.py+67-47
tests/test_dataset_primary_policy.mjs+4-1
tests/test_reader_pdf_range_transport.mjs+15-1
tests/test_static_contract.py+1
typings/reader-globals.d.ts+1-1