-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathtest_authenticator.py
709 lines (566 loc) · 21.5 KB
/
test_authenticator.py
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
from __future__ import annotations
import base64
import logging
import re
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
import httpretty
import pytest
import requests
from cleo.io.null_io import NullIO
from poetry.utils.authenticator import Authenticator
from poetry.utils.authenticator import RepositoryCertificateConfig
if TYPE_CHECKING:
from _pytest.logging import LogCaptureFixture
from _pytest.monkeypatch import MonkeyPatch
from pytest_mock import MockerFixture
from tests.conftest import Config
from tests.conftest import DummyBackend
@dataclass
class SimpleCredential:
username: str
password: str
@pytest.fixture()
def mock_remote(http: type[httpretty.httpretty]) -> None:
http.register_uri(
http.GET,
re.compile("^https?://foo.bar/(.+?)$"),
)
@pytest.fixture()
def repo() -> dict[str, dict[str, str]]:
return {"foo": {"url": "https://foo.bar/simple/"}}
@pytest.fixture
def mock_config(config: Config, repo: dict[str, dict[str, str]]) -> Config:
config.merge(
{
"repositories": repo,
"http-basic": {"foo": {"username": "bar", "password": "baz"}},
}
)
return config
def test_authenticator_uses_url_provided_credentials(
mock_config: Config, mock_remote: None, http: type[httpretty.httpretty]
) -> None:
authenticator = Authenticator(mock_config, NullIO())
authenticator.request("get", "https://foo001:bar002@foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"foo001:bar002").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_uses_credentials_from_config_if_not_provided(
mock_config: Config, mock_remote: None, http: type[httpretty.httpretty]
) -> None:
authenticator = Authenticator(mock_config, NullIO())
authenticator.request("get", "https://foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"bar:baz").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_uses_username_only_credentials(
mock_config: Config,
mock_remote: None,
http: type[httpretty.httpretty],
with_simple_keyring: None,
) -> None:
authenticator = Authenticator(mock_config, NullIO())
authenticator.request("get", "https://foo001@foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"foo001:").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_ignores_locked_keyring(
mock_remote: None,
http: type[httpretty.httpretty],
with_locked_keyring: None,
caplog: LogCaptureFixture,
) -> None:
caplog.set_level(logging.DEBUG, logger="poetry.utils.password_manager")
authenticator = Authenticator()
authenticator.request("get", "https://foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
assert request.headers["Authorization"] is None
assert "Keyring foo.bar is locked" in caplog.messages
def test_authenticator_ignores_failing_keyring(
mock_remote: None,
http: type[httpretty.httpretty],
with_erroneous_keyring: None,
caplog: LogCaptureFixture,
) -> None:
caplog.set_level(logging.DEBUG, logger="poetry.utils.password_manager")
authenticator = Authenticator()
authenticator.request("get", "https://foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
assert request.headers["Authorization"] is None
assert "Accessing keyring foo.bar failed" in caplog.messages
def test_authenticator_uses_password_only_credentials(
mock_config: Config, mock_remote: None, http: type[httpretty.httpretty]
) -> None:
authenticator = Authenticator(mock_config, NullIO())
authenticator.request("get", "https://:bar002@foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b":bar002").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_uses_empty_strings_as_default_password(
config: Config,
mock_remote: None,
repo: dict[str, dict[str, str]],
http: type[httpretty.httpretty],
with_simple_keyring: None,
) -> None:
config.merge(
{
"repositories": repo,
"http-basic": {"foo": {"username": "bar"}},
}
)
authenticator = Authenticator(config, NullIO())
authenticator.request("get", "https://foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"bar:").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_uses_empty_strings_as_default_username(
config: Config,
mock_remote: None,
repo: dict[str, dict[str, str]],
http: type[httpretty.httpretty],
) -> None:
config.merge(
{
"repositories": repo,
"http-basic": {"foo": {"username": None, "password": "bar"}},
}
)
authenticator = Authenticator(config, NullIO())
authenticator.request("get", "https://foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b":bar").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_falls_back_to_keyring_url(
config: Config,
mock_remote: None,
repo: dict[str, dict[str, str]],
http: type[httpretty.httpretty],
with_simple_keyring: None,
dummy_keyring: DummyBackend,
) -> None:
config.merge(
{
"repositories": repo,
}
)
dummy_keyring.set_password(
"https://foo.bar/simple/", None, SimpleCredential("foo", "bar")
)
authenticator = Authenticator(config, NullIO())
authenticator.request("get", "https://foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"foo:bar").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_falls_back_to_keyring_netloc(
config: Config,
mock_remote: None,
repo: dict[str, dict[str, str]],
http: type[httpretty.httpretty],
with_simple_keyring: None,
dummy_keyring: DummyBackend,
) -> None:
config.merge(
{
"repositories": repo,
}
)
dummy_keyring.set_password("foo.bar", None, SimpleCredential("foo", "bar"))
authenticator = Authenticator(config, NullIO())
authenticator.request("get", "https://foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"foo:bar").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")
def test_authenticator_request_retries_on_exception(
mocker: MockerFixture, config: Config, http: type[httpretty.httpretty]
) -> None:
sleep = mocker.patch("time.sleep")
sdist_uri = f"https://foo.bar/files/{uuid.uuid4()!s}/foo-0.1.0.tar.gz"
content = str(uuid.uuid4())
seen: list[str] = []
def callback(
request: requests.Request, uri: str, response_headers: dict[str, str]
) -> list[int | dict[str, str] | str]:
if seen.count(uri) < 2:
seen.append(uri)
raise requests.exceptions.ConnectionError("Disconnected")
return [200, response_headers, content]
http.register_uri(httpretty.GET, sdist_uri, body=callback)
authenticator = Authenticator(config, NullIO())
response = authenticator.request("get", sdist_uri)
assert response.text == content
assert sleep.call_count == 2
@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning")
def test_authenticator_request_raises_exception_when_attempts_exhausted(
mocker: MockerFixture, config: Config, http: type[httpretty.httpretty]
) -> None:
sleep = mocker.patch("time.sleep")
sdist_uri = f"https://foo.bar/files/{uuid.uuid4()!s}/foo-0.1.0.tar.gz"
def callback(*_: Any, **___: Any) -> None:
raise requests.exceptions.ConnectionError(str(uuid.uuid4()))
http.register_uri(httpretty.GET, sdist_uri, body=callback)
authenticator = Authenticator(config, NullIO())
with pytest.raises(requests.exceptions.ConnectionError):
authenticator.request("get", sdist_uri)
assert sleep.call_count == 5
def test_authenticator_request_respects_retry_header(
mocker: MockerFixture,
config: Config,
http: type[httpretty.httpretty],
) -> None:
sleep = mocker.patch("time.sleep")
sdist_uri = f"https://foo.bar/files/{uuid.uuid4()!s}/foo-0.1.0.tar.gz"
content = str(uuid.uuid4())
seen: list[str] = []
def callback(
request: requests.Request, uri: str, response_headers: dict[str, str]
) -> list[int | dict[str, str] | str]:
if not seen.count(uri):
seen.append(uri)
return [429, {"Retry-After": "42"}, "Retry later"]
return [200, response_headers, content]
http.register_uri(httpretty.GET, sdist_uri, body=callback)
authenticator = Authenticator(config, NullIO())
response = authenticator.request("get", sdist_uri)
assert sleep.call_args[0] == (42.0,)
assert response.text == content
@pytest.mark.parametrize(
["status", "attempts"],
[
(400, 0),
(401, 0),
(403, 0),
(404, 0),
(429, 5),
(500, 5),
(501, 5),
(502, 5),
(503, 5),
(504, 5),
],
)
def test_authenticator_request_retries_on_status_code(
mocker: MockerFixture,
config: Config,
http: type[httpretty.httpretty],
status: int,
attempts: int,
) -> None:
sleep = mocker.patch("time.sleep")
sdist_uri = f"https://foo.bar/files/{uuid.uuid4()!s}/foo-0.1.0.tar.gz"
content = str(uuid.uuid4())
def callback(
request: requests.Request, uri: str, response_headers: dict[str, str]
) -> list[int | dict[str, str] | str]:
return [status, response_headers, content]
http.register_uri(httpretty.GET, sdist_uri, body=callback)
authenticator = Authenticator(config, NullIO())
with pytest.raises(requests.exceptions.HTTPError) as excinfo:
authenticator.request("get", sdist_uri)
assert excinfo.value.response.status_code == status
assert excinfo.value.response.text == content
assert sleep.call_count == attempts
def test_authenticator_uses_env_provided_credentials(
config: Config,
repo: dict[str, dict[str, str]],
environ: None,
mock_remote: type[httpretty.httpretty],
http: type[httpretty.httpretty],
monkeypatch: MonkeyPatch,
) -> None:
monkeypatch.setenv("POETRY_HTTP_BASIC_FOO_USERNAME", "bar")
monkeypatch.setenv("POETRY_HTTP_BASIC_FOO_PASSWORD", "baz")
config.merge({"repositories": repo})
authenticator = Authenticator(config, NullIO())
authenticator.request("get", "https://foo.bar/files/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"bar:baz").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
@pytest.mark.parametrize(
"cert,client_cert",
[
(None, None),
(None, "path/to/provided/client-cert"),
("/path/to/provided/cert", None),
("/path/to/provided/cert", "path/to/provided/client-cert"),
],
)
def test_authenticator_uses_certs_from_config_if_not_provided(
config: Config,
mock_remote: type[httpretty.httpretty],
mock_config: Config,
http: type[httpretty.httpretty],
mocker: MockerFixture,
cert: str | None,
client_cert: str | None,
) -> None:
configured_cert = "/path/to/cert"
configured_client_cert = "/path/to/client-cert"
mock_config.merge(
{
"certificates": {
"foo": {"cert": configured_cert, "client-cert": configured_client_cert}
},
}
)
authenticator = Authenticator(mock_config, NullIO())
url = "https://foo.bar/files/foo-0.1.0.tar.gz"
session = authenticator.get_session(url)
session_send = mocker.patch.object(session, "send")
authenticator.request(
"get",
url,
verify=cert,
cert=client_cert,
)
kwargs = session_send.call_args[1]
assert Path(kwargs["verify"]) == Path(cert or configured_cert)
assert Path(kwargs["cert"]) == Path(client_cert or configured_client_cert)
def test_authenticator_uses_credentials_from_config_matched_by_url_path(
config: Config, mock_remote: None, http: type[httpretty.httpretty]
) -> None:
config.merge(
{
"repositories": {
"foo-alpha": {"url": "https://foo.bar/alpha/files/simple/"},
"foo-beta": {"url": "https://foo.bar/beta/files/simple/"},
},
"http-basic": {
"foo-alpha": {"username": "bar", "password": "alpha"},
"foo-beta": {"username": "baz", "password": "beta"},
},
}
)
authenticator = Authenticator(config, NullIO())
authenticator.request("get", "https://foo.bar/alpha/files/simple/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"bar:alpha").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
# Make request on second repository with the same netloc but different credentials
authenticator.request("get", "https://foo.bar/beta/files/simple/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"baz:beta").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_uses_credentials_from_config_with_at_sign_in_path(
config: Config, mock_remote: None, http: type[httpretty.httpretty]
) -> None:
config.merge(
{
"repositories": {
"foo": {"url": "https://foo.bar/beta/files/simple/"},
},
"http-basic": {
"foo": {"username": "bar", "password": "baz"},
},
}
)
authenticator = Authenticator(config, NullIO())
authenticator.request("get", "https://foo.bar/beta/files/simple/f@@-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"bar:baz").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_falls_back_to_keyring_url_matched_by_path(
config: Config,
mock_remote: None,
http: type[httpretty.httpretty],
with_simple_keyring: None,
dummy_keyring: DummyBackend,
) -> None:
config.merge(
{
"repositories": {
"foo-alpha": {"url": "https://foo.bar/alpha/files/simple/"},
"foo-beta": {"url": "https://foo.bar/beta/files/simple/"},
}
}
)
dummy_keyring.set_password(
"https://foo.bar/alpha/files/simple/", None, SimpleCredential("foo", "bar")
)
dummy_keyring.set_password(
"https://foo.bar/beta/files/simple/", None, SimpleCredential("foo", "baz")
)
authenticator = Authenticator(config, NullIO())
authenticator.request("get", "https://foo.bar/alpha/files/simple/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"foo:bar").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
authenticator.request("get", "https://foo.bar/beta/files/simple/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"foo:baz").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_uses_env_provided_credentials_matched_by_url_path(
config: Config,
environ: None,
mock_remote: type[httpretty.httpretty],
http: type[httpretty.httpretty],
monkeypatch: MonkeyPatch,
) -> None:
monkeypatch.setenv("POETRY_HTTP_BASIC_FOO_ALPHA_USERNAME", "bar")
monkeypatch.setenv("POETRY_HTTP_BASIC_FOO_ALPHA_PASSWORD", "alpha")
monkeypatch.setenv("POETRY_HTTP_BASIC_FOO_BETA_USERNAME", "baz")
monkeypatch.setenv("POETRY_HTTP_BASIC_FOO_BETA_PASSWORD", "beta")
config.merge(
{
"repositories": {
"foo-alpha": {"url": "https://foo.bar/alpha/files/simple/"},
"foo-beta": {"url": "https://foo.bar/beta/files/simple/"},
}
}
)
authenticator = Authenticator(config, NullIO())
authenticator.request("get", "https://foo.bar/alpha/files/simple/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"bar:alpha").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
authenticator.request("get", "https://foo.bar/beta/files/simple/foo-0.1.0.tar.gz")
request = http.last_request()
basic_auth = base64.b64encode(b"baz:beta").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_azure_feed_guid_credentials(
config: Config,
mock_remote: None,
http: type[httpretty.httpretty],
with_simple_keyring: None,
dummy_keyring: DummyBackend,
) -> None:
config.merge(
{
"repositories": {
"alpha": {
"url": "https://foo.bar/org-alpha/_packaging/feed/pypi/simple/"
},
"beta": {
"url": "https://foo.bar/org-beta/_packaging/feed/pypi/simple/"
},
},
"http-basic": {
"alpha": {"username": "foo", "password": "bar"},
"beta": {"username": "baz", "password": "qux"},
},
}
)
authenticator = Authenticator(config, NullIO())
authenticator.request(
"get",
"https://foo.bar/org-alpha/_packaging/GUID/pypi/simple/a/1.0.0/a-1.0.0.whl",
)
request = http.last_request()
basic_auth = base64.b64encode(b"foo:bar").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
authenticator.request(
"get",
"https://foo.bar/org-beta/_packaging/GUID/pypi/simple/b/1.0.0/a-1.0.0.whl",
)
request = http.last_request()
basic_auth = base64.b64encode(b"baz:qux").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_add_repository(
config: Config,
mock_remote: None,
http: type[httpretty.httpretty],
with_simple_keyring: None,
dummy_keyring: DummyBackend,
) -> None:
config.merge(
{
"http-basic": {
"source": {"username": "foo", "password": "bar"},
},
}
)
authenticator = Authenticator(config, NullIO())
authenticator.request(
"get",
"https://foo.bar/simple/a/1.0.0/a-1.0.0.whl",
)
request = http.last_request()
assert "Authorization" not in request.headers
authenticator.add_repository("source", "https://foo.bar/simple/")
authenticator.request(
"get",
"https://foo.bar/simple/a/1.0.0/a-1.0.0.whl",
)
request = http.last_request()
basic_auth = base64.b64encode(b"foo:bar").decode()
assert request.headers["Authorization"] == f"Basic {basic_auth}"
def test_authenticator_git_repositories(
config: Config,
mock_remote: None,
http: type[httpretty.httpretty],
with_simple_keyring: None,
dummy_keyring: DummyBackend,
) -> None:
config.merge(
{
"repositories": {
"one": {"url": "https://foo.bar/org/one.git"},
"two": {"url": "https://foo.bar/org/two.git"},
},
"http-basic": {
"one": {"username": "foo", "password": "bar"},
"two": {"username": "baz", "password": "qux"},
},
}
)
authenticator = Authenticator(config, NullIO())
one = authenticator.get_credentials_for_git_url("https://foo.bar/org/one.git")
assert one.username == "foo"
assert one.password == "bar"
two = authenticator.get_credentials_for_git_url("https://foo.bar/org/two.git")
assert two.username == "baz"
assert two.password == "qux"
two_ssh = authenticator.get_credentials_for_git_url("ssh://git@foo.bar/org/two.git")
assert not two_ssh.username
assert not two_ssh.password
three = authenticator.get_credentials_for_git_url("https://foo.bar/org/three.git")
assert not three.username
assert not three.password
@pytest.mark.parametrize(
("ca_cert", "client_cert", "result"),
[
(None, None, RepositoryCertificateConfig()),
(
"path/to/ca.pem",
"path/to/client.pem",
RepositoryCertificateConfig(
Path("path/to/ca.pem"), Path("path/to/client.pem")
),
),
(
None,
"path/to/client.pem",
RepositoryCertificateConfig(None, Path("path/to/client.pem")),
),
(
"path/to/ca.pem",
None,
RepositoryCertificateConfig(Path("path/to/ca.pem"), None),
),
(True, None, RepositoryCertificateConfig()),
(False, None, RepositoryCertificateConfig(verify=False)),
(
False,
"path/to/client.pem",
RepositoryCertificateConfig(None, Path("path/to/client.pem"), verify=False),
),
],
)
def test_repository_certificate_configuration_create(
ca_cert: str | bool | None,
client_cert: str | None,
result: RepositoryCertificateConfig,
config: Config,
) -> None:
cert_config = {}
if ca_cert is not None:
cert_config["cert"] = ca_cert
if client_cert is not None:
cert_config["client-cert"] = client_cert
config.merge({"certificates": {"foo": cert_config}})
assert RepositoryCertificateConfig.create("foo", config) == result