File size: 5,328 Bytes
9d57416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""No-socket routing, static files and the single segment-view contract."""
import copy
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import shutil
import socket
import sys
import tempfile
import threading
import unittest
from urllib.request import urlopen

APP = Path(__file__).resolve().parents[1]
REPO = APP.parents[1]
sys.path[:0] = [str(APP), str(REPO)]
from tests.timing import HANG_TIMEOUT, hang_diagnostics
from server.http_app import Application, make_server
from server.registry import Registry
from server.schema import validate


class StandardLibraryTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.root = Path(self.temp.name)
        (self.root / 'index.html').write_text('<html lang="zh">审阅台</html>')
        self.app = Application(Registry([]), self.root)

    def tearDown(self):
        self.temp.cleanup()

    def test_routes_and_rejections(self):
        self.assertEqual(self.app.dispatch('GET', '/api/v1/health').status, 200)
        self.assertEqual(json.loads(self.app.dispatch('GET', '/api/v1/segments').body), {'segments': []})
        for url in ('/api/v1/segments/unregistered', '/api/v1/segments/a%2F..%2Fb',
                    '/%2e%2e/index.html', '/api/v1/segments/%252e%252e', '/missing',
                    '/%00', '/%ff', 'http://outside.example/'):
            with self.subTest(url=url):
                self.assertEqual(self.app.dispatch('GET', url).status, 404)
        response = self.app.dispatch('POST', '/api/v1/segments')
        self.assertEqual(response.status, 405)
        self.assertEqual(response.headers['Allow'], 'GET, HEAD')
        self.assertEqual(self.app.dispatch('GET', '/', {'Host': 'outside.example'}).status, 403)
        self.assertEqual(self.app.dispatch('GET', '/', {'Origin': 'http://outside.example'}).status, 403)
        self.assertEqual(self.app.dispatch('GET', '/', {'Host': '127.0.0.1:1234', 'Origin': 'http://127.0.0.1:1234'}).status, 200)

    def test_static_symlink_escape_and_positive_control(self):
        with tempfile.TemporaryDirectory() as outside:
            file = Path(outside) / 'private.txt'
            file.write_text('not served')
            (self.root / 'escape.txt').symlink_to(file)
            self.assertEqual(self.app.dispatch('GET', '/escape.txt').status, 404)
            self.assertEqual(self.app.dispatch('GET', '/index.html').status, 200)

    def test_generated_types_match_single_schema(self):
        spec = importlib.util.spec_from_file_location('generator', APP / 'tools/generate_contract.py')
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        for path, expected in module.outputs().items():
            self.assertEqual(path.read_text(), expected, 'schema/type drift: ' + str(path))

    def test_schema_validator_rejects_renamed_fields_and_unknown_keys(self):
        schema = {'type': 'object', 'required': ['id'], 'additionalProperties': False,
                  'properties': {'id': {'type': 'string'}}}
        validate({'id': 'positive'}, schema)
        for value in ({'renamed_id': 'bad'}, {'id': 3}, {'id': 'ok', 'extra': 1}):
            with self.assertRaises(ValueError):
                validate(value, schema)

    def test_every_contract_definition_validates_a_value(self):
        # 每个 $defs 都要能被校验器读:不支持的关键字可能只有碰到真值才触发断言
        root = json.loads((APP / 'server/contract.schema.json').read_text())
        for name, node in root['$defs'].items():
            with self.subTest(name=name):
                try:
                    validate(None, node, root)
                except ValueError:
                    pass
        validate({'layer': 'time', 'mover': 'actor-001', 'first_s': 1.0, 'second_s': 2.0, 'early_view': 'A'},
                 {'$ref': '#/$defs/ObserverSplit'}, root)
        with self.assertRaises(AssertionError):
            validate(1, {'type': 'number', 'format': 'x'})   # 真不认识的约束仍然拒

    @hang_diagnostics()
    def test_actual_loopback_http_when_permitted(self):
        try:
            server = make_server(self.app, 0)
        except PermissionError as exc:
            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.assertEqual(response.status, 200)
                self.assertEqual(json.load(response)['service_version'], 'console/1')
            from http.client import HTTPConnection
            connection = HTTPConnection('127.0.0.1', server.server_port, timeout=HANG_TIMEOUT)
            connection.request('HEAD', '/api/v1/health')
            head = connection.getresponse()
            self.assertEqual(head.status, 200)
            self.assertGreater(int(head.getheader('Content-Length')), 0)
            self.assertEqual(head.read(), b'')
            connection.close()
        finally:
            server.shutdown()
            server.server_close()
            thread.join(timeout=HANG_TIMEOUT)

if __name__ == '__main__':
    unittest.main()