forked from Azure/azure-sdk-for-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_certificate_credential.py
More file actions
77 lines (59 loc) · 2.58 KB
/
test_certificate_credential.py
File metadata and controls
77 lines (59 loc) · 2.58 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
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import json
import os
from azure.core.pipeline.policies import ContentDecodePolicy, SansIOHTTPPolicy
from azure.identity import CertificateCredential
from six.moves.urllib_parse import urlparse
from helpers import build_aad_response, urlsafeb64_decode, mock_response
try:
from unittest.mock import Mock, patch
except ImportError: # python < 3.3
from mock import Mock, patch # type: ignore
CERT_PATH = os.path.join(os.path.dirname(__file__), "certificate.pem")
def test_policies_configurable():
policy = Mock(spec_set=SansIOHTTPPolicy, on_request=Mock())
credential = CertificateCredential(
"tenant-id",
"client-id",
CERT_PATH,
policies=[ContentDecodePolicy(), policy],
transport=Mock(send=lambda *_, **__: mock_response(json_payload=build_aad_response(access_token="**"))),
)
credential.get_token("scope")
assert policy.on_request.called
def test_request_url():
authority = "authority.com"
tenant_id = "expected_tenant"
access_token = "***"
def validate_url(url):
scheme, netloc, path, _, _, _ = urlparse(url)
assert scheme == "https"
assert netloc == authority
assert path.startswith("/" + tenant_id)
def mock_send(request, **kwargs):
validate_url(request.url)
return mock_response(json_payload={"token_type": "Bearer", "expires_in": 42, "access_token": access_token})
cred = CertificateCredential(tenant_id, "client_id", CERT_PATH, transport=Mock(send=mock_send), authority=authority)
token = cred.get_token("scope")
assert token.token == access_token
def test_request_body():
access_token = "***"
authority = "authority.com"
tenant_id = "tenant"
def validate_url(url):
scheme, netloc, path, _, _, _ = urlparse(url)
assert scheme == "https"
assert netloc == authority
assert path.startswith("/" + tenant_id)
def mock_send(request, **kwargs):
jwt = request.body["client_assertion"]
header, payload, signature = (urlsafeb64_decode(s) for s in jwt.split("."))
claims = json.loads(payload.decode("utf-8"))
validate_url(claims["aud"])
return mock_response(json_payload={"token_type": "Bearer", "expires_in": 42, "access_token": access_token})
cred = CertificateCredential(tenant_id, "client_id", CERT_PATH, transport=Mock(send=mock_send), authority=authority)
token = cred.get_token("scope")
assert token.token == access_token