Exemplo n.º 1
0
async def test_certificate_credential(live_certificate):
    tenant_id = live_certificate["tenant_id"]
    client_id = live_certificate["client_id"]

    credential = CertificateCredential(tenant_id, client_id,
                                       live_certificate["cert_path"])
    await get_token(credential)

    credential = CertificateCredential(
        tenant_id,
        client_id,
        live_certificate["cert_with_password_path"],
        password=live_certificate["password"])
    await get_token(credential)

    credential = CertificateCredential(
        tenant_id, client_id, certificate_bytes=live_certificate["cert_bytes"])
    await get_token(credential)

    credential = CertificateCredential(
        tenant_id,
        client_id,
        certificate_bytes=live_certificate["cert_with_password_bytes"],
        password=live_certificate["password"],
    )
    await get_token(credential)
Exemplo n.º 2
0
def test_persistent_cache_linux(mock_extensions, cert_path, cert_password):
    """The credential should use an unencrypted cache when encryption is unavailable and the user explicitly opts in.

    This test was written when Linux was the only platform on which encryption may not be available.
    """

    required_arguments = ("tenant-id", "client-id", cert_path)

    # the credential should prefer an encrypted cache even when the user allows an unencrypted one
    CertificateCredential(
        *required_arguments, password=cert_password, enable_persistent_cache=True, allow_unencrypted_cache=True
    )
    assert mock_extensions.PersistedTokenCache.called_with(mock_extensions.LibsecretPersistence)
    mock_extensions.PersistedTokenCache.reset_mock()

    # (when LibsecretPersistence's dependencies aren't available, constructing it raises ImportError)
    mock_extensions.LibsecretPersistence = Mock(side_effect=ImportError)

    # encryption unavailable, no opt in to unencrypted cache -> credential should raise
    with pytest.raises(ValueError):
        CertificateCredential(*required_arguments, password=cert_password, enable_persistent_cache=True)

    CertificateCredential(
        *required_arguments, password=cert_password, enable_persistent_cache=True, allow_unencrypted_cache=True
    )
    assert mock_extensions.PersistedTokenCache.called_with(mock_extensions.FilePersistence)
Exemplo n.º 3
0
async def test_request_url(cert_path, cert_password, authority):
    """the credential should accept an authority, with or without scheme, as an argument or environment variable"""

    tenant_id = "expected-tenant"
    access_token = "***"
    parsed_authority = urlparse(authority)
    expected_netloc = parsed_authority.netloc or authority  # "localhost" parses to netloc "", path "localhost"

    async def mock_send(request, **kwargs):
        actual = urlparse(request.url)
        assert actual.scheme == "https"
        assert actual.netloc == expected_netloc
        assert actual.path.startswith("/" + tenant_id)
        return mock_response(json_payload={"token_type": "Bearer", "expires_in": 42, "access_token": access_token})

    cred = CertificateCredential(
        tenant_id, "client-id", cert_path, password=cert_password, transport=Mock(send=mock_send), authority=authority
    )
    token = await cred.get_token("scope")
    assert token.token == access_token

    # authority can be configured via environment variable
    with patch.dict("os.environ", {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
        credential = CertificateCredential(
            tenant_id, "client-id", cert_path, password=cert_password, transport=Mock(send=mock_send)
        )
        await credential.get_token("scope")
    assert token.token == access_token
Exemplo n.º 4
0
async def test_certificate_credential(certificate_fixture, request):
    cert = request.getfixturevalue(certificate_fixture)

    tenant_id = cert["tenant_id"]
    client_id = cert["client_id"]

    credential = CertificateCredential(tenant_id, client_id, cert["cert_path"])
    await get_token(credential)

    credential = CertificateCredential(tenant_id,
                                       client_id,
                                       cert["cert_with_password_path"],
                                       password=cert["password"])
    await get_token(credential)

    credential = CertificateCredential(tenant_id,
                                       client_id,
                                       certificate_data=cert["cert_bytes"])
    await get_token(credential)

    credential = CertificateCredential(
        tenant_id,
        client_id,
        certificate_data=cert["cert_with_password_bytes"],
        password=cert["password"])
    await get_token(credential)
Exemplo n.º 5
0
async def test_persistent_cache_multiple_clients(cert_path, cert_password):
    """the credential shouldn't use tokens issued to other service principals"""

    access_token_a = "token a"
    access_token_b = "not " + access_token_a
    transport_a = async_validating_transport(
        requests=[Request()], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_a))]
    )
    transport_b = async_validating_transport(
        requests=[Request()], responses=[mock_response(json_payload=build_aad_response(access_token=access_token_b))]
    )

    cache = TokenCache()
    with patch("azure.identity._internal.persistent_cache._load_persistent_cache") as mock_cache_loader:
        mock_cache_loader.return_value = Mock(wraps=cache)
        credential_a = CertificateCredential(
            "tenant", "client-a", cert_path, password=cert_password, enable_persistent_cache=True, transport=transport_a
        )
        assert mock_cache_loader.call_count == 1, "credential should load the persistent cache"
        credential_b = CertificateCredential(
            "tenant", "client-b", cert_path, password=cert_password, enable_persistent_cache=True, transport=transport_b
        )
        assert mock_cache_loader.call_count == 2, "credential should load the persistent cache"

    # A caches a token
    scope = "scope"
    token_a = await credential_a.get_token(scope)
    assert token_a.token == access_token_a
    assert transport_a.send.call_count == 1

    # B should get a different token for the same scope
    token_b = await credential_b.get_token(scope)
    assert token_b.token == access_token_b
    assert transport_b.send.call_count == 1
Exemplo n.º 6
0
def test_enable_persistent_cache(cert_path, cert_password):
    """the credential should use the persistent cache only when given enable_persistent_cache=True"""

    persistent_cache = "azure.identity._internal.persistent_cache"
    required_arguments = ("tenant-id", "client-id", cert_path)

    # credential should default to an in memory cache
    raise_when_called = Mock(side_effect=Exception("credential shouldn't attempt to load a persistent cache"))
    with patch(persistent_cache + "._load_persistent_cache", raise_when_called):
        CertificateCredential(*required_arguments, password=cert_password)

        # allowing an unencrypted cache doesn't count as opting in to the persistent cache
        CertificateCredential(*required_arguments, password=cert_password, allow_unencrypted_cache=True)

    # keyword argument opts in to persistent cache
    with patch(persistent_cache + ".msal_extensions") as mock_extensions:
        CertificateCredential(*required_arguments, password=cert_password, enable_persistent_cache=True)
    assert mock_extensions.PersistedTokenCache.call_count == 1

    # opting in on an unsupported platform raises an exception
    with patch(persistent_cache + ".sys.platform", "commodore64"):
        with pytest.raises(NotImplementedError):
            CertificateCredential(*required_arguments, password=cert_password, enable_persistent_cache=True)
        with pytest.raises(NotImplementedError):
            CertificateCredential(
                *required_arguments, password=cert_password, enable_persistent_cache=True, allow_unencrypted_cache=True
            )
Exemplo n.º 7
0
def test_non_rsa_key():
    """The credential should raise ValueError when given a cert without an RSA private key"""
    with pytest.raises(ValueError, match=".*RS256.*"):
        CertificateCredential("tenant-id", "client-id", EC_CERT_PATH)
    with pytest.raises(ValueError, match=".*RS256.*"):
        CertificateCredential("tenant-id",
                              "client-id",
                              certificate_data=open(EC_CERT_PATH, "rb").read())
Exemplo n.º 8
0
def test_tenant_id_validation():
    """The credential should raise ValueError when given an invalid tenant_id"""

    valid_ids = {"c878a2ab-8ef4-413b-83a0-199afb84d7fb", "contoso.onmicrosoft.com", "organizations", "common"}
    for tenant in valid_ids:
        CertificateCredential(tenant, "client-id", PEM_CERT_PATH)

    invalid_ids = {"", "my tenant", "my_tenant", "/", "\\", '"', "'"}
    for tenant in invalid_ids:
        with pytest.raises(ValueError):
            CertificateCredential(tenant, "client-id", PEM_CERT_PATH)
Exemplo n.º 9
0
def test_requires_certificate():
    """the credential should raise ValueError when not given a certificate"""

    with pytest.raises(ValueError):
        CertificateCredential("tenant", "client-id")
    with pytest.raises(ValueError):
        CertificateCredential("tenant", "client-id", certificate_path=None)
    with pytest.raises(ValueError):
        CertificateCredential("tenant", "client-id", certificate_path="")
    with pytest.raises(ValueError):
        CertificateCredential("tenant", "client-id", certificate_data=None)
    with pytest.raises(ValueError):
        CertificateCredential("tenant", "client-id", certificate_path="", certificate_data=None)
Exemplo n.º 10
0
async def test_request_body(cert_path, cert_password):
    access_token = "***"
    authority = "authority.com"
    client_id = "client-id"
    expected_scope = "scope"
    tenant_id = "tenant"

    async def mock_send(request, **kwargs):
        assert request.body["grant_type"] == "client_credentials"
        assert request.body["scope"] == expected_scope

        with open(cert_path, "rb") as cert_file:
            validate_jwt(request, client_id, cert_file.read())

        return mock_response(json_payload={
            "token_type": "Bearer",
            "expires_in": 42,
            "access_token": access_token
        })

    cred = CertificateCredential(tenant_id,
                                 client_id,
                                 cert_path,
                                 password=cert_password,
                                 transport=Mock(send=mock_send),
                                 authority=authority)
    token = await cred.get_token("scope")

    assert token.token == access_token
Exemplo n.º 11
0
def test_certificate_arguments():
    """The credential should raise ValueError for mutually exclusive arguments"""

    with pytest.raises(ValueError) as ex:
        CertificateCredential("tenant-id", "client-id", certificate_path="...", certificate_data="...")
    message = str(ex.value)
    assert "certificate_data" in message and "certificate_path" in message
async 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)

    async 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 = await cred.get_token("scope")
    assert token.token == access_token
async 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)

    async 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 = await cred.get_token("scope")
    assert token.token == access_token
Exemplo n.º 14
0
async def test_multitenant_authentication(cert_path, cert_password):
    first_tenant = "first-tenant"
    first_token = "***"
    second_tenant = "second-tenant"
    second_token = first_token * 2

    async def send(request, **_):
        parsed = urlparse(request.url)
        tenant = parsed.path.split("/")[1]
        assert tenant in (first_tenant, second_tenant), 'unexpected tenant "{}"'.format(tenant)
        token = first_token if tenant == first_tenant else second_token
        return mock_response(json_payload=build_aad_response(access_token=token))

    credential = CertificateCredential(
        first_tenant,
        "client-id",
        cert_path,
        password=cert_password,
        transport=Mock(send=send),
    )
    token = await credential.get_token("scope")
    assert token.token == first_token

    token = await credential.get_token("scope", tenant_id=first_tenant)
    assert token.token == first_token

    token = await credential.get_token("scope", tenant_id=second_tenant)
    assert token.token == second_token

    # should still default to the first tenant
    token = await credential.get_token("scope")
    assert token.token == first_token
Exemplo n.º 15
0
async def test_close():
    transport = AsyncMockTransport()
    credential = CertificateCredential("tenant-id", "client-id", PEM_CERT_PATH, transport=transport)

    await credential.close()

    assert transport.__aexit__.call_count == 1
async def test_multitenant_authentication_backcompat(cert_path, cert_password):
    expected_tenant = "expected-tenant"
    expected_token = "***"

    async def send(request, **_):
        parsed = urlparse(request.url)
        tenant = parsed.path.split("/")[1]
        token = expected_token if tenant == expected_tenant else expected_token * 2
        return mock_response(json_payload=build_aad_response(
            access_token=token))

    credential = CertificateCredential(expected_tenant,
                                       "client-id",
                                       cert_path,
                                       password=cert_password,
                                       transport=Mock(send=send))

    token = await credential.get_token("scope")
    assert token.token == expected_token

    # explicitly specifying the configured tenant is okay
    token = await credential.get_token("scope", tenant_id=expected_tenant)
    assert token.token == expected_token

    token = await credential.get_token("scope",
                                       tenant_id="un" + expected_tenant)
    assert token.token == expected_token * 2
Exemplo n.º 17
0
def test_token_cache(cert_path, cert_password):
    """the credential should optionally use a persistent cache, and default to an in memory cache"""

    with patch(CertificateCredential.__module__ + "._load_persistent_cache") as load_persistent_cache:
        with patch(CertificateCredential.__module__ + ".msal") as mock_msal:
            CertificateCredential("tenant", "client-id", cert_path, password=cert_password)
        assert mock_msal.TokenCache.call_count == 1
        assert not load_persistent_cache.called

        CertificateCredential(
            "tenant",
            "client-id",
            cert_path,
            password=cert_password,
            cache_persistence_options=TokenCachePersistenceOptions(),
        )
        assert load_persistent_cache.call_count == 1
Exemplo n.º 18
0
async def test_user_agent():
    transport = async_validating_transport(
        requests=[Request(required_headers={"User-Agent": USER_AGENT})],
        responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
    )

    credential = CertificateCredential("tenant-id", "client-id", PEM_CERT_PATH, transport=transport)

    await credential.get_token("scope")
async def test_certificate_credential_with_password(
        live_certificate_with_password):
    credential = CertificateCredential(
        live_certificate_with_password["tenant_id"],
        live_certificate_with_password["client_id"],
        live_certificate_with_password["cert_path"],
        password=live_certificate_with_password["password"],
    )
    await get_token(credential)
Exemplo n.º 20
0
async def test_context_manager():
    transport = AsyncMockTransport()
    credential = CertificateCredential("tenant-id", "client-id", PEM_CERT_PATH, transport=transport)

    async with credential:
        assert transport.__aenter__.call_count == 1

    assert transport.__aenter__.call_count == 1
    assert transport.__aexit__.call_count == 1
Exemplo n.º 21
0
async def test_certificate_credential(live_certificate_settings):
    credential = CertificateCredential(
        live_certificate_settings["client_id"],
        live_certificate_settings["tenant_id"],
        live_certificate_settings["cert_path"],
    )
    token = await credential.get_token(ARM_SCOPE)
    assert token
    assert token.token
    assert token.expires_on
Exemplo n.º 22
0
async def test_policies_configurable():
    policy = Mock(spec_set=SansIOHTTPPolicy, on_request=Mock())

    async def send(*_, **__):
        return mock_response(json_payload=build_aad_response(access_token="**"))

    credential = CertificateCredential(
        "tenant-id", "client-id", PEM_CERT_PATH, policies=[ContentDecodePolicy(), policy], transport=Mock(send=send)
    )

    await credential.get_token("scope")

    assert policy.on_request.called
async def test_request_url(cert_path, cert_password):
    authority = "authority.com"
    tenant_id = "expected_tenant"
    access_token = "***"

    def validate_url(url):
        parsed = urlparse(url)
        assert parsed.scheme == "https"
        assert parsed.netloc == authority
        assert parsed.path.startswith("/" + tenant_id)

    async 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,
                                 password=cert_password,
                                 transport=Mock(send=mock_send),
                                 authority=authority)
    token = await cred.get_token("scope")
    assert token.token == access_token

    # authority can be configured via environment variable
    with patch.dict("os.environ",
                    {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority},
                    clear=True):
        credential = CertificateCredential(tenant_id,
                                           "client-id",
                                           cert_path,
                                           password=cert_password,
                                           transport=Mock(send=mock_send))
        await credential.get_token("scope")
    assert token.token == access_token
Exemplo n.º 24
0
async def test_multitenant_authentication_backcompat(cert_path, cert_password):
    """When allow_multitenant_authentication is True, the credential should respect get_token(tenant_id=...)"""

    expected_tenant = "expected-tenant"
    expected_token = "***"

    async def send(request, **_):
        parsed = urlparse(request.url)
        tenant = parsed.path.split("/")[1]
        token = expected_token if tenant == expected_tenant else expected_token * 2
        return mock_response(json_payload=build_aad_response(
            access_token=token))

    credential = CertificateCredential(expected_tenant,
                                       "client-id",
                                       cert_path,
                                       password=cert_password,
                                       transport=Mock(send=send))

    token = await credential.get_token("scope")
    assert token.token == expected_token

    # explicitly specifying the configured tenant is okay
    token = await credential.get_token("scope", tenant_id=expected_tenant)
    assert token.token == expected_token

    # but any other tenant should get an error
    with pytest.raises(ClientAuthenticationError,
                       match="allow_multitenant_authentication"):
        await credential.get_token("scope", tenant_id="un" + expected_tenant)

    # ...unless the compat switch is enabled
    with patch.dict("os.environ", {
            EnvironmentVariables.AZURE_IDENTITY_ENABLE_LEGACY_TENANT_SELECTION:
            "true"
    },
                    clear=True):
        token = await credential.get_token("scope",
                                           tenant_id="un" + expected_tenant)
    assert token.token == expected_token, "credential should ignore tenant_id kwarg when the compat switch is enabled"
Exemplo n.º 25
0
async def test_no_scopes():
    """The credential should raise ValueError when get_token is called with no scopes"""

    credential = CertificateCredential("tenant-id", "client-id", PEM_CERT_PATH)
    with pytest.raises(ValueError):
        await credential.get_token()
Exemplo n.º 26
0
async def test_certificate_credential(live_certificate):
    credential = CertificateCredential(live_certificate["tenant_id"],
                                       live_certificate["client_id"],
                                       live_certificate["cert_path"])
    await get_token(credential)