def test_exception_with_api_key_and_adc_env_var():
    with mock.patch.dict(os.environ, {environment_vars.API_KEY: "api-key"}):
        with mock.patch.dict(os.environ,
                             {environment_vars.CREDENTIALS: "/path/to/json"}):
            with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
                _default.default()

            assert excinfo.match(
                r"GOOGLE_API_KEY and GOOGLE_APPLICATION_CREDENTIALS are mutually exclusive"
            )
def test_default_environ_external_credentials_bad_format(monkeypatch, tmpdir):
    filename = tmpdir.join("external_account_bad.json")
    filename.write(json.dumps({"type": "external_account"}))
    monkeypatch.setenv(environment_vars.CREDENTIALS, str(filename))

    with pytest.raises(exceptions.DefaultCredentialsError) as excinfo:
        _default.default()

    assert excinfo.match(
        "Failed to load external account credentials from {}".format(
            str(filename)))
    def Run(self, args):
        """Run the helper command."""
        impersonate_service_account = (
            properties.VALUES.auth.impersonate_service_account.Get())
        if impersonate_service_account:
            log.warning(
                "Impersonate service account '{}' is detected. This command cannot be"
                ' used to print the access token for an impersonate account. The '
                "token below is still the application default credentials' access "
                'token.'.format(impersonate_service_account))

        try:
            creds, _ = google_auth_default.default(
                scopes=[auth_util.CLOUD_PLATFORM_SCOPE])
        except google_auth_exceptions.DefaultCredentialsError as e:
            log.debug(e, exc_info=True)
            raise c_exc.ToolException(six.text_type(e))

        # Converts the user credentials so that it can handle reauth during refresh.
        if isinstance(creds, google_auth_creds.Credentials):
            creds = c_google_auth.UserCredWithReauth.FromGoogleAuthUserCredentials(
                creds)
        with c_store.HandleGoogleAuthCredentialsRefreshError(for_adc=True):
            creds.refresh(http.GoogleAuthRequest())
        return creds
def test_default_scoped(with_scopes_mock, get_mock):
    scopes = ['one', 'two']

    credentials, project_id = _default.default(scopes=scopes)

    assert credentials == with_scopes_mock.return_value
    assert project_id == mock.sentinel.project_id
    with_scopes_mock.assert_called_once_with(mock.sentinel.credentials, scopes)
Beispiel #5
0
def test_default_scoped(with_scopes, unused_get):
    scopes = ["one", "two"]

    credentials, project_id = _default.default(scopes=scopes)

    assert credentials == with_scopes.return_value
    assert project_id == mock.sentinel.project_id
    with_scopes.assert_called_once_with(mock.sentinel.credentials, scopes)
def test_default_impersonated_service_account_set_both_scopes_and_default_scopes(
        get_adc_path):
    get_adc_path.return_value = IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_FILE
    scopes = ["scope1", "scope2"]
    default_scopes = ["scope3", "scope4"]

    credentials, _ = _default.default(scopes=scopes,
                                      default_scopes=default_scopes)
    assert credentials._target_scopes == scopes
def test_default_environ_external_credentials(get_project_id, monkeypatch, tmpdir):
    config_file = tmpdir.join("config.json")
    config_file.write(json.dumps(IDENTITY_POOL_DATA))
    monkeypatch.setenv(environment_vars.CREDENTIALS, str(config_file))

    credentials, project_id = _default.default()

    assert isinstance(credentials, identity_pool.Credentials)
    # Without scopes, project ID cannot be determined.
    assert project_id is None
def test_default_impersonated_service_account(get_adc_path):
    get_adc_path.return_value = IMPERSONATED_SERVICE_ACCOUNT_AUTHORIZED_USER_SOURCE_FILE

    credentials, _ = _default.default()

    assert isinstance(credentials, impersonated_credentials.Credentials)
    assert isinstance(credentials._source_credentials,
                      google.oauth2.credentials.Credentials)
    assert credentials.service_account_email == "*****@*****.**"
    assert credentials._delegates == ["*****@*****.**"]
    assert not credentials._quota_project_id
    assert not credentials._target_scopes
def test_default_no_app_engine_compute_engine_module(unused_get):
    """
    google.auth.compute_engine and google.auth.app_engine are both optional
    to allow not including them when using this package. This verifies
    that default fails gracefully if these modules are absent
    """
    import sys

    with mock.patch.dict("sys.modules"):
        sys.modules["google.auth.compute_engine"] = None
        sys.modules["google.auth.app_engine"] = None
        assert _default.default() == (MOCK_CREDENTIALS, mock.sentinel.project_id)
def test_default_environ_external_credentials_workforce_impersonated(
        get_project_id, monkeypatch, tmpdir):
    config_file = tmpdir.join("config.json")
    config_file.write(json.dumps(IMPERSONATED_IDENTITY_POOL_WORKFORCE_DATA))
    monkeypatch.setenv(environment_vars.CREDENTIALS, str(config_file))

    credentials, project_id = _default.default(
        scopes=["https://www.google.com/calendar/feeds"])

    assert isinstance(credentials, identity_pool.Credentials)
    assert not credentials.is_user
    assert credentials.is_workforce_pool
    assert project_id is mock.sentinel.project_id
    assert credentials.scopes == ["https://www.google.com/calendar/feeds"]
def test_default_environ_external_credentials_explicit_request_with_scopes(
        get_project_id, monkeypatch, tmpdir):
    config_file = tmpdir.join("config.json")
    config_file.write(json.dumps(IDENTITY_POOL_DATA))
    monkeypatch.setenv(environment_vars.CREDENTIALS, str(config_file))

    credentials, project_id = _default.default(
        request=mock.sentinel.request,
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )

    assert isinstance(credentials, identity_pool.Credentials)
    assert project_id is mock.sentinel.project_id
    # default() will initialize new credentials via with_scopes_if_required
    # and potentially with_quota_project.
    # As a result the caller of get_project_id() will not match the returned
    # credentials.
    get_project_id.assert_called_with(mock.ANY, request=mock.sentinel.request)
def test_default_environ_external_credentials_with_user_and_default_scopes_and_quota_project_id(
        get_project_id, monkeypatch, tmpdir):
    config_file = tmpdir.join("config.json")
    config_file.write(json.dumps(IDENTITY_POOL_DATA))
    monkeypatch.setenv(environment_vars.CREDENTIALS, str(config_file))

    credentials, project_id = _default.default(
        scopes=["https://www.google.com/calendar/feeds"],
        default_scopes=["https://www.googleapis.com/auth/cloud-platform"],
        quota_project_id="project-foo",
    )

    assert isinstance(credentials, identity_pool.Credentials)
    assert project_id is mock.sentinel.project_id
    assert credentials.quota_project_id == "project-foo"
    assert credentials.scopes == ["https://www.google.com/calendar/feeds"]
    assert credentials.default_scopes == [
        "https://www.googleapis.com/auth/cloud-platform"
    ]
Beispiel #13
0
def test_default_without_project_id(unused_gce, unused_gae, unused_sdk,
                                    unused_explicit, logger_warning):
    assert _default.default() == (mock.sentinel.credentials, None)
    logger_warning.assert_called_with(mock.ANY, mock.ANY, mock.ANY)
Beispiel #14
0
def test_default_explict_project_id(unused_get, monkeypatch):
    monkeypatch.setenv(environment_vars.PROJECT, "explicit-env")
    assert _default.default() == (mock.sentinel.credentials, "explicit-env")
def test_default_quota_project(with_quota_project):
    credentials, project_id = _default.default(quota_project_id="project-foo")

    MOCK_CREDENTIALS.with_quota_project.assert_called_once_with("project-foo")
    assert project_id == mock.sentinel.project_id
def test_default_fail(unused_gce, unused_gae, unused_sdk, unused_explicit):
    with pytest.raises(exceptions.DefaultCredentialsError):
        assert _default.default()
def test_default_api_key_from_env_var():
    with mock.patch.dict(os.environ, {environment_vars.API_KEY: "api-key"}):
        cred, project_id = _default.default()
        assert isinstance(cred, api_key.Credentials)
        assert cred.token == "api-key"
        assert project_id is None
def test_default_no_warning_with_quota_project_id_for_user_creds(get_adc_path):
    get_adc_path.return_value = AUTHORIZED_USER_CLOUD_SDK_FILE

    credentials, project_id = _default.default(quota_project_id="project-foo")
def test_default_warning_without_quota_project_id_for_user_creds(get_adc_path):
    get_adc_path.return_value = AUTHORIZED_USER_CLOUD_SDK_FILE

    with pytest.warns(UserWarning, match="Cloud SDK"):
        credentials, project_id = _default.default(quota_project_id=None)
def test_default_early_out(get_mock):
    assert _default.default() == (mock.sentinel.credentials,
                                  mock.sentinel.project_id)
def test_default_explict_legacy_project_id(get_mock, monkeypatch):
    monkeypatch.setenv(environment_vars.LEGACY_PROJECT, 'explicit-env')
    assert _default.default() == (mock.sentinel.credentials, 'explicit-env')
def test_default_explict_legacy_project_id(unused_get, monkeypatch):
    monkeypatch.setenv(environment_vars.LEGACY_PROJECT, "explicit-env")
    assert _default.default() == (MOCK_CREDENTIALS, "explicit-env")
def test_default_early_out(unused_get):
    assert _default.default() == (MOCK_CREDENTIALS, mock.sentinel.project_id)
def test_default_without_project_id(unused_gce, unused_gae, unused_sdk,
                                    unused_explicit, logger_warning):
    assert _default.default() == (MOCK_CREDENTIALS, None)
    logger_warning.assert_called_with(mock.ANY, mock.ANY, mock.ANY)