@cclabsnz/sf-audit 1.22.0 → 1.24.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/PERMISSIONS.md +16 -2
  3. package/docs/permissionset/SF_Audit_MFA.permissionset-meta.xml +36 -0
  4. package/lib/chains/CapabilityRegistry.js +16 -8
  5. package/lib/chains/ChainEngine.js +10 -2
  6. package/lib/chains/namedChains.d.ts +1 -0
  7. package/lib/chains/namedChains.js +59 -26
  8. package/lib/checks/impl/ApexCrudFLSCheck.js +12 -3
  9. package/lib/checks/impl/ApexRestEndpointCheck.js +15 -7
  10. package/lib/checks/impl/ApexSharingCheck.js +19 -8
  11. package/lib/checks/impl/FlowsWithoutSharingCheck.d.ts +1 -1
  12. package/lib/checks/impl/FlowsWithoutSharingCheck.js +17 -12
  13. package/lib/checks/impl/GuestExecutableApexCheck.js +18 -9
  14. package/lib/checks/impl/GuestObjectExposureCheck.d.ts +6 -7
  15. package/lib/checks/impl/GuestObjectExposureCheck.js +123 -38
  16. package/lib/checks/impl/GuestSiteOptionsCheck.js +40 -6
  17. package/lib/checks/impl/GuestUserAccessCheck.d.ts +1 -0
  18. package/lib/checks/impl/GuestUserAccessCheck.js +88 -57
  19. package/lib/checks/impl/GuestUserVisibilityCheck.d.ts +9 -6
  20. package/lib/checks/impl/GuestUserVisibilityCheck.js +59 -66
  21. package/lib/checks/impl/HardcodedCredentialsCheck.js +3 -1
  22. package/lib/checks/impl/MfaMethodStrengthCheck.js +6 -5
  23. package/lib/checks/impl/MfaRegistrationCheck.d.ts +1 -1
  24. package/lib/checks/impl/MfaRegistrationCheck.js +67 -18
  25. package/lib/checks/impl/PublicGroupSharingCheck.js +7 -2
  26. package/lib/checks/impl/ReleaseUpdatesCheck.js +1 -1
  27. package/lib/checks/impl/SsoEnforcementCheck.js +6 -4
  28. package/lib/checks/support/apexAccess.d.ts +21 -1
  29. package/lib/checks/support/apexAccess.js +55 -0
  30. package/lib/checks/support/guestShares.d.ts +39 -0
  31. package/lib/checks/support/guestShares.js +113 -0
  32. package/lib/findings/CheckMeta.js +2 -2
  33. package/lib/preflight/permissions.d.ts +1 -1
  34. package/lib/preflight/permissions.js +10 -2
  35. package/lib/renderers/ClientReportRenderer.d.ts +2 -0
  36. package/lib/renderers/ClientReportRenderer.js +18 -3
  37. package/package.json +3 -2
@@ -1,6 +1,8 @@
1
+ import { guestPrincipals, guestReadsSample, guestShareCount } from '../support/guestShares.js';
1
2
  const STANDARD_OBJECTS = ['Account', 'Contact', 'Case', 'Lead', 'Opportunity'];
2
3
  const HEALTH_CLOUD_OBJECTS = ['CarePlan__c', 'CareTeamMember__c', 'EhrPatient__c'];
3
- const SHARE_TABLES = ['AccountShare', 'CaseShare', 'ContactShare', 'OpportunityShare'];
4
+ // The standard objects whose guest shares this check reports; GuestObjectExposureCheck covers the rest.
5
+ const SHARED_OBJECTS = ['Account', 'Case', 'Contact', 'Opportunity'];
4
6
  export class GuestUserAccessCheck {
5
7
  id = 'guest-user-access';
6
8
  name = 'Guest User Access';
@@ -23,14 +25,24 @@ export class GuestUserAccessCheck {
23
25
  });
24
26
  return { findings };
25
27
  }
26
- // Build profile → users map and unique profile ID list for batch queries
27
- const profileUserMap = new Map();
28
- for (const user of guestUsers) {
29
- const list = profileUserMap.get(user.ProfileId) ?? [];
30
- list.push(user);
31
- profileUserMap.set(user.ProfileId, list);
28
+ // ObjectPermissions.ParentId is a permission set Id, never a profile Id: a profile's object
29
+ // permissions sit on the permission set it owns. The guests' assignments cover that one and any
30
+ // permission set assigned to a guest. (Filtering ParentId on profile Ids matched nothing.)
31
+ const userById = new Map(guestUsers.map((u) => [u.Id, u]));
32
+ const guestsByPermSet = new Map();
33
+ try {
34
+ const assignments = await ctx.soql.queryAll(`SELECT AssigneeId, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId IN (${guestUsers.map((u) => `'${u.Id}'`).join(', ')})`);
35
+ for (const a of assignments) {
36
+ const u = userById.get(a.AssigneeId);
37
+ if (!u)
38
+ continue;
39
+ guestsByPermSet.set(a.PermissionSetId, [...(guestsByPermSet.get(a.PermissionSetId) ?? []), u]);
40
+ }
41
+ }
42
+ catch {
43
+ // Unreadable: object access is then not judged (no read or write finding).
32
44
  }
33
- const profileIds = [...profileUserMap.keys()];
45
+ const permSetIds = [...guestsByPermSet.keys()];
34
46
  // Determine which objects to check (include HC objects only if installed)
35
47
  const objectsToCheck = [...STANDARD_OBJECTS];
36
48
  if (ctx.cache.healthCloudInstalled === true) {
@@ -38,59 +50,65 @@ export class GuestUserAccessCheck {
38
50
  }
39
51
  const writeViolations = [];
40
52
  const readViolations = [];
41
- // Single batch query: all profiles × all objects (replaces per-profile loop)
42
- const profileIdList = profileIds.map((id) => `'${id}'`).join(', ');
53
+ // One batch query: every guest permission set × every object.
43
54
  const objectList = objectsToCheck.map((o) => `'${o}'`).join(', ');
44
- try {
45
- const perms = await ctx.soql.queryAll(`SELECT ParentId, SobjectType, PermissionsCreate, PermissionsEdit, PermissionsDelete, PermissionsRead
55
+ // Objects some guest can read, for the share-table fallback below; null when unknown.
56
+ let guestReadable = permSetIds.length === 0 ? new Set() : null;
57
+ if (permSetIds.length > 0)
58
+ try {
59
+ const perms = await ctx.soql.queryAll(`SELECT ParentId, SobjectType, PermissionsCreate, PermissionsEdit, PermissionsDelete, PermissionsRead
46
60
  FROM ObjectPermissions
47
- WHERE ParentId IN (${profileIdList})
61
+ WHERE ParentId IN (${permSetIds.map((id) => `'${id}'`).join(', ')})
48
62
  AND SobjectType IN (${objectList})`);
49
- for (const perm of perms) {
50
- const profileUsers = profileUserMap.get(perm.ParentId) ?? [];
51
- if (perm.PermissionsCreate || perm.PermissionsEdit || perm.PermissionsDelete) {
52
- for (const u of profileUsers) {
53
- writeViolations.push({
54
- userId: u.Id,
55
- username: u.Username,
56
- sobjectType: perm.SobjectType,
57
- canCreate: perm.PermissionsCreate,
58
- canEdit: perm.PermissionsEdit,
59
- canDelete: perm.PermissionsDelete,
60
- });
63
+ guestReadable = new Set(perms.filter((p) => p.PermissionsRead).map((p) => p.SobjectType));
64
+ for (const perm of perms) {
65
+ const profileUsers = guestsByPermSet.get(perm.ParentId) ?? [];
66
+ if (perm.PermissionsCreate || perm.PermissionsEdit || perm.PermissionsDelete) {
67
+ for (const u of profileUsers) {
68
+ writeViolations.push({
69
+ userId: u.Id,
70
+ username: u.Username,
71
+ sobjectType: perm.SobjectType,
72
+ canCreate: perm.PermissionsCreate,
73
+ canEdit: perm.PermissionsEdit,
74
+ canDelete: perm.PermissionsDelete,
75
+ });
76
+ }
61
77
  }
62
- }
63
- else if (perm.PermissionsRead) {
64
- for (const u of profileUsers) {
65
- readViolations.push({
66
- userId: u.Id,
67
- username: u.Username,
68
- sobjectType: perm.SobjectType,
69
- });
78
+ else if (perm.PermissionsRead) {
79
+ for (const u of profileUsers) {
80
+ readViolations.push({
81
+ userId: u.Id,
82
+ username: u.Username,
83
+ sobjectType: perm.SobjectType,
84
+ });
85
+ }
70
86
  }
71
87
  }
72
88
  }
73
- }
74
- catch {
75
- // Skip on error
76
- }
77
- const sharingExposures = [];
78
- const userIdList = guestUsers.map((u) => `'${u.Id}'`).join(', ');
79
- for (const shareTable of SHARE_TABLES) {
80
- try {
81
- const result = await ctx.soql.query(`SELECT UserOrGroupId, COUNT(Id) cnt
82
- FROM ${shareTable}
83
- WHERE UserOrGroupId IN (${userIdList})
84
- AND RowCause = 'SharingRule'
85
- GROUP BY UserOrGroupId`);
86
- const totalCount = result.records.reduce((sum, r) => sum + (r.cnt ?? 0), 0);
87
- if (totalCount > 0) {
88
- sharingExposures.push({ shareTable, count: totalCount });
89
- }
90
- }
91
89
  catch {
92
- // Object may not be accessible — skip silently
90
+ // Skip on error
91
+ }
92
+ const sharingExposures = [];
93
+ const guestIds = guestUsers.map((u) => u.Id);
94
+ const guestIdList = guestIds.map((i) => `'${i}'`).join(', ');
95
+ const principals = await guestPrincipals(ctx, guestIds);
96
+ for (const obj of SHARED_OBJECTS) {
97
+ // Null: the share table could not be read (or the object is not shareable in this org).
98
+ const count = await guestShareCount(ctx, obj, principals);
99
+ if (count !== null && count > 0) {
100
+ sharingExposures.push({ shareTable: `${obj}Share`, count });
101
+ continue;
93
102
  }
103
+ // The fallback asks only where a guest can read the object (a read without object access is
104
+ // no exposure; unknown access is asked), and not where the guest owns records: owned records
105
+ // are always readable and are reported as guest-object-exposure-guest-owned.
106
+ if (guestReadable !== null && !guestReadable.has(obj))
107
+ continue;
108
+ if (await this.guestOwns(ctx, obj, guestIdList))
109
+ continue;
110
+ if ((await guestReadsSample(ctx, obj, guestIds)) === true)
111
+ sharingExposures.push({ shareTable: `${obj}Share` });
94
112
  }
95
113
  // Emit findings based on what was found
96
114
  if (writeViolations.length > 0) {
@@ -132,19 +150,24 @@ export class GuestUserAccessCheck {
132
150
  });
133
151
  }
134
152
  if (sharingExposures.length > 0) {
135
- const count = sharingExposures.reduce((sum, e) => sum + e.count, 0);
153
+ const count = sharingExposures.reduce((sum, e) => sum + (e.count ?? 0), 0);
154
+ const confirmedOnly = sharingExposures.filter((e) => e.count === undefined).length;
136
155
  findings.push({
137
156
  id: 'guest-user-sharing-exposure',
138
157
  category: this.category,
139
158
  riskLevel: 'HIGH',
140
- title: `${count} object sharing rule(s) expose records to guest users`,
159
+ title: count > 0
160
+ ? `${count} share row(s) give guest users access to Account, Case, Contact or Opportunity records${confirmedOnly > 0 ? `, and guests read records on ${confirmedOnly} more object(s)` : ''}`
161
+ : `Guest users can read Account, Case, Contact or Opportunity records on ${confirmedOnly} object(s)`,
141
162
  affectedItems: sharingExposures.map((e) => ({
142
163
  label: e.shareTable,
143
164
  url: `${baseUrl}/lightning/setup/SecuritySharing/page`,
144
- note: `${e.count} sharing rule(s): review and remove guest-targeting rules`,
165
+ note: e.count !== undefined
166
+ ? `${e.count} share row(s) giving guests access: review the guest sharing rules and legacy shares`
167
+ : 'No share row seen, but UserRecordAccess confirms a guest user reads a sampled record',
145
168
  })),
146
- detail: 'Sharing rules targeting guest users can expose internal records to unauthenticated visitors.',
147
- remediation: 'Review and remove sharing rules that grant guest users access to Salesforce records. Use Experience Cloud sites with explicit data access controls instead.',
169
+ detail: 'Records on these objects are shared with guest users: by guest user sharing rules (and the parent access they imply), or by manual, Apex-managed or public-group shares made before Winter \'21, which the platform did not remove. Any unauthenticated visitor to the site can read the shared records.',
170
+ remediation: 'Confirm the shared records are meant to be public. If not, narrow or remove the guest user sharing rules (Setup → Sharing Settings), delete manual and Apex shares to the guest user, and remove the guest user from public groups and queues.',
148
171
  });
149
172
  }
150
173
  if (writeViolations.length === 0 && readViolations.length === 0 && sharingExposures.length === 0) {
@@ -165,5 +188,13 @@ export class GuestUserAccessCheck {
165
188
  }
166
189
  return { findings };
167
190
  }
191
+ async guestOwns(ctx, obj, guestIdList) {
192
+ try {
193
+ return (await ctx.soql.query(`SELECT COUNT() FROM ${obj} WHERE OwnerId IN (${guestIdList})`)).totalSize > 0;
194
+ }
195
+ catch {
196
+ return false;
197
+ }
198
+ }
168
199
  }
169
200
  //# sourceMappingURL=GuestUserAccessCheck.js.map
@@ -6,13 +6,16 @@ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
6
6
  * not in their fixed object lists and is rarely surfaced by a guest profile's
7
7
  * ObjectPermissions.
8
8
  *
9
- * Three independent paths reach the same outcome, so all three are graded:
9
+ * Three paths are graded:
10
10
  * - "View All Users" on a guest profile/permission set: total bypass of User
11
11
  * sharing, every User record readable regardless of OWD (CRITICAL).
12
- * - A public EXTERNAL org-wide default on `User` (Read/ReadWrite): every User
13
- * record is visible to portal and guest users by sharing alone (HIGH).
14
- * - An explicit Read grant on `User` in a guest permission set, which combined
15
- * with any sharing path turns the roster into a queryable directory (HIGH).
12
+ * (Not a Read grant on `User` in a guest permission set: User takes no object
13
+ * permissions, so ObjectPermissions never has a User row; a live org had none
14
+ * among all its permission sets.)
15
+ * - A public EXTERNAL org-wide default on `User` (Read/ReadWrite). Since Winter '21
16
+ * secure guest record access keeps the guest OWD Private on every object, User
17
+ * included, so this shows every User record to logged-in portal and community
18
+ * users, not to guests (MEDIUM).
16
19
  *
17
20
  * The INTERNAL sharing model is reported for context but never graded: `User`
18
21
  * ships as Public Read Only in every org, so grading it would fire on every audit.
@@ -28,7 +31,7 @@ export declare class GuestUserVisibilityCheck implements SecurityCheck {
28
31
  readonly id = "guest-user-visibility";
29
32
  readonly name = "Guest Visibility of Other Users";
30
33
  readonly category = "Access Control";
31
- readonly description = "Checks whether unauthenticated guests can see other User records \u2014 via View All Users, a public external OWD on User, or a guest Read grant on the User object";
34
+ readonly description = "Checks whether unauthenticated guests can see other User records \u2014 via View All Users \u2014 and whether a public external OWD on User shows the roster to logged-in external users";
32
35
  run(ctx: AuditContext): Promise<CheckResult>;
33
36
  private inconclusive;
34
37
  }
@@ -1,4 +1,7 @@
1
- // External sharing models that expose every User record to external (portal/guest) users.
1
+ // User types of logged-in external (portal, community, partner) users, as UserType's picklist has them.
2
+ const EXTERNAL_USER_TYPES = ['PowerCustomerSuccess', 'CustomerSuccess', 'PowerPartner', 'CspLitePortal', 'CsnOnly', 'SelfService'];
3
+ // External sharing models that expose every User record to logged-in external (portal/community)
4
+ // users. Not to guests: secure guest record access keeps the guest OWD Private on every object.
2
5
  const PUBLIC_OWD = new Set(['Read', 'ReadWrite', 'ReadSelect']);
3
6
  /**
4
7
  * Detects whether unauthenticated guests can see OTHER USERS — the identity-
@@ -6,13 +9,16 @@ const PUBLIC_OWD = new Set(['Read', 'ReadWrite', 'ReadSelect']);
6
9
  * not in their fixed object lists and is rarely surfaced by a guest profile's
7
10
  * ObjectPermissions.
8
11
  *
9
- * Three independent paths reach the same outcome, so all three are graded:
12
+ * Three paths are graded:
10
13
  * - "View All Users" on a guest profile/permission set: total bypass of User
11
14
  * sharing, every User record readable regardless of OWD (CRITICAL).
12
- * - A public EXTERNAL org-wide default on `User` (Read/ReadWrite): every User
13
- * record is visible to portal and guest users by sharing alone (HIGH).
14
- * - An explicit Read grant on `User` in a guest permission set, which combined
15
- * with any sharing path turns the roster into a queryable directory (HIGH).
15
+ * (Not a Read grant on `User` in a guest permission set: User takes no object
16
+ * permissions, so ObjectPermissions never has a User row; a live org had none
17
+ * among all its permission sets.)
18
+ * - A public EXTERNAL org-wide default on `User` (Read/ReadWrite). Since Winter '21
19
+ * secure guest record access keeps the guest OWD Private on every object, User
20
+ * included, so this shows every User record to logged-in portal and community
21
+ * users, not to guests (MEDIUM).
16
22
  *
17
23
  * The INTERNAL sharing model is reported for context but never graded: `User`
18
24
  * ships as Public Read Only in every org, so grading it would fire on every audit.
@@ -28,12 +34,56 @@ export class GuestUserVisibilityCheck {
28
34
  id = 'guest-user-visibility';
29
35
  name = 'Guest Visibility of Other Users';
30
36
  category = 'Access Control';
31
- description = 'Checks whether unauthenticated guests can see other User records — via View All Users, a public external OWD on User, or a guest Read grant on the User object';
37
+ description = 'Checks whether unauthenticated guests can see other User records — via View All Users — and whether a public external OWD on User shows the roster to logged-in external users';
32
38
  async run(ctx) {
33
39
  const findings = [];
34
40
  const baseUrl = ctx.orgInfo.instanceUrl;
35
41
  const sharingUrl = `${baseUrl}/lightning/setup/SecuritySharing/page`;
36
42
  const permSetUrl = `${baseUrl}/lightning/setup/PermSets/home`;
43
+ // The external org-wide default on User reaches logged-in external users, not guests, so it is
44
+ // graded whether or not the org has a guest user.
45
+ let userEntity;
46
+ try {
47
+ const defs = await ctx.soql.queryAll("SELECT QualifiedApiName, InternalSharingModel, ExternalSharingModel FROM EntityDefinition WHERE QualifiedApiName = 'User'");
48
+ userEntity = defs.find((d) => d.QualifiedApiName === 'User');
49
+ }
50
+ catch {
51
+ // OWD unreadable — the other two signals are still graded below.
52
+ }
53
+ const external = userEntity?.ExternalSharingModel ?? null;
54
+ const internal = userEntity?.InternalSharingModel ?? null;
55
+ // Nobody is reached without an external user or a site to sign up on. Unreadable counts are
56
+ // treated as present, so an access gap never hides the finding.
57
+ const countOr = async (q) => {
58
+ try {
59
+ return (await ctx.soql.query(q)).totalSize;
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ };
65
+ const externalUsers = external && PUBLIC_OWD.has(external)
66
+ ? await countOr(`SELECT COUNT() FROM User WHERE IsActive = true AND UserType IN (${EXTERNAL_USER_TYPES.map((t) => `'${t}'`).join(', ')})`)
67
+ : 0;
68
+ const sites = external && PUBLIC_OWD.has(external) ? await countOr('SELECT COUNT() FROM Network') : 0;
69
+ const reachesSomeone = externalUsers !== 0 || sites !== 0;
70
+ if (external && PUBLIC_OWD.has(external) && reachesSomeone) {
71
+ findings.push({
72
+ id: 'guest-user-visibility-owd',
73
+ category: this.category,
74
+ riskLevel: 'MEDIUM',
75
+ title: `The User object has a public external org-wide default (${external}): logged-in external users can see every user`,
76
+ detail: 'The external org-wide default on User controls what logged-in portal and community users can see of other users. Set to Read or Read/Write, every User record in the org is visible to any external user by sharing alone, turning each portal or community account into a directory of internal staff. It does not reach unauthenticated guests: since Winter \'21 secure guest record access keeps the guest org-wide default Private on every object, User included. Where self-registration is on, anyone who signs up gets the directory.',
77
+ remediation: 'Set the User object\'s Default External Access to Private in Setup → Sharing Settings. Where portal users legitimately need to see each other, grant it narrowly with sharing sets or user sharing rules rather than an open default.',
78
+ affectedItems: [
79
+ {
80
+ label: 'User',
81
+ url: sharingUrl,
82
+ note: `External OWD: ${external}${internal ? ` (internal: ${internal})` : ''}; ${externalUsers ?? 'unknown number of'} active external user(s), ${sites ?? 'unknown number of'} Experience Cloud site(s)`,
83
+ },
84
+ ],
85
+ });
86
+ }
37
87
  let guests;
38
88
  try {
39
89
  guests = await ctx.soql.queryAll("SELECT Id, Username FROM User WHERE UserType = 'Guest' AND IsActive = true");
@@ -65,7 +115,6 @@ export class GuestUserVisibilityCheck {
65
115
  return { findings };
66
116
  }
67
117
  const guestById = new Map(guests.map((g) => [g.Id, g]));
68
- const labelById = new Map(psa.filter((p) => p.PermissionSet).map((p) => [p.PermissionSetId, p.PermissionSet.Label]));
69
118
  // 1. "View All Users" — bypasses User sharing entirely.
70
119
  const viewAll = psa.filter((p) => p.PermissionSet?.PermissionsViewAllUsers);
71
120
  if (viewAll.length > 0) {
@@ -74,7 +123,7 @@ export class GuestUserVisibilityCheck {
74
123
  category: this.category,
75
124
  riskLevel: 'CRITICAL',
76
125
  title: `${viewAll.length} guest permission grant(s) include "View All Users"`,
77
- detail: '"View All Users" lets the holder read every User record in the org regardless of the sharing model. On a guest user this hands an unauthenticated visitor the full staff roster — usernames, email addresses, roles, manager relationships and phone numbers — which is a ready-made target list for credential stuffing, phishing and social engineering against named administrators.',
126
+ detail: '"View All Users" lets the holder read every User record in the org regardless of the sharing model. It can no longer be granted to guests since Winter \'21, so this is a grant that survived from before. On a guest user it hands an unauthenticated visitor the full staff roster — usernames, email addresses, roles, manager relationships and phone numbers — which is a ready-made target list for credential stuffing, phishing and social engineering against named administrators.',
78
127
  remediation: 'Remove "View All Users" from the guest profile and from every permission set assigned to a guest user. Guests must never hold org-wide user visibility.',
79
128
  affectedItems: viewAll.slice(0, 30).map((p) => ({
80
129
  label: `${guestById.get(p.AssigneeId)?.Username ?? p.AssigneeId} — via ${p.PermissionSet.Label}`,
@@ -83,62 +132,6 @@ export class GuestUserVisibilityCheck {
83
132
  })),
84
133
  });
85
134
  }
86
- // 2. External org-wide default on User.
87
- let userEntity;
88
- try {
89
- const defs = await ctx.soql.queryAll("SELECT QualifiedApiName, InternalSharingModel, ExternalSharingModel FROM EntityDefinition WHERE QualifiedApiName = 'User'");
90
- userEntity = defs.find((d) => d.QualifiedApiName === 'User');
91
- }
92
- catch {
93
- // OWD unreadable — the other two signals are still graded below.
94
- }
95
- const external = userEntity?.ExternalSharingModel ?? null;
96
- const internal = userEntity?.InternalSharingModel ?? null;
97
- if (external && PUBLIC_OWD.has(external)) {
98
- findings.push({
99
- id: 'guest-user-visibility-owd',
100
- category: this.category,
101
- riskLevel: 'HIGH',
102
- title: `The User object has a public external org-wide default (${external})`,
103
- detail: 'The external org-wide default on User controls what portal and guest users can see of other users. Set to Read or Read/Write, every User record in the org is visible to any external or unauthenticated visitor by sharing alone — no permission grant required — turning the site into a directory of internal staff.',
104
- remediation: 'Set the User object\'s Default External Access to Private in Setup → Sharing Settings. Where portal users legitimately need to see each other, grant it narrowly with sharing sets or user sharing rules rather than an open default.',
105
- affectedItems: [
106
- {
107
- label: 'User',
108
- url: sharingUrl,
109
- note: `External OWD: ${external}${internal ? ` (internal: ${internal})` : ''} — ${guests.length} active guest user(s)`,
110
- },
111
- ],
112
- });
113
- }
114
- // 3. Explicit Read grant on the User object in a guest permission set.
115
- const psIds = [...new Set(psa.map((p) => p.PermissionSetId))];
116
- let userRead = [];
117
- if (psIds.length > 0) {
118
- try {
119
- const psIn = psIds.map((i) => `'${i}'`).join(', ');
120
- userRead = await ctx.soql.queryAll(`SELECT ParentId, SobjectType, PermissionsRead FROM ObjectPermissions
121
- WHERE ParentId IN (${psIn}) AND SobjectType = 'User' AND PermissionsRead = true`);
122
- }
123
- catch {
124
- // Object permissions unreadable — the other two signals still stand.
125
- }
126
- }
127
- if (userRead.length > 0) {
128
- findings.push({
129
- id: 'guest-user-visibility-object-read',
130
- category: this.category,
131
- riskLevel: 'HIGH',
132
- title: `${userRead.length} guest permission grant(s) give Read access to the User object`,
133
- detail: 'A guest permission set or profile grants Read on the User object. Object-level read is what makes User queryable at all for a guest; combined with any sharing path that exposes records — a public external OWD, a user sharing rule, or guest member visibility on an Experience site — it turns the User table into an enumerable directory reachable over the UI API.',
134
- remediation: 'Remove Read on the User object from guest profiles and guest permission sets. Where site components must show a name, expose it through Apex that returns only the specific fields required.',
135
- affectedItems: userRead.slice(0, 30).map((p) => ({
136
- label: labelById.get(p.ParentId) ?? p.ParentId,
137
- url: permSetUrl,
138
- note: 'Read on User granted: remove from guest permissions',
139
- })),
140
- });
141
- }
142
135
  if (findings.length === 0) {
143
136
  findings.push({
144
137
  id: 'guest-user-visibility-ok',
@@ -146,7 +139,7 @@ export class GuestUserVisibilityCheck {
146
139
  riskLevel: 'LOW',
147
140
  passed: true,
148
141
  title: `${guests.length} active guest user(s); no user-enumeration path found`,
149
- detail: `No guest holds "View All Users", the User object's external org-wide default is ${external ?? 'not publicly readable'}, and no guest permission set grants Read on User.${internal ? ` The internal model is ${internal}, which is the platform default and is not graded here.` : ''} One control is not API-readable: the "Portal User Visibility" and "Community User Visibility" checkboxes in Sharing Settings are exposed to no read API this plugin uses, so that leg needs manual confirmation.`,
142
+ detail: `No guest holds "View All Users", the User object's external org-wide default is ${external ?? 'not publicly readable'}.${internal ? ` The internal model is ${internal}, which is the platform default and is not graded here.` : ''} One control is not API-readable: the "Portal User Visibility" and "Community User Visibility" checkboxes in Sharing Settings are exposed to no read API this plugin uses, so that leg needs manual confirmation.`,
150
143
  remediation: 'In Setup → Sharing Settings, confirm the portal/community user visibility checkboxes are off unless a member directory is intended, and keep the User external default Private as sites are added. The per-site equivalent ("Let guest users see other members") is covered by the Experience Cloud Guest Site Options check.',
151
144
  affectedItems: [{ label: 'Sharing Settings', url: sharingUrl, note: 'Manual verification of user visibility checkboxes' }],
152
145
  });
@@ -5,7 +5,9 @@ const HIGH_RISK_PATTERNS = [
5
5
  /Basic\s+[A-Za-z0-9+/]{20,}=*/gi, // Basic auth (min length)
6
6
  /Authorization['":\s]+['"](Bearer|Basic)/gi, // Auth header construction
7
7
  // Credential variable assignments with a string literal RHS (single or double quoted)
8
- /(?:password|passwd|secret|apiKey|api_key|clientSecret|client_secret|accessToken|access_token|authToken|auth_token)\s*[=+]\s*['"][^'"]{8,}['"]/gi,
8
+ // The literal must end the expression, so "'client_secret=' + EncodingUtil.urlEncode(cfg.Secret__c, 'UTF-8')"
9
+ // (a value read at run time) does not match.
10
+ /(?:password|passwd|secret|apiKey|api_key|clientSecret|client_secret|accessToken|access_token|authToken|auth_token)\s*[=+]\s*['"][^'"]{8,}['"]\s*[;,)]/gi,
9
11
  ];
10
12
  const ENDPOINT_PATTERN = /\.setEndpoint\s*\(\s*'(https?:\/\/[^']+)'/gi;
11
13
  const IS_TEST_CLASS = /@IsTest\b/i;
@@ -34,8 +34,8 @@ export class MfaMethodStrengthCheck {
34
34
  riskLevel: 'INFO',
35
35
  inconclusive: true,
36
36
  title: 'No MFA registration data available: MfaRegistrationCheck must run first',
37
- detail: 'MFA registration data was not gathered: either MfaRegistrationCheck did not run, or TwoFactorInfo could not be read. MFA method strength analysis cannot be performed without this data.',
38
- remediation: 'Ensure MfaRegistrationCheck runs before this check. Grant "Manage Multi-Factor Authentication in API" permission to the audit user.',
37
+ detail: 'MFA registration data was not gathered: either MfaRegistrationCheck did not run, or TwoFactorMethodsInfo could not be read (it needs "Manage MFA in API"; see PERMISSIONS.md). MFA method strength analysis cannot be performed without this data.',
38
+ remediation: 'Ensure MfaRegistrationCheck runs before this check, and that the audit user holds "Manage MFA in API" (optional: Salesforce grants it only with user-management permissions; see PERMISSIONS.md).',
39
39
  });
40
40
  return { findings };
41
41
  }
@@ -45,9 +45,10 @@ export class MfaMethodStrengthCheck {
45
45
  id: 'mfa-method-strength-none-registered',
46
46
  category: this.category,
47
47
  riskLevel: 'INFO',
48
- passed: true,
49
- title: 'No registered MFA methods to grade',
50
- detail: 'No active internal user has a registered MFA method, so there is no method strength to assess. Missing registration itself is reported by the MFA registration check.',
48
+ // Nothing was graded, so it is no assurance about method strength (not passed); the data was
49
+ // read, so it is not inconclusive either. INFO carries no penalty under the default scoring.
50
+ title: 'MFA method strength not graded: no user has registered a method',
51
+ detail: 'No active internal user has a registered MFA method in Salesforce, so there is no method strength to assess. With single sign-on, MFA happens at the identity provider and this is expected; otherwise missing registration is reported by the MFA registration check.',
51
52
  remediation: 'None for method strength. Address MFA registration coverage first.',
52
53
  });
53
54
  return { findings };
@@ -4,7 +4,7 @@ export declare class MfaRegistrationCheck implements SecurityCheck {
4
4
  readonly id = "mfa-registration";
5
5
  readonly name = "MFA Method Registration";
6
6
  readonly category = "Authentication";
7
- readonly description = "Identifies active standard users who have not registered any MFA method in TwoFactorInfo";
7
+ readonly description = "Identifies active standard users who have not registered an MFA method (authenticator app, Salesforce Authenticator, security key or built-in authenticator) in TwoFactorMethodsInfo";
8
8
  readonly populatesCache: readonly ['mfaRegistrations'];
9
9
  run(ctx: AuditContext): Promise<CheckResult>;
10
10
  }
@@ -1,8 +1,27 @@
1
+ /**
2
+ * TwoFactorMethodsInfo flags, mapped to the method names MfaMethodStrengthCheck grades. TwoFactorInfo
3
+ * is not used: its Type picklist holds only 'TOTP', so it never shows Salesforce Authenticator,
4
+ * security keys or built-in authenticators.
5
+ */
6
+ const METHOD_FLAGS = [
7
+ ['HasSecurityKey', 'FIDO2'],
8
+ ['HasU2F', 'U2F'],
9
+ ['HasBuiltInAuthenticator', 'BUILT_IN_AUTHENTICATOR'],
10
+ ['HasSalesforceAuthenticator', 'SALESFORCE_AUTHENTICATOR'],
11
+ ['HasTotp', 'TOTP'],
12
+ ['HasUserVerifiedMobileNumber', 'SMS_OTP'],
13
+ ['HasVerifiedMobileNumber', 'SMS_OTP'],
14
+ ['HasUserVerifiedEmailAddress', 'EMAIL'],
15
+ ['HasTempCode', 'VERIFICATIONCODE'],
16
+ ];
17
+ // Methods that satisfy Salesforce's MFA requirement. A verified phone or email address, or a
18
+ // temporary code, is a sign-in fallback, not an MFA registration.
19
+ const QUALIFYING = new Set(['FIDO2', 'U2F', 'BUILT_IN_AUTHENTICATOR', 'SALESFORCE_AUTHENTICATOR', 'TOTP']);
1
20
  export class MfaRegistrationCheck {
2
21
  id = 'mfa-registration';
3
22
  name = 'MFA Method Registration';
4
23
  category = 'Authentication';
5
- description = 'Identifies active standard users who have not registered any MFA method in TwoFactorInfo';
24
+ description = 'Identifies active standard users who have not registered an MFA method (authenticator app, Salesforce Authenticator, security key or built-in authenticator) in TwoFactorMethodsInfo';
6
25
  populatesCache = ['mfaRegistrations'];
7
26
  async run(ctx) {
8
27
  const findings = [];
@@ -17,14 +36,20 @@ export class MfaRegistrationCheck {
17
36
  AND UserType = 'Standard'
18
37
  AND ${frozenFilter}`);
19
38
  const totalActiveUsers = countResult.records[0]?.expr0 ?? 0;
20
- let twoFactorRecords = [];
39
+ // Same population as the count: active, unfrozen standard users. Frozen users are dropped from
40
+ // the registrations below client-side; a semi-join on TwoFactorMethodsInfo has not been tested against a
41
+ // live org. Like the count, this reads UserLogin outside the TwoFactorMethodsInfo error handling.
42
+ const frozen = new Set((await ctx.soql.queryAll(`SELECT UserId FROM UserLogin WHERE IsFrozen = true`))
43
+ .map((r) => r.UserId));
44
+ let methodRecords = [];
21
45
  try {
22
- twoFactorRecords = await ctx.soql.queryAll(`SELECT UserId, User.Username, User.Profile.Name, Type
23
- FROM TwoFactorInfo
46
+ // queryAll pages through every row, so a large org is not cut off at a fixed limit and its
47
+ // remaining users counted as unregistered.
48
+ methodRecords = (await ctx.soql.queryAll(`SELECT UserId, User.Username, User.Profile.Name, ${METHOD_FLAGS.map(([f]) => f).join(', ')}
49
+ FROM TwoFactorMethodsInfo
24
50
  WHERE User.IsActive = true
25
51
  AND User.UserType = 'Standard'
26
- ORDER BY UserId
27
- LIMIT 2000`);
52
+ ORDER BY UserId`)).filter((r) => !frozen.has(r.UserId));
28
53
  }
29
54
  catch {
30
55
  // Leave the cache unset: an empty list would read downstream as "nobody registered MFA".
@@ -33,35 +58,59 @@ export class MfaRegistrationCheck {
33
58
  category: this.category,
34
59
  riskLevel: 'INFO',
35
60
  inconclusive: true,
36
- title: 'TwoFactorInfo could not be queried: MFA registration status cannot be verified',
37
- detail: 'The TwoFactorInfo object was not accessible. This may indicate the audit user lacks the "Manage Multi-Factor Authentication in API" permission or the org edition does not support this query.',
38
- remediation: 'Grant "Manage Multi-Factor Authentication in API" permission to the audit user. Review MFA registration status manually in Setup → Identity → Identity Verification.',
61
+ title: 'TwoFactorMethodsInfo could not be queried: MFA registration status cannot be verified',
62
+ detail: 'The TwoFactorMethodsInfo object was not accessible. The audit user most likely lacks the "Manage MFA in API" permission (PermissionsManageTwoFactor), which hides the object.',
63
+ remediation: 'Grant the audit user "Manage MFA in API" through a permission set, or review MFA registration manually in Setup → Identity → Identity Verification. Salesforce grants it only with user-management permissions (Manage Users, Manage Internal Users, Manage Sharing, Manage Roles, Reset Passwords and others; PERMISSIONS.md lists them), so it suits an audit user who is already an administrator.',
39
64
  affectedItems: [{ label: 'Identity Verification Setup', url: setupUrl }],
40
65
  });
41
66
  return { findings };
42
67
  }
68
+ // Only users with a qualifying method are registered, and only they go to the cache: a user
69
+ // with just a verified phone, email or temporary code has no MFA method, and is reported here
70
+ // as unregistered, not graded by the strength check as "weak MFA" (which would rate an admin
71
+ // who verified an email worse than one who did nothing). Their fallbacks still appear in the
72
+ // cached methods of registered users.
43
73
  const userMethodMap = new Map();
44
- for (const r of twoFactorRecords) {
74
+ for (const r of methodRecords) {
75
+ const methods = [...new Set(METHOD_FLAGS.filter(([f]) => r[f] === true).map(([, m]) => m))];
76
+ if (methods.length === 0)
77
+ continue;
45
78
  const existing = userMethodMap.get(r.UserId);
46
79
  if (existing) {
47
- existing.methods.push(r.Type);
80
+ existing.methods = [...new Set([...existing.methods, ...methods])];
48
81
  }
49
82
  else {
50
83
  userMethodMap.set(r.UserId, {
51
- username: r.User.Username,
52
- profileName: r.User.Profile?.Name ?? 'Unknown',
53
- methods: [r.Type],
84
+ username: r.User?.Username ?? r.UserId,
85
+ profileName: r.User?.Profile?.Name ?? 'Unknown',
86
+ methods,
54
87
  });
55
88
  }
56
89
  }
57
- ctx.cache.mfaRegistrations = [...userMethodMap.entries()].map(([userId, data]) => ({
90
+ ctx.cache.mfaRegistrations = [...userMethodMap.entries()].filter(([, data]) => data.methods.some((m) => QUALIFYING.has(m))).map(([userId, data]) => ({
58
91
  userId,
59
92
  username: data.username,
60
93
  profileName: data.profileName,
61
94
  methods: data.methods,
62
95
  }));
63
- const registeredCount = userMethodMap.size;
96
+ const registeredCount = [...userMethodMap.values()].filter((u) => u.methods.some((m) => QUALIFYING.has(m))).length;
97
+ const fallbackOnly = userMethodMap.size - registeredCount;
64
98
  const unregisteredCount = Math.max(0, totalActiveUsers - registeredCount);
99
+ // The audit user is itself an active standard user, so a count of 0 means the count could not
100
+ // see users, not that there are none: inconclusive, never a pass.
101
+ if (totalActiveUsers === 0) {
102
+ findings.push({
103
+ id: 'mfa-registration-no-users-visible',
104
+ category: this.category,
105
+ riskLevel: 'INFO',
106
+ inconclusive: true,
107
+ title: 'No active standard users were visible: MFA registration cannot be checked',
108
+ detail: 'The count of active, unfrozen standard users returned 0, although the audit user is one. The audit user may not be able to read User records.',
109
+ remediation: 'Grant the audit user "View Setup and Configuration" and "Manage Users" read access, then re-run, or review MFA registration manually in Setup → Identity → Identity Verification.',
110
+ affectedItems: [{ label: 'Identity Verification Setup', url: setupUrl }],
111
+ });
112
+ return { findings };
113
+ }
65
114
  if (unregisteredCount === 0) {
66
115
  findings.push({
67
116
  id: 'mfa-registration-ok',
@@ -69,7 +118,7 @@ export class MfaRegistrationCheck {
69
118
  riskLevel: 'LOW',
70
119
  passed: true,
71
120
  title: `All ${totalActiveUsers} active standard user(s) have registered at least one MFA method`,
72
- detail: `All ${totalActiveUsers} active, unfrozen standard users have at least one MFA method registered in TwoFactorInfo. Users who have not registered a method cannot complete MFA challenges and may be locked out of the org if MFA is enforced.`,
121
+ detail: `All ${totalActiveUsers} active, unfrozen standard users have at least one MFA method registered (authenticator app, Salesforce Authenticator, security key or built-in authenticator). Users who have not registered a method cannot complete MFA challenges and may be locked out of the org if MFA is enforced.`,
73
122
  remediation: 'Continue monitoring MFA registration as new users are onboarded. Ensure new user onboarding includes an MFA registration step before their first login.',
74
123
  });
75
124
  return { findings };
@@ -80,7 +129,7 @@ export class MfaRegistrationCheck {
80
129
  category: this.category,
81
130
  riskLevel,
82
131
  title: `${unregisteredCount} of ${totalActiveUsers} active user(s) have not registered any MFA method`,
83
- detail: `${unregisteredCount} active standard users have no registered MFA methods in TwoFactorInfo. These users cannot complete MFA challenges and may be locked out or have a degraded authentication experience when MFA is enforced. ${registeredCount} user(s) have registered at least one method. Unregistered users should complete MFA setup immediately.`,
132
+ detail: `${unregisteredCount} active standard users have no MFA method registered: no authenticator app, Salesforce Authenticator, security key or built-in authenticator. These users cannot complete MFA challenges and may be locked out or have a degraded authentication experience when MFA is enforced. ${registeredCount} user(s) have registered at least one method.${fallbackOnly > 0 ? ` ${fallbackOnly} of the unregistered user(s) have only a verified phone number, email address or temporary code, which are sign-in fallbacks, not MFA methods.` : ''} Unregistered users should complete MFA setup immediately.`,
84
133
  remediation: 'Identify unregistered users in Setup → Identity → Identity Verification → User Management. Send MFA registration prompts or require registration on next login. Consider using Salesforce automation or the MFA rollout tools to enforce registration deadlines.',
85
134
  affectedItems: [
86
135
  {