emailengine-app 2.79.8 → 2.80.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/dependabot.yml +22 -0
- package/.github/workflows/test.yml +39 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +69 -0
- package/DOCKER_DEPLOYMENT.md +6 -7
- package/Dockerfile +35 -11
- package/config/default.toml +7 -2
- package/copy-static-files.sh +23 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +43 -0
- package/lib/account/account-state.js +62 -0
- package/lib/account.js +60 -3
- package/lib/api-routes/account-routes.js +20 -0
- package/lib/api-routes/bull-board-routes.js +3 -2
- package/lib/api-routes/index.js +1 -1
- package/lib/api-routes/route-helpers.js +8 -0
- package/lib/api-routes/settings-routes.js +17 -2
- package/lib/auth-token.js +73 -2
- package/lib/autodetect-imap-settings.js +379 -69
- package/lib/cert-handler.js +62 -0
- package/lib/consts.js +58 -7
- package/lib/db.js +12 -0
- package/lib/egress-fetch.js +145 -0
- package/lib/email-client/base-client.js +234 -66
- package/lib/email-client/credential-errors.js +118 -0
- package/lib/email-client/gmail/gmail-api.js +2 -1
- package/lib/email-client/gmail-client.js +70 -64
- package/lib/email-client/imap/connection-errors.js +52 -0
- package/lib/email-client/imap/listing-diff.js +47 -6
- package/lib/email-client/imap/mailbox.js +457 -379
- package/lib/email-client/imap/subconnection.js +15 -11
- package/lib/email-client/imap/sync-operations.js +46 -59
- package/lib/email-client/imap-client.js +136 -95
- package/lib/email-client/message-builder.js +11 -11
- package/lib/email-client/outlook/graph-api.js +2 -1
- package/lib/email-client/outlook-client.js +219 -106
- package/lib/export.js +35 -2
- package/lib/handlebars-helpers.js +129 -0
- package/lib/imap-proxy-auth.js +96 -21
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
- package/lib/imapproxy/imap-server.js +56 -66
- package/lib/lua/h-del-if-equals.lua +39 -0
- package/lib/lua/h-set-if-equals.lua +39 -0
- package/lib/openapi/index.js +3 -0
- package/lib/outbox.js +28 -3
- package/lib/rate-limit.js +23 -4
- package/lib/routes-ui.js +4 -34
- package/lib/schemas.js +42 -3
- package/lib/security-headers.js +411 -0
- package/lib/sentry.js +36 -4
- package/lib/smtp-auth.js +86 -7
- package/lib/tls/context.js +376 -0
- package/lib/tls/der.js +223 -0
- package/lib/tls/provision.js +555 -0
- package/lib/tls/self-signed.js +282 -0
- package/lib/tls/status.js +431 -0
- package/lib/tls/store.js +666 -0
- package/lib/tools.js +337 -147
- package/lib/ui-routes/account-routes.js +47 -33
- package/lib/ui-routes/admin-config-routes.js +22 -1
- package/lib/ui-routes/auth-routes.js +16 -1
- package/lib/ui-routes/export-routes.js +4 -0
- package/lib/ui-routes/internals-routes.js +3 -5
- package/lib/ui-routes/mcp-consent-routes.js +7 -0
- package/lib/ui-routes/network-config-routes.js +58 -48
- package/lib/ui-routes/route-helpers.js +24 -8
- package/lib/ui-routes/smtp-test-routes.js +7 -0
- package/lib/ui-routes/tls-config-routes.js +581 -0
- package/lib/utils/mailbox-path.js +51 -0
- package/lib/utils/severity.js +31 -0
- package/lib/webhook-egress.js +5 -0
- package/package.json +21 -24
- package/sbom.json +1 -1
- package/server.js +53 -36
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +11 -0
- package/static/js/ace/css/ace.css +1462 -0
- package/static/js/ace/css/kuroir-1.png +0 -0
- package/static/js/ace/css/kuroir-2.png +0 -0
- package/static/js/ace/css/main-1.png +0 -0
- package/static/js/ace/css/main-10.svg +4 -0
- package/static/js/ace/css/main-11.svg +5 -0
- package/static/js/ace/css/main-12.svg +4 -0
- package/static/js/ace/css/main-13.png +0 -0
- package/static/js/ace/css/main-14.png +0 -0
- package/static/js/ace/css/main-15.png +0 -0
- package/static/js/ace/css/main-16.png +0 -0
- package/static/js/ace/css/main-17.png +0 -0
- package/static/js/ace/css/main-18.png +0 -0
- package/static/js/ace/css/main-19.png +0 -0
- package/static/js/ace/css/main-2.png +0 -0
- package/static/js/ace/css/main-20.png +0 -0
- package/static/js/ace/css/main-21.png +0 -0
- package/static/js/ace/css/main-22.png +0 -0
- package/static/js/ace/css/main-23.png +0 -0
- package/static/js/ace/css/main-24.png +0 -0
- package/static/js/ace/css/main-25.svg +1 -0
- package/static/js/ace/css/main-26.png +0 -0
- package/static/js/ace/css/main-3.png +0 -0
- package/static/js/ace/css/main-4.png +0 -0
- package/static/js/ace/css/main-5.svg +7 -0
- package/static/js/ace/css/main-6.svg +9 -0
- package/static/js/ace/css/main-7.svg +7 -0
- package/static/js/ace/css/main-8.svg +9 -0
- package/static/js/ace/css/main-9.svg +6 -0
- package/static/js/ace/css/theme/kuroir.css +78 -0
- package/static/js/ace/css/theme/tomorrow_night.css +128 -0
- package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
- package/static/js/ace/css/theme/xcode.css +106 -0
- package/static/js/ace/css/tomorrow_night-1.png +0 -0
- package/static/js/ace/css/tomorrow_night-2.png +0 -0
- package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
- package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
- package/static/js/ace/css/xcode-1.png +0 -0
- package/static/js/ace/css/xcode-2.png +0 -0
- package/static/js/app.js +34 -0
- package/static/js/ee-client.js +256 -102
- package/static/js/public.js +13 -2
- package/static/js/ui.js +40 -25
- package/static/licenses.html +393 -1282
- package/static/vendor/simplewebauthn/browser.min.js +2 -2
- package/translations/messages.pot +203 -157
- package/views/account/login-redirect.hbs +22 -0
- package/views/accounts/account.hbs +15 -37
- package/views/accounts/browse.hbs +3 -1
- package/views/accounts/edit.hbs +1 -1
- package/views/accounts/register/imap-server.hbs +1 -1
- package/views/config/ai.hbs +1 -1
- package/views/config/branding.hbs +2 -2
- package/views/config/document-store/chat.hbs +1 -1
- package/views/config/document-store/index.hbs +1 -1
- package/views/config/imap-proxy.hbs +1 -4
- package/views/config/license.hbs +1 -1
- package/views/config/mcp.hbs +1 -1
- package/views/config/network.hbs +14 -16
- package/views/config/oauth/app.hbs +2 -2
- package/views/config/service.hbs +1 -1
- package/views/config/smtp.hbs +1 -4
- package/views/config/tls-upload.hbs +81 -0
- package/views/config/tls.hbs +492 -0
- package/views/config/webhooks.hbs +2 -2
- package/views/error.hbs +4 -2
- package/views/internals/index.hbs +1 -1
- package/views/layout/app.hbs +3 -11
- package/views/mcp/authorize.hbs +1 -1
- package/views/partials/ace_assets.hbs +13 -0
- package/views/partials/add_account_modal.hbs +1 -1
- package/views/partials/address_list.hbs +4 -4
- package/views/partials/filter_editor_js.hbs +2 -2
- package/views/partials/gateway_js.hbs +1 -1
- package/views/partials/oauth_form.hbs +1 -1
- package/views/partials/public_theme_init.hbs +1 -1
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/template_form.hbs +2 -2
- package/views/partials/test_send.hbs +7 -4
- package/views/partials/theme_init.hbs +1 -1
- package/views/partials/tls_security_card.hbs +25 -53
- package/views/partials/ui/alert-banner.hbs +3 -2
- package/views/partials/ui/badge.hbs +6 -2
- package/views/partials/ui/btn.hbs +5 -2
- package/views/partials/ui/details.hbs +2 -2
- package/views/partials/webhooks_editor_functions.hbs +1 -1
- package/views/reference/redirect.hbs +1 -1
- package/views/templates/template.hbs +2 -2
- package/views/tokens/new.hbs +1 -1
- package/views/unsubscribe.hbs +1 -1
- package/views/webhooks/webhook.hbs +2 -2
- package/workers/api.js +131 -242
- package/workers/export.js +1 -5
- package/workers/imap-proxy.js +4 -1
- package/workers/imap.js +1 -3
- package/workers/smtp.js +59 -83
- package/workers/submit.js +6 -12
- package/workers/webhooks.js +6 -17
- package/static/front/EmailEngine_logo_horiz.png +0 -0
- package/static/front/EmailEngine_logo_vert.png +0 -0
- package/static/front/index.html +0 -57
- package/static/front/logo.png +0 -0
- package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
- package/views/partials/tls_security_js.hbs +0 -64
- package/views/partials/tls_security_modal.hbs +0 -22
package/lib/smtp-auth.js
CHANGED
|
@@ -9,7 +9,7 @@ const settings = require('./settings');
|
|
|
9
9
|
const { redis } = require('./db');
|
|
10
10
|
const { Account } = require('./account');
|
|
11
11
|
const getSecret = require('./get-secret');
|
|
12
|
-
const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
|
|
12
|
+
const { validateAuthToken, withAuthFailureBudget, REASON_MESSAGES } = require('./auth-token');
|
|
13
13
|
const { constantTimeEqual } = require('./tools');
|
|
14
14
|
|
|
15
15
|
/**
|
|
@@ -21,11 +21,9 @@ const { constantTimeEqual } = require('./tools');
|
|
|
21
21
|
* @returns {Function} async onAuth(auth, session)
|
|
22
22
|
*/
|
|
23
23
|
function createSmtpAuthHandler({ accountCache, call }) {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
}
|
|
28
|
-
|
|
24
|
+
// The credential check proper. Everything it throws is a refusal the client caused, which
|
|
25
|
+
// is what the failure budget in onAuth() counts.
|
|
26
|
+
async function authenticate(auth, session) {
|
|
29
27
|
let account = auth.username;
|
|
30
28
|
|
|
31
29
|
let smtpPassword = await settings.get('smtpServerPassword');
|
|
@@ -65,7 +63,88 @@ function createSmtpAuthHandler({ accountCache, call }) {
|
|
|
65
63
|
|
|
66
64
|
accountCache.set(session, accountObject);
|
|
67
65
|
return { user: accountData.account };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return async function onAuth(auth, session) {
|
|
69
|
+
if (!session.eeAuthEnabled) {
|
|
70
|
+
throw new Error('Authentication not enabled');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return await withAuthFailureBudget(
|
|
74
|
+
{ remoteAddress: session.remoteAddress, account: auth.username },
|
|
75
|
+
() => authenticate(auth, session),
|
|
76
|
+
() => {
|
|
77
|
+
let err = new Error(REASON_MESSAGES.limited);
|
|
78
|
+
// A temporary failure, so the client retries later instead of concluding that its
|
|
79
|
+
// credentials are wrong
|
|
80
|
+
err.responseCode = 454;
|
|
81
|
+
return err;
|
|
82
|
+
}
|
|
83
|
+
);
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Builds the resolver that finds the Account a submitted message is sent through.
|
|
89
|
+
*
|
|
90
|
+
* Lives beside the auth handler for the same reason it does: the worker can not be required
|
|
91
|
+
* from a test, and this is the other half of the decision of who may submit through which
|
|
92
|
+
* account. An authenticated session submits through the account it logged in as; a session
|
|
93
|
+
* opened while authentication was off names the account with the X-EE-Account header.
|
|
94
|
+
*
|
|
95
|
+
* @param {Object} deps
|
|
96
|
+
* @param {WeakMap} deps.accountCache - session -> Account cache shared with the auth handler
|
|
97
|
+
* @param {Function} deps.call - RPC function passed to the Account instance
|
|
98
|
+
* @returns {Function} async resolveAccount(session, messageMeta) -> Account
|
|
99
|
+
*/
|
|
100
|
+
function createSmtpAccountResolver({ accountCache, call }) {
|
|
101
|
+
return async function resolveAccount(session, messageMeta) {
|
|
102
|
+
let accountObject;
|
|
103
|
+
|
|
104
|
+
if (!session.eeAuthEnabled) {
|
|
105
|
+
// The session decided at connect time that no authentication was required. A client
|
|
106
|
+
// can hold a connection open for as long as it likes, so if the operator has switched
|
|
107
|
+
// authentication on since, the stale decision must not keep admitting submissions.
|
|
108
|
+
if (await settings.get('smtpServerAuthEnabled')) {
|
|
109
|
+
let err = new Error('Authentication required');
|
|
110
|
+
err.responseCode = 530;
|
|
111
|
+
throw err;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (!session.eeAuthEnabled && messageMeta.requestedAccount) {
|
|
116
|
+
// Only a loaded account counts as resolved. Keeping the instance after a failed load
|
|
117
|
+
// let an unknown header value through here, to fail later inside the queueing with
|
|
118
|
+
// an error that never named the reason
|
|
119
|
+
let requested = new Account({ account: messageMeta.requestedAccount, redis, call, secret: await getSecret() });
|
|
120
|
+
try {
|
|
121
|
+
// throws if unknown user
|
|
122
|
+
if (await requested.loadAccountData()) {
|
|
123
|
+
accountObject = requested;
|
|
124
|
+
accountCache.set(session, accountObject);
|
|
125
|
+
logger.debug({ msg: 'Resolved requested account', account: messageMeta.requestedAccount });
|
|
126
|
+
}
|
|
127
|
+
} catch (err) {
|
|
128
|
+
logger.warn({ msg: 'Failed to resolve requested account', account: messageMeta.requestedAccount, err });
|
|
129
|
+
}
|
|
130
|
+
} else {
|
|
131
|
+
accountObject = accountCache.get(session);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (!session.eeAuthEnabled && !messageMeta.requestedAccount && !accountObject) {
|
|
135
|
+
let err = new Error('Sender account ID not provided, can not send mail');
|
|
136
|
+
err.responseCode = 451;
|
|
137
|
+
throw err;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!accountObject) {
|
|
141
|
+
let err = new Error('Failed to load account');
|
|
142
|
+
err.responseCode = 451;
|
|
143
|
+
throw err;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return accountObject;
|
|
68
147
|
};
|
|
69
148
|
}
|
|
70
149
|
|
|
71
|
-
module.exports = { createSmtpAuthHandler };
|
|
150
|
+
module.exports = { createSmtpAuthHandler, createSmtpAccountResolver };
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Turns the sources in lib/tls/store.js into something a TLS listener can be handed, and lets a
|
|
4
|
+
// listener swap what it serves without being restarted.
|
|
5
|
+
//
|
|
6
|
+
// Both problems are the same problem. A listener used to bake `cert` and `key` into its options at
|
|
7
|
+
// startup, so a renewed certificate only reached clients when the worker was terminated and
|
|
8
|
+
// respawned - every SMTP submission and every IMAP session in flight was cut for a certificate that
|
|
9
|
+
// had another thirty days on it. A secure context built here can be replaced in place, and the
|
|
10
|
+
// SNI callback reads whatever the latest refresh produced.
|
|
11
|
+
//
|
|
12
|
+
// The same callback is what serves more than one hostname. EmailEngine's admin URL and its mail
|
|
13
|
+
// hostname are usually different names, and a client connecting to smtp.example.com has to be
|
|
14
|
+
// offered a certificate for smtp.example.com, not for the admin UI's.
|
|
15
|
+
//
|
|
16
|
+
// Everything a handshake needs is computed in refresh(): the certificates are parsed once there,
|
|
17
|
+
// not per connection. The SNI callback is on the accept path of the SMTP server, the IMAP proxy
|
|
18
|
+
// and the API's HTTPS listener, so anything it does is done once per client.
|
|
19
|
+
|
|
20
|
+
const tls = require('tls');
|
|
21
|
+
const config = require('@zone-eu/wild-config');
|
|
22
|
+
|
|
23
|
+
const settings = require('../settings');
|
|
24
|
+
const { hasEnvValue, readEnvValue, getBoolean } = require('../tools');
|
|
25
|
+
const {
|
|
26
|
+
getCertificateHostnames,
|
|
27
|
+
getManualCertificate,
|
|
28
|
+
getSelfSignedCertificate,
|
|
29
|
+
getAcmeCertificate,
|
|
30
|
+
parseCertificate,
|
|
31
|
+
coversHostname,
|
|
32
|
+
describeX509,
|
|
33
|
+
normalizeHostname
|
|
34
|
+
} = require('./store');
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The certificate plus whatever chain came with it, which is what a TLS context wants.
|
|
38
|
+
*
|
|
39
|
+
* @param {Object} material Resolved material
|
|
40
|
+
* @returns {string} PEM bundle, leaf first
|
|
41
|
+
*/
|
|
42
|
+
function fullChain(material) {
|
|
43
|
+
return material.ca && material.ca.length ? [material.cert].concat(material.ca).join('\n') : material.cert;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether, and how, the API listener serves TLS: EENGINE_API_TLS and `[api.tls]`.
|
|
48
|
+
*
|
|
49
|
+
* Read from the environment and the config file, which every process shares, so the API worker
|
|
50
|
+
* (which builds its listener from it) and the certificate reconciler (which asks whether any
|
|
51
|
+
* listener would serve a certificate) cannot answer differently.
|
|
52
|
+
*
|
|
53
|
+
* @returns {Object|false} The `[api.tls]` options to build the listener from, or false when the
|
|
54
|
+
* API serves plain HTTP
|
|
55
|
+
*/
|
|
56
|
+
function apiTlsConfig() {
|
|
57
|
+
return hasEnvValue('EENGINE_API_TLS') ? getBoolean(readEnvValue('EENGINE_API_TLS')) && (config.api.tls || {}) : config.api.tls || false;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// How a listener negotiates, as opposed to what it serves. These belong to the listener rather
|
|
61
|
+
// than to any one certificate, and they travel with the resolved options because installing a
|
|
62
|
+
// context replaces it whole: tls.Server.setSecureContext() reverts everything absent from its
|
|
63
|
+
// argument to Node's default, so a reload carrying nothing but a certificate and a key dropped an
|
|
64
|
+
// operator's mTLS `ca` and version bounds at the first renewal. Every context built here is built
|
|
65
|
+
// from the same set, so what a listener installs and what the SNI callback hands back cannot drift.
|
|
66
|
+
//
|
|
67
|
+
// The names are the tls.createSecureContext() ones, which is what lib/tools.js loadTlsConfig()
|
|
68
|
+
// fills in from EENGINE_{API,SMTP,IMAPPROXY}_TLS_* and [api.tls]. `requestCert` and
|
|
69
|
+
// `rejectUnauthorized` are deliberately absent: they are listener options, not context options.
|
|
70
|
+
const HANDSHAKE_KEYS = ['ca', 'ciphers', 'ecdhCurve', 'dhparam', 'minVersion', 'maxVersion', 'honorCipherOrder', 'secureOptions', 'sigalgs', 'crl'];
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Picks the handshake settings out of a listener's TLS options.
|
|
74
|
+
*
|
|
75
|
+
* @param {Object} [source] Listener TLS options
|
|
76
|
+
* @returns {Object} Just the settings a secure context understands
|
|
77
|
+
*/
|
|
78
|
+
function handshakeOptionsFrom(source) {
|
|
79
|
+
const options = {};
|
|
80
|
+
|
|
81
|
+
for (const key of HANDSHAKE_KEYS) {
|
|
82
|
+
if (source && typeof source[key] !== 'undefined' && source[key] !== null) {
|
|
83
|
+
options[key] = source[key];
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return options;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Which stored sources the operator's choice admits. The setting is the certificate SOURCE, so it
|
|
91
|
+
// has to decide what is served and not only whether an order is placed: picking "self-signed only"
|
|
92
|
+
// while a Let's Encrypt certificate was still being served is the same class of bug this rework
|
|
93
|
+
// exists to remove - the UI describing behaviour the code does not have.
|
|
94
|
+
//
|
|
95
|
+
// Material from the environment is admitted by every mode. It is not a source EmailEngine chose.
|
|
96
|
+
const MODE_SOURCES = {
|
|
97
|
+
acme: { manual: true, acme: true },
|
|
98
|
+
manual: { manual: true, acme: false },
|
|
99
|
+
'self-signed': { manual: false, acme: false }
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
function sourcesFor(mode) {
|
|
103
|
+
return MODE_SOURCES[mode] || MODE_SOURCES.acme;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Material for one name, in the precedence order lib/tls/store.js documents. The self-signed
|
|
108
|
+
* fallback is not here: it covers every configured name at once and is resolved by the caller when
|
|
109
|
+
* nothing else answered.
|
|
110
|
+
*
|
|
111
|
+
* @param {Object} opts
|
|
112
|
+
* @param {Object} [opts.certs] @postalsys/certs handler, or null to skip the ACME source
|
|
113
|
+
* @param {string} opts.hostname Name being resolved
|
|
114
|
+
* @param {Object} [opts.sources] Which stored sources the configured mode admits
|
|
115
|
+
* @param {Object} [opts.env] Material from the environment or config file
|
|
116
|
+
* @param {Object} [opts.envX509] That certificate, parsed once
|
|
117
|
+
* @param {Object} [opts.manual] Pre-loaded uploaded certificate, so one lookup serves every name
|
|
118
|
+
* @param {Object} [opts.manualX509] That certificate, parsed once
|
|
119
|
+
* @param {Object} [opts.logger] Logger for a stored certificate that could not be read
|
|
120
|
+
* @returns {Promise<Object|false>} Material, or false when only the fallback is left
|
|
121
|
+
*/
|
|
122
|
+
async function resolveHostname(opts) {
|
|
123
|
+
const { certs, hostname, env, envX509, manual, manualX509, logger } = opts;
|
|
124
|
+
const sources = opts.sources || sourcesFor('acme');
|
|
125
|
+
|
|
126
|
+
// An explicit instruction from the operator, and the only source not stored in Redis. Applied
|
|
127
|
+
// per name like every other source: a listener told to serve one certificate should still
|
|
128
|
+
// offer a second configured hostname the certificate that actually covers it.
|
|
129
|
+
if (env && coversHostname(envX509, hostname)) {
|
|
130
|
+
return env;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (sources.manual && manual && coversHostname(manualX509, hostname)) {
|
|
134
|
+
return manual;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (sources.acme) {
|
|
138
|
+
return (await getAcmeCertificate(certs, hostname, logger)) || false;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Builds a listener's TLS material and keeps it refreshable.
|
|
146
|
+
*
|
|
147
|
+
* @param {Object} opts
|
|
148
|
+
* @param {Object} [opts.certs] @postalsys/certs handler
|
|
149
|
+
* @param {Object} opts.logger Worker logger
|
|
150
|
+
* @param {Object} [opts.listenerOptions] The listener's own TLS options: its handshake settings, and
|
|
151
|
+
* the material the environment or config file supplied
|
|
152
|
+
* @param {Object} [opts.envMaterial] That material stated explicitly, when it is not on the listener
|
|
153
|
+
* options: `{ cert, key, ca, passphrase }`
|
|
154
|
+
* @returns {Promise<Object>} `{ options, active, source, refresh() }`
|
|
155
|
+
*/
|
|
156
|
+
async function createTlsContext(opts) {
|
|
157
|
+
const { certs, logger } = opts || {};
|
|
158
|
+
const listenerOptions = (opts && opts.listenerOptions) || null;
|
|
159
|
+
|
|
160
|
+
// Both snapshotted here rather than read per refresh: a listener writes the resolved options
|
|
161
|
+
// back into the same object it passed in, so re-reading it later would mean reading this
|
|
162
|
+
// module's own output back as if the operator had configured it.
|
|
163
|
+
const handshake = handshakeOptionsFrom(listenerOptions);
|
|
164
|
+
const envMaterial =
|
|
165
|
+
(opts && opts.envMaterial) ||
|
|
166
|
+
(listenerOptions ? { cert: listenerOptions.cert, key: listenerOptions.key, ca: listenerOptions.ca, passphrase: listenerOptions.passphrase } : null);
|
|
167
|
+
|
|
168
|
+
// The state the SNI callback reads. Replaced wholesale by refresh(), so a handshake either sees
|
|
169
|
+
// the previous set or the new one, never a half-built one.
|
|
170
|
+
let state = { hostnames: [], entries: [], fallback: null, options: {} };
|
|
171
|
+
|
|
172
|
+
// What one certificate is served with. The passphrase only ever comes from the environment:
|
|
173
|
+
// everything EmailEngine stores is decrypted before it reaches here, and an operator's
|
|
174
|
+
// encrypted key without it fails to load, which used to leave the listener quietly serving the
|
|
175
|
+
// self-signed fallback instead of the certificate it was configured with. It is always set,
|
|
176
|
+
// even when there is none - tls.createSecureContext() treats undefined as absent, and merging
|
|
177
|
+
// this into a listener's own options has to clear a passphrase belonging to material it no
|
|
178
|
+
// longer serves.
|
|
179
|
+
const secureContextOptions = material =>
|
|
180
|
+
Object.assign({}, handshake, { cert: fullChain(material), key: material.privateKey, passphrase: material.passphrase });
|
|
181
|
+
|
|
182
|
+
const buildEntry = (hostname, material) => {
|
|
183
|
+
try {
|
|
184
|
+
return {
|
|
185
|
+
hostname,
|
|
186
|
+
material,
|
|
187
|
+
x509: parseCertificate(material.cert),
|
|
188
|
+
context: tls.createSecureContext(secureContextOptions(material))
|
|
189
|
+
};
|
|
190
|
+
} catch (err) {
|
|
191
|
+
if (logger) {
|
|
192
|
+
logger.error({ msg: 'Failed to build a TLS context', hostname, source: material.source, err });
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
// Stable across refreshes, so the options object handed to a listener stays valid while the
|
|
199
|
+
// material behind it is replaced.
|
|
200
|
+
const contextFor = servername => {
|
|
201
|
+
const name = normalizeHostname(servername);
|
|
202
|
+
|
|
203
|
+
if (name) {
|
|
204
|
+
const match = state.entries.find(entry => coversHostname(entry.x509, name));
|
|
205
|
+
if (match) {
|
|
206
|
+
return match.context;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return state.fallback && state.fallback.context;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const sniCallback = (servername, cb) => {
|
|
214
|
+
const context = contextFor(servername);
|
|
215
|
+
return typeof cb === 'function' ? cb(null, context) : context;
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
const refresh = async () => {
|
|
219
|
+
const env =
|
|
220
|
+
envMaterial && envMaterial.cert && envMaterial.key
|
|
221
|
+
? {
|
|
222
|
+
source: 'env',
|
|
223
|
+
cert: envMaterial.cert,
|
|
224
|
+
ca: [].concat(envMaterial.ca || []).filter(entry => entry),
|
|
225
|
+
privateKey: envMaterial.key,
|
|
226
|
+
passphrase: envMaterial.passphrase
|
|
227
|
+
}
|
|
228
|
+
: null;
|
|
229
|
+
const envX509 = env ? parseCertificate(env.cert) : null;
|
|
230
|
+
|
|
231
|
+
// The uploaded certificate is loaded whether or not the environment supplied one: both are
|
|
232
|
+
// applied per name, so a listener pinned to one certificate still has to offer a second
|
|
233
|
+
// configured hostname the uploaded certificate that covers it.
|
|
234
|
+
const [hostnames, mode, manual] = await Promise.all([getCertificateHostnames(), settings.get('tlsProvisioning'), getManualCertificate()]);
|
|
235
|
+
|
|
236
|
+
const sources = sourcesFor(mode);
|
|
237
|
+
const manualX509 = manual ? parseCertificate(manual.cert) : null;
|
|
238
|
+
|
|
239
|
+
// Resolved concurrently: each hostname is an independent pair of Redis reads and a key
|
|
240
|
+
// decrypt, and this runs before the listener binds its port in every worker that serves
|
|
241
|
+
// TLS. Order is preserved, which is what makes entries[0] the primary name.
|
|
242
|
+
const resolved = await Promise.all(hostnames.map(hostname => resolveHostname({ certs, hostname, sources, env, envX509, manual, manualX509, logger })));
|
|
243
|
+
|
|
244
|
+
const entries = [];
|
|
245
|
+
for (let i = 0; i < hostnames.length; i++) {
|
|
246
|
+
if (!resolved[i]) {
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
const entry = buildEntry(hostnames[i], resolved[i]);
|
|
250
|
+
if (entry) {
|
|
251
|
+
entries.push(entry);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// The default context answers a client that sent no SNI, and every name nothing else covers.
|
|
256
|
+
// In order: the certificate for the primary name; then material the operator supplied, even
|
|
257
|
+
// when it covers none of the configured names, because they configured this listener with
|
|
258
|
+
// it on purpose; then any certificate at all; then the self-signed fallback, because a
|
|
259
|
+
// listener that has been switched on has to start. Decided before the self-signed entry
|
|
260
|
+
// joins the list, so it stays the last resort for the default context too.
|
|
261
|
+
let fallback = entries.find(entry => coversHostname(entry.x509, hostnames[0])) || null;
|
|
262
|
+
|
|
263
|
+
if (!fallback && env) {
|
|
264
|
+
fallback = buildEntry(hostnames[0] || null, env);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (!fallback) {
|
|
268
|
+
fallback = entries[0] || null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// The fourth source. The self-signed certificate covers every configured name, and it is
|
|
272
|
+
// the entry for the ones no stored source answers for - not whichever certificate came
|
|
273
|
+
// first, which fails the client's name check just the same and is not what the page says
|
|
274
|
+
// the name has. Generated only when some name needs it: once every name has a certificate
|
|
275
|
+
// of its own there is nothing for it to answer for, and generating it anyway would put a
|
|
276
|
+
// certificate on the page that no listener serves. Material from the environment answers
|
|
277
|
+
// for those names itself, as the default context above: the operator pinned it on purpose.
|
|
278
|
+
const uncovered = env ? [] : hostnames.filter(hostname => !entries.some(entry => coversHostname(entry.x509, hostname)));
|
|
279
|
+
|
|
280
|
+
if (uncovered.length || !fallback) {
|
|
281
|
+
const selfSigned = buildEntry(uncovered[0] || hostnames[0] || null, await getSelfSignedCertificate(hostnames, logger));
|
|
282
|
+
if (selfSigned) {
|
|
283
|
+
entries.push(selfSigned);
|
|
284
|
+
fallback = fallback || selfSigned;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
state = {
|
|
289
|
+
hostnames,
|
|
290
|
+
entries,
|
|
291
|
+
fallback,
|
|
292
|
+
// Built here rather than per read: `cert` and `key` are still set because both mail
|
|
293
|
+
// server libraries assert on them before a handshake happens, and a client that sends
|
|
294
|
+
// no SNI never reaches the callback. The handshake settings come along because a
|
|
295
|
+
// listener installing this replaces its context whole.
|
|
296
|
+
options: fallback ? Object.assign(secureContextOptions(fallback.material), { SNICallback: sniCallback }) : {}
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
return state;
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
await refresh();
|
|
303
|
+
|
|
304
|
+
return {
|
|
305
|
+
refresh,
|
|
306
|
+
|
|
307
|
+
get options() {
|
|
308
|
+
return state.options;
|
|
309
|
+
},
|
|
310
|
+
|
|
311
|
+
get source() {
|
|
312
|
+
return (state.fallback && state.fallback.material.source) || null;
|
|
313
|
+
},
|
|
314
|
+
|
|
315
|
+
// What the listener is serving, for the admin UI's listener table and the state payload.
|
|
316
|
+
get active() {
|
|
317
|
+
if (!state.fallback) {
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// The store's own shape rather than a hand-picked subset of it: the page that renders
|
|
322
|
+
// this reports a certificate that is not valid yet and lists the names it covers, and
|
|
323
|
+
// neither field was here to report.
|
|
324
|
+
return Object.assign(
|
|
325
|
+
{
|
|
326
|
+
source: state.fallback.material.source,
|
|
327
|
+
// Env material is per listener and per process, so the listener is the only
|
|
328
|
+
// thing that knows which of the configured names it serves from it, and the
|
|
329
|
+
// TLS page reads that off this report.
|
|
330
|
+
envHostnames: state.entries.filter(entry => entry.material.source === 'env').map(entry => entry.hostname)
|
|
331
|
+
},
|
|
332
|
+
describeX509(state.fallback.x509) || {}
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Installs whatever the context now resolves to on a running listener.
|
|
340
|
+
*
|
|
341
|
+
* Every TLS listener does the same four things on a reload - refresh, check there is something to
|
|
342
|
+
* serve, hand it over, say what happened - and the last time each of them carried its own copy of a
|
|
343
|
+
* certificate step, the renewal path reloaded the SMTP server and forgot the IMAP proxy for months.
|
|
344
|
+
*
|
|
345
|
+
* @param {Object} opts
|
|
346
|
+
* @param {Object} opts.context Result of createTlsContext(); null when the listener serves no TLS
|
|
347
|
+
* @param {Function} opts.apply Receives the full option set (certificate, key and handshake settings) and installs it
|
|
348
|
+
* @param {Object} opts.logger Worker logger
|
|
349
|
+
* @returns {Promise<Object>} `{ updated, tls }`
|
|
350
|
+
*/
|
|
351
|
+
async function applyTlsContext(opts) {
|
|
352
|
+
const { context, apply, logger } = opts;
|
|
353
|
+
|
|
354
|
+
if (!context) {
|
|
355
|
+
return { updated: false, tls: null };
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
await context.refresh();
|
|
359
|
+
|
|
360
|
+
const options = context.options;
|
|
361
|
+
if (!options.cert || !options.key) {
|
|
362
|
+
logger.error({ msg: 'Refusing to reload TLS certificates, nothing to serve' });
|
|
363
|
+
return { updated: false, tls: null };
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// Everything, not just the certificate and key: a listener that installs a context from those
|
|
367
|
+
// two alone drops whatever the operator configured for the handshake.
|
|
368
|
+
apply(options);
|
|
369
|
+
|
|
370
|
+
const active = context.active;
|
|
371
|
+
logger.info({ msg: 'Reloaded TLS certificates', source: active && active.source, fingerprint: active && active.fingerprint });
|
|
372
|
+
|
|
373
|
+
return { updated: true, tls: active };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
module.exports = { createTlsContext, applyTlsContext, resolveHostname, sourcesFor, apiTlsConfig };
|