credentials.ts 9.4 KB
Newer Older
Diego Molteni's avatar
Diego Molteni committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// ============================================================================
// Copyright 2017-2019, Schlumberger
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ============================================================================

import jwttoken from 'jsonwebtoken';
import request from 'request-promise';
import { Config } from '../../../cloud';
import { Error, Utils } from '../../../shared';
import { AbstractCredentials, CredentialsFactory, IAccessTokenModel } from '../../credentials';
import { ConfigGoogle } from './config';

24

Diego Molteni's avatar
Diego Molteni committed
25
26
27
28
29
30
31
32
interface IDTokenModel {
    id_token: string;
}

interface IDownScopedToken {
    access_token: string;
    token_type: string;
    issued_token_type: string;
Diego Molteni's avatar
Diego Molteni committed
33
    expires_in: string;
Diego Molteni's avatar
Diego Molteni committed
34
35
36
37
38
39
40
}

const KExpiresMargin = 300; // 5 minutes

@CredentialsFactory.register('google')
export class Credentials extends AbstractCredentials {

Diego Molteni's avatar
Diego Molteni committed
41
    public async getStorageCredentials(
Diego Molteni's avatar
Diego Molteni committed
42
        tenant: string, subproject: string,
43
        bucket: string, readonly: boolean, _partition: string, objectPrefix?: string): Promise<IAccessTokenModel> {
Diego Molteni's avatar
Diego Molteni committed
44
45
46

        const serviceAccessToken = await this.getServiceAccountAccessToken(false);
        const serviceAccessTokenDownscoped = await this.exchangeJwtWithDownScopedAccessToken(
47
            serviceAccessToken.access_token, bucket, readonly, objectPrefix);
Diego Molteni's avatar
Diego Molteni committed
48

Diego Molteni's avatar
Diego Molteni committed
49
        return {
Diego Molteni's avatar
Diego Molteni committed
50
51
52
            access_token: serviceAccessTokenDownscoped.access_token,
            expires_in: +serviceAccessTokenDownscoped.expires_in,
            token_type: serviceAccessTokenDownscoped.token_type,
Diego Molteni's avatar
Diego Molteni committed
53
54
        };
    }
Diego Molteni's avatar
Diego Molteni committed
55

Diego Molteni's avatar
Diego Molteni committed
56
    private async exchangeJwtWithDownScopedAccessToken(accessToken: string,
57
        bucket: string, readonly: boolean, objectPrefix?: string): Promise<IDownScopedToken> {
Diego Molteni's avatar
Diego Molteni committed
58
        try {
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

            const accessBoundary = {
                'accessBoundaryRules': [
                    {
                        'availableResource': '//storage.googleapis.com/projects/_/buckets/' + bucket,
                        'availablePermissions': [
                            'inRole:roles/' + (readonly ? 'storage.objectViewer' : 'storage.objectAdmin')
                        ],
                    }
                ]
            };

            if (objectPrefix) {
                accessBoundary.accessBoundaryRules[0]['availabilityCondition'] = {
                    'title': 'obj-prefixes',
                    'expression': 'resource.name.startsWith(\"projects/_/buckets/' +
                        bucket + '/objects/' + objectPrefix + '\")'
                };
            }

            const requestOptions = {
Diego Molteni's avatar
Diego Molteni committed
80
                form: {
81
82
83
84
85
86
87
                    'grant_type': 'urn:ietf:params:oauth:grant-type:token-exchange',
                    'subject_token_type': 'urn:ietf:params:oauth:token-type:access_token',
                    'requested_token_type': 'urn:ietf:params:oauth:token-type:access_token',
                    'subject_token': accessToken,
                    'options': JSON.stringify({
                        'accessBoundary': accessBoundary
                    })
Diego Molteni's avatar
Diego Molteni committed
88
89
                },
                headers: {
Diego Molteni's avatar
Diego Molteni committed
90
                    'Content-Type': 'application/x-www-form-urlencoded',
Diego Molteni's avatar
Diego Molteni committed
91
                },
92
93
94
95
96
                url: 'https://sts.googleapis.com/v1beta/token',
            };

            return JSON.parse(await request.post(requestOptions));

Diego Molteni's avatar
Diego Molteni committed
97
98
99
        } catch (error) {
            throw (Error.makeForHTTPRequest(error));
        }
Diego Molteni's avatar
Diego Molteni committed
100
101
102
103
104
    }

    public async getServiceCredentials(): Promise<string> {

        const now = Math.floor(Date.now() / 1000);
Diego Molteni's avatar
Diego Molteni committed
105
106
        if (Credentials.serviceAccountIdTokenExpiresIn > now) {
            return Credentials.serviceAccountIdToken;
Diego Molteni's avatar
Diego Molteni committed
107
108
        }

Diego Molteni's avatar
Diego Molteni committed
109
        Credentials.serviceAccountEmail = await this.getServiceAccountEmail();
Diego Molteni's avatar
Diego Molteni committed
110
111
112
113
114
115
116
117
        const svcToken = (await this.getServiceAccountAccessToken()).access_token;

        const options = {
            form: {
                payload: JSON.stringify({
                    aud: ConfigGoogle.GOOGLE_EP_OAUTH2 + '/token',
                    exp: (now + 3600),
                    iat: now,
Diego Molteni's avatar
Diego Molteni committed
118
                    iss: Credentials.serviceAccountEmail,
Diego Molteni's avatar
Diego Molteni committed
119
120
121
122
123
124
125
126
                    target_audience: ConfigGoogle.DES_SERVICE_TARGET_AUDIENCE,
                }),
            },
            headers: {
                'Authorization': 'Bearer ' + svcToken,
                'Content-Type': 'application/json',
            },
            url: ConfigGoogle.GOOGLE_EP_IAM + '/projects/' +
Diego Molteni's avatar
Diego Molteni committed
127
                ConfigGoogle.SERVICE_CLOUD_PROJECT + '/serviceAccounts/' + Credentials.serviceAccountEmail + ':signJwt',
Diego Molteni's avatar
Diego Molteni committed
128
129
130
131
132
133
        };

        try {
            const idToken = await this.signJWT(
                JSON.parse(await request.post(options)).signedJwt) as IDTokenModel;

Diego Molteni's avatar
Diego Molteni committed
134
135
136
            Credentials.serviceAccountIdToken = idToken.id_token;
            Credentials.serviceAccountIdTokenExpiresIn =
                Utils.getExpTimeFromPayload(Credentials.serviceAccountIdToken) - KExpiresMargin;
Diego Molteni's avatar
Diego Molteni committed
137

Diego Molteni's avatar
Diego Molteni committed
138
            return Credentials.serviceAccountIdToken;
Diego Molteni's avatar
Diego Molteni committed
139
140
141
142
143
144
145

        } catch (error) {
            throw (Error.makeForHTTPRequest(error));
        }

    }

Diego Molteni's avatar
Diego Molteni committed
146
    public async getServiceAccountAccessToken(useCached = true): Promise<IAccessTokenModel> {
Diego Molteni's avatar
Diego Molteni committed
147
148

        const now = Math.floor(Date.now() / 1000);
Diego Molteni's avatar
Diego Molteni committed
149
150
151
        if (useCached && Credentials.serviceAccountAccessToken &&
            Credentials.serviceAccountAccessTokenExpiresIn > now) {
            return Credentials.serviceAccountAccessToken;
Diego Molteni's avatar
Diego Molteni committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        }

        if (ConfigGoogle.SERVICE_IDENTITY_PRIVATE_KEY) {
            const jwt = jwttoken.sign({
                aud: ConfigGoogle.GOOGLE_EP_OAUTH2 + '/token',
                exp: (now + 3600),
                iat: now,
                iss: ConfigGoogle.SERVICE_IDENTITY_EMAIL,
                scope: ConfigGoogle.GOOGLE_SCOPE_PLATFORM,
            }, ConfigGoogle.SERVICE_IDENTITY_PRIVATE_KEY, {
                header: {
                    alg: 'RS256',
                    kid: ConfigGoogle.SERVICE_IDENTITY_PRIVATE_KEY_ID,
                    typ: 'JWT',
                },
            });

Diego Molteni's avatar
Diego Molteni committed
169
170
171
172
            Credentials.serviceAccountAccessToken = await this.signJWT(jwt) as IAccessTokenModel;
            Credentials.serviceAccountAccessTokenExpiresIn =
                Math.floor(Date.now() / 1000) + Credentials.serviceAccountAccessToken.expires_in - KExpiresMargin;
            return Credentials.serviceAccountAccessToken;
Diego Molteni's avatar
Diego Molteni committed
173
174
175
176
177
178
179
180
        }

        const options = {
            headers: { 'Metadata-Flavor': 'Google' },
            url: ConfigGoogle.GOOGLE_EP_METADATA + '/instance/service-accounts/default/token',
        };

        try {
Diego Molteni's avatar
Diego Molteni committed
181
182
183
184
            Credentials.serviceAccountAccessToken = JSON.parse(await request.get(options));
            Credentials.serviceAccountAccessTokenExpiresIn =
                Math.floor(Date.now() / 1000) + Credentials.serviceAccountAccessToken.expires_in - KExpiresMargin;
            return Credentials.serviceAccountAccessToken;
Diego Molteni's avatar
Diego Molteni committed
185
186
187
188
189
190
191
        } catch (error) {
            throw (Error.makeForHTTPRequest(error));
        }
    }

    public async getServiceAccountEmail(): Promise<string> {

Diego Molteni's avatar
Diego Molteni committed
192
        if (Credentials.serviceAccountEmail) { return Credentials.serviceAccountEmail; }
Diego Molteni's avatar
Diego Molteni committed
193
194

        if (ConfigGoogle.SERVICE_IDENTITY_EMAIL) {
Diego Molteni's avatar
Diego Molteni committed
195
196
            Credentials.serviceAccountEmail = ConfigGoogle.SERVICE_IDENTITY_EMAIL;
            return Credentials.serviceAccountEmail;
Diego Molteni's avatar
Diego Molteni committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
        }

        const options = {
            headers: { 'Metadata-Flavor': 'Google' },
            url: ConfigGoogle.GOOGLE_EP_METADATA + '/instance/service-accounts/default/email',
        };

        try {
            return await request.get(options);
        } catch (error) {
            throw (Error.makeForHTTPRequest(error));
        }
    }

    public getIAMResourceUrl(serviceSigner: string): string {
        return ConfigGoogle.GOOGLE_EP_IAM + '/projects/' + ConfigGoogle.SERVICE_CLOUD_PROJECT +
            '/serviceAccounts/' + serviceSigner + ':signJwt';
    }

    public getAudienceForImpCredentials(): string {
        return ConfigGoogle.GOOGLE_EP_OAUTH2 + '/token';
    }

    public getPublicKeyCertificatesUrl(): string {
        return ConfigGoogle.GOOGLE_EP_ROBOT + '/metadata/x509/' + Config.IMP_SERVICE_ACCOUNT_SIGNER;
    }

    // cache the services tokens
Diego Molteni's avatar
Diego Molteni committed
225
226
227
228
229
    private static serviceAccountEmail: string;
    private static serviceAccountAccessToken: IAccessTokenModel;
    private static serviceAccountAccessTokenExpiresIn = 0;
    private static serviceAccountIdToken: string;
    private static serviceAccountIdTokenExpiresIn = 0;
Diego Molteni's avatar
Diego Molteni committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

    public async signJWT(jwt: string): Promise<IDTokenModel | IAccessTokenModel> {

        const options = {
            form: {
                assertion: jwt,
                grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            url: ConfigGoogle.GOOGLE_EP_OAUTH2 + '/token',
        };

        try {
            return JSON.parse(await request.post(options));
        } catch (error) {
            throw (Error.makeForHTTPRequest(error));
        }

    }

}