@cclabsnz/sf-audit 1.0.1 → 1.2.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 (196) hide show
  1. package/README.md +228 -31
  2. package/lib/api/ToolingClientImpl.js +5 -2
  3. package/lib/chains/AttackChain.d.ts +20 -0
  4. package/lib/chains/AttackChain.js +2 -0
  5. package/lib/chains/Capability.d.ts +7 -0
  6. package/lib/chains/Capability.js +11 -0
  7. package/lib/chains/CapabilityRegistry.d.ts +18 -0
  8. package/lib/chains/CapabilityRegistry.js +53 -0
  9. package/lib/chains/ChainEngine.d.ts +13 -0
  10. package/lib/chains/ChainEngine.js +137 -0
  11. package/lib/chains/namedChains.d.ts +14 -0
  12. package/lib/chains/namedChains.js +99 -0
  13. package/lib/checks/CheckEngine.js +33 -5
  14. package/lib/checks/impl/AnonymousApexAuditCheck.d.ts +10 -0
  15. package/lib/checks/impl/AnonymousApexAuditCheck.js +106 -0
  16. package/lib/checks/impl/ApexCrudFLSCheck.d.ts +11 -0
  17. package/lib/checks/impl/ApexCrudFLSCheck.js +98 -0
  18. package/lib/checks/impl/ApexLoggingCheck.d.ts +11 -0
  19. package/lib/checks/impl/ApexLoggingCheck.js +124 -0
  20. package/lib/checks/impl/ApexRestEndpointCheck.d.ts +11 -0
  21. package/lib/checks/impl/ApexRestEndpointCheck.js +94 -0
  22. package/lib/checks/impl/ApexSharingCheck.js +29 -0
  23. package/lib/checks/impl/ApiClientPermissionCheck.d.ts +10 -0
  24. package/lib/checks/impl/ApiClientPermissionCheck.js +59 -0
  25. package/lib/checks/impl/AuditTrailCheck.js +29 -0
  26. package/lib/checks/impl/CertificateExpiryCheck.d.ts +10 -0
  27. package/lib/checks/impl/CertificateExpiryCheck.js +123 -0
  28. package/lib/checks/impl/CodeSecurityCheck.d.ts +2 -1
  29. package/lib/checks/impl/CodeSecurityCheck.js +46 -6
  30. package/lib/checks/impl/ConnectedAppInactivityCheck.d.ts +11 -0
  31. package/lib/checks/impl/ConnectedAppInactivityCheck.js +86 -0
  32. package/lib/checks/impl/ConnectedAppScopeCheck.d.ts +10 -0
  33. package/lib/checks/impl/ConnectedAppScopeCheck.js +125 -0
  34. package/lib/checks/impl/ConnectedAppsCheck.d.ts +1 -0
  35. package/lib/checks/impl/ConnectedAppsCheck.js +37 -2
  36. package/lib/checks/impl/ContentLinksCheck.d.ts +10 -0
  37. package/lib/checks/impl/ContentLinksCheck.js +115 -0
  38. package/lib/checks/impl/CorsAllowlistCheck.d.ts +10 -0
  39. package/lib/checks/impl/CorsAllowlistCheck.js +80 -0
  40. package/lib/checks/impl/CspTrustedSitesCheck.d.ts +10 -0
  41. package/lib/checks/impl/CspTrustedSitesCheck.js +55 -0
  42. package/lib/checks/impl/CustomLabelsCredentialCheck.d.ts +10 -0
  43. package/lib/checks/impl/CustomLabelsCredentialCheck.js +97 -0
  44. package/lib/checks/impl/DataClassificationCheck.d.ts +10 -0
  45. package/lib/checks/impl/DataClassificationCheck.js +112 -0
  46. package/lib/checks/impl/DebugLogAccessCheck.d.ts +10 -0
  47. package/lib/checks/impl/DebugLogAccessCheck.js +81 -0
  48. package/lib/checks/impl/DeploymentIdentityCheck.d.ts +11 -0
  49. package/lib/checks/impl/DeploymentIdentityCheck.js +144 -0
  50. package/lib/checks/impl/EnhancedDomainsCheck.d.ts +10 -0
  51. package/lib/checks/impl/EnhancedDomainsCheck.js +84 -0
  52. package/lib/checks/impl/EscalationPermsCheck.d.ts +10 -0
  53. package/lib/checks/impl/EscalationPermsCheck.js +77 -0
  54. package/lib/checks/impl/EventMonitoringCheck.d.ts +11 -0
  55. package/lib/checks/impl/EventMonitoringCheck.js +84 -0
  56. package/lib/checks/impl/ExperienceCloudSiteCheck.d.ts +10 -0
  57. package/lib/checks/impl/ExperienceCloudSiteCheck.js +91 -0
  58. package/lib/checks/impl/FailedLoginCheck.d.ts +10 -0
  59. package/lib/checks/impl/FailedLoginCheck.js +122 -0
  60. package/lib/checks/impl/FieldHistoryTrackingCheck.d.ts +10 -0
  61. package/lib/checks/impl/FieldHistoryTrackingCheck.js +70 -0
  62. package/lib/checks/impl/FieldLevelSecurityCheck.js +28 -18
  63. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +11 -0
  64. package/lib/checks/impl/GuestExecutableApexCheck.js +93 -0
  65. package/lib/checks/impl/GuestUserAccessCheck.js +74 -66
  66. package/lib/checks/impl/HardcodedCredentialsCheck.js +2 -2
  67. package/lib/checks/impl/HighAssuranceSessionCheck.d.ts +10 -0
  68. package/lib/checks/impl/HighAssuranceSessionCheck.js +103 -0
  69. package/lib/checks/impl/InactiveUsersCheck.js +38 -19
  70. package/lib/checks/impl/InstalledPackagesCheck.d.ts +10 -0
  71. package/lib/checks/impl/InstalledPackagesCheck.js +94 -0
  72. package/lib/checks/impl/IntegrationUsersCheck.d.ts +10 -0
  73. package/lib/checks/impl/IntegrationUsersCheck.js +108 -0
  74. package/lib/checks/impl/InternalUserMfaCheck.d.ts +10 -0
  75. package/lib/checks/impl/InternalUserMfaCheck.js +81 -0
  76. package/lib/checks/impl/IpRestrictionsCheck.js +86 -23
  77. package/lib/checks/impl/LegacyApiVersionCheck.d.ts +10 -0
  78. package/lib/checks/impl/LegacyApiVersionCheck.js +91 -0
  79. package/lib/checks/impl/MfaEnforcementCheck.d.ts +10 -0
  80. package/lib/checks/impl/MfaEnforcementCheck.js +76 -0
  81. package/lib/checks/impl/MfaMethodStrengthCheck.d.ts +11 -0
  82. package/lib/checks/impl/MfaMethodStrengthCheck.js +116 -0
  83. package/lib/checks/impl/MfaRegistrationCheck.d.ts +11 -0
  84. package/lib/checks/impl/MfaRegistrationCheck.js +95 -0
  85. package/lib/checks/impl/MyDomainLoginPolicyCheck.d.ts +10 -0
  86. package/lib/checks/impl/MyDomainLoginPolicyCheck.js +105 -0
  87. package/lib/checks/impl/NamedCredentialsCheck.js +37 -2
  88. package/lib/checks/impl/PermissionsCheck.js +67 -14
  89. package/lib/checks/impl/PublicGroupSharingCheck.js +20 -9
  90. package/lib/checks/impl/ReleaseUpdatesCheck.d.ts +10 -0
  91. package/lib/checks/impl/ReleaseUpdatesCheck.js +106 -0
  92. package/lib/checks/impl/ReportFolderAccessCheck.d.ts +10 -0
  93. package/lib/checks/impl/ReportFolderAccessCheck.js +54 -0
  94. package/lib/checks/impl/ScheduledApexCheck.d.ts +1 -0
  95. package/lib/checks/impl/ScheduledApexCheck.js +3 -0
  96. package/lib/checks/impl/SharingModelCheck.d.ts +1 -1
  97. package/lib/checks/impl/SharingModelCheck.js +103 -32
  98. package/lib/checks/impl/SiemIntegrationCheck.d.ts +11 -0
  99. package/lib/checks/impl/SiemIntegrationCheck.js +102 -0
  100. package/lib/checks/impl/SsoEnforcementCheck.d.ts +10 -0
  101. package/lib/checks/impl/SsoEnforcementCheck.js +90 -0
  102. package/lib/checks/impl/StandardProfilesCheck.d.ts +10 -0
  103. package/lib/checks/impl/StandardProfilesCheck.js +68 -0
  104. package/lib/checks/impl/TransactionSecurityPolicyCheck.d.ts +10 -0
  105. package/lib/checks/impl/TransactionSecurityPolicyCheck.js +62 -0
  106. package/lib/checks/impl/TrustedIPRangesCheck.d.ts +10 -0
  107. package/lib/checks/impl/TrustedIPRangesCheck.js +106 -0
  108. package/lib/checks/impl/UsersAndAdminsCheck.js +50 -20
  109. package/lib/checks/impl/VisualforceXssCheck.d.ts +11 -0
  110. package/lib/checks/impl/VisualforceXssCheck.js +150 -0
  111. package/lib/checks/registry.js +97 -12
  112. package/lib/commands/audit/diff.d.ts +17 -0
  113. package/lib/commands/audit/diff.js +76 -0
  114. package/lib/commands/audit/history.d.ts +15 -0
  115. package/lib/commands/audit/history.js +59 -0
  116. package/lib/commands/audit/security.d.ts +5 -0
  117. package/lib/commands/audit/security.js +38 -9
  118. package/lib/compliance/catalogs/hiso10029.d.ts +3 -0
  119. package/lib/compliance/catalogs/hiso10029.js +35 -0
  120. package/lib/compliance/catalogs/index.d.ts +4 -0
  121. package/lib/compliance/catalogs/index.js +21 -0
  122. package/lib/compliance/catalogs/iso27001.d.ts +3 -0
  123. package/lib/compliance/catalogs/iso27001.js +39 -0
  124. package/lib/compliance/catalogs/nzism.d.ts +3 -0
  125. package/lib/compliance/catalogs/nzism.js +31 -0
  126. package/lib/compliance/catalogs/owasp.d.ts +3 -0
  127. package/lib/compliance/catalogs/owasp.js +37 -0
  128. package/lib/compliance/catalogs/privacyAct.d.ts +3 -0
  129. package/lib/compliance/catalogs/privacyAct.js +17 -0
  130. package/lib/compliance/catalogs/sbs.d.ts +3 -0
  131. package/lib/compliance/catalogs/sbs.js +61 -0
  132. package/lib/compliance/catalogs/soc2.d.ts +3 -0
  133. package/lib/compliance/catalogs/soc2.js +42 -0
  134. package/lib/compliance/mapping.d.ts +2 -0
  135. package/lib/compliance/mapping.js +111 -0
  136. package/lib/compliance/resolve.d.ts +12 -0
  137. package/lib/compliance/resolve.js +49 -0
  138. package/lib/compliance/types.d.ts +13 -0
  139. package/lib/compliance/types.js +2 -0
  140. package/lib/context/AuditCache.d.ts +20 -0
  141. package/lib/context/AuditContext.d.ts +0 -2
  142. package/lib/findings/AuditResult.d.ts +3 -0
  143. package/lib/findings/CheckMeta.d.ts +9 -0
  144. package/lib/findings/CheckMeta.js +67 -0
  145. package/lib/findings/ComplianceMapping.d.ts +3 -0
  146. package/lib/findings/ComplianceMapping.js +75 -0
  147. package/lib/findings/Finding.d.ts +20 -0
  148. package/lib/findings/loadScoringConfig.js +9 -2
  149. package/lib/findings/scoring.d.ts +2 -1
  150. package/lib/findings/scoring.js +20 -7
  151. package/lib/history/AuditDiff.d.ts +26 -0
  152. package/lib/history/AuditDiff.js +2 -0
  153. package/lib/history/DiffEngine.d.ts +4 -0
  154. package/lib/history/DiffEngine.js +61 -0
  155. package/lib/history/HistoryStore.d.ts +11 -0
  156. package/lib/history/HistoryStore.js +56 -0
  157. package/lib/history/metricMeta.d.ts +9 -0
  158. package/lib/history/metricMeta.js +28 -0
  159. package/lib/index.d.ts +7 -1
  160. package/lib/index.js +2 -1
  161. package/lib/lib/wire.d.ts +1 -2
  162. package/lib/lib/wire.js +1 -2
  163. package/lib/renderers/AuditRenderer.d.ts +2 -0
  164. package/lib/renderers/ClientReportRenderer.d.ts +29 -0
  165. package/lib/renderers/ClientReportRenderer.js +205 -0
  166. package/lib/renderers/DiffHtmlRenderer.d.ts +8 -0
  167. package/lib/renderers/DiffHtmlRenderer.js +164 -0
  168. package/lib/renderers/DiffJsonRenderer.d.ts +8 -0
  169. package/lib/renderers/DiffJsonRenderer.js +8 -0
  170. package/lib/renderers/DiffRenderer.d.ts +7 -0
  171. package/lib/renderers/DiffRenderer.js +2 -0
  172. package/lib/renderers/HistoryRenderer.d.ts +6 -0
  173. package/lib/renderers/HistoryRenderer.js +140 -0
  174. package/lib/renderers/HtmlRenderer.d.ts +1 -0
  175. package/lib/renderers/HtmlRenderer.js +354 -60
  176. package/lib/renderers/MarkdownRenderer.js +34 -1
  177. package/lib/renderers/html-utils.d.ts +2 -0
  178. package/lib/renderers/html-utils.js +8 -0
  179. package/lib/report/ComplianceMatrix.d.ts +19 -0
  180. package/lib/report/ComplianceMatrix.js +47 -0
  181. package/lib/report/ExecutivePriorities.d.ts +8 -0
  182. package/lib/report/ExecutivePriorities.js +22 -0
  183. package/lib/report/RemediationRoadmap.d.ts +9 -0
  184. package/lib/report/RemediationRoadmap.js +18 -0
  185. package/lib/report/branding.d.ts +18 -0
  186. package/lib/report/branding.js +19 -0
  187. package/lib/report/fonts.d.ts +2 -0
  188. package/lib/report/fonts.js +22 -0
  189. package/package.json +4 -3
  190. package/src/assets/fonts/dm-sans-italic-latin.woff2 +0 -0
  191. package/src/assets/fonts/dm-sans-normal-latin.woff2 +0 -0
  192. package/src/assets/fonts/dm-serif-display-italic-latin.woff2 +0 -0
  193. package/src/assets/fonts/dm-serif-display-normal-latin.woff2 +0 -0
  194. package/config/queries/soql.json +0 -24
  195. package/config/queries/tooling.json +0 -28
  196. package/config/scoring.json +0 -17
@@ -0,0 +1,99 @@
1
+ const has = (s, ...caps) => caps.every((c) => s.has(c));
2
+ const hasAny = (s, ...caps) => caps.some((c) => s.has(c));
3
+ const byIds = (active, ids) => active.filter((f) => ids.includes(f.id));
4
+ export const NAMED_CHAINS = [
5
+ {
6
+ id: 'unauth-bulk-exfil',
7
+ title: 'Unauthenticated bulk exfiltration',
8
+ severity: 'CRITICAL',
9
+ narrative: 'An unauthenticated guest foothold combines with guest-reachable code execution or public ' +
10
+ 'external sharing to read business data in bulk without any login.',
11
+ remediation: 'Remove guest object/sharing access, ensure no guest-invokable Apex runs without sharing, ' +
12
+ 'and set external OWD to Private. Grant portal access only via sharing sets.',
13
+ match(present, active) {
14
+ if (!has(present, 'unauth-foothold'))
15
+ return null;
16
+ if (!hasAny(present, 'code-exec', 'data-read-bulk', 'data-write'))
17
+ return null;
18
+ const steps = byIds(active, [
19
+ 'guest-user-read-access', 'guest-user-write-access', 'guest-user-sharing-exposure', 'guest-user-baseline',
20
+ 'guest-executable-apex-unprotected', 'guest-executable-apex-exposed',
21
+ 'portal-exposed-apex-without-sharing', 'sharing-model-external-read', 'sharing-model-external-write',
22
+ 'field-level-security-high', 'field-level-security-medium',
23
+ ]);
24
+ return steps.length >= 2 ? steps : null;
25
+ },
26
+ },
27
+ {
28
+ id: 'standard-to-takeover',
29
+ title: 'Standard user → org takeover',
30
+ severity: 'CRITICAL',
31
+ narrative: 'A low-trust authenticated user combines with a privilege-escalation permission ' +
32
+ '(assign permission sets, manage users, author apex, modify metadata) to reach full org control.',
33
+ remediation: 'Remove escalation permissions from non-admin profiles/permission sets and review who holds them.',
34
+ match(present, active) {
35
+ if (!hasAny(present, 'low-trust-authenticated', 'unauth-foothold'))
36
+ return null;
37
+ if (!hasAny(present, 'priv-esc', 'org-takeover'))
38
+ return null;
39
+ const steps = byIds(active, [
40
+ 'sharing-model-external-read', 'sharing-model-external-write', 'guest-user-baseline',
41
+ 'escalation-perms-found', 'users-author-apex', 'users-super-admin-combo',
42
+ ]);
43
+ return steps.length >= 2 ? steps : null;
44
+ },
45
+ },
46
+ {
47
+ id: 'cred-theft-pivot',
48
+ title: 'Credential theft → external pivot',
49
+ severity: 'CRITICAL',
50
+ narrative: 'Exposed secrets (hardcoded credentials, credentials in custom labels, debug logs, or broad CORS) ' +
51
+ 'combine with an external egress path (named credential or remote site) to exfiltrate data to attacker infrastructure.',
52
+ remediation: 'Rotate and remove exposed secrets, tighten CORS origins, and review external callout endpoints.',
53
+ match(present, active) {
54
+ if (!has(present, 'credential-theft', 'external-egress'))
55
+ return null;
56
+ const steps = byIds(active, [
57
+ 'hardcoded-credentials-found', 'custom-labels-credential-value-match', 'custom-labels-credential-name-match',
58
+ 'debug-log-active-traces', 'cors-wildcard-origin', 'cors-broad-origin',
59
+ 'named-credentials-inventory', 'named-credentials-http-endpoint', 'remote-sites-inventory',
60
+ ]);
61
+ return steps.length >= 2 ? steps : null;
62
+ },
63
+ },
64
+ {
65
+ id: 'soql-injection-read',
66
+ title: 'SOQL injection → mass read',
67
+ severity: 'HIGH',
68
+ narrative: 'Injectable dynamic SOQL combines with bulk data readability to let an attacker extract large datasets.',
69
+ remediation: 'Use bind variables in all dynamic SOQL and enforce CRUD/FLS; restrict bulk read access.',
70
+ match(present, active) {
71
+ if (!has(present, 'code-exec'))
72
+ return null;
73
+ const inj = byIds(active, ['soql-injection-risk']);
74
+ if (inj.length === 0)
75
+ return null;
76
+ const sink = byIds(active, [
77
+ 'sharing-model-external-read', 'sharing-model-external-write',
78
+ 'field-level-security-high', 'field-level-security-medium', 'users-view-all-data',
79
+ ]);
80
+ return sink.length > 0 ? [...inj, ...sink] : null;
81
+ },
82
+ },
83
+ {
84
+ id: 'mfa-bypass-admin',
85
+ title: 'MFA bypass → privileged compromise',
86
+ severity: 'HIGH',
87
+ narrative: 'Weak MFA enforcement or trusted-IP MFA bypass combines with the presence of highly-privileged ' +
88
+ 'accounts, so a credential-stuffing or phishing attacker can take over an admin without a second factor.',
89
+ remediation: 'Enforce MFA for all internal users, remove trusted-IP MFA bypass ranges, and minimise privileged accounts.',
90
+ match(_present, active) {
91
+ const weakness = byIds(active, [
92
+ 'trusted-ip-broad-ranges', 'internal-user-mfa-gaps', 'mfa-portal-users-without-enforcement',
93
+ ]);
94
+ const targets = byIds(active, ['users-modify-all-data', 'users-view-all-data', 'users-super-admin-combo']);
95
+ return weakness.length > 0 && targets.length > 0 ? [...weakness, ...targets] : null;
96
+ },
97
+ },
98
+ ];
99
+ //# sourceMappingURL=namedChains.js.map
@@ -1,14 +1,40 @@
1
1
  import { buildAuditResult } from '../findings/scoring.js';
2
+ import { getComplianceTags } from '../compliance/resolve.js';
3
+ import { ChainEngine } from '../chains/ChainEngine.js';
4
+ const PERMISSION_ERROR_CODES = new Set([
5
+ 'INSUFFICIENT_ACCESS_RIGHTS',
6
+ 'INVALID_CROSS_REFERENCE_KEY',
7
+ 'ENTITY_IS_INACCESSIBLE',
8
+ 'INVALID_FIELD',
9
+ 'INVALID_TYPE',
10
+ ]);
11
+ function isPermissionError(err) {
12
+ if (!(err instanceof Error))
13
+ return false;
14
+ const code = err.errorCode ?? '';
15
+ const msg = err.message ?? '';
16
+ return (PERMISSION_ERROR_CODES.has(code) ||
17
+ msg.includes('INSUFFICIENT_ACCESS') ||
18
+ msg.includes('insufficient access') ||
19
+ msg.includes('INVALID_FIELD') ||
20
+ msg.includes('entity type cannot be queried'));
21
+ }
2
22
  function buildErrorFinding(check, err) {
3
23
  const msg = err instanceof Error ? err.message : String(err);
24
+ const inconclusive = isPermissionError(err);
4
25
  return {
5
26
  id: `${check.id}-error`,
6
27
  checkId: check.id,
7
28
  category: check.category,
8
29
  riskLevel: 'INFO',
9
- title: `${check.name}: check failed`,
10
- detail: `This check encountered an error and could not complete: ${msg}`,
11
- remediation: 'Review the error message and verify the running user has the required permissions.',
30
+ title: `${check.name}: ${inconclusive ? 'insufficient permissions' : 'check failed'}`,
31
+ detail: inconclusive
32
+ ? `This check could not gather evidence because the running user lacks the required permissions: ${msg}`
33
+ : `This check encountered an error and could not complete: ${msg}`,
34
+ remediation: inconclusive
35
+ ? 'Grant the audit user the permissions listed in the tool documentation, then re-run the audit.'
36
+ : 'Review the error message and verify the running user has the required permissions.',
37
+ inconclusive: inconclusive || undefined,
12
38
  };
13
39
  }
14
40
  export class CheckEngine {
@@ -30,7 +56,8 @@ export class CheckEngine {
30
56
  onProgress?.(i + 1, total, check.name);
31
57
  try {
32
58
  const result = await check.run(this.ctx);
33
- findings.push(...result.findings.map((f) => ({ ...f, checkId: check.id })));
59
+ const tags = getComplianceTags(check.id);
60
+ findings.push(...result.findings.map((f) => ({ ...f, checkId: check.id, complianceTags: tags })));
34
61
  if (result.metrics) {
35
62
  metrics = { ...metrics, ...result.metrics };
36
63
  }
@@ -39,7 +66,8 @@ export class CheckEngine {
39
66
  findings.push(buildErrorFinding(check, err));
40
67
  }
41
68
  }
42
- return buildAuditResult(this.ctx, findings, metrics, this.scoringConfig);
69
+ const attackChains = new ChainEngine().correlate(findings);
70
+ return buildAuditResult(this.ctx, findings, metrics, this.scoringConfig, attackChains);
43
71
  }
44
72
  validateCacheOrdering() {
45
73
  const populated = new Set();
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class AnonymousApexAuditCheck implements SecurityCheck {
4
+ readonly id = "anonymous-apex-audit";
5
+ readonly name = "Anonymous Apex Execution Audit";
6
+ readonly category = "Code Security";
7
+ readonly description = "Detects anonymous Apex execution in the last 90 days via SetupAuditTrail";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=AnonymousApexAuditCheck.d.ts.map
@@ -0,0 +1,106 @@
1
+ function isAdminProfile(profileName) {
2
+ const lower = profileName.toLowerCase();
3
+ return lower.includes('admin') || lower.includes('system administrator');
4
+ }
5
+ export class AnonymousApexAuditCheck {
6
+ id = 'anonymous-apex-audit';
7
+ name = 'Anonymous Apex Execution Audit';
8
+ category = 'Code Security';
9
+ description = 'Detects anonymous Apex execution in the last 90 days via SetupAuditTrail';
10
+ async run(ctx) {
11
+ const findings = [];
12
+ const baseUrl = ctx.orgInfo.instanceUrl;
13
+ const auditTrailUrl = `${baseUrl}/lightning/setup/AuditTrail/home`;
14
+ let records = [];
15
+ try {
16
+ records = await ctx.soql.queryAll(`SELECT CreatedDate, CreatedBy.Id, CreatedBy.Username, CreatedBy.Profile.Name,
17
+ Section, Action, Display
18
+ FROM SetupAuditTrail
19
+ WHERE CreatedDate > LAST_N_DAYS:90
20
+ AND (Section IN ('Developer Console', 'Developer Tools', 'IDE', 'Development', 'Workbench')
21
+ OR Action LIKE '%anon%'
22
+ OR Action LIKE '%runAs%'
23
+ OR Action LIKE '%executeCode%')
24
+ ORDER BY CreatedDate DESC
25
+ LIMIT 200`);
26
+ }
27
+ catch {
28
+ findings.push({
29
+ id: 'anonymous-apex-inaccessible',
30
+ category: this.category,
31
+ riskLevel: 'INFO',
32
+ inconclusive: true,
33
+ title: 'SetupAuditTrail could not be queried — anonymous Apex execution cannot be verified',
34
+ detail: 'The SetupAuditTrail object was not accessible. This may indicate insufficient permissions to view the org audit trail.',
35
+ remediation: 'Grant "View Setup and Configuration" permission to the audit user. Review anonymous Apex execution manually in Setup → Audit Trail.',
36
+ affectedItems: [{ label: 'Setup Audit Trail', url: auditTrailUrl }],
37
+ });
38
+ return { findings };
39
+ }
40
+ if (records.length === 0) {
41
+ findings.push({
42
+ id: 'anonymous-apex-none',
43
+ category: this.category,
44
+ riskLevel: 'LOW',
45
+ passed: true,
46
+ title: 'No anonymous Apex execution detected in the last 90 days',
47
+ detail: 'No SetupAuditTrail entries matching anonymous Apex execution patterns were found in the last 90 days. This indicates the Developer Console and anonymous Apex execution have not been used recently in production.',
48
+ remediation: 'Continue monitoring. If anonymous Apex execution is ever required, ensure it is pre-approved, logged, and reviewed.',
49
+ });
50
+ return { findings };
51
+ }
52
+ const userMap = new Map();
53
+ for (const r of records) {
54
+ const userId = r.CreatedBy.Id;
55
+ const existing = userMap.get(userId);
56
+ const profileName = r.CreatedBy.Profile?.Name ?? 'Unknown';
57
+ if (existing) {
58
+ existing.count += 1;
59
+ if (r.CreatedDate > existing.latest)
60
+ existing.latest = r.CreatedDate;
61
+ }
62
+ else {
63
+ userMap.set(userId, {
64
+ username: r.CreatedBy.Username,
65
+ profile: profileName,
66
+ count: 1,
67
+ latest: r.CreatedDate,
68
+ });
69
+ }
70
+ }
71
+ const nonAdminUsers = [...userMap.values()].filter((u) => !isAdminProfile(u.profile));
72
+ const adminOnlyUsers = [...userMap.values()].filter((u) => isAdminProfile(u.profile));
73
+ if (nonAdminUsers.length > 0) {
74
+ findings.push({
75
+ id: 'anonymous-apex-executed',
76
+ category: this.category,
77
+ riskLevel: 'HIGH',
78
+ title: `${nonAdminUsers.length} non-admin user(s) executed anonymous Apex in the last 90 days`,
79
+ detail: 'Anonymous Apex execution in production is a privileged, hard-to-audit operation. Anon Apex runs as the executing user but leaves no code artifact — it cannot be reviewed, versioned, or rolled back. Non-admin users executing anonymous Apex indicates a significant control gap: these users have Developer Console access in production and can manipulate data or bypass sharing rules without leaving a traceable code change.',
80
+ remediation: 'Remove Developer Console access from non-admin users. Revoke the "Author Apex" permission from all profiles and permission sets that do not require it. All code changes in production must go through a formal deployment process (change sets, Salesforce DX). Review each execution instance to determine what code was run and what data was affected.',
81
+ affectedItems: nonAdminUsers.map((u) => ({
82
+ label: u.username,
83
+ url: auditTrailUrl,
84
+ note: `${u.count} execution(s) — latest: ${new Date(u.latest).toISOString().split('T')[0]} — profile: ${u.profile}`,
85
+ })),
86
+ });
87
+ }
88
+ if (adminOnlyUsers.length > 0) {
89
+ findings.push({
90
+ id: 'anonymous-apex-admin-only',
91
+ category: this.category,
92
+ riskLevel: 'MEDIUM',
93
+ title: `Anonymous Apex executed by ${adminOnlyUsers.length} admin-profile user(s) in the last 90 days — monitoring recommended`,
94
+ detail: 'Anonymous Apex execution by administrator-profile users still represents a risk in production: it bypasses change management, leaves no deployable artifact, and cannot be peer-reviewed. Even legitimate use by admins should be tracked, approved, and documented as part of a change management process.',
95
+ remediation: 'Establish a policy requiring pre-approval for any anonymous Apex execution in production. Log approvals in your change management system. Prefer metadata deployments over anonymous Apex for all production data or configuration changes. Consider restricting Developer Console to a dedicated integration user only.',
96
+ affectedItems: adminOnlyUsers.map((u) => ({
97
+ label: u.username,
98
+ url: auditTrailUrl,
99
+ note: `${u.count} execution(s) — latest: ${new Date(u.latest).toISOString().split('T')[0]} — profile: ${u.profile}`,
100
+ })),
101
+ });
102
+ }
103
+ return { findings };
104
+ }
105
+ }
106
+ //# sourceMappingURL=AnonymousApexAuditCheck.js.map
@@ -0,0 +1,11 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class ApexCrudFLSCheck implements SecurityCheck {
4
+ readonly id = "apex-crud-fls";
5
+ readonly name = "Apex CRUD/FLS Enforcement";
6
+ readonly category = "Code Security";
7
+ readonly description = "Flags Apex classes that perform DML or SOQL without checking CRUD/FLS permissions \u2014 OWASP Top 10 for Salesforce";
8
+ readonly dependsOnCache: readonly ["apexBodies"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ }
11
+ //# sourceMappingURL=ApexCrudFLSCheck.d.ts.map
@@ -0,0 +1,98 @@
1
+ // Patterns that indicate DML or inline SOQL is being performed
2
+ const HAS_DML = /\b(?:insert|update|delete|upsert|merge)\s+\w+|Database\.(?:insert|update|delete|upsert|merge)\s*\(/i;
3
+ const HAS_SOQL = /\[\s*SELECT\b|Database\.(?:query|queryWithBinds|countQuery)\s*\(/i;
4
+ // Patterns that indicate FLS/CRUD is being checked or enforced
5
+ const HAS_FLS = /(?:\.isAccessible\(\)|\.isCreateable\(\)|\.isUpdateable\(\)|\.isDeletable\(\)|Security\.stripInaccessible|SObjectAccessDecision|Schema\.describeSObjects|Schema\.sObjectType\.\w+\.fields)/i;
6
+ // Classes that are exempt from CRUD/FLS enforcement by design:
7
+ // batch, scheduled, and trigger handlers run in a system context
8
+ const IS_BATCH_OR_SCHEDULED = /implements\s+(?:Database\.Batchable|Schedulable|Database\.StatefulBatch|Database\.AllowsCallouts)/i;
9
+ const IS_TEST = /@IsTest\b/i;
10
+ const WITHOUT_SHARING = /\bwithout\s+sharing\b/i;
11
+ export class ApexCrudFLSCheck {
12
+ id = 'apex-crud-fls';
13
+ name = 'Apex CRUD/FLS Enforcement';
14
+ category = 'Code Security';
15
+ description = 'Flags Apex classes that perform DML or SOQL without checking CRUD/FLS permissions — OWASP Top 10 for Salesforce';
16
+ dependsOnCache = ['apexBodies'];
17
+ async run(ctx) {
18
+ const findings = [];
19
+ const apexClassesUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ApexClasses/home`;
20
+ const apexBodies = ctx.cache.apexBodies ?? [];
21
+ if (apexBodies.length === 0) {
22
+ findings.push({
23
+ id: 'apex-crud-fls-no-bodies',
24
+ category: this.category,
25
+ riskLevel: 'INFO',
26
+ inconclusive: true,
27
+ title: 'Apex class bodies not available — CRUD/FLS check skipped',
28
+ detail: 'Apex class bodies were not cached. Ensure HardcodedCredentialsCheck runs before this check.',
29
+ remediation: 'Verify registry ordering so HardcodedCredentialsCheck (which populates apexBodies) precedes ApexCrudFLSCheck.',
30
+ });
31
+ return { findings };
32
+ }
33
+ const withoutSharingNoFls = [];
34
+ const withDmlNoFls = [];
35
+ // apexBodies is pre-filtered by HardcodedCredentialsCheck to exclude test classes;
36
+ // IS_TEST guard here is redundant but kept for cache-miss safety
37
+ for (const { name, body } of apexBodies) {
38
+ if (!body || IS_BATCH_OR_SCHEDULED.test(body))
39
+ continue;
40
+ const hasDml = HAS_DML.test(body);
41
+ const hasSoql = HAS_SOQL.test(body);
42
+ if (!hasDml && !hasSoql)
43
+ continue;
44
+ const hasFls = HAS_FLS.test(body);
45
+ if (hasFls)
46
+ continue;
47
+ if (WITHOUT_SHARING.test(body)) {
48
+ withoutSharingNoFls.push(name);
49
+ }
50
+ else {
51
+ withDmlNoFls.push(name);
52
+ }
53
+ }
54
+ if (withoutSharingNoFls.length > 0) {
55
+ findings.push({
56
+ id: 'apex-crud-fls-without-sharing',
57
+ category: this.category,
58
+ riskLevel: 'HIGH',
59
+ title: `${withoutSharingNoFls.length} Apex class(es) run "without sharing" and perform DML/SOQL without CRUD/FLS checks`,
60
+ detail: `Apex classes declared "without sharing" bypass record-level visibility AND have no field-level or object-level permission checks, meaning any user who triggers the code can read or write any record and field regardless of their assigned permissions. This is the most exploited Salesforce access control vulnerability. OWASP Salesforce Top 10 ranks CRUD/FLS bypass as the #1 risk.`,
61
+ remediation: 'Refactor to use "with sharing" where possible. Add `Security.stripInaccessible()` before DML and `Schema.SObjectType.[Object].fields.[Field].isAccessible()` before displaying fields. Where "without sharing" is required for a technical reason, document the justification and tighten the scope.',
62
+ affectedItems: withoutSharingNoFls.slice(0, 30).map((n) => ({
63
+ label: n,
64
+ url: apexClassesUrl,
65
+ note: '"without sharing" + DML/SOQL + no FLS check — highest risk',
66
+ })),
67
+ });
68
+ }
69
+ if (withDmlNoFls.length > 0) {
70
+ findings.push({
71
+ id: 'apex-crud-fls-missing',
72
+ category: this.category,
73
+ riskLevel: 'MEDIUM',
74
+ title: `${withDmlNoFls.length} Apex class(es) perform DML or SOQL without CRUD/FLS permission checks`,
75
+ detail: `These classes perform database operations without checking whether the running user has create, read, update, or delete permission on the relevant objects or fields. While sharing rules still apply, object and field-level access is not enforced in code. Users can potentially access or modify data beyond their intended permissions via these code paths.`,
76
+ remediation: `Add CRUD checks before DML: \`Schema.SObjectType.[Object].isCreateable()\`. Use \`Security.stripInaccessible(AccessType.READABLE, records)\` before exposing query results. Consider adopting a shared FLS utility class to centralise enforcement.`,
77
+ affectedItems: withDmlNoFls.slice(0, 30).map((n) => ({
78
+ label: n,
79
+ url: apexClassesUrl,
80
+ note: 'DML/SOQL without FLS check — add Security.stripInaccessible() or isAccessible() guards',
81
+ })),
82
+ });
83
+ }
84
+ if (withoutSharingNoFls.length === 0 && withDmlNoFls.length === 0) {
85
+ findings.push({
86
+ id: 'apex-crud-fls-ok',
87
+ category: this.category,
88
+ riskLevel: 'LOW',
89
+ passed: true,
90
+ title: 'All scanned Apex classes with DML/SOQL include CRUD/FLS permission checks',
91
+ detail: 'No Apex classes were found performing DML or SOQL without corresponding object-level or field-level security checks. This scan covers non-test, non-batch classes in the org namespace.',
92
+ remediation: 'Continue monitoring as new Apex classes are developed.',
93
+ });
94
+ }
95
+ return { findings };
96
+ }
97
+ }
98
+ //# sourceMappingURL=ApexCrudFLSCheck.js.map
@@ -0,0 +1,11 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class ApexLoggingCheck implements SecurityCheck {
4
+ readonly id = "apex-logging";
5
+ readonly name = "Apex Logging Framework";
6
+ readonly category = "Code Security";
7
+ readonly description = "SBS-CODE-003/004: checks for persistent logging framework usage and sensitive data in Apex logs";
8
+ readonly dependsOnCache: readonly ["apexBodies", "scheduledApexClassNames"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ }
11
+ //# sourceMappingURL=ApexLoggingCheck.d.ts.map
@@ -0,0 +1,124 @@
1
+ // SBS-CODE-003: indicators of a persistent logging framework (as opposed to System.debug)
2
+ const PERSISTENT_LOGGER_PATTERNS = [
3
+ /\bfflib_Logger\b/i,
4
+ /\bLogger\s*\.\s*(?:log|info|warn|error|debug|fine)\s*\(/i,
5
+ /\bLoggingService\s*\.\s*(?:log|info|warn|error)\s*\(/i,
6
+ /\bLogService\s*\.\s*(?:log|info|warn|error)\s*\(/i,
7
+ /\bApplicationLogger\b/i,
8
+ /\bPlatformLogger\b/i,
9
+ /EventBus\.publish\s*\(/i, // logging via Platform Events
10
+ /insert\s+new\s+Log__c\b/i, // custom log object insert
11
+ /insert\s+logRecords\b/i,
12
+ /\bApplicationLog\s*\.\s*(?:log|add)\b/i,
13
+ ];
14
+ // SBS-CODE-004: patterns suggesting sensitive data is passed to System.debug
15
+ const SENSITIVE_LOG_PATTERNS = [
16
+ /System\.debug\s*\([^)]*(?:password|secret|token|apiKey|api_key|credential|ssn|dob|dateOfBirth|creditCard|cardNumber)/i,
17
+ /System\.debug\s*\([^)]*(?:UserInfo\.getSessionId|Auth\.AuthToken|getSessionId\(\))/i,
18
+ ];
19
+ const SYSTEM_DEBUG_RE = /\bSystem\.debug\s*\(/;
20
+ const IS_TEST_CLASS_RE = /@IsTest\b/i;
21
+ export class ApexLoggingCheck {
22
+ id = 'apex-logging';
23
+ name = 'Apex Logging Framework';
24
+ category = 'Code Security';
25
+ description = 'SBS-CODE-003/004: checks for persistent logging framework usage and sensitive data in Apex logs';
26
+ // Apex bodies are written by HardcodedCredentialsCheck;
27
+ // scheduled class names are written by ScheduledApexCheck.
28
+ dependsOnCache = ['apexBodies', 'scheduledApexClassNames'];
29
+ async run(ctx) {
30
+ const findings = [];
31
+ const apexClassesUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ApexClasses/home`;
32
+ const apexBodies = ctx.cache.apexBodies ?? [];
33
+ const scheduledClassNames = new Set(ctx.cache.scheduledApexClassNames ?? []);
34
+ if (apexBodies.length === 0) {
35
+ findings.push({
36
+ id: 'apex-logging-no-bodies',
37
+ category: this.category,
38
+ riskLevel: 'INFO',
39
+ inconclusive: true,
40
+ title: 'Apex class bodies not available — SBS-CODE-003/004 check skipped',
41
+ detail: 'SBS-CODE-003/004 require scanning Apex class bodies for logging patterns. Apex bodies were not available in the audit cache — ensure HardcodedCredentialsCheck runs before this check.',
42
+ remediation: 'Verify HardcodedCredentialsCheck is registered before ApexLoggingCheck in the check registry.',
43
+ });
44
+ return { findings };
45
+ }
46
+ const productionClasses = apexBodies.filter((c) => c.body && !IS_TEST_CLASS_RE.test(c.body));
47
+ const debugOnlyClasses = [];
48
+ const persistentLoggerClasses = [];
49
+ for (const { name, body } of productionClasses) {
50
+ const hasPersistentLogger = PERSISTENT_LOGGER_PATTERNS.some((p) => p.test(body));
51
+ const hasSystemDebug = SYSTEM_DEBUG_RE.test(body);
52
+ if (hasPersistentLogger) {
53
+ persistentLoggerClasses.push(name);
54
+ }
55
+ else if (hasSystemDebug) {
56
+ debugOnlyClasses.push(name);
57
+ }
58
+ }
59
+ // SBS-CODE-004: flag classes that appear to log sensitive values
60
+ const sensitiveLogClasses = [];
61
+ for (const { name, body } of productionClasses) {
62
+ if (SENSITIVE_LOG_PATTERNS.some((p) => p.test(body))) {
63
+ sensitiveLogClasses.push(name);
64
+ }
65
+ }
66
+ const scheduledDebugClasses = debugOnlyClasses.filter((n) => scheduledClassNames.has(n));
67
+ if (persistentLoggerClasses.length > 0) {
68
+ findings.push({
69
+ id: 'apex-logging-framework-in-use',
70
+ category: this.category,
71
+ riskLevel: 'LOW',
72
+ passed: true,
73
+ title: `${persistentLoggerClasses.length} Apex class(es) use a persistent logging framework — SBS-CODE-003`,
74
+ detail: `SBS-CODE-003 requires Apex to use a persistent logging framework rather than transient System.debug calls. ${persistentLoggerClasses.length} class(es) reference a persistent logger. Examples: ${persistentLoggerClasses.slice(0, 5).join(', ')}${persistentLoggerClasses.length > 5 ? ` (+${persistentLoggerClasses.length - 5} more)` : ''}.`,
75
+ remediation: 'Extend persistent logging coverage to all production classes that handle significant business logic or integration operations.',
76
+ });
77
+ }
78
+ if (debugOnlyClasses.length > 0) {
79
+ findings.push({
80
+ id: 'apex-logging-debug-only',
81
+ category: this.category,
82
+ riskLevel: scheduledDebugClasses.length > 0 ? 'MEDIUM' : 'LOW',
83
+ title: `${debugOnlyClasses.length} Apex class(es) use only System.debug — SBS-CODE-003`,
84
+ detail: `SBS-CODE-003 requires a persistent logging framework so that audit and error events are durable and searchable after the fact. ${debugOnlyClasses.length} production class(es) rely solely on System.debug, whose output is transient and unavailable once the debug log expires. ${scheduledDebugClasses.length > 0 ? `${scheduledDebugClasses.length} of these are scheduled or batch jobs — persistent logging is especially important for operational visibility in background processes.` : ''}`,
85
+ remediation: 'Adopt a persistent logging framework (a custom Log__c object, Platform Events, or an open-source framework) and migrate System.debug calls to it for all classes handling critical business logic.',
86
+ affectedItems: debugOnlyClasses.slice(0, 30).map((name) => ({
87
+ label: name,
88
+ url: apexClassesUrl,
89
+ note: scheduledClassNames.has(name)
90
+ ? 'scheduled/batch job — high priority to add persistent logging'
91
+ : 'System.debug only — no persistent log trail',
92
+ })),
93
+ });
94
+ }
95
+ if (sensitiveLogClasses.length > 0) {
96
+ findings.push({
97
+ id: 'apex-logging-sensitive-data',
98
+ category: this.category,
99
+ riskLevel: 'HIGH',
100
+ title: `${sensitiveLogClasses.length} Apex class(es) may log sensitive data — SBS-CODE-004`,
101
+ detail: 'SBS-CODE-004 prohibits logging sensitive data (passwords, tokens, session IDs, PII) in Apex. The flagged classes appear to pass sensitive variable names or credential values directly to System.debug(), which writes them to debug logs accessible to any administrator who can view debug logs.',
102
+ remediation: 'Remove all logging of passwords, tokens, API keys, and PII from Apex code. Review each flagged class and mask, redact, or entirely exclude sensitive values before passing them to any logging call.',
103
+ affectedItems: sensitiveLogClasses.map((name) => ({
104
+ label: name,
105
+ url: apexClassesUrl,
106
+ note: 'Review System.debug() calls — sensitive variable names detected near logging statements',
107
+ })),
108
+ });
109
+ }
110
+ if (debugOnlyClasses.length === 0 && sensitiveLogClasses.length === 0 && persistentLoggerClasses.length === 0) {
111
+ findings.push({
112
+ id: 'apex-logging-no-debug',
113
+ category: this.category,
114
+ riskLevel: 'LOW',
115
+ passed: true,
116
+ title: 'No System.debug-only logging or sensitive-data logging patterns found — SBS-CODE-003/004',
117
+ detail: 'SBS-CODE-003 requires a persistent logging framework and SBS-CODE-004 prohibits sensitive data in logs. No violations were detected in the scanned Apex classes.',
118
+ remediation: 'Continue monitoring as new Apex classes are added to the org.',
119
+ });
120
+ }
121
+ return { findings };
122
+ }
123
+ }
124
+ //# sourceMappingURL=ApexLoggingCheck.js.map
@@ -0,0 +1,11 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class ApexRestEndpointCheck implements SecurityCheck {
4
+ readonly id = "apex-rest-endpoint";
5
+ readonly name = "Apex REST Endpoint Security";
6
+ readonly category = "Code Security";
7
+ readonly description = "Flags @RestResource Apex classes that run without sharing, exposing records to REST callers without record-level access control";
8
+ readonly dependsOnCache: readonly ["apexBodies"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ }
11
+ //# sourceMappingURL=ApexRestEndpointCheck.d.ts.map
@@ -0,0 +1,94 @@
1
+ const REST_RESOURCE_RE = /@RestResource\s*\(\s*urlMapping\s*=/i;
2
+ const WITHOUT_SHARING_RE = /\bwithout\s+sharing\b/i;
3
+ const NO_SHARING_DECLARED_RE = /\b(with|without|inherited)\s+sharing\b/i;
4
+ const IS_TEST_RE = /@IsTest\b/i;
5
+ // Indicators that the endpoint performs some form of caller verification
6
+ const AUTH_CHECK_RE = /(?:RestContext\.request\.headers\.get|UserInfo\.getUserId\(\)|UserInfo\.getOrganizationId\(\)|Auth\.AuthConfiguration|isPortalEnabled\(\)|getSessionId\(\))/i;
7
+ const GUEST_VISIBLE_RE = /(@HttpGet|@HttpPost|@HttpPut|@HttpDelete|@HttpPatch)/i;
8
+ export class ApexRestEndpointCheck {
9
+ id = 'apex-rest-endpoint';
10
+ name = 'Apex REST Endpoint Security';
11
+ category = 'Code Security';
12
+ description = 'Flags @RestResource Apex classes that run without sharing, exposing records to REST callers without record-level access control';
13
+ dependsOnCache = ['apexBodies'];
14
+ async run(ctx) {
15
+ const findings = [];
16
+ const apexClassesUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ApexClasses/home`;
17
+ const apexBodies = ctx.cache.apexBodies ?? [];
18
+ if (apexBodies.length === 0) {
19
+ findings.push({
20
+ id: 'apex-rest-no-bodies',
21
+ category: this.category,
22
+ riskLevel: 'INFO',
23
+ inconclusive: true,
24
+ title: 'Apex class bodies not available — REST endpoint check skipped',
25
+ detail: 'Apex bodies were not cached. Ensure HardcodedCredentialsCheck runs before this check.',
26
+ remediation: 'Verify registry ordering.',
27
+ });
28
+ return { findings };
29
+ }
30
+ const restClasses = apexBodies.filter(({ body }) => body && !IS_TEST_RE.test(body) && REST_RESOURCE_RE.test(body));
31
+ if (restClasses.length === 0) {
32
+ findings.push({
33
+ id: 'apex-rest-none',
34
+ category: this.category,
35
+ riskLevel: 'LOW',
36
+ passed: true,
37
+ title: 'No custom @RestResource Apex endpoints found',
38
+ detail: 'No Apex classes with the @RestResource annotation were found in the org namespace.',
39
+ remediation: 'Continue monitoring as new Apex code is developed.',
40
+ });
41
+ return { findings };
42
+ }
43
+ // Always emit an inventory of all REST endpoints
44
+ findings.push({
45
+ id: 'apex-rest-inventory',
46
+ category: this.category,
47
+ riskLevel: 'INFO',
48
+ title: `${restClasses.length} custom Apex REST endpoint(s) found`,
49
+ detail: 'Apex classes with @RestResource expose custom REST APIs. These should be reviewed to ensure they enforce authentication, sharing, and field-level security appropriate to the data they expose.',
50
+ remediation: 'Review each REST endpoint: confirm it uses "with sharing", validates the caller, and applies field-level security before returning data.',
51
+ affectedItems: restClasses.map(({ name }) => ({
52
+ label: name,
53
+ url: apexClassesUrl,
54
+ note: 'Custom REST endpoint — review access controls',
55
+ })),
56
+ });
57
+ // Flag endpoints declared without sharing — REST callers bypass record-level access
58
+ const withoutSharing = restClasses.filter(({ body }) => WITHOUT_SHARING_RE.test(body));
59
+ if (withoutSharing.length > 0) {
60
+ findings.push({
61
+ id: 'apex-rest-without-sharing',
62
+ category: this.category,
63
+ riskLevel: 'HIGH',
64
+ title: `${withoutSharing.length} REST endpoint class(es) declared "without sharing"`,
65
+ detail: `Apex REST endpoints declared "without sharing" execute with elevated system privileges — any authenticated (or, if the endpoint is exposed via a Community, unauthenticated) caller can retrieve or modify records regardless of the running user's sharing rules. This is a common vector for horizontal privilege escalation in Salesforce integrations.`,
66
+ remediation: 'Change declarations to "with sharing" so that record-level access is enforced for REST callers. Where system-level access is genuinely required (e.g. an integration service account), document the justification and ensure the endpoint is not accessible to end-user profiles.',
67
+ affectedItems: withoutSharing.map(({ name }) => ({
68
+ label: name,
69
+ url: apexClassesUrl,
70
+ note: '"without sharing" REST endpoint — callers bypass record sharing rules',
71
+ })),
72
+ });
73
+ }
74
+ // Flag endpoints with no sharing declaration at all (inherits from caller — unpredictable)
75
+ const noSharingDeclaration = restClasses.filter(({ body }) => !WITHOUT_SHARING_RE.test(body) && !NO_SHARING_DECLARED_RE.test(body));
76
+ if (noSharingDeclaration.length > 0) {
77
+ findings.push({
78
+ id: 'apex-rest-no-sharing-declaration',
79
+ category: this.category,
80
+ riskLevel: 'MEDIUM',
81
+ title: `${noSharingDeclaration.length} REST endpoint class(es) have no sharing declaration`,
82
+ detail: `Apex classes with no sharing declaration inherit sharing mode from their caller, which is non-deterministic for REST API calls. In REST API contexts the caller is typically the integration user, whose sharing context may be broader than intended. Explicit "with sharing" is required for predictable, secure behaviour.`,
83
+ remediation: 'Add "with sharing" to all @RestResource classes to make sharing enforcement explicit and predictable.',
84
+ affectedItems: noSharingDeclaration.map(({ name }) => ({
85
+ label: name,
86
+ url: apexClassesUrl,
87
+ note: 'No sharing declaration — add "with sharing" explicitly',
88
+ })),
89
+ });
90
+ }
91
+ return { findings };
92
+ }
93
+ }
94
+ //# sourceMappingURL=ApexRestEndpointCheck.js.map