Ejemplo n.º 1
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:
        record = AuthenticationRecord(tenant, "client-id", "authority",
                                      "home.account.id", "username")
        SharedTokenCacheCredential(_authentication_record=record)
        SharedTokenCacheCredential(_authentication_record=record,
                                   tenant_id=tenant)

    invalid_ids = {
        "", "my tenant", "my_tenant", "/", "\\", '"my-tenant"', "'my-tenant'"
    }
    for tenant in invalid_ids:
        record = AuthenticationRecord(tenant, "client-id", "authority",
                                      "home.account.id", "username")
        with pytest.raises(ValueError):
            SharedTokenCacheCredential(_authentication_record=record)
        with pytest.raises(ValueError):
            SharedTokenCacheCredential(_authentication_record=record,
                                       tenant_id=tenant)
async def test_authentication_record_no_match():
    tenant_id = "tenant-id"
    client_id = "client-id"
    authority = "localhost"
    object_id = "object-id"
    home_account_id = object_id + "." + tenant_id
    username = "******"
    record = AuthenticationRecord(tenant_id, client_id, authority,
                                  home_account_id, username)

    transport = Mock(
        side_effect=Exception("the credential shouldn't send a request"))
    cache = populated_cache(
        get_account_event(
            "not-" + username,
            "not-" + object_id,
            "different-" + tenant_id,
            client_id="not-" + client_id,
        ), )
    credential = SharedTokenCacheCredential(_authentication_record=record,
                                            transport=transport,
                                            _cache=cache)

    with pytest.raises(CredentialUnavailableError):
        await credential.get_token("scope")
def test_disable_automatic_authentication():
    """When silent auth fails the credential should raise, if it's configured not to authenticate automatically"""

    expected_details = "something went wrong"
    record = AuthenticationRecord("tenant-id", "client-id", "localhost",
                                  "object.tenant", "username")
    msal_app = Mock(
        acquire_token_silent_with_error=Mock(
            return_value={"error_description": expected_details}),
        get_accounts=Mock(
            return_value=[{
                "home_account_id": record.home_account_id
            }]),
    )

    credential = MockCredential(
        _authentication_record=record,
        _disable_automatic_authentication=True,
        msal_app_factory=lambda *_, **__: msal_app,
        request_token=Mock(side_effect=Exception(
            "credential shouldn't begin interactive authentication")),
    )

    scope = "scope"
    with pytest.raises(AuthenticationRequiredError) as ex:
        credential.get_token(scope)

    # the exception should carry the requested scopes and any error message from AAD
    assert ex.value.scopes == (scope, )
    assert ex.value.error_details == expected_details
Ejemplo n.º 4
0
def test_authentication_record_no_match():
    tenant_id = "tenant-id"
    client_id = "client-id"
    authority = "localhost"
    object_id = "object-id"
    home_account_id = object_id + "." + tenant_id
    username = "******"
    record = AuthenticationRecord(tenant_id, client_id, authority,
                                  home_account_id, username)

    def send(request, **_):
        # expecting only MSAL discovery requests
        assert request.method == "GET"
        return get_discovery_response()

    cache = populated_cache(
        get_account_event(
            "not-" + username,
            "not-" + object_id,
            "different-" + tenant_id,
            client_id="not-" + client_id,
        ), )
    credential = SharedTokenCacheCredential(_authentication_record=record,
                                            transport=Mock(send=send),
                                            _cache=cache)

    with pytest.raises(CredentialUnavailableError):
        credential.get_token("scope")
async def test_authentication_record_empty_cache():
    record = AuthenticationRecord("tenant_id", "client_id", "authority",
                                  "home_account_id", "username")
    transport = Mock(
        side_effect=Exception("the credential shouldn't send a request"))
    credential = SharedTokenCacheCredential(_authentication_record=record,
                                            transport=transport,
                                            _cache=TokenCache())

    with pytest.raises(CredentialUnavailableError):
        await credential.get_token("scope")
def test_serialization():
    """serialize should accept arbitrary additional key/value pairs, which deserialize should ignore"""

    attrs = ("authority", "client_id", "home_account_id", "tenant_id",
             "username")
    nums = (n for n in range(len(attrs)))
    record_values = {attr: next(nums) for attr in attrs}

    record = AuthenticationRecord(**record_values)
    serialized = record.serialize()

    # AuthenticationRecord's fields should have been serialized
    assert json.loads(serialized) == record_values

    deserialized = AuthenticationRecord.deserialize(serialized)

    # the deserialized record and the constructed record should have the same fields
    assert sorted(vars(deserialized)) == sorted(vars(record))

    # the constructed and deserialized records should have the same values
    assert all(
        getattr(deserialized, attr) == record_values[attr] for attr in attrs)
Ejemplo n.º 7
0
def test_authentication_record_empty_cache():
    record = AuthenticationRecord("tenant-id", "client_id", "authority",
                                  "home_account_id", "username")

    def send(request, **_):
        # expecting only MSAL discovery requests
        assert request.method == "GET"
        return get_discovery_response()

    credential = SharedTokenCacheCredential(_authentication_record=record,
                                            transport=Mock(send=send),
                                            _cache=TokenCache())

    with pytest.raises(CredentialUnavailableError):
        credential.get_token("scope")
Ejemplo n.º 8
0
def test_auth_record_multiple_accounts_for_username():
    tenant_id = "tenant-id"
    client_id = "client-id"
    authority = "localhost"
    object_id = "object-id"
    home_account_id = object_id + "." + tenant_id
    username = "******"
    record = AuthenticationRecord(tenant_id, client_id, authority,
                                  home_account_id, username)

    expected_access_token = "****"
    expected_refresh_token = "**"
    expected_account = get_account_event(username,
                                         object_id,
                                         tenant_id,
                                         authority=authority,
                                         client_id=client_id,
                                         refresh_token=expected_refresh_token)
    cache = populated_cache(
        expected_account,
        get_account_event(  # this account matches all but the record's tenant
            username,
            object_id,
            "different-" + tenant_id,
            authority=authority,
            client_id=client_id,
            refresh_token="not-" + expected_refresh_token,
        ),
    )

    transport = msal_validating_transport(
        endpoint="https://{}/{}".format(authority, tenant_id),
        requests=[
            Request(authority=authority,
                    required_data={"refresh_token": expected_refresh_token})
        ],
        responses=[
            mock_response(json_payload=build_aad_response(
                access_token=expected_access_token))
        ],
    )
    credential = SharedTokenCacheCredential(_authentication_record=record,
                                            transport=transport,
                                            _cache=cache)

    token = credential.get_token("scope")
    assert token.token == expected_access_token
Ejemplo n.º 9
0
def test_get_token_wraps_exceptions():
    """get_token shouldn't propagate exceptions from MSAL"""

    class CustomException(Exception):
        pass

    expected_message = "something went wrong"
    record = AuthenticationRecord("tenant-id", "client-id", "localhost", "object.tenant", "username")
    msal_app = Mock(
        acquire_token_silent_with_error=Mock(side_effect=CustomException(expected_message)),
        get_accounts=Mock(return_value=[{"home_account_id": record.home_account_id}]),
    )
    credential = MockCredential(msal_app_factory=lambda *_, **__: msal_app, _authentication_record=record)
    with pytest.raises(ClientAuthenticationError) as ex:
        credential.get_token("scope")

    assert expected_message in ex.value.message
    assert msal_app.acquire_token_silent_with_error.call_count == 1, "credential didn't attempt silent auth"
Ejemplo n.º 10
0
def test_authentication_record_argument():
    """The credential should initialize its msal.ClientApplication with values from a given record"""

    record = AuthenticationRecord("tenant-id", "client-id", "localhost", "object.tenant", "username")

    def validate_app_parameters(authority, client_id, **_):
        # the 'authority' argument to msal.ClientApplication should be a URL of the form https://authority/tenant
        assert authority == "https://{}/{}".format(record.authority, record.tenant_id)
        assert client_id == record.client_id
        return Mock(get_accounts=Mock(return_value=[]))

    app_factory = Mock(wraps=validate_app_parameters)
    credential = MockCredential(
        _authentication_record=record, _disable_automatic_authentication=True, msal_app_factory=app_factory,
    )
    with pytest.raises(AuthenticationRequiredError):
        credential.get_token("scope")

    assert app_factory.call_count == 1, "credential didn't create an msal application"
async def test_authentication_record_authenticating_tenant():
    """when given a record and 'tenant_id', the credential should authenticate in the latter"""

    expected_tenant_id = "tenant-id"
    record = AuthenticationRecord("not- " + expected_tenant_id, "...", "...",
                                  "...", "...")

    with patch.object(SharedTokenCacheCredential,
                      "_get_auth_client") as get_auth_client:
        credential = SharedTokenCacheCredential(_authentication_record=record,
                                                _cache=TokenCache(),
                                                tenant_id=expected_tenant_id)
        with pytest.raises(CredentialUnavailableError):
            # this raises because the cache is empty
            await credential.get_token("scope")

    assert get_auth_client.call_count == 1
    _, kwargs = get_auth_client.call_args
    assert kwargs["tenant_id"] == expected_tenant_id
Ejemplo n.º 12
0
def test_tenant_argument_overrides_record():
    """The 'tenant_ic' keyword argument should override a given record's value"""

    tenant_id = "some-guid"
    authority = "localhost"
    record = AuthenticationRecord(tenant_id, "client-id", authority, "object.tenant", "username")

    expected_tenant = tenant_id[::-1]
    expected_authority = "https://{}/{}".format(authority, expected_tenant)

    def validate_authority(authority, **_):
        assert authority == expected_authority
        return Mock(get_accounts=Mock(return_value=[]))

    credential = MockCredential(
        _authentication_record=record,
        tenant_id=expected_tenant,
        _disable_automatic_authentication=True,
        msal_app_factory=validate_authority,
    )
    with pytest.raises(AuthenticationRequiredError):
        credential.get_token("scope")
Ejemplo n.º 13
0
def test_authentication_record_authenticating_tenant():
    """when given a record and 'tenant_id', the credential should authenticate in the latter"""

    expected_tenant_id = "tenant-id"
    record = AuthenticationRecord("not- " + expected_tenant_id, "...",
                                  "localhost", "...", "...")

    def mock_send(request, **_):
        if not request.body:
            return get_discovery_response()
        assert request.url.startswith("https://localhost/" +
                                      expected_tenant_id)
        return mock_response(json_payload=build_aad_response(access_token="*"))

    transport = Mock(send=Mock(wraps=mock_send))
    credential = SharedTokenCacheCredential(_authentication_record=record,
                                            _cache=TokenCache(),
                                            tenant_id=expected_tenant_id,
                                            transport=transport)
    with pytest.raises(CredentialUnavailableError):
        credential.get_token("scope")  # this raises because the cache is empty

    assert transport.send.called
async def test_authentication_record():
    tenant_id = "tenant-id"
    client_id = "client-id"
    authority = "localhost"
    object_id = "object-id"
    home_account_id = object_id + "." + tenant_id
    username = "******"
    record = AuthenticationRecord(tenant_id, client_id, authority,
                                  home_account_id, username)

    expected_access_token = "****"
    expected_refresh_token = "**"
    account = get_account_event(username,
                                object_id,
                                tenant_id,
                                authority=authority,
                                client_id=client_id,
                                refresh_token=expected_refresh_token)
    cache = populated_cache(account)

    transport = async_validating_transport(
        requests=[
            Request(authority=authority,
                    required_data={"refresh_token": expected_refresh_token})
        ],
        responses=[
            mock_response(json_payload=build_aad_response(
                access_token=expected_access_token))
        ],
    )
    credential = SharedTokenCacheCredential(_authentication_record=record,
                                            transport=transport,
                                            _cache=cache)

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