-
Notifications
You must be signed in to change notification settings - Fork 272
/
api-server.ts
807 lines (701 loc) · 29 KB
/
api-server.ts
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
import type { AddressInfo } from "net";
import type { Server as SecureServer } from "https";
import type { Request, Response, RequestHandler } from "express";
import type { ServerOptions as SocketIoServerOptions } from "socket.io";
import type { Socket as SocketIoSocket } from "socket.io";
import exitHook from "async-exit-hook";
import os from "os";
import path from "path";
import tls from "tls";
import { Server, createServer } from "http";
import { createServer as createSecureServer } from "https";
import { RuntimeError } from "run-time-error";
import { gte } from "semver";
import lmify from "lmify";
import fs from "fs-extra";
import expressHttpProxy from "express-http-proxy";
import { Server as GrpcServer } from "@grpc/grpc-js";
import { ServerCredentials as GrpcServerCredentials } from "@grpc/grpc-js";
import express from "express";
import { OpenAPIV3 } from "express-openapi-validator/dist/framework/types";
import compression from "compression";
import bodyParser from "body-parser";
import cors, { CorsOptionsDelegate, CorsRequest } from "cors";
import rateLimit from "express-rate-limit";
import { Server as SocketIoServer } from "socket.io";
import { authorize as authorizeSocket } from "@thream/socketio-jwt";
import {
ICactusPlugin,
isIPluginWebService,
IPluginWebService,
IPluginFactoryOptions,
PluginFactoryFactory,
PluginImport,
Constants,
PluginImportAction,
} from "@hyperledger/cactus-core-api";
import {
PluginRegistry,
registerWebServiceEndpoint,
} from "@hyperledger/cactus-core";
import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core";
import {
Bools,
Logger,
LoggerProvider,
newRex,
Servers,
} from "@hyperledger/cactus-common";
import { ICactusApiServerOptions } from "./config/config-service";
import OAS from "../json/openapi.json";
import { PrometheusExporter } from "./prometheus-exporter/prometheus-exporter";
import { AuthorizerFactory } from "./authzn/authorizer-factory";
import { WatchHealthcheckV1 } from "./generated/openapi/typescript-axios";
import { WatchHealthcheckV1Endpoint } from "./web-services/watch-healthcheck-v1-endpoint";
import * as default_service from "./generated/proto/protoc-gen-ts/services/default_service";
import { GrpcServerApiServer } from "./web-services/grpc/grpc-server-api-server";
import { determineAddressFamily } from "./common/determine-address-family";
import {
GetOpenApiSpecV1Endpoint,
IGetOpenApiSpecV1EndpointOptions,
} from "./web-services/get-open-api-spec-v1-endpoint";
export interface IApiServerConstructorOptions {
readonly pluginManagerOptions?: { pluginsPath: string };
readonly pluginRegistry?: PluginRegistry;
readonly httpServerApi?: Server | SecureServer;
readonly wsServerApi?: SocketIoServer;
readonly grpcServer?: GrpcServer;
readonly wsOptions?: SocketIoServerOptions;
readonly httpServerCockpit?: Server | SecureServer;
readonly config: ICactusApiServerOptions;
readonly prometheusExporter?: PrometheusExporter;
readonly enableShutdownHook?: boolean;
}
export class ApiServer {
public static readonly CLASS_NAME = "ApiServer";
public static readonly E_POST_CRASH_SHUTDOWN =
"API server failed to shut itself down, will ignore this because we were already crashing anyway...";
public static readonly E_NON_EXEMPT_UNPROTECTED_ENDPOINTS =
`Non-exempt unprotected endpoints found. ` +
`You can allow them as unprotected via the configuration of the ` +
`API server by specifying an array of patterns in the property ` +
`"unprotectedEndpointExemptions" of "authorizationConfigJson". ` +
`This mechanism is meant to foster DevOps where both dev & ops ` +
`work together in making secure application deployments a reality. ` +
`The comma separated list of unprotected endpoints that were not marked as exempt: `;
private readonly log: Logger;
private pluginRegistry: PluginRegistry | undefined;
private readonly httpServerApi: Server | SecureServer;
private readonly httpServerCockpit?: Server | SecureServer;
private readonly wsApi: SocketIoServer;
private readonly grpcServer: GrpcServer;
private readonly expressApi: express.Express;
private readonly expressCockpit: express.Express;
private readonly pluginsPath: string;
private readonly enableShutdownHook: boolean;
public prometheusExporter: PrometheusExporter;
public get className(): string {
return ApiServer.CLASS_NAME;
}
constructor(public readonly options: IApiServerConstructorOptions) {
if (!options) {
throw new Error(`ApiServer#ctor options was falsy`);
}
if (!options.config) {
throw new Error(`ApiServer#ctor options.config was falsy`);
}
this.enableShutdownHook = Bools.isBooleanStrict(
options.config.enableShutdownHook,
)
? (options.config.enableShutdownHook as boolean)
: true;
if (this.enableShutdownHook) {
exitHook(() => this.shutdown());
}
LoggerProvider.setLogLevel(options.config.logLevel);
if (this.options.httpServerApi) {
this.httpServerApi = this.options.httpServerApi;
} else if (this.options.config.apiTlsEnabled) {
this.httpServerApi = createSecureServer({
key: this.options.config.apiTlsKeyPem,
cert: this.options.config.apiTlsCertPem,
});
} else {
this.httpServerApi = createServer();
}
if (this.options.config.cockpitEnabled) {
if (this.options.httpServerCockpit) {
this.httpServerCockpit = this.options.httpServerCockpit;
} else if (this.options.config.cockpitTlsEnabled) {
this.httpServerCockpit = createSecureServer({
key: this.options.config.cockpitTlsKeyPem,
cert: this.options.config.cockpitTlsCertPem,
});
} else {
this.httpServerCockpit = createServer();
}
}
this.grpcServer = this.options.grpcServer || new GrpcServer({});
this.wsApi = new SocketIoServer();
this.expressApi = express();
this.expressCockpit = express();
if (this.options.prometheusExporter) {
this.prometheusExporter = this.options.prometheusExporter;
} else {
this.prometheusExporter = new PrometheusExporter({
pollingIntervalInMin: 1,
});
}
this.prometheusExporter.startMetricsCollection();
this.prometheusExporter.setTotalPluginImports(this.getPluginImportsCount());
this.log = LoggerProvider.getOrCreate({
label: "api-server",
level: options.config.logLevel,
});
const defaultPluginsPath = path.join(
os.tmpdir(),
"org",
"hyperledger",
"cactus",
"plugins",
);
const { pluginsPath } = {
...{ pluginsPath: defaultPluginsPath },
...JSON.parse(this.options.config.pluginManagerOptionsJson),
...this.options.pluginManagerOptions,
} as { pluginsPath: string };
this.pluginsPath = pluginsPath;
this.log.debug("pluginsPath: %o", pluginsPath);
}
public getPrometheusExporter(): PrometheusExporter {
return this.prometheusExporter;
}
public async getPrometheusExporterMetrics(): Promise<string> {
this.prometheusExporter.setTotalPluginImports(this.getPluginImportsCount());
const res: string = await this.prometheusExporter.getPrometheusMetrics();
this.log.debug(`getPrometheusExporterMetrics() response: %o`, res);
return res;
}
public getPluginImportsCount(): number {
return this.pluginRegistry?.plugins.length || 0;
}
async start(): Promise<{
addressInfoCockpit?: AddressInfo;
addressInfoApi: AddressInfo;
addressInfoGrpc: AddressInfo;
}> {
this.checkNodeVersion();
const tlsMaxVersion = this.options.config.tlsDefaultMaxVersion;
this.log.info("Setting tls.DEFAULT_MAX_VERSION to %s...", tlsMaxVersion);
tls.DEFAULT_MAX_VERSION = tlsMaxVersion;
try {
const { cockpitTlsEnabled, apiTlsEnabled } = this.options.config;
let addressInfoCockpit: AddressInfo | undefined;
if (this.options.config.cockpitEnabled) {
addressInfoCockpit = await this.startCockpitFileServer();
}
const addressInfoApi = await this.startApiServer();
const addressInfoGrpc = await this.startGrpcServer();
{
const { port, address } = addressInfoGrpc;
const grpcUrl = `${address}:${port}`;
this.log.info(`Cactus gRPC reachable ${grpcUrl}`);
}
{
const { apiHost: host } = this.options.config;
const { port } = addressInfoApi;
const protocol = apiTlsEnabled ? "https:" : "http:";
const httpUrl = `${protocol}//${host}:${port}`;
this.log.info(`Cactus API reachable ${httpUrl}`);
}
if (this.options.config.cockpitEnabled) {
const { cockpitHost: host } = this.options.config;
const { port } = addressInfoCockpit as AddressInfo;
const protocol = cockpitTlsEnabled ? "https:" : "http:";
const httpUrl = `${protocol}//${host}:${port}`;
this.log.info(`Cactus Cockpit reachable ${httpUrl}`);
}
return { addressInfoCockpit, addressInfoApi, addressInfoGrpc };
} catch (ex1: unknown) {
const context = "Failed to start ApiServer";
this.log.error(context, ex1);
this.log.error(`Attempting shutdown...`);
try {
await this.shutdown();
this.log.info(`Server shut down after crash OK`);
} catch (ex2: unknown) {
this.log.error(ApiServer.E_POST_CRASH_SHUTDOWN, ex2);
}
throw newRex(context, ex1);
}
}
/**
* Verifies that the currently running NodeJS process is at least of a certain
* NodeJS version as specified by the configuration.
*
* @throws {Error} if the version contraint is not satisfied by the runtime.
*/
public checkNodeVersion(currentVersion: string = process.version): void {
if (gte(this.options.config.minNodeVersion, currentVersion)) {
const msg =
`ApiServer#checkNodeVersion() detected NodeJS ` +
`v${process.version} that is outdated as per the configuration. ` +
`If you must run on this NodeJS version you can override the minimum ` +
`acceptable version via config parameters of the API server. ` +
`Though doing so may lead to vulnerabilities in your deployment. ` +
`You've been warned.`;
throw new Error(msg);
}
}
public getHttpServerApi(): Server | SecureServer {
return this.httpServerApi;
}
public getHttpServerCockpit(): Server | SecureServer | undefined {
return this.httpServerCockpit;
}
public async getOrInitPluginRegistry(): Promise<PluginRegistry> {
try {
if (!this.pluginRegistry) {
if (!this.options.pluginRegistry) {
this.log.info(`getOrInitPluginRegistry() initializing a new one...`);
this.pluginRegistry = await this.initPluginRegistry();
} else {
this.log.info(`getOrInitPluginRegistry() re-using injected one...`);
this.pluginRegistry = this.options.pluginRegistry;
}
}
await this.prometheusExporter.setTotalPluginImports(
await this.getPluginImportsCount(),
);
return this.pluginRegistry;
} catch (ex: unknown) {
this.pluginRegistry = new PluginRegistry({ plugins: [] });
const context = "Failed to init PluginRegistry";
this.log.debug(context, ex);
throw newRex(context, ex);
}
}
public async initPluginRegistry(req?: {
readonly pluginRegistry: PluginRegistry;
}): Promise<PluginRegistry> {
const { pluginRegistry = new PluginRegistry({ plugins: [] }) } = req || {};
const { plugins } = this.options.config;
this.log.info(`Instantiated empty registry, invoking plugin factories...`);
for (const pluginImport of plugins) {
const plugin = await this.instantiatePlugin(pluginImport, pluginRegistry);
pluginRegistry.add(plugin);
}
return pluginRegistry;
}
private async instantiatePlugin(
pluginImport: PluginImport,
registry: PluginRegistry,
): Promise<ICactusPlugin> {
const fnTag = `${this.className}#instantiatePlugin`;
const { logLevel } = this.options.config;
const { packageName, options } = pluginImport;
this.log.info(`Creating plugin from package: ${packageName}`, options);
const pluginOptions = { ...options, logLevel, pluginRegistry: registry };
try {
if (pluginImport.action == PluginImportAction.Install) {
await this.installPluginPackage(pluginImport);
} else {
this.log.info(
`The installation of the plugin package ${packageName} was skipped due to the configuration flag action`,
);
}
const packagePath = path.join(
this.pluginsPath,
options.instanceId,
"node_modules",
packageName,
);
this.log.debug("Package path: %o", packagePath);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const pluginPackage = require(/* webpackIgnore: true */ packagePath);
const createPluginFactory =
pluginPackage.createPluginFactory as PluginFactoryFactory;
const pluginFactoryOptions: IPluginFactoryOptions = {
pluginImportType: pluginImport.type,
};
const pluginFactory = await createPluginFactory(pluginFactoryOptions);
const plugin = await pluginFactory.create(pluginOptions);
// need to invoke the i-cactus-plugin onPluginInit functionality here before plugin registry can be used further
await plugin.onPluginInit();
return plugin;
} catch (ex: unknown) {
const context = `${fnTag} failed instantiating plugin '${packageName}' with the instanceId '${options.instanceId}'`;
this.log.debug(context, ex);
throw newRex(context, ex);
}
}
private async installPluginPackage(
pluginImport: PluginImport,
): Promise<void> {
const fnTag = `ApiServer#installPluginPackage()`;
const pkgName = pluginImport.options.packageSrc
? pluginImport.options.packageSrc
: pluginImport.packageName;
const instanceId = pluginImport.options.instanceId;
const pluginPackageDir = path.join(this.pluginsPath, instanceId);
// version of the npm package
const pluginVersion = pluginImport.options.version
? "@".concat(pluginImport.options.version)
: "";
try {
await fs.mkdirp(pluginPackageDir);
this.log.debug(`${pkgName} plugin package dir: %o`, pluginPackageDir);
} catch (ex: unknown) {
const context =
"Could not create plugin installation directory, check the file-system permissions.";
throw newRex(context, ex);
}
try {
lmify.setPackageManager("npm");
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
lmify.setRootDir(pluginPackageDir);
this.log.debug(`Installing ${pkgName} for plugin import`, pluginImport);
const out = await lmify.install([
pkgName.concat(pluginVersion), // empty if no version was specified
"--production",
"--audit=false",
"--progress=false",
"--fund=false",
`--prefix=${pluginPackageDir}`,
// "--ignore-workspace-root-check",
]);
this.log.debug("%o install result: %o", pkgName, out);
if (out?.exitCode && out.exitCode !== 0) {
const eMsg = "Non-zero exit code returned by lmify.install() indicating that the underlying npm install OS process had encountered a problem:";
throw newRex(eMsg, out);
}
this.log.info(`Installed ${pkgName} OK`);
} catch (ex: unknown) {
const context = `${fnTag} failed installing plugin '${pkgName}`;
this.log.debug(ex, context);
throw newRex(context, ex);
}
}
public async shutdown(): Promise<void> {
this.log.info(`Shutting down API server ...`);
const registry = await this.getOrInitPluginRegistry();
const webServicesShutdown = registry
.getPlugins()
.filter((pluginInstance) => isIPluginWebService(pluginInstance))
.map((pluginInstance: ICactusPlugin) => {
return (pluginInstance as IPluginWebService).shutdown();
});
this.log.info(`Stopping ${webServicesShutdown.length} WS plugin(s)...`);
await Promise.all(webServicesShutdown);
this.log.info(`Stopped ${webServicesShutdown.length} WS plugin(s) OK`);
if (this.httpServerApi?.listening) {
this.log.info(`Closing Cacti HTTP server of the API...`);
await Servers.shutdown(this.httpServerApi);
this.log.info(`Close HTTP server of the API OK`);
}
if (this.httpServerCockpit?.listening) {
this.log.info(`Closing Cacti HTTP server of the cockpit ...`);
await Servers.shutdown(this.httpServerCockpit);
this.log.info(`Close HTTP server of the cockpit OK`);
}
if (this.grpcServer) {
this.log.info(`Closing Cacti gRPC server ...`);
await new Promise<void>((resolve, reject) => {
this.grpcServer.tryShutdown((ex?: Error) => {
if (ex) {
const eMsg = "Failed to shut down gRPC server of the Cacti API server.";
this.log.debug(eMsg, ex);
reject(newRex(eMsg, ex));
} else {
resolve();
}
});
});
this.log.info(`Close gRPC server OK`);
}
}
async startCockpitFileServer(): Promise<AddressInfo> {
const { expressCockpit: app } = this;
const cockpitWwwRoot = this.options.config.cockpitWwwRoot;
this.log.info(`wwwRoot: ${cockpitWwwRoot}`);
const resolvedWwwRoot = path.resolve(process.cwd(), cockpitWwwRoot);
this.log.info(`resolvedWwwRoot: ${resolvedWwwRoot}`);
const resolvedIndexHtml = path.resolve(resolvedWwwRoot + "/index.html");
this.log.info(`resolvedIndexHtml: ${resolvedIndexHtml}`);
const cockpitCorsDomainCsv = this.options.config.cockpitCorsDomainCsv;
const allowedDomains = cockpitCorsDomainCsv.split(",");
const corsMiddleware = this.createCorsMiddleware(allowedDomains);
const {
apiHost,
apiPort,
cockpitApiProxyRejectUnauthorized: rejectUnauthorized,
} = this.options.config;
const protocol = this.options.config.apiTlsEnabled ? "https:" : "http:";
const apiHttpUrl = `${protocol}//${apiHost}:${apiPort}`;
const apiProxyMiddleware = expressHttpProxy(apiHttpUrl, {
// preserve the path whatever it was. Without this the proxy just uses /
proxyReqPathResolver: (srcReq) => srcReq.originalUrl,
proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
const { originalUrl: thePath } = srcReq;
const srcHost = srcReq.header("host");
const { host: destHostname, port: destPort } = proxyReqOpts;
const destHost = `${destHostname}:${destPort}`;
this.log.debug(`PROXY ${srcHost} => ${destHost} :: ${thePath}`);
// make sure self signed certs are accepted if it was configured as such by the user
(proxyReqOpts as Record<string, unknown>).rejectUnauthorized =
rejectUnauthorized;
return proxyReqOpts;
},
});
const rateLimiterIndexHtml = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
const middlewareIndexHtml: RequestHandler = (_, res) =>
res.sendFile(resolvedIndexHtml);
app.use("/api/v*", apiProxyMiddleware);
app.use(compression());
app.use(corsMiddleware);
app.use(express.static(resolvedWwwRoot));
app.get("/*", rateLimiterIndexHtml, middlewareIndexHtml);
const cockpitPort: number = this.options.config.cockpitPort;
const cockpitHost: string = this.options.config.cockpitHost;
if (!this.httpServerCockpit?.listening) {
await new Promise((resolve, reject) => {
this.httpServerCockpit?.once("error", reject);
this.httpServerCockpit?.once("listening", resolve);
this.httpServerCockpit?.listen(cockpitPort, cockpitHost);
});
}
this.httpServerCockpit?.on("request", app);
// the address() method returns a string for unix domain sockets and null
// if the server is not listening but we don't care about any of those cases
// so the casting here should be safe. Famous last words... I know.
const addressInfo = this.httpServerCockpit?.address() as AddressInfo;
this.log.info(`Cactus Cockpit net.AddressInfo`, addressInfo);
return addressInfo;
}
/**
* Installs the own endpoints of the API server such as the ones providing
* healthcheck and monitoring information.
* @param app
*/
async getOrCreateWebServices(app: express.Express): Promise<void> {
const { log } = this;
const { logLevel } = this.options.config;
const pluginRegistry = await this.getOrInitPluginRegistry();
{
const oasPath = OAS.paths["/api/v1/api-server/get-open-api-spec"];
const operationId = oasPath.get.operationId;
const opts: IGetOpenApiSpecV1EndpointOptions = {
oas: OAS,
oasPath,
operationId,
path: oasPath.get["x-hyperledger-cactus"].http.path,
pluginRegistry,
verbLowerCase: oasPath.get["x-hyperledger-cactus"].http.verbLowerCase,
logLevel,
};
const endpoint = new GetOpenApiSpecV1Endpoint(opts);
await registerWebServiceEndpoint(app, endpoint);
}
const healthcheckHandler = (req: Request, res: Response) => {
res.json({
success: true,
createdAt: new Date(),
memoryUsage: process.memoryUsage(),
});
};
const { "/api/v1/api-server/healthcheck": oasPath } = OAS.paths;
const { http } = oasPath.get["x-hyperledger-cactus"];
const { path: httpPath, verbLowerCase: httpVerb } = http;
(app as any)[httpVerb](httpPath, healthcheckHandler);
this.wsApi.on("connection", (socket: SocketIoSocket) => {
const { id } = socket;
const transport = socket.conn.transport.name; // in most cases, "polling"
log.debug(`Socket connected. ID=${id} transport=%o`, transport);
socket.conn.on("upgrade", () => {
const upgradedTransport = socket.conn.transport.name; // in most cases, "websocket"
log.debug(`Socket upgraded ID=${id} transport=%o`, upgradedTransport);
});
socket.on(WatchHealthcheckV1.Subscribe, () =>
new WatchHealthcheckV1Endpoint({
process,
socket,
logLevel,
}).subscribe(),
);
});
const prometheusExporterHandler = (req: Request, res: Response) => {
this.getPrometheusExporterMetrics().then((resBody) => {
res.status(200);
res.send(resBody);
});
};
const {
"/api/v1/api-server/get-prometheus-exporter-metrics": oasPathPrometheus,
} = OAS.paths;
const { http: httpPrometheus } =
oasPathPrometheus.get["x-hyperledger-cactus"];
const { path: httpPathPrometheus, verbLowerCase: httpVerbPrometheus } =
httpPrometheus;
(app as any)[httpVerbPrometheus](
httpPathPrometheus,
prometheusExporterHandler,
);
}
async startGrpcServer(): Promise<AddressInfo> {
return new Promise((resolve, reject) => {
// const grpcHost = "0.0.0.0"; // FIXME - make this configurable (config-service.ts)
const grpcHost = "127.0.0.1"; // FIXME - make this configurable (config-service.ts)
const grpcHostAndPort = `${grpcHost}:${this.options.config.grpcPort}`;
const grpcTlsCredentials = this.options.config.grpcMtlsEnabled
? GrpcServerCredentials.createSsl(
Buffer.from(this.options.config.apiTlsCertPem),
[
{
cert_chain: Buffer.from(this.options.config.apiTlsCertPem),
private_key: Buffer.from(this.options.config.apiTlsKeyPem),
},
],
true,
)
: GrpcServerCredentials.createInsecure();
this.grpcServer.addService(
default_service.org.hyperledger.cactus.cmd_api_server
.DefaultServiceClient.service,
new GrpcServerApiServer(),
);
this.grpcServer.bindAsync(
grpcHostAndPort,
grpcTlsCredentials,
(error: Error | null, port: number) => {
if (error) {
this.log.error("Binding gRPC failed: ", error);
return reject(new RuntimeError("Binding gRPC failed: ", error));
}
this.grpcServer.start();
const family = determineAddressFamily(grpcHost);
resolve({ address: grpcHost, port, family });
},
);
});
}
async startApiServer(): Promise<AddressInfo> {
const { options, expressApi: app, wsApi } = this;
const { config } = options;
const {
authorizationConfigJson: authzConf,
authorizationProtocol: authzProtocol,
logLevel,
} = config;
const apiServerOptions = config;
const pluginRegistry = await this.getOrInitPluginRegistry();
app.use(compression());
const apiCorsDomainCsv = this.options.config.apiCorsDomainCsv;
const allowedDomains = apiCorsDomainCsv.split(",");
const corsMiddleware = this.createCorsMiddleware(allowedDomains);
app.use(corsMiddleware);
app.use(bodyParser.json({ limit: "50mb" }));
const authzFactoryOptions = { apiServerOptions, pluginRegistry, logLevel };
const authzFactory = new AuthorizerFactory(authzFactoryOptions);
await authzFactory.initOnce();
const authorizerO = await authzFactory.createMiddleware(
authzProtocol,
authzConf,
);
if (authorizerO.isPresent()) {
const authorizer = authorizerO.get();
this.checkNonExemptUnprotectedEps(authzFactory);
app.use(authorizer);
this.log.info(`Authorization request handler configured OK.`);
}
this.getOrCreateWebServices(app); // The API server's own endpoints
this.log.info(`Starting to install web services...`);
const webServicesInstalled = pluginRegistry
.getPlugins()
.filter((pluginInstance) => isIPluginWebService(pluginInstance))
.map(async (plugin: ICactusPlugin) => {
const p = plugin as IPluginWebService;
await p.getOrCreateWebServices();
const apiSpec = p.getOpenApiSpec() as OpenAPIV3.Document;
if (apiSpec)
await installOpenapiValidationMiddleware({ app, apiSpec, logLevel });
const webSvcs = await p.registerWebServices(app, wsApi);
return webSvcs;
});
const endpoints2D = await Promise.all(webServicesInstalled);
this.log.info(`Installed ${webServicesInstalled.length} web service(s) OK`);
const endpoints = endpoints2D.reduce((acc, val) => acc.concat(val), []);
endpoints.forEach((ep) => this.log.info(`Endpoint={path=${ep.getPath()}}`));
const apiPort: number = this.options.config.apiPort;
const apiHost: string = this.options.config.apiHost;
if (!this.httpServerApi.listening) {
await new Promise((resolve, reject) => {
this.httpServerApi.once("error", reject);
this.httpServerApi.once("listening", resolve);
this.httpServerApi.listen(apiPort, apiHost);
});
}
this.httpServerApi.on("request", app);
// the address() method returns a string for unix domain sockets and null
// if the server is not listening but we don't care about any of those cases
// so the casting here should be safe. Famous last words... I know.
const addressInfo = this.httpServerApi.address() as AddressInfo;
this.log.info(`Cactus API net.AddressInfo`, addressInfo);
const wsOptions = {
path: Constants.SocketIoConnectionPathV1,
serveClient: false,
...this.options.wsOptions,
} as SocketIoServerOptions;
this.wsApi.attach(this.httpServerApi, wsOptions);
if (authorizerO.isPresent()) {
const socketIoAuthorizer = authorizeSocket({
...authzConf.socketIoJwtOptions,
onAuthentication: (decodedToken) => {
this.log.debug("Socket authorized OK: %o", decodedToken);
},
});
this.wsApi.use(socketIoAuthorizer as never);
}
return addressInfo;
}
private checkNonExemptUnprotectedEps(factory: AuthorizerFactory): void {
const { config } = this.options;
const { authorizationConfigJson } = config;
const { unprotectedEndpointExemptions } = authorizationConfigJson;
const nonExempts = factory.unprotectedEndpoints.filter(
(nse) =>
!unprotectedEndpointExemptions.some((pt) => nse.getPath().match(pt)),
);
if (nonExempts.length > 0) {
const csv = nonExempts.join(", ");
const { E_NON_EXEMPT_UNPROTECTED_ENDPOINTS } = ApiServer;
throw new Error(`${E_NON_EXEMPT_UNPROTECTED_ENDPOINTS} ${csv}`);
}
}
createCorsMiddleware(allowedDomains: string[]): RequestHandler {
const allDomainsOk = allowedDomains.includes("*");
const corsOptionsDelegate: CorsOptionsDelegate<CorsRequest> = (
req,
callback,
) => {
const origin = req.headers["origin"];
const isDomainOk = origin && allowedDomains.includes(origin);
// this.log.debug("CORS %j %j %s", allDomainsOk, isDomainOk, req.originalUrl);
let corsOptions;
if (allDomainsOk) {
corsOptions = { origin: "*" }; // reflect (enable) the all origins in the CORS response
} else if (isDomainOk) {
corsOptions = { origin }; // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false }; // disable CORS for this request
}
callback(null, corsOptions); // callback expects two parameters: error and options
};
return cors(corsOptionsDelegate);
}
}