amazon-web-servicesgoogle-cloud-platformaws-lambdafederated-identity

AWS Python Lambda Authentication for Google reCaptcha Enterprise Client Using Non-secret JSON


Here is what I currently have:

{
    "type": "external_account",
    "audience": "//iam.googleapis.com/projects/<my_account_number>/locations/global/workloadIdentityPools/<my-pool-name>/providers/aws-provider",
    "subject_token_type": "urn:ietf:params:aws:token-type:aws4_request",
    "service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/<my-service-account-name>@<my-gcp-project-name>.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"
    }
}

Now I want my AWS Lambda to use this so I can successfully do the following:

client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient(credentials=???)

and do the calls I need for my recaptcha stuff.

How on earth do I do that? All online examples seem to use either the old secret key way or aren't using a lambda or aren't using the google python lib, etc...


Solution

  • Thanks to @JohnHanley for the link to the relevant documentation.

    Here is how it is done:

    import json
    from google.auth import aws
    from google.cloud import recaptchaenterprise_v1
    from google.cloud.recaptchaenterprise_v1 import Assessment
    
    # The JSON in the question in string form loaded from the AWS Lambda's env variables.
    service_account_json_info = "{ ... }" 
    
    service_account_json_info_dict = json.loads(service_account_json_info)
    credentials = aws.Credentials.from_info(service_account_json_info_dict)
    scoped_credentials = credentials.with_scopes(["https://www.googleapis.com/auth/cloud-platform"])
    
    # This then works and can make the calls it's authorized to do according to the GCP config.
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient(credentials=scoped_credentials)