|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | + |
| 14 | +import json |
| 15 | +import os |
| 16 | +import sys |
| 17 | + |
| 18 | +import boto3 |
| 19 | +from dotenv import load_dotenv |
| 20 | +from google.auth.aws import Credentials as AwsCredentials |
| 21 | +from google.auth.aws import AwsSecurityCredentials, AwsSecurityCredentialsSupplier |
| 22 | +from google.auth.exceptions import GoogleAuthError |
| 23 | +from google.auth.transport.requests import AuthorizedSession |
| 24 | + |
| 25 | +load_dotenv() |
| 26 | + |
| 27 | + |
| 28 | +class CustomAwsSupplier(AwsSecurityCredentialsSupplier): |
| 29 | + """Custom AWS Security Credentials Supplier.""" |
| 30 | + |
| 31 | + def __init__(self): |
| 32 | + """Initializes the Boto3 session, prioritizing environment variables for region.""" |
| 33 | + # Explicitly read the region from the environment first. This ensures that |
| 34 | + # a value from a .env file is picked up reliably for local testing. |
| 35 | + region = os.getenv("AWS_REGION") or os.getenv("AWS_DEFAULT_REGION") |
| 36 | + |
| 37 | + # If region is None, Boto3's discovery chain will be used when needed. |
| 38 | + self.session = boto3.Session(region_name=region) |
| 39 | + self._cached_region = None |
| 40 | + print(f"[INFO] CustomAwsSupplier initialized. Region from env: {region}") |
| 41 | + |
| 42 | + def get_aws_region(self, context, request) -> str: |
| 43 | + """Returns the AWS region using Boto3's default provider chain.""" |
| 44 | + if self._cached_region: |
| 45 | + return self._cached_region |
| 46 | + |
| 47 | + # Accessing region_name will use the value from the constructor if provided, |
| 48 | + # otherwise it triggers Boto3's lazy-loading discovery (e.g., metadata service). |
| 49 | + self._cached_region = self.session.region_name |
| 50 | + |
| 51 | + if not self._cached_region: |
| 52 | + print("[ERROR] Boto3 was unable to resolve an AWS region.", file=sys.stderr) |
| 53 | + raise GoogleAuthError("Boto3 was unable to resolve an AWS region.") |
| 54 | + |
| 55 | + print(f"[INFO] Boto3 resolved AWS Region: {self._cached_region}") |
| 56 | + return self._cached_region |
| 57 | + |
| 58 | + def get_aws_security_credentials(self, context, request=None) -> AwsSecurityCredentials: |
| 59 | + """Retrieves AWS security credentials using Boto3's default provider chain.""" |
| 60 | + aws_credentials = self.session.get_credentials() |
| 61 | + if not aws_credentials: |
| 62 | + print("[ERROR] Unable to resolve AWS credentials.", file=sys.stderr) |
| 63 | + raise GoogleAuthError("Unable to resolve AWS credentials from the provider chain.") |
| 64 | + |
| 65 | + print(f"[INFO] Resolved AWS Access Key ID: {aws_credentials.access_key}") |
| 66 | + |
| 67 | + return AwsSecurityCredentials( |
| 68 | + access_key_id=aws_credentials.access_key, |
| 69 | + secret_access_key=aws_credentials.secret_key, |
| 70 | + session_token=aws_credentials.token, |
| 71 | + ) |
| 72 | + |
| 73 | + |
| 74 | +def main(): |
| 75 | + """Main function to demonstrate the custom AWS supplier.""" |
| 76 | + print("--- Starting Script ---") |
| 77 | + |
| 78 | + gcp_audience = os.getenv("GCP_WORKLOAD_AUDIENCE") |
| 79 | + sa_impersonation_url = os.getenv("GCP_SERVICE_ACCOUNT_IMPERSONATION_URL") |
| 80 | + gcs_bucket_name = os.getenv("GCS_BUCKET_NAME") |
| 81 | + |
| 82 | + print(f"GCP_WORKLOAD_AUDIENCE: {gcp_audience}") |
| 83 | + print(f"GCS_BUCKET_NAME: {gcs_bucket_name}") |
| 84 | + |
| 85 | + if not all([gcp_audience, sa_impersonation_url, gcs_bucket_name]): |
| 86 | + print("[ERROR] Missing required environment variables.", file=sys.stderr) |
| 87 | + raise GoogleAuthError("Missing required environment variables.") |
| 88 | + |
| 89 | + custom_supplier = CustomAwsSupplier() |
| 90 | + |
| 91 | + credentials = AwsCredentials( |
| 92 | + audience=gcp_audience, |
| 93 | + subject_token_type="urn:ietf:params:aws:token-type:aws4_request", |
| 94 | + service_account_impersonation_url=sa_impersonation_url, |
| 95 | + aws_security_credentials_supplier=custom_supplier, |
| 96 | + scopes=['https://www.googleapis.com/auth/devstorage.read_write'], |
| 97 | + ) |
| 98 | + |
| 99 | + bucket_url = f"https://storage.googleapis.com/storage/v1/b/{gcs_bucket_name}" |
| 100 | + print(f"Request URL: {bucket_url}") |
| 101 | + |
| 102 | + authed_session = AuthorizedSession(credentials) |
| 103 | + try: |
| 104 | + print("Attempting to make authenticated request to Google Cloud Storage...") |
| 105 | + res = authed_session.get(bucket_url) |
| 106 | + res.raise_for_status() |
| 107 | + print("\n--- SUCCESS! ---") |
| 108 | + print("Successfully authenticated and retrieved bucket data:") |
| 109 | + print(json.dumps(res.json(), indent=2)) |
| 110 | + except Exception as e: |
| 111 | + print("--- FAILED --- ", file=sys.stderr) |
| 112 | + print(e, file=sys.stderr) |
| 113 | + exit(1) |
| 114 | + |
| 115 | + |
| 116 | +if __name__ == "__main__": |
| 117 | + main() |
0 commit comments