diff --git a/.changeset/cyan-lizards-confess.md b/.changeset/cyan-lizards-confess.md new file mode 100644 index 0000000000..17ff8f0cdf --- /dev/null +++ b/.changeset/cyan-lizards-confess.md @@ -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. diff --git a/packages/backend-common/config.d.ts b/packages/backend-common/config.d.ts index 3e21235c63..b7241bcc03 100644 --- a/packages/backend-common/config.d.ts +++ b/packages/backend-common/config.d.ts @@ -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: diff --git a/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts b/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts index 46bf23beef..9c5ac20fa3 100644 --- a/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts +++ b/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts @@ -145,7 +145,7 @@ export class ServiceBuilderImpl implements ServiceBuilder { return this; } - start(): Promise { + async start(): Promise { 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}`); diff --git a/packages/backend-common/src/service/lib/config.ts b/packages/backend-common/src/service/lib/config.ts index ea1a2b0887..6abea97454 100644 --- a/packages/backend-common/src/service/lib/config.ts +++ b/packages/backend-common/src/service/lib/config.ts @@ -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; } diff --git a/packages/backend-common/src/service/lib/hostFactory.ts b/packages/backend-common/src/service/lib/hostFactory.ts index 8fab2fd4ab..656f160c31 100644 --- a/packages/backend-common/src/service/lib/hostFactory.ts +++ b/packages/backend-common/src/service/lib/hostFactory.ts @@ -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 { 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 = 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 = 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 }); + } + }, + ), + ); +}