emailengine-app 2.86.0 → 2.87.1
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/.ncurc.js +2 -4
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +42 -0
- package/DOCKER_DEPLOYMENT.md +2 -1
- package/Dockerfile +5 -6
- package/README.md +4 -0
- package/bin/emailengine.js +2 -4
- package/bin/healthcheck.js +20 -0
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +3 -7
- package/lib/account/auth-failure-backfill.js +3 -2
- package/lib/account/expected-identity.js +2 -2
- package/lib/account.js +101 -39
- package/lib/api-listener.js +40 -0
- package/lib/api-routes/account-routes.js +14 -7
- package/lib/api-routes/submit-routes.js +21 -2
- package/lib/api-token-auth.js +406 -0
- package/lib/autodetect-imap-settings.js +36 -3
- package/lib/consts.js +5 -0
- package/lib/email-client/base-client.js +27 -109
- package/lib/email-client/gmail-client.js +15 -4
- package/lib/email-client/imap/mailbox.js +97 -97
- package/lib/email-client/imap/sync-operations.js +13 -6
- package/lib/email-client/imap-client.js +28 -7
- package/lib/email-client/new-message-steps.js +162 -0
- package/lib/email-client/outlook-client.js +10 -2
- package/lib/env-setting-overrides.js +6 -2
- package/lib/export-worker.js +3 -2
- package/lib/export.js +43 -4
- package/lib/field-usage.js +1 -1
- package/lib/get-boolean.js +38 -0
- package/lib/get-raw-email.js +10 -1
- package/lib/health-probe.js +71 -0
- package/lib/imapproxy/imap-server.js +4 -55
- package/lib/net-tos-guard.js +42 -0
- package/lib/oauth/gmail.js +54 -29
- package/lib/oauth2-apps.js +2 -1
- package/lib/otp.js +66 -0
- package/lib/read-env-value.js +19 -7
- package/lib/redis-keys.js +19 -0
- package/lib/redis-operations.js +7 -3
- package/lib/schemas.js +62 -2
- package/lib/security-headers.js +18 -0
- package/lib/session-default.js +50 -0
- package/lib/settings.js +2 -1
- package/lib/stream-encrypt.js +71 -20
- package/lib/sub-script.js +8 -2
- package/lib/submit-lock.js +84 -0
- package/lib/submit-processor.js +283 -0
- package/lib/swagger-options.js +2 -2
- package/lib/templates.js +6 -3
- package/lib/tls/context.js +2 -16
- package/lib/tools.js +8 -30
- package/lib/utils/redis-errors.js +44 -0
- package/lib/webhook-delivery.js +3 -4
- package/lib/webhooks.js +5 -0
- package/lib/worker-rpc-error.js +10 -5
- package/lib/worker-rpc.js +138 -0
- package/package.json +25 -26
- package/sbom.json +660 -1736
- package/server.js +6 -5
- package/static/css/flyonui.css +2 -2
- package/static/js/ee-client.js +650 -196
- package/static/licenses.html +280 -1393
- package/translations/messages.pot +16 -16
- package/views/layout/app.hbs +9 -6
- package/views/legal.hbs +8 -0
- package/workers/api.js +51 -474
- package/workers/export.js +14 -55
- package/workers/imap-proxy.js +5 -18
- package/workers/imap.js +27 -49
- package/workers/smtp.js +7 -69
- package/workers/submit.js +21 -279
- package/workers/webhooks.js +7 -72
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const Joi = require('joi');
|
|
4
|
+
const Boom = require('@hapi/boom');
|
|
4
5
|
const { redis } = require('../db');
|
|
5
6
|
const { Account } = require('../account');
|
|
6
7
|
const getSecret = require('../get-secret');
|
|
@@ -27,7 +28,8 @@ const {
|
|
|
27
28
|
apiResponses,
|
|
28
29
|
ENUM_DESCRIPTIONS,
|
|
29
30
|
MAX_MESSAGE_ATTACHMENTS,
|
|
30
|
-
apiBoolean
|
|
31
|
+
apiBoolean,
|
|
32
|
+
submitOtpSchema
|
|
31
33
|
} = require('../schemas');
|
|
32
34
|
|
|
33
35
|
// Schema fragments shared between the message submit and the draft submit routes. Joi schemas
|
|
@@ -96,6 +98,18 @@ const idempotencyResponseSchema = Joi.object({
|
|
|
96
98
|
.description('Idempotency info, present when an Idempotency-Key header was used')
|
|
97
99
|
.label('ResponseIdempotency');
|
|
98
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Refuses an otp with useStructuredFormat, whose JSON Graph send would drop the OTP-Token header
|
|
103
|
+
*
|
|
104
|
+
* @param {Object} request - the Hapi request
|
|
105
|
+
*/
|
|
106
|
+
function assertOtpFormat(request) {
|
|
107
|
+
const payload = request.payload || {};
|
|
108
|
+
if (request.query.useStructuredFormat && (payload.otp || (payload.mailMerge || []).some(entry => entry && entry.otp))) {
|
|
109
|
+
throw Boom.badRequest('A one-time passcode (otp) can not be sent with useStructuredFormat');
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
99
113
|
function buildSubmitMessagePayloadSchema(MAX_ATTACHMENT_SIZE) {
|
|
100
114
|
return Joi.object({
|
|
101
115
|
reference: messageReferenceSchema,
|
|
@@ -203,7 +217,8 @@ function buildSubmitMessagePayloadSchema(MAX_ATTACHMENT_SIZE) {
|
|
|
203
217
|
sendAt: Joi.date()
|
|
204
218
|
.iso()
|
|
205
219
|
.example('2021-07-08T07:06:34.336Z')
|
|
206
|
-
.description('Send message at specified time. Overrides message level `sendAt` value.')
|
|
220
|
+
.description('Send message at specified time. Overrides message level `sendAt` value.'),
|
|
221
|
+
otp: submitOtpSchema.description('One-time passcode for this recipient. Overrides message level `otp` value.').label('MailMergeOtp')
|
|
207
222
|
}).label('MailMergeListEntry')
|
|
208
223
|
)
|
|
209
224
|
.min(1)
|
|
@@ -252,6 +267,8 @@ function buildSubmitMessagePayloadSchema(MAX_ATTACHMENT_SIZE) {
|
|
|
252
267
|
'X-My-Custom-Header': 'Custom header value'
|
|
253
268
|
}),
|
|
254
269
|
|
|
270
|
+
otp: submitOtpSchema,
|
|
271
|
+
|
|
255
272
|
trackingEnabled: Joi.boolean().example(false).description('Should EmailEngine track clicks and opens for this message').meta({ swaggerHidden: true }),
|
|
256
273
|
|
|
257
274
|
trackOpens: Joi.boolean().example(false).description('Should EmailEngine track opens for this message'),
|
|
@@ -418,6 +435,7 @@ function registerSubmitMessage(server, args) {
|
|
|
418
435
|
|
|
419
436
|
try {
|
|
420
437
|
assertNoNetworkOverride(request);
|
|
438
|
+
assertOtpFormat(request);
|
|
421
439
|
|
|
422
440
|
return await accountObject.queueMessage(request.payload, {
|
|
423
441
|
source: 'api',
|
|
@@ -710,3 +728,4 @@ async function init(args) {
|
|
|
710
728
|
}
|
|
711
729
|
|
|
712
730
|
module.exports = init;
|
|
731
|
+
module.exports.assertOtpFormat = assertOtpFormat;
|
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The decision of the `api-token` auth strategy: which credential a REST request carries and
|
|
4
|
+
// whether it may make this request. Moved out of workers/api.js, which cannot be loaded by a test
|
|
5
|
+
// (it boots a server on require), so every branch here is unit tested in
|
|
6
|
+
// test/api-token-auth-test.js instead of only being reachable through a live server.
|
|
7
|
+
//
|
|
8
|
+
// The order of the checks is part of the contract: token resolved, scope, permissions, account,
|
|
9
|
+
// restrictions. Each refusal is logged and written to the token's audit trail before it is thrown,
|
|
10
|
+
// and the accepted path writes one audit row (except at the MCP door, see below).
|
|
11
|
+
//
|
|
12
|
+
// Everything that does I/O comes in through createApiTokenValidator() so a test can stand it in.
|
|
13
|
+
|
|
14
|
+
const Boom = require('@hapi/boom');
|
|
15
|
+
const { REDIS_PREFIX } = require('./consts');
|
|
16
|
+
const { isEndedSession, matcher } = require('./tools');
|
|
17
|
+
const { matchIp } = require('./utils/network');
|
|
18
|
+
const tokenPermissions = require('./token-permissions');
|
|
19
|
+
const { routeGrant, perRequestSurfaceAdmits, sessionTokenAdmits } = require('./api-routes/permission-map');
|
|
20
|
+
const { boundRouteBinding } = require('./api-routes/account-binding');
|
|
21
|
+
const { mcpOptions } = require('./api-routes/route-metadata');
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Builds the `validate` function of the api-token strategy.
|
|
25
|
+
*
|
|
26
|
+
* @param {Object} deps
|
|
27
|
+
* @param {Object} deps.settings - settings store (`get()`)
|
|
28
|
+
* @param {Object} deps.tokens - token store (`get()`, `validateSessionToken()`)
|
|
29
|
+
* @param {Object} deps.tokenAuditLog - per-token audit trail (`allowed()`, `denied()`)
|
|
30
|
+
* @param {Object} deps.redis - Redis client, for the template ownership lookup
|
|
31
|
+
* @param {Function} deps.checkRateLimit - async (key, count, allowed, windowSize) => { success, allowed, count, ttl }
|
|
32
|
+
* @param {Function} deps.sessionPasswordVersion - async () => the password version sessions are stamped with
|
|
33
|
+
* @param {String[]} [deps.adminAccessAddresses] - EENGINE_ADMIN_ACCESS_ADDRESSES, the admin perimeter
|
|
34
|
+
* @param {Object} deps.logger
|
|
35
|
+
* @returns {Function} async (request, token) => { isValid, credentials, artifacts }
|
|
36
|
+
*/
|
|
37
|
+
function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, checkRateLimit, sessionPasswordVersion, adminAccessAddresses, logger }) {
|
|
38
|
+
return async function validateApiToken(request, token) {
|
|
39
|
+
let disableTokens = await settings.get('disableTokens');
|
|
40
|
+
if (disableTokens && (!token || token === 'preauth')) {
|
|
41
|
+
// tokens checks are disabled, allow all if token is not set.
|
|
42
|
+
// `preauth` marks a caller that presented NO credential at all - routes that hand
|
|
43
|
+
// out lasting privilege have to be able to tell that apart from a real token.
|
|
44
|
+
return {
|
|
45
|
+
isValid: true,
|
|
46
|
+
credentials: { preauth: true },
|
|
47
|
+
artifacts: {}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Every scope a route names admits a token that holds it. Single-scope routes behave
|
|
52
|
+
// exactly as before; the MCP endpoint is the one route naming two (`scope:api` and
|
|
53
|
+
// `scope:mcp`), so both kinds of credential can open it.
|
|
54
|
+
let tags = (request.route && request.route.settings && request.route.settings.tags) || [];
|
|
55
|
+
let scopes = tags.filter(tag => tag === 'api' || /^scope:/.test(tag)).map(tag => tag.replace(/^scope:/, ''));
|
|
56
|
+
|
|
57
|
+
// The MCP endpoint (lib/api-routes/mcp-routes.js) is a protocol multiplexer with no
|
|
58
|
+
// operation of its own: every tools/call becomes an injected API request that runs
|
|
59
|
+
// this whole strategy again against the route it actually targets. Several checks
|
|
60
|
+
// below defer to that inner request, and each says so where it does.
|
|
61
|
+
const mcpEndpoint = !!mcpOptions(request.route).endpoint;
|
|
62
|
+
|
|
63
|
+
// Session tokens are refused at the MCP door rather than half-admitted: a session
|
|
64
|
+
// credential carries no bearer token the injected inner requests could forward, so
|
|
65
|
+
// it could initialize and list tools but every tools/call would die on an inner 401.
|
|
66
|
+
if (token.startsWith('sess_') && scopes.includes('api') && !mcpEndpoint) {
|
|
67
|
+
// seems like a session token
|
|
68
|
+
const session = (request.state && request.state.ee) || {};
|
|
69
|
+
|
|
70
|
+
// "Log out all sessions" has to reach this credential too. The session strategy's
|
|
71
|
+
// own passwordVersion check never runs here - an API request authenticates with
|
|
72
|
+
// this strategy and only reads the cookie for its `sid` - and validateSessionToken()
|
|
73
|
+
// slides the token's TTL on every use, so a cookie-plus-token pair left behind on a
|
|
74
|
+
// device the operator no longer controls stayed usable indefinitely after the click
|
|
75
|
+
// that was supposed to end every session. Same predicate as the session strategy,
|
|
76
|
+
// including its "only when a local password exists" condition, so a session stamped
|
|
77
|
+
// before this shipped is not force-expired.
|
|
78
|
+
if (isEndedSession(await sessionPasswordVersion(), session)) {
|
|
79
|
+
logger.warn({
|
|
80
|
+
msg: 'Session token presented for an ended session',
|
|
81
|
+
account: request.params.account,
|
|
82
|
+
method: request.route.method,
|
|
83
|
+
path: request.route.path
|
|
84
|
+
});
|
|
85
|
+
throw Boom.unauthorized('Session has ended');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
let isValidSessionToken = await tokens.validateSessionToken(session.sid, token, request.params.account, 900);
|
|
89
|
+
if (isValidSessionToken) {
|
|
90
|
+
// The credential was minted for a page inside the admin perimeter, so it is
|
|
91
|
+
// held to that perimeter too. The /v1 path it is presented on is not an admin
|
|
92
|
+
// path, so the request-level check above did not apply.
|
|
93
|
+
if (adminAccessAddresses && adminAccessAddresses.length && !matchIp(request.app.ip, adminAccessAddresses)) {
|
|
94
|
+
logger.warn({
|
|
95
|
+
msg: 'Session token presented from outside the admin address list',
|
|
96
|
+
account: request.params.account,
|
|
97
|
+
remoteAddress: request.app.ip,
|
|
98
|
+
method: request.route.method,
|
|
99
|
+
path: request.route.path
|
|
100
|
+
});
|
|
101
|
+
throw Boom.forbidden('Unauthorized address');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// A session token is bound to the account whose page minted it (checked above,
|
|
105
|
+
// against request.params.account), but it used to reach every api-tagged route
|
|
106
|
+
// naming that account - it never met the permission model at all. It lives in
|
|
107
|
+
// the page HTML where any script on the page can read it, which the HttpOnly
|
|
108
|
+
// session cookie does not, so it must not be the wider of the two credentials:
|
|
109
|
+
// SESSION_TOKEN_GRANTS is what the browser actually calls, and everything else
|
|
110
|
+
// - the account edit that rewrites a webhook target, the route that hands out
|
|
111
|
+
// the account's provider access token - is refused here.
|
|
112
|
+
if (!sessionTokenAdmits(routeGrant(request.route), { account: request.params.account })) {
|
|
113
|
+
logger.warn({
|
|
114
|
+
msg: 'Session token used outside the message browser grants',
|
|
115
|
+
account: request.params.account,
|
|
116
|
+
method: request.route.method,
|
|
117
|
+
path: request.route.path
|
|
118
|
+
});
|
|
119
|
+
throw Boom.forbidden('Unauthorized permission');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// The credential is bounded by a grant list rather than by a permissions
|
|
123
|
+
// record, so anything that keys off "is this token narrowed" cannot see it -
|
|
124
|
+
// assertNoNetworkOverride() is the one that matters, since `send/submit` is
|
|
125
|
+
// admitted above and a submit payload's `proxy` decides where the session
|
|
126
|
+
// carrying the account's SMTP credential connects.
|
|
127
|
+
request.app.sessionToken = true;
|
|
128
|
+
|
|
129
|
+
return {
|
|
130
|
+
isValid: true,
|
|
131
|
+
credentials: {},
|
|
132
|
+
artifacts: {}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
let tokenData;
|
|
138
|
+
try {
|
|
139
|
+
// The last-use record is skipped on MCP-dispatched injects: the outer /mcp
|
|
140
|
+
// request just wrote the same credential's entry, and the second write would
|
|
141
|
+
// only repeat it
|
|
142
|
+
tokenData = await tokens.get(token, false, { log: !request.app.mcpInternal, remoteAddress: request.app.ip });
|
|
143
|
+
} catch (err) {
|
|
144
|
+
// A thrown Boom reaches the client the way the scope and permission refusals
|
|
145
|
+
// below do (the api-token scheme does not catch it), so the reason travels as a
|
|
146
|
+
// machine-readable code - UnknownToken, ExpiredToken, InvalidToken - while the
|
|
147
|
+
// message stays the generic one the scheme itself would have sent. The scheme
|
|
148
|
+
// name keeps the WWW-Authenticate header the plugin's own refusal carries.
|
|
149
|
+
let error = Boom.unauthorized('Bad token', 'Bearer');
|
|
150
|
+
if (err.code) {
|
|
151
|
+
error.output.payload.code = err.code;
|
|
152
|
+
}
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Bind the token hash (id) to the request logger so it is included in the per-request
|
|
157
|
+
// log entry, allowing API requests to be correlated to the token that made them.
|
|
158
|
+
if (request.logger && typeof request.logger.setBindings === 'function') {
|
|
159
|
+
request.logger.setBindings({ tokenId: tokenData.id, tokenAccount: tokenData.account || null });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const grant = routeGrant(request.route);
|
|
163
|
+
|
|
164
|
+
// This strategy runs before route validation, so `request.query` is whatever the client
|
|
165
|
+
// sent: a repeated `?account=` arrives as an array. Only a string can name an account,
|
|
166
|
+
// and this value is persisted into the audit log, so anything else is not one.
|
|
167
|
+
const queryAccount = request.query && typeof request.query.account === 'string' ? request.query.account : null;
|
|
168
|
+
|
|
169
|
+
// Shared by every audit entry below, so an allow and a deny describe the same request.
|
|
170
|
+
// Built before the first check that can refuse: a rejection is the strongest signal of
|
|
171
|
+
// credential misuse there is, and a trail that only held the calls that succeeded would
|
|
172
|
+
// be silent about exactly the ones worth looking at.
|
|
173
|
+
const auditEntry = {
|
|
174
|
+
tokenId: tokenData.id,
|
|
175
|
+
ip: request.app.ip,
|
|
176
|
+
method: request.route.method,
|
|
177
|
+
path: request.route.path,
|
|
178
|
+
action: grant.action,
|
|
179
|
+
group: grant.group,
|
|
180
|
+
// The account the REQUEST addressed, which is not always the one in the path: the
|
|
181
|
+
// routes that take it as a query argument are the ones a bound token gets refused
|
|
182
|
+
// on, and falling straight through to the token's own account recorded a
|
|
183
|
+
// cross-account attempt against the account it was entitled to reach - the opposite
|
|
184
|
+
// of what the entry exists to show. The token's account is still the answer for the
|
|
185
|
+
// routes that name no account at all.
|
|
186
|
+
//
|
|
187
|
+
// The refusals below log this field rather than re-deriving it, so the application
|
|
188
|
+
// log and the audit row cannot disagree about which account a denial concerned.
|
|
189
|
+
account: (request.params && request.params.account) || queryAccount || tokenData.account || null
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
// `mcp` and `mcp-manage` are surface scopes like `smtp`: each admits exactly the API
|
|
193
|
+
// operations its half of the MCP tool set wraps (perRequestSurfaceAdmits over
|
|
194
|
+
// SURFACE_GRANTS), and only on requests the MCP endpoint dispatched itself -
|
|
195
|
+
// request.app.mcpInternal is set by lib/mcp/inject.js and cannot be set from the
|
|
196
|
+
// network, so an mcp-scoped token presented to plain REST is refused here like any
|
|
197
|
+
// other missing scope.
|
|
198
|
+
const mcpSurfaceAdmits = scopes.includes('api') && !!request.app.mcpInternal && perRequestSurfaceAdmits(tokenData.scopes, grant);
|
|
199
|
+
|
|
200
|
+
const hasRequiredScope =
|
|
201
|
+
!scopes.length || !tokenData.scopes || tokenData.scopes.includes('*') || tokenData.scopes.some(entry => scopes.includes(entry)) || mcpSurfaceAdmits;
|
|
202
|
+
|
|
203
|
+
if (!hasRequiredScope) {
|
|
204
|
+
// failed scope validation
|
|
205
|
+
logger.warn({
|
|
206
|
+
msg: 'Trying to use invalid scope for a token',
|
|
207
|
+
tokenAccount: tokenData.account,
|
|
208
|
+
tokenId: tokenData.id,
|
|
209
|
+
requestedScope: scopes.join(', '),
|
|
210
|
+
tokenScopes: tokenData.scopes
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
tokenAuditLog.denied(auditEntry, 'scope');
|
|
214
|
+
|
|
215
|
+
let error = Boom.forbidden('Unauthorized scope');
|
|
216
|
+
error.output.payload.requestedScope = scopes.join(', ');
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Narrowing below the scope. Runs after the scope check and before the account binding,
|
|
221
|
+
// so the order is: token resolved, scope, permissions, account, restrictions.
|
|
222
|
+
//
|
|
223
|
+
// Before the account switch on purpose - that switch reads the account from the query or
|
|
224
|
+
// from a Redis membership check for the three /v1/templates special cases, and none of
|
|
225
|
+
// that should happen for a request the permissions already refuse.
|
|
226
|
+
//
|
|
227
|
+
// Only subtracts: a token with no `permissions` field takes the allowed path, which is
|
|
228
|
+
// every token issued before this shipped.
|
|
229
|
+
// The MCP door defers this check: its own routeGrant() resolves to no group on
|
|
230
|
+
// purpose, and the operation a narrowed token must hold a grant for is the injected
|
|
231
|
+
// inner request, which re-runs this strategy with the real route.
|
|
232
|
+
const permissionCheck = mcpEndpoint ? { allowed: true } : tokenPermissions.check({ tokenData, operation: grant });
|
|
233
|
+
if (!permissionCheck.allowed) {
|
|
234
|
+
logger.warn({
|
|
235
|
+
msg: 'Token permissions do not allow this operation',
|
|
236
|
+
tokenAccount: tokenData.account,
|
|
237
|
+
tokenId: tokenData.id,
|
|
238
|
+
account: auditEntry.account,
|
|
239
|
+
reason: permissionCheck.reason,
|
|
240
|
+
required: permissionCheck.required
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
let error = Boom.forbidden('Unauthorized permission');
|
|
244
|
+
// Mirrors how the scope failure above attaches requestedScope: an agent that gets a
|
|
245
|
+
// 403 needs to know WHICH grant it lacked, not just that it lacked one.
|
|
246
|
+
// A refused call is the interesting record, so it is logged before the throw
|
|
247
|
+
tokenAuditLog.denied(auditEntry, permissionCheck.reason);
|
|
248
|
+
|
|
249
|
+
error.output.payload.requiredPermission = permissionCheck.required;
|
|
250
|
+
throw error;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
if (tokenData.account && mcpEndpoint) {
|
|
254
|
+
// The door names no account, so the binding cannot be checked here; it is
|
|
255
|
+
// enforced on every injected inner request, which does name one. Parked on the
|
|
256
|
+
// request so the MCP layer can seed resources/list and the agent instructions
|
|
257
|
+
// for a bound credential.
|
|
258
|
+
request.app.mcpBoundAccount = tokenData.account;
|
|
259
|
+
} else if (tokenData.account) {
|
|
260
|
+
// account token
|
|
261
|
+
|
|
262
|
+
let accountIdSource;
|
|
263
|
+
|
|
264
|
+
// Routes that carry an account component somewhere other than their URL params, named
|
|
265
|
+
// by lib/api-routes/account-binding.js. The table is shared with the MCP tool registry,
|
|
266
|
+
// which has to advertise exactly the tools a bound credential can actually call; the
|
|
267
|
+
// resolution of each kind stays here, where the request is.
|
|
268
|
+
switch (boundRouteBinding(request.method, request.route.path)) {
|
|
269
|
+
case 'query':
|
|
270
|
+
// `/v1/tokens` is in the table because it replaced
|
|
271
|
+
// GET /v1/tokens/account/{account}, which carried the account in the path and so
|
|
272
|
+
// reached a bound token's own tokens through the default branch below - as its
|
|
273
|
+
// deprecated alias registration still does. Both stay under the same rule as
|
|
274
|
+
// everything else: the argument has to name the token's own account, and
|
|
275
|
+
// omitting it still refuses, because a bound credential must not enumerate the
|
|
276
|
+
// instance.
|
|
277
|
+
accountIdSource = queryAccount;
|
|
278
|
+
break;
|
|
279
|
+
|
|
280
|
+
case 'record': {
|
|
281
|
+
let isAccountTemplate =
|
|
282
|
+
request.params.template && (await redis.sismember(`${REDIS_PREFIX}tpl:${tokenData.account}:i`, request.params.template));
|
|
283
|
+
if (isAccountTemplate) {
|
|
284
|
+
accountIdSource = tokenData.account;
|
|
285
|
+
}
|
|
286
|
+
break;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
case 'token':
|
|
290
|
+
request.app.enforceAccount = tokenData.account;
|
|
291
|
+
accountIdSource = tokenData.account;
|
|
292
|
+
break;
|
|
293
|
+
|
|
294
|
+
default:
|
|
295
|
+
accountIdSource = request.params && request.params.account;
|
|
296
|
+
break;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
if (accountIdSource !== tokenData.account) {
|
|
300
|
+
logger.warn({
|
|
301
|
+
msg: 'Trying to use invalid account for a token',
|
|
302
|
+
tokenAccount: tokenData.account,
|
|
303
|
+
tokenId: tokenData.id,
|
|
304
|
+
account: auditEntry.account
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
tokenAuditLog.denied(auditEntry, 'account');
|
|
308
|
+
|
|
309
|
+
let error = Boom.forbidden('Unauthorized account');
|
|
310
|
+
throw error;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (tokenData.restrictions) {
|
|
315
|
+
if (tokenData.restrictions.addresses && !matchIp(request.app.ip, tokenData.restrictions.addresses)) {
|
|
316
|
+
logger.warn({
|
|
317
|
+
msg: 'Trying to use invalid IP for a token',
|
|
318
|
+
tokenAccount: tokenData.account,
|
|
319
|
+
tokenId: tokenData.id,
|
|
320
|
+
account: auditEntry.account,
|
|
321
|
+
remoteAddress: request.app.ip,
|
|
322
|
+
addressAllowlist: tokenData.restrictions.addresses
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
tokenAuditLog.denied(auditEntry, 'address');
|
|
326
|
+
|
|
327
|
+
let error = Boom.forbidden('Unauthorized address');
|
|
328
|
+
error.output.payload.remoteAddress = request.app.ip;
|
|
329
|
+
throw error;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (
|
|
333
|
+
tokenData.restrictions.referrers &&
|
|
334
|
+
tokenData.restrictions.referrers.length &&
|
|
335
|
+
!matcher(tokenData.restrictions.referrers, request.headers.referer)
|
|
336
|
+
) {
|
|
337
|
+
logger.warn({
|
|
338
|
+
msg: 'Trying to use invalid referer for a token',
|
|
339
|
+
tokenAccount: tokenData.account,
|
|
340
|
+
tokenId: tokenData.id,
|
|
341
|
+
account: auditEntry.account,
|
|
342
|
+
referer: request.headers.referer,
|
|
343
|
+
referrerAllowlist: tokenData.restrictions.referrers
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
tokenAuditLog.denied(auditEntry, 'referrer');
|
|
347
|
+
|
|
348
|
+
let error = Boom.forbidden('Unauthorized referrer');
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Skipped on MCP-dispatched injects like the last-use record above: the outer
|
|
353
|
+
// /mcp request already spent one unit of this token's budget at the door, and
|
|
354
|
+
// counting the inner request too silently halved every restricted token's
|
|
355
|
+
// effective limit over MCP.
|
|
356
|
+
if (tokenData.restrictions.rateLimit && !request.app.mcpInternal) {
|
|
357
|
+
let rateLimit = await checkRateLimit(
|
|
358
|
+
`api:${tokenData.id}`,
|
|
359
|
+
1,
|
|
360
|
+
tokenData.restrictions.rateLimit.maxRequests,
|
|
361
|
+
tokenData.restrictions.rateLimit.timeWindow
|
|
362
|
+
);
|
|
363
|
+
|
|
364
|
+
if (!rateLimit.success) {
|
|
365
|
+
logger.warn({ msg: 'Rate limited', token: tokenData.id, rateLimit });
|
|
366
|
+
tokenAuditLog.denied(auditEntry, 'rateLimit');
|
|
367
|
+
|
|
368
|
+
let error = Boom.tooManyRequests('Rate limit exceeded');
|
|
369
|
+
error.output.payload.ttl = Math.ceil(rateLimit.ttl);
|
|
370
|
+
error.output.headers = {
|
|
371
|
+
'X-RateLimit-Limit': rateLimit.allowed,
|
|
372
|
+
'X-RateLimit-Reset': Math.ceil(rateLimit.ttl),
|
|
373
|
+
// The conventional header for a 429, so a generic HTTP client backs
|
|
374
|
+
// off without knowing about the ttl field in the body
|
|
375
|
+
'Retry-After': Math.ceil(rateLimit.ttl)
|
|
376
|
+
};
|
|
377
|
+
throw error;
|
|
378
|
+
} else {
|
|
379
|
+
request.app.rateLimitHeaders = {
|
|
380
|
+
'X-RateLimit-Limit': rateLimit.allowed,
|
|
381
|
+
'X-RateLimit-Reset': Math.ceil(rateLimit.ttl),
|
|
382
|
+
'X-RateLimit-Remaining': rateLimit.allowed - rateLimit.count
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// The one point every accepted token request passes. "allowed" means the credential was
|
|
389
|
+
// accepted, not that the request succeeded: this runs in the auth strategy, before
|
|
390
|
+
// payload validation and the handler, so a call recorded here can still end in a 400 or
|
|
391
|
+
// a 404. That is the right boundary for a credential trail - it answers what the token
|
|
392
|
+
// was permitted to attempt.
|
|
393
|
+
//
|
|
394
|
+
// Except at the MCP door, where "allowed" describes no operation at all (the permission
|
|
395
|
+
// check above was deferred): every tool call writes its own row as the injected API
|
|
396
|
+
// request it becomes, and a second content-free row per call would halve the capped
|
|
397
|
+
// audit retention for MCP traffic. Denials at the door are still recorded above.
|
|
398
|
+
if (!mcpEndpoint) {
|
|
399
|
+
tokenAuditLog.allowed(auditEntry);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return { isValid: true, credentials: { token }, artifacts: tokenData };
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
module.exports = { createApiTokenValidator };
|
|
@@ -1120,6 +1120,38 @@ async function resolveUsingAutodiscovery(email, ctx, credentials) {
|
|
|
1120
1120
|
}
|
|
1121
1121
|
}
|
|
1122
1122
|
|
|
1123
|
+
// Ports where TLS starts with the connection rather than through STARTTLS
|
|
1124
|
+
const IMPLICIT_TLS_PORTS = new Set([993, 465]);
|
|
1125
|
+
|
|
1126
|
+
/**
|
|
1127
|
+
* Reads the TLS mode off a POX `<Protocol>` entry.
|
|
1128
|
+
*
|
|
1129
|
+
* `<Encryption>` (None, SSL, TLS, Auto) overrides `<SSL>` when both are present, per the POX
|
|
1130
|
+
* schema. "TLS" is STARTTLS on the cleartext port, and "Auto" leaves the choice to the client,
|
|
1131
|
+
* so it is decided by the port.
|
|
1132
|
+
*
|
|
1133
|
+
* @param {Object} entry - Parsed `<Protocol>` fields
|
|
1134
|
+
* @param {Number} [port] - The listed port
|
|
1135
|
+
* @returns {Boolean|undefined} true for implicit TLS, false for none or STARTTLS, undefined when neither element says
|
|
1136
|
+
*/
|
|
1137
|
+
function poxSecure(entry, port) {
|
|
1138
|
+
if (entry.encryption && typeof entry.encryption === 'string') {
|
|
1139
|
+
switch (entry.encryption.trim().toLowerCase()) {
|
|
1140
|
+
case 'ssl':
|
|
1141
|
+
return true;
|
|
1142
|
+
case 'tls':
|
|
1143
|
+
case 'none':
|
|
1144
|
+
return false;
|
|
1145
|
+
case 'auto':
|
|
1146
|
+
return IMPLICIT_TLS_PORTS.has(port);
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
if (entry.ssl && typeof entry.ssl === 'string') {
|
|
1150
|
+
return entry.ssl === 'on';
|
|
1151
|
+
}
|
|
1152
|
+
return undefined;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1123
1155
|
function processAutodiscoverResponse(text, source) {
|
|
1124
1156
|
let json = parseXml(text);
|
|
1125
1157
|
|
|
@@ -1144,7 +1176,7 @@ function processAutodiscoverResponse(text, source) {
|
|
|
1144
1176
|
|
|
1145
1177
|
accountRow.protocol.forEach(protocolRow => {
|
|
1146
1178
|
let entry = {};
|
|
1147
|
-
for (let key of ['type', 'server', 'loginname', 'port', 'ssl']) {
|
|
1179
|
+
for (let key of ['type', 'server', 'loginname', 'port', 'ssl', 'encryption']) {
|
|
1148
1180
|
if (protocolRow && Array.isArray(protocolRow[key]) && protocolRow[key].length) {
|
|
1149
1181
|
entry[key] = protocolRow[key][0];
|
|
1150
1182
|
}
|
|
@@ -1161,8 +1193,9 @@ function processAutodiscoverResponse(text, source) {
|
|
|
1161
1193
|
if (entry.port && (typeof entry.port === 'string' || (typeof entry.port === 'number' && !isNaN(entry.port)))) {
|
|
1162
1194
|
res.port = Number(entry.port);
|
|
1163
1195
|
}
|
|
1164
|
-
|
|
1165
|
-
|
|
1196
|
+
let secure = poxSecure(entry, res.port);
|
|
1197
|
+
if (typeof secure === 'boolean') {
|
|
1198
|
+
res.secure = secure;
|
|
1166
1199
|
}
|
|
1167
1200
|
if (entry.loginname && typeof entry.loginname === 'string') {
|
|
1168
1201
|
res.auth = { user: entry.loginname };
|
package/lib/consts.js
CHANGED
|
@@ -89,6 +89,11 @@ module.exports = {
|
|
|
89
89
|
DEFAULT_EXPORT_MAX_CONCURRENT: 2,
|
|
90
90
|
DEFAULT_EXPORT_MAX_GLOBAL_CONCURRENT: 8,
|
|
91
91
|
DEFAULT_EXPORT_MAX_MESSAGE_SIZE: 50 * 1024 * 1024, // 50MB
|
|
92
|
+
|
|
93
|
+
// The export worker's BullMQ lock, renewed every half of it while an export runs, and how
|
|
94
|
+
// often the worker looks for a job whose lock lapsed (its worker died). See workers/export.js
|
|
95
|
+
EXPORT_LOCK_DURATION: 2 * 60 * 1000,
|
|
96
|
+
EXPORT_STALLED_INTERVAL: 60 * 1000,
|
|
92
97
|
DEFAULT_GMAIL_EXPORT_BATCH_SIZE: 10,
|
|
93
98
|
DEFAULT_OUTLOOK_EXPORT_BATCH_SIZE: 20,
|
|
94
99
|
|