コード例 #1
0
ファイル: base.py プロジェクト: flamingo-run/gcp-pilot
    def _delegated_credential(
        cls,
        credentials: Credentials,
        subject: str,
        scopes: List[str],
    ) -> ServiceAccountCredentials:
        try:
            admin_credentials = credentials.with_subject(subject).with_scopes(
                scopes)
        except AttributeError:
            # When inside GCP, the credentials provided by the metadata service are immutable.
            # https://github.com/GoogleCloudPlatform/professional-services/tree/master/examples/gce-to-adminsdk

            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_credentials = ServiceAccountCredentials(
                signer,
                credentials.service_account_email,
                TOKEN_URI,
                scopes=scopes,
                subject=subject,
            )

        return admin_credentials
コード例 #2
0
    async def _get_ephemeral(
        client_session: aiohttp.ClientSession,
        credentials: Credentials,
        project: str,
        instance: str,
        pub_key: str,
    ) -> str:
        """Asynchronously requests an ephemeral certificate from the Cloud SQL Instance.

        :type credentials: google.oauth2.service_account.Credentials
        :param credentials: A credentials object
            created from the google-auth library. Must be
            using the SQL Admin API scopes. For more info, check out
            https://google-auth.readthedocs.io/en/latest/.

        :type project: str
        :param project : A string representing the name of the project.

        :type instance: str
        :param instance: A string representing the name of the instance.

        :type pub_key:
        :param str: A string representing PEM-encoded RSA public key.

        :rtype: str
        :returns: An ephemeral certificate from the Cloud SQL instance that allows
              authorized connections to the instance.

        :raises TypeError: If one of the arguments passed in is None.
        """

        logger.debug("Requesting ephemeral certificate")

        if (not isinstance(credentials, Credentials)
                or not isinstance(project, str)
                or not isinstance(instance, str)
                or not isinstance(pub_key, str)):
            raise TypeError("Cannot take None as an argument.")

        if not credentials.valid:
            request = google.auth.transport.requests.Request()
            credentials.refresh(request)

        headers = {
            "Authorization": "Bearer {}".format(credentials.token),
        }

        url = "https://www.googleapis.com/sql/{}/projects/{}/instances/{}/createEphemeral".format(
            _sql_api_version, project, instance)

        data = {"public_key": pub_key}

        resp = await client_session.post(url,
                                         headers=headers,
                                         json=data,
                                         raise_for_status=True)

        ret_dict = json.loads(await resp.text())

        return ret_dict["cert"]
コード例 #3
0
 def __refresh_credentials(self, credentials: Credentials) -> str:
     # Attempt to refresh token if not currently valid
     try:
         auth_req = google.auth.transport.requests.Request()
         credentials.refresh(auth_req)
     except RefreshError as err:
         logger.error("Could not get refreshed credentials for GCP. "
                      "Reauthentication Required.")
         raise err
コード例 #4
0
    def _get_auth_token(self, credentials: Credentials) -> str:
        """
        This method is used to get the authentication token.

        Returns:
        auth_token (str):
        """
        # getting request object
        auth_req = google.auth.transport.requests.Request()
        credentials.refresh(auth_req)  # refresh token
        # check for valid credentials
        auth_token = credentials.token
        return auth_token
コード例 #5
0
    async def _get_metadata(
        client_session: aiohttp.ClientSession,
        credentials: Credentials,
        project: str,
        instance: str,
    ) -> Dict[str, Union[Dict, str]]:
        """Requests metadata from the Cloud SQL Instance
        and returns a dictionary containing the IP addresses and certificate
        authority of the Cloud SQL Instance.

        :type credentials: google.oauth2.service_account.Credentials
        :param service:
            A credentials object created from the google-auth Python library.
            Must have the SQL Admin API scopes. For more info check out
            https://google-auth.readthedocs.io/en/latest/.

        :type project: str
        :param project:
            A string representing the name of the project.

        :type inst_name: str
        :param project: A string representing the name of the instance.

        :rtype: Dict[str: Union[Dict, str]]
        :returns: Returns a dictionary containing a dictionary of all IP
              addresses and their type and a string representing the
              certificate authority.

        :raises TypeError: If any of the arguments are not the specified type.
        """

        if (not isinstance(credentials, Credentials)
                or not isinstance(project, str)
                or not isinstance(instance, str)):
            raise TypeError("Arguments must be as follows: " +
                            "service (googleapiclient.discovery.Resource), " +
                            "proj_name (str) and inst_name (str).")

        if not credentials.valid:
            request = google.auth.transport.requests.Request()
            credentials.refresh(request)

        headers = {
            "Authorization": "Bearer {}".format(credentials.token),
        }

        url = "https://www.googleapis.com/sql/{}/projects/{}/instances/{}".format(
            _sql_api_version, project, instance)

        logger.debug("Requesting metadata")

        resp = await client_session.get(url,
                                        headers=headers,
                                        raise_for_status=True)
        ret_dict = json.loads(await resp.text())

        metadata = {
            "ip_addresses":
            {ip["type"]: ip["ipAddress"]
             for ip in ret_dict["ipAddresses"]},
            "server_ca_cert": ret_dict["serverCaCert"]["cert"],
        }

        return metadata