vomebook commited on
Commit ·
da87c58
1
Parent(s): 325a518
Allow Reader PDF documents up to 2 GiB
Browse files- Dockerfile +1 -0
- 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 -0
- typings/reader-globals.d.ts +1 -1
Dockerfile
CHANGED
|
@@ -49,6 +49,7 @@ RUN npx --no-install pyright --project pyrightconfig.json \
|
|
| 49 |
&& node scripts/check_search_filter_equality_baseline.mjs \
|
| 50 |
&& node scripts/check_search_folder_merge_baseline.mjs \
|
| 51 |
&& node --test tests/test_tap_contracts.mjs \
|
|
|
|
| 52 |
&& node scripts/check_download_controller_coverage.mjs \
|
| 53 |
&& printf 'static gate tests passed\n' >/check/static-gate-test-ok
|
| 54 |
|
|
|
|
| 49 |
&& node scripts/check_search_filter_equality_baseline.mjs \
|
| 50 |
&& node scripts/check_search_folder_merge_baseline.mjs \
|
| 51 |
&& node --test tests/test_tap_contracts.mjs \
|
| 52 |
+
&& node tests/test_dataset_primary_policy.mjs \
|
| 53 |
&& node scripts/check_download_controller_coverage.mjs \
|
| 54 |
&& printf 'static gate tests passed\n' >/check/static-gate-test-ok
|
| 55 |
|
backend/app.py
CHANGED
|
@@ -1622,9 +1622,9 @@ READER_ISOLATION_HEADERS = {
|
|
| 1622 |
"X-Content-Type-Options": "nosniff",
|
| 1623 |
}
|
| 1624 |
READER_DOCUMENT_MAX_BYTES = 512 * 1024 * 1024
|
| 1625 |
-
#
|
| 1626 |
-
#
|
| 1627 |
-
|
| 1628 |
READER_RESOURCE_MAX_ARCHIVE_BYTES = 512 * 1024 * 1024
|
| 1629 |
READER_RESOURCE_MAX_BYTES = 64 * 1024 * 1024
|
| 1630 |
READER_BUCKET_CACHE_TTL_SECONDS = 3600
|
|
@@ -2032,7 +2032,8 @@ async def api_reader_bucket_resource(path: str = Query(...), request: Request =
|
|
| 2032 |
validation_scope=(validate_reader_bucket_redirect_url, source_url),
|
| 2033 |
cache_control=reader_bucket_cache_control(resource_path),
|
| 2034 |
max_bytes=(None if media_type.startswith(("audio/", "video/")) else
|
| 2035 |
-
|
|
|
|
| 2036 |
media_type=media_type,
|
| 2037 |
**integrity,
|
| 2038 |
)
|
|
@@ -2381,6 +2382,8 @@ async def api_reader_content(request: Request, url: Optional[str] = Query(defaul
|
|
| 2381 |
except ValueError as exc:
|
| 2382 |
return JSONResponse({"error": str(exc)}, status_code=403)
|
| 2383 |
source_type = READER_RESOURCE_TYPES.get(unquote(urlparse(target_url).path).rsplit(".", 1)[-1].lower(), "")
|
|
|
|
|
|
|
| 2384 |
if source_type.startswith(("audio/", "video/")):
|
| 2385 |
return await stream_reader_document(request, target_url, media_type=source_type)
|
| 2386 |
return await stream_reader_document(request, target_url)
|
|
@@ -2448,6 +2451,7 @@ async def _stream_reader_document(
|
|
| 2448 |
# Native media is streamed, not parsed or buffered as a complete document.
|
| 2449 |
# Bound transport memory and idle time instead of rejecting large recordings.
|
| 2450 |
is_media_stream = bool(media_type and media_type.startswith(("audio/", "video/")))
|
|
|
|
| 2451 |
if max_bytes is None and not is_media_stream:
|
| 2452 |
max_bytes = READER_DOCUMENT_MAX_BYTES
|
| 2453 |
forwarded_headers = {
|
|
@@ -2456,11 +2460,7 @@ async def _stream_reader_document(
|
|
| 2456 |
if name in request.headers
|
| 2457 |
}
|
| 2458 |
range_header = forwarded_headers.get("Range")
|
| 2459 |
-
bounded_range = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_header or "")
|
| 2460 |
total_limit = max_bytes
|
| 2461 |
-
if (max_bytes is not None and bounded_range and not is_media_stream
|
| 2462 |
-
and (urlparse(target_url).path.lower().endswith(".pdf") or media_type == "application/pdf")):
|
| 2463 |
-
total_limit = max(max_bytes, READER_PDF_RANGE_MAX_BYTES)
|
| 2464 |
# Conditional requests must reach the origin: a cached partial body cannot
|
| 2465 |
# represent a 200/304 decision made against a different validator.
|
| 2466 |
has_conditionals = any(
|
|
@@ -2506,7 +2506,9 @@ async def _stream_reader_document(
|
|
| 2506 |
upstream = lease.response = await open_download_response(
|
| 2507 |
app.state.http_session,
|
| 2508 |
target_url,
|
| 2509 |
-
|
|
|
|
|
|
|
| 2510 |
method=request.method,
|
| 2511 |
request_headers=forwarded_headers,
|
| 2512 |
url_validator=url_validator,
|
|
|
|
| 1622 |
"X-Content-Type-Options": "nosniff",
|
| 1623 |
}
|
| 1624 |
READER_DOCUMENT_MAX_BYTES = 512 * 1024 * 1024
|
| 1625 |
+
# PDFs have their own limit for both complete bodies and range totals. Other
|
| 1626 |
+
# document formats retain their existing limits.
|
| 1627 |
+
READER_PDF_MAX_BYTES = 2 * 1024 * 1024 * 1024
|
| 1628 |
READER_RESOURCE_MAX_ARCHIVE_BYTES = 512 * 1024 * 1024
|
| 1629 |
READER_RESOURCE_MAX_BYTES = 64 * 1024 * 1024
|
| 1630 |
READER_BUCKET_CACHE_TTL_SECONDS = 3600
|
|
|
|
| 2032 |
validation_scope=(validate_reader_bucket_redirect_url, source_url),
|
| 2033 |
cache_control=reader_bucket_cache_control(resource_path),
|
| 2034 |
max_bytes=(None if media_type.startswith(("audio/", "video/")) else
|
| 2035 |
+
READER_PDF_MAX_BYTES if suffix == "pdf" else
|
| 2036 |
+
READER_DOCUMENT_MAX_BYTES if suffix == "djvu" else READER_RESOURCE_MAX_BYTES),
|
| 2037 |
media_type=media_type,
|
| 2038 |
**integrity,
|
| 2039 |
)
|
|
|
|
| 2382 |
except ValueError as exc:
|
| 2383 |
return JSONResponse({"error": str(exc)}, status_code=403)
|
| 2384 |
source_type = READER_RESOURCE_TYPES.get(unquote(urlparse(target_url).path).rsplit(".", 1)[-1].lower(), "")
|
| 2385 |
+
if source_type == "application/pdf":
|
| 2386 |
+
return await stream_reader_document(request, target_url, max_bytes=READER_PDF_MAX_BYTES)
|
| 2387 |
if source_type.startswith(("audio/", "video/")):
|
| 2388 |
return await stream_reader_document(request, target_url, media_type=source_type)
|
| 2389 |
return await stream_reader_document(request, target_url)
|
|
|
|
| 2451 |
# Native media is streamed, not parsed or buffered as a complete document.
|
| 2452 |
# Bound transport memory and idle time instead of rejecting large recordings.
|
| 2453 |
is_media_stream = bool(media_type and media_type.startswith(("audio/", "video/")))
|
| 2454 |
+
is_pdf = media_type == "application/pdf" or unquote(urlparse(target_url).path).lower().endswith(".pdf")
|
| 2455 |
if max_bytes is None and not is_media_stream:
|
| 2456 |
max_bytes = READER_DOCUMENT_MAX_BYTES
|
| 2457 |
forwarded_headers = {
|
|
|
|
| 2460 |
if name in request.headers
|
| 2461 |
}
|
| 2462 |
range_header = forwarded_headers.get("Range")
|
|
|
|
| 2463 |
total_limit = max_bytes
|
|
|
|
|
|
|
|
|
|
| 2464 |
# Conditional requests must reach the origin: a cached partial body cannot
|
| 2465 |
# represent a 200/304 decision made against a different validator.
|
| 2466 |
has_conditionals = any(
|
|
|
|
| 2506 |
upstream = lease.response = await open_download_response(
|
| 2507 |
app.state.http_session,
|
| 2508 |
target_url,
|
| 2509 |
+
# A fixed 180-second total can truncate a valid multi-gigabyte PDF
|
| 2510 |
+
# on a slow connection; retain connect and idle-read timeouts.
|
| 2511 |
+
aiohttp.ClientTimeout(total=None if is_media_stream or is_pdf else 180, connect=15, sock_read=60),
|
| 2512 |
method=request.method,
|
| 2513 |
request_headers=forwarded_headers,
|
| 2514 |
url_validator=url_validator,
|
static/reader/core/reader-security.js
CHANGED
|
@@ -2,8 +2,9 @@
|
|
| 2 |
"use strict";
|
| 3 |
const LIMITS = Object.freeze({
|
| 4 |
documentBytes: 512 * 1024 * 1024,
|
| 5 |
-
// PDF
|
| 6 |
-
|
|
|
|
| 7 |
archiveCompressedBytes: 512 * 1024 * 1024,
|
| 8 |
archiveExpandedBytes: 1536 * 1024 * 1024,
|
| 9 |
archiveEntries: 20000,
|
|
|
|
| 2 |
"use strict";
|
| 3 |
const LIMITS = Object.freeze({
|
| 4 |
documentBytes: 512 * 1024 * 1024,
|
| 5 |
+
// PDF is distinct from DjVu and other document formats. Range reads remain
|
| 6 |
+
// preferred for large files to avoid downloading the entire body at once.
|
| 7 |
+
pdfDocumentBytes: 2 * 1024 * 1024 * 1024,
|
| 8 |
archiveCompressedBytes: 512 * 1024 * 1024,
|
| 9 |
archiveExpandedBytes: 1536 * 1024 * 1024,
|
| 10 |
archiveEntries: 20000,
|
static/reader/pdf/reader-pdf-engine.mjs
CHANGED
|
@@ -27,8 +27,8 @@ export function createReaderPdfEngine(readerContext) {
|
|
| 27 |
const documentOptions = options(url);
|
| 28 |
readerContext.openPdfRangeTask(pdfjs, documentOptions, {
|
| 29 |
signal:owner.signal, readBytes:VoiceOfMLReaderSecurity.readBytes, initial,
|
| 30 |
-
limit:VoiceOfMLReaderSecurity.LIMITS.
|
| 31 |
-
rangeLimit:VoiceOfMLReaderSecurity.LIMITS.
|
| 32 |
boundedMetadata: !!documentOptions.worker?.readerFirstPageWorker,
|
| 33 |
ratePriority: (begin,end) => readerContext.pdfFetchPolicy?.prioritizeRange?.(begin,end,url),
|
| 34 |
canPrefetchOpening: () => !!readerContext.pdfV3Manifest && readerContext.readerRestorationLoaded &&
|
|
@@ -235,8 +235,8 @@ export function createReaderPdfEngine(readerContext) {
|
|
| 235 |
// Keep it owned while engine preparation is pending and consume it only once.
|
| 236 |
let initial = readerContext.preparePdfInitialRange({url:proxyUrl, rangeChunkSize:262144}, {
|
| 237 |
signal:AbortSignal.any([owner.signal, readerContext.readerAbortController.signal]),
|
| 238 |
-
readBytes:VoiceOfMLReaderSecurity.readBytes, limit:VoiceOfMLReaderSecurity.LIMITS.
|
| 239 |
-
rangeLimit:VoiceOfMLReaderSecurity.LIMITS.
|
| 240 |
canPrefetchFirstPage: () => pageOneKnown && !owner.signal.aborted &&
|
| 241 |
navigation === readerContext.readerRuntime?.currentGeneration("navigation")
|
| 242 |
});
|
|
@@ -288,8 +288,8 @@ export function createReaderPdfEngine(readerContext) {
|
|
| 288 |
if (initial !== pending) return null;
|
| 289 |
initial = readerContext.preparePdfInitialRange({url:proxyUrl, rangeChunkSize:262144}, {
|
| 290 |
signal:AbortSignal.any([owner.signal, readerContext.readerAbortController.signal]),
|
| 291 |
-
readBytes:VoiceOfMLReaderSecurity.readBytes, limit:VoiceOfMLReaderSecurity.LIMITS.
|
| 292 |
-
rangeLimit:VoiceOfMLReaderSecurity.LIMITS.
|
| 293 |
canPrefetchFirstPage: () => pageOneKnown && !owner.signal.aborted &&
|
| 294 |
navigation === readerContext.readerRuntime?.currentGeneration("navigation")
|
| 295 |
});
|
|
|
|
| 27 |
const documentOptions = options(url);
|
| 28 |
readerContext.openPdfRangeTask(pdfjs, documentOptions, {
|
| 29 |
signal:owner.signal, readBytes:VoiceOfMLReaderSecurity.readBytes, initial,
|
| 30 |
+
limit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,
|
| 31 |
+
rangeLimit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,
|
| 32 |
boundedMetadata: !!documentOptions.worker?.readerFirstPageWorker,
|
| 33 |
ratePriority: (begin,end) => readerContext.pdfFetchPolicy?.prioritizeRange?.(begin,end,url),
|
| 34 |
canPrefetchOpening: () => !!readerContext.pdfV3Manifest && readerContext.readerRestorationLoaded &&
|
|
|
|
| 235 |
// Keep it owned while engine preparation is pending and consume it only once.
|
| 236 |
let initial = readerContext.preparePdfInitialRange({url:proxyUrl, rangeChunkSize:262144}, {
|
| 237 |
signal:AbortSignal.any([owner.signal, readerContext.readerAbortController.signal]),
|
| 238 |
+
readBytes:VoiceOfMLReaderSecurity.readBytes, limit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,
|
| 239 |
+
rangeLimit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,
|
| 240 |
canPrefetchFirstPage: () => pageOneKnown && !owner.signal.aborted &&
|
| 241 |
navigation === readerContext.readerRuntime?.currentGeneration("navigation")
|
| 242 |
});
|
|
|
|
| 288 |
if (initial !== pending) return null;
|
| 289 |
initial = readerContext.preparePdfInitialRange({url:proxyUrl, rangeChunkSize:262144}, {
|
| 290 |
signal:AbortSignal.any([owner.signal, readerContext.readerAbortController.signal]),
|
| 291 |
+
readBytes:VoiceOfMLReaderSecurity.readBytes, limit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,
|
| 292 |
+
rangeLimit:VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,
|
| 293 |
canPrefetchFirstPage: () => pageOneKnown && !owner.signal.aborted &&
|
| 294 |
navigation === readerContext.readerRuntime?.currentGeneration("navigation")
|
| 295 |
});
|
static/reader/pdf/reader-v3.mjs
CHANGED
|
@@ -26,7 +26,8 @@ export function validateDatasetPrimary(ref, sourceKey, sourceSha, expectedKind)
|
|
| 26 |
ref.path.split("/").some(part => !part || part === "." || part === "..") ||
|
| 27 |
/[\\%?#\x00-\x1f\x7f\p{Cs}]/u.test(ref.path) || !/\.(?:pdf|djvu)$/i.test(ref.path) ||
|
| 28 |
typeof ref.revision !== "string" || !/^[0-9a-f]{40}$/.test(ref.revision) ||
|
| 29 |
-
!sha(ref.sha256) || !integer(ref.bytes) ||
|
|
|
|
| 30 |
(sourceKey !== undefined && sourceKey !== ref.repo + "\0" + ref.path) ||
|
| 31 |
(sourceSha !== undefined && sourceSha !== ref.sha256) ||
|
| 32 |
(expectedKind !== undefined && !ref.path.toLowerCase().endsWith("." + expectedKind))) invalid();
|
|
|
|
| 26 |
ref.path.split("/").some(part => !part || part === "." || part === "..") ||
|
| 27 |
/[\\%?#\x00-\x1f\x7f\p{Cs}]/u.test(ref.path) || !/\.(?:pdf|djvu)$/i.test(ref.path) ||
|
| 28 |
typeof ref.revision !== "string" || !/^[0-9a-f]{40}$/.test(ref.revision) ||
|
| 29 |
+
!sha(ref.sha256) || !integer(ref.bytes) ||
|
| 30 |
+
ref.bytes > (/\.pdf$/i.test(ref.path) ? 2 * 1024 * 1024 * 1024 : 512 * 1024 * 1024) ||
|
| 31 |
(sourceKey !== undefined && sourceKey !== ref.repo + "\0" + ref.path) ||
|
| 32 |
(sourceSha !== undefined && sourceSha !== ref.sha256) ||
|
| 33 |
(expectedKind !== undefined && !ref.path.toLowerCase().endsWith("." + expectedKind))) invalid();
|
tests/test_async_proxy.py
CHANGED
|
@@ -1126,8 +1126,8 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
|
|
| 1126 |
path = "derived/test/" + "a" * 32 + "/document.pdf"
|
| 1127 |
for status, headers, expected in (
|
| 1128 |
(206, {"Content-Range": "invalid"}, 502),
|
| 1129 |
-
(206, {"Content-Range": f"bytes 0-1/{app.
|
| 1130 |
-
(200, {"Content-Length": str(app.
|
| 1131 |
(200, {"Content-Encoding": "gzip"}, 502),
|
| 1132 |
(404, {}, 404),
|
| 1133 |
):
|
|
@@ -1144,45 +1144,65 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
|
|
| 1144 |
await app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={}))
|
| 1145 |
self.assertEqual(semaphore._value, 1)
|
| 1146 |
|
| 1147 |
-
async def
|
| 1148 |
-
|
| 1149 |
-
|
| 1150 |
-
large = app.READER_DOCUMENT_MAX_BYTES + 100
|
| 1151 |
-
over = app.READER_PDF_RANGE_MAX_BYTES + 1
|
| 1152 |
url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large.pdf"
|
| 1153 |
-
for
|
| 1154 |
-
|
| 1155 |
-
|
| 1156 |
-
|
| 1157 |
-
|
| 1158 |
-
|
| 1159 |
-
|
| 1160 |
-
|
| 1161 |
-
|
| 1162 |
-
|
| 1163 |
-
|
| 1164 |
-
|
| 1165 |
-
|
| 1166 |
-
|
| 1167 |
-
|
| 1168 |
-
|
| 1169 |
-
|
| 1170 |
-
|
| 1171 |
-
|
| 1172 |
-
|
| 1173 |
-
|
| 1174 |
-
|
| 1175 |
-
|
| 1176 |
-
|
| 1177 |
-
|
| 1178 |
-
|
| 1179 |
-
|
| 1180 |
-
|
| 1181 |
-
|
| 1182 |
-
|
| 1183 |
-
|
| 1184 |
-
|
| 1185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1186 |
|
| 1187 |
async def test_bucket_pdf_redirect_cannot_switch_to_another_hf_source(self):
|
| 1188 |
path = "derived/test/" + "a" * 32 + "/document.pdf"
|
|
@@ -1718,7 +1738,7 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
|
|
| 1718 |
self.assertEqual(semaphore._value, 1)
|
| 1719 |
|
| 1720 |
async def test_reader_content_rejects_oversized_content_length_before_streaming(self):
|
| 1721 |
-
upstream = FakeResponse(200, {"Content-Length": str(app.
|
| 1722 |
semaphore = asyncio.Semaphore(1)
|
| 1723 |
app.app.state.http_session = FakeSession([upstream])
|
| 1724 |
app.app.state.upstream_semaphore = semaphore
|
|
@@ -1731,8 +1751,8 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
|
|
| 1731 |
self.assertEqual(semaphore._value, 1)
|
| 1732 |
|
| 1733 |
async def test_reader_content_rejects_oversized_range_total(self):
|
| 1734 |
-
old_limit = app.
|
| 1735 |
-
app.
|
| 1736 |
upstream = FakeResponse(206, {
|
| 1737 |
"Content-Length": "1",
|
| 1738 |
"Content-Range": "bytes 0-0/4",
|
|
@@ -1746,14 +1766,14 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
|
|
| 1746 |
"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf",
|
| 1747 |
)
|
| 1748 |
finally:
|
| 1749 |
-
app.
|
| 1750 |
self.assertEqual(response.status_code, 413)
|
| 1751 |
self.assertTrue(upstream.released)
|
| 1752 |
self.assertEqual(semaphore._value, 1)
|
| 1753 |
|
| 1754 |
async def test_reader_content_enforces_actual_stream_limit_and_releases(self):
|
| 1755 |
-
old_limit = app.
|
| 1756 |
-
app.
|
| 1757 |
upstream = FakeResponse(200, {}, chunks=(b"ab", b"cd"))
|
| 1758 |
semaphore = asyncio.Semaphore(1)
|
| 1759 |
app.app.state.http_session = FakeSession([upstream])
|
|
@@ -1766,7 +1786,7 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
|
|
| 1766 |
with self.assertRaises(app.ReaderDocumentLimitError):
|
| 1767 |
[chunk async for chunk in response.body_iterator]
|
| 1768 |
finally:
|
| 1769 |
-
app.
|
| 1770 |
self.assertTrue(upstream.released)
|
| 1771 |
self.assertEqual(semaphore._value, 1)
|
| 1772 |
|
|
|
|
| 1126 |
path = "derived/test/" + "a" * 32 + "/document.pdf"
|
| 1127 |
for status, headers, expected in (
|
| 1128 |
(206, {"Content-Range": "invalid"}, 502),
|
| 1129 |
+
(206, {"Content-Range": f"bytes 0-1/{app.READER_PDF_MAX_BYTES + 1}"}, 413),
|
| 1130 |
+
(200, {"Content-Length": str(app.READER_PDF_MAX_BYTES + 1)}, 413),
|
| 1131 |
(200, {"Content-Encoding": "gzip"}, 502),
|
| 1132 |
(404, {}, 404),
|
| 1133 |
):
|
|
|
|
| 1144 |
await app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={}))
|
| 1145 |
self.assertEqual(semaphore._value, 1)
|
| 1146 |
|
| 1147 |
+
async def test_pdf_limit_for_body_head_and_all_range_forms(self):
|
| 1148 |
+
limit = 2 * 1024 * 1024 * 1024
|
| 1149 |
+
self.assertEqual(app.READER_PDF_MAX_BYTES, limit)
|
|
|
|
|
|
|
| 1150 |
url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large.pdf"
|
| 1151 |
+
for total in (1_610_000_000, limit, limit + 1):
|
| 1152 |
+
allowed = total <= limit
|
| 1153 |
+
for method, forwarded, status, headers in (
|
| 1154 |
+
("HEAD", {}, 200, {"Content-Length": str(total)}),
|
| 1155 |
+
("GET", {}, 200, {"Content-Length": str(total)}),
|
| 1156 |
+
("GET", {"Range": "bytes=0-1"}, 206,
|
| 1157 |
+
{"Content-Length": "2", "Content-Range": f"bytes 0-1/{total}"}),
|
| 1158 |
+
("GET", {"Range": f"bytes={total - 2}-"}, 206,
|
| 1159 |
+
{"Content-Length": "2", "Content-Range": f"bytes {total - 2}-{total - 1}/{total}"}),
|
| 1160 |
+
("GET", {"Range": "bytes=-2"}, 206,
|
| 1161 |
+
{"Content-Length": "2", "Content-Range": f"bytes {total - 2}-{total - 1}/{total}"}),
|
| 1162 |
+
("GET", {"Range": f"bytes={total}-"}, 416,
|
| 1163 |
+
{"Content-Length": "0", "Content-Range": f"bytes */{total}"}),
|
| 1164 |
+
):
|
| 1165 |
+
for source in ("bucket", "original"):
|
| 1166 |
+
with self.subTest(total=total, method=method, range=forwarded, source=source):
|
| 1167 |
+
upstream = FakeResponse(status, headers, chunks=(b"a", b"b") if status != 416 else ())
|
| 1168 |
+
session = app.app.state.http_session = FakeSession([upstream])
|
| 1169 |
+
semaphore = app.app.state.upstream_semaphore = asyncio.Semaphore(1)
|
| 1170 |
+
app.app.state.reader_range_cache = OrderedDict()
|
| 1171 |
+
app.app.state.reader_range_cache_bytes = 0
|
| 1172 |
+
request = SimpleNamespace(method=method, headers=forwarded)
|
| 1173 |
+
if source == "bucket":
|
| 1174 |
+
response = await app.api_reader_bucket_resource("derived/test/" + "a" * 32 + "/document.pdf", request)
|
| 1175 |
+
else:
|
| 1176 |
+
response = await app.api_reader_content(request, url=url, id=None)
|
| 1177 |
+
self.assertEqual(response.status_code, status if allowed else 413)
|
| 1178 |
+
self.assertIsNone(session.urls[0][1]["timeout"].total)
|
| 1179 |
+
self.assertEqual(session.urls[0][1]["timeout"].sock_read, 60)
|
| 1180 |
+
if allowed and method == "GET":
|
| 1181 |
+
self.assertEqual(b"".join([chunk async for chunk in response.body_iterator]),
|
| 1182 |
+
b"" if status == 416 else b"ab")
|
| 1183 |
+
self.assertTrue(upstream.released)
|
| 1184 |
+
self.assertEqual(semaphore._value, 1)
|
| 1185 |
+
# Other document types do not inherit the PDF allowance.
|
| 1186 |
+
for suffix in ("djvu", "txt"):
|
| 1187 |
+
total = app.READER_DOCUMENT_MAX_BYTES + 1
|
| 1188 |
+
upstream = FakeResponse(206, {"Content-Length": "2", "Content-Range": f"bytes 0-1/{total}"})
|
| 1189 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 1190 |
+
app.app.state.upstream_semaphore = asyncio.Semaphore(1)
|
| 1191 |
+
response = await app.api_reader_content(SimpleNamespace(method="GET", headers={"Range": "bytes=0-1"}),
|
| 1192 |
+
url=f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/large.{suffix}", id=None)
|
| 1193 |
+
self.assertEqual(response.status_code, 413)
|
| 1194 |
+
self.assertTrue(upstream.released)
|
| 1195 |
+
|
| 1196 |
+
# Bucket DjVu and page images retain their own lower body bounds too.
|
| 1197 |
+
for path, size in ((f"objects/aa/{'a' * 64}/{'b' * 16}/document.djvu", app.READER_DOCUMENT_MAX_BYTES + 1),
|
| 1198 |
+
(f"objects/aa/{'a' * 64}/{'b' * 16}/pages/page-000002.webp", app.READER_RESOURCE_MAX_BYTES + 1)):
|
| 1199 |
+
upstream = FakeResponse(200, {"Content-Length": str(size)})
|
| 1200 |
+
app.app.state.http_session = FakeSession([upstream])
|
| 1201 |
+
semaphore = app.app.state.upstream_semaphore = asyncio.Semaphore(1)
|
| 1202 |
+
response = await app.api_reader_bucket_resource(path, SimpleNamespace(method="GET", headers={}))
|
| 1203 |
+
self.assertEqual(response.status_code, 413)
|
| 1204 |
+
self.assertTrue(upstream.released)
|
| 1205 |
+
self.assertEqual(semaphore._value, 1)
|
| 1206 |
|
| 1207 |
async def test_bucket_pdf_redirect_cannot_switch_to_another_hf_source(self):
|
| 1208 |
path = "derived/test/" + "a" * 32 + "/document.pdf"
|
|
|
|
| 1738 |
self.assertEqual(semaphore._value, 1)
|
| 1739 |
|
| 1740 |
async def test_reader_content_rejects_oversized_content_length_before_streaming(self):
|
| 1741 |
+
upstream = FakeResponse(200, {"Content-Length": str(app.READER_PDF_MAX_BYTES + 1)}, chunks=(b"not-read",))
|
| 1742 |
semaphore = asyncio.Semaphore(1)
|
| 1743 |
app.app.state.http_session = FakeSession([upstream])
|
| 1744 |
app.app.state.upstream_semaphore = semaphore
|
|
|
|
| 1751 |
self.assertEqual(semaphore._value, 1)
|
| 1752 |
|
| 1753 |
async def test_reader_content_rejects_oversized_range_total(self):
|
| 1754 |
+
old_limit = app.READER_PDF_MAX_BYTES
|
| 1755 |
+
app.READER_PDF_MAX_BYTES = 3
|
| 1756 |
upstream = FakeResponse(206, {
|
| 1757 |
"Content-Length": "1",
|
| 1758 |
"Content-Range": "bytes 0-0/4",
|
|
|
|
| 1766 |
"https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf",
|
| 1767 |
)
|
| 1768 |
finally:
|
| 1769 |
+
app.READER_PDF_MAX_BYTES = old_limit
|
| 1770 |
self.assertEqual(response.status_code, 413)
|
| 1771 |
self.assertTrue(upstream.released)
|
| 1772 |
self.assertEqual(semaphore._value, 1)
|
| 1773 |
|
| 1774 |
async def test_reader_content_enforces_actual_stream_limit_and_releases(self):
|
| 1775 |
+
old_limit = app.READER_PDF_MAX_BYTES
|
| 1776 |
+
app.READER_PDF_MAX_BYTES = 3
|
| 1777 |
upstream = FakeResponse(200, {}, chunks=(b"ab", b"cd"))
|
| 1778 |
semaphore = asyncio.Semaphore(1)
|
| 1779 |
app.app.state.http_session = FakeSession([upstream])
|
|
|
|
| 1786 |
with self.assertRaises(app.ReaderDocumentLimitError):
|
| 1787 |
[chunk async for chunk in response.body_iterator]
|
| 1788 |
finally:
|
| 1789 |
+
app.READER_PDF_MAX_BYTES = old_limit
|
| 1790 |
self.assertTrue(upstream.released)
|
| 1791 |
self.assertEqual(semaphore._value, 1)
|
| 1792 |
|
tests/test_dataset_primary_policy.mjs
CHANGED
|
@@ -22,7 +22,8 @@ for (const ext of ['pdf','djvu']) {
|
|
| 22 |
{repo:'Other/books'}, {repo:'VoiceOfML/../evil'}, {repo:'VoiceOfML/..'}, {revision:'main'}, {revision:'f'.repeat(39)},
|
| 23 |
{path:'../book.'+ext}, {path:'中文/%2e%2e/book.'+ext}, {path:'/book.'+ext},
|
| 24 |
{path:'中文/book.'+ext+'?x'}, {path:'中文/book.html'}, {role:'provenance'},
|
| 25 |
-
{bytes:0}, {bytes:512*1024*1024+1},
|
|
|
|
| 26 |
{path:'中文/\ud800.'+ext}
|
| 27 |
]) {
|
| 28 |
const bad=reading(ext);Object.assign(bad.primary.resource,mutation);
|
|
@@ -32,6 +33,8 @@ for (const ext of ['pdf','djvu']) {
|
|
| 32 |
assert.throws(()=>validateReadingManifest(wrongKey,100),/PDF_V3_INVALID/);
|
| 33 |
const mismatch=reading(ext);mismatch.primary.kind=ext==='pdf'?'djvu':'pdf';
|
| 34 |
assert.throws(()=>validateReadingManifest(mismatch,100),/PDF_V3_INVALID/);
|
|
|
|
|
|
|
| 35 |
}
|
| 36 |
const tooMany=reading('djvu');tooMany.page_count=tooMany.preview.page_count=10001;
|
| 37 |
assert.throws(()=>validateReadingManifest(tooMany,20000),/PDF_V3_INVALID/);
|
|
|
|
| 22 |
{repo:'Other/books'}, {repo:'VoiceOfML/../evil'}, {repo:'VoiceOfML/..'}, {revision:'main'}, {revision:'f'.repeat(39)},
|
| 23 |
{path:'../book.'+ext}, {path:'中文/%2e%2e/book.'+ext}, {path:'/book.'+ext},
|
| 24 |
{path:'中文/book.'+ext+'?x'}, {path:'中文/book.html'}, {role:'provenance'},
|
| 25 |
+
{bytes:0}, {bytes:(ext==='pdf'?2*1024*1024*1024:512*1024*1024)+1},
|
| 26 |
+
{sha256:'f'.repeat(64)}, {bucket:'vomebook/pdf-pages-v2'},
|
| 27 |
{path:'中文/\ud800.'+ext}
|
| 28 |
]) {
|
| 29 |
const bad=reading(ext);Object.assign(bad.primary.resource,mutation);
|
|
|
|
| 33 |
assert.throws(()=>validateReadingManifest(wrongKey,100),/PDF_V3_INVALID/);
|
| 34 |
const mismatch=reading(ext);mismatch.primary.kind=ext==='pdf'?'djvu':'pdf';
|
| 35 |
assert.throws(()=>validateReadingManifest(mismatch,100),/PDF_V3_INVALID/);
|
| 36 |
+
const atLimit=reading(ext);atLimit.primary.resource.bytes=(ext==='pdf'?2:0.5)*1024*1024*1024;
|
| 37 |
+
assert.equal(validateReadingManifest(atLimit,100),atLimit);
|
| 38 |
}
|
| 39 |
const tooMany=reading('djvu');tooMany.page_count=tooMany.preview.page_count=10001;
|
| 40 |
assert.throws(()=>validateReadingManifest(tooMany,20000),/PDF_V3_INVALID/);
|
tests/test_reader_pdf_range_transport.mjs
CHANGED
|
@@ -327,7 +327,21 @@ try {
|
|
| 327 |
await assert.rejects(openPdfRangeTask(pdfjs,options,{signal:new AbortController().signal,readBytes,limit:64,rangeLimit:128,rangeCache:null}),
|
| 328 |
/READER_RESOURCE_LIMIT/,'a complete body keeps the body limit');
|
| 329 |
assert.equal(globalThis.VoiceOfMLReaderSecurity.LIMITS.documentBytes,512*1024*1024);
|
| 330 |
-
assert.equal(globalThis.VoiceOfMLReaderSecurity.LIMITS.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
}
|
| 332 |
await assert.rejects(open(async()=>new Response('missing',{status:404})),error=>error.status===404);
|
| 333 |
|
|
|
|
| 327 |
await assert.rejects(openPdfRangeTask(pdfjs,options,{signal:new AbortController().signal,readBytes,limit:64,rangeLimit:128,rangeCache:null}),
|
| 328 |
/READER_RESOURCE_LIMIT/,'a complete body keeps the body limit');
|
| 329 |
assert.equal(globalThis.VoiceOfMLReaderSecurity.LIMITS.documentBytes,512*1024*1024);
|
| 330 |
+
assert.equal(globalThis.VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes,2*1024*1024*1024);
|
| 331 |
+
const pdfLimit=globalThis.VoiceOfMLReaderSecurity.LIMITS.pdfDocumentBytes;
|
| 332 |
+
for (const total of [1_610_000_000,pdfLimit,pdfLimit+1]) {
|
| 333 |
+
globalThis.fetch=async()=>response([1,2,3,4],[0,3,total]);
|
| 334 |
+
const task=()=>openPdfRangeTask(pdfjs,options,{signal:new AbortController().signal,
|
| 335 |
+
readBytes,limit:pdfLimit,rangeLimit:pdfLimit,rangeCache:null});
|
| 336 |
+
if (total>pdfLimit) await assert.rejects(task(),/READER_RESOURCE_LIMIT/);
|
| 337 |
+
else {const opened=await task();assert.equal((await opened.promise).range.length,total);await opened.destroy();}
|
| 338 |
+
}
|
| 339 |
+
let cancelled=false;
|
| 340 |
+
globalThis.fetch=async()=>({ok:true,status:200,headers:new Headers({'Content-Length':String(pdfLimit+1)}),
|
| 341 |
+
body:{cancel:async()=>{cancelled=true;}}});
|
| 342 |
+
await assert.rejects(openPdfRangeTask(pdfjs,options,{signal:new AbortController().signal,
|
| 343 |
+
readBytes,limit:pdfLimit,rangeLimit:pdfLimit,rangeCache:null}),/READER_RESOURCE_LIMIT/);
|
| 344 |
+
assert.ok(cancelled,'oversized complete response must release its body');
|
| 345 |
}
|
| 346 |
await assert.rejects(open(async()=>new Response('missing',{status:404})),error=>error.status===404);
|
| 347 |
|
tests/test_static_contract.py
CHANGED
|
@@ -452,6 +452,7 @@ class StaticFrontendContractTests(unittest.TestCase):
|
|
| 452 |
self.assertIn("node scripts/check_search_response_validation_coverage.mjs", dockerfile)
|
| 453 |
self.assertIn("node scripts/check_search_result_identity_coverage.mjs", dockerfile)
|
| 454 |
self.assertIn("node --test tests/test_tap_contracts.mjs", dockerfile)
|
|
|
|
| 455 |
self.assertIn("node scripts/check_download_controller_coverage.mjs", dockerfile)
|
| 456 |
self.assertIn("node scripts/check_search_filter_equality_baseline.mjs", dockerfile)
|
| 457 |
self.assertIn("node scripts/check_search_folder_merge_baseline.mjs", dockerfile)
|
|
|
|
| 452 |
self.assertIn("node scripts/check_search_response_validation_coverage.mjs", dockerfile)
|
| 453 |
self.assertIn("node scripts/check_search_result_identity_coverage.mjs", dockerfile)
|
| 454 |
self.assertIn("node --test tests/test_tap_contracts.mjs", dockerfile)
|
| 455 |
+
self.assertIn("node tests/test_dataset_primary_policy.mjs", dockerfile)
|
| 456 |
self.assertIn("node scripts/check_download_controller_coverage.mjs", dockerfile)
|
| 457 |
self.assertIn("node scripts/check_search_filter_equality_baseline.mjs", dockerfile)
|
| 458 |
self.assertIn("node scripts/check_search_folder_merge_baseline.mjs", dockerfile)
|
typings/reader-globals.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ declare class BoundedResponseCache<T = unknown> extends Map<string, T> {
|
|
| 24 |
|
| 25 |
interface ReaderSecurityApi {
|
| 26 |
readonly LIMITS: Readonly<{
|
| 27 |
-
documentBytes: number;
|
| 28 |
archiveExpandedBytes: number; archiveEntries: number; archiveRatio: number;
|
| 29 |
manifestBytes: number; pdfPages: number; chapters: number; chapterBytes: number;
|
| 30 |
chapterTotalBytes: number;
|
|
|
|
| 24 |
|
| 25 |
interface ReaderSecurityApi {
|
| 26 |
readonly LIMITS: Readonly<{
|
| 27 |
+
documentBytes: number; pdfDocumentBytes: number; archiveCompressedBytes: number;
|
| 28 |
archiveExpandedBytes: number; archiveEntries: number; archiveRatio: number;
|
| 29 |
manifestBytes: number; pdfPages: number; chapters: number; chapterBytes: number;
|
| 30 |
chapterTotalBytes: number;
|