Merge pull request #3885 from backstage/rugvip/https

backend-common: Fix HTTPS certificate generation, deprecate params, and cache certificates
This commit is contained in:
Patrik Oldsberg
2020-12-30 14:45:48 +01:00
committed by GitHub
5 changed files with 206 additions and 59 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/backend-common': patch
---
Fix HTTPS certificate generation and add new config switch, enabling it simply by setting `backend.https = true`. Also introduces caching of generated certificates in order to avoid having to add a browser override every time the backend is restarted.
+35 -20
View File
@@ -32,26 +32,41 @@ export interface Config {
port?: string | number;
};
/** HTTPS configuration for the backend. If omitted the backend will serve HTTP */
https?: {
/** Certificate configuration or parameters for generating a self-signed certificate */
certificate?:
| {
/** Algorithm to use to generate a self-signed certificate */
algorithm: string;
keySize?: number;
days?: number;
}
| {
/** PEM encoded certificate. Use $file to load in a file */
cert: string;
/**
* PEM encoded certificate key. Use $file to load in a file.
* @visibility secret
*/
key: string;
};
};
/**
* HTTPS configuration for the backend. If omitted the backend will serve HTTP.
*
* Setting this to `true` will cause self-signed certificates to be generated, which
* can be useful for local development or other non-production scenarios.
*/
https?:
| true
| {
/**
* Certificate configuration or parameters for generating a self-signed certificate
*
* Setting parameters for self-signed certificates is deprecated and will be removed in
* the future, set `backend.https = true` instead.
*/
certificate?:
| {
/** Algorithm to use to generate a self-signed certificate */
algorithm?: string;
keySize?: number;
days?: number;
attributes: {
commonName: string;
};
}
| {
/** PEM encoded certificate. Use $file to load in a file */
cert: string;
/**
* PEM encoded certificate key. Use $file to load in a file.
* @visibility secret
*/
key: string;
};
};
/** Database connection configuration, select database type using the `client` field */
database:
@@ -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}`);
@@ -47,14 +47,14 @@ export type CertificateReferenceOptions = {
};
export type CertificateSigningOptions = {
algorithm: string;
algorithm?: string;
size?: number;
days?: number;
attributes?: CertificateAttributes;
attributes: CertificateAttributes;
};
export type CertificateAttributes = {
commonName?: string;
commonName: string;
};
/**
@@ -193,8 +193,26 @@ export function readCspOptions(
* ```
*/
export function readHttpsSettings(config: Config): HttpsSettings | undefined {
const cc = config.getOptionalConfig('https');
const https = config.get('https');
if (https === true) {
const baseUrl = config.getString('baseUrl');
let commonName;
try {
commonName = new URL(baseUrl).hostname;
} catch (error) {
throw new Error(`Invalid backend.baseUrl "${baseUrl}"`);
}
return {
certificate: {
attributes: {
commonName,
},
},
};
}
const cc = config.getOptionalConfig('https');
if (!cc) {
return undefined;
}
@@ -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,48 +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;
if (signingOptions?.algorithm !== undefined) {
logger?.info('Generating self-signed certificate with attributes');
const certificateAttributes: Array<any> = Object.entries(
signingOptions.attributes,
).map(([name, value]) => ({ name, value }));
// TODO: Create a type def for selfsigned.
const signatures = require('selfsigned').generate(certificateAttributes, {
algorithm: signingOptions?.algorithm,
keySize: signingOptions?.size || 2048,
days: signingOptions?.days || 30,
});
logger?.info('Bootstrapping self-signed certificate');
credentials.key = signatures.private;
credentials.cert = signatures.cert;
// TODO(Rugvip): remove support for generated certificate params and make this a more straightforward check
if (signingOptions?.attributes) {
credentials = await getGeneratedCertificate(signingOptions, logger);
} else {
logger?.info('Bootstrapping cert from config');
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 });
}
},
),
);
}