handler.ts 6.53 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
// ============================================================================
// Copyright 2017-2020, 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';
import { TenantModel } from '.';
import { Auth, AuthGroups } from '../../auth';
Diego Molteni's avatar
Diego Molteni committed
20
21
import { Config, JournalFactoryTenantClient } from '../../cloud';
import { Error, ErrorModel, Feature, FeatureFlags, Response } from '../../shared';
Diego Molteni's avatar
Diego Molteni committed
22
23
24
25
26
27
28
29
30
31
32
33
34
import { SubProjectDAO } from '../subproject';
import { TenantDAO } from './dao';
import { TenantGroups } from './groups';
import { TenantOP } from './optype';
import { TenantParser } from './parser';

export class TenantHandler {

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

        try {

Diego Molteni's avatar
lint    
Diego Molteni committed
35
            // tenant endpoints are not available with impersonation token
Diego Molteni's avatar
Diego Molteni committed
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
75
76
            if (Auth.isImpersonationToken(req.headers.authorization)) {
                throw (Error.make(Error.Status.PERMISSION_DENIED,
                    'tenant endpoints not available' +
                    ' with an impersonation token as Auth credentials.'));
            }

            if (op === TenantOP.CREATE) {

                Response.writeOK(res, await this.create(req));

            } else if (op === TenantOP.GET) {

                Response.writeOK(res, await this.get(req));

            } else if (op === TenantOP.DELETE) {

                Response.writeOK(res, await this.delete(req));

            } else if (op === TenantOP.GETSDPATH) {

                Response.writeOK(res, await this.getTenantSDPath(req));

            } else { throw (Error.make(Error.Status.UNKNOWN, 'Internal Server Error')); }

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

    }

    // create a new tenant
    private static async create(req: expRequest): Promise<TenantModel> {

        // Parse input parameters
        const tenant = TenantParser.create(req);

        if (!tenant.default_acls) {
            throw (Error.make(Error.Status.BAD_REQUEST,
                'Default ACL for ' + tenant.name + ' was not provided'));
        }

        if (FeatureFlags.isEnabled(Feature.AUTHORIZATION)) {
            await Auth.isUserAuthorized(
Diego Molteni's avatar
Diego Molteni committed
77
78
                req.headers.authorization, [AuthGroups.datalakeUserAdminGroupEmail(tenant.esd)],
                tenant.esd, req[Config.DE_FORWARD_APPKEY]);
Diego Molteni's avatar
Diego Molteni committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
        }

        // Check if tenant already exists
        if (await TenantDAO.exist(tenant)) {
            throw (Error.make(Error.Status.ALREADY_EXISTS,
                'The tenant ' + tenant.name + ' has been registered already'));
        }

        // register the tenant metadata
        // leave this registration at the end as last operation (mapping to do only if all previuos operation succed)
        await TenantDAO.register(tenant);

        return tenant;

    }

    // get the tenant project metadata
    private static async get(req: expRequest): Promise<TenantModel> {

        // retrieve the tenant informations
        const tenant = await TenantDAO.get(req.params.tenantid);

        if (FeatureFlags.isEnabled(Feature.AUTHORIZATION)) {
            await Auth.isUserAuthorized(
Diego Molteni's avatar
Diego Molteni committed
103
104
                req.headers.authorization, [AuthGroups.datalakeUserAdminGroupEmail(tenant.esd)],
                tenant.esd, req[Config.DE_FORWARD_APPKEY]);
Diego Molteni's avatar
Diego Molteni committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
        }

        return tenant;
    }

    // delete the tenant project metadata
    private static async delete(req: expRequest): Promise<void> {

        // retrieve the tenant informations
        const tenant = await TenantDAO.get(req.params.tenantid);

        if (FeatureFlags.isEnabled(Feature.AUTHORIZATION)) {
            // check if who make the request is a data parititon admin admin
            await Auth.isUserAuthorized(
Diego Molteni's avatar
Diego Molteni committed
119
120
                req.headers.authorization, [AuthGroups.datalakeUserAdminGroupEmail(tenant.esd)],
                tenant.esd, req[Config.DE_FORWARD_APPKEY]);
Diego Molteni's avatar
Diego Molteni committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
        }

        // retrieve the subprojects list
        const journalClient = JournalFactoryTenantClient.get(tenant);
        const subprojects = await SubProjectDAO.list(journalClient, tenant.name);

        if (!subprojects || subprojects.length > 0) {
            throw (Error.make(Error.Status.BAD_REQUEST,
                'The tenant project \'' + tenant.name + '\' cannot be deleted, ' +
                'it is not empty (contains subprojects).'));
        }

        // clear groups and delete the mapping entry
        await Promise.all([
            // need to keep it for the old ones that have tenant group
136
            TenantDAO.delete(tenant.name), !tenant.default_acls ? AuthGroups.deleteGroup(req.headers.authorization,
Diego Molteni's avatar
Diego Molteni committed
137
138
139
140
141
142
                TenantGroups.adminGroup(tenant), tenant.esd, req[Config.DE_FORWARD_APPKEY]) : undefined]);
    }

    // get tenant path from data partition information
    public static async getTenantSDPath(req: expRequest): Promise<string> {

143
144
145
146
147
148
149
        const dataPartition = TenantParser.dataPartition(req);

        if (FeatureFlags.isEnabled(Feature.AUTHORIZATION)) {
            await Auth.isUserRegistered(req.headers.authorization,
                (await TenantDAO.get(dataPartition)).esd, req[Config.DE_FORWARD_APPKEY]);
        }

Diego Molteni's avatar
Diego Molteni committed
150
151
        try {
            const tenants = await TenantDAO.getAll();
152
            if (dataPartition === 'slb') return (Config.SDPATHPREFIX + dataPartition);
Diego Molteni's avatar
Diego Molteni committed
153
            for (const tenant of tenants) {
154
                if (tenant.esd.startsWith(dataPartition)) {
Diego Molteni's avatar
Diego Molteni committed
155
156
157
158
159
160
161
162
163
                    if (FeatureFlags.isEnabled(Feature.AUTHORIZATION)) {
                        await Auth.isUserRegistered(req.headers.authorization,
                            tenant.esd, req[Config.DE_FORWARD_APPKEY]);
                    }
                    return Config.SDPATHPREFIX + tenant.name;
                }
            }
        } catch (error) {
            if ((error as ErrorModel).error.code === Error.Status.NOT_IMPLEMENTED) {
164
                return Config.SDPATHPREFIX + dataPartition;
Diego Molteni's avatar
Diego Molteni committed
165
166
167
168
169
170
171
            } else { throw error; }
        }


    }

}