File size: 43,256 Bytes
2a0df63
 
 
ed20146
 
2a0df63
 
49a03ba
2a0df63
 
 
 
6a7cb2e
 
 
 
 
 
 
2a0df63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a7cb2e
 
 
 
2a0df63
 
810f0ba
 
 
 
ed20146
 
 
 
 
 
 
 
 
 
 
 
 
63e3e38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb915bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
810f0ba
ed20146
 
810f0ba
 
ed20146
 
 
810f0ba
 
ed20146
 
 
 
 
 
810f0ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed20146
6a7cb2e
ed20146
810f0ba
ed20146
 
 
810f0ba
 
 
 
 
 
 
 
ed20146
29a508e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a7cb2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c62083
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a7cb2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62ae3c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a0df63
 
 
 
 
 
 
 
 
9ceac12
 
 
 
 
 
 
 
 
28bdb16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c62083
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a0df63
 
6a7cb2e
2a0df63
6a7cb2e
2a0df63
6a7cb2e
2a0df63
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
"""Upstream transport contracts without importing or starting the application."""
import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch
from urllib.parse import quote

import aiohttp
from backend import upstream_http as upstream


class UpstreamHttpTests(unittest.IsolatedAsyncioTestCase):
    def setUp(self):
        class CheckedEvictionCache(dict):
            def pop(self, key, *default):
                if len(self) > upstream.UPSTREAM_REDIRECT_MAX_ENTRIES and key not in self:
                    raise AssertionError("eviction must remove an existing entry")
                return super().pop(key, *default)

        self.cache = patch.object(upstream, "upstream_redirect_cache", CheckedEvictionCache())
        self.cache.start()
        self.addCleanup(self.cache.stop)
        self.timeout = aiohttp.ClientTimeout(total=1)
        self.source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/book.pdf"
        self.target = "https://cdn-lfs.hf.co/signed-book"

    async def test_transport_variants_preserve_head_range_timeout_and_encoding(self):
        for method, transport in [("GET", "request"), ("HEAD", "request"), ("GET", "get"), ("HEAD", "head")]:
            with self.subTest(method=method, transport=transport):
                response = SimpleNamespace(status=206)
                call = AsyncMock(return_value=response)
                session = SimpleNamespace(**{transport: call})
                result = await upstream.open_download_response(
                    session, self.source, self.timeout, method=method.lower(),
                    request_headers={"Range": "bytes=0-99"}, auto_decompress=False,
                    url_validator=upstream.validate_reader_redirect_url,
                )
                self.assertIs(result, response)
                expected_args = (method, self.source) if transport == "request" else (self.source,)
                self.assertEqual(call.call_args.args, expected_args)
                self.assertEqual(call.call_args.kwargs, dict(
                    allow_redirects=False, timeout=self.timeout,
                    headers={"Accept-Encoding": "identity", "Range": "bytes=0-99"}, auto_decompress=False,
                ))

    async def test_head_never_falls_back_to_get_and_rejects_other_methods(self):
        session = SimpleNamespace(get=AsyncMock())
        with self.assertRaisesRegex(ValueError, "^上游会话不支持 HEAD 请求$"):
            await upstream.open_download_response(session, self.source, self.timeout, method="HEAD")
        with self.assertRaisesRegex(ValueError, "^不支持的上游请求方法$"):
            await upstream.open_download_response(session, self.source, self.timeout, method="POST")
        session.get.assert_not_called()

    async def test_reader_cache_redirect_is_validated_followed_and_reused(self):
        path = "000640/第一卷/book.epub"
        source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/" + quote(path)
        target = ("https://huggingface.co/api/resolve-cache/datasets/VoiceOfML/Test/"
                  + "c" * 40 + "/" + quote(path, safe="") + "?etag=%22abc%22")
        redirect = SimpleNamespace(status=307, headers={"Location": target}, release=Mock())
        response = SimpleNamespace(status=200)
        session = SimpleNamespace(request=AsyncMock(side_effect=[redirect, response, response]))
        for _ in range(2):
            self.assertIs(await upstream.open_download_response(
                session, source, self.timeout, url_validator=upstream.validate_reader_redirect_url,
            ), response)
        self.assertEqual([call.args[1] for call in session.request.call_args_list], [source, target, target])
        redirect.release.assert_called_once()
        with self.assertRaises(ValueError):
            upstream.validate_reader_source_url(target)

    async def test_cache_redirect_preserves_encoded_filename_delimiters(self):
        for filename in ("Chapter#1.txt", "Guide?.txt", "Chapter #1; notes?.txt"):
            encoded = quote("Text files/" + filename)
            source = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/" + encoded
            target = ("https://huggingface.co/api/resolve-cache/datasets/VoiceOfML/Test/"
                      + "c" * 40 + "/" + encoded + "?etag=%22abc%22")
            for method, validator in (("GET", upstream.validate_reader_redirect_url),
                                      ("HEAD", upstream.validate_voiceofml_redirect_url)):
                with self.subTest(filename=filename, method=method):
                    redirect = SimpleNamespace(status=307, headers={"Location": target}, release=Mock())
                    response = SimpleNamespace(status=200)
                    session = SimpleNamespace(request=AsyncMock(side_effect=[redirect, response]))
                    self.assertIs(await upstream.open_download_response(
                        session, source, self.timeout, method=method, url_validator=validator,
                    ), response)
                    self.assertEqual([call.args for call in session.request.call_args_list],
                                     [(method, source), (method, target)])
                    redirect.release.assert_called_once()

    async def test_fixed_revision_reader_rejects_redirect_to_other_revision_or_file(self):
        revision = 'a' * 40
        source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/' + revision + '/book.djvu'
        for target in (
            source.replace(revision, 'b' * 40),
            source.replace('/book.djvu', '/other.djvu'),
            'https://huggingface.co/api/resolve-cache/datasets/VoiceOfML/Test/' + 'b' * 40 + '/book.djvu',
        ):
            redirect = SimpleNamespace(status=307, headers={'Location': target}, release=Mock())
            session = SimpleNamespace(request=AsyncMock(return_value=redirect))
            with self.subTest(target=target), self.assertRaises(ValueError):
                await upstream.open_download_response(session, source, self.timeout,
                    url_validator=upstream.validate_reader_redirect_url)
            session.request.assert_awaited_once()

    async def test_fixed_revision_accepts_only_exact_cache_redirect_and_signed_host(self):
        revision = 'a' * 40
        source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/' + revision + '/%E4%B9%A6.djvu'
        cache = ('https://huggingface.co/api/resolve-cache/datasets/VoiceOfML/Test/' + revision +
                 '/%E4%B9%A6.djvu?etag=%22abc%22')
        signed = 'https://us.aws.cdn.hf.co/signed-file'
        responses = [SimpleNamespace(status=307, headers={'Location':cache}, release=Mock()),
                     SimpleNamespace(status=307, headers={'Location':signed}, release=Mock()),
                     SimpleNamespace(status=200)]
        session = SimpleNamespace(request=AsyncMock(side_effect=responses))
        result = await upstream.open_download_response(session, source, self.timeout,
            url_validator=upstream.validate_reader_redirect_url)
        self.assertIs(result, responses[-1])
        self.assertEqual([c.args[1] for c in session.request.call_args_list], [source,cache,signed])

    async def test_reader_cache_redirect_rejects_unsafe_paths_and_removed_dataset(self):
        prefix = "https://huggingface.co/api/resolve-cache/datasets/"
        revision = "c" * 40
        # Formerly accepted object path of the deleted vomebook/Reader-Assets dataset.
        asset = "objects/aa/" + "b" * 64 + "/foliate-original-v1/document.epub"
        for suffix in [
            f"untrusted/Test/{revision}/book.epub",
            f"vomebook/Reader-Assets/{revision}/private.json",
            f"vomebook/Reader-Assets/{revision}/" + asset,
            f"vomebook/Reader-Assets/{revision}/" + quote(asset, safe=""),
            f"VoiceOfML/Test/{revision}/%252e%252e%252fsecret",
            "VoiceOfML/Test/main/book.epub",
            f"VoiceOfML/Test/{revision}/book.epub#fragment",
        ]:
            with self.subTest(suffix=suffix), self.assertRaises(ValueError):
                upstream.validate_reader_redirect_url(prefix + suffix)
        removed = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/" + asset
        session = SimpleNamespace(request=AsyncMock())
        with self.assertRaisesRegex(ValueError, "不允许的阅读来源"):
            await upstream.open_download_response(
                session, removed, self.timeout, url_validator=upstream.validate_reader_redirect_url,
            )
        session.request.assert_not_awaited()
        for destination in (removed, prefix + f"vomebook/Reader-Assets/{revision}/" + asset):
            with self.subTest(destination=destination):
                redirect = SimpleNamespace(status=307, headers={"Location": destination}, release=Mock())
                session = SimpleNamespace(request=AsyncMock(return_value=redirect))
                with self.assertRaisesRegex(ValueError, "不允许的阅读来源"):
                    await upstream.open_download_response(
                        session, self.source, self.timeout, url_validator=upstream.validate_reader_redirect_url,
                    )
                session.request.assert_awaited_once()
                redirect.release.assert_called_once()

    async def test_cross_scope_redirect_is_rejected_and_cached_target_evicted(self):
        # VoiceOfML is the only built-in scope; a second family exercises the retained check.
        original_scope = upstream.source_url_scope
        other = "https://huggingface.co/datasets/VoiceOfML/Other/resolve/main/book.pdf"

        def scope(url):
            return "other" if "/Other/" in url else original_scope(url)

        with patch.object(upstream, "source_url_scope", scope):
            redirect = SimpleNamespace(status=307, headers={"Location": other}, release=Mock())
            session = SimpleNamespace(request=AsyncMock(return_value=redirect))
            with self.assertRaisesRegex(ValueError, "^上游重定向超出允许的数据集范围$"):
                await upstream.open_download_response(
                    session, self.source, self.timeout, url_validator=upstream.validate_reader_redirect_url,
                )
            session.request.assert_awaited_once()
            redirect.release.assert_called_once()
            upstream.upstream_redirect_cache[("GET", self.source)] = (1000, other)
            session = SimpleNamespace(request=AsyncMock(return_value=SimpleNamespace(status=200)))
            with patch.object(upstream.time, "monotonic", return_value=1001):
                await upstream.open_download_response(
                    session, self.source, self.timeout, url_validator=upstream.validate_reader_redirect_url,
                )
        self.assertEqual(session.request.call_args.args, ("GET", self.source))
        self.assertNotIn(("GET", self.source), upstream.upstream_redirect_cache)

    async def test_voiceofml_cache_redirect_is_validated_followed_and_reused(self):
        path = "000640/book.html"
        source = "https://huggingface.co/datasets/VoiceOfML/MLMRL-Hub/resolve/main/" + path
        target = ("https://huggingface.co/api/resolve-cache/datasets/VoiceOfML/MLMRL-Hub/"
                  + "c" * 40 + "/" + path + "?etag=%22abc%22")
        redirect = SimpleNamespace(status=307, headers={"Location": target}, release=Mock())
        response = SimpleNamespace(status=200)
        session = SimpleNamespace(request=AsyncMock(side_effect=[redirect, response, response]))
        for _ in range(2):
            self.assertIs(await upstream.open_download_response(
                session, source, self.timeout, url_validator=upstream.validate_voiceofml_redirect_url,
            ), response)
        self.assertEqual([call.args[1] for call in session.request.call_args_list], [source, target, target])
        redirect.release.assert_called_once()

    def test_voiceofml_redirect_rejects_reader_assets_cache_scope(self):
        target = ("https://huggingface.co/api/resolve-cache/datasets/vomebook/Reader-Assets/"
                  + "c" * 40 + "/objects/aa/" + "b" * 64 + "/document.pdf")
        with self.assertRaises(ValueError):
            upstream.validate_voiceofml_redirect_url(target)

    def test_repeated_percent_decoding_stops_at_the_security_limit(self):
        def encoded_dot(depth):
            value = "."
            for _ in range(depth):
                value = "%2e" if value == "." else value.replace("%", "%25")
            return value

        # The eighth transformation is deliberately rejected even when it
        # happens to produce a plain character: no unchecked ninth pass.
        self.assertEqual(upstream.decode_url_path(encoded_dot(7)), ".")
        for value in (encoded_dot(8), encoded_dot(9)):
            with self.subTest(value=value), self.assertRaisesRegex(ValueError, "^不允许的下载来源路径$"):
                upstream.decode_url_path(value)

    def test_voiceofml_redirect_uses_only_explicit_signed_hosts(self):
        for host in upstream.TRUSTED_REDIRECT_HOSTS:
            target = f"https://{host}/signed?expires=1"
            with self.subTest(host=host):
                self.assertEqual(upstream.validate_voiceofml_redirect_url(target), target)
        for target in ("https://attacker.hf.co/x", "https://huggingface.co.evil.test/x",
                       "https://unknown.xethub.hf.co/x"):
            with self.subTest(target=target), self.assertRaises(ValueError):
                upstream.validate_voiceofml_redirect_url(target)

    def test_fixed_revision_identity_accepts_only_exact_source_or_cache(self):
        revision = "a" * 40
        source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/{revision}/book.pdf"
        cache = f"https://huggingface.co/api/resolve-cache/datasets/VoiceOfML/Test/{revision}/book.pdf?etag=x"
        self.assertTrue(upstream.reader_redirect_matches_pinned_source(source, source))
        self.assertTrue(upstream.reader_redirect_matches_pinned_source(source, cache))
        self.assertTrue(upstream.reader_redirect_matches_pinned_source(source, self.target))
        for target in (source + "?different=1", source + "#fragment", cache + "#fragment",
                       source.replace("book.pdf", "other.pdf"), cache.replace(revision, "b" * 40)):
            with self.subTest(target=target):
                self.assertFalse(upstream.reader_redirect_matches_pinned_source(source, target))
        non_document = source.replace("book.pdf", "book.txt")
        self.assertTrue(upstream.reader_redirect_matches_pinned_source(non_document, source))

    async def test_cached_fixed_revision_redirect_cannot_change_document_identity(self):
        revision = "a" * 40
        source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/{revision}/book.pdf"
        stale = f"https://huggingface.co/api/resolve-cache/datasets/VoiceOfML/Test/{'b' * 40}/book.pdf"
        upstream.upstream_redirect_cache[("GET", source)] = (1000, stale)
        response = SimpleNamespace(status=200)
        session = SimpleNamespace(request=AsyncMock(return_value=response))
        with patch.object(upstream.time, "monotonic", return_value=1001):
            result = await upstream.open_download_response(
                session, source, self.timeout, url_validator=upstream.validate_reader_redirect_url)
        self.assertIs(result, response)
        self.assertEqual(session.request.call_args.args, ("GET", source))
        self.assertNotIn(("GET", source), upstream.upstream_redirect_cache)

    def test_download_source_and_fixed_redirect_security_boundaries(self):
        allowed = "https://huggingface.co:443/datasets/VoiceOfML/Test/resolve/main/book.pdf"
        self.assertEqual(upstream.validate_download_url(allowed), allowed)
        for url in ("https://user@huggingface.co/x", "https://:password@huggingface.co/x",
                    "https://huggingface.co:444/x", "http://huggingface.co/x"):
            with self.subTest(url=url), self.assertRaises(ValueError):
                upstream.validate_download_url(url)
        mirror = "https://hf-mirror.com/datasets/VoiceOfML/Test/resolve/main/书.pdf"
        self.assertEqual(upstream.normalize_download_url(mirror), mirror.replace("hf-mirror.com", "huggingface.co"))
        self.assertEqual(upstream.validate_voiceofml_source_url(mirror), mirror.replace("hf-mirror.com", "huggingface.co"))
        for url in (self.source + "?download=1", self.source + "#section",
                    self.source.replace("huggingface.co", "hf.co")):
            with self.subTest(url=url), self.assertRaises(ValueError):
                upstream.validate_voiceofml_source_url(url)
            with self.subTest(reader=url), self.assertRaises(ValueError):
                upstream.validate_reader_source_url(url)
        self.assertEqual(upstream.validate_fixed_source_redirect_url(self.source, self.source), self.source)
        self.assertEqual(upstream.validate_fixed_source_redirect_url(self.target, self.source), self.target)
        for target in (self.target + "#fragment", "https://attacker.hf.co/x",
                       "https://huggingface.co/datasets/VoiceOfML/Other/resolve/main/book.pdf"):
            with self.subTest(target=target), self.assertRaisesRegex(ValueError, "^上游重定向超出允许的存储范围$"):
                upstream.validate_fixed_source_redirect_url(target, self.source)

    def test_path_normalization_rejects_nested_traversal_and_controls(self):
        for path in ("/a/./book", "/a/../book", "/a/%252e%252e/book", "/a/%255cbook", "/a/%2500book"):
            with self.subTest(path=path), self.assertRaisesRegex(ValueError, "^不允许的下载来源路径$"):
                upstream.validate_path_safety(path)
        revision = "a" * 40
        base = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/{revision}/"
        self.assertEqual(upstream.validate_reader_source_url(base + "book%20name.pdf"), base + "book%20name.pdf")
        for name in ("book%1F.pdf", "book%7F.pdf", "book%25.pdf", "book%3F.pdf", "book%23.pdf", "a//book.pdf"):
            with self.subTest(name=name), self.assertRaises(ValueError):
                upstream.validate_reader_source_url(base + name)

    def test_source_error_messages_and_scope_are_stable(self):
        for value, message in (("https:///book", "不允许的下载跳转地址: unknown"),
                               ("http://huggingface.co/book", "不允许的下载跳转地址: huggingface.co")):
            with self.subTest(value=value), self.assertRaises(ValueError) as error:
                upstream.validate_download_url(value)
            self.assertEqual(str(error.exception), message)
        for value in ("https://hf.co/book", self.source + "?download=1"):
            with self.subTest(value=value), self.assertRaises(ValueError) as error:
                upstream.validate_voiceofml_source_url(value)
            self.assertEqual(str(error.exception), "只允许 VoiceOfML 数据集文件")
        for value in ("https://hf.co/book", self.source + "?download=1", self.source.replace("/main/", "/dev/")):
            with self.subTest(value=value), self.assertRaises(ValueError) as error:
                upstream.validate_reader_source_url(value)
            self.assertEqual(str(error.exception), "不允许的阅读来源")
        for validator in (upstream.validate_reader_redirect_url, upstream.validate_voiceofml_redirect_url):
            with self.subTest(validator=validator), self.assertRaises(ValueError) as error:
                validator("https://attacker.hf.co/signed")
            self.assertEqual(str(error.exception), "上游重定向超出允许的存储范围")
        self.assertEqual(upstream.source_url_scope(self.source), "voiceofml")
        self.assertIsNone(upstream.source_url_scope(self.target))

    async def test_all_redirect_statuses_preserve_relative_targets_and_release_intermediate(self):
        source = self.source
        target = source.rsplit("/", 1)[0] + "/next.pdf"
        for status in (301, 302, 303, 307, 308):
            redirect = SimpleNamespace(status=status, headers={"Location": "next.pdf"}, release=Mock())
            response = SimpleNamespace(status=200)
            session = SimpleNamespace(request=AsyncMock(side_effect=[redirect, response]))
            with self.subTest(status=status):
                self.assertIs(await upstream.open_download_response(session, source, self.timeout,
                              url_validator=upstream.validate_reader_redirect_url, cache_redirects=False), response)
                self.assertEqual([call.args[1] for call in session.request.call_args_list], [source, target])
                redirect.release.assert_called_once()

    async def test_missing_redirect_location_releases_response_and_fails_closed(self):
        redirect = SimpleNamespace(status=302, headers={}, release=Mock())
        with self.assertRaisesRegex(ValueError, "^上游重定向缺少地址$"):
            await upstream.open_download_response(SimpleNamespace(request=AsyncMock(return_value=redirect)),
                                                  self.source, self.timeout)
        redirect.release.assert_called_once()

    async def test_cached_http_expiry_retries_from_source_even_when_redirect_caching_disabled(self):
        stale = SimpleNamespace(status=403, release=Mock())
        fresh = SimpleNamespace(status=200)
        upstream.upstream_redirect_cache[("GET", self.source)] = (1000, self.target)
        session = SimpleNamespace(request=AsyncMock(side_effect=[stale, fresh]))
        with patch.object(upstream.time, "monotonic", return_value=1001):
            result = await upstream.open_download_response(session, self.source, self.timeout)
        self.assertIs(result, fresh)
        self.assertEqual([call.args[1] for call in session.request.call_args_list], [self.target, self.source])
        stale.release.assert_called_once()
        self.assertNotIn(("GET", self.source), upstream.upstream_redirect_cache)
        upstream.upstream_redirect_cache[("GET", self.source)] = (1000, self.target)
        session = SimpleNamespace(request=AsyncMock(return_value=fresh))
        with patch.object(upstream.time, "monotonic", return_value=1001):
            self.assertIs(await upstream.open_download_response(session, self.source, self.timeout,
                                                                cache_redirects=False), fresh)
        self.assertEqual(session.request.call_args.args, ("GET", self.source))

    async def test_redirect_to_unchanged_pinned_source_still_requires_identity(self):
        revision = "a" * 40
        source = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/{revision}/book.pdf"
        other = source.replace("book.pdf", "other.pdf")
        redirect = SimpleNamespace(status=307, headers={"Location": other}, release=Mock())
        session = SimpleNamespace(request=AsyncMock(return_value=redirect))
        with self.assertRaisesRegex(ValueError, "^固定版本文件的重定向身份不匹配$"):
            await upstream.open_download_response(session, source, self.timeout,
                                                  url_validator=upstream.validate_reader_redirect_url)
        redirect.release.assert_called_once()

    async def test_304_after_redirect_is_cached_and_reused(self):
        redirect = SimpleNamespace(status=307, headers={"Location": self.target}, release=Mock())
        not_modified = SimpleNamespace(status=304)
        session = SimpleNamespace(request=AsyncMock(side_effect=[redirect, not_modified, not_modified]))
        with patch.object(upstream.time, "monotonic", return_value=1000):
            self.assertIs(await upstream.open_download_response(session, self.source, self.timeout), not_modified)
            self.assertEqual(upstream.upstream_redirect_cache[("GET", self.source)], (1000, self.target))
            self.assertIs(await upstream.open_download_response(session, self.source, self.timeout), not_modified)
        self.assertEqual([call.args[1] for call in session.request.call_args_list],
                         [self.source, self.target, self.target])

    def test_cache_invalidation_tolerates_an_entry_removed_during_validation(self):
        class EvictedOnRead(dict):
            def get(self, key, default=None):
                value = super().get(key, default)
                if key in self:
                    del self[key]
                return value

        revision = "a" * 40
        pinned = f"https://huggingface.co/datasets/VoiceOfML/Test/resolve/{revision}/book.pdf"
        other = f"https://huggingface.co/api/resolve-cache/datasets/VoiceOfML/Test/{'b' * 40}/book.pdf"
        cases = [
            (self.source, self.target, upstream.time.monotonic() - upstream.UPSTREAM_REDIRECT_TTL_SECONDS - 1,
             lambda url: url, "voiceofml", None),
            (self.source, self.target, upstream.time.monotonic(),
             lambda _url: (_ for _ in ()).throw(ValueError("invalid")), "voiceofml", None),
            (pinned, other, upstream.time.monotonic(), lambda url: url, "voiceofml", None),
            (self.source, self.target, upstream.time.monotonic(), lambda url: url, "voiceofml", "other"),
        ]
        for source, target, stamp, validator, scope, overridden_scope in cases:
            cache = EvictedOnRead({("GET", source): (stamp, target)})
            with self.subTest(source=source, target=target, overridden_scope=overridden_scope), \
                 patch.object(upstream, "upstream_redirect_cache", cache):
                if overridden_scope is None:
                    self.assertIsNone(upstream._redirect_cache_get("GET", source, validator, scope))
                else:
                    with patch.object(upstream, "source_url_scope", return_value=overridden_scope):
                        self.assertIsNone(upstream._redirect_cache_get("GET", source, validator, scope))
                self.assertEqual(cache, {})

    def test_cache_capacity_eviction_tolerates_already_removed_oldest_entry(self):
        class RemovedBeforePop(dict):
            def pop(self, key, *default):
                if len(self) > upstream.UPSTREAM_REDIRECT_MAX_ENTRIES and key not in self:
                    raise AssertionError("eviction must remove an existing entry")
                if key in self:
                    del self[key]
                return super().pop(key, *default)

        cache = RemovedBeforePop({("GET", self.source): (1, self.target)})
        with patch.object(upstream, "upstream_redirect_cache", cache), \
             patch.object(upstream, "UPSTREAM_REDIRECT_MAX_ENTRIES", 1):
            upstream._redirect_cache_put("GET", self.source + "/new", self.target)
        self.assertEqual(list(cache), [("GET", self.source + "/new")])

    async def test_cached_target_invalidation_tolerates_concurrent_eviction(self):
        for stale in (aiohttp.ClientError("expired"), SimpleNamespace(status=403, release=Mock())):
            key = ("GET", self.source)
            upstream.upstream_redirect_cache[key] = (upstream.time.monotonic(), self.target)
            response = SimpleNamespace(status=200)

            async def request(_method, url, **_kwargs):
                if url == self.target:
                    upstream.upstream_redirect_cache.pop(key, None)
                    if isinstance(stale, Exception):
                        raise stale
                    return stale
                return response

            with self.subTest(stale=type(stale).__name__):
                result = await upstream.open_download_response(SimpleNamespace(request=request), self.source, self.timeout)
                self.assertIs(result, response)
                self.assertNotIn(key, upstream.upstream_redirect_cache)
                if not isinstance(stale, Exception):
                    stale.release.assert_called_once()

    async def test_cached_target_still_retries_if_validation_evicted_the_alias(self):
        key = ("GET", self.source)
        upstream.upstream_redirect_cache[key] = (upstream.time.monotonic(), self.target)
        stale = SimpleNamespace(status=410, release=Mock())
        fresh = SimpleNamespace(status=206)
        session = SimpleNamespace(request=AsyncMock(side_effect=[stale, fresh]))

        def validate_redirect(url):
            del upstream.upstream_redirect_cache[key]
            return upstream.validate_reader_redirect_url(url)

        self.assertIs(await upstream.open_download_response(
            session, self.source, self.timeout, redirect_validator=validate_redirect,
        ), fresh)
        self.assertEqual([c.args[1] for c in session.request.call_args_list], [self.target, self.source])
        stale.release.assert_called_once()
        self.assertNotIn(key, upstream.upstream_redirect_cache)

    async def test_redirect_limit_allows_five_hops_but_rejects_six(self):
        def redirects(count):
            return [SimpleNamespace(status=302, headers={"Location": f"/next-{index}"}, release=Mock())
                    for index in range(count)]
        responses = redirects(upstream.MAX_REDIRECTS)
        final = SimpleNamespace(status=200)
        session = SimpleNamespace(request=AsyncMock(side_effect=responses + [final]))
        self.assertIs(await upstream.open_download_response(session, self.source, self.timeout,
                                                             cache_redirects=False), final)
        self.assertEqual(session.request.await_count, upstream.MAX_REDIRECTS + 1)
        for response in responses:
            response.release.assert_called_once()
        responses = redirects(upstream.MAX_REDIRECTS + 1)
        session = SimpleNamespace(request=AsyncMock(side_effect=responses))
        with self.assertRaisesRegex(ValueError, "^上游重定向次数过多$"):
            await upstream.open_download_response(session, self.source, self.timeout, cache_redirects=False)
        for response in responses:
            response.release.assert_called_once()

    def test_redirects_accept_only_known_signed_storage_hosts(self):
        for host in ("cdn-lfs.hf.co", "us.aws.cdn.hf.co", "cas-bridge.xethub.hf.co"):
            with self.subTest(host=host):
                self.assertEqual(
                    upstream.validate_reader_redirect_url(f"https://{host}/signed/book"),
                    f"https://{host}/signed/book",
                )
        for host in ("attacker.hf.co", "unknown.xethub.hf.co", "huggingface.co.evil.test"):
            with self.subTest(host=host), self.assertRaises(ValueError):
                upstream.validate_reader_redirect_url(f"https://{host}/signed/book")

    async def test_redirect_to_unlisted_hf_subdomain_is_rejected(self):
        redirect = SimpleNamespace(
            status=307, headers={"Location": "https://attacker.hf.co/secret"}, release=Mock()
        )
        with self.assertRaisesRegex(ValueError, "存储范围"):
            await upstream.open_download_response(
                SimpleNamespace(request=AsyncMock(return_value=redirect)),
                self.source, self.timeout, url_validator=upstream.validate_reader_redirect_url,
            )
        redirect.release.assert_called_once()

    async def test_expired_redirect_and_other_method_restart_at_source(self):
        with patch.object(upstream.time, "monotonic", return_value=1000):
            upstream.upstream_redirect_cache[("GET", self.source)] = (700, self.target)
            for method in ["HEAD", "GET"]:
                session = SimpleNamespace(request=AsyncMock(return_value=SimpleNamespace(status=200)))
                await upstream.open_download_response(session, self.source, self.timeout, method=method)
                self.assertEqual(session.request.call_args.args, (method, self.source))
            self.assertEqual(upstream.upstream_redirect_cache, {})

    async def test_failed_cached_target_retries_fresh_source_and_propagates_failure(self):
        session = SimpleNamespace(request=AsyncMock(side_effect=[aiohttp.ClientError("stale"), aiohttp.ClientError("fresh")]))
        with patch.object(upstream.time, "monotonic", return_value=1000):
            upstream.upstream_redirect_cache[("GET", self.source)] = (1000, self.target)
            with self.assertRaisesRegex(aiohttp.ClientError, "fresh"):
                await upstream.open_download_response(session, self.source, self.timeout)
        self.assertEqual([call.args[1] for call in session.request.call_args_list], [self.target, self.source])
        self.assertNotIn(("GET", self.source), upstream.upstream_redirect_cache)

    async def test_pdf_ranges_reuse_redirect_without_extending_signed_target_lifetime(self):
        redirect = SimpleNamespace(status=307, headers={"Location": self.target}, release=Mock())
        response = SimpleNamespace(status=206)
        session = SimpleNamespace(request=AsyncMock(side_effect=[redirect, response, response, response]))
        with patch.object(upstream.time, "monotonic", return_value=1000) as clock:
            await upstream.open_download_response(
                session, self.source, self.timeout, request_headers={"Range": "bytes=0-99"},
            )
            clock.return_value = 1200
            await upstream.open_download_response(
                session, self.source, self.timeout, request_headers={"Range": "bytes=900-999"},
            )
            self.assertEqual(upstream.upstream_redirect_cache[("GET", self.source)], (1000, self.target))
            clock.return_value = 1301
            await upstream.open_download_response(session, self.source, self.timeout)
        self.assertEqual([call.args[1] for call in session.request.call_args_list],
                         [self.source, self.target, self.target, self.source])
        self.assertEqual(session.request.call_args_list[2].kwargs["headers"]["Range"], "bytes=900-999")

    async def test_failed_redirect_target_is_not_cached(self):
        for status in (403, 404, 500, 503):
            with self.subTest(status=status):
                redirect = SimpleNamespace(status=307, headers={"Location": self.target}, release=Mock())
                response = SimpleNamespace(status=status, release=Mock())
                session = SimpleNamespace(request=AsyncMock(side_effect=[redirect, response, response]))
                result = await upstream.open_download_response(session, self.source, self.timeout)
                self.assertIs(result, response)
                self.assertNotIn(("GET", self.source), upstream.upstream_redirect_cache)

    async def test_bypass_without_refresh_keeps_existing_alias_and_default_provenance(self):
        key = ("GET", self.source)
        entry = (upstream.time.monotonic(), self.target)
        upstream.upstream_redirect_cache[key] = entry
        walk = upstream.RedirectWalk(refresh=False)
        response = SimpleNamespace(status=206)
        session = SimpleNamespace(request=AsyncMock(return_value=response))
        cache = upstream.upstream_redirect_cache
        with patch.object(cache, "get", wraps=cache.get) as cache_lookup:
            self.assertIs(await upstream.open_download_response(
                session, self.source, self.timeout, cache_redirects=False, redirect_walk=walk,
            ), response)
        cache_lookup.assert_not_called()
        session.request.assert_awaited_once()
        self.assertEqual(session.request.call_args.args, key)
        self.assertIs(walk.is_current(), True)
        self.assertIs(walk.forget(False), False)
        self.assertIs(upstream.upstream_redirect_cache[key], entry)

    async def test_refresh_bypasses_alias_and_only_retires_it_on_commit(self):
        key = ("GET", self.source)
        other = self.target + "-new"
        for previous, target, status, moved, kept in (
            (self.target, self.target, 304, False, True),
            (self.target, other, 304, True, False),
            (self.target, self.target, 206, False, False),
            (None, self.source, 304, False, False),
            (self.target, other, 503, False, True),
        ):
            with self.subTest(previous=previous, target=target, status=status):
                entry = (upstream.time.monotonic(), previous) if previous else None
                if entry is not None:
                    upstream.upstream_redirect_cache[key] = entry
                else:
                    upstream.upstream_redirect_cache.pop(key, None)
                walk = upstream.RedirectWalk(refresh=True)
                response = SimpleNamespace(status=status)
                redirects = [self.redirect_to(target)] if target != self.source else []
                session = SimpleNamespace(request=AsyncMock(side_effect=redirects + [response]))
                self.assertIs(await upstream.open_download_response(
                    session, self.source, self.timeout, redirect_walk=walk,
                ), response)
                self.assertEqual([c.args[1] for c in session.request.call_args_list],
                                 [self.source] + ([target] if redirects else []))
                for redirect in redirects:
                    redirect.release.assert_called_once()
                self.assertIs(upstream.upstream_redirect_cache.get(key), entry)
                self.assertIs(walk.is_current(), True)
                self.assertIs(walk.forget(status == 304), moved)
                self.assertIs(upstream.upstream_redirect_cache.get(key), entry if kept else None)
                if kept and status == 304:
                    # The same accepted 304 can be acknowledged again without losing the alias.
                    self.assertIs(walk.forget(True), False)
                    self.assertIs(upstream.upstream_redirect_cache[key], entry)

    @staticmethod
    def redirect_to(target):
        return SimpleNamespace(status=307, headers={"Location": target}, release=Mock())

    async def test_refresh_commit_invalidates_a_walk_that_already_started(self):
        key = ("GET", self.source)
        response = SimpleNamespace(status=206)
        refresh = upstream.RedirectWalk(refresh=True)
        session = SimpleNamespace(request=AsyncMock(return_value=response))
        self.assertIs(await upstream.open_download_response(
            session, self.source, self.timeout, cache_redirects=False, redirect_walk=refresh,
        ), response)

        walk = upstream.RedirectWalk(refresh=False)

        async def request(_method, url, **_options):
            if url == self.source:
                return self.redirect_to(self.target)
            self.assertEqual(url, self.target)
            self.assertIs(walk.is_current(), True)
            # The earlier refresh commits while the ordinary walk waits for headers.
            self.assertIs(refresh.forget(False), False)
            self.assertIs(walk.is_current(), False)
            return response

        self.assertIs(await upstream.open_download_response(
            SimpleNamespace(request=request), self.source, self.timeout, redirect_walk=walk,
        ), response)
        self.assertIs(walk.is_current(), False)
        self.assertNotIn(key, upstream.upstream_redirect_cache)

    async def test_late_source_walk_cannot_supersede_a_newer_source_walk(self):
        key = ("GET", self.source)
        newer_target = self.target + "-new"
        response = SimpleNamespace(status=206)
        for refresh in (None, False, True):
            with self.subTest(refresh=refresh):
                upstream.upstream_redirect_cache.clear()
                walk = None if refresh is None else upstream.RedirectWalk(refresh=refresh)
                newer = SimpleNamespace(request=AsyncMock(side_effect=[self.redirect_to(newer_target), response]))

                async def request(_method, url, **_options):
                    if url == self.source:
                        return self.redirect_to(self.target)
                    self.assertEqual(url, self.target)
                    self.assertIs(await upstream.open_download_response(newer, self.source, self.timeout), response)
                    return response

                self.assertIs(await upstream.open_download_response(
                    SimpleNamespace(request=request), self.source, self.timeout, redirect_walk=walk,
                ), response)
                if refresh is True:
                    self.assertIsNone(walk.forget(False))
                elif walk is not None:
                    self.assertIs(walk.is_current(), False)
                self.assertEqual(upstream.upstream_redirect_cache[key][1], newer_target)

    async def test_cached_walk_publishes_target_only_while_it_owns_the_alias(self):
        key = ("GET", self.source)
        late_target = self.target + "-late"
        replacement = self.target + "-replacement"
        response = SimpleNamespace(status=206)
        for overlap in (False, True):
            with self.subTest(overlap=overlap):
                upstream.upstream_redirect_cache[key] = (upstream.time.monotonic(), self.target)
                newer = SimpleNamespace(request=AsyncMock(side_effect=[self.redirect_to(replacement), response]))

                async def request(_method, url, **_options):
                    if url == self.target:
                        return self.redirect_to(late_target)
                    self.assertEqual(url, late_target)
                    if overlap:
                        self.assertIs(await upstream.open_download_response(newer, self.source, self.timeout), response)
                        self.assertEqual([c.args[1] for c in newer.request.call_args_list], [self.target, replacement])
                    return response

                self.assertIs(await upstream.open_download_response(
                    SimpleNamespace(request=request), self.source, self.timeout,
                ), response)
                self.assertEqual(upstream.upstream_redirect_cache[key][1], replacement if overlap else late_target)

    async def test_redirect_capacity_evicts_oldest_and_revalidates_cached_host(self):
        with patch.object(upstream, "UPSTREAM_REDIRECT_MAX_ENTRIES", 2):
            with patch.object(upstream.time, "monotonic", side_effect=[3, 1, 2]):
                for suffix in ["a", "b", "c"]:
                    upstream._redirect_cache_put("GET", self.source + suffix, self.target + suffix)
            self.assertEqual(set(upstream.upstream_redirect_cache), {
                ("GET", self.source + "a"), ("GET", self.source + "c")})
        upstream.upstream_redirect_cache[("GET", self.source)] = (1000, "https://invalid.example/book")
        session = SimpleNamespace(request=AsyncMock(return_value=SimpleNamespace(status=200)))
        with patch.object(upstream.time, "monotonic", return_value=1001):
            await upstream.open_download_response(session, self.source, self.timeout)
        self.assertEqual(session.request.call_args.args, ("GET", self.source))
        self.assertNotIn(("GET", self.source), upstream.upstream_redirect_cache)