dao.ts 6.61 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
// ============================================================================
// 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 { decode as jwtDecode, verify as jwtVerify } from 'jsonwebtoken';
18
import request from 'request-promise';
Diego Molteni's avatar
Diego Molteni committed
19
import { ImpTokenModel } from '.';
20
import { Config, CredentialsFactory } from '../../cloud';
Diego Molteni's avatar
Diego Molteni committed
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
69
70
71
72
73
74
import { Error } from '../../shared';
import { IImpTokenBodyModel as ImpTokenBodyModel, IRefreshUrl } from './model';


export class ImpTokenDAO {

    public static async create(impTokenBody: ImpTokenBodyModel): Promise<ImpTokenModel> {

        const serviceSigner = Config.IMP_SERVICE_ACCOUNT_SIGNER;

        if (!impTokenBody.iat) {
            impTokenBody.iat = Math.floor(Date.now() / 1000);
        }

        const credentials = CredentialsFactory.build(Config.CLOUDPROVIDER);
        const options = {
            form: {
                payload: JSON.stringify({
                    aud: credentials.getAudienceForImpCredentials(),
                    email: serviceSigner,
                    exp: (impTokenBody.iat + 3600),
                    iat: impTokenBody.iat,
                    iss: serviceSigner,
                    obo: impTokenBody.user,
                    rsrc: impTokenBody.resources,
                    rurl: impTokenBody.refreshUrl,
                    sub: serviceSigner,
                }),
            },
            headers: {
                'Authorization': 'Bearer ' + (await credentials.getServiceAccountAccessToken()).access_token,
                'Content-Type': 'application/json',
            },
            url: credentials.getIAMResourceUrl(serviceSigner),
        };

        try {

            const impToken = {} as ImpTokenModel;
            impToken.impersonation_token = JSON.parse(await request.post(options)).signedJwt;
            impToken.expires_in = 3600;
            impToken.token_type = 'Bearer';
            return impToken;

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

    }

    public static async canBeRefreshed(refreshUrl: string) {

        const options: request.Options = { method: 'GET', url: '' };

75
        if (refreshUrl.startsWith('https://') || refreshUrl.startsWith('http://')) {
Diego Molteni's avatar
Diego Molteni committed
76
77
78
            options.method = 'GET';
            options.headers = {
                'Accept': 'application/json',
79
80
                'Content-Type': 'application/json'
            };
Diego Molteni's avatar
Diego Molteni committed
81
82
83
84
85
86
            options.url = refreshUrl;
        }
        else {
            const refreshUrlOptions = JSON.parse(refreshUrl) as IRefreshUrl;
            options.method = refreshUrlOptions.method;
            options.url = refreshUrlOptions.url;
87
88
            if (refreshUrlOptions.headers) options.headers = refreshUrlOptions.headers;
            if (refreshUrlOptions.body) options.json = refreshUrlOptions.body;
Diego Molteni's avatar
Diego Molteni committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
        }

        try {
            await request(options);
        } catch (error) {
            throw (Error.make(Error.Status.BAD_REQUEST, 'The impersonation token cannot be refreshed.'));
        }

    }

    public static async validate(token: string, skipExpireCheck = false): Promise<ImpTokenBodyModel> {

        const credentials = CredentialsFactory.build(Config.CLOUDPROVIDER);
        const options = {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            url: credentials.getPublicKeyCertificatesUrl(),
        };

        let result: any;
        try {
            result = await request.get(options);
        } catch (error) {
            throw (Error.makeForHTTPRequest(error));
        }

        let pubkey: string;
        let decodedtoken: any;

        try {
            decodedtoken = jwtDecode(token, { complete: true });
            if (!decodedtoken.header.kid) {
                throw (Error.make(Error.Status.BAD_REQUEST,
                    'The impersonation token is not' +
                    ' a valid seismic store impersonation token. header kid not found'));
            }
            pubkey = JSON.parse(result)[decodedtoken.header.kid];
            if (!pubkey) {
                throw (Error.make(Error.Status.BAD_REQUEST,
                    'The impersonation token is not' +
                    ' a valid seismic store impersonation token. pub key not found'));
            }
        } catch (e) {
            throw (Error.make(Error.Status.BAD_REQUEST,
                'The impersonation token is not a valid seismic store impersonation token.'));
        }

        let payload: any;
        try {
            payload = jwtVerify(token, pubkey);
        } catch (error) {
            if (!skipExpireCheck || (error.name && error.name !== 'TokenExpiredError')) {
                throw (Error.make(Error.Status.BAD_REQUEST,
                    'The impersonation token is not a valid seismic store impersonation token.'));
            } else {
                payload = decodedtoken.payload;
            }
        }

        if (payload.iss !== Config.IMP_SERVICE_ACCOUNT_SIGNER) {
            throw (Error.make(Error.Status.BAD_REQUEST,
                'The impersonation token is not a valid seismic store impersonation token.'));

        }

        const impTokenBody = {} as ImpTokenBodyModel;
        impTokenBody.iat = undefined;
        impTokenBody.refreshUrl = payload.rurl;
        impTokenBody.user = payload.obo;
        impTokenBody.resources = payload.rsrc;

        if (!impTokenBody.refreshUrl || !impTokenBody.user || !impTokenBody.resources) {
            throw (Error.make(Error.Status.BAD_REQUEST,
                'The impersonation token is not a valid seismic store impersonation token.'));
        }

        return impTokenBody;

    }

    public static getImpTokenBody(impToken: string): ImpTokenBodyModel {

        const payload = JSON.parse(Buffer.from(
            impToken.replace('Bearer', '').replace(/\s/g, '').split('.')[1], 'base64').toString());

        return {
            iat: payload.iat,
            refreshUrl: payload.rurl,
            resources: payload.rsrc,
            user: payload.obo,
        } as ImpTokenBodyModel;

    }

185
}