rflib-plugin 0.21.10 → 0.22.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/README.md +53 -0
- package/lib/commands/rflib/debug/userpermissions/check.d.ts +21 -0
- package/lib/commands/rflib/debug/userpermissions/check.js +100 -0
- package/lib/commands/rflib/debug/userpermissions/check.js.map +1 -0
- package/lib/shared/orgClient.d.ts +2 -0
- package/lib/shared/orgClient.js +1 -0
- package/lib/shared/orgClient.js.map +1 -1
- package/lib/shared/permissionAggregator.d.ts +15 -0
- package/lib/shared/permissionAggregator.js +5 -5
- package/lib/shared/permissionAggregator.js.map +1 -1
- package/lib/shared/permissionCheck.d.ts +58 -0
- package/lib/shared/permissionCheck.js +365 -0
- package/lib/shared/permissionCheck.js.map +1 -0
- package/messages/rflib.debug.userpermissions.check.md +136 -0
- package/oclif.manifest.json +781 -618
- package/package.json +1 -1
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import { buildIdList, buildUserCondition, escapeSingleQuotes, ID_PATTERN, queryAll, } from './permissionAggregator.js';
|
|
2
|
+
const NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/;
|
|
3
|
+
const FIELD_PATTERN = /^([A-Za-z][A-Za-z0-9_]*)\.([A-Za-z][A-Za-z0-9_]*)$/;
|
|
4
|
+
const PARENT_FIELDS = 'Parent.Name, Parent.Label, Parent.IsOwnedByProfile, Parent.Profile.Name, Parent.PermissionSetGroupId';
|
|
5
|
+
const PERMISSION_SET_FIELDS = 'Id, Name, Label, IsOwnedByProfile, Profile.Name, PermissionSetGroupId';
|
|
6
|
+
const OBJECT_ACCESS = {
|
|
7
|
+
read: { field: 'PermissionsRead', label: 'Read' },
|
|
8
|
+
create: { field: 'PermissionsCreate', label: 'Create' },
|
|
9
|
+
edit: { field: 'PermissionsEdit', label: 'Edit' },
|
|
10
|
+
delete: { field: 'PermissionsDelete', label: 'Delete' },
|
|
11
|
+
viewall: { field: 'PermissionsViewAllRecords', label: 'View All Records' },
|
|
12
|
+
modifyall: { field: 'PermissionsModifyAllRecords', label: 'Modify All Records' },
|
|
13
|
+
viewallfields: { field: 'PermissionsViewAllFields', label: 'View All Fields' },
|
|
14
|
+
};
|
|
15
|
+
const OBJECT_PERMISSION_FIELDS = Object.values(OBJECT_ACCESS)
|
|
16
|
+
.map((access) => access.field)
|
|
17
|
+
.join(', ');
|
|
18
|
+
/** Access levels accepted by `checkUserPermission`. Field checks only accept read and edit. */
|
|
19
|
+
export const ACCESS_LEVELS = Object.keys(OBJECT_ACCESS);
|
|
20
|
+
const FIELD_ACCESS_LEVELS = ['read', 'edit'];
|
|
21
|
+
const SETUP_ENTITIES = {
|
|
22
|
+
apexClass: {
|
|
23
|
+
table: 'ApexClass',
|
|
24
|
+
nameField: 'Name',
|
|
25
|
+
label: 'Apex class',
|
|
26
|
+
impliedBy: {
|
|
27
|
+
field: 'PermissionsAuthorApex',
|
|
28
|
+
note: 'Users with the Author Apex permission can access all Apex classes.',
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
apexPage: {
|
|
32
|
+
table: 'ApexPage',
|
|
33
|
+
nameField: 'Name',
|
|
34
|
+
label: 'Visualforce page',
|
|
35
|
+
impliedBy: {
|
|
36
|
+
field: 'PermissionsCustomizeApplication',
|
|
37
|
+
note: 'Users with the Customize Application permission can access all Visualforce pages.',
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
customPermission: { table: 'CustomPermission', nameField: 'DeveloperName', label: 'custom permission' },
|
|
41
|
+
};
|
|
42
|
+
function validateName(value, label) {
|
|
43
|
+
if (!NAME_PATTERN.test(value)) {
|
|
44
|
+
throw new Error(`Invalid ${label} "${value}". Use the API name, e.g. Account or My_Class.`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function parseObjectAccess(access) {
|
|
48
|
+
const value = (access ?? 'read').toLowerCase();
|
|
49
|
+
if (!ACCESS_LEVELS.includes(value)) {
|
|
50
|
+
throw new Error(`Invalid access "${access ?? ''}". Use one of: ${ACCESS_LEVELS.join(', ')}.`);
|
|
51
|
+
}
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
/** Splits `ns__Name` or `ns.Name` into its namespace and name. */
|
|
55
|
+
function parseQualifiedName(value, label) {
|
|
56
|
+
const separator = value.includes('.') ? '.' : value.includes('__') ? '__' : undefined;
|
|
57
|
+
if (!separator) {
|
|
58
|
+
validateName(value, label);
|
|
59
|
+
return { name: value };
|
|
60
|
+
}
|
|
61
|
+
const index = value.indexOf(separator);
|
|
62
|
+
const namespace = value.slice(0, index);
|
|
63
|
+
const name = value.slice(index + separator.length);
|
|
64
|
+
validateName(namespace, `${label} namespace`);
|
|
65
|
+
validateName(name, label);
|
|
66
|
+
return { namespace, name };
|
|
67
|
+
}
|
|
68
|
+
/** Validates the arguments and works out which permission to check, before any query is sent. */
|
|
69
|
+
function parseTarget(args) {
|
|
70
|
+
const given = [
|
|
71
|
+
args.object,
|
|
72
|
+
args.field,
|
|
73
|
+
args.apexClass,
|
|
74
|
+
args.apexPage,
|
|
75
|
+
args.customPermission,
|
|
76
|
+
args.systemPermission,
|
|
77
|
+
].filter((value) => value !== undefined);
|
|
78
|
+
if (given.length !== 1) {
|
|
79
|
+
throw new Error('Specify exactly one of: object, field, apexClass, apexPage, customPermission, or systemPermission.');
|
|
80
|
+
}
|
|
81
|
+
if (args.access !== undefined && args.object === undefined && args.field === undefined) {
|
|
82
|
+
throw new Error('access only applies to object and field checks.');
|
|
83
|
+
}
|
|
84
|
+
if (args.object !== undefined) {
|
|
85
|
+
validateName(args.object, 'object');
|
|
86
|
+
return { type: 'object', object: args.object, access: parseObjectAccess(args.access) };
|
|
87
|
+
}
|
|
88
|
+
if (args.field !== undefined) {
|
|
89
|
+
const match = FIELD_PATTERN.exec(args.field);
|
|
90
|
+
if (!match) {
|
|
91
|
+
throw new Error(`Invalid field "${args.field}". Use the form Object.Field, e.g. Account.AnnualRevenue.`);
|
|
92
|
+
}
|
|
93
|
+
const access = parseObjectAccess(args.access);
|
|
94
|
+
if (!FIELD_ACCESS_LEVELS.includes(access)) {
|
|
95
|
+
throw new Error(`Invalid access "${access}" for a field. Use one of: ${FIELD_ACCESS_LEVELS.join(', ')}.`);
|
|
96
|
+
}
|
|
97
|
+
return { type: 'field', object: match[1], field: match[2], access: access };
|
|
98
|
+
}
|
|
99
|
+
if (args.systemPermission !== undefined) {
|
|
100
|
+
const name = args.systemPermission.replace(/^Permissions/i, '');
|
|
101
|
+
validateName(name, 'system permission');
|
|
102
|
+
return { type: 'systemPermission', name };
|
|
103
|
+
}
|
|
104
|
+
if (args.apexClass !== undefined) {
|
|
105
|
+
return { type: 'apexClass', ...parseQualifiedName(args.apexClass, SETUP_ENTITIES.apexClass.label) };
|
|
106
|
+
}
|
|
107
|
+
if (args.apexPage !== undefined) {
|
|
108
|
+
return { type: 'apexPage', ...parseQualifiedName(args.apexPage, SETUP_ENTITIES.apexPage.label) };
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
type: 'customPermission',
|
|
112
|
+
...parseQualifiedName(args.customPermission, SETUP_ENTITIES.customPermission.label),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
async function resolveUser(conn, user) {
|
|
116
|
+
const isId = ID_PATTERN.test(user);
|
|
117
|
+
if (!isId && !user.includes('@')) {
|
|
118
|
+
throw new Error(`Invalid user "${user}". Expected a 15 or 18 character User ID or a username.`);
|
|
119
|
+
}
|
|
120
|
+
const condition = isId ? `Id = '${escapeSingleQuotes(user)}'` : `Username = '${escapeSingleQuotes(user)}'`;
|
|
121
|
+
const rows = await conn.query(`SELECT Id, Username, Name, IsActive, ProfileId, Profile.Name FROM User WHERE ${condition} LIMIT 1`);
|
|
122
|
+
if (rows.records.length === 0) {
|
|
123
|
+
throw new Error(`User "${user}" was not found.`);
|
|
124
|
+
}
|
|
125
|
+
return rows.records[0];
|
|
126
|
+
}
|
|
127
|
+
async function loadContext(conn, user) {
|
|
128
|
+
const assignments = (await queryAll(conn, 'SELECT PermissionSetId, PermissionSetGroupId, PermissionSet.IsOwnedByProfile, ' +
|
|
129
|
+
'PermissionSetGroup.MasterLabel, PermissionSetGroup.DeveloperName ' +
|
|
130
|
+
`FROM PermissionSetAssignment WHERE AssigneeId = '${escapeSingleQuotes(user.Id)}'`)).records;
|
|
131
|
+
const sourceIds = { profileId: user.ProfileId, permissionSetIds: [], permissionSetGroupIds: [] };
|
|
132
|
+
const groupLabels = new Map();
|
|
133
|
+
for (const assignment of assignments) {
|
|
134
|
+
if (assignment.PermissionSet?.IsOwnedByProfile)
|
|
135
|
+
continue;
|
|
136
|
+
if (assignment.PermissionSetGroupId) {
|
|
137
|
+
sourceIds.permissionSetGroupIds.push(assignment.PermissionSetGroupId);
|
|
138
|
+
groupLabels.set(assignment.PermissionSetGroupId, assignment.PermissionSetGroup?.MasterLabel ??
|
|
139
|
+
assignment.PermissionSetGroup?.DeveloperName ??
|
|
140
|
+
assignment.PermissionSetGroupId);
|
|
141
|
+
}
|
|
142
|
+
else if (assignment.PermissionSetId) {
|
|
143
|
+
sourceIds.permissionSetIds.push(assignment.PermissionSetId);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return { conn, sourceIds, groupLabels };
|
|
147
|
+
}
|
|
148
|
+
function toSource(ps, permission, ctx) {
|
|
149
|
+
if (ps?.IsOwnedByProfile) {
|
|
150
|
+
return { type: 'Profile', name: ps.Profile?.Name ?? ps.Label ?? '', permission };
|
|
151
|
+
}
|
|
152
|
+
if (ps?.PermissionSetGroupId) {
|
|
153
|
+
const name = ctx.groupLabels.get(ps.PermissionSetGroupId) ?? ps.PermissionSetGroupId;
|
|
154
|
+
return { type: 'PermissionSetGroup', name, permission };
|
|
155
|
+
}
|
|
156
|
+
return { type: 'PermissionSet', name: ps?.Label ?? ps?.Name ?? '', apiName: ps?.Name, permission };
|
|
157
|
+
}
|
|
158
|
+
/** Returns a source for every row whose `permission` field is true. */
|
|
159
|
+
function grantsFrom(rows, permission, ctx) {
|
|
160
|
+
return rows.filter((row) => row[permission] === true).map((row) => toSource(row.Parent, permission, ctx));
|
|
161
|
+
}
|
|
162
|
+
function uniqueSources(sources) {
|
|
163
|
+
const seen = new Set();
|
|
164
|
+
return sources.filter((source) => {
|
|
165
|
+
const key = `${source.type}|${source.name}|${source.permission}`;
|
|
166
|
+
if (seen.has(key))
|
|
167
|
+
return false;
|
|
168
|
+
seen.add(key);
|
|
169
|
+
return true;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
async function describeSObject(conn, name) {
|
|
173
|
+
try {
|
|
174
|
+
return await conn.sobject(name).describe();
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
178
|
+
throw new Error(`Could not describe SObject "${name}": ${message}`, { cause: error });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
async function queryObjectPermissions(ctx, sobjectType) {
|
|
182
|
+
const soql = `SELECT ${PARENT_FIELDS}, SobjectType, ${OBJECT_PERMISSION_FIELDS} FROM ObjectPermissions` +
|
|
183
|
+
`${buildUserCondition(ctx.sourceIds)} AND SobjectType = '${escapeSingleQuotes(sobjectType)}'`;
|
|
184
|
+
return (await queryAll(ctx.conn, soql)).records;
|
|
185
|
+
}
|
|
186
|
+
/** Returns the user's permission sets (including their profile's) that have `permissionField` enabled. */
|
|
187
|
+
async function queryPermissionSets(ctx, permissionField) {
|
|
188
|
+
const { profileId, permissionSetIds, permissionSetGroupIds } = ctx.sourceIds;
|
|
189
|
+
const clauses = [`ProfileId = '${escapeSingleQuotes(profileId)}'`];
|
|
190
|
+
if (permissionSetIds.length > 0)
|
|
191
|
+
clauses.push(`Id IN ${buildIdList(permissionSetIds)}`);
|
|
192
|
+
if (permissionSetGroupIds.length > 0)
|
|
193
|
+
clauses.push(`PermissionSetGroupId IN ${buildIdList(permissionSetGroupIds)}`);
|
|
194
|
+
const soql = `SELECT ${PERMISSION_SET_FIELDS} FROM PermissionSet WHERE (${clauses.join(' OR ')}) AND ${permissionField} = true`;
|
|
195
|
+
return (await queryAll(ctx.conn, soql)).records;
|
|
196
|
+
}
|
|
197
|
+
async function checkObject(ctx, target) {
|
|
198
|
+
const describe = await describeSObject(ctx.conn, target.object);
|
|
199
|
+
const objectName = describe.name ?? target.object;
|
|
200
|
+
const { field, label } = OBJECT_ACCESS[target.access];
|
|
201
|
+
const sources = grantsFrom(await queryObjectPermissions(ctx, objectName), field, ctx);
|
|
202
|
+
return {
|
|
203
|
+
target: objectName,
|
|
204
|
+
description: `${label} access on ${objectName}`,
|
|
205
|
+
granted: sources.length > 0,
|
|
206
|
+
sources: uniqueSources(sources),
|
|
207
|
+
notes: [],
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
async function checkField(ctx, target) {
|
|
211
|
+
const describe = await describeSObject(ctx.conn, target.object);
|
|
212
|
+
const objectName = describe.name ?? target.object;
|
|
213
|
+
const field = describe.fields.find((candidate) => candidate.name.toLowerCase() === target.field.toLowerCase());
|
|
214
|
+
if (!field) {
|
|
215
|
+
throw new Error(`Field "${target.field}" was not found on ${objectName}.`);
|
|
216
|
+
}
|
|
217
|
+
const fieldName = `${objectName}.${field.name}`;
|
|
218
|
+
const { field: permission, label } = OBJECT_ACCESS[target.access];
|
|
219
|
+
const notes = [];
|
|
220
|
+
const objectRows = await queryObjectPermissions(ctx, objectName);
|
|
221
|
+
const objectAccess = {
|
|
222
|
+
read: objectRows.some((row) => row.PermissionsRead === true),
|
|
223
|
+
edit: objectRows.some((row) => row.PermissionsEdit === true),
|
|
224
|
+
};
|
|
225
|
+
let sources;
|
|
226
|
+
if (field.permissionable === false) {
|
|
227
|
+
// Fields such as Id, Name or CreatedDate have no field-level security; the object permission decides.
|
|
228
|
+
notes.push(`${fieldName} isn't controlled by field-level security, so access follows the ${label} permission on ${objectName}.`);
|
|
229
|
+
sources = grantsFrom(objectRows, permission, ctx);
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
const flsRows = (await queryAll(ctx.conn, `SELECT ${PARENT_FIELDS}, Field, PermissionsRead, PermissionsEdit FROM FieldPermissions` +
|
|
233
|
+
`${buildUserCondition(ctx.sourceIds)} AND SobjectType = '${escapeSingleQuotes(objectName)}'` +
|
|
234
|
+
` AND Field = '${escapeSingleQuotes(fieldName)}'`)).records;
|
|
235
|
+
sources = grantsFrom(flsRows, permission, ctx);
|
|
236
|
+
if (target.access === 'read') {
|
|
237
|
+
// View All Fields on the object grants Read on every field, regardless of field-level security.
|
|
238
|
+
sources.push(...grantsFrom(objectRows, OBJECT_ACCESS.viewallfields.field, ctx));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const readOnly = target.access === 'edit' && (field.calculated === true || field.autoNumber === true);
|
|
242
|
+
if (readOnly) {
|
|
243
|
+
notes.push(`${fieldName} is a formula or auto-number field, so no user can edit it.`);
|
|
244
|
+
}
|
|
245
|
+
const fieldPermissionGranted = sources.length > 0 && !readOnly;
|
|
246
|
+
if (fieldPermissionGranted && !objectAccess[target.access]) {
|
|
247
|
+
notes.push(`The user has field-level access, but no ${label} permission on ${objectName}, so the field isn't accessible.`);
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
target: fieldName,
|
|
251
|
+
description: `${label} access on ${fieldName}`,
|
|
252
|
+
granted: fieldPermissionGranted && objectAccess[target.access],
|
|
253
|
+
sources: uniqueSources(sources),
|
|
254
|
+
notes,
|
|
255
|
+
fieldPermissionGranted,
|
|
256
|
+
objectAccess,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
async function checkSetupEntity(ctx, target) {
|
|
260
|
+
const config = SETUP_ENTITIES[target.type];
|
|
261
|
+
const namespaceFilter = target.namespace === undefined ? '' : ` AND NamespacePrefix = '${escapeSingleQuotes(target.namespace)}'`;
|
|
262
|
+
const matches = (await ctx.conn.query(`SELECT Id, ${config.nameField}, NamespacePrefix FROM ${config.table}` +
|
|
263
|
+
` WHERE ${config.nameField} = '${escapeSingleQuotes(target.name)}'${namespaceFilter}`)).records;
|
|
264
|
+
const displayName = target.namespace ? `${target.namespace}__${target.name}` : target.name;
|
|
265
|
+
if (matches.length === 0) {
|
|
266
|
+
throw new Error(`The ${config.label} "${displayName}" was not found.`);
|
|
267
|
+
}
|
|
268
|
+
// Without a namespace, prefer the org's own entity over managed ones, like Apex name resolution does.
|
|
269
|
+
const local = matches.filter((match) => !match.NamespacePrefix);
|
|
270
|
+
const candidates = matches.length > 1 && local.length === 1 ? local : matches;
|
|
271
|
+
if (candidates.length > 1) {
|
|
272
|
+
const namespaces = candidates.map((match) => match.NamespacePrefix ?? '(none)').join(', ');
|
|
273
|
+
throw new Error(`More than one ${config.label} is named "${target.name}" (namespaces: ${namespaces}). Specify one as namespace__${target.name}.`);
|
|
274
|
+
}
|
|
275
|
+
const entity = candidates[0];
|
|
276
|
+
const targetName = entity.NamespacePrefix ? `${entity.NamespacePrefix}__${target.name}` : target.name;
|
|
277
|
+
const rows = (await queryAll(ctx.conn, `SELECT ${PARENT_FIELDS}, SetupEntityId FROM SetupEntityAccess${buildUserCondition(ctx.sourceIds)}` +
|
|
278
|
+
` AND SetupEntityId = '${escapeSingleQuotes(entity.Id)}'`)).records;
|
|
279
|
+
const sources = rows.map((row) => toSource(row.Parent, 'SetupEntityAccess', ctx));
|
|
280
|
+
const notes = [];
|
|
281
|
+
if (config.impliedBy) {
|
|
282
|
+
const implied = (await queryPermissionSets(ctx, config.impliedBy.field)).map((ps) => toSource(ps, config.impliedBy.field, ctx));
|
|
283
|
+
if (implied.length > 0) {
|
|
284
|
+
sources.push(...implied);
|
|
285
|
+
notes.push(config.impliedBy.note);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return {
|
|
289
|
+
target: targetName,
|
|
290
|
+
description: `access to the ${config.label} ${targetName}`,
|
|
291
|
+
granted: sources.length > 0,
|
|
292
|
+
sources: uniqueSources(sources),
|
|
293
|
+
notes,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
async function checkSystemPermission(ctx, target) {
|
|
297
|
+
const describe = await describeSObject(ctx.conn, 'PermissionSet');
|
|
298
|
+
const expected = `permissions${target.name}`.toLowerCase();
|
|
299
|
+
const field = describe.fields.find((candidate) => candidate.name.toLowerCase() === expected && candidate.type === 'boolean');
|
|
300
|
+
if (!field) {
|
|
301
|
+
throw new Error(`Unknown system permission "${target.name}". Use the API name without the "Permissions" prefix, e.g. ModifyAllData or ViewSetup.`);
|
|
302
|
+
}
|
|
303
|
+
const name = field.name.slice('Permissions'.length);
|
|
304
|
+
const sources = (await queryPermissionSets(ctx, field.name)).map((ps) => toSource(ps, field.name, ctx));
|
|
305
|
+
return {
|
|
306
|
+
target: name,
|
|
307
|
+
description: `the ${name} system permission`,
|
|
308
|
+
granted: sources.length > 0,
|
|
309
|
+
sources: uniqueSources(sources),
|
|
310
|
+
notes: [],
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
async function runCheck(ctx, target) {
|
|
314
|
+
switch (target.type) {
|
|
315
|
+
case 'object':
|
|
316
|
+
return checkObject(ctx, target);
|
|
317
|
+
case 'field':
|
|
318
|
+
return checkField(ctx, target);
|
|
319
|
+
case 'systemPermission':
|
|
320
|
+
return checkSystemPermission(ctx, target);
|
|
321
|
+
case 'apexClass':
|
|
322
|
+
case 'apexPage':
|
|
323
|
+
case 'customPermission':
|
|
324
|
+
return checkSetupEntity(ctx, target);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Checks whether a user has one specific permission, and which profile, permission sets, and
|
|
329
|
+
* permission set groups grant it. Answers questions such as "can this user edit
|
|
330
|
+
* Account.AnnualRevenue?" with a verdict instead of the raw permission rows.
|
|
331
|
+
*/
|
|
332
|
+
export async function checkUserPermission(conn, args) {
|
|
333
|
+
if (!args.user) {
|
|
334
|
+
throw new Error('user is required');
|
|
335
|
+
}
|
|
336
|
+
const target = parseTarget(args);
|
|
337
|
+
const user = await resolveUser(conn, args.user);
|
|
338
|
+
const ctx = await loadContext(conn, user);
|
|
339
|
+
const outcome = await runCheck(ctx, target);
|
|
340
|
+
const notes = [...outcome.notes];
|
|
341
|
+
if (!user.IsActive) {
|
|
342
|
+
notes.unshift('The user is inactive and cannot log in, regardless of their permissions.');
|
|
343
|
+
}
|
|
344
|
+
const access = target.type === 'object' || target.type === 'field' ? target.access : undefined;
|
|
345
|
+
const result = {
|
|
346
|
+
user: {
|
|
347
|
+
id: user.Id,
|
|
348
|
+
username: user.Username,
|
|
349
|
+
name: user.Name,
|
|
350
|
+
isActive: user.IsActive,
|
|
351
|
+
profileName: user.Profile?.Name ?? '',
|
|
352
|
+
},
|
|
353
|
+
check: { type: target.type, target: outcome.target, ...(access ? { access } : {}) },
|
|
354
|
+
granted: outcome.granted,
|
|
355
|
+
summary: `${user.Username} ${outcome.granted ? 'has' : "doesn't have"} ${outcome.description}.`,
|
|
356
|
+
sources: outcome.sources,
|
|
357
|
+
notes,
|
|
358
|
+
};
|
|
359
|
+
if (outcome.fieldPermissionGranted !== undefined)
|
|
360
|
+
result.fieldPermissionGranted = outcome.fieldPermissionGranted;
|
|
361
|
+
if (outcome.objectAccess)
|
|
362
|
+
result.objectAccess = outcome.objectAccess;
|
|
363
|
+
return result;
|
|
364
|
+
}
|
|
365
|
+
//# sourceMappingURL=permissionCheck.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"permissionCheck.js","sourceRoot":"","sources":["../../src/shared/permissionCheck.ts"],"names":[],"mappings":"AACA,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,kBAAkB,EAClB,UAAU,EACV,QAAQ,GAET,MAAM,2BAA2B,CAAC;AAEnC,MAAM,YAAY,GAAG,yBAAyB,CAAC;AAC/C,MAAM,aAAa,GAAG,oDAAoD,CAAC;AAE3E,MAAM,aAAa,GACjB,sGAAsG,CAAC;AACzG,MAAM,qBAAqB,GAAG,uEAAuE,CAAC;AAKtG,MAAM,aAAa,GAA2D;IAC5E,IAAI,EAAE,EAAE,KAA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IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE;QACnF,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,OAAO,EAAE,GAAG,IAAI,CAAC,QAAQ,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,cAAc,IAAI,OAAO,CAAC,WAAW,GAAG;QAC/F,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,KAAK;KACN,CAAC;IACF,IAAI,OAAO,CAAC,sBAAsB,KAAK,SAAS;QAAE,MAAM,CAAC,sBAAsB,GAAG,OAAO,CAAC,sBAAsB,CAAC;IACjH,IAAI,OAAO,CAAC,YAAY;QAAE,MAAM,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IACrE,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { Connection } from '@salesforce/core';\nimport {\n buildIdList,\n buildUserCondition,\n escapeSingleQuotes,\n ID_PATTERN,\n queryAll,\n type PermissionSourceIds,\n} from './permissionAggregator.js';\n\nconst NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/;\nconst FIELD_PATTERN = /^([A-Za-z][A-Za-z0-9_]*)\\.([A-Za-z][A-Za-z0-9_]*)$/;\n\nconst PARENT_FIELDS =\n 'Parent.Name, Parent.Label, Parent.IsOwnedByProfile, Parent.Profile.Name, Parent.PermissionSetGroupId';\nconst PERMISSION_SET_FIELDS = 'Id, Name, Label, IsOwnedByProfile, Profile.Name, PermissionSetGroupId';\n\nexport type ObjectAccess = 'read' | 'create' | 'edit' | 'delete' | 'viewall' | 'modifyall' | 'viewallfields';\nexport type FieldAccess = 'read' | 'edit';\n\nconst OBJECT_ACCESS: Record<ObjectAccess, { field: string; label: string }> = {\n read: { field: 'PermissionsRead', label: 'Read' },\n create: { field: 'PermissionsCreate', label: 'Create' },\n edit: { field: 'PermissionsEdit', label: 'Edit' },\n delete: { field: 'PermissionsDelete', label: 'Delete' },\n viewall: { field: 'PermissionsViewAllRecords', label: 'View All Records' },\n modifyall: { field: 'PermissionsModifyAllRecords', label: 'Modify All Records' },\n viewallfields: { field: 'PermissionsViewAllFields', label: 'View All Fields' },\n};\nconst OBJECT_PERMISSION_FIELDS = Object.values(OBJECT_ACCESS)\n .map((access) => access.field)\n .join(', ');\n\n/** Access levels accepted by `checkUserPermission`. Field checks only accept read and edit. */\nexport const ACCESS_LEVELS = Object.keys(OBJECT_ACCESS) as ObjectAccess[];\nconst FIELD_ACCESS_LEVELS: FieldAccess[] = ['read', 'edit'];\n\ntype SetupEntityType = 'apexClass' | 'apexPage' | 'customPermission';\n\ntype SetupEntityConfig = {\n table: string;\n nameField: string;\n label: string;\n /** System permission that grants access to every entity of this type. */\n impliedBy?: { field: string; note: string };\n};\n\nconst SETUP_ENTITIES: Record<SetupEntityType, SetupEntityConfig> = {\n apexClass: {\n table: 'ApexClass',\n nameField: 'Name',\n label: 'Apex class',\n impliedBy: {\n field: 'PermissionsAuthorApex',\n note: 'Users with the Author Apex permission can access all Apex classes.',\n },\n },\n apexPage: {\n table: 'ApexPage',\n nameField: 'Name',\n label: 'Visualforce page',\n impliedBy: {\n field: 'PermissionsCustomizeApplication',\n note: 'Users with the Customize Application permission can access all Visualforce pages.',\n },\n },\n customPermission: { table: 'CustomPermission', nameField: 'DeveloperName', label: 'custom permission' },\n};\n\nexport type CheckUserPermissionArgs = {\n /** User ID (15 or 18 characters) or username. */\n user: string;\n object?: string;\n /** Field in the form `Object.Field`. */\n field?: string;\n access?: string;\n apexClass?: string;\n apexPage?: string;\n customPermission?: string;\n systemPermission?: string;\n};\n\nexport type PermissionCheckType = 'object' | 'field' | SetupEntityType | 'systemPermission';\n\nexport type PermissionSource = {\n type: 'Profile' | 'PermissionSet' | 'PermissionSetGroup';\n name: string;\n apiName?: string;\n /** The permission on the source that grants the access, e.g. PermissionsEdit or SetupEntityAccess. */\n permission: string;\n};\n\nexport type CheckUserPermissionResult = {\n user: { id: string; username: string; name: string; isActive: boolean; profileName: string };\n check: { type: PermissionCheckType; target: string; access?: string };\n granted: boolean;\n summary: string;\n sources: PermissionSource[];\n notes: string[];\n /** Field checks only: whether field-level security alone grants the access, ignoring object permissions. */\n fieldPermissionGranted?: boolean;\n /** Field checks only: the user's Read and Edit permissions on the field's object. */\n objectAccess?: { read: boolean; edit: boolean };\n};\n\ntype CheckTarget =\n | { type: 'object'; object: string; access: ObjectAccess }\n | { type: 'field'; object: string; field: string; access: FieldAccess }\n | { type: SetupEntityType; namespace?: string; name: string }\n | { type: 'systemPermission'; name: string };\n\ntype CheckOutcome = Pick<CheckUserPermissionResult, 'granted' | 'sources' | 'notes'> &\n Partial<Pick<CheckUserPermissionResult, 'fieldPermissionGranted' | 'objectAccess'>> & {\n target: string;\n description: string;\n };\n\ntype PermissionSetRecord = {\n Name?: string;\n Label?: string;\n IsOwnedByProfile?: boolean;\n Profile?: { Name?: string } | null;\n PermissionSetGroupId?: string | null;\n};\n\ntype GrantRow = { Parent?: PermissionSetRecord } & Record<string, unknown>;\n\ntype UserRow = {\n Id: string;\n Username: string;\n Name: string;\n IsActive: boolean;\n ProfileId: string;\n Profile?: { Name?: string } | null;\n};\n\ntype AssignmentRow = {\n PermissionSetId: string | null;\n PermissionSetGroupId: string | null;\n PermissionSet?: { IsOwnedByProfile?: boolean } | null;\n PermissionSetGroup?: { MasterLabel?: string; DeveloperName?: string } | null;\n};\n\ntype DescribeField = {\n name: string;\n type?: string;\n permissionable?: boolean;\n calculated?: boolean;\n autoNumber?: boolean;\n};\ntype DescribeResult = { name?: string; fields: DescribeField[] };\n\ntype CheckContext = {\n conn: Connection;\n sourceIds: PermissionSourceIds;\n groupLabels: Map<string, string>;\n};\n\nfunction validateName(value: string, label: string): void {\n if (!NAME_PATTERN.test(value)) {\n throw new Error(`Invalid ${label} \"${value}\". Use the API name, e.g. Account or My_Class.`);\n }\n}\n\nfunction parseObjectAccess(access: string | undefined): ObjectAccess {\n const value = (access ?? 'read').toLowerCase();\n if (!ACCESS_LEVELS.includes(value as ObjectAccess)) {\n throw new Error(`Invalid access \"${access ?? ''}\". Use one of: ${ACCESS_LEVELS.join(', ')}.`);\n }\n return value as ObjectAccess;\n}\n\n/** Splits `ns__Name` or `ns.Name` into its namespace and name. */\nfunction parseQualifiedName(value: string, label: string): { namespace?: string; name: string } {\n const separator = value.includes('.') ? '.' : value.includes('__') ? '__' : undefined;\n if (!separator) {\n validateName(value, label);\n return { name: value };\n }\n const index = value.indexOf(separator);\n const namespace = value.slice(0, index);\n const name = value.slice(index + separator.length);\n validateName(namespace, `${label} namespace`);\n validateName(name, label);\n return { namespace, name };\n}\n\n/** Validates the arguments and works out which permission to check, before any query is sent. */\nfunction parseTarget(args: CheckUserPermissionArgs): CheckTarget {\n const given = [\n args.object,\n args.field,\n args.apexClass,\n args.apexPage,\n args.customPermission,\n args.systemPermission,\n ].filter((value) => value !== undefined);\n if (given.length !== 1) {\n throw new Error(\n 'Specify exactly one of: object, field, apexClass, apexPage, customPermission, or systemPermission.',\n );\n }\n if (args.access !== undefined && args.object === undefined && args.field === undefined) {\n throw new Error('access only applies to object and field checks.');\n }\n\n if (args.object !== undefined) {\n validateName(args.object, 'object');\n return { type: 'object', object: args.object, access: parseObjectAccess(args.access) };\n }\n if (args.field !== undefined) {\n const match = FIELD_PATTERN.exec(args.field);\n if (!match) {\n throw new Error(`Invalid field \"${args.field}\". Use the form Object.Field, e.g. Account.AnnualRevenue.`);\n }\n const access = parseObjectAccess(args.access);\n if (!FIELD_ACCESS_LEVELS.includes(access as FieldAccess)) {\n throw new Error(`Invalid access \"${access}\" for a field. Use one of: ${FIELD_ACCESS_LEVELS.join(', ')}.`);\n }\n return { type: 'field', object: match[1], field: match[2], access: access as FieldAccess };\n }\n if (args.systemPermission !== undefined) {\n const name = args.systemPermission.replace(/^Permissions/i, '');\n validateName(name, 'system permission');\n return { type: 'systemPermission', name };\n }\n if (args.apexClass !== undefined) {\n return { type: 'apexClass', ...parseQualifiedName(args.apexClass, SETUP_ENTITIES.apexClass.label) };\n }\n if (args.apexPage !== undefined) {\n return { type: 'apexPage', ...parseQualifiedName(args.apexPage, SETUP_ENTITIES.apexPage.label) };\n }\n return {\n type: 'customPermission',\n ...parseQualifiedName(args.customPermission!, SETUP_ENTITIES.customPermission.label),\n };\n}\n\nasync function resolveUser(conn: Connection, user: string): Promise<UserRow> {\n const isId = ID_PATTERN.test(user);\n if (!isId && !user.includes('@')) {\n throw new Error(`Invalid user \"${user}\". Expected a 15 or 18 character User ID or a username.`);\n }\n const condition = isId ? `Id = '${escapeSingleQuotes(user)}'` : `Username = '${escapeSingleQuotes(user)}'`;\n const rows = await conn.query<UserRow>(\n `SELECT Id, Username, Name, IsActive, ProfileId, Profile.Name FROM User WHERE ${condition} LIMIT 1`,\n );\n if (rows.records.length === 0) {\n throw new Error(`User \"${user}\" was not found.`);\n }\n return rows.records[0];\n}\n\nasync function loadContext(conn: Connection, user: UserRow): Promise<CheckContext> {\n const assignments = (\n await queryAll<AssignmentRow>(\n conn,\n 'SELECT PermissionSetId, PermissionSetGroupId, PermissionSet.IsOwnedByProfile, ' +\n 'PermissionSetGroup.MasterLabel, PermissionSetGroup.DeveloperName ' +\n `FROM PermissionSetAssignment WHERE AssigneeId = '${escapeSingleQuotes(user.Id)}'`,\n )\n ).records;\n\n const sourceIds: PermissionSourceIds = { profileId: user.ProfileId, permissionSetIds: [], permissionSetGroupIds: [] };\n const groupLabels = new Map<string, string>();\n for (const assignment of assignments) {\n if (assignment.PermissionSet?.IsOwnedByProfile) continue;\n if (assignment.PermissionSetGroupId) {\n sourceIds.permissionSetGroupIds.push(assignment.PermissionSetGroupId);\n groupLabels.set(\n assignment.PermissionSetGroupId,\n assignment.PermissionSetGroup?.MasterLabel ??\n assignment.PermissionSetGroup?.DeveloperName ??\n assignment.PermissionSetGroupId,\n );\n } else if (assignment.PermissionSetId) {\n sourceIds.permissionSetIds.push(assignment.PermissionSetId);\n }\n }\n return { conn, sourceIds, groupLabels };\n}\n\nfunction toSource(ps: PermissionSetRecord | undefined, permission: string, ctx: CheckContext): PermissionSource {\n if (ps?.IsOwnedByProfile) {\n return { type: 'Profile', name: ps.Profile?.Name ?? ps.Label ?? '', permission };\n }\n if (ps?.PermissionSetGroupId) {\n const name = ctx.groupLabels.get(ps.PermissionSetGroupId) ?? ps.PermissionSetGroupId;\n return { type: 'PermissionSetGroup', name, permission };\n }\n return { type: 'PermissionSet', name: ps?.Label ?? ps?.Name ?? '', apiName: ps?.Name, permission };\n}\n\n/** Returns a source for every row whose `permission` field is true. */\nfunction grantsFrom(rows: readonly GrantRow[], permission: string, ctx: CheckContext): PermissionSource[] {\n return rows.filter((row) => row[permission] === true).map((row) => toSource(row.Parent, permission, ctx));\n}\n\nfunction uniqueSources(sources: readonly PermissionSource[]): PermissionSource[] {\n const seen = new Set<string>();\n return sources.filter((source) => {\n const key = `${source.type}|${source.name}|${source.permission}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nasync function describeSObject(conn: Connection, name: string): Promise<DescribeResult> {\n try {\n return await conn.sobject(name).describe();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Could not describe SObject \"${name}\": ${message}`, { cause: error });\n }\n}\n\nasync function queryObjectPermissions(ctx: CheckContext, sobjectType: string): Promise<GrantRow[]> {\n const soql =\n `SELECT ${PARENT_FIELDS}, SobjectType, ${OBJECT_PERMISSION_FIELDS} FROM ObjectPermissions` +\n `${buildUserCondition(ctx.sourceIds)} AND SobjectType = '${escapeSingleQuotes(sobjectType)}'`;\n return (await queryAll<GrantRow>(ctx.conn, soql)).records;\n}\n\n/** Returns the user's permission sets (including their profile's) that have `permissionField` enabled. */\nasync function queryPermissionSets(ctx: CheckContext, permissionField: string): Promise<PermissionSetRecord[]> {\n const { profileId, permissionSetIds, permissionSetGroupIds } = ctx.sourceIds;\n const clauses = [`ProfileId = '${escapeSingleQuotes(profileId)}'`];\n if (permissionSetIds.length > 0) clauses.push(`Id IN ${buildIdList(permissionSetIds)}`);\n if (permissionSetGroupIds.length > 0) clauses.push(`PermissionSetGroupId IN ${buildIdList(permissionSetGroupIds)}`);\n const soql = `SELECT ${PERMISSION_SET_FIELDS} FROM PermissionSet WHERE (${clauses.join(' OR ')}) AND ${permissionField} = true`;\n return (await queryAll<PermissionSetRecord & Record<string, unknown>>(ctx.conn, soql)).records;\n}\n\nasync function checkObject(ctx: CheckContext, target: { object: string; access: ObjectAccess }): Promise<CheckOutcome> {\n const describe = await describeSObject(ctx.conn, target.object);\n const objectName = describe.name ?? target.object;\n const { field, label } = OBJECT_ACCESS[target.access];\n const sources = grantsFrom(await queryObjectPermissions(ctx, objectName), field, ctx);\n return {\n target: objectName,\n description: `${label} access on ${objectName}`,\n granted: sources.length > 0,\n sources: uniqueSources(sources),\n notes: [],\n };\n}\n\nasync function checkField(\n ctx: CheckContext,\n target: { object: string; field: string; access: FieldAccess },\n): Promise<CheckOutcome> {\n const describe = await describeSObject(ctx.conn, target.object);\n const objectName = describe.name ?? target.object;\n const field = describe.fields.find((candidate) => candidate.name.toLowerCase() === target.field.toLowerCase());\n if (!field) {\n throw new Error(`Field \"${target.field}\" was not found on ${objectName}.`);\n }\n const fieldName = `${objectName}.${field.name}`;\n const { field: permission, label } = OBJECT_ACCESS[target.access];\n const notes: string[] = [];\n\n const objectRows = await queryObjectPermissions(ctx, objectName);\n const objectAccess = {\n read: objectRows.some((row) => row.PermissionsRead === true),\n edit: objectRows.some((row) => row.PermissionsEdit === true),\n };\n\n let sources: PermissionSource[];\n if (field.permissionable === false) {\n // Fields such as Id, Name or CreatedDate have no field-level security; the object permission decides.\n notes.push(\n `${fieldName} isn't controlled by field-level security, so access follows the ${label} permission on ${objectName}.`,\n );\n sources = grantsFrom(objectRows, permission, ctx);\n } else {\n const flsRows = (\n await queryAll<GrantRow>(\n ctx.conn,\n `SELECT ${PARENT_FIELDS}, Field, PermissionsRead, PermissionsEdit FROM FieldPermissions` +\n `${buildUserCondition(ctx.sourceIds)} AND SobjectType = '${escapeSingleQuotes(objectName)}'` +\n ` AND Field = '${escapeSingleQuotes(fieldName)}'`,\n )\n ).records;\n sources = grantsFrom(flsRows, permission, ctx);\n if (target.access === 'read') {\n // View All Fields on the object grants Read on every field, regardless of field-level security.\n sources.push(...grantsFrom(objectRows, OBJECT_ACCESS.viewallfields.field, ctx));\n }\n }\n\n const readOnly = target.access === 'edit' && (field.calculated === true || field.autoNumber === true);\n if (readOnly) {\n notes.push(`${fieldName} is a formula or auto-number field, so no user can edit it.`);\n }\n const fieldPermissionGranted = sources.length > 0 && !readOnly;\n if (fieldPermissionGranted && !objectAccess[target.access]) {\n notes.push(\n `The user has field-level access, but no ${label} permission on ${objectName}, so the field isn't accessible.`,\n );\n }\n\n return {\n target: fieldName,\n description: `${label} access on ${fieldName}`,\n granted: fieldPermissionGranted && objectAccess[target.access],\n sources: uniqueSources(sources),\n notes,\n fieldPermissionGranted,\n objectAccess,\n };\n}\n\nasync function checkSetupEntity(\n ctx: CheckContext,\n target: { type: SetupEntityType; namespace?: string; name: string },\n): Promise<CheckOutcome> {\n const config = SETUP_ENTITIES[target.type];\n const namespaceFilter =\n target.namespace === undefined ? '' : ` AND NamespacePrefix = '${escapeSingleQuotes(target.namespace)}'`;\n const matches = (\n await ctx.conn.query<{ Id: string; NamespacePrefix?: string | null }>(\n `SELECT Id, ${config.nameField}, NamespacePrefix FROM ${config.table}` +\n ` WHERE ${config.nameField} = '${escapeSingleQuotes(target.name)}'${namespaceFilter}`,\n )\n ).records;\n const displayName = target.namespace ? `${target.namespace}__${target.name}` : target.name;\n if (matches.length === 0) {\n throw new Error(`The ${config.label} \"${displayName}\" was not found.`);\n }\n // Without a namespace, prefer the org's own entity over managed ones, like Apex name resolution does.\n const local = matches.filter((match) => !match.NamespacePrefix);\n const candidates = matches.length > 1 && local.length === 1 ? local : matches;\n if (candidates.length > 1) {\n const namespaces = candidates.map((match) => match.NamespacePrefix ?? '(none)').join(', ');\n throw new Error(\n `More than one ${config.label} is named \"${target.name}\" (namespaces: ${namespaces}). Specify one as namespace__${target.name}.`,\n );\n }\n const entity = candidates[0];\n const targetName = entity.NamespacePrefix ? `${entity.NamespacePrefix}__${target.name}` : target.name;\n\n const rows = (\n await queryAll<GrantRow>(\n ctx.conn,\n `SELECT ${PARENT_FIELDS}, SetupEntityId FROM SetupEntityAccess${buildUserCondition(ctx.sourceIds)}` +\n ` AND SetupEntityId = '${escapeSingleQuotes(entity.Id)}'`,\n )\n ).records;\n const sources = rows.map((row) => toSource(row.Parent, 'SetupEntityAccess', ctx));\n const notes: string[] = [];\n\n if (config.impliedBy) {\n const implied = (await queryPermissionSets(ctx, config.impliedBy.field)).map((ps) =>\n toSource(ps, config.impliedBy!.field, ctx),\n );\n if (implied.length > 0) {\n sources.push(...implied);\n notes.push(config.impliedBy.note);\n }\n }\n\n return {\n target: targetName,\n description: `access to the ${config.label} ${targetName}`,\n granted: sources.length > 0,\n sources: uniqueSources(sources),\n notes,\n };\n}\n\nasync function checkSystemPermission(ctx: CheckContext, target: { name: string }): Promise<CheckOutcome> {\n const describe = await describeSObject(ctx.conn, 'PermissionSet');\n const expected = `permissions${target.name}`.toLowerCase();\n const field = describe.fields.find(\n (candidate) => candidate.name.toLowerCase() === expected && candidate.type === 'boolean',\n );\n if (!field) {\n throw new Error(\n `Unknown system permission \"${target.name}\". Use the API name without the \"Permissions\" prefix, e.g. ModifyAllData or ViewSetup.`,\n );\n }\n const name = field.name.slice('Permissions'.length);\n const sources = (await queryPermissionSets(ctx, field.name)).map((ps) => toSource(ps, field.name, ctx));\n return {\n target: name,\n description: `the ${name} system permission`,\n granted: sources.length > 0,\n sources: uniqueSources(sources),\n notes: [],\n };\n}\n\nasync function runCheck(ctx: CheckContext, target: CheckTarget): Promise<CheckOutcome> {\n switch (target.type) {\n case 'object':\n return checkObject(ctx, target);\n case 'field':\n return checkField(ctx, target);\n case 'systemPermission':\n return checkSystemPermission(ctx, target);\n case 'apexClass':\n case 'apexPage':\n case 'customPermission':\n return checkSetupEntity(ctx, target);\n }\n}\n\n/**\n * Checks whether a user has one specific permission, and which profile, permission sets, and\n * permission set groups grant it. Answers questions such as \"can this user edit\n * Account.AnnualRevenue?\" with a verdict instead of the raw permission rows.\n */\nexport async function checkUserPermission(\n conn: Connection,\n args: CheckUserPermissionArgs,\n): Promise<CheckUserPermissionResult> {\n if (!args.user) {\n throw new Error('user is required');\n }\n const target = parseTarget(args);\n const user = await resolveUser(conn, args.user);\n const ctx = await loadContext(conn, user);\n const outcome = await runCheck(ctx, target);\n\n const notes = [...outcome.notes];\n if (!user.IsActive) {\n notes.unshift('The user is inactive and cannot log in, regardless of their permissions.');\n }\n const access = target.type === 'object' || target.type === 'field' ? target.access : undefined;\n\n const result: CheckUserPermissionResult = {\n user: {\n id: user.Id,\n username: user.Username,\n name: user.Name,\n isActive: user.IsActive,\n profileName: user.Profile?.Name ?? '',\n },\n check: { type: target.type, target: outcome.target, ...(access ? { access } : {}) },\n granted: outcome.granted,\n summary: `${user.Username} ${outcome.granted ? 'has' : \"doesn't have\"} ${outcome.description}.`,\n sources: outcome.sources,\n notes,\n };\n if (outcome.fieldPermissionGranted !== undefined) result.fieldPermissionGranted = outcome.fieldPermissionGranted;\n if (outcome.objectAccess) result.objectAccess = outcome.objectAccess;\n return result;\n}\n"]}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# summary
|
|
2
|
+
|
|
3
|
+
Check whether a user has a specific permission, and where it comes from.
|
|
4
|
+
|
|
5
|
+
# description
|
|
6
|
+
|
|
7
|
+
Answers questions such as "Can this user edit Account.AnnualRevenue?" or "Does this user have Modify All Data?". The command checks the user's profile, permission sets, and permission set groups, and returns whether the permission is granted and which of them grant it.
|
|
8
|
+
|
|
9
|
+
Check exactly one of the following:
|
|
10
|
+
- An object permission (--object, with --access read, create, edit, delete, viewall, modifyall, or viewallfields)
|
|
11
|
+
- A field permission (--field, with --access read or edit)
|
|
12
|
+
- Access to an Apex class (--apex-class) or a Visualforce page (--apex-page)
|
|
13
|
+
- A custom permission (--custom-permission)
|
|
14
|
+
- A system permission (--system-permission), e.g. ModifyAllData or ViewSetup
|
|
15
|
+
|
|
16
|
+
Field checks take the object permissions into account: a field is only accessible when the user also has Read (or Edit) on the object. View All Fields on the object grants Read on all of its fields. Apex class and Visualforce page checks include access granted by the Author Apex and Customize Application system permissions.
|
|
17
|
+
|
|
18
|
+
Sharing and record-level access aren't checked.
|
|
19
|
+
|
|
20
|
+
The command only reads standard setup objects, so the RFLIB package doesn't need to be installed. The running user needs the View Setup and Configuration permission.
|
|
21
|
+
|
|
22
|
+
# flags.target-org.summary
|
|
23
|
+
|
|
24
|
+
Username or alias of the target org.
|
|
25
|
+
|
|
26
|
+
# flags.target-org.description
|
|
27
|
+
|
|
28
|
+
The username or alias of the Salesforce org to check the permission in.
|
|
29
|
+
|
|
30
|
+
# flags.user.summary
|
|
31
|
+
|
|
32
|
+
User ID (15 or 18 characters) or username of the user to check.
|
|
33
|
+
|
|
34
|
+
# flags.user.description
|
|
35
|
+
|
|
36
|
+
The Salesforce User ID (15 or 18 characters) or the username of the user whose permission should be checked.
|
|
37
|
+
|
|
38
|
+
# flags.object.summary
|
|
39
|
+
|
|
40
|
+
API name of the object to check object permissions for, e.g. Account.
|
|
41
|
+
|
|
42
|
+
# flags.object.description
|
|
43
|
+
|
|
44
|
+
Checks an object permission. Use --access to choose which one; the default is read.
|
|
45
|
+
|
|
46
|
+
# flags.field.summary
|
|
47
|
+
|
|
48
|
+
Field to check field-level security for, in the form Object.Field, e.g. Account.AnnualRevenue.
|
|
49
|
+
|
|
50
|
+
# flags.field.description
|
|
51
|
+
|
|
52
|
+
Checks field-level security for a field. Use --access read (default) or --access edit.
|
|
53
|
+
|
|
54
|
+
# flags.access.summary
|
|
55
|
+
|
|
56
|
+
Access level to check for --object or --field. Default: read.
|
|
57
|
+
|
|
58
|
+
# flags.access.description
|
|
59
|
+
|
|
60
|
+
The access level to check:
|
|
61
|
+
- read, edit: for objects and fields
|
|
62
|
+
- create, delete, viewall (View All Records), modifyall (Modify All Records), viewallfields (View All Fields): for objects only
|
|
63
|
+
|
|
64
|
+
# flags.apex-class.summary
|
|
65
|
+
|
|
66
|
+
Name of the Apex class to check access for.
|
|
67
|
+
|
|
68
|
+
# flags.apex-class.description
|
|
69
|
+
|
|
70
|
+
Checks whether the user can access an Apex class. Use namespace__Name or namespace.Name for a class in a managed package.
|
|
71
|
+
|
|
72
|
+
# flags.apex-page.summary
|
|
73
|
+
|
|
74
|
+
Name of the Visualforce page to check access for.
|
|
75
|
+
|
|
76
|
+
# flags.apex-page.description
|
|
77
|
+
|
|
78
|
+
Checks whether the user can access a Visualforce page. Use namespace__Name for a page in a managed package.
|
|
79
|
+
|
|
80
|
+
# flags.custom-permission.summary
|
|
81
|
+
|
|
82
|
+
API name of the custom permission to check.
|
|
83
|
+
|
|
84
|
+
# flags.custom-permission.description
|
|
85
|
+
|
|
86
|
+
Checks whether the user has a custom permission. Use namespace__Name for a custom permission in a managed package.
|
|
87
|
+
|
|
88
|
+
# flags.system-permission.summary
|
|
89
|
+
|
|
90
|
+
API name of the system permission to check, e.g. ModifyAllData or ViewSetup.
|
|
91
|
+
|
|
92
|
+
# flags.system-permission.description
|
|
93
|
+
|
|
94
|
+
Checks a system (user) permission. Use the name of the permission field on the PermissionSet object, with or without the "Permissions" prefix, e.g. ModifyAllData, ViewAllData, ApiEnabled, or PermissionsAuthorApex.
|
|
95
|
+
|
|
96
|
+
# info.granted
|
|
97
|
+
|
|
98
|
+
GRANTED: %s
|
|
99
|
+
|
|
100
|
+
# info.notGranted
|
|
101
|
+
|
|
102
|
+
NOT GRANTED: %s
|
|
103
|
+
|
|
104
|
+
# info.sources
|
|
105
|
+
|
|
106
|
+
Granted by:
|
|
107
|
+
|
|
108
|
+
# info.source
|
|
109
|
+
|
|
110
|
+
%s "%s" (%s)
|
|
111
|
+
|
|
112
|
+
# info.note
|
|
113
|
+
|
|
114
|
+
Note: %s
|
|
115
|
+
|
|
116
|
+
# examples
|
|
117
|
+
|
|
118
|
+
- Check whether a user can edit a field:
|
|
119
|
+
|
|
120
|
+
$ sf rflib debug userpermissions check --target-org myOrg --user jane@example.com --field Account.AnnualRevenue --access edit
|
|
121
|
+
|
|
122
|
+
- Check whether a user can delete Opportunity records:
|
|
123
|
+
|
|
124
|
+
$ sf rflib debug userpermissions check --target-org myOrg --user 0057000000XXXXXX --object Opportunity --access delete
|
|
125
|
+
|
|
126
|
+
- Check access to an Apex class:
|
|
127
|
+
|
|
128
|
+
$ sf rflib debug userpermissions check --target-org myOrg --user jane@example.com --apex-class OrderController
|
|
129
|
+
|
|
130
|
+
- Check a custom permission:
|
|
131
|
+
|
|
132
|
+
$ sf rflib debug userpermissions check --target-org myOrg --user jane@example.com --custom-permission Approve_Discounts
|
|
133
|
+
|
|
134
|
+
- Check a system permission:
|
|
135
|
+
|
|
136
|
+
$ sf rflib debug userpermissions check --target-org myOrg --user jane@example.com --system-permission ModifyAllData
|