fix various terminology in code

subdomain, domain - strings
location - { subdomain, domain }
bundle - { cert, key }
bundlePath - { certFilePath, keyFilePath }

vhost is really just for virtual hosting
fqdn for others
This commit is contained in:
Girish Ramakrishnan
2022-07-13 09:26:27 +05:30
parent 5d16aca8f4
commit 1549f6a4d0
5 changed files with 102 additions and 106 deletions
+81 -85
View File
@@ -13,14 +13,14 @@ exports = module.exports = {
checkCerts,
// the 'configure' ensure a certificate and generate nginx config
// the 'configure' functions ensure a certificate and generate nginx config
configureApp,
unconfigureApp,
// these only generate nginx config
writeDefaultConfig,
writeDashboardConfig,
writeAppConfig,
writeAppConfigs,
removeAppConfigs,
restoreFallbackCertificates,
@@ -59,17 +59,14 @@ const RESTART_SERVICE_CMD = path.join(__dirname, 'scripts/restartservice.sh');
function nginxLocation(s) {
if (!s.startsWith('!')) return s;
let re = s.replace(/[\^$\\.*+?()[\]{}|]/g, '\\$&'); // https://github.com/es-shims/regexp.escape/blob/master/implementation.js
const re = s.replace(/[\^$\\.*+?()[\]{}|]/g, '\\$&'); // https://github.com/es-shims/regexp.escape/blob/master/implementation.js
return `~ ^(?!(${re.slice(1)}))`; // negative regex assertion - https://stackoverflow.com/questions/16302897/nginx-location-not-equal-to-regex
}
async function getAcmeApi(domainObject) {
assert.strictEqual(typeof domainObject, 'object');
const acmeApi = acme2;
let apiOptions = { prod: false, performHttpAuthorization: false, wildcard: false, email: '' };
const apiOptions = { prod: false, performHttpAuthorization: false, wildcard: false, email: '' };
apiOptions.prod = domainObject.tlsConfig.provider.match(/.*-prod/) !== null; // matches 'le-prod' or 'letsencrypt-prod'
apiOptions.performHttpAuthorization = domainObject.provider.match(/noop|manual|wildcard/) !== null;
apiOptions.wildcard = !!domainObject.tlsConfig.wildcard;
@@ -81,7 +78,7 @@ async function getAcmeApi(domainObject) {
const [error, owner] = await safe(users.getOwner());
apiOptions.email = (error || !owner) ? 'webmaster@cloudron.io' : owner.email; // can error if not activated yet
return { acmeApi, apiOptions };
return { acme2, apiOptions };
}
function getExpiryDate(certFilePath) {
@@ -144,19 +141,19 @@ function providerMatchesSync(domainObject, certFilePath, apiOptions) {
// note: https://tools.ietf.org/html/rfc4346#section-7.4.2 (certificate_list) requires that the
// servers certificate appears first (and not the intermediate cert)
function validateCertificate(location, domainObject, certificate) {
assert.strictEqual(typeof location, 'string');
function validateCertificate(subdomain, domainObject, bundle) {
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof domainObject, 'object');
assert(certificate && typeof certificate, 'object');
assert(bundle && typeof bundle, 'object');
const cert = certificate.cert, key = certificate.key;
const { cert, key } = bundle;
// check for empty cert and key strings
if (!cert && key) return new BoxError(BoxError.BAD_FIELD, 'missing cert');
if (cert && !key) return new BoxError(BoxError.BAD_FIELD, 'missing key');
// -checkhost checks for SAN or CN exclusively. SAN takes precedence and if present, ignores the CN.
const fqdn = dns.fqdn(location, domainObject);
const fqdn = dns.fqdn(subdomain, domainObject);
let result = safe.child_process.execSync(`openssl x509 -noout -checkhost "${fqdn}"`, { encoding: 'utf8', input: cert });
if (result === null) return new BoxError(BoxError.BAD_FIELD, 'Unable to get certificate subject:' + safe.error.message);
@@ -198,7 +195,7 @@ async function generateFallbackCertificate(domain) {
let opensslConfWithSan;
const cn = domain;
debug(`generateFallbackCertificateSync: domain=${domain} cn=${cn}`);
debug(`generateFallbackCertificate: domain=${domain} cn=${cn}`);
opensslConfWithSan = `${opensslConf}\n[SAN]\nsubjectAltName=DNS:${domain},DNS:*.${cn}\n`;
const configFile = path.join(os.tmpdir(), 'openssl-' + crypto.randomBytes(4).readUInt32LE(0) + '.conf');
@@ -219,14 +216,13 @@ async function generateFallbackCertificate(domain) {
return { cert, key };
}
async function setFallbackCertificate(domain, fallback) {
async function setFallbackCertificate(domain, bundle) {
assert.strictEqual(typeof domain, 'string');
assert(fallback && typeof fallback === 'object');
assert.strictEqual(typeof fallback, 'object');
assert(bundle && typeof bundle === 'object');
debug(`setFallbackCertificate: setting certs for domain ${domain}`);
if (!safe.fs.writeFileSync(path.join(paths.NGINX_CERT_DIR, `${domain}.host.cert`), fallback.cert)) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
if (!safe.fs.writeFileSync(path.join(paths.NGINX_CERT_DIR, `${domain}.host.key`), fallback.key)) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
if (!safe.fs.writeFileSync(path.join(paths.NGINX_CERT_DIR, `${domain}.host.cert`), bundle.cert)) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
if (!safe.fs.writeFileSync(path.join(paths.NGINX_CERT_DIR, `${domain}.host.key`), bundle.key)) throw new BoxError(BoxError.FS_ERROR, safe.error.message);
// TODO: maybe the cert is being used by the mail container
await reload();
@@ -250,47 +246,47 @@ function getFallbackCertificatePathSync(domain) {
return { certFilePath, keyFilePath };
}
function getAppCertificatePathSync(vhost) {
assert.strictEqual(typeof vhost, 'string');
function getAppCertificatePathSync(fqdn) {
assert.strictEqual(typeof fqdn, 'string');
const certFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.user.cert`);
const keyFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.user.key`);
const certFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.user.cert`);
const keyFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.user.key`);
return { certFilePath, keyFilePath };
}
function getAcmeCertificatePathSync(vhost, domainObject) {
assert.strictEqual(typeof vhost, 'string'); // this can contain wildcard domain (for alias domains)
function getAcmeCertificatePathSync(fqdn, domainObject) {
assert.strictEqual(typeof fqdn, 'string'); // this can contain wildcard domain (for alias domains)
assert.strictEqual(typeof domainObject, 'object');
let certName, certFilePath, keyFilePath, csrFilePath, acmeChallengesDir = paths.ACME_CHALLENGES_DIR;
if (vhost !== domainObject.domain && domainObject.tlsConfig.wildcard) { // bare domain is not part of wildcard SAN
certName = dns.makeWildcard(vhost).replace('*.', '_.');
if (fqdn !== domainObject.domain && domainObject.tlsConfig.wildcard) { // bare domain is not part of wildcard SAN
certName = dns.makeWildcard(fqdn).replace('*.', '_.');
certFilePath = path.join(paths.NGINX_CERT_DIR, `${certName}.cert`);
keyFilePath = path.join(paths.NGINX_CERT_DIR, `${certName}.key`);
csrFilePath = path.join(paths.NGINX_CERT_DIR, `${certName}.csr`);
} else {
certName = vhost;
certFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.cert`);
keyFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.key`);
csrFilePath = path.join(paths.NGINX_CERT_DIR, `${vhost}.csr`);
certName = fqdn;
certFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.cert`);
keyFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.key`);
csrFilePath = path.join(paths.NGINX_CERT_DIR, `${fqdn}.csr`);
}
return { certName, certFilePath, keyFilePath, csrFilePath, acmeChallengesDir };
}
async function setAppCertificate(location, domainObject, certificate) {
assert.strictEqual(typeof location, 'string');
async function setAppCertificate(subdomain, domainObject, bundle) {
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof domainObject, 'object');
assert.strictEqual(typeof certificate, 'object');
assert(bundle && typeof bundle === 'object');
const fqdn = dns.fqdn(location, domainObject);
const fqdn = dns.fqdn(subdomain, domainObject);
const { certFilePath, keyFilePath } = getAppCertificatePathSync(fqdn);
if (certificate.cert && certificate.key) {
if (!safe.fs.writeFileSync(certFilePath, certificate.cert)) throw safe.error;
if (!safe.fs.writeFileSync(keyFilePath, certificate.key)) throw safe.error;
if (bundle.cert && bundle.key) {
if (!safe.fs.writeFileSync(certFilePath, bundle.cert)) throw safe.error;
if (!safe.fs.writeFileSync(keyFilePath, bundle.key)) throw safe.error;
} else { // remove existing cert/key
if (!safe.fs.unlinkSync(certFilePath)) debug(`Error removing cert: ${safe.error.message}`);
if (!safe.fs.unlinkSync(keyFilePath)) debug(`Error removing key: ${safe.error.message}`);
@@ -309,38 +305,38 @@ async function getCertificatePath(fqdn, domain) {
const domainObject = await domains.get(domain);
const appCertPath = getAppCertificatePathSync(fqdn); // user cert always wins
if (fs.existsSync(appCertPath.certFilePath) && fs.existsSync(appCertPath.keyFilePath)) return appCertPath;
const bundlePath = getAppCertificatePathSync(fqdn); // user cert always wins
if (fs.existsSync(bundlePath.certFilePath) && fs.existsSync(bundlePath.keyFilePath)) return bundlePath;
if (domainObject.tlsConfig.provider === 'fallback') return getFallbackCertificatePathSync(domain);
const acmeCertPath = getAcmeCertificatePathSync(fqdn, domainObject);
if (fs.existsSync(acmeCertPath.certFilePath) && fs.existsSync(acmeCertPath.keyFilePath)) return acmeCertPath;
const acmeBundlePath = getAcmeCertificatePathSync(fqdn, domainObject);
if (fs.existsSync(acmeBundlePath.certFilePath) && fs.existsSync(acmeBundlePath.keyFilePath)) return acmeBundlePath;
return getFallbackCertificatePathSync(domain);
}
async function checkAppCertificate(vhost, domainObject) {
assert.strictEqual(typeof vhost, 'string'); // this can contain wildcard domain (for alias domains)
async function checkAppCertificate(fqdn, domainObject) {
assert.strictEqual(typeof fqdn, 'string'); // this can contain wildcard domain (for alias domains)
assert.strictEqual(typeof domainObject, 'object');
const subdomain = vhost.substr(0, vhost.length - domainObject.domain.length - 1);
const certificate = await apps.getCertificate(subdomain, domainObject.domain);
if (!certificate) return null;
const subdomain = fqdn.substr(0, fqdn.length - domainObject.domain.length - 1);
const bundle = await apps.getCertificate(subdomain, domainObject.domain);
if (!bundle) return null;
const { certFilePath, keyFilePath } = getAppCertificatePathSync(vhost);
const { certFilePath, keyFilePath } = getAppCertificatePathSync(fqdn);
if (!safe.fs.writeFileSync(certFilePath, certificate.cert)) throw new BoxError(BoxError.FS_ERROR, `Failed to write certificate: ${safe.error.message}`);
if (!safe.fs.writeFileSync(keyFilePath, certificate.key)) throw new BoxError(BoxError.FS_ERROR, `Failed to write key: ${safe.error.message}`);
if (!safe.fs.writeFileSync(certFilePath, bundle.cert)) throw new BoxError(BoxError.FS_ERROR, `Failed to write certificate: ${safe.error.message}`);
if (!safe.fs.writeFileSync(keyFilePath, bundle.key)) throw new BoxError(BoxError.FS_ERROR, `Failed to write key: ${safe.error.message}`);
return { certFilePath, keyFilePath };
}
async function checkAcmeCertificate(vhost, domainObject) {
assert.strictEqual(typeof vhost, 'string'); // this can contain wildcard domain (for alias domains)
async function checkAcmeCertificate(fqdn, domainObject) {
assert.strictEqual(typeof fqdn, 'string'); // this can contain wildcard domain (for alias domains)
assert.strictEqual(typeof domainObject, 'object');
const { certName, certFilePath, keyFilePath, csrFilePath } = getAcmeCertificatePathSync(vhost, domainObject);
const { certName, certFilePath, keyFilePath, csrFilePath } = getAcmeCertificatePathSync(fqdn, domainObject);
const privateKey = await blobs.get(`${blobs.CERT_PREFIX}-${certName}.key`);
const cert = await blobs.get(`${blobs.CERT_PREFIX}-${certName}.cert`);
@@ -356,11 +352,11 @@ async function checkAcmeCertificate(vhost, domainObject) {
return { certFilePath, keyFilePath };
}
async function updateCertBlobs(vhost, domainObject) {
assert.strictEqual(typeof vhost, 'string'); // this can contain wildcard domain (for alias domains)
async function updateCertBlobs(fqdn, domainObject) {
assert.strictEqual(typeof fqdn, 'string'); // this can contain wildcard domain (for alias domains)
assert.strictEqual(typeof domainObject, 'object');
const { certName, certFilePath, keyFilePath, csrFilePath } = getAcmeCertificatePathSync(vhost, domainObject);
const { certName, certFilePath, keyFilePath, csrFilePath } = getAcmeCertificatePathSync(fqdn, domainObject);
const privateKey = safe.fs.readFileSync(keyFilePath);
if (!privateKey) throw new BoxError(BoxError.FS_ERROR, `Failed to read private key: ${safe.error.message}`);
@@ -376,18 +372,18 @@ async function updateCertBlobs(vhost, domainObject) {
await blobs.set(`${blobs.CERT_PREFIX}-${certName}.csr`, csr);
}
async function ensureCertificate(vhost, domain, auditSource) {
assert.strictEqual(typeof vhost, 'string');
async function ensureCertificate(subdomain, domain, auditSource) {
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof domain, 'string');
assert.strictEqual(typeof auditSource, 'object');
const domainObject = await domains.get(domain);
let bundle = await checkAppCertificate(vhost, domainObject);
const bundle = await checkAppCertificate(subdomain, domainObject);
if (bundle) return { bundle, renewed: false };
if (domainObject.tlsConfig.provider === 'fallback') {
debug(`ensureCertificate: ${vhost} will use fallback certs`);
debug(`ensureCertificate: ${subdomain} will use fallback certs`);
return { bundle: getFallbackCertificatePathSync(domain), renewed: false };
}
@@ -395,24 +391,24 @@ async function ensureCertificate(vhost, domain, auditSource) {
const { acmeApi, apiOptions } = await getAcmeApi(domainObject);
let notAfter = null;
const [, currentBundle] = await safe(checkAcmeCertificate(vhost, domainObject));
const [, currentBundle] = await safe(checkAcmeCertificate(subdomain, domainObject));
if (currentBundle) {
debug(`ensureCertificate: ${vhost} certificate already exists at ${currentBundle.keyFilePath}`);
debug(`ensureCertificate: ${subdomain} certificate already exists at ${currentBundle.keyFilePath}`);
notAfter = getExpiryDate(currentBundle.certFilePath);
const isExpiring = (notAfter - new Date()) <= (30 * 24 * 60 * 60 * 1000); // expiring in a month
if (!isExpiring && providerMatchesSync(domainObject, currentBundle.certFilePath, apiOptions)) return { bundle: currentBundle, renewed: false };
debug(`ensureCertificate: ${vhost} cert requires renewal`);
debug(`ensureCertificate: ${subdomain} cert requires renewal`);
} else {
debug(`ensureCertificate: ${vhost} cert does not exist`);
debug(`ensureCertificate: ${subdomain} cert does not exist`);
}
debug('ensureCertificate: getting certificate for %s with options %j', vhost, apiOptions);
debug('ensureCertificate: getting certificate for %s with options %j', subdomain, apiOptions);
const acmePaths = getAcmeCertificatePathSync(vhost, domainObject);
let [error] = await safe(acmeApi.getCertificate(vhost, domain, acmePaths, apiOptions));
const acmePaths = getAcmeCertificatePathSync(subdomain, domainObject);
let [error] = await safe(acmeApi.getCertificate(subdomain, domain, acmePaths, apiOptions));
debug(`ensureCertificate: error: ${error ? error.message : 'null'} cert: ${acmePaths.certFilePath || 'null'}`);
await safe(eventlog.add(currentBundle ? eventlog.ACTION_CERTIFICATE_RENEWAL : eventlog.ACTION_CERTIFICATE_NEW, auditSource, { domain: vhost, errorMessage: error ? error.message : '', notAfter }));
await safe(eventlog.add(currentBundle ? eventlog.ACTION_CERTIFICATE_RENEWAL : eventlog.ACTION_CERTIFICATE_NEW, auditSource, { domain: subdomain, errorMessage: error ? error.message : '', notAfter }));
if (error && currentBundle && (notAfter - new Date() > 0)) { // still some life left in this certificate
debug('ensureCertificate: continue using existing bundle since renewal failed');
@@ -420,32 +416,32 @@ async function ensureCertificate(vhost, domain, auditSource) {
}
if (!error) {
[error] = await safe(updateCertBlobs(vhost, domainObject));
[error] = await safe(updateCertBlobs(subdomain, domainObject));
if (!error) return { bundle: { certFilePath: acmePaths.certFilePath, keyFilePath: acmePaths.keyFilePath }, renewed: true };
}
debug(`ensureCertificate: renewal of ${vhost} failed. using fallback certificates for ${domain}`);
debug(`ensureCertificate: renewal of ${subdomain} failed. using fallback certificates for ${domain}`);
return { bundle: getFallbackCertificatePathSync(domain), renewed: false };
}
async function writeDashboardNginxConfig(vhost, bundle) {
assert.strictEqual(typeof vhost, 'string');
assert.strictEqual(typeof bundle, 'object');
async function writeDashboardNginxConfig(fqdn, bundlePath) {
assert.strictEqual(typeof fqdn, 'string');
assert.strictEqual(typeof bundlePath, 'object');
const data = {
sourceDir: path.resolve(__dirname, '..'),
vhost: vhost,
vhost: fqdn,
hasIPv6: sysinfo.hasIPv6(),
endpoint: 'dashboard',
certFilePath: bundle.certFilePath,
keyFilePath: bundle.keyFilePath,
certFilePath: bundlePath.certFilePath,
keyFilePath: bundlePath.keyFilePath,
robotsTxtQuoted: JSON.stringify('User-agent: *\nDisallow: /\n'),
proxyAuth: { enabled: false, id: null, location: nginxLocation('/') },
ocsp: await isOcspEnabled(bundle.certFilePath)
ocsp: await isOcspEnabled(bundlePath.certFilePath)
};
const nginxConf = ejs.render(NGINX_APPCONFIG_EJS, data);
const nginxConfigFilename = path.join(paths.NGINX_APPCONFIG_DIR, `${vhost}.conf`);
const nginxConfigFilename = path.join(paths.NGINX_APPCONFIG_DIR, `${fqdn}.conf`);
if (!safe.fs.writeFileSync(nginxConfigFilename, nginxConf)) throw new BoxError(BoxError.FS_ERROR, safe.error);
@@ -481,11 +477,11 @@ function getNginxConfigFilename(app, fqdn, type) {
return path.join(paths.NGINX_APPCONFIG_DIR, `${app.id}${nginxConfigFilenameSuffix}.conf`);
}
async function writeAppNginxConfig(app, fqdn, type, bundle) {
async function writeAppNginxConfig(app, fqdn, type, bundlePath) {
assert.strictEqual(typeof app, 'object');
assert.strictEqual(typeof fqdn, 'string');
assert.strictEqual(typeof type, 'string');
assert.strictEqual(typeof bundle, 'object');
assert.strictEqual(typeof bundlePath, 'object');
const data = {
sourceDir: path.resolve(__dirname, '..'),
@@ -495,14 +491,14 @@ async function writeAppNginxConfig(app, fqdn, type, bundle) {
port: null,
endpoint: null,
redirectTo: null,
certFilePath: bundle.certFilePath,
keyFilePath: bundle.keyFilePath,
certFilePath: bundlePath.certFilePath,
keyFilePath: bundlePath.keyFilePath,
robotsTxtQuoted: null,
cspQuoted: null,
hideHeaders: [],
proxyAuth: { enabled: false },
upstreamUri: '', // only for endpoint === external
ocsp: await isOcspEnabled(bundle.certFilePath)
ocsp: await isOcspEnabled(bundlePath.certFilePath)
};
if (type === apps.LOCATION_TYPE_PRIMARY || type === apps.LOCATION_TYPE_ALIAS || type === apps.LOCATION_TYPE_SECONDARY) {
@@ -555,7 +551,7 @@ async function writeAppNginxConfig(app, fqdn, type, bundle) {
await reload();
}
async function writeAppConfig(app) {
async function writeAppConfigs(app) {
assert.strictEqual(typeof app, 'object');
const appDomains = [{ domain: app.domain, fqdn: app.fqdn, type: apps.LOCATION_TYPE_PRIMARY }]
@@ -582,7 +578,7 @@ async function configureApp(app, auditSource) {
await ensureCertificate(appDomain.fqdn, appDomain.domain, auditSource);
}
await writeAppConfig(app);
await writeAppConfigs(app);
}
async function unconfigureApp(app) {