def _get_transfer_service_account():
        credentials = default_credentials()
        credentials = with_scopes(credentials, scopes=['https://www.googleapis.com/auth/cloud-platform'])
        service = discovery.build('storagetransfer', 'v1', cache_discovery=False, credentials=credentials)

        request = service.googleServiceAccounts().get(projectId=GCP_PROJECT_ID)
        return request.execute()
    def _get_transfer_service_account():
        credentials = default_credentials()
        credentials = with_scopes(credentials, scopes=['https://www.googleapis.com/auth/cloud-platform'])
        service = discovery.build('storagetransfer', 'v1', cache_discovery=False, credentials=credentials)

        request = service.googleServiceAccounts().get(projectId=GCP_PROJECT_ID)
        return request.execute()
    def test_with_scopes_scoped(self):
        credentials = mock.Mock(spec=oauth2client.client.GoogleCredentials)
        credentials.create_scoped_required.return_value = True

        returned = _auth.with_scopes(credentials, mock.sentinel.scopes)

        self.assertNotEqual(credentials, returned)
        self.assertEqual(returned, credentials.create_scoped.return_value)
        credentials.create_scoped.assert_called_once_with(mock.sentinel.scopes)
    def test_with_scopes_scoped(self):
        credentials = mock.Mock(spec=oauth2client.client.GoogleCredentials)
        credentials.create_scoped_required.return_value = True

        returned = _auth.with_scopes(credentials, mock.sentinel.scopes)

        self.assertNotEqual(credentials, returned)
        self.assertEqual(returned, credentials.create_scoped.return_value)
        credentials.create_scoped.assert_called_once_with(mock.sentinel.scopes)
Exemplo n.º 5
0
    def test_with_scopes_scoped(self):
        class CredentialsWithScopes(google.auth.credentials.Credentials,
                                    google.auth.credentials.Scoped):
            pass

        credentials = mock.Mock(spec=CredentialsWithScopes)
        credentials.requires_scopes = True

        returned = _auth.with_scopes(credentials, mock.sentinel.scopes)

        self.assertNotEqual(credentials, returned)
        self.assertEqual(returned, credentials.with_scopes.return_value)
        credentials.with_scopes.assert_called_once_with(mock.sentinel.scopes)
    def test_with_scopes_scoped(self):
        class CredentialsWithScopes(
                google.auth.credentials.Credentials,
                google.auth.credentials.Scoped):
            pass

        credentials = mock.Mock(spec=CredentialsWithScopes)
        credentials.requires_scopes = True

        returned = _auth.with_scopes(credentials, mock.sentinel.scopes)

        self.assertNotEqual(credentials, returned)
        self.assertEqual(returned, credentials.with_scopes.return_value)
        credentials.with_scopes.assert_called_once_with(mock.sentinel.scopes)
Exemplo n.º 7
0
def get_authenticated_service(auth_root):
    auth_name = os.path.join(auth_root, AUTHENTICATED_SERVICE_FILE)
    secrets_name = os.path.join(auth_root, CLIENT_SECRETS_FILE)
    if os.path.isfile(auth_name):
        credentials = read_credentials(auth_name)
    else:
        flow = InstalledAppFlow.from_client_secrets_file(secrets_name, SCOPES)
        credentials = flow.run_console()
        write_credentials(auth_name, credentials)

    # The credentials need to be scoped.
    credentials = _auth.with_scopes(credentials, SCOPES)

    # Create an authorized http instance
    http = _auth.authorized_http(credentials)

    # return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
    return build(API_SERVICE_NAME, API_VERSION, http=http)
def build_from_document(service,
                        base=None,
                        future=None,
                        http=None,
                        developerKey=None,
                        model=None,
                        requestBuilder=HttpRequest,
                        credentials=None):
    """Create a Resource for interacting with an API.

  Same as `build()`, but constructs the Resource object from a discovery
  document that is it given, as opposed to retrieving one over HTTP.

  Args:
    service: string or object, the JSON discovery document describing the API.
      The value passed in may either be the JSON string or the deserialized
      JSON.
    base: string, base URI for all HTTP requests, usually the discovery URI.
      This parameter is no longer used as rootUrl and servicePath are included
      within the discovery document. (deprecated)
    future: string, discovery document with future capabilities (deprecated).
    http: httplib2.Http, An instance of httplib2.Http or something that acts
      like it that HTTP requests will be made through.
    developerKey: string, Key for controlling API usage, generated
      from the API Console.
    model: Model class instance that serializes and de-serializes requests and
      responses.
    requestBuilder: Takes an http request and packages it up to be executed.
    credentials: oauth2client.Credentials or
      google.auth.credentials.Credentials, credentials to be used for
      authentication.

  Returns:
    A Resource object with methods for interacting with the service.
  """

    if http is not None and credentials is not None:
        raise ValueError(
            'Arguments http and credentials are mutually exclusive.')

    if isinstance(service, six.string_types):
        service = json.loads(service)

    if 'rootUrl' not in service and (isinstance(http,
                                                (HttpMock, HttpMockSequence))):
        logger.error(
            "You are using HttpMock or HttpMockSequence without" +
            "having the service discovery doc in cache. Try calling " +
            "build() without mocking once first to populate the " + "cache.")
        raise InvalidJsonError()

    base = urljoin(service['rootUrl'], service['servicePath'])
    schema = Schemas(service)

    # If the http client is not specified, then we must construct an http client
    # to make requests. If the service has scopes, then we also need to setup
    # authentication.
    if http is None:
        # Does the service require scopes?
        scopes = list(
            service.get('auth', {}).get('oauth2', {}).get('scopes', {}).keys())

        # If so, then the we need to setup authentication if no developerKey is
        # specified.
        if scopes and not developerKey:
            # If the user didn't pass in credentials, attempt to acquire application
            # default credentials.
            if credentials is None:
                credentials = _auth.default_credentials()

            # The credentials need to be scoped.
            credentials = _auth.with_scopes(credentials, scopes)

            # Create an authorized http instance
            http = _auth.authorized_http(credentials)

        # If the service doesn't require scopes then there is no need for
        # authentication.
        else:
            http = build_http()

    if model is None:
        features = service.get('features', [])
        model = JsonModel('dataWrapper' in features)

    return Resource(http=http,
                    baseUrl=base,
                    model=model,
                    developerKey=developerKey,
                    requestBuilder=requestBuilder,
                    resourceDesc=service,
                    rootDesc=service,
                    schema=schema)
    def test_with_scopes_non_scoped(self):
        credentials = mock.Mock(spec=google.auth.credentials.Credentials)

        returned = _auth.with_scopes(credentials, mock.sentinel.scopes)

        self.assertEqual(credentials, returned)
Exemplo n.º 10
0
def build_from_document(
    service,
    base=None,
    future=None,
    http=None,
    developerKey=None,
    model=None,
    requestBuilder=HttpRequest,
    credentials=None
):
    """Create a Resource for interacting with an API.

  Same as `build()`, but constructs the Resource object from a discovery
  document that is it given, as opposed to retrieving one over HTTP.

  Args:
    service: string or object, the JSON discovery document describing the API.
      The value passed in may either be the JSON string or the deserialized
      JSON.
    base: string, base URI for all HTTP requests, usually the discovery URI.
      This parameter is no longer used as rootUrl and servicePath are included
      within the discovery document. (deprecated)
    future: string, discovery document with future capabilities (deprecated).
    http: httplib2.Http, An instance of httplib2.Http or something that acts
      like it that HTTP requests will be made through.
    developerKey: string, Key for controlling API usage, generated
      from the API Console.
    model: Model class instance that serializes and de-serializes requests and
      responses.
    requestBuilder: Takes an http request and packages it up to be executed.
    credentials: oauth2client.Credentials or
      google.auth.credentials.Credentials, credentials to be used for
      authentication.

  Returns:
    A Resource object with methods for interacting with the service.
  """

    if http is not None and credentials is not None:
        raise ValueError('Arguments http and credentials are mutually exclusive.')

    if isinstance(service, six.string_types):
        service = json.loads(service)

    if 'rootUrl' not in service and (isinstance(http, (HttpMock, HttpMockSequence))):
        logger.error(
            "You are using HttpMock or HttpMockSequence without" +
            "having the service discovery doc in cache. Try calling " +
            "build() without mocking once first to populate the " + "cache."
        )
        raise InvalidJsonError()

    base = urljoin(service['rootUrl'], service['servicePath'])
    schema = Schemas(service)

    # If the http client is not specified, then we must construct an http client
    # to make requests. If the service has scopes, then we also need to setup
    # authentication.
    if http is None:
        # Does the service require scopes?
        scopes = list(service.get('auth', {}).get('oauth2', {}).get('scopes', {}).keys())

        # If so, then the we need to setup authentication if no developerKey is
        # specified.
        if scopes and not developerKey:
            # If the user didn't pass in credentials, attempt to acquire application
            # default credentials.
            if credentials is None:
                credentials = _auth.default_credentials()

            # The credentials need to be scoped.
            credentials = _auth.with_scopes(credentials, scopes)

            # Create an authorized http instance
            http = _auth.authorized_http(credentials)

        # If the service doesn't require scopes then there is no need for
        # authentication.
        else:
            http = build_http()

    if model is None:
        features = service.get('features', [])
        model = JsonModel('dataWrapper' in features)

    return Resource(
        http=http,
        baseUrl=base,
        model=model,
        developerKey=developerKey,
        requestBuilder=requestBuilder,
        resourceDesc=service,
        rootDesc=service,
        schema=schema
    )
Exemplo n.º 11
0
    def test_with_scopes_non_scoped(self):
        credentials = mock.Mock(spec=oauth2client.client.Credentials)

        returned = _auth.with_scopes(credentials, mock.sentinel.scopes)

        self.assertEqual(credentials, returned)
Exemplo n.º 12
0
def build_from_document(
    service,
    base=None,
    future=None,
    http=None,
    developerKey=None,
    model=None,
    requestBuilder=HttpRequest,
    credentials=None,
    client_options=None,
    adc_cert_path=None,
    adc_key_path=None,
):
    if http is not None and credentials is not None:
        raise ValueError(
            "Arguments http and credentials are mutually exclusive.")

    if isinstance(service, six.string_types):
        service = json.loads(service)
    elif isinstance(service, six.binary_type):
        service = json.loads(service.decode("utf-8"))

    if "rootUrl" not in service and isinstance(http,
                                               (HttpMock, HttpMockSequence)):
        logger.error(
            "You are using HttpMock or HttpMockSequence without" +
            "having the service discovery doc in cache. Try calling " +
            "build() without mocking once first to populate the " + "cache.")
        raise InvalidJsonError()

    base = urljoin(service["rootUrl"], service["servicePath"])
    if client_options:
        if isinstance(client_options, six.moves.collections_abc.Mapping):
            client_options = google.api_core.client_options.from_dict(
                client_options)
        if client_options.api_endpoint:
            base = client_options.api_endpoint

    schema = Schemas(service)

    if http is None:
        scopes = list(
            service.get("auth", {}).get("oauth2", {}).get("scopes", {}).keys())

        if scopes and not developerKey:

            if credentials is None:
                credentials = _auth.default_credentials()

            credentials = _auth.with_scopes(credentials, scopes)

        if credentials:
            http = _auth.authorized_http(credentials)

        else:
            http = build_http()

        client_cert_to_use = None
        if client_options and client_options.client_cert_source:
            raise MutualTLSChannelError(
                "ClientOptions.client_cert_source is not supported, please use ClientOptions.client_encrypted_cert_source."
            )
        if (client_options
                and hasattr(client_options, "client_encrypted_cert_source")
                and client_options.client_encrypted_cert_source):
            client_cert_to_use = client_options.client_encrypted_cert_source
        elif adc_cert_path and adc_key_path and mtls.has_default_client_cert_source(
        ):
            client_cert_to_use = mtls.default_client_encrypted_cert_source(
                adc_cert_path, adc_key_path)
        if client_cert_to_use:
            cert_path, key_path, passphrase = client_cert_to_use()

            http_channel = (http.http if google_auth_httplib2 and isinstance(
                http, google_auth_httplib2.AuthorizedHttp) else http)
            http_channel.add_certificate(key_path, cert_path, "", passphrase)

        if "mtlsRootUrl" in service and (not client_options
                                         or not client_options.api_endpoint):
            mtls_endpoint = urljoin(service["mtlsRootUrl"],
                                    service["servicePath"])
            use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never")

            if not use_mtls_env in ("never", "auto", "always"):
                raise MutualTLSChannelError(
                    "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always"
                )

            if use_mtls_env == "always" or (use_mtls_env == "auto"
                                            and client_cert_to_use):
                base = mtls_endpoint

    if model is None:
        features = service.get("features", [])
        model = JsonModel("dataWrapper" in features)

    return {
        'http': http,
        'baseUrl': base,
        'model': model,
        'developerKey': developerKey,
        'requestBuilder': requestBuilder,
        'resourceDesc': service,
        'rootDesc': service,
        'schema': schema,
    }