pythongoogle-cloud-platformworkload-identity

No token in google.auth credentials for aws workload identity federation


Why would the code below result in no token in returned credentials? (WIF pool with aws provider exist and service account connected to it)

from google.auth import aws

def lambda_handler(event, context):

    json_config_info = {
      "type": "external_account",
      "audience": "//iam.googleapis.com/projects/XXX/locations/global/workloadIdentityPools/awspool/providers/awsprovider",
      "subject_token_type": "urn:ietf:params:aws:token-type:aws4_request",
      "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/serviceaccount@XXX.iam.gserviceaccount.com:generateAccessToken",
      "token_url": "https://sts.googleapis.com/v1/token",
      "credential_source": {
        "environment_id": "aws1",
        "region_url": "http://169.254.169.254/latest/meta-data/placement/availability-zone",
        "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials",
        "regional_cred_verification_url": "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"
      }
    }

    credentials = aws.Credentials.from_info(json_config_info)
    print('token: ', credentials.token)
    print('valid: ', credentials.valid)

I'm getting token=None and valid=False while my understanding credentials should have a token and valid=True?


Solution

  • You have to perform a refresh of your credential to effectively perform a request to Google Cloud. Something like this

    from google.auth import aws
    
    def lambda_handler(event, context):
    
        json_config_info = {
          "type": "external_account",
          "audience": "//iam.googleapis.com/projects/XXX/locations/global/workloadIdentityPools/awspool/providers/awsprovider",
          "subject_token_type": "urn:ietf:params:aws:token-type:aws4_request",
          "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/serviceaccount@XXX.iam.gserviceaccount.com:generateAccessToken",
          "token_url": "https://sts.googleapis.com/v1/token",
          "credential_source": {
            "environment_id": "aws1",
            "region_url": "http://169.254.169.254/latest/meta-data/placement/availability-zone",
            "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials",
            "regional_cred_verification_url": "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"
          }
        }
    
        credentials = aws.Credentials.from_info(json_config_info)
    
        ### Code added
        import google.auth.transport.requests
        request = google.auth.transport.requests.Request()
        creds.refresh(request)
        ### Code end
    
        print('token: ', credentials.token)
        print('valid: ', credentials.valid)