UNPKG

2.82 kBPlain TextView Raw
1/*
2 * Copyright 2019 gRPC authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18import { SecureServerOptions } from 'http2';
19import { CIPHER_SUITES, getDefaultRootsData } from './tls-helpers';
20
21export interface KeyCertPair {
22 private_key: Buffer;
23 cert_chain: Buffer;
24}
25
26export abstract class ServerCredentials {
27 abstract _isSecure(): boolean;
28 abstract _getSettings(): SecureServerOptions | null;
29
30 static createInsecure(): ServerCredentials {
31 return new InsecureServerCredentials();
32 }
33
34 static createSsl(
35 rootCerts: Buffer | null,
36 keyCertPairs: KeyCertPair[],
37 checkClientCertificate = false
38 ): ServerCredentials {
39 if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) {
40 throw new TypeError('rootCerts must be null or a Buffer');
41 }
42
43 if (!Array.isArray(keyCertPairs)) {
44 throw new TypeError('keyCertPairs must be an array');
45 }
46
47 if (typeof checkClientCertificate !== 'boolean') {
48 throw new TypeError('checkClientCertificate must be a boolean');
49 }
50
51 const cert = [];
52 const key = [];
53
54 for (let i = 0; i < keyCertPairs.length; i++) {
55 const pair = keyCertPairs[i];
56
57 if (pair === null || typeof pair !== 'object') {
58 throw new TypeError(`keyCertPair[${i}] must be an object`);
59 }
60
61 if (!Buffer.isBuffer(pair.private_key)) {
62 throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`);
63 }
64
65 if (!Buffer.isBuffer(pair.cert_chain)) {
66 throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`);
67 }
68
69 cert.push(pair.cert_chain);
70 key.push(pair.private_key);
71 }
72
73 return new SecureServerCredentials({
74 ca: rootCerts || getDefaultRootsData() || undefined,
75 cert,
76 key,
77 requestCert: checkClientCertificate,
78 ciphers: CIPHER_SUITES,
79 });
80 }
81}
82
83class InsecureServerCredentials extends ServerCredentials {
84 _isSecure(): boolean {
85 return false;
86 }
87
88 _getSettings(): null {
89 return null;
90 }
91}
92
93class SecureServerCredentials extends ServerCredentials {
94 private options: SecureServerOptions;
95
96 constructor(options: SecureServerOptions) {
97 super();
98 this.options = options;
99 }
100
101 _isSecure(): boolean {
102 return true;
103 }
104
105 _getSettings(): SecureServerOptions {
106 return this.options;
107 }
108}