backend-common: cache generated HTTPS certificates

This commit is contained in:
Patrik Oldsberg
2020-12-30 12:46:58 +01:00
parent 751f58ff7c
commit 9db9bc878f
2 changed files with 142 additions and 85 deletions
@@ -145,7 +145,7 @@ export class ServiceBuilderImpl implements ServiceBuilder {
return this;
}
start(): Promise<http.Server> {
async start(): Promise<http.Server> {
const app = express();
const {
port,
@@ -168,16 +168,16 @@ export class ServiceBuilderImpl implements ServiceBuilder {
app.use(notFoundHandler());
app.use(errorHandler());
const server: http.Server = httpsSettings
? await createHttpsServer(app, httpsSettings, logger)
: createHttpServer(app, logger);
return new Promise((resolve, reject) => {
app.on('error', e => {
logger.error(`Failed to start up on port ${port}, ${e}`);
reject(e);
});
const server: http.Server = httpsSettings
? createHttpsServer(app, httpsSettings, logger)
: createHttpServer(app, logger);
const stoppableServer = stoppable(
server.listen(port, host, () => {
logger.info(`Listening on ${host}:${port}`);
@@ -13,11 +13,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from 'fs-extra';
import { resolve as resolvePath, dirname } from 'path';
import express from 'express';
import * as http from 'http';
import * as https from 'https';
import { Logger } from 'winston';
import { HttpsSettings } from './config';
import { CertificateSigningOptions, HttpsSettings } from './config';
const ALMOST_MONTH_IN_MS = 25 * 24 * 60 * 60 * 1000;
/**
* Creates a Http server instance based on an Express application.
@@ -45,100 +50,152 @@ export function createHttpServer(
* @returns A Https server instance
*
*/
export function createHttpsServer(
export async function createHttpsServer(
app: express.Express,
httpsSettings: HttpsSettings,
logger?: Logger,
): http.Server {
): Promise<http.Server> {
logger?.info('Initializing https server');
const credentials: { key: string; cert: string } = {
key: '',
cert: '',
};
let credentials: { key: string | Buffer; cert: string | Buffer };
const signingOptions: any = httpsSettings?.certificate;
// TODO(Rugvip): remove support for generated certificate params and make this a more straightforward check
if (signingOptions?.attributes) {
logger?.info('Generating self-signed certificate with attributes');
if (signingOptions?.algorithm) {
logger?.warn(
'Certificate generation configuration with parameters in backend.https.certificate is deprecated, set backend.https = true instead',
);
}
const certificateAttributes: Array<any> = Object.entries(
signingOptions.attributes,
).map(([name, value]) => ({ name, value }));
const signatures = require('selfsigned').generate(certificateAttributes, {
algorithm: signingOptions?.algorithm || 'sha256',
keySize: signingOptions?.size || 2048,
days: signingOptions?.days || 30,
extensions: [
{
name: 'keyUsage',
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true,
},
{
name: 'extKeyUsage',
serverAuth: true,
clientAuth: true,
codeSigning: true,
timeStamping: true,
},
{
name: 'subjectAltName',
altNames: [
{
type: 2, // DNS
value: 'localhost',
},
{
type: 2,
value: 'localhost.localdomain',
},
{
type: 2,
value: '[::1]',
},
{
type: 7, // IP
ip: '127.0.0.1',
},
{
type: 7,
ip: 'fe80::1',
},
...(signingOptions.attributes.commonName
? [
{
type: 2, // DNS
value: signingOptions.attributes.commonName,
},
]
: []),
],
},
],
});
credentials.key = signatures.private;
credentials.cert = signatures.cert;
credentials = await getGeneratedCertificate(signingOptions, logger);
} else {
logger?.info('Loading certificate from config');
credentials.key = signingOptions?.key;
credentials.cert = signingOptions?.cert;
credentials = {
key: signingOptions?.key,
cert: signingOptions?.cert,
};
}
if (credentials.key === '' || credentials.cert === '') {
throw new Error('Invalid credentials');
if (!credentials.key || !credentials.cert) {
throw new Error('Invalid HTTPS credentials');
}
return https.createServer(credentials, app) as http.Server;
}
async function getGeneratedCertificate(
options: CertificateSigningOptions,
logger?: Logger,
) {
if (options?.algorithm) {
logger?.warn(
'Certificate generation configuration with parameters in backend.https.certificate is deprecated, set backend.https = true instead',
);
}
const hasModules = await fs.pathExists('node_modules');
let certPath;
if (hasModules) {
certPath = resolvePath(
'node_modules/.cache/backstage-backend/dev-cert.pem',
);
await fs.ensureDir(dirname(certPath));
} else {
certPath = resolvePath('.dev-cert.pem');
}
let cert = undefined;
if (await fs.pathExists(certPath)) {
const stat = await fs.stat(certPath);
const ageMs = Date.now() - stat.ctimeMs;
if (stat.isFile() && ageMs < ALMOST_MONTH_IN_MS) {
cert = await fs.readFile(certPath);
}
}
if (cert) {
logger?.info('Using existing self-signed certificate');
return {
key: cert,
cert: cert,
};
}
logger?.info('Generating new self-signed certificate');
const newCert = await createCertificate(options);
await fs.writeFile(certPath, newCert.cert + newCert.key, 'utf8');
return newCert;
}
async function createCertificate(options: CertificateSigningOptions) {
const attributes: Array<any> = Object.entries(
options.attributes,
).map(([name, value]) => ({ name, value }));
const params = {
algorithm: options?.algorithm || 'sha256',
keySize: options?.size || 2048,
days: options?.days || 30,
extensions: [
{
name: 'keyUsage',
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true,
},
{
name: 'extKeyUsage',
serverAuth: true,
clientAuth: true,
codeSigning: true,
timeStamping: true,
},
{
name: 'subjectAltName',
altNames: [
{
type: 2, // DNS
value: 'localhost',
},
{
type: 2,
value: 'localhost.localdomain',
},
{
type: 2,
value: '[::1]',
},
{
type: 7, // IP
ip: '127.0.0.1',
},
{
type: 7,
ip: 'fe80::1',
},
...(options.attributes.commonName
? [
{
type: 2, // DNS
value: options.attributes.commonName,
},
]
: []),
],
},
],
};
return new Promise<{ key: string; cert: string }>((resolve, reject) =>
require('selfsigned').generate(
attributes,
params,
(err: Error, bundle: { private: string; cert: string }) => {
if (err) {
reject(err);
} else {
resolve({ key: bundle.private, cert: bundle.cert });
}
},
),
);
}