-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpermission-evaluator.ts
More file actions
422 lines (392 loc) · 17.3 KB
/
Copy pathpermission-evaluator.ts
File metadata and controls
422 lines (392 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import type { PermissionSet, ObjectPermission, FieldPermission } from '@objectstack/spec/security';
/**
* Operation type mapping to permission checks.
*
* `transfer`/`restore`/`purge` are pre-mapped to their RBAC bits (#1883) even
* though the ObjectQL operations do not exist yet (roadmap M2): the moment such
* an operation is dispatched through the security middleware it is gated by the
* corresponding `allow*` bit — deny unless a resolved permission set grants it.
* There is no window where the ops could ship ungated.
*/
const OPERATION_TO_PERMISSION: Record<string, keyof ObjectPermission> = {
find: 'allowRead',
findOne: 'allowRead',
count: 'allowRead',
aggregate: 'allowRead',
insert: 'allowCreate',
update: 'allowEdit',
delete: 'allowDelete',
transfer: 'allowTransfer',
restore: 'allowRestore',
purge: 'allowPurge',
};
/**
* Destructive operation class — operations that must FAIL CLOSED when they are
* not mapped to a concrete permission key. See ADR-0049: an unrecognised
* destructive operation must be DENIED rather than silently allowed by the
* default-allow fallthrough. `transfer`/`restore`/`purge` are now mapped above
* (#1883), so this set acts as a backstop: it keeps them (and any future
* destructive op prefixed here before its mapping lands) fail-closed if the
* mapping is ever removed. Non-destructive unknown operations retain
* default-allow so custom read-side operations are not broken.
*/
const DESTRUCTIVE_OPERATIONS = new Set<string>(['transfer', 'restore', 'purge']);
/**
* Permission keys covered by the `modifyAllRecords` super-user WRITE bypass:
* edit/delete plus the destructive lifecycle class, DERIVED from the two
* constants above so a future destructive op added to the map+set is covered
* automatically (hand-listing it inline is how bypass gaps happen — #1883).
* NOTE this means "Modify All Data" grants (incl. the wildcard on
* organization_admin / admin_full_access defaults) will cover
* transfer/restore/purge the moment the M2 ops ship — Salesforce semantics,
* confirmed in the #1883 disposition; revisit per-op when M2 lands.
*/
const MODIFY_ALL_WRITE_KEYS = new Set<keyof ObjectPermission>([
'allowEdit',
'allowDelete',
...[...DESTRUCTIVE_OPERATIONS].map((op) => OPERATION_TO_PERMISSION[op]),
]);
/** CRUD operation class an object-level `requiredPermissions` map keys on. */
export type CrudBucket = 'read' | 'create' | 'update' | 'delete';
/**
* [ADR-0066 ⑤] Map a raw ObjectQL operation to the CRUD class a per-operation
* `requiredPermissions` map is keyed on, DERIVED from `OPERATION_TO_PERMISSION`
* so it stays in lockstep with the CRUD permission bits (and any future
* destructive op added there). `transfer`/`restore` fold into `update`,
* `purge` into `delete`. Returns `null` for an operation with no CRUD mapping
* (e.g. a custom read-side op) — such an op is never matched by a per-operation
* map, but the flat `string[]` form still gates it via its `all` bucket.
*/
export function crudBucketForOperation(operation: string): CrudBucket | null {
switch (OPERATION_TO_PERMISSION[operation]) {
case 'allowRead': return 'read';
case 'allowCreate': return 'create';
case 'allowEdit':
case 'allowTransfer':
case 'allowRestore': return 'update';
case 'allowDelete':
case 'allowPurge': return 'delete';
default: return null;
}
}
/**
* [ADR-0066 D2] Resolve the object permission a permission set contributes for
* `objectName`, honouring the secure-by-default posture:
*
* - an EXPLICIT per-object grant (`ps.objects[objectName]`) always applies;
* - the `'*'` wildcard applies to a `public` object (today's allow-by-default);
* - for a `private` object the `'*'` wildcard applies ONLY when it carries the
* super-user bypass bits (`viewAllRecords`/`modifyAllRecords` — the Salesforce
* "View/Modify All Data" power). A plain `'*': {allowRead:true}` does NOT cover
* a private object; access then requires an explicit per-object grant.
*/
function resolveObjectPermission(
ps: PermissionSet,
objectName: string,
isPrivate: boolean,
): ObjectPermission | undefined {
const explicit = ps.objects?.[objectName];
if (explicit) return explicit;
const wild = ps.objects?.['*'];
if (!wild) return undefined;
if (!isPrivate) return wild;
return wild.viewAllRecords || wild.modifyAllRecords ? wild : undefined;
}
/**
* [#3544] Fold the user-level EXPORT axis across the resolved permission sets.
*
* `allowExport` is deliberately absent from {@link OPERATION_TO_PERMISSION}:
* that map's semantics are "the bit must be truthy", which would deny export to
* every permission set authored before the axis existed. The bit is a TRI-state
* instead, and this is its merge rule:
*
* - any set `true` → `true` (an explicit grant outranks another set's deny)
* - else any `false` → `false` (an explicit opt-out outranks silence)
* - else all unset → `undefined` (inherit read — the pre-#3544
* "can-list ⇒ can-export" behaviour, so existing sets are unaffected)
*
* This is the same answer the `/me/permissions` per-object merge produces
* (`if (v === true) acc[k] = true; else if (acc[k] === undefined) acc[k] = v`,
* read back as `acc.allowExport !== false`). That equality is load-bearing, not
* incidental: the client hides its Export button on the merged map while this
* decides the server's 403, and the two disagreeing is exactly the
* `declared ≠ enforced` gap the axis exists to close.
*/
export function resolveUserExportAllowed(
objectName: string,
permissionSets: PermissionSet[],
opts: { isPrivate?: boolean } = {},
): boolean | undefined {
let denied = false;
for (const ps of permissionSets) {
const objPerm = resolveObjectPermission(ps, objectName, opts.isPrivate ?? false);
const bit = objPerm?.allowExport;
if (bit === true) return true;
if (bit === false) denied = true;
}
return denied ? false : undefined;
}
/**
* PermissionEvaluator
*
* Runtime evaluator for PermissionSet definitions.
* Resolves aggregated permissions from roles to concrete allow/deny decisions.
*/
export class PermissionEvaluator {
/**
* Check if an operation is allowed on an object for the given permission sets.
* Uses "most permissive" merging: if ANY permission set allows, it's allowed.
*/
checkObjectPermission(
operation: string,
objectName: string,
permissionSets: PermissionSet[],
/** [ADR-0066 D2] When the object is `private`, the `'*'` wildcard only covers it if it is a super-user grant. */
opts: { isPrivate?: boolean } = {},
): boolean {
// [#3544] User-level export axis. `export` is NOT a bit lookup: per the
// spec's derivation table (`API_METHOD_DERIVATION`) it is `list ∧
// userExportAllowed`, so it requires READ and is then vetoed by an explicit
// `allowExport: false`. Handled here rather than in OPERATION_TO_PERMISSION
// so an UNSET bit keeps inheriting read — otherwise every permission set
// written before the axis existed would silently lose export.
if (operation === 'export') {
if (resolveUserExportAllowed(objectName, permissionSets, opts) === false) return false;
return this.checkObjectPermission('find', objectName, permissionSets, opts);
}
const permKey = OPERATION_TO_PERMISSION[operation];
if (!permKey) {
// Fail CLOSED for the destructive operation class (ADR-0049): an
// unrecognised destructive op must be denied, never silently allowed.
// Other unknown operations are allowed by default.
return !DESTRUCTIVE_OPERATIONS.has(operation);
}
for (const ps of permissionSets) {
// [ADR-0066 D2] Honour the `'*'` wildcard sentinel — admin permission
// sets grant blanket access via a single `objects: { '*': … }` entry —
// but a `private` object is excluded from a non-super-user wildcard.
const objPerm = resolveObjectPermission(ps, objectName, opts.isPrivate ?? false);
if (objPerm) {
// Super-user WRITE bypass ("Modify All Data") — covers edit/delete and
// the destructive lifecycle class (see MODIFY_ALL_WRITE_KEYS).
if (MODIFY_ALL_WRITE_KEYS.has(permKey) && objPerm.modifyAllRecords) {
return true;
}
// Check if viewAllRecords is set (super-user bypass for read ops)
if (permKey === 'allowRead' && (objPerm.viewAllRecords || objPerm.modifyAllRecords)) {
return true;
}
// Check the specific permission
if (objPerm[permKey]) {
return true;
}
}
}
return false;
}
/**
* [ADR-0057 D1] Effective access DEPTH for an operation class on an object,
* merged most-permissively across the permission sets. `view/modifyAll`
* shortcut to 'org'. A granting set with no scope defaults to 'own' (the
* owner-only baseline owner-scoped objects already enforce); the WIDEST wins.
* Returns 'org' when no set grants the op (the caller denies separately, so
* the value is unused).
*/
getEffectiveScope(
opClass: 'read' | 'write',
objectName: string,
permissionSets: PermissionSet[],
opts: { isPrivate?: boolean } = {},
): 'own' | 'own_and_reports' | 'unit' | 'unit_and_below' | 'org' {
const RANK = { own: 0, own_and_reports: 1, unit: 2, unit_and_below: 3, org: 4 } as const;
const ORDER = ['own', 'own_and_reports', 'unit', 'unit_and_below', 'org'] as const;
let widest = -1;
let matched = false;
for (const ps of permissionSets) {
const op: any = resolveObjectPermission(ps, objectName, opts.isPrivate ?? false);
if (!op) continue;
matched = true;
if (opClass === 'read' && (op.viewAllRecords || op.modifyAllRecords)) return 'org';
if (opClass === 'write' && op.modifyAllRecords) return 'org';
const s = opClass === 'read' ? op.readScope : op.writeScope;
const rank = s ? RANK[s as keyof typeof RANK] : RANK.own;
if (rank > widest) widest = rank;
}
if (!matched) return 'org';
return ORDER[widest < 0 ? 0 : widest];
}
/**
* [ADR-0066 D3] Union of `systemPermissions` (capabilities) the caller holds
* across the resolved permission sets — used to enforce a resource's
* `requiredPermissions` AND-gate.
*/
getSystemPermissions(permissionSets: PermissionSet[]): Set<string> {
const out = new Set<string>();
for (const ps of permissionSets) {
for (const cap of ps.systemPermissions ?? []) out.add(cap);
}
return out;
}
/**
* [ADR-0066 D2 / ①] Does any resolved set grant the super-user READ bypass
* (`viewAllRecords`/`modifyAllRecords`, the "View All Data" power) for the
* object? Honours the private posture (see {@link resolveObjectPermission}).
* The security plugin uses this to skip wildcard RLS on private/platform-global
* objects so a platform admin sees all rows.
*/
hasSuperuserReadBypass(
objectName: string,
permissionSets: PermissionSet[],
opts: { isPrivate?: boolean } = {},
): boolean {
for (const ps of permissionSets) {
const op = resolveObjectPermission(ps, objectName, opts.isPrivate ?? false);
if (op && (op.viewAllRecords || op.modifyAllRecords)) return true;
}
return false;
}
/** [ADR-0066 D2 / ①] Super-user WRITE bypass (`modifyAllRecords`) for the object. */
hasSuperuserWriteBypass(
objectName: string,
permissionSets: PermissionSet[],
opts: { isPrivate?: boolean } = {},
): boolean {
for (const ps of permissionSets) {
const op = resolveObjectPermission(ps, objectName, opts.isPrivate ?? false);
if (op && op.modifyAllRecords) return true;
}
return false;
}
/**
* Get the merged field permissions for an object.
* Returns a map of field names to their effective permissions.
* Uses "most permissive" merging.
*/
getFieldPermissions(
objectName: string,
permissionSets: PermissionSet[]
): Record<string, FieldPermission> {
const result: Record<string, FieldPermission> = {};
for (const ps of permissionSets) {
if (!ps.fields) continue;
for (const [key, perm] of Object.entries(ps.fields)) {
// Field keys are in format: "object_name.field_name"
if (!key.startsWith(`${objectName}.`)) continue;
const fieldName = key.substring(objectName.length + 1);
if (!result[fieldName]) {
result[fieldName] = { readable: false, editable: false };
}
// Most permissive merge
if (perm.readable) result[fieldName].readable = true;
if (perm.editable) result[fieldName].editable = true;
}
}
return result;
}
/**
* Resolve permission sets for a list of identifier names from metadata.
*
* Identifiers are matched to `PermissionSet.name`. The names may be
* either role names (when `sys_position.name` is reused as a permission set
* name — common for default admin/member/viewer roles) or explicit
* permission set names supplied through `ExecutionContext.permissions[]`
* (resolved by `resolveExecutionContext` from `sys_user_permission_set`
* and `sys_position_permission_set`).
*
* Async because the underlying metadata service exposes `list()` as a
* Promise — synchronous iteration would silently yield zero results
* (the historical SecurityPlugin behaviour, masking all enforcement).
*
* `bootstrapPermissionSets` is a fallback list of plugin-owned permission
* sets (typically the platform defaults: admin_full_access /
* member_default / viewer_readonly) that are registered via
* `manifest.register({ permissions })` but do not currently propagate
* into the metadata service's `list()` index. Without this fallback,
* SecurityPlugin would never resolve the defaults and all enforcement
* would be silently disabled for authenticated requests.
*/
async resolvePermissionSets(
identifiers: string[],
metadataService: any,
bootstrapPermissionSets: PermissionSet[] = [],
/**
* Optional async loader for permission set names that aren't found in
* metadata or bootstrap. Lets callers query user-defined permission
* sets persisted in `sys_permission_set`. Failures are swallowed
* (fail-closed: unresolvable sets grant nothing) but SURFACED via
* `options.logger` — see #2565: without the warn, a transient DB error
* makes custom permission sets silently vanish and the resulting 403s
* are undiagnosable.
*/
dbLoader?: (unresolved: string[]) => Promise<PermissionSet[]>,
/** Optional logger; only `warn` is used. Resolution behavior is unchanged. */
options: { logger?: { warn?: (msg: string, meta?: Record<string, any>) => void } } = {},
): Promise<PermissionSet[]> {
if (identifiers.length === 0) return [];
const result: PermissionSet[] = [];
const seen = new Set<string>();
// Get all permission sets from metadata. Support both async (Manager) and
// sync (test stub) implementations of `list`.
let allPermSets: any = [];
try {
const listed = metadataService?.list?.('permission')
?? metadataService?.list?.('permissions')
?? [];
allPermSets = typeof (listed as any)?.then === 'function' ? await listed : listed;
} catch (e) {
allPermSets = [];
options.logger?.warn?.(
'[security] permission-set metadata list() failed — falling back to bootstrap/db sources (#2565)',
{ requested: identifiers, error: (e as Error)?.message },
);
}
if (!Array.isArray(allPermSets)) allPermSets = [];
const wanted = new Set(identifiers);
for (const ps of allPermSets) {
if (wanted.has(ps.name) && !seen.has(ps.name)) {
seen.add(ps.name);
result.push(ps);
}
}
// Fallback: any wanted name not yet matched is sourced from the
// bootstrap list (plugin-owned defaults). Avoids silent failure when
// permission sets are registered via `manifest.register` but the
// metadata service hasn't indexed them.
for (const ps of bootstrapPermissionSets) {
if (wanted.has(ps.name) && !seen.has(ps.name)) {
seen.add(ps.name);
result.push(ps);
}
}
// Last-resort: query user-defined permission sets from the database.
// Without this, custom permission sets (created via the admin UI as
// `sys_permission_set` rows) would be silently ignored both for CRUD
// enforcement and for field-level masking.
if (dbLoader) {
const unresolved = identifiers.filter((n) => !seen.has(n));
if (unresolved.length > 0) {
try {
const dbRows = await dbLoader(unresolved);
for (const ps of dbRows ?? []) {
if (ps?.name && !seen.has(ps.name)) {
seen.add(ps.name);
result.push(ps);
}
}
} catch (e) {
// Swallow — the request shouldn't fail just because the DB
// lookup is unavailable (fail-closed: the unresolved sets simply
// grant nothing). But surface it: without this warn a transient
// DB error silently drops custom permission sets and the
// resulting 403s point nowhere near the cause (#2565).
options.logger?.warn?.(
'[security] sys_permission_set db lookup failed — unresolved sets grant nothing this request (#2565)',
{ unresolved, error: (e as Error)?.message },
);
}
}
}
return result;
}
}