UNPKG

@cloud-carbon-footprint/aws

Version:

The core logic to get cloud usage data and estimate energy and carbon emissions from Amazon Web Services.

73 lines 2.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const credential_providers_1 = require("@aws-sdk/credential-providers"); const google_auth_library_1 = require("google-auth-library"); class GCPCredentials { accountId; targetRoleName; proxyAccountId; proxyRoleName; constructor(accountId, targetRoleName, proxyAccountId, proxyRoleName) { this.accountId = accountId; this.targetRoleName = targetRoleName; this.proxyAccountId = proxyAccountId; this.proxyRoleName = proxyRoleName; } getProvider() { return async () => { const token = await this.getTokenId(); const masterCredentials = (0, credential_providers_1.fromWebToken)({ roleArn: `arn:aws:iam::${this.proxyAccountId}:role/${this.proxyRoleName}`, roleSessionName: this.proxyRoleName, webIdentityToken: token, }); return (0, credential_providers_1.fromTemporaryCredentials)({ params: { RoleArn: `arn:aws:iam::${this.accountId}:role/${this.targetRoleName}`, RoleSessionName: this.targetRoleName, }, masterCredentials, })(); }; } async getTokenId() { const auth = new google_auth_library_1.GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform', }); const authClient = await auth.getClient(); const projectId = await auth.getProjectId(); const serviceAccountEmail = authClient.email ? authClient.email : `${projectId}@appspot.gserviceaccount.com`; const { token: accessToken } = await authClient.getAccessToken(); if (!accessToken) { throw new Error('Failed to obtain GCP access token'); } return this.generateIdToken(serviceAccountEmail, accessToken); } async generateIdToken(serviceAccountEmail, accessToken) { const url = `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(serviceAccountEmail)}:generateIdToken`; const res = await fetch(url, { method: 'POST', headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ audience: serviceAccountEmail, includeEmail: true, }), }); if (!res.ok) { const body = await res.text(); throw new Error(`IAM generateIdToken failed: ${res.status} ${res.statusText}. ${body}`); } const data = (await res.json()); if (!data.token) { throw new Error('IAM generateIdToken returned no token'); } return data.token; } } exports.default = GCPCredentials; //# sourceMappingURL=GCPCredentials.js.map