"""Pin byte-sensitive Reader response eligibility without modifying its implementation.""" from types import SimpleNamespace import unittest from unittest.mock import patch from starlette.datastructures import Headers from backend import app class ReaderCompressionSafetyTests(unittest.TestCase): def test_all_supported_text_suffixes_are_allowed_for_full_gets(self): for suffix in ('txt', 'md', 'markdown', 'html', 'htm', 'xhtml', 'json', 'css', 'xml'): with self.subTest(suffix=suffix): self.assertTrue(app.reader_body_allows_compression('/book.' + suffix.upper())) self.assertTrue(app.reader_body_allows_compression('/book%2E' + suffix + '?download=1')) for suffix in ('pdf', 'epub', 'json.gz', 'jxl', 'webp', 'png', 'mp3', 'mp4', 'zip', ''): with self.subTest(suffix=suffix): self.assertFalse(app.reader_body_allows_compression('/book.' + suffix)) def test_range_conditional_head_and_non_200_remain_identity(self): for status in (0, 199, 201, 206, 304, 416, 500): self.assertFalse(app.reader_body_allows_compression('/book.txt', None, status)) for method in ('HEAD', 'POST', 'get', ''): self.assertFalse(app.reader_body_allows_compression('/book.txt', SimpleNamespace(method=method, headers={}))) for name in ('range', 'if-range', 'if-none-match', 'if-modified-since'): with self.subTest(name=name): request = SimpleNamespace(method='GET', headers=Headers({name: ''})) self.assertFalse(app.reader_body_allows_compression('/book.txt', request)) self.assertTrue(app.reader_body_allows_compression( '/book.txt', SimpleNamespace(method='GET', headers=Headers({'accept': '*/*'})))) def test_path_is_decoded_once_and_query_or_fragment_is_not_a_suffix(self): for path, result in (('/a.txt?x=.pdf#fragment', True), ('/a.pdf?x=.txt', False), ('/a%2Etxt', True), ('/a%252Etxt', False), ('/a%2Etxt%2Fb', False), ('/folder.txt/book', False), ('/a.b.txt', True), ('', False)): with self.subTest(path=path): self.assertIs(app.reader_body_allows_compression(path), result) def test_short_circuit_and_dynamic_suffix_policy(self): class Request: @property def method(self): raise AssertionError('method must not be read after rejected status') with patch.object(app, 'urlparse', side_effect=AssertionError('must not parse')): self.assertFalse(app.reader_body_allows_compression('/book.txt', Request(), 206)) self.assertFalse(app.reader_body_allows_compression('/book.txt', SimpleNamespace(method='HEAD'))) self.assertFalse(app.reader_body_allows_compression( '/book.txt', SimpleNamespace(method='GET', headers={'Range': ''}))) with patch.object(app, 'READER_COMPRESSIBLE_SUFFIXES', {'pdf'}): self.assertTrue(app.reader_body_allows_compression('/book.pdf')) self.assertFalse(app.reader_body_allows_compression('/book.txt')) def test_rebinding_and_exception_evaluation_order(self): events = [] class HeadersProbe: def __contains__(self, name): events.append(('header', name)) return False class Request: @property def method(self): events.append(('method',)) return 'GET' @property def headers(self): events.append(('headers',)) return HeadersProbe() def decoder(path): events.append(('old decoder', path)) return path def parser(path): events.append(('parser', path)) app.unquote = lambda _path: 'changed.pdf' app.READER_COMPRESSIBLE_SUFFIXES = {'txt'} return SimpleNamespace(path='/book.TXT') with patch.object(app, 'unquote', decoder), patch.object(app, 'urlparse', parser), \ patch.object(app, 'READER_COMPRESSIBLE_SUFFIXES', set()): self.assertTrue(app.reader_body_allows_compression('/input', Request())) self.assertEqual(events, [('method',), ('headers',), ('header', 'Range'), ('header', 'If-Range'), ('header', 'If-None-Match'), ('header', 'If-Modified-Since'), ('parser', '/input'), ('old decoder', '/book.TXT')]) with self.assertRaises(ValueError): app.reader_body_allows_compression('https://[invalid/book.txt') self.assertFalse(app.reader_body_allows_compression('https://[invalid/book.txt', status=304)) def test_conditional_header_failure_propagates_before_url_parse(self): calls = [] class BrokenHeaders: def __contains__(self, name): calls.append(name) if name == 'If-Range': raise LookupError('conditional failure') return False with patch.object(app, 'urlparse') as parser: with self.assertRaisesRegex(LookupError, 'conditional failure'): app.reader_body_allows_compression('/book.txt', SimpleNamespace(method='GET', headers=BrokenHeaders())) parser.assert_not_called() self.assertEqual(calls, ['Range', 'If-Range']) def test_any_is_resolved_after_headers_and_only_after_early_rejections(self): events = [] def reject(values): events.append(('any', tuple(values))) return True class Request: method = 'GET' @property def headers(self): events.append(('headers',)) app.any = reject return {} with patch.object(app, 'any', side_effect=AssertionError('must not call any'), create=True), \ patch.object(app, 'urlparse') as parser: self.assertFalse(app.reader_body_allows_compression('/book.txt', Request(), 206)) self.assertFalse(app.reader_body_allows_compression('/book.txt', SimpleNamespace(method='HEAD'))) self.assertFalse(app.reader_body_allows_compression('/book.txt', Request())) parser.assert_not_called() self.assertEqual(events, [('headers',), ('any', (False, False, False, False))]) def test_rebound_decoder_retains_rsplit_arguments_and_final_index(self): events = [] class Parts: def __getitem__(self, index): events.append(('index', index)) return 'TXT' if index == -1 else 'pdf' class Path(str): def rsplit(self, sep=None, maxsplit=-1): events.append(('rsplit', sep, maxsplit)) return Parts() with patch.object(app, 'unquote', lambda path: Path(path)): self.assertTrue(app.reader_body_allows_compression('/book.txt')) self.assertEqual(events, [('rsplit', '.', 1), ('index', -1)]) def test_partial_pdf_cache_control_preserves_headers_and_copy_semantics(self): original = {'Content-Type': ' application/PDF ; charset=binary', 'Cache-Control': 'private', 'ETag': '"stable"', 'Content-Range': 'bytes 0-1/10'} partial = app.reader_document_browser_headers('/synthetic.bin', original, 206) self.assertIsNot(partial, original) self.assertEqual(partial, {**original, 'Cache-Control': 'no-store'}) self.assertEqual(original['Cache-Control'], 'private') for url, status in (('/synthetic.pdf', 200), ('/synthetic.pdf', 304), ('/synthetic.mp4', 206)): headers = {'Content-Type': 'application/octet-stream', 'ETag': '"stable"'} with self.subTest(url=url, status=status): self.assertIs(app.reader_document_browser_headers(url, headers, status), headers) def test_pdf_detection_uses_mime_or_url_path_but_not_query(self): for url, mime, status, changes in ( ('/book.PDF?download=1', '', 206, True), ('/book.bin?name=book.pdf', '', 206, False), ('/book.bin', 'application/pdf; charset=binary', 206, True), ('/book%2Epdf', '', 206, False), ('/book.pdf#page=4', '', 206, True), ('/book.pdf', '', 416, False)): with self.subTest(url=url, mime=mime, status=status): headers = {'Content-Type': mime, 'Cache-Control': 'private'} result = app.reader_document_browser_headers(url, headers, status) self.assertEqual(result['Cache-Control'], 'no-store' if changes else 'private') self.assertEqual(result is headers, not changes) def test_pdf_mime_short_circuits_url_parser_but_other_statuses_do_not(self): with patch.object(app, 'urlparse', side_effect=ValueError('bad URL')): self.assertEqual(app.reader_document_browser_headers('invalid', {'Content-Type': 'application/pdf'}, 206), {'Content-Type': 'application/pdf', 'Cache-Control': 'no-store'}) with self.assertRaisesRegex(ValueError, 'bad URL'): app.reader_document_browser_headers('invalid', {'Content-Type': 'text/plain'}, 200)