cert-sync-script.test.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. import assert from 'node:assert/strict';
  2. import {
  3. chmodSync,
  4. mkdirSync,
  5. mkdtempSync,
  6. readFileSync,
  7. readdirSync,
  8. rmSync,
  9. statSync,
  10. writeFileSync
  11. } from 'node:fs';
  12. import os from 'node:os';
  13. import path from 'node:path';
  14. import { fileURLToPath } from 'node:url';
  15. import { spawnSync } from 'node:child_process';
  16. import { test } from 'node:test';
  17. const scriptPath = fileURLToPath(new URL('../scripts/sync-tls-certificate.sh', import.meta.url));
  18. const scriptSource = readFileSync(scriptPath, 'utf8');
  19. const opensslLookup = process.platform === 'win32'
  20. ? { status: 1, stdout: '' }
  21. : spawnSync('sh', ['-c', 'command -v openssl'], { encoding: 'utf8' });
  22. const opensslPath = opensslLookup.status === 0 ? opensslLookup.stdout.trim() : '';
  23. const canRun = process.platform !== 'win32' && Boolean(opensslPath);
  24. test('uses protocol-specific STARTTLS probes for explicit TLS upgrade ports', () => {
  25. assert.match(scriptSource, /25\|587\|2525\) protocol_args=\(-starttls smtp\)/);
  26. assert.match(scriptSource, /110\).*protocol_args=\(-starttls pop3\)/);
  27. assert.match(scriptSource, /143\).*protocol_args=\(-starttls imap\)/);
  28. });
  29. test('atomically synchronizes a valid wildcard certificate and preserves safe permissions', { skip: !canRun }, (t) => {
  30. const fixture = createFixture(t);
  31. generateCertificate(fixture.sourceDir, 'example.test');
  32. const first = runSync(fixture);
  33. assert.equal(first.status, 0, first.stderr);
  34. assert.match(first.stdout, /MailHub TLS certificate synchronized for mail\.example\.test\./);
  35. assert.deepEqual(readFileSync(fixture.targetCert), readFileSync(fixture.sourceCert));
  36. assert.deepEqual(readFileSync(fixture.targetKey), readFileSync(fixture.sourceKey));
  37. assert.equal(fileMode(fixture.targetCert), 0o644);
  38. assert.equal(fileMode(fixture.targetKey), 0o640);
  39. assert.deepEqual(stagingFiles(fixture.certsDir), []);
  40. const previousCert = readFileSync(fixture.targetCert);
  41. const previousKey = readFileSync(fixture.targetKey);
  42. chmodSync(fixture.targetCert, 0o640);
  43. chmodSync(fixture.targetKey, 0o600);
  44. generateCertificate(fixture.sourceDir, 'example.test');
  45. const replacement = runSync(fixture);
  46. assert.equal(replacement.status, 0, replacement.stderr);
  47. assert.deepEqual(readFileSync(`${fixture.targetCert}.previous`), previousCert);
  48. assert.deepEqual(readFileSync(`${fixture.targetKey}.previous`), previousKey);
  49. assert.deepEqual(readFileSync(fixture.targetCert), readFileSync(fixture.sourceCert));
  50. assert.deepEqual(readFileSync(fixture.targetKey), readFileSync(fixture.sourceKey));
  51. assert.equal(fileMode(fixture.targetCert), 0o644);
  52. assert.equal(fileMode(fixture.targetKey), 0o640);
  53. assert.deepEqual(stagingFiles(fixture.certsDir), []);
  54. });
  55. test('is idempotent when the synchronized certificate is already current', { skip: !canRun }, (t) => {
  56. const fixture = createFixture(t);
  57. generateCertificate(fixture.sourceDir, 'example.test');
  58. const first = runSync(fixture);
  59. assert.equal(first.status, 0, first.stderr);
  60. const certBefore = statSnapshot(fixture.targetCert);
  61. const keyBefore = statSnapshot(fixture.targetKey);
  62. const second = runSync(fixture);
  63. assert.equal(second.status, 0, second.stderr);
  64. assert.match(second.stdout, /MailHub TLS certificate is already up to date\./);
  65. assert.deepEqual(statSnapshot(fixture.targetCert), certBefore);
  66. assert.deepEqual(statSnapshot(fixture.targetKey), keyBefore);
  67. assert.equal(readdirSync(fixture.certsDir).some((name) => name.endsWith('.previous')), false);
  68. assert.deepEqual(stagingFiles(fixture.certsDir), []);
  69. });
  70. test('rejects a certificate that does not cover MAIL_HOSTNAME without touching the targets', { skip: !canRun }, (t) => {
  71. const fixture = createFixture(t);
  72. generateCertificate(fixture.sourceDir, 'other.test');
  73. mkdirSync(fixture.certsDir, { recursive: true });
  74. writeFileSync(fixture.targetCert, 'existing certificate\n');
  75. writeFileSync(fixture.targetKey, 'existing private key\n');
  76. chmodSync(fixture.targetCert, 0o640);
  77. chmodSync(fixture.targetKey, 0o600);
  78. const certBefore = readFileSync(fixture.targetCert);
  79. const keyBefore = readFileSync(fixture.targetKey);
  80. const result = runSync(fixture);
  81. assert.notEqual(result.status, 0);
  82. assert.match(result.stderr, /source certificate does not cover mail\.example\.test\./);
  83. assert.deepEqual(readFileSync(fixture.targetCert), certBefore);
  84. assert.deepEqual(readFileSync(fixture.targetKey), keyBefore);
  85. assert.equal(fileMode(fixture.targetCert), 0o640);
  86. assert.equal(fileMode(fixture.targetKey), 0o600);
  87. assert.equal(readdirSync(fixture.certsDir).some((name) => name.endsWith('.previous')), false);
  88. assert.deepEqual(stagingFiles(fixture.certsDir), []);
  89. });
  90. test('rejects certificate and private key paths that resolve to the same target', { skip: !canRun }, (t) => {
  91. const fixture = createFixture(t);
  92. generateCertificate(fixture.sourceDir, 'example.test');
  93. mkdirSync(fixture.certsDir, { recursive: true });
  94. writeEnvironment(fixture, {
  95. SUBMISSION_TLS_KEY: '/certs/fullchain.pem'
  96. });
  97. const result = runSync(fixture);
  98. assert.notEqual(result.status, 0);
  99. assert.equal(readdirSync(fixture.certsDir).some((name) => name === 'fullchain.pem' || name === 'privkey.pem'), false);
  100. assert.deepEqual(stagingFiles(fixture.certsDir), []);
  101. });
  102. test('rejects a mismatched certificate and private key without touching the targets', { skip: !canRun }, (t) => {
  103. const fixture = createFixture(t);
  104. const unrelatedDir = path.join(fixture.root, 'unrelated');
  105. mkdirSync(unrelatedDir, { recursive: true });
  106. generateCertificate(fixture.sourceDir, 'example.test');
  107. generateCertificate(unrelatedDir, 'example.test');
  108. writeFileSync(fixture.sourceKey, readFileSync(path.join(unrelatedDir, 'privkey.pem')));
  109. mkdirSync(fixture.certsDir, { recursive: true });
  110. writeFileSync(fixture.targetCert, 'existing certificate\n');
  111. writeFileSync(fixture.targetKey, 'existing private key\n');
  112. const certBefore = readFileSync(fixture.targetCert);
  113. const keyBefore = readFileSync(fixture.targetKey);
  114. const result = runSync(fixture);
  115. assert.notEqual(result.status, 0);
  116. assert.match(result.stderr, /certificate and private key do not match/i);
  117. assert.deepEqual(readFileSync(fixture.targetCert), certBefore);
  118. assert.deepEqual(readFileSync(fixture.targetKey), keyBefore);
  119. assert.equal(readdirSync(fixture.certsDir).some((name) => name.endsWith('.previous')), false);
  120. assert.deepEqual(stagingFiles(fixture.certsDir), []);
  121. });
  122. test('tightens an overly permissive existing private key to mode 0640', { skip: !canRun }, (t) => {
  123. const fixture = createFixture(t);
  124. generateCertificate(fixture.sourceDir, 'example.test');
  125. const first = runSync(fixture);
  126. assert.equal(first.status, 0, first.stderr);
  127. chmodSync(fixture.targetKey, 0o666);
  128. generateCertificate(fixture.sourceDir, 'example.test');
  129. const replacement = runSync(fixture);
  130. assert.equal(replacement.status, 0, replacement.stderr);
  131. assert.equal(fileMode(fixture.targetKey), 0o640);
  132. assert.deepEqual(readFileSync(fixture.targetKey), readFileSync(fixture.sourceKey));
  133. });
  134. test('validates and installs a staged source snapshot when managed files change mid-run', { skip: !canRun }, (t) => {
  135. const fixture = createFixture(t);
  136. const replacementDir = path.join(fixture.root, 'replacement');
  137. mkdirSync(replacementDir, { recursive: true });
  138. generateCertificate(fixture.sourceDir, 'example.test');
  139. generateCertificate(replacementDir, 'example.test');
  140. const expectedCert = readFileSync(fixture.sourceCert);
  141. const expectedKey = readFileSync(fixture.sourceKey);
  142. const marker = path.join(fixture.root, 'source-mutated');
  143. const mutationPath = createOpenSslMutationPath(fixture.root, fixture.path);
  144. const result = runSync(fixture, {
  145. env: {
  146. PATH: mutationPath,
  147. MAILHUB_TEST_REAL_OPENSSL: opensslPath,
  148. MAILHUB_TEST_MUTATION_MARKER: marker,
  149. MAILHUB_TEST_SOURCE_CERT: fixture.sourceCert,
  150. MAILHUB_TEST_SOURCE_KEY: fixture.sourceKey,
  151. MAILHUB_TEST_REPLACEMENT_CERT: path.join(replacementDir, 'fullchain.pem'),
  152. MAILHUB_TEST_REPLACEMENT_KEY: path.join(replacementDir, 'privkey.pem')
  153. }
  154. });
  155. assert.equal(result.status, 0, result.stderr);
  156. assert.equal(readFileSync(fixture.targetCert).equals(expectedCert), true, 'installed certificate must use the staged snapshot');
  157. assert.equal(readFileSync(fixture.targetKey).equals(expectedKey), true, 'installed private key must use the staged snapshot');
  158. assert.notDeepEqual(readFileSync(fixture.sourceCert), expectedCert);
  159. assert.notDeepEqual(readFileSync(fixture.sourceKey), expectedKey);
  160. assert.deepEqual(stagingFiles(fixture.certsDir), []);
  161. });
  162. test('rolls back both certificate files when post-restart health validation fails', { skip: !canRun }, (t) => {
  163. const fixture = createFixture(t);
  164. generateCertificate(fixture.sourceDir, 'example.test');
  165. const first = runSync(fixture);
  166. assert.equal(first.status, 0, first.stderr);
  167. const certBefore = readFileSync(fixture.targetCert);
  168. const keyBefore = readFileSync(fixture.targetKey);
  169. const certModeBefore = fileMode(fixture.targetCert);
  170. const keyModeBefore = fileMode(fixture.targetKey);
  171. generateCertificate(fixture.sourceDir, 'example.test');
  172. const failurePath = createFailedHealthPath(fixture.root, fixture.path);
  173. const result = runSync(fixture, {
  174. restart: '1',
  175. env: { PATH: failurePath }
  176. });
  177. assert.notEqual(result.status, 0);
  178. assert.match(result.stderr, /did not become healthy/i);
  179. assert.equal(readFileSync(fixture.targetCert).equals(certBefore), true, 'certificate must roll back after failed health validation');
  180. assert.equal(readFileSync(fixture.targetKey).equals(keyBefore), true, 'private key must roll back after failed health validation');
  181. assert.equal(fileMode(fixture.targetCert), certModeBefore);
  182. assert.equal(fileMode(fixture.targetKey), keyModeBefore);
  183. assert.deepEqual(stagingFiles(fixture.certsDir), []);
  184. });
  185. function createFixture(t) {
  186. const root = mkdtempSync(path.join(os.tmpdir(), 'mailhub-cert-sync-'));
  187. const projectDir = path.join(root, 'project');
  188. const sourceDir = path.join(root, 'source');
  189. const certsDir = path.join(projectDir, 'certs');
  190. const envFile = path.join(projectDir, '.env');
  191. mkdirSync(projectDir, { recursive: true });
  192. mkdirSync(sourceDir, { recursive: true });
  193. writeFileSync(envFile, [
  194. 'MAIL_HOSTNAME=mail.example.test',
  195. 'SUBMISSION_TLS_CERT=/certs/fullchain.pem',
  196. 'SUBMISSION_TLS_KEY=/certs/privkey.pem',
  197. ''
  198. ].join('\n'));
  199. t.after(() => rmSync(root, { recursive: true, force: true }));
  200. return {
  201. root,
  202. projectDir,
  203. sourceDir,
  204. certsDir,
  205. envFile,
  206. sourceCert: path.join(sourceDir, 'fullchain.pem'),
  207. sourceKey: path.join(sourceDir, 'privkey.pem'),
  208. targetCert: path.join(certsDir, 'fullchain.pem'),
  209. targetKey: path.join(certsDir, 'privkey.pem'),
  210. path: createCompatibilityPath(root)
  211. };
  212. }
  213. function writeEnvironment(fixture, overrides = {}) {
  214. const values = {
  215. MAIL_HOSTNAME: 'mail.example.test',
  216. SUBMISSION_TLS_CERT: '/certs/fullchain.pem',
  217. SUBMISSION_TLS_KEY: '/certs/privkey.pem',
  218. ...overrides
  219. };
  220. writeFileSync(fixture.envFile, [
  221. `MAIL_HOSTNAME=${values.MAIL_HOSTNAME}`,
  222. `SUBMISSION_TLS_CERT=${values.SUBMISSION_TLS_CERT}`,
  223. `SUBMISSION_TLS_KEY=${values.SUBMISSION_TLS_KEY}`,
  224. ''
  225. ].join('\n'));
  226. }
  227. function generateCertificate(sourceDir, domain) {
  228. const result = spawnSync('openssl', [
  229. 'req',
  230. '-x509',
  231. '-newkey', 'rsa:2048',
  232. '-nodes',
  233. '-sha256',
  234. '-days', '30',
  235. '-subj', `/CN=*.${domain}`,
  236. '-addext', `subjectAltName=DNS:*.${domain},DNS:${domain}`,
  237. '-keyout', path.join(sourceDir, 'privkey.pem'),
  238. '-out', path.join(sourceDir, 'fullchain.pem')
  239. ], { encoding: 'utf8' });
  240. assert.equal(result.status, 0, result.stderr);
  241. }
  242. function runSync(fixture, { restart = '0', env = {} } = {}) {
  243. const rootOwnershipEnv = typeof process.getuid === 'function' && process.getuid() === 0
  244. ? { MAILHUB_CERT_READER_GID: String(process.getgid()) }
  245. : {};
  246. return spawnSync('bash', [scriptPath], {
  247. cwd: fixture.projectDir,
  248. encoding: 'utf8',
  249. env: {
  250. ...process.env,
  251. PATH: fixture.path,
  252. MAILHUB_CERT_PROJECT_DIR: fixture.projectDir,
  253. MAILHUB_CERT_ENV_FILE: fixture.envFile,
  254. MAILHUB_CERT_SOURCE_DIR: fixture.sourceDir,
  255. MAILHUB_CERT_RESTART: restart,
  256. ...rootOwnershipEnv,
  257. ...env
  258. }
  259. });
  260. }
  261. function statSnapshot(file) {
  262. const stat = statSync(file);
  263. return {
  264. ino: stat.ino,
  265. mode: stat.mode & 0o777,
  266. size: stat.size,
  267. mtimeMs: stat.mtimeMs
  268. };
  269. }
  270. function fileMode(file) {
  271. return statSync(file).mode & 0o777;
  272. }
  273. function stagingFiles(directory) {
  274. return readdirSync(directory).filter((name) => name.includes('.tmp.') || name.startsWith('.cert-sync.'));
  275. }
  276. function createCompatibilityPath(root) {
  277. if (process.platform !== 'darwin') return process.env.PATH || '';
  278. const binDir = path.join(root, 'bin');
  279. mkdirSync(binDir, { recursive: true });
  280. writeExecutable(path.join(binDir, 'cp'), stripDoubleDashWrapper('/bin/cp'));
  281. writeExecutable(path.join(binDir, 'mv'), stripDoubleDashWrapper('/bin/mv'));
  282. writeExecutable(path.join(binDir, 'rm'), stripDoubleDashWrapper('/bin/rm'));
  283. writeExecutable(path.join(binDir, 'chmod'), `#!/usr/bin/env bash
  284. set -euo pipefail
  285. if [[ "\${1:-}" == --reference=* ]]; then
  286. reference="\${1#*=}"
  287. shift
  288. mode="$(/usr/bin/stat -f '%Lp' "\${reference}")"
  289. exec /bin/chmod "\${mode}" "$@"
  290. fi
  291. exec /bin/chmod "$@"
  292. `);
  293. writeExecutable(path.join(binDir, 'chown'), `#!/usr/bin/env bash
  294. set -euo pipefail
  295. if [[ "\${1:-}" == --reference=* ]]; then
  296. reference="\${1#*=}"
  297. shift
  298. owner="$(/usr/bin/stat -f '%u:%g' "\${reference}")"
  299. exec /usr/sbin/chown "\${owner}" "$@"
  300. fi
  301. exec /usr/sbin/chown "$@"
  302. `);
  303. writeExecutable(path.join(binDir, 'sha256sum'), `#!/usr/bin/env bash
  304. exec /usr/bin/shasum -a 256 "$@"
  305. `);
  306. return `${binDir}${path.delimiter}${process.env.PATH || ''}`;
  307. }
  308. function createOpenSslMutationPath(root, basePath) {
  309. const binDir = path.join(root, 'mutating-openssl-bin');
  310. mkdirSync(binDir, { recursive: true });
  311. writeExecutable(path.join(binDir, 'openssl'), `#!/usr/bin/env bash
  312. set -euo pipefail
  313. if [[ ! -e "\${MAILHUB_TEST_MUTATION_MARKER}" ]]; then
  314. : > "\${MAILHUB_TEST_MUTATION_MARKER}"
  315. cp "\${MAILHUB_TEST_REPLACEMENT_CERT}" "\${MAILHUB_TEST_SOURCE_CERT}"
  316. cp "\${MAILHUB_TEST_REPLACEMENT_KEY}" "\${MAILHUB_TEST_SOURCE_KEY}"
  317. fi
  318. exec "\${MAILHUB_TEST_REAL_OPENSSL}" "$@"
  319. `);
  320. return `${binDir}${path.delimiter}${basePath}`;
  321. }
  322. function createFailedHealthPath(root, basePath) {
  323. const binDir = path.join(root, 'failed-health-bin');
  324. mkdirSync(binDir, { recursive: true });
  325. writeExecutable(path.join(binDir, 'docker'), `#!/usr/bin/env bash
  326. set -euo pipefail
  327. if [[ "$*" == *"tls.createSecureContext"* ]]; then
  328. exit 0
  329. fi
  330. if [[ "$*" == *"test -r"* ]]; then
  331. exit 0
  332. fi
  333. if [[ "\${1:-}" == "compose" && "\${2:-}" == "restart" ]]; then
  334. exit 0
  335. fi
  336. exit 1
  337. `);
  338. writeExecutable(path.join(binDir, 'sleep'), `#!/usr/bin/env bash
  339. exit 0
  340. `);
  341. return `${binDir}${path.delimiter}${basePath}`;
  342. }
  343. function stripDoubleDashWrapper(command) {
  344. return `#!/usr/bin/env bash
  345. set -euo pipefail
  346. args=()
  347. for argument in "$@"; do
  348. [[ "\${argument}" == "--" ]] || args+=("\${argument}")
  349. done
  350. exec ${command} "\${args[@]}"
  351. `;
  352. }
  353. function writeExecutable(file, content) {
  354. writeFileSync(file, content);
  355. chmodSync(file, 0o755);
  356. }