File size: 10,089 Bytes
c47ec10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import copy
import json
import math
import tempfile
import unittest
from pathlib import Path

from services.config import (
    DEFAULT_PROXY_RUNTIME,
    ConfigStore,
    _normalize_proxy_runtime_settings,
)


class ProxyRuntimeConfigTests(unittest.TestCase):
    def _make_store(self, initial: dict[str, object] | None = None) -> tuple[tempfile.TemporaryDirectory[str], ConfigStore]:
        tmp_dir = tempfile.TemporaryDirectory()
        path = Path(tmp_dir.name) / "config.json"
        data = {"auth-key": "test-auth"}
        if initial:
            data.update(initial)
        path.write_text(json.dumps(data), encoding="utf-8")
        return tmp_dir, ConfigStore(path)

    def test_defaults_are_safe_and_included_in_public_config(self) -> None:
        tmp_dir, store = self._make_store({"proxy": " http://legacy.example:8080 "})
        with tmp_dir:
            expected_default = copy.deepcopy(DEFAULT_PROXY_RUNTIME)
            runtime = store.get_proxy_runtime_settings()
            self.assertEqual(runtime, expected_default)
            self.assertEqual(store.get_proxy_settings(), "http://legacy.example:8080")

            expected_public = copy.deepcopy(expected_default)
            expected_public["clearance"]["has_cf_cookies"] = False
            expected_public["clearance"]["has_cf_clearance"] = False
            public_config = store.get()
            self.assertEqual(public_config["proxy"], " http://legacy.example:8080 ")
            self.assertEqual(public_config["proxy_runtime"], expected_public)
            self.assertNotIn("auth-key", public_config)

            runtime["enabled"] = True
            runtime["clearance"]["enabled"] = True
            self.assertEqual(DEFAULT_PROXY_RUNTIME, expected_default)
            self.assertEqual(store.get_proxy_runtime_settings(), expected_default)

    def test_normalize_proxy_runtime_sanitizes_invalid_values(self) -> None:
        normalized = _normalize_proxy_runtime_settings(
            {
                "enabled": "yes",
                "egress_mode": "tor",
                "proxy_url": "  http://proxy.example:8080  ",
                "resource_proxy_url": "  socks5://resource.example:1080  ",
                "skip_ssl_verify": "on",
                "reset_session_status_codes": ["403", 429, 99, 600, "bad", None, True],
                "clearance": {
                    "enabled": "0",
                    "mode": "manual",
                    "cf_cookies": "  a=b; c=d  ",
                    "cf_clearance": "  token  ",
                    "user_agent": "  Custom UA  ",
                    "browser": "  firefox  ",
                    "flaresolverr_url": "  http://flare.example/  ",
                    "timeout_sec": 0,
                    "refresh_interval": 59,
                    "warm_up_on_start": "true",
                },
            }
        )

        self.assertTrue(normalized["enabled"])
        self.assertEqual(normalized["egress_mode"], "direct")
        self.assertEqual(normalized["proxy_url"], "http://proxy.example:8080")
        self.assertEqual(normalized["resource_proxy_url"], "socks5://resource.example:1080")
        self.assertTrue(normalized["skip_ssl_verify"])
        self.assertEqual(normalized["reset_session_status_codes"], [403, 429])

        clearance = normalized["clearance"]
        self.assertFalse(clearance["enabled"])
        self.assertEqual(clearance["mode"], "manual")
        self.assertEqual(clearance["cf_cookies"], "a=b; c=d")
        self.assertEqual(clearance["cf_clearance"], "token")
        self.assertEqual(clearance["user_agent"], "Custom UA")
        self.assertEqual(clearance["browser"], "firefox")
        self.assertEqual(clearance["flaresolverr_url"], "http://flare.example/")
        self.assertEqual(clearance["timeout_sec"], 1)
        self.assertEqual(clearance["refresh_interval"], 60)
        self.assertTrue(clearance["warm_up_on_start"])

    def test_normalize_proxy_runtime_uses_defaults_for_missing_or_empty_values(self) -> None:
        self.assertEqual(_normalize_proxy_runtime_settings(None), DEFAULT_PROXY_RUNTIME)
        self.assertEqual(
            _normalize_proxy_runtime_settings(
                {
                    "egress_mode": "single_proxy",
                    "reset_session_status_codes": ["bad", 99, 600],
                    "clearance": {
                        "enabled": True,
                        "mode": "invalid",
                        "user_agent": "",
                        "browser": "",
                        "timeout_sec": "bad",
                        "refresh_interval": "bad",
                    },
                }
            ),
            {
                **DEFAULT_PROXY_RUNTIME,
                "egress_mode": "single_proxy",
                "reset_session_status_codes": [403],
                "clearance": {
                    **DEFAULT_PROXY_RUNTIME["clearance"],
                    "enabled": True,
                    "mode": "none",
                },
            },
        )

    def test_malformed_proxy_runtime_values_fall_back_safely(self) -> None:
        normalized = _normalize_proxy_runtime_settings(
            {
                "enabled": "maybe",
                "skip_ssl_verify": "maybe",
                "reset_session_status_codes": [math.inf, "NaN", "403"],
                "clearance": {
                    "enabled": "maybe",
                    "timeout_sec": math.inf,
                    "refresh_interval": -math.inf,
                    "warm_up_on_start": "maybe",
                },
            }
        )

        self.assertFalse(normalized["enabled"])
        self.assertFalse(normalized["skip_ssl_verify"])
        self.assertEqual(normalized["reset_session_status_codes"], [403])
        clearance = normalized["clearance"]
        self.assertFalse(clearance["enabled"])
        self.assertEqual(clearance["timeout_sec"], DEFAULT_PROXY_RUNTIME["clearance"]["timeout_sec"])
        self.assertEqual(clearance["refresh_interval"], DEFAULT_PROXY_RUNTIME["clearance"]["refresh_interval"])
        self.assertFalse(clearance["warm_up_on_start"])

    def test_update_normalizes_and_persists_proxy_runtime(self) -> None:
        tmp_dir, store = self._make_store()
        with tmp_dir:
            public_config = store.update(
                {
                    "proxy_runtime": {
                        "enabled": "true",
                        "egress_mode": "single_proxy",
                        "proxy_url": "  http://proxy.example  ",
                        "reset_session_status_codes": [401, "403", "nope"],
                        "clearance": {
                            "enabled": "yes",
                            "mode": "flaresolverr",
                            "flaresolverr_url": " http://localhost:8191 ",
                            "timeout_sec": "30",
                            "refresh_interval": "120",
                        },
                    }
                }
            )

            expected = {
                **DEFAULT_PROXY_RUNTIME,
                "enabled": True,
                "egress_mode": "single_proxy",
                "proxy_url": "http://proxy.example",
                "reset_session_status_codes": [401, 403],
                "clearance": {
                    **DEFAULT_PROXY_RUNTIME["clearance"],
                    "enabled": True,
                    "mode": "flaresolverr",
                    "flaresolverr_url": "http://localhost:8191",
                    "timeout_sec": 30,
                    "refresh_interval": 120,
                },
            }
            expected_public = copy.deepcopy(expected)
            expected_public["clearance"]["cf_cookies"] = ""
            expected_public["clearance"]["cf_clearance"] = ""
            expected_public["clearance"]["has_cf_cookies"] = False
            expected_public["clearance"]["has_cf_clearance"] = False
            self.assertEqual(public_config["proxy_runtime"], expected_public)

            raw_saved = json.loads(store.path.read_text(encoding="utf-8"))
            self.assertEqual(raw_saved["proxy_runtime"], expected)
            reloaded = ConfigStore(store.path)
            self.assertEqual(reloaded.get_proxy_runtime_settings(), expected)

    def test_public_proxy_runtime_redacts_and_preserves_existing_clearance_values(self) -> None:
        existing = copy.deepcopy(DEFAULT_PROXY_RUNTIME)
        existing["enabled"] = True
        existing["clearance"]["enabled"] = True
        existing["clearance"]["mode"] = "manual"
        existing["clearance"]["cf_cookies"] = "session=secret-cookie"
        existing["clearance"]["cf_clearance"] = "secret-clearance"
        tmp_dir, store = self._make_store({"proxy_runtime": existing})
        with tmp_dir:
            public_config = store.get()
            public_runtime = public_config["proxy_runtime"]
            public_clearance = public_runtime["clearance"]
            self.assertEqual(public_clearance["cf_cookies"], "")
            self.assertEqual(public_clearance["cf_clearance"], "")
            self.assertTrue(public_clearance["has_cf_cookies"])
            self.assertTrue(public_clearance["has_cf_clearance"])
            self.assertNotIn("secret-cookie", json.dumps(public_config))
            self.assertNotIn("secret-clearance", json.dumps(public_config))

            public_clearance["user_agent"] = "Updated UA"
            updated_public = store.update({"proxy_runtime": public_runtime})
            updated_raw = json.loads(store.path.read_text(encoding="utf-8"))["proxy_runtime"]
            self.assertEqual(updated_raw["clearance"]["cf_cookies"], "session=secret-cookie")
            self.assertEqual(updated_raw["clearance"]["cf_clearance"], "secret-clearance")
            self.assertEqual(updated_raw["clearance"]["user_agent"], "Updated UA")
            self.assertEqual(updated_public["proxy_runtime"]["clearance"]["cf_cookies"], "")
            self.assertEqual(updated_public["proxy_runtime"]["clearance"]["cf_clearance"], "")


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