Skip to content

Instantly share code, notes, and snippets.

@jamylak
Last active August 30, 2024 03:53
Show Gist options
  • Save jamylak/f0c7629318c0a4920f1769e4f9da3f62 to your computer and use it in GitHub Desktop.
Save jamylak/f0c7629318c0a4920f1769e4f9da3f62 to your computer and use it in GitHub Desktop.
AWS Lambda to Cloud Run Ext Client
// This assumes you created a file with
// gcloud iam workload-identity-pools create-cred-config \
// projects/INSERT_PROJECT_NUMBER/locations/global/workloadIdentityPools/INSERT_POOL_ID/providers/INSERT_PROVIDER_ID \
// [email protected] \
// --aws \
// --output-file=testcreds.json
// Then you have gone through the rest of the federated auth setup eg.
// Pool / provider / sa / principalset / etc
// Note this is calling get() for cloud run
// Also seems SA requires `OpenID connect token creator`
import { ExternalAccountClient } from 'google-auth-library';
import axios from 'axios';
async function main() {
// https://stackoverflow.com/a/77594859/1219006
const projectId = 'INSERT_PROJECT_ID_HERE';
const targetAudience = 'INSERT_CLOUD_RUN_URL_HERE';
const client = ExternalAccountClient.fromJSON(...);
client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
client.projectId = projectId;
const accessTokenResponse = await client.getAccessToken();
const accessToken = accessTokenResponse?.token;
if (!accessToken) {
throw new Error('accessToken not present');
}
const serviceAccountEmail = client.getServiceAccountEmail();
const getServiceTokenData = {
audience: targetAudience,
};
const getServiceTokenHeaders = {
'Content-Type': 'text/json',
Authorization: `Bearer ${accessToken}`,
};
const getServiceTokenConfig = {
headers: getServiceTokenHeaders,
};
console.log('Getting service token');
// this is simply the call from https://cloud.google.com/docs/authentication/get-id-token#external-idp , written in JS
const getServiceTokenResponse = await axios.post(
`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${serviceAccountEmail}:generateIdToken`,
getServiceTokenData,
getServiceTokenConfig,
);
console.log('Call cloud run');
const idToken = getServiceTokenResponse.data.token;
const resp = await axios.get(targetAudience, {
headers: {
Authorization: `Bearer ${idToken}`,
},
});
console.log('We did it!');
console.log(resp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment