server.ts 6.81 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
// ============================================================================
// 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 bodyparser from 'body-parser';
import cors from 'cors';
import express from 'express';
import jwtProxy, { JwtProxyOptions } from 'jwtproxy';
import { Config, LoggerFactory } from '../cloud';
import { ServiceRouter } from '../services';
Diego Molteni's avatar
Diego Molteni committed
23
import { Feature, FeatureFlags } from '../shared';
Diego Molteni's avatar
Diego Molteni committed
24

25
26
import fs from 'fs';
import https from 'https';
Diego Molteni's avatar
Diego Molteni committed
27

Daniel Perez's avatar
Daniel Perez committed
28
import swaggerUi from 'swagger-ui-express';
29
import YAML from 'yamljs';
30
import replaceInFile from 'replace-in-file';
Daniel Perez's avatar
Daniel Perez committed
31

Diego Molteni's avatar
Diego Molteni committed
32
33
34
35
36
37
38
// -------------------------------------------------------------------
// Seismic Store Service
// -------------------------------------------------------------------
export class Server {

    private app: express.Express;
    private port: number;
39
40
41

    private httpServer: import('http').Server;
    private httpsServer: import('https').Server;
Diego Molteni's avatar
Diego Molteni committed
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

    private corsOptions = {
        methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
        preflightContinue: false,
        optionsSuccessStatus: 204,
        credentials: true,
        maxAge: 3600,
        exposedHeaders: [
            'Origin',
            'Content-Type',
            'X-Requested-With',
            'Authorization',
            'Accept',
            'Referer',
            'X-Requested-With',
            'Access-Control-Allow-Origin',
            'x-traffic-manager'
        ],
        allowedHeaders: [
            'Origin',
            'Content-Type',
            'X-Requested-With',
            'Authorization',
            'Accept',
            'Referer',
            'X-Requested-With',
            'Access-Control-Allow-Origin',
            'x-traffic-manager'
        ]
    }

Diego Molteni's avatar
Diego Molteni committed
73
    private optionsDivClear = {
74
        files: 'node_modules/swagger-ui-dist/swagger-ui.css',
75
        from: '.swagger-ui .topbar{display:none;visibility:hidden',
76
        to: '.swagger-ui .topbar{'
77
78
    }

Diego Molteni's avatar
Diego Molteni committed
79
    private optionsDivHide = {
80
81
        files: 'node_modules/swagger-ui-dist/swagger-ui.css',
        from: '.swagger-ui .topbar{',
82
        to: '.swagger-ui .topbar{display:none;visibility:hidden;'
83
84
    }

Diego Molteni's avatar
Diego Molteni committed
85
    constructor() {
Diego Molteni's avatar
Diego Molteni committed
86

87
        const swaggerDocument = YAML.load('./dist/docs/api/openapi.osdu.yaml');
88
        try {
Diego Molteni's avatar
Diego Molteni committed
89
90
            replaceInFile.sync(this.optionsDivClear);
            replaceInFile.sync(this.optionsDivHide);
91
92
93
94
        }
        catch (error) {
            console.error('Error occurred:', error);
        }
95

Diego Molteni's avatar
Diego Molteni committed
96
97
98
99
100
101
        this.app = express();
        this.app.use(bodyparser.urlencoded({ extended: false }));
        this.app.use(bodyparser.json());
        this.app.disable('x-powered-by');
        this.app.use(cors(this.corsOptions));
        this.app.options('*', cors());
Daniel Perez's avatar
Daniel Perez committed
102
        this.app.use('/seistore-svc/api/v3/swagger-ui.html',swaggerUi.serve, swaggerUi.setup(swaggerDocument,{
103
            customCss: '.swagger-ui .topbar { display: none }'
Daniel Perez's avatar
Daniel Perez committed
104
        }));
Diego Molteni's avatar
Diego Molteni committed
105
106
107
108
109
110
111
        this.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {

            // not required anymore - to verify
            if (req.get('slb-on-behalf-of') !== undefined) {
                req.headers.authorization = req.get('slb-on-behalf-of');
            }

Diego Molteni's avatar
Diego Molteni committed
112
113
114
115
116
117
118
            // track caller to the main log
            const key = req.headers['x-api-key'] as string;
            const logger = LoggerFactory.build(Config.CLOUDPROVIDER);
            logger.info(
                ((key && key.length > 5) ? ('[***' + key.substr(key.length - 5) +  '] ') : '')
                + '[' + req.method + '] ' + req.url);

Diego Molteni's avatar
Diego Molteni committed
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
            // init the metrics logger
            if(FeatureFlags.isEnabled(Feature.LOGGING))  {
                LoggerFactory.build(Config.CLOUDPROVIDER).metric('Request Size',
                    req.headers['content-length'] ? +req.headers['content-length'] : 0)
            }

            // forward the caller appkey if exist
            // if exists ensure it does not collide the google-esp api-key (required for backward compatibility)
            req[Config.DE_FORWARD_APPKEY] =
                req.headers['appkey'] !== req.headers['x-api-key'] ? req.headers['appkey'] : undefined

            next();
        });

        const jwtValidateOptions: JwtProxyOptions = {
            disable: !Config.JWT_ENABLE_FEATURE,
            excluded: Config.JWT_EXCLUDE_PATHS ? Config.JWT_EXCLUDE_PATHS.split(';') : [],
            jwksUrl:Config.JWKS_URL,
            algorithms: ['RS256'],
            audience: Config.JWT_AUDIENCE
        }

        // adding middleware to intercept and valiate jwt
        this.app.use(jwtProxy(jwtValidateOptions));

        this.app.use(ServiceRouter);
    }

    public async start(port = Config.SERVICE_PORT) {
        this.port = port;
        // The timeout of the backend service should be greater than the timeout of the load balancer. This will
        // prevent premature connection closures from the service
        // Additionally, the headerstimeout needs to be greater than keepalivetimeout
        // https://github.com/nodejs/node/issues/27363
153
154
155


        // SSL
156
157
158
159
160
        if (Config.SSL_ENABLED){
            const privateKey  = fs.readFileSync(Config.SSL_KEY_PATH, 'utf8');
            const certificate = fs.readFileSync(Config.SSL_CERT_PATH, 'utf8');
            const credentials = {key: privateKey, cert: certificate};
            this.httpsServer = https.createServer(credentials, this.app).listen(this.port, () => {
161
162
163
                // tslint:disable-next-line
                console.log(`- Server is listening on port ${this.port}...`);
            });
Diego Molteni's avatar
fixed    
Diego Molteni committed
164
            this.httpsServer.setTimeout(610000);
Diego Molteni's avatar
Diego Molteni committed
165
166
            this.httpsServer.keepAliveTimeout = 610 * 1000;
            this.httpsServer.headersTimeout = 611 * 1000;
Diego Molteni's avatar
fixed    
Diego Molteni committed
167
        } else {
168
169
170
171
            this.httpServer = this.app.listen(this.port, () => {
                // tslint:disable-next-line
                console.log(`- Server is listening on port ${this.port}...`);
            });
Diego Molteni's avatar
fixed    
Diego Molteni committed
172
            this.httpServer.setTimeout(610000);
Diego Molteni's avatar
fixed    
Diego Molteni committed
173
174
            this.httpServer.keepAliveTimeout = 610 * 1000;
            this.httpServer.headersTimeout = 611 * 1000;
175
        }
Diego Molteni's avatar
Diego Molteni committed
176
177
178
    }

    public stop() {
179
180
181
182
183
        if (this.httpServer) {
            this.httpServer.close();
        }
        if (this.httpsServer) {
            this.httpsServer.close();
Diego Molteni's avatar
Diego Molteni committed
184
185
186
        }
    }
}