-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (53 loc) · 2.07 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const { Compute, Impersonated, JWT, OAuth2Client } = require('google-auth-library');
const { request } = require('gaxios');
const google = require('@googleapis/iam');
const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';
const unpaddedB64encode = (input) =>
Buffer.from(input)
.toString('base64')
.replace(/=*$/, '');
module.exports = async (client, subject, scopes) => {
let iss;
if (client instanceof JWT) {
iss = client.email;
} else if (client instanceof Impersonated) {
iss = client.targetPrincipal;
} else if (client instanceof Compute) {
const response = await request({ url: 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email', method: 'GET',
headers: { 'Metadata-Flavor': 'Google' }, responseType: 'text' });
iss = response.data;
}
if (iss) {
const now = Math.floor(new Date().getTime() / 1000);
const expiry = now + 3600;
const payload = JSON.stringify({
aud: TOKEN_ENDPOINT,
exp: expiry,
iat: now,
iss: iss,
scope: scopes.join(' '),
sub: subject,
});
const header = JSON.stringify({
alg: 'RS256',
typ: 'JWT',
});
const iamPayload = `${unpaddedB64encode(header)}.${unpaddedB64encode(payload)}`;
const iam = google.iam('v1');
const { data } = await iam.projects.serviceAccounts.signBlob({
auth: client,
name: `projects/-/serviceAccounts/${iss}`,
requestBody: {
bytesToSign: unpaddedB64encode(iamPayload)
},
});
const assertion = `${iamPayload}.${data.signature.replace(/=*$/, '')}`;
const body = new URLSearchParams({ assertion, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer' }).toString();
const response = await request({ url: TOKEN_ENDPOINT, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body });
const newCredentials = new OAuth2Client();
newCredentials.setCredentials({ access_token: response.data.access_token });
return newCredentials;
} else {
throw new Error('Unexpected authentication type');
}
}