Repository navigation
Expand file tree
/
Copy pathtest_errors.py
More file actions
355 lines (311 loc) · 13.5 KB
/
Copy pathtest_errors.py
File metadata and controls
355 lines (311 loc) · 13.5 KB
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
# Copyright © Michal Čihař <michal@weblate.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Test the module."""
from __future__ import annotations
import os
from itertools import product
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
import responses
from requests.exceptions import InvalidHeader, RequestException
from wlc import (
API_URL,
Weblate,
WeblateException,
)
from wlc.config import WeblateConfig
from wlc.exceptions import WeblateThrottlingError
from .test_base import (
CONFIG_PARSE_ERRORS,
CONFIG_PARSE_MARKER,
APITest,
CLITestBase,
register_error,
)
class CLIErrorTest(CLITestBase):
"""Testing CLI error handling."""
API_KEY = "reflected-api-key"
def test_url_resolution_errors_hide_rejected_urls(self) -> None:
"""URL resolution failures produce a generic error before HTTP dispatch."""
base_url = "http://127.0.0.1:8000/test-api"
rejected_url = "rejected-url-marker"
translation = "translations/hello/weblate/cs"
cases = (
("projects", {"next": rejected_url, "results": []}, ["list-projects"]),
(
translation,
{"url": f"{base_url}/{translation}/", "file_url": rejected_url},
["download", "hello/weblate/cs"],
),
)
for path, response, command in cases:
with self.subTest(command=command):
url = f"{base_url}/{path}/"
register_error(path, 200, domain=base_url, json=response)
request_count = len(responses.calls)
with patch(
"wlc.client.urljoin",
side_effect=[url, ValueError("parser-detail-marker")],
) as resolve_url:
output = self.execute(
["--debug", "--url", base_url, *command], expected=1, tty=True
)
resolve_url.assert_called_with(f"{base_url}/", rejected_url)
self.assertIn("HTTP failure GET <rejected URL> -> Invalid URL.", output)
self.assertIn("Error: Invalid URL.\n", output)
self.assertNotIn(rejected_url, output)
self.assertNotIn("parser-detail-marker", output)
self.assertEqual(len(responses.calls), request_count + 1)
def test_download_rejects_non_string_file_url(self) -> None:
"""Reject malformed URL fields before formatting or dispatch."""
base_url = "http://127.0.0.1:8000/test-api"
path = "translations/hello/weblate/cs"
for value, options in ((None, []), ({"invalid": True}, ["--convert", "po"])):
with self.subTest(value=value):
register_error(
path,
200,
domain=base_url,
json={"url": f"{base_url}/{path}/", "file_url": value},
)
count = len(responses.calls)
output = self.execute(
["--url", base_url, "download", "hello/weblate/cs", *options],
expected=1,
)
self.assertIn("Error: Invalid URL.\n", output)
self.assertEqual(len(responses.calls), count + 1)
def test_malformed_config_hides_contents(self) -> None:
"""Explicit and discovered configuration errors never echo file contents."""
for source, (content, detail) in product(
("explicit", "user", "project"), CONFIG_PARSE_ERRORS
):
with (
self.subTest(source=source, content=content),
TemporaryDirectory() as tmpdirname,
):
path = Path(tmpdirname) / "invalid.ini"
path.write_text(content, encoding="utf-8")
args = ["list-projects"]
if source == "explicit":
args = ["--config", str(path), *args]
with (
patch.object(
WeblateConfig,
"find_config",
return_value=path if source == "user" else None,
),
patch.object(
WeblateConfig,
"find_project_config",
return_value=path if source == "project" else None,
),
):
output = self.execute(args, settings=False, expected=1)
self.assertEqual(
output, f"Error: Invalid configuration file: {path} ({detail})\n"
)
self.assertNotIn(CONFIG_PARSE_MARKER, output)
self.assertNotIn("Traceback", output)
self.assertEqual(len(responses.calls), 0)
def assert_api_key_redacted(self, args: list[str], expected_message: str) -> None:
"""Verify that a CLI error does not disclose the configured API key."""
output = self.execute(["--key", self.API_KEY, *args], expected=1)
self.assertIn(expected_message, output)
self.assertIn("<redacted>", output)
self.assertNotIn(self.API_KEY, output)
def test_rejects_api_keys_with_unsafe_characters(self) -> None:
"""CLI and environment keys with unsafe characters should not be disclosed."""
for source in ("environment", "command-line"):
for character in ("\r", "\n", "\x1b"):
for debug in (False, True):
with self.subTest(
source=source,
character=repr(character),
debug=debug,
):
key = f"invalid-secret{character}continuation"
args = ["--debug"] if debug else []
environment = {}
if source == "environment":
environment = {"WLC_KEY": key}
else:
args.extend(["--key", key])
args.append("list-projects")
with patch.dict(os.environ, environment, clear=True):
output = self.execute(args, expected=1)
self.assertIn("printable ASCII", output)
self.assertNotIn("invalid-secret", output)
self.assertNotIn("continuation", output)
def test_request_error_redacts_authorization(self) -> None:
"""Request errors should not disclose configured API tokens."""
key = "request-error-secret"
with patch(
"wlc.main.ListProjects.run",
side_effect=RequestException(f"Invalid Authorization: 'Token {key}'"),
):
output = self.execute(
["--key", key, "list-projects"],
expected=10,
)
self.assertIn("Request failed: Invalid Authorization: <redacted>", output)
self.assertNotIn(key, output)
def test_permission_error_redacts_reflected_api_key(self) -> None:
"""Permission error details should mask a reflected API key."""
register_error(
"projects/reflected-permission",
403,
json={"detail": f"Authentication failed for {self.API_KEY}"},
)
self.assert_api_key_redacted(
["show", "reflected-permission"], "Authentication failed"
)
def test_server_error_redacts_reflected_api_key(self) -> None:
"""Generic HTTP response bodies should mask a reflected API key."""
register_error(
"projects/reflected-server-error",
500,
json={"detail": f"token={self.API_KEY}"},
)
self.assert_api_key_redacted(
["show", "reflected-server-error"], "HTTP error 500"
)
def test_throttling_error_redacts_reflected_api_key(self) -> None:
"""Throttling response headers should mask a reflected API key."""
register_error(
"projects/reflected-throttling",
429,
headers={
"X-RateLimit-Limit": f"{self.API_KEY}-via-header",
"Retry-After": "60",
},
)
self.assert_api_key_redacted(
["show", "reflected-throttling"], "Throttling on the server"
)
def test_command_error_redacts_reflected_api_key(self) -> None:
"""Unsuccessful command details should mask a reflected API key."""
project_url = "http://127.0.0.1:8000/api/projects/reflected-command/"
repository_url = f"{project_url}repository/"
register_error(
"projects/reflected-command",
200,
json={
"url": project_url,
"web_url": "http://127.0.0.1:8000/projects/reflected-command/",
"name": "Reflected command",
"slug": "reflected-command",
"web": "",
"repository_url": repository_url,
},
)
register_error(
"projects/reflected-command/repository",
200,
method=responses.POST,
json={
"result": False,
"detail": f"Retry with token {self.API_KEY}",
},
)
self.assert_api_key_redacted(
["commit", "reflected-command"], "Failed to commit changes"
)
class WeblateErrorTest(APITest):
"""Testing error handling."""
def test_nonexisting(self) -> None:
"""Test error handling for non-existing objects."""
with self.assertRaisesRegex(WeblateException, "not found"):
Weblate().get_object("nonexisting")
def test_denied(self) -> None:
"""Test permission denied error handling."""
with self.assertRaisesRegex(WeblateException, "permission"):
Weblate().get_object("denied")
def test_denied_json(self) -> None:
"""Test permission denied when posting components."""
with self.assertRaisesRegex(WeblateException, "Can not create"):
Weblate().create_component(
project="denied_json",
slug="component1",
name="component1",
file_format="po",
filemask="/something",
repo="a_repo",
)
def test_denied_json_510(self) -> None:
"""Test permission denied when posting components."""
with self.assertRaisesRegex(WeblateException, "This is a required error"):
Weblate().create_component(
project="denied_json_510",
slug="component1",
name="component1",
file_format="po",
filemask="/something",
repo="a_repo",
)
def test_throttled(self) -> None:
"""Test handling of throttling error when listing projects."""
with self.assertRaisesRegex(
WeblateThrottlingError,
"Throttling.*Limit is 100 requests. Retry after 81818 seconds.",
) as error:
Weblate().get_object("throttled")
self.assertEqual(error.exception.limit, "100")
self.assertEqual(error.exception.retry_after, "81818")
def test_error(self) -> None:
"""Test general server error (HTTP 500) handling."""
with self.assertRaisesRegex(WeblateException, "500"):
Weblate().get_object("error")
def test_oserror(self) -> None:
"""Test handling of OS/request-level errors when listing projects."""
with self.assertRaises(RequestException):
Weblate().get_object("io")
def test_debug_failure_redacts_invalid_authorization(self) -> None:
"""Invalid authorization headers should not leak into debug logs."""
key = "debug-secret"
error = InvalidHeader(
f"Invalid leading whitespace in header value: {f'Token {key}'!r}"
)
weblate = Weblate(key=key)
with (
self.assertLogs("wlc", level="DEBUG") as captured,
self.assertRaises(InvalidHeader),
patch.object(weblate.session, "request", side_effect=error),
):
weblate.invoke_request("GET", API_URL)
output = "\n".join(captured.output)
self.assertIn("HTTP failure", output)
self.assertIn("<redacted>", output)
self.assertIn("Invalid leading whitespace", output)
self.assertNotIn("debug-secret", output)
def test_bug(self) -> None:
"""Test handling of an unexpected error when listing projects."""
with self.assertRaises(RuntimeError):
Weblate().get_object("bug")
def test_invalid(self) -> None:
"""Test handling of invalid JSON responses."""
with self.assertRaisesRegex(WeblateException, "invalid JSON"):
Weblate().get_object("invalid")
def test_too_long(self) -> None:
"""Unsupported object paths raise a handled error without echoing input."""
for path in (
"a/b/c/d",
"a/b/c/d/e",
"a/b/c/d\x1b]0;title\x07",
"a/b/c/d/e\x1b]52;c;cHJlZmVyZW5jZQ==\x07",
"a/b/c/d\x1b[2J",
):
with (
self.subTest(path=path),
self.assertRaisesRegex(WeblateException, r"^Invalid object path\.$"),
):
Weblate().get_object(path)
self.assertFalse(responses.calls)
def test_invalid_attribute(self) -> None:
"""Test attributes getting."""
obj = Weblate().get_object("hello")
self.assertEqual(obj.name, "Hello")
with self.assertRaises(AttributeError):
print(obj.invalid_attribute) # ruff: ignore[print]