"""Display denominator/units and explicit embedding boundary.""" from pathlib import Path import sys import tempfile import threading import unittest from urllib.request import urlopen APP = Path(__file__).resolve().parents[1] sys.path[:0] = [str(APP), str(APP.parents[1])] from tests.timing import HANG_TIMEOUT, hang_diagnostics from server.embedding import frame_ancestors from server.http_app import Application, make_server from server.registry import Registry class EmbeddingTests(unittest.TestCase): def test_sources_are_explicit_and_cannot_inject_policy(self): self.assertEqual(frame_ancestors([]), "'none'") self.assertEqual(frame_ancestors(['file:', 'http://127.0.0.1:1234', 'file:']), 'file: http://127.0.0.1:1234') for bad in ['*', 'null', 'file://', 'http:', 'http://x/', 'https://x/path', 'http://a@b', 'http://x;script-src', 'http://x\n', 'http://x:0', "'self'"]: with self.subTest(bad=bad), self.assertRaises(ValueError): frame_ancestors([bad]) @hang_diagnostics() def test_actual_headers_default_deny_and_explicit_file(self): with tempfile.TemporaryDirectory() as directory: for sources, expected in [((), "'none'"), (('file:',), 'file:')]: app = Application(Registry([]), directory, frame_sources=sources) try: server = make_server(app, 0) except PermissionError as exc: app.close() self.skipTest('沙箱不允许绑定 loopback:' + str(exc)) thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start() try: with urlopen('http://127.0.0.1:' + str(server.server_port) + '/api/v1/health', timeout=HANG_TIMEOUT) as response: self.assertIn('frame-ancestors ' + expected, response.headers['Content-Security-Policy']) self.assertEqual(app.dispatch('POST', '/api/v1/notes', {'Host': '127.0.0.1', 'Origin': 'null'}).status, 403) finally: server.shutdown(); server.server_close(); thread.join(); app.close()