server.ts 5.55 KB
Newer Older
Spencer Sutton's avatar
SSL AWS  
Spencer Sutton committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
// ============================================================================
// 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 '../../..';
import { ServiceRouter } from '../../../../services';
import { Feature, FeatureFlags, TraceLog } from '../../../../shared';
import fs from 'fs';
import https from 'https';

// -------------------------------------------------------------------
// Seismic Store Service
// -------------------------------------------------------------------
export class Server {

    private app: express.Express;
    private port: number;

    private httpServer: import('http').Server;
    private httpsServer: import('https').Server;

    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'
        ]
    }

    constructor() {
        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());
        this.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {

            // create and start a new trace object
            res.locals.trace = new TraceLog(req.method + ':' + req.url);

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

            // 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


        // SSL
        const privateKey  = fs.readFileSync(process.env.SSL_KEY_PATH, 'utf8');
        const certificate = fs.readFileSync(process.env.SSL_CERT_PATH, 'utf8');
        const credentials = {key: privateKey, cert: certificate};
        
        if (process.env.SSL_ENABLED === "true"){
            this.httpsServer = https.createServer(credentials, this.app).listen(this.port, () => {
                // tslint:disable-next-line
                console.log(`- Server is listening on port ${this.port}...`);
            });
            this.httpsServer.keepAliveTimeout = 65 * 1000;
            this.httpsServer.headersTimeout = 66 * 1000;
        } else {
            this.httpServer = this.app.listen(this.port, () => {
                // tslint:disable-next-line
                console.log(`- Server is listening on port ${this.port}...`);
            });
            this.httpServer.keepAliveTimeout = 65 * 1000;
            this.httpServer.headersTimeout = 66 * 1000;
        }
    }

    public stop() {
        if (this.httpServer) {
            this.httpServer.close();
        }
        if (this.httpsServer) {
            this.httpsServer.close();
        }
    }
}