Exemple #1
0
def test_regions_client_service_account_always_use_jwt(transport_class, transport_name):
    with mock.patch.object(
        service_account.Credentials, "with_always_use_jwt_access", create=True
    ) as use_jwt:
        creds = service_account.Credentials(None, None, None)
        transport = transport_class(credentials=creds, always_use_jwt_access=True)
        use_jwt.assert_called_once_with(True)

    with mock.patch.object(
        service_account.Credentials, "with_always_use_jwt_access", create=True
    ) as use_jwt:
        creds = service_account.Credentials(None, None, None)
        transport = transport_class(credentials=creds, always_use_jwt_access=False)
        use_jwt.assert_not_called()
def delegated_credential(credentials, subject, scopes):
    try:
        admin_creds = credentials.with_subject(subject).with_scopes(scopes)
    except AttributeError:  # Looks like a compute creds object

        # Refresh the boostrap credentials. This ensures that the information
        # about this account, notably the email, is populated.
        request = requests.Request()
        credentials.refresh(request)

        # Create an IAM signer using the bootstrap credentials.
        signer = iam.Signer(request, credentials,
                            credentials.service_account_email)

        # Create OAuth 2.0 Service Account credentials using the IAM-based
        # signer and the bootstrap_credential's service account email.
        admin_creds = service_account.Credentials(
            signer,
            credentials.service_account_email,
            TOKEN_URI,
            scopes=scopes,
            subject=subject)
    except Exception:
        raise

    return admin_creds
Exemple #3
0
def get_google_open_id_connect_token(service_account_file, oauth_client_id):
    """
    Get an OpenID Connect token issued by Google for the service account.
    """
    svc = service_account.Credentials.from_service_account_file(
        service_account_file, scopes=SCOPE)

    service_account_credentials = service_account.Credentials(
        svc.signer,
        svc.service_account_email,
        token_uri=OAUTH_TOKEN_URI,
        additional_claims={'target_audience': oauth_client_id})

    service_account_jwt = service_account_credentials._make_authorization_grant_assertion(
    )

    request = google.auth.transport.requests.Request()

    body = {
        'assertion': service_account_jwt,
        'grant_type': google.oauth2._client._JWT_GRANT_TYPE,
    }

    token_response = google.oauth2._client._token_endpoint_request(
        request, OAUTH_TOKEN_URI, body)

    return token_response['id_token']
Exemple #4
0
def _make_delegated_credentials(credentials, user_email, scopes):
    """Make delegated credentials.
    Allows a service account to impersonate the user passed in `user_email`,
    using a restricted set of scopes.
    Args:
        credentials (service_account.Credentials): The service account credentials.
        user_email (str): The email for the user to impersonate.
        scopes (list): A list of scopes.
    Returns:
        service_account.Credentials: The delegated credentials
    """
    request = requests.Request()
    credentials = with_scopes_if_required(credentials, _TOKEN_SCOPE)
    credentials.refresh(request)
    email = credentials.service_account_email
    signer = iam.Signer(
        request,
        credentials,
        email)
    return service_account.Credentials(
        signer,
        email,
        _TOKEN_URI,
        scopes=scopes,
        subject=user_email)
Exemple #5
0
    def test_refresh_jwt_not_used_for_domain_wide_delegation(
        self, self_signed_jwt_refresh, jwt_grant
    ):
        # Create a domain wide delegation credentials by setting the subject.
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            always_use_jwt_access=True,
            subject="subject",
        )
        credentials._create_self_signed_jwt("https://pubsub.googleapis.com")
        jwt_grant.return_value = (
            "token",
            _helpers.utcnow() + datetime.timedelta(seconds=500),
            {},
        )
        request = mock.create_autospec(transport.Request, instance=True)

        # Refresh credentials
        credentials.refresh(request)

        # Make sure we are using jwt_grant and not self signed JWT refresh
        # method to obtain the token.
        assert jwt_grant.called
        assert not self_signed_jwt_refresh.called
def test_event_service_client_service_account_always_use_jwt(client_class):
    with mock.patch.object(service_account.Credentials,
                           "with_always_use_jwt_access",
                           create=True) as use_jwt:
        creds = service_account.Credentials(None, None, None)
        client = client_class(credentials=creds)
        use_jwt.assert_not_called()
    def test__create_self_signed_jwt(self, from_signing_credentials):
        credentials = service_account.Credentials(SIGNER,
                                                  self.SERVICE_ACCOUNT_EMAIL,
                                                  self.TOKEN_URI)

        audience = "https://pubsub.googleapis.com"
        credentials._create_self_signed_jwt(audience)
        from_signing_credentials.assert_called_once_with(credentials, audience)
 def testIsServiceAccountCredential(self):
     oauth2client_cred = service_account.ServiceAccountCredentials(
         None, 'email')
     google_auth_cred = google_auth_service_account.Credentials(
         None, 'email', 'token_uri')
     self.assertTrue(
         auth_util.IsServiceAccountCredential(oauth2client_cred))
     self.assertTrue(auth_util.IsServiceAccountCredential(google_auth_cred))
Exemple #9
0
def test_video_intelligence_service_client_service_account_always_use_jwt_true(
        transport_class, transport_name):
    with mock.patch.object(service_account.Credentials,
                           "with_always_use_jwt_access",
                           create=True) as use_jwt:
        creds = service_account.Credentials(None, None, None)
        transport = transport_class(credentials=creds,
                                    always_use_jwt_access=True)
        use_jwt.assert_called_once_with(True)
Exemple #10
0
def test_license_notification_service_client_service_account_always_use_jwt_true(
        transport_class, transport_name):
    with mock.patch.object(service_account.Credentials,
                           'with_always_use_jwt_access',
                           create=True) as use_jwt:
        creds = service_account.Credentials(None, None, None)
        transport = transport_class(credentials=creds,
                                    always_use_jwt_access=True)
        use_jwt.assert_called_once_with(True)
Exemple #11
0
    def test_apply_with_no_quota_project_id(self):
        credentials = service_account.Credentials(SIGNER,
                                                  self.SERVICE_ACCOUNT_EMAIL,
                                                  self.TOKEN_URI)

        headers = {}
        credentials.apply(headers, token="token")

        assert "x-goog-user-project" not in headers
        assert "token" in headers["authorization"]
Exemple #12
0
    def test__create_self_signed_jwt_always_use_jwt_access(self, jwt):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            always_use_jwt_access=True,
        )

        credentials._create_self_signed_jwt(None)
        jwt.from_signing_credentials.assert_not_called()
Exemple #13
0
    def test__create_self_signed_jwt_with_user_scopes(self, jwt):
        credentials = service_account.Credentials(
            SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI, scopes=["foo"]
        )

        audience = "https://pubsub.googleapis.com"
        credentials._create_self_signed_jwt(audience)

        # JWT should not be created if there are user-defined scopes
        jwt.from_signing_credentials.assert_not_called()
 def testValidate(self):
     """Tests that the credentials type is validated."""
     prop = oauth2_util.CredentialsProperty()
     # None is allowed
     prop._validate(None)
     # User authorization and service accounts are allowed
     prop._validate(authorized_user.Credentials(None))
     prop._validate(service_account.Credentials(None, None, None))
     # Anything else is forbidden
     with self.assertRaises(TypeError):
         prop._validate({})
Exemple #15
0
def init_service_account_credentials(args):
    global service_account_credentials

    with open(args['gee_key_path'], 'r') as file_:
        key_data = file_.read()
    signer = crypt.RSASigner.from_string(key_data)
    service_account_credentials = service_account.Credentials(
        signer=signer,
        service_account_email=args['gee_email'],
        token_uri=ee.oauth.TOKEN_URI,
        scopes=ee.oauth.SCOPES + ['https://www.googleapis.com/auth/drive'])
Exemple #16
0
    def test__create_self_signed_jwt_always_use_jwt_access_with_audience(self, jwt):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            default_scopes=["bar", "foo"],
            always_use_jwt_access=True,
        )

        audience = "https://pubsub.googleapis.com"
        credentials._create_self_signed_jwt(audience)
        jwt.from_signing_credentials.assert_called_once_with(credentials, audience)
Exemple #17
0
 def testAuthorizeWithServiceAccount(self, mock_parse_key):
     """Tests that an action can be authorized with a service account."""
     action_id = self.test_run_actions[1].key.id()  # unauthorized
     # Mock parsing service account JSON key
     mock_parse_key.return_value = service_account.Credentials(
         None, None, None)
     # Verify that credentials were obtained and stored
     self.app.put_json(
         '/_ah/api/mtt/v1/test_run_actions/%s/auth' % action_id,
         {'value': '{}'})
     action = ndb_models.TestRunAction.get_by_id(action_id)
     self.assertIsNotNone(action.credentials)
Exemple #18
0
    def test__create_self_signed_jwt_always_use_jwt_access_with_default_scopes(
            self, jwt):
        credentials = service_account.Credentials(
            SIGNER,
            self.SERVICE_ACCOUNT_EMAIL,
            self.TOKEN_URI,
            default_scopes=["bar", "foo"],
            always_use_jwt_access=True,
        )

        credentials._create_self_signed_jwt(None)
        jwt.from_signing_credentials.assert_called_once_with(
            credentials, None, additional_claims={"scope": "bar foo"})
 def testAuthorizeConfigWithServiceAccount(self, mock_parse_key):
     """Tests that a build channel can be authorized with a service account."""
     config = self._CreateMockBuildChannel(name='android',
                                           provider='Android')
     # Mock parsing service account JSON key
     mock_parse_key.return_value = service_account.Credentials(
         None, None, None)
     # Verify that credentials were obtained and stored
     self.app.put_json(
         '/_ah/api/mtt/v1/build_channels/%s/auth' % config.key.id(),
         {'value': '{}'})
     config = ndb_models.BuildChannelConfig.get_by_id(config.key.id())
     self.assertIsNotNone(config.credentials)
    def testRemoveDefaultServiceAccount(self):
        """Tests removing the default service account."""
        credentials = service_account.Credentials(None, None, None)
        private_node_config = ndb_models.GetPrivateNodeConfig()
        private_node_config.default_credentials = credentials
        private_node_config.put()

        # Remove default auth
        self.app.delete(
            '/_ah/api/mtt/v1/private_node_config/default_service_account')

        # Verify that credentials were cleared
        private_node_config = ndb_models.GetPrivateNodeConfig()
        self.assertIsNone(private_node_config.default_credentials)
    def testSetDefaultServiceAccount(self, mock_parse_key):
        """Tests setting the default service account."""

        # Mock parsing service account JSON key
        mock_parse_key.return_value = service_account.Credentials(
            None, None, None)
        # Set default auth
        self.app.put_json(
            '/_ah/api/mtt/v1/private_node_config/default_service_account',
            {'value': '{}'})

        # Verify that credentials were set
        private_node_config = ndb_models.GetPrivateNodeConfig()
        self.assertIsNotNone(private_node_config.default_credentials)
def get_delegated_credentials(credentials, subject, scopes):
    try:
        request = requests.Request()
        credentials.refresh(request)

        signer = iam.Signer(request, credentials, config.GMAIL_SERVICE_ACCOUNT)
        creds = service_account.Credentials(
            signer=signer,
            service_account_email=config.GMAIL_SERVICE_ACCOUNT,
            token_uri=TOKEN_URI,
            scopes=scopes,
            subject=subject)
    except Exception:
        raise

    return creds
def request_auth_token():
    try:
        credentials, project_id = google.auth.default(
            scopes=['https://www.googleapis.com/auth/iam'])

        request = gcp_requests.Request()
        credentials.refresh(request)

        signer = iam.Signer(request, credentials, config.DELEGATED_SA)
        creds = service_account.Credentials(
            signer=signer,
            service_account_email=config.DELEGATED_SA,
            token_uri=TOKEN_URI,
            scopes=['https://www.googleapis.com/auth/cloud-platform'],
            subject=config.DELEGATED_SA)
    except Exception:
        raise

    return creds
Exemple #24
0
  def testAttachAccessTokenCacheStoreGoogleAuth(self):
    # Create credentials.
    credentials = google_auth_service_account.Credentials(
        None, 'email', 'token_uri')
    self.assertIsNone(credentials.token)

    # Create access token cache.
    access_token_cache = creds.AccessTokenCache(
        config.Paths().access_token_db_path)
    access_token_cache.Store(
        credentials.service_account_email,
        access_token='token1',
        token_expiry=datetime.datetime.utcnow() +
        datetime.timedelta(seconds=3600),
        rapt_token=None,
        id_token=None)

    # Attach access token cache store to credentials.
    new_creds = creds.MaybeAttachAccessTokenCacheStoreGoogleAuth(credentials)
    self.assertEqual(new_creds.token, 'token1')
    def request_auth_token(self):
        try:
            credentials, project_id = google.auth.default(
                scopes=["https://www.googleapis.com/auth/iam"])

            request = gcp_requests.Request()
            credentials.refresh(request)

            signer = iam.Signer(request, credentials, config.DELEGATED_SA)
            token_url = "https://accounts.google.com/o/oauth2/token"  # nosec
            creds = service_account.Credentials(
                signer=signer,
                service_account_email=config.DELEGATED_SA,
                token_uri=token_url,
                scopes=["https://www.googleapis.com/auth/cloud-platform"],
                subject=config.DELEGATED_SA,
            )
        except Exception:
            raise

        return creds
def ServiceAccountCredentials(email, key_file=None, key_data=None):
    """Configure OAuth2 credentials for a Google Service Account.

  Args:
    email: The email address of the account for which to configure credentials.
        Ignored if key_file or key_data represents a JSON service account key.
    key_file: The path to a file containing the private key associated with
        the service account. Both JSON and PEM files are supported.
    key_data: Raw key data to use, if key_file is not specified.

  Returns:
    An OAuth2 credentials object.
  """

    # Assume anything that doesn't end in '.pem' is a JSON key.
    if key_file and not key_file.endswith('.pem'):
        return service_account.Credentials.from_service_account_file(
            key_file, scopes=oauth.SCOPES)

    # If 'key_data' can be decoded as JSON, it's probably a raw JSON key.
    if key_data:
        try:
            key_data = json.loads(key_data)
            return service_account.Credentials.from_service_account_info(
                key_data, scopes=oauth.SCOPES)
        except ValueError:
            # It may actually be a raw PEM string, we'll try that below.
            pass

    # Probably a PEM key - just read the file into 'key_data'.
    if key_file:
        with open(key_file, 'r') as file_:
            key_data = file_.read()

    # Raw PEM key.
    signer = crypt.RSASigner.from_string(key_data)
    return service_account.Credentials(signer,
                                       email,
                                       oauth.TOKEN_URI,
                                       scopes=oauth.SCOPES)
def get_delegated_credential(delegated_account, scopes):
    """Build delegated credentials required for accessing the gsuite APIs.

    Args:
        delegated_account (str): The account to delegate the service account to
            use.
        scopes (list): The list of required scopes for the service account.

    Returns:
        service_account.Credentials: Credentials as built by
        google.oauth2.service_account.
    """
    request = requests.Request()

    # Get the "bootstrap" credentials that will be used to talk to the IAM
    # API to sign blobs.
    bootstrap_credentials, _ = google.auth.default()

    bootstrap_credentials = with_scopes_if_required(bootstrap_credentials,
                                                    list(CLOUD_SCOPES))

    # Refresh the boostrap credentials. This ensures that the information about
    # this account, notably the email, is populated.
    bootstrap_credentials.refresh(request)

    # Create an IAM signer using the bootstrap credentials.
    signer = iam.Signer(request, bootstrap_credentials,
                        bootstrap_credentials.service_account_email)

    # Create OAuth 2.0 Service Account credentials using the IAM-based signer
    # and the bootstrap_credential's service account email.
    delegated_credentials = service_account.Credentials(
        signer,
        bootstrap_credentials.service_account_email,
        _TOKEN_URI,
        scopes=scopes,
        subject=delegated_account)

    return delegated_credentials
Exemple #28
0
def new_creds(scopes=None):
    """Create credentials wih non-default scopes.

    The IAP API must be enabled, and the service account must have been
    granted permissions to create auth tokens (included in the Service Account
    Token Creator role).
    """
    if not in_production():
        # Local development.
        creds, _ = google.auth.default(scopes=scopes)
        return creds

    request = google.auth.transport.requests.Request()
    creds = credentials.IDTokenCredentials(request, None)
    signer = creds.signer
    service_account_email = creds.service_account_email
    token_uri = _DEFAULT_TOKEN_URI
    creds = service_account.Credentials(signer, service_account_email, token_uri)

    if scopes:
        creds = creds.with_scopes(scopes)

    return creds
Exemple #29
0
def __update_credentials(credentials, subject, scopes):
    try:
        updated_credentials = credentials.with_subject(subject).with_scopes(
            scopes)
    except AttributeError:
        # AttributeError implies that we are using GCE credentials so we cannot
        # use with_subject and with_scopes. Following link has more details:
        # https://github.com/GoogleCloudPlatform/professional-services/tree/master/examples/gce-to-adminsdk
        request = requests.Request()
        credentials.refresh(request)

        signer = iam.Signer(request, credentials,
                            credentials.service_account_email)

        updated_credentials = service_account.Credentials(
            signer,
            credentials.service_account_email,
            GOOGLE_API['token_uri'],
            scopes=scopes,
            subject=subject)
    except Exception:
        raise

    return updated_credentials
Exemple #30
0
def delegated_credentials(credentials, scopes, subject=None):
    """
    Generate scoped credentials. This needs the 'SA Token Creator' role for the SA

    Source: https://stackoverflow.com/a/57092533
    :param credentials: Credentials object to add scopes/subject to
    :param scopes: Scopes to add to credentials
    :param subject: Subject to add to credentials
    :return: Updated credentials object with access token for scopes
    """
    try:
        # If using service account credentials from json file
        updated_credentials = credentials.with_subject(subject).with_scopes(
            scopes)
    except AttributeError:
        # If using GCE/GAE default credentials
        request = requests.Request()

        # Refresh the default credentials. This ensures that the information
        # about this account, notably the email, is populated.
        credentials.refresh(request)

        # Create an IAM signer using the default credentials.
        signer = iam.Signer(request, credentials,
                            credentials.service_account_email)

        # Create OAuth 2.0 Service Account credentials using the IAM-based
        # signer and the bootstrap_credential's service account email
        updated_credentials = service_account.Credentials(
            signer,
            credentials.service_account_email,
            TOKEN_URI,
            scopes=scopes,
            subject=subject)

    return updated_credentials