handler.ts 6.76 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 { Request as expRequest, Response as expResponse } from 'express';
Diego Molteni's avatar
Diego Molteni committed
18
import { ImpTokenModel } from '.';
Diego Molteni's avatar
Diego Molteni committed
19
import { Auth } from '../../auth';
Diego Molteni's avatar
Diego Molteni committed
20
import { Config, JournalFactoryTenantClient } from '../../cloud';
21
import { SeistoreFactory } from '../../cloud/seistore';
Diego Molteni's avatar
Diego Molteni committed
22
23
import { Error, Feature, FeatureFlags, Response, Utils } from '../../shared';
import { SubProjectDAO } from '../subproject';
Diego Molteni's avatar
Diego Molteni committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { TenantDAO } from '../tenant';
import { ImpTokenDAO } from './dao';
import { ImpTokenOP } from './optype';
import { ImpTokenParser } from './parser';

export class ImpTokenHandler {

    // handler for the [ /imptoken ] endpoints
    public static async handler(req: expRequest, res: expResponse, op: ImpTokenOP) {

        try {

            // This check will be removed once the azure implementation for imptoken will be provided.
            if (Config.CLOUDPROVIDER === 'azure') {
                throw (Error.make(Error.Status.NOT_IMPLEMENTED,
                    'The impersonation token endpoints are not currently supported in azure.'));
            }

42
43
44
45
46
            if (Config.CLOUDPROVIDER === 'aws') {
                throw (Error.make(Error.Status.NOT_IMPLEMENTED,
                    'The impersonation token endpoints are not currently supported in aws.'));
            }

Diego Molteni's avatar
Diego Molteni committed
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
            // subproject endpoints are not available with impersonation token
            if (op !== ImpTokenOP.Refresh) {
                if (Auth.isImpersonationToken(req.headers.authorization)) {
                    throw (Error.make(Error.Status.PERMISSION_DENIED,
                        'Impersonation token endpoints not available' +
                        ' with an impersonation token as Auth credentials.'));
                }
            }

            if (op === ImpTokenOP.Generate) {
                Response.writeOK(res, await this.create(req));
            } else if (op === ImpTokenOP.Refresh) {
                Response.writeOK(res, await this.refresh(req));
            } else if (op === ImpTokenOP.Patch) {
                Response.writeOK(res, await this.patch(req));
            } else { throw (Error.make(Error.Status.UNKNOWN, 'Internal Server Error')); }

        } catch (error) { Response.writeError(res, error); }

    }

    // create an impersonation token
    private static async create(req: expRequest): Promise<ImpTokenModel> {

        if (!FeatureFlags.isEnabled(Feature.IMPTOKEN)) return {} as ImpTokenModel;

73
        const tokenBody = await ImpTokenParser.create(req);
Diego Molteni's avatar
Diego Molteni committed
74
75
76
77
        const tenantName = tokenBody.resources[0].resource.split('/')[0];
        const tenant = await TenantDAO.get(tenantName);

        // check if it is a trusted application
78
79
        const appEmail = await SeistoreFactory.build(
            Config.CLOUDPROVIDER).getEmailFromTokenPayload(req.headers.authorization, false);
Diego Molteni's avatar
Diego Molteni committed
80
81
82
83
84
85
86

        await Auth.isAppAuthorized(tenant, appEmail);

        // check authorization in each subproject
        const checkAuthorizations = [];
        for (const item of tokenBody.resources) {
            const resourcePath = item.resource.split('/');
Diego Molteni's avatar
Diego Molteni committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

            const subprojectName = resourcePath[1]


            // init journalClient client
            const journalClient = JournalFactoryTenantClient.get(tenant);

            const spkey = journalClient.createKey({
                namespace: Config.SEISMIC_STORE_NS + '-' + tenant.name,
                path: [Config.SUBPROJECTS_KIND, subprojectName],
            });

            // retrieve the destination subproject info
            const subproject = await SubProjectDAO.get(journalClient, tenant.name, subprojectName, spkey);

Diego Molteni's avatar
Diego Molteni committed
102
103
104
            if (item.readonly) {
                checkAuthorizations.push(
                    Auth.isReadAuthorized(tokenBody.userToken,
Diego Molteni's avatar
Diego Molteni committed
105
                        subproject.acls.viewers.concat(subproject.acls.admins),
Diego Molteni's avatar
Diego Molteni committed
106
107
108
109
                        resourcePath[0], resourcePath[1], tenant.esd, req[Config.DE_FORWARD_APPKEY], false));
            } else {
                checkAuthorizations.push(
                    Auth.isWriteAuthorized(tokenBody.userToken,
Diego Molteni's avatar
Diego Molteni committed
110
                        subproject.acls.admins,
Diego Molteni's avatar
Diego Molteni committed
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
                        resourcePath[0], resourcePath[1], tenant.esd, req[Config.DE_FORWARD_APPKEY], false));
            }
        }
        const results = await Promise.all(checkAuthorizations);
        const index = results.indexOf(false);
        if (results.indexOf(false) !== -1) {
            const readMex = tokenBody.resources[index].readonly ? 'read' : 'write';
            const sprojMex = Config.SDPATHPREFIX + tokenBody.resources[index].resource;
            throw (Error.make(Error.Status.PERMISSION_DENIED,
                'User is not ' + readMex + 'authorized in the ' + sprojMex + ' subproject resource.'));
        }

        // generate the imp token
        return await ImpTokenDAO.create(tokenBody);

    }

    // refresh an impersonation token
    private static async refresh(req: expRequest): Promise<ImpTokenModel> {

        if (!FeatureFlags.isEnabled(Feature.IMPTOKEN)) return {} as ImpTokenModel;

        // parse the request input and retrieve the token
        const tokenToRefresh = ImpTokenParser.refresh(req);

        // validate the refresh token
        const tokenToRefreshBody = await ImpTokenDAO.validate(tokenToRefresh, true);

        // check if it can be refreshed
        await ImpTokenDAO.canBeRefreshed(tokenToRefreshBody.refreshUrl);

        // generate a new impersonation token
        return await ImpTokenDAO.create(tokenToRefreshBody);

    }

    // patch an impersonation token
    private static async patch(req: expRequest): Promise<ImpTokenModel> {

        if (!FeatureFlags.isEnabled(Feature.IMPTOKEN)) return {} as ImpTokenModel;

        const result = await ImpTokenParser.patch(req);
        const tokenToPach = result.tokenToPatch;
        const refreshUrl = result.refreshUrl;

        // validate the refresh token
        const tokenToPachBody = await ImpTokenDAO.validate(tokenToPach);

        // generate a new impersonation token with a new refresh url
        tokenToPachBody.refreshUrl = refreshUrl;
        return await ImpTokenDAO.create(tokenToPachBody);

    }

}