emailengine-app 2.89.0 → 2.90.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/.ncurc.js +19 -8
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +44 -0
- package/Dockerfile +5 -1
- package/bin/healthcheck.js +1 -1
- package/copy-static-files.sh +0 -8
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +1 -4
- package/lib/account/field-codec.js +396 -0
- package/lib/account.js +158 -453
- package/lib/api-routes/account-routes.js +42 -6
- package/lib/api-routes/route-metadata.js +5 -2
- package/lib/api-routes/submit-routes.js +15 -2
- package/lib/api-token-auth.js +342 -274
- package/lib/arf-detect.js +174 -149
- package/lib/attachment-size.js +29 -0
- package/lib/autodetect-imap-settings.js +83 -234
- package/lib/consts.js +1 -5
- package/lib/db.js +1 -4
- package/lib/email-client/base-client.js +907 -780
- package/lib/email-client/gmail-client.js +557 -450
- package/lib/email-client/imap/cid-parts.js +61 -0
- package/lib/email-client/imap/mailbox.js +376 -422
- package/lib/email-client/imap/sync-operations.js +239 -178
- package/lib/email-client/new-message-steps.js +168 -2
- package/lib/email-client/outlook/graph-message.js +266 -0
- package/lib/email-client/outlook/subscription-expiry.js +30 -0
- package/lib/email-client/outlook-client.js +652 -808
- package/lib/get-raw-email.js +338 -232
- package/lib/get-secret.js +1 -4
- package/lib/license-subscription.js +60 -0
- package/lib/load-env.js +48 -0
- package/lib/logger.js +1 -4
- package/lib/mcp/tools.js +244 -207
- package/lib/metric-values.js +76 -0
- package/lib/metrics.js +320 -0
- package/lib/oauth/gmail.js +39 -120
- package/lib/oauth/http-request.js +195 -0
- package/lib/oauth/mail-ru.js +24 -58
- package/lib/oauth/outlook.js +37 -137
- package/lib/oauth/pubsub/google.js +176 -117
- package/lib/oauth2-apps.js +440 -463
- package/lib/openapi/build-document.js +10 -10
- package/lib/read-env-value.js +1 -1
- package/lib/route-descriptors.js +78 -0
- package/lib/schemas.js +10 -1
- package/lib/sentry-integrations.js +299 -0
- package/lib/sentry.js +75 -27
- package/lib/sso-routes.js +249 -0
- package/lib/sso.js +29 -6
- package/lib/ui-routes/account-edit-form.js +198 -0
- package/lib/ui-routes/account-page.js +241 -0
- package/lib/ui-routes/account-routes.js +12 -318
- package/lib/ui-routes/auth-routes.js +10 -10
- package/lib/ui-view-context.js +328 -0
- package/lib/utils/public-suffix.js +22 -101
- package/lib/web-safe-html.js +20 -7
- package/lib/worker-metrics.js +82 -0
- package/list-generate.js +2 -5
- package/package.json +23 -19
- package/sbom.json +267 -908
- package/scripts/refresh-test-tokens.js +1 -1
- package/server.js +320 -676
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +18 -0
- package/static/js/ee-client.js +2619 -645
- package/static/js/ui.js +12 -2
- package/static/licenses.html +219 -737
- package/translations/messages.pot +64 -53
- package/views/accounts/browse.hbs +19 -1
- package/workers/api.js +20 -451
- package/data/public_suffix_list.dat +0 -16698
package/lib/api-token-auth.js
CHANGED
|
@@ -46,106 +46,82 @@ function createApiTokenValidator({
|
|
|
46
46
|
adminAccessAddresses,
|
|
47
47
|
logger
|
|
48
48
|
}) {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
49
|
+
async function authenticateSessionToken(request, token) {
|
|
50
|
+
// seems like a session token
|
|
51
|
+
const session = (request.state && request.state.ee) || {};
|
|
52
|
+
|
|
53
|
+
// "Log out all sessions" has to reach this credential too. The session strategy's
|
|
54
|
+
// own passwordVersion check never runs here - an API request authenticates with
|
|
55
|
+
// this strategy and only reads the cookie for its `sid` - and validateSessionToken()
|
|
56
|
+
// slides the token's TTL on every use, so a cookie-plus-token pair left behind on a
|
|
57
|
+
// device the operator no longer controls stayed usable indefinitely after the click
|
|
58
|
+
// that was supposed to end every session. Same predicate as the session strategy,
|
|
59
|
+
// including its "only when a local password exists" condition, so a session stamped
|
|
60
|
+
// before this shipped is not force-expired.
|
|
61
|
+
// The same goes for an SSO user the identity provider's allow-list no longer admits
|
|
62
|
+
if (isEndedSession(await sessionPasswordVersion(), session) || !sessionAdmitted(session)) {
|
|
63
|
+
logger.warn({
|
|
64
|
+
msg: 'Session token presented for an ended session',
|
|
65
|
+
account: request.params.account,
|
|
66
|
+
method: request.route.method,
|
|
67
|
+
path: request.route.path
|
|
68
|
+
});
|
|
69
|
+
throw Boom.unauthorized('Session has ended');
|
|
60
70
|
}
|
|
61
71
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
// The MCP endpoint (lib/api-routes/mcp-routes.js) is a protocol multiplexer with no
|
|
69
|
-
// operation of its own: every tools/call becomes an injected API request that runs
|
|
70
|
-
// this whole strategy again against the route it actually targets. Several checks
|
|
71
|
-
// below defer to that inner request, and each says so where it does.
|
|
72
|
-
const mcpEndpoint = !!mcpOptions(request.route).endpoint;
|
|
72
|
+
let isValidSessionToken = await tokens.validateSessionToken(session.sid, token, request.params.account, 900);
|
|
73
|
+
if (!isValidSessionToken) {
|
|
74
|
+
// not a live session token, the token store decides
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
73
77
|
|
|
74
|
-
//
|
|
75
|
-
//
|
|
76
|
-
//
|
|
77
|
-
if (
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
// including its "only when a local password exists" condition, so a session stamped
|
|
88
|
-
// before this shipped is not force-expired.
|
|
89
|
-
// The same goes for an SSO user the identity provider's allow-list no longer admits
|
|
90
|
-
if (isEndedSession(await sessionPasswordVersion(), session) || !sessionAdmitted(session)) {
|
|
91
|
-
logger.warn({
|
|
92
|
-
msg: 'Session token presented for an ended session',
|
|
93
|
-
account: request.params.account,
|
|
94
|
-
method: request.route.method,
|
|
95
|
-
path: request.route.path
|
|
96
|
-
});
|
|
97
|
-
throw Boom.unauthorized('Session has ended');
|
|
98
|
-
}
|
|
78
|
+
// The credential was minted for a page inside the admin perimeter, so it is
|
|
79
|
+
// held to that perimeter too. The /v1 path it is presented on is not an admin
|
|
80
|
+
// path, so the request-level check above did not apply.
|
|
81
|
+
if (adminAccessAddresses && adminAccessAddresses.length && !matchIp(request.app.ip, adminAccessAddresses)) {
|
|
82
|
+
logger.warn({
|
|
83
|
+
msg: 'Session token presented from outside the admin address list',
|
|
84
|
+
account: request.params.account,
|
|
85
|
+
remoteAddress: request.app.ip,
|
|
86
|
+
method: request.route.method,
|
|
87
|
+
path: request.route.path
|
|
88
|
+
});
|
|
89
|
+
throw Boom.forbidden('Unauthorized address');
|
|
90
|
+
}
|
|
99
91
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
// A session token is bound to the account whose page minted it (checked above,
|
|
117
|
-
// against request.params.account), but it used to reach every api-tagged route
|
|
118
|
-
// naming that account - it never met the permission model at all. It lives in
|
|
119
|
-
// the page HTML where any script on the page can read it, which the HttpOnly
|
|
120
|
-
// session cookie does not, so it must not be the wider of the two credentials:
|
|
121
|
-
// SESSION_TOKEN_GRANTS is what the browser actually calls, and everything else
|
|
122
|
-
// - the account edit that rewrites a webhook target, the route that hands out
|
|
123
|
-
// the account's provider access token - is refused here.
|
|
124
|
-
if (!sessionTokenAdmits(routeGrant(request.route), { account: request.params.account })) {
|
|
125
|
-
logger.warn({
|
|
126
|
-
msg: 'Session token used outside the message browser grants',
|
|
127
|
-
account: request.params.account,
|
|
128
|
-
method: request.route.method,
|
|
129
|
-
path: request.route.path
|
|
130
|
-
});
|
|
131
|
-
throw Boom.forbidden('Unauthorized permission');
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// The credential is bounded by a grant list rather than by a permissions
|
|
135
|
-
// record, so anything that keys off "is this token narrowed" cannot see it -
|
|
136
|
-
// assertNoNetworkOverride() is the one that matters, since `send/submit` is
|
|
137
|
-
// admitted above and a submit payload's `proxy` decides where the session
|
|
138
|
-
// carrying the account's SMTP credential connects.
|
|
139
|
-
request.app.sessionToken = true;
|
|
140
|
-
|
|
141
|
-
return {
|
|
142
|
-
isValid: true,
|
|
143
|
-
credentials: {},
|
|
144
|
-
artifacts: {}
|
|
145
|
-
};
|
|
146
|
-
}
|
|
92
|
+
// A session token is bound to the account whose page minted it (checked above,
|
|
93
|
+
// against request.params.account), but it used to reach every api-tagged route
|
|
94
|
+
// naming that account - it never met the permission model at all. It lives in
|
|
95
|
+
// the page HTML where any script on the page can read it, which the HttpOnly
|
|
96
|
+
// session cookie does not, so it must not be the wider of the two credentials:
|
|
97
|
+
// SESSION_TOKEN_GRANTS is what the browser actually calls, and everything else
|
|
98
|
+
// - the account edit that rewrites a webhook target, the route that hands out
|
|
99
|
+
// the account's provider access token - is refused here.
|
|
100
|
+
if (!sessionTokenAdmits(routeGrant(request.route), { account: request.params.account })) {
|
|
101
|
+
logger.warn({
|
|
102
|
+
msg: 'Session token used outside the message browser grants',
|
|
103
|
+
account: request.params.account,
|
|
104
|
+
method: request.route.method,
|
|
105
|
+
path: request.route.path
|
|
106
|
+
});
|
|
107
|
+
throw Boom.forbidden('Unauthorized permission');
|
|
147
108
|
}
|
|
148
109
|
|
|
110
|
+
// The credential is bounded by a grant list rather than by a permissions
|
|
111
|
+
// record, so anything that keys off "is this token narrowed" cannot see it -
|
|
112
|
+
// assertNoNetworkOverride() is the one that matters, since `send/submit` is
|
|
113
|
+
// admitted above and a submit payload's `proxy` decides where the session
|
|
114
|
+
// carrying the account's SMTP credential connects.
|
|
115
|
+
request.app.sessionToken = true;
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
isValid: true,
|
|
119
|
+
credentials: {},
|
|
120
|
+
artifacts: {}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function loadTokenData(request, token) {
|
|
149
125
|
let tokenData;
|
|
150
126
|
try {
|
|
151
127
|
// The last-use record is skipped on MCP-dispatched injects: the outer /mcp
|
|
@@ -171,36 +147,10 @@ function createApiTokenValidator({
|
|
|
171
147
|
request.logger.setBindings({ tokenId: tokenData.id, tokenAccount: tokenData.account || null });
|
|
172
148
|
}
|
|
173
149
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
// This strategy runs before route validation, so `request.query` is whatever the client
|
|
177
|
-
// sent: a repeated `?account=` arrives as an array. Only a string can name an account,
|
|
178
|
-
// and this value is persisted into the audit log, so anything else is not one.
|
|
179
|
-
const queryAccount = request.query && typeof request.query.account === 'string' ? request.query.account : null;
|
|
180
|
-
|
|
181
|
-
// Shared by every audit entry below, so an allow and a deny describe the same request.
|
|
182
|
-
// Built before the first check that can refuse: a rejection is the strongest signal of
|
|
183
|
-
// credential misuse there is, and a trail that only held the calls that succeeded would
|
|
184
|
-
// be silent about exactly the ones worth looking at.
|
|
185
|
-
const auditEntry = {
|
|
186
|
-
tokenId: tokenData.id,
|
|
187
|
-
ip: request.app.ip,
|
|
188
|
-
method: request.route.method,
|
|
189
|
-
path: request.route.path,
|
|
190
|
-
action: grant.action,
|
|
191
|
-
group: grant.group,
|
|
192
|
-
// The account the REQUEST addressed, which is not always the one in the path: the
|
|
193
|
-
// routes that take it as a query argument are the ones a bound token gets refused
|
|
194
|
-
// on, and falling straight through to the token's own account recorded a
|
|
195
|
-
// cross-account attempt against the account it was entitled to reach - the opposite
|
|
196
|
-
// of what the entry exists to show. The token's account is still the answer for the
|
|
197
|
-
// routes that name no account at all.
|
|
198
|
-
//
|
|
199
|
-
// The refusals below log this field rather than re-deriving it, so the application
|
|
200
|
-
// log and the audit row cannot disagree about which account a denial concerned.
|
|
201
|
-
account: (request.params && request.params.account) || queryAccount || tokenData.account || null
|
|
202
|
-
};
|
|
150
|
+
return tokenData;
|
|
151
|
+
}
|
|
203
152
|
|
|
153
|
+
function assertScope(request, tokenData, scopes, grant, auditEntry) {
|
|
204
154
|
// `mcp` and `mcp-manage` are surface scopes like `smtp`: each admits exactly the API
|
|
205
155
|
// operations its half of the MCP tool set wraps (perRequestSurfaceAdmits over
|
|
206
156
|
// SURFACE_GRANTS), and only on requests the MCP endpoint dispatched itself -
|
|
@@ -212,23 +162,27 @@ function createApiTokenValidator({
|
|
|
212
162
|
const hasRequiredScope =
|
|
213
163
|
!scopes.length || !tokenData.scopes || tokenData.scopes.includes('*') || tokenData.scopes.some(entry => scopes.includes(entry)) || mcpSurfaceAdmits;
|
|
214
164
|
|
|
215
|
-
if (
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
msg: 'Trying to use invalid scope for a token',
|
|
219
|
-
tokenAccount: tokenData.account,
|
|
220
|
-
tokenId: tokenData.id,
|
|
221
|
-
requestedScope: scopes.join(', '),
|
|
222
|
-
tokenScopes: tokenData.scopes
|
|
223
|
-
});
|
|
165
|
+
if (hasRequiredScope) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
224
168
|
|
|
225
|
-
|
|
169
|
+
// failed scope validation
|
|
170
|
+
logger.warn({
|
|
171
|
+
msg: 'Trying to use invalid scope for a token',
|
|
172
|
+
tokenAccount: tokenData.account,
|
|
173
|
+
tokenId: tokenData.id,
|
|
174
|
+
requestedScope: scopes.join(', '),
|
|
175
|
+
tokenScopes: tokenData.scopes
|
|
176
|
+
});
|
|
226
177
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
178
|
+
tokenAuditLog.denied(auditEntry, 'scope');
|
|
179
|
+
|
|
180
|
+
let error = Boom.forbidden('Unauthorized scope');
|
|
181
|
+
error.output.payload.requestedScope = scopes.join(', ');
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
231
184
|
|
|
185
|
+
function assertPermission(tokenData, grant, auditEntry, mcpEndpoint) {
|
|
232
186
|
// Narrowing below the scope. Runs after the scope check and before the account binding,
|
|
233
187
|
// so the order is: token resolved, scope, permissions, account, restrictions.
|
|
234
188
|
//
|
|
@@ -242,162 +196,236 @@ function createApiTokenValidator({
|
|
|
242
196
|
// purpose, and the operation a narrowed token must hold a grant for is the injected
|
|
243
197
|
// inner request, which re-runs this strategy with the real route.
|
|
244
198
|
const permissionCheck = mcpEndpoint ? { allowed: true } : tokenPermissions.check({ tokenData, operation: grant });
|
|
245
|
-
if (
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
tokenAccount: tokenData.account,
|
|
249
|
-
tokenId: tokenData.id,
|
|
250
|
-
account: auditEntry.account,
|
|
251
|
-
reason: permissionCheck.reason,
|
|
252
|
-
required: permissionCheck.required
|
|
253
|
-
});
|
|
199
|
+
if (permissionCheck.allowed) {
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
254
202
|
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
203
|
+
logger.warn({
|
|
204
|
+
msg: 'Token permissions do not allow this operation',
|
|
205
|
+
tokenAccount: tokenData.account,
|
|
206
|
+
tokenId: tokenData.id,
|
|
207
|
+
account: auditEntry.account,
|
|
208
|
+
reason: permissionCheck.reason,
|
|
209
|
+
required: permissionCheck.required
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
let error = Boom.forbidden('Unauthorized permission');
|
|
213
|
+
// Mirrors how the scope failure above attaches requestedScope: an agent that gets a
|
|
214
|
+
// 403 needs to know WHICH grant it lacked, not just that it lacked one.
|
|
215
|
+
// A refused call is the interesting record, so it is logged before the throw
|
|
216
|
+
tokenAuditLog.denied(auditEntry, permissionCheck.reason);
|
|
217
|
+
|
|
218
|
+
error.output.payload.requiredPermission = permissionCheck.required;
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// The account a bound token's request addresses. Routes that carry an account component
|
|
223
|
+
// somewhere other than their URL params, named by lib/api-routes/account-binding.js. The
|
|
224
|
+
// table is shared with the MCP tool registry, which has to advertise exactly the tools a bound
|
|
225
|
+
// credential can actually call; the resolution of each kind stays here, where the request is.
|
|
226
|
+
async function resolveRequestAccount(request, tokenData, queryAccount) {
|
|
227
|
+
switch (boundRouteBinding(request.method, request.route.path)) {
|
|
228
|
+
case 'query':
|
|
229
|
+
// `/v1/tokens` is in the table because it replaced
|
|
230
|
+
// GET /v1/tokens/account/{account}, which carried the account in the path and so
|
|
231
|
+
// reached a bound token's own tokens through the default branch below - as its
|
|
232
|
+
// deprecated alias registration still does. Both stay under the same rule as
|
|
233
|
+
// everything else: the argument has to name the token's own account, and
|
|
234
|
+
// omitting it still refuses, because a bound credential must not enumerate the
|
|
235
|
+
// instance.
|
|
236
|
+
return queryAccount;
|
|
237
|
+
|
|
238
|
+
case 'record': {
|
|
239
|
+
let isAccountTemplate =
|
|
240
|
+
request.params.template && (await redis.sismember(`${REDIS_PREFIX}tpl:${tokenData.account}:i`, request.params.template));
|
|
241
|
+
return isAccountTemplate ? tokenData.account : undefined;
|
|
242
|
+
}
|
|
260
243
|
|
|
261
|
-
|
|
262
|
-
|
|
244
|
+
case 'token':
|
|
245
|
+
request.app.enforceAccount = tokenData.account;
|
|
246
|
+
return tokenData.account;
|
|
247
|
+
|
|
248
|
+
default:
|
|
249
|
+
return request.params && request.params.account;
|
|
263
250
|
}
|
|
251
|
+
}
|
|
264
252
|
|
|
265
|
-
|
|
253
|
+
async function assertAccountBinding(request, tokenData, queryAccount, auditEntry, mcpEndpoint) {
|
|
254
|
+
if (!tokenData.account) {
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (mcpEndpoint) {
|
|
266
259
|
// The door names no account, so the binding cannot be checked here; it is
|
|
267
260
|
// enforced on every injected inner request, which does name one. Parked on the
|
|
268
261
|
// request so the MCP layer can seed resources/list and the agent instructions
|
|
269
262
|
// for a bound credential.
|
|
270
263
|
request.app.mcpBoundAccount = tokenData.account;
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
let accountIdSource;
|
|
275
|
-
|
|
276
|
-
// Routes that carry an account component somewhere other than their URL params, named
|
|
277
|
-
// by lib/api-routes/account-binding.js. The table is shared with the MCP tool registry,
|
|
278
|
-
// which has to advertise exactly the tools a bound credential can actually call; the
|
|
279
|
-
// resolution of each kind stays here, where the request is.
|
|
280
|
-
switch (boundRouteBinding(request.method, request.route.path)) {
|
|
281
|
-
case 'query':
|
|
282
|
-
// `/v1/tokens` is in the table because it replaced
|
|
283
|
-
// GET /v1/tokens/account/{account}, which carried the account in the path and so
|
|
284
|
-
// reached a bound token's own tokens through the default branch below - as its
|
|
285
|
-
// deprecated alias registration still does. Both stay under the same rule as
|
|
286
|
-
// everything else: the argument has to name the token's own account, and
|
|
287
|
-
// omitting it still refuses, because a bound credential must not enumerate the
|
|
288
|
-
// instance.
|
|
289
|
-
accountIdSource = queryAccount;
|
|
290
|
-
break;
|
|
291
|
-
|
|
292
|
-
case 'record': {
|
|
293
|
-
let isAccountTemplate =
|
|
294
|
-
request.params.template && (await redis.sismember(`${REDIS_PREFIX}tpl:${tokenData.account}:i`, request.params.template));
|
|
295
|
-
if (isAccountTemplate) {
|
|
296
|
-
accountIdSource = tokenData.account;
|
|
297
|
-
}
|
|
298
|
-
break;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
case 'token':
|
|
302
|
-
request.app.enforceAccount = tokenData.account;
|
|
303
|
-
accountIdSource = tokenData.account;
|
|
304
|
-
break;
|
|
305
|
-
|
|
306
|
-
default:
|
|
307
|
-
accountIdSource = request.params && request.params.account;
|
|
308
|
-
break;
|
|
309
|
-
}
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
310
266
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
msg: 'Trying to use invalid account for a token',
|
|
314
|
-
tokenAccount: tokenData.account,
|
|
315
|
-
tokenId: tokenData.id,
|
|
316
|
-
account: auditEntry.account
|
|
317
|
-
});
|
|
267
|
+
// account token
|
|
268
|
+
const accountIdSource = await resolveRequestAccount(request, tokenData, queryAccount);
|
|
318
269
|
|
|
319
|
-
|
|
270
|
+
if (accountIdSource !== tokenData.account) {
|
|
271
|
+
logger.warn({
|
|
272
|
+
msg: 'Trying to use invalid account for a token',
|
|
273
|
+
tokenAccount: tokenData.account,
|
|
274
|
+
tokenId: tokenData.id,
|
|
275
|
+
account: auditEntry.account
|
|
276
|
+
});
|
|
320
277
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
278
|
+
tokenAuditLog.denied(auditEntry, 'account');
|
|
279
|
+
|
|
280
|
+
let error = Boom.forbidden('Unauthorized account');
|
|
281
|
+
throw error;
|
|
324
282
|
}
|
|
283
|
+
}
|
|
325
284
|
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
tokenAccount: tokenData.account,
|
|
331
|
-
tokenId: tokenData.id,
|
|
332
|
-
account: auditEntry.account,
|
|
333
|
-
remoteAddress: request.app.ip,
|
|
334
|
-
addressAllowlist: tokenData.restrictions.addresses
|
|
335
|
-
});
|
|
336
|
-
|
|
337
|
-
tokenAuditLog.denied(auditEntry, 'address');
|
|
338
|
-
|
|
339
|
-
let error = Boom.forbidden('Unauthorized address');
|
|
340
|
-
error.output.payload.remoteAddress = request.app.ip;
|
|
341
|
-
throw error;
|
|
342
|
-
}
|
|
285
|
+
function assertAddressRestriction(request, tokenData, auditEntry) {
|
|
286
|
+
if (!tokenData.restrictions.addresses || matchIp(request.app.ip, tokenData.restrictions.addresses)) {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
343
289
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
290
|
+
logger.warn({
|
|
291
|
+
msg: 'Trying to use invalid IP for a token',
|
|
292
|
+
tokenAccount: tokenData.account,
|
|
293
|
+
tokenId: tokenData.id,
|
|
294
|
+
account: auditEntry.account,
|
|
295
|
+
remoteAddress: request.app.ip,
|
|
296
|
+
addressAllowlist: tokenData.restrictions.addresses
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
tokenAuditLog.denied(auditEntry, 'address');
|
|
300
|
+
|
|
301
|
+
let error = Boom.forbidden('Unauthorized address');
|
|
302
|
+
error.output.payload.remoteAddress = request.app.ip;
|
|
303
|
+
throw error;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function assertReferrerRestriction(request, tokenData, auditEntry) {
|
|
307
|
+
const referrers = tokenData.restrictions.referrers;
|
|
308
|
+
if (!referrers || !referrers.length || matcher(referrers, request.headers.referer)) {
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
logger.warn({
|
|
313
|
+
msg: 'Trying to use invalid referer for a token',
|
|
314
|
+
tokenAccount: tokenData.account,
|
|
315
|
+
tokenId: tokenData.id,
|
|
316
|
+
account: auditEntry.account,
|
|
317
|
+
referer: request.headers.referer,
|
|
318
|
+
referrerAllowlist: referrers
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
tokenAuditLog.denied(auditEntry, 'referrer');
|
|
322
|
+
|
|
323
|
+
let error = Boom.forbidden('Unauthorized referrer');
|
|
324
|
+
throw error;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function assertRateLimit(request, tokenData, auditEntry) {
|
|
328
|
+
// Skipped on MCP-dispatched injects like the last-use record above: the outer
|
|
329
|
+
// /mcp request already spent one unit of this token's budget at the door, and
|
|
330
|
+
// counting the inner request too silently halved every restricted token's
|
|
331
|
+
// effective limit over MCP.
|
|
332
|
+
// A re-check of an open stream (request.app.authRecheck) is not a request either.
|
|
333
|
+
if (!tokenData.restrictions.rateLimit || request.app.mcpInternal || request.app.authRecheck) {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
363
336
|
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
337
|
+
let rateLimit = await checkRateLimit(
|
|
338
|
+
`api:${tokenData.id}`,
|
|
339
|
+
1,
|
|
340
|
+
tokenData.restrictions.rateLimit.maxRequests,
|
|
341
|
+
tokenData.restrictions.rateLimit.timeWindow
|
|
342
|
+
);
|
|
343
|
+
|
|
344
|
+
if (rateLimit.success) {
|
|
345
|
+
request.app.rateLimitHeaders = {
|
|
346
|
+
'X-RateLimit-Limit': rateLimit.allowed,
|
|
347
|
+
'X-RateLimit-Reset': Math.ceil(rateLimit.ttl),
|
|
348
|
+
'X-RateLimit-Remaining': rateLimit.allowed - rateLimit.count
|
|
349
|
+
};
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
logger.warn({ msg: 'Rate limited', token: tokenData.id, rateLimit });
|
|
354
|
+
tokenAuditLog.denied(auditEntry, 'rateLimit');
|
|
355
|
+
|
|
356
|
+
let error = Boom.tooManyRequests('Rate limit exceeded');
|
|
357
|
+
error.output.payload.ttl = Math.ceil(rateLimit.ttl);
|
|
358
|
+
error.output.headers = {
|
|
359
|
+
'X-RateLimit-Limit': rateLimit.allowed,
|
|
360
|
+
'X-RateLimit-Reset': Math.ceil(rateLimit.ttl),
|
|
361
|
+
// The conventional header for a 429, so a generic HTTP client backs
|
|
362
|
+
// off without knowing about the ttl field in the body
|
|
363
|
+
'Retry-After': Math.ceil(rateLimit.ttl)
|
|
364
|
+
};
|
|
365
|
+
throw error;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// In this order: address, referrer, and the rate limit last, so a request refused for
|
|
369
|
+
// another reason spends nothing of the token's budget
|
|
370
|
+
async function assertRestrictions(request, tokenData, auditEntry) {
|
|
371
|
+
if (!tokenData.restrictions) {
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
assertAddressRestriction(request, tokenData, auditEntry);
|
|
376
|
+
assertReferrerRestriction(request, tokenData, auditEntry);
|
|
377
|
+
await assertRateLimit(request, tokenData, auditEntry);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
return async function validateApiToken(request, token) {
|
|
381
|
+
let disableTokens = await settings.get('disableTokens');
|
|
382
|
+
if (disableTokens && (!token || token === 'preauth')) {
|
|
383
|
+
// tokens checks are disabled, allow all if token is not set.
|
|
384
|
+
// `preauth` marks a caller that presented NO credential at all - routes that hand
|
|
385
|
+
// out lasting privilege have to be able to tell that apart from a real token.
|
|
386
|
+
return {
|
|
387
|
+
isValid: true,
|
|
388
|
+
credentials: { preauth: true },
|
|
389
|
+
artifacts: {}
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
if (!token) {
|
|
394
|
+
// The bearer scheme never calls this without a token, but nothing here relies on it:
|
|
395
|
+
// a missing credential is refused like an unknown one, before anything is looked up
|
|
396
|
+
// or audited, as the other refusals that come before a token is resolved are
|
|
397
|
+
throw Boom.unauthorized('Bad token', 'Bearer');
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const scopes = routeScopes(request.route);
|
|
401
|
+
|
|
402
|
+
// The MCP endpoint (lib/api-routes/mcp-routes.js) is a protocol multiplexer with no
|
|
403
|
+
// operation of its own: every tools/call becomes an injected API request that runs
|
|
404
|
+
// this whole strategy again against the route it actually targets. Several checks
|
|
405
|
+
// below defer to that inner request, and each says so where it does.
|
|
406
|
+
const mcpEndpoint = !!mcpOptions(request.route).endpoint;
|
|
407
|
+
|
|
408
|
+
// Session tokens are refused at the MCP door rather than half-admitted: a session
|
|
409
|
+
// credential carries no bearer token the injected inner requests could forward, so
|
|
410
|
+
// it could initialize and list tools but every tools/call would die on an inner 401.
|
|
411
|
+
if (token.startsWith('sess_') && scopes.includes('api') && !mcpEndpoint) {
|
|
412
|
+
const sessionResult = await authenticateSessionToken(request, token);
|
|
413
|
+
if (sessionResult) {
|
|
414
|
+
return sessionResult;
|
|
398
415
|
}
|
|
399
416
|
}
|
|
400
417
|
|
|
418
|
+
const tokenData = await loadTokenData(request, token);
|
|
419
|
+
const grant = routeGrant(request.route);
|
|
420
|
+
const queryAccount = requestQueryAccount(request);
|
|
421
|
+
const auditEntry = buildAuditEntry(request, tokenData, grant, queryAccount);
|
|
422
|
+
|
|
423
|
+
// Every refusal from here on writes its audit row before it throws
|
|
424
|
+
assertScope(request, tokenData, scopes, grant, auditEntry);
|
|
425
|
+
assertPermission(tokenData, grant, auditEntry, mcpEndpoint);
|
|
426
|
+
await assertAccountBinding(request, tokenData, queryAccount, auditEntry, mcpEndpoint);
|
|
427
|
+
await assertRestrictions(request, tokenData, auditEntry);
|
|
428
|
+
|
|
401
429
|
// The one point every accepted token request passes. "allowed" means the credential was
|
|
402
430
|
// accepted, not that the request succeeded: this runs in the auth strategy, before
|
|
403
431
|
// payload validation and the handler, so a call recorded here can still end in a 400 or
|
|
@@ -419,4 +447,44 @@ function createApiTokenValidator({
|
|
|
419
447
|
};
|
|
420
448
|
}
|
|
421
449
|
|
|
450
|
+
// Every scope a route names admits a token that holds it. Single-scope routes behave
|
|
451
|
+
// exactly as before; the MCP endpoint is the one route naming two (`scope:api` and
|
|
452
|
+
// `scope:mcp`), so both kinds of credential can open it.
|
|
453
|
+
function routeScopes(route) {
|
|
454
|
+
let tags = (route && route.settings && route.settings.tags) || [];
|
|
455
|
+
return tags.filter(tag => tag === 'api' || /^scope:/.test(tag)).map(tag => tag.replace(/^scope:/, ''));
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// This strategy runs before route validation, so `request.query` is whatever the client
|
|
459
|
+
// sent: a repeated `?account=` arrives as an array. Only a string can name an account,
|
|
460
|
+
// and this value is persisted into the audit log, so anything else is not one.
|
|
461
|
+
function requestQueryAccount(request) {
|
|
462
|
+
return request.query && typeof request.query.account === 'string' ? request.query.account : null;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Shared by every audit entry, so an allow and a deny describe the same request.
|
|
466
|
+
// Built before the first check that can refuse: a rejection is the strongest signal of
|
|
467
|
+
// credential misuse there is, and a trail that only held the calls that succeeded would
|
|
468
|
+
// be silent about exactly the ones worth looking at.
|
|
469
|
+
function buildAuditEntry(request, tokenData, grant, queryAccount) {
|
|
470
|
+
return {
|
|
471
|
+
tokenId: tokenData.id,
|
|
472
|
+
ip: request.app.ip,
|
|
473
|
+
method: request.route.method,
|
|
474
|
+
path: request.route.path,
|
|
475
|
+
action: grant.action,
|
|
476
|
+
group: grant.group,
|
|
477
|
+
// The account the REQUEST addressed, which is not always the one in the path: the
|
|
478
|
+
// routes that take it as a query argument are the ones a bound token gets refused
|
|
479
|
+
// on, and falling straight through to the token's own account recorded a
|
|
480
|
+
// cross-account attempt against the account it was entitled to reach - the opposite
|
|
481
|
+
// of what the entry exists to show. The token's account is still the answer for the
|
|
482
|
+
// routes that name no account at all.
|
|
483
|
+
//
|
|
484
|
+
// The refusals log this field rather than re-deriving it, so the application
|
|
485
|
+
// log and the audit row cannot disagree about which account a denial concerned.
|
|
486
|
+
account: (request.params && request.params.account) || queryAccount || tokenData.account || null
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
422
490
|
module.exports = { createApiTokenValidator };
|