def testCredentialsFromAdcDictGoogleAuth_InputMissClientEmail(self):
    """Verifies that missing 'client_email' should fail the creds creation."""
    del self.creds_dict['client_email']

    with self.assertRaisesRegex(service_account.BadCredentialJsonFileException,
                                'The .json key file is not in a valid format.'):
      service_account.CredentialsFromAdcDictGoogleAuth(self.creds_dict)
Example #2
0
    def Run(self, args):
        """Create service account credentials."""

        file_content, is_json = _IsJsonFile(args.key_file)
        if is_json:
            if _UseGoogleAuth():
                cred = auth_service_account.CredentialsFromAdcDictGoogleAuth(
                    file_content)
            else:
                # TODO(b/161992086): Remove the flow of activating via oauth2client once
                # this legacy auth lib is deprecated. Leave this option for now so that
                # the users are able to fall back to the old flow of if any issues
                # related to google-auth comes up. The users can do this by setting
                # property auth/disable_activate_service_account_google_auth to True.
                cred = auth_service_account.CredentialsFromAdcDict(
                    file_content)
            if args.password_file or args.prompt_for_password:
                raise c_exc.InvalidArgumentException(
                    '--password-file',
                    'A .json service account key does not require a password.')
            account = cred.service_account_email
            if args.account and args.account != account:
                raise c_exc.InvalidArgumentException(
                    'ACCOUNT',
                    'The given account name does not match the account name in the key '
                    'file.  This argument can be omitted when using .json keys.'
                )
        else:
            account = args.account
            if not account:
                raise c_exc.RequiredArgumentException(
                    'ACCOUNT', 'An account is required when using .p12 keys')
            password = None
            if args.password_file:
                try:
                    password = files.ReadFileContents(
                        args.password_file).strip()
                except files.Error as e:
                    raise c_exc.UnknownArgumentException('--password-file', e)
            elif args.prompt_for_password:
                password = console_io.PromptPassword('Password: '******'Activated service account credentials for: [{0}]'.format(account))
  def testCredentialsFromAdcDictGoogleAuth(self):
    creds = service_account.CredentialsFromAdcDictGoogleAuth(self.creds_dict)

    self.assertIsInstance(creds, google_auth_service_account.Credentials)
    self.AssertCredentialsEqual(
        creds, {
            'client_id': 'bar.apps.googleusercontent.com',
            'service_account_email': '*****@*****.**',
            'private_key_id': 'fake-private-key-id',
            'private_key': 'fake-private-key',
            'project_id': 'fake-project-id',
            '_token_uri': 'https://oauth2.googleapis.com/token',
        })
  def testCredentialsFromAdcDictGoogleAuth_TokenUriNotProvided(self):
    """Verifies that missing 'token_uri' should not throw the creds creation."""
    del self.creds_dict['token_uri']
    creds = service_account.CredentialsFromAdcDictGoogleAuth(self.creds_dict)

    self.assertIsInstance(creds, google_auth_service_account.Credentials)
    self.AssertCredentialsEqual(
        creds, {
            'client_id': 'bar.apps.googleusercontent.com',
            'service_account_email': '*****@*****.**',
            'private_key_id': 'fake-private-key-id',
            'private_key': 'fake-private-key',
            'project_id': 'fake-project-id',
            '_token_uri': 'https://oauth2.googleapis.com/token',
        })
Example #5
0
    def Run(self, args):
        """Create service account credentials."""

        file_content, is_json = _IsJsonFile(args.key_file)
        if is_json:
            cred = auth_service_account.CredentialsFromAdcDictGoogleAuth(
                file_content)
            if args.password_file or args.prompt_for_password:
                raise c_exc.InvalidArgumentException(
                    '--password-file',
                    'A .json service account key does not require a password.')
            account = cred.service_account_email
            if args.account and args.account != account:
                raise c_exc.InvalidArgumentException(
                    'ACCOUNT',
                    'The given account name does not match the account name in the key '
                    'file.  This argument can be omitted when using .json keys.'
                )
        else:
            account = args.account
            if not account:
                raise c_exc.RequiredArgumentException(
                    'ACCOUNT', 'An account is required when using .p12 keys')
            password = None
            if args.password_file:
                try:
                    password = files.ReadFileContents(
                        args.password_file).strip()
                except files.Error as e:
                    raise c_exc.UnknownArgumentException('--password-file', e)
            elif args.prompt_for_password:
                password = console_io.PromptPassword('Password: '******'Activated service account credentials for: [{0}]'.format(account))
def LoginWithCredFileConfig(cred_config, scopes, project, activate, brief,
                            update_adc, add_quota_project_to_adc,
                            args_account):
    """Login with the provided configuration loaded from --cred-file.

  Args:
    cred_config (Mapping): The configuration dictionary representing the
      credentials. This is loaded from the --cred-file argument.
    scopes (Tuple[str]): The default OAuth scopes to use.
    project (Optional[str]): The optional project ID to activate / persist.
    activate (bool): Whether to set the new account associated with the
      credentials to active.
    brief (bool): Whether to use minimal user output.
    update_adc (bool): Whether to write the obtained credentials to the
      well-known location for Application Default Credentials (ADC).
    add_quota_project_to_adc (bool): Whether to add the quota project to the
      application default credentials file.
    args_account (Optional[str]): The optional ACCOUNT argument. When provided,
      this should match the account ID on the authenticated credentials.

  Returns:
    google.auth.credentials.Credentials: The authenticated stored credentials.

  Raises:
    calliope_exceptions.ConflictingArgumentsException: If conflicting arguments
      are provided.
    calliope_exceptions.InvalidArgumentException: If invalid arguments are
      provided.
  """
    # Remove reauth scope (only applicable to 1P user accounts).
    scopes = tuple(x for x in scopes if x != config.REAUTH_SCOPE)
    # Reject unsupported arguments.
    if add_quota_project_to_adc:
        raise calliope_exceptions.ConflictingArgumentsException(
            '[--add-quota-project-to-adc] cannot be specified with --cred-file'
        )
    if auth_external_account.IsExternalAccountConfig(cred_config):
        creds = auth_external_account.CredentialsFromAdcDictGoogleAuth(
            cred_config)
        account = auth_external_account.GetExternalAccountId(creds)
    elif auth_service_account.IsServiceAccountConfig(cred_config):
        creds = auth_service_account.CredentialsFromAdcDictGoogleAuth(
            cred_config)
        account = creds.service_account_email
    else:
        raise calliope_exceptions.InvalidArgumentException(
            '--cred-file',
            'Only external account or service account JSON credential file types '
            'are supported.')

    if args_account and args_account != account:
        raise calliope_exceptions.InvalidArgumentException(
            'ACCOUNT',
            'The given account name does not match the account name in the '
            'credential file. This argument can be omitted when using '
            'credential files.')
    # Check if account already exists in storage.
    try:
        exist_creds = c_store.Load(account=account, scopes=scopes)
    except creds_exceptions.Error:
        exist_creds = None
    if exist_creds:
        message = textwrap.dedent("""
      You are already authenticated with '%s'.
      Do you wish to proceed and overwrite existing credentials?
      """)
        answer = console_io.PromptContinue(message=message % account,
                                           default=True)
        if not answer:
            return None
    # Store credentials and activate if --activate is true.
    c_store.Store(creds, account, scopes=scopes)
    return LoginAs(account, creds, project, activate, brief, update_adc, False)