-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathappUtils.ts
More file actions
233 lines (212 loc) · 6.78 KB
/
Copy pathappUtils.ts
File metadata and controls
233 lines (212 loc) · 6.78 KB
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
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import express from 'express';
import path from 'path';
import https from 'https';
import http from 'http';
import morgan from 'morgan';
import fs from 'fs';
import timeout from 'connect-timeout';
import bodyParser from 'body-parser';
import pjson from '../../package.json';
import logger from '../logger';
import { Config, TlsMode } from '../initConfig';
/**
* Set up the logging middleware provided by morgan
*/
export function setupLogging(app: express.Application, config: Config): void {
// Set up morgan for logging, with optional logging into a file
let middleware;
if (config.logFile) {
// create a write stream (in append mode)
const accessLogPath = path.resolve(config.logFile);
const accessLogStream = fs.createWriteStream(accessLogPath, { flags: 'a' });
logger.info(`Log location: ${accessLogPath}`);
// setup the logger
middleware = morgan('combined', { stream: accessLogStream });
} else {
middleware = morgan('combined');
}
app.use(middleware);
}
/**
* Create common Express middleware
*/
export function setupCommonMiddleware(app: express.Application, config: Config): void {
// Be more robust about accepting URLs with double slashes
app.use(function replaceUrlSlashes(
req: express.Request,
res: express.Response,
next: express.NextFunction,
) {
req.url = req.url.replace(/\/{2,}/g, '/');
next();
});
// Set timeout
app.use(timeout(config.timeout) as any);
// Add body parser
app.use(bodyParser.json({ limit: '20mb' }));
}
/**
* Create error handling middleware
*/
export function createErrorHandler() {
return function (
err: any,
req: express.Request,
res: express.Response,
_next: express.NextFunction,
) {
logger.error('Error:', { error: err && err.message ? err.message : String(err) });
const statusCode = err && err.status ? err.status : 500;
const result = {
error: err && err.message ? err.message : String(err),
name: err && err.name ? err.name : 'Error',
code: err && err.code ? err.code : undefined,
version: pjson.version,
};
return res.status(statusCode).json(result);
};
}
/**
* Create HTTP server
*/
export function createHttpServer(app: express.Application): http.Server {
return http.createServer(app);
}
/**
* Configure server timeouts
*/
export function configureServerTimeouts(server: https.Server | http.Server, config: Config): void {
if (config.keepAliveTimeout !== undefined) {
server.keepAliveTimeout = config.keepAliveTimeout;
}
if (config.headersTimeout !== undefined) {
server.headersTimeout = config.headersTimeout;
}
}
/**
* Prepare IPC socket
*/
export async function prepareIpc(ipcSocketFilePath: string): Promise<void> {
if (process.platform === 'win32') {
throw new Error(`IPC option is not supported on platform ${process.platform}`);
}
try {
const stat = fs.statSync(ipcSocketFilePath);
if (!stat.isSocket()) {
throw new Error('IPC socket is not actually a socket');
}
fs.unlinkSync(ipcSocketFilePath);
} catch (e: any) {
if (e.code !== 'ENOENT') {
throw e;
}
}
}
/**
* Read SSL/TLS certificates from files
*/
export async function readCertificates(
keyPath: string,
crtPath: string,
): Promise<{ key: string; cert: string }> {
const privateKeyPromise = fs.promises.readFile(keyPath, 'utf8');
const certificatePromise = fs.promises.readFile(crtPath, 'utf8');
const [key, cert] = await Promise.all([privateKeyPromise, certificatePromise]);
return { key, cert };
}
/**
* Setup common health check routes
*/
export function setupHealthCheckRoutes(app: express.Application, serverType: string): void {
app.get('/ping', (_req, res) => {
res.json({
status: `${serverType} server is ok!`,
timestamp: new Date().toISOString(),
});
});
app.get('/version', (_req, res) => {
res.json({
version: pjson.version,
name: pjson.name,
});
});
}
/**
* Create mTLS middleware for validating client certificates
*/
export function createMtlsMiddleware(config: {
tlsMode: TlsMode;
mtlsRequestCert: boolean;
allowSelfSigned?: boolean;
mtlsAllowedClientFingerprints?: string[];
}): express.RequestHandler {
return (req: express.Request, res: express.Response, next: express.NextFunction) => {
const clientCert = (req as any).socket?.getPeerCertificate();
// Check if client certificate is actually present (not just an empty object)
const hasValidClientCert =
clientCert && Object.keys(clientCert).length > 0 && clientCert.subject;
// If client cert is required but not provided
if (config.mtlsRequestCert && !hasValidClientCert) {
return res.status(403).json({
error: 'mTLS Authentication Failed',
message: 'Client certificate is required for this endpoint',
details: 'Please provide a valid client certificate in your request',
});
}
// If client cert is provided, validate it
if (hasValidClientCert) {
// Check if self-signed certificates are allowed
if (!config.allowSelfSigned && clientCert.issuer.CN === clientCert.subject.CN) {
return res.status(403).json({
error: 'mTLS Authentication Failed',
message: 'Self-signed certificates are not allowed',
details: 'Please use a certificate issued by a trusted CA',
});
}
// Check fingerprint restrictions if configured
if (config.mtlsAllowedClientFingerprints?.length) {
const fingerprint = clientCert.fingerprint256?.replace(/:/g, '').toUpperCase();
if (!fingerprint || !config.mtlsAllowedClientFingerprints?.includes(fingerprint)) {
return res.status(403).json({
error: 'mTLS Authentication Failed',
message: 'Client certificate fingerprint not authorized',
details: `Certificate fingerprint ${fingerprint} is not in the allowed list`,
});
}
}
}
// Store client certificate info for logging
if (hasValidClientCert) {
(req as any).clientCert = clientCert;
}
next();
};
}
/**
* Validate that TLS certificates are properly loaded when TLS is enabled
*/
export function validateTlsCertificates(config: {
tlsMode: TlsMode;
tlsKey?: string;
tlsCert?: string;
}): void {
if (config.tlsMode !== TlsMode.DISABLED) {
if (!config.tlsKey || !config.tlsCert) {
throw new Error('TLS is enabled but certificates are not properly loaded');
}
}
}
/**
* Validate Master Express configuration
*/
export function validateMasterExpressConfig(config: {
enclavedExpressUrl: string;
enclavedExpressCert: string;
}): void {
if (!config.enclavedExpressUrl) {
throw new Error('ENCLAVED_EXPRESS_URL is required for Master Express mode');
}
if (!config.enclavedExpressCert) {
throw new Error('ENCLAVED_EXPRESS_CERT is required for Master Express mode');
}
}