@cclabsnz/sf-audit 1.15.1 → 1.16.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/CHANGELOG.md CHANGED
@@ -11,6 +11,31 @@ published note and carries the signed provenance attestation and CycloneDX SBOM
11
11
 
12
12
  Merged to `main`, not yet released.
13
13
 
14
+ ## [v1.16.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.16.0) — 2026-10-09
15
+
16
+ The AI & Agents checks now run on real orgs: since 1.6.0 they had been silent everywhere, because the agent inventory asked the Tooling API for objects only the data API serves. This release fixes that, and adds two checks and a named chain for the SalesBleed and PipeLeak pattern, all verified against a live Agentforce agent.
17
+
18
+ ### Added
19
+
20
+ - `agent-query-reach` (AI & Agents): flags agents carrying the standard General CRM topic or a
21
+ Query Records action, the open-ended query SalesBleed used to read Account data from a poisoned lead.
22
+ - `agent-outbound-actions` (AI & Agents): flags Slack, email, external-service and MCP actions that
23
+ send data out of the org without user confirmation (HIGH), and standard Slack/email actions whose
24
+ confirmation setting is not readable (MEDIUM).
25
+ - `salesbleed-pattern` named attack chain (HIGH): open-ended query reach plus an unconfirmed outbound action.
26
+
27
+ ### Fixed
28
+
29
+ - **AI & Agents checks never ran on a real org.** `agent-inventory` read `BotDefinition` and
30
+ `BotVersion` through the Tooling API, which answers `INVALID_TYPE` for both even in orgs with
31
+ active agents, so every org was classed as "Agentforce not enabled" and all AI & Agents checks
32
+ stayed silent since 1.6.0. Both are now read through SOQL. Verified against a live agent;
33
+ `test/fixtures/agentforce/live-agent-v67.json` replays it so the shape cannot regress.
34
+ - Agent checks now follow the platform's real shapes: one planner per agent version (only the
35
+ active version is reported), topic and action links that hold record Ids rather than names, and
36
+ Flow actions judged by what the active flow version does (Send Email, email alerts, external
37
+ services).
38
+
14
39
  ## [v1.15.1](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.15.1) — 2026-10-06
15
40
 
16
41
  The executive and incident reports now say which tool produced them. No change to any check, flag or finding.
package/README.md CHANGED
@@ -15,8 +15,8 @@
15
15
 
16
16
  A Salesforce CLI (`sf`) plugin that runs a complete, **read-only** security audit against any Salesforce org, risk-scores it with an A–F grade, and turns the result into a report your security team (or your client's) can act on.
17
17
 
18
- - **93 read-only checks** across identity, access, data, code, integrations, monitoring, and Agentforce / GenAI
19
- - **Attack-chain correlation:** links individual findings into named, multi-step attack scenarios — sixteen modelled chains, plus an emergent pass for combinations nobody has named yet (see [Attack chains](#attack-chains))
18
+ - **95 read-only checks** across identity, access, data, code, integrations, monitoring, and Agentforce / GenAI
19
+ - **Attack-chain correlation:** links individual findings into named, multi-step attack scenarios — seventeen modelled chains, plus an emergent pass for combinations nobody has named yet (see [Attack chains](#attack-chains))
20
20
  - **Compliance mapping:** every finding mapped to **source-verified** controls across 10 frameworks (OWASP, OWASP LLM Top 10, SOC 2, ISO/IEC 27001:2022, Security Benchmark for Salesforce, NZ Privacy Act, HISO 10029, NZISM, HIPAA Security Rule, GDPR)
21
21
  - **Outputs:** a technical `html` / `md` / `json` report, or a branded, client-ready **executive report** (print-to-PDF) with priorities, remediation roadmap, and a compliance coverage matrix
22
22
  - **History & diff:** archives each run and shows security-posture drift over time
@@ -45,7 +45,7 @@ guarantees here are checkable rather than asserted — see [Trust & verification
45
45
  sf audit security --target-org <orgAlias>
46
46
  ```
47
47
 
48
- Runs all 93 checks and writes an HTML report to the current directory. `sf audit list` prints every
48
+ Runs all 95 checks and writes an HTML report to the current directory. `sf audit list` prints every
49
49
  check id.
50
50
 
51
51
  | Flag | Default | |
@@ -77,6 +77,12 @@ sf audit security --target-org myOrg --json
77
77
  sf audit security --target-org myOrg --json --digest
78
78
  ```
79
79
 
80
+ In GitHub Actions, [cclabsnz/sf-audit-action](https://github.com/cclabsnz/sf-audit-action) wraps this:
81
+ it installs the plugin, logs in from a secret, writes a digest to the job summary, uploads the reports
82
+ and applies `--fail-on`. It audits the org, not the repository, so run it on a schedule against
83
+ production or after deploying to a validation sandbox, and from a private repository: anyone can read
84
+ a public repository's job summaries.
85
+
80
86
  ### Exit codes
81
87
 
82
88
  | Code | Meaning |
@@ -95,7 +101,7 @@ All twelve flags, more examples, and what the executive report contains:
95
101
 
96
102
  ## What It Checks
97
103
 
98
- **93 read-only checks** across ten domains. Every finding is risk-rated CRITICAL → INFO, mapped to
104
+ **95 read-only checks** across ten domains. Every finding is risk-rated CRITICAL → INFO, mapped to
99
105
  compliance controls, and correlated into [attack chains](#attack-chains).
100
106
 
101
107
  | Domain | Checks |
@@ -107,7 +113,7 @@ compliance controls, and correlated into [attack chains](#attack-chains).
107
113
  | Integrations, Connected Apps & Deployments | 11 |
108
114
  | Monitoring & Threat Detection | 10 |
109
115
  | Apex & Code Security | 10 |
110
- | AI & Agents (Agentforce / GenAI) | 6 |
116
+ | AI & Agents (Agentforce / GenAI) | 8 |
111
117
  | Org Health & Configuration | 5 |
112
118
  | Secrets & Credential Storage | 2 |
113
119
 
@@ -144,7 +150,7 @@ A list of findings is not a risk assessment. Three MEDIUM findings that combine
144
150
  unauthenticated path to bulk data matter more than a lone HIGH that leads nowhere, and reading a
145
151
  report severity-by-severity hides exactly that.
146
152
 
147
- So every audit correlates its findings into attack chains. **Sixteen named chains** are hand-modelled
153
+ So every audit correlates its findings into attack chains. **Seventeen named chains** are hand-modelled
148
154
  scenarios — each with its own narrative and remediation, several naming the concrete request path an
149
155
  attacker would use. Where no named chain explains a combination, an emergent pass reports the
150
156
  remaining entry-point → outcome pairs as lower-confidence "potential attack paths", so a novel
@@ -153,7 +159,7 @@ combination is still surfaced.
153
159
  Every chain lists the findings forming its steps, and remediating **any one step breaks the chain**.
154
160
  A chain is reported only when every ingredient is present: a clean org produces none.
155
161
 
156
- All eleven with severities and trigger conditions: **[docs/ATTACK-CHAINS.md](docs/ATTACK-CHAINS.md)**.
162
+ All seventeen with severities and trigger conditions: **[docs/ATTACK-CHAINS.md](docs/ATTACK-CHAINS.md)**.
157
163
 
158
164
  ## Scope & Liability
159
165
 
@@ -189,6 +189,25 @@ export const NAMED_CHAINS = [
189
189
  return [...agents, ...staleUrl, ...noCapture];
190
190
  },
191
191
  },
192
+ {
193
+ id: 'salesbleed-pattern',
194
+ title: 'SalesBleed pattern',
195
+ severity: 'HIGH',
196
+ narrative: 'An active agent can run open-ended record queries (the General CRM topic or Query Records action) and ' +
197
+ 'the org has agent actions that send data out (Slack, email, external services) without user confirmation. ' +
198
+ 'That is two of the three ingredients in SalesBleed (Zenity Labs, Sept 2026) and PipeLeak (Capsule ' +
199
+ 'Security, Apr 2026); the third, text an outsider wrote, arrives through Web-to-Lead, Web-to-Case, email or ' +
200
+ 'chat in almost every org. One injected instruction in a lead can query Accounts and send the result out.',
201
+ remediation: 'Break any one link: remove open-ended querying from agents that read untrusted records, require user ' +
202
+ 'confirmation on every outbound action, or keep the agent that queries separate from the agent that sends.',
203
+ match(_present, active) {
204
+ const reach = byPrefixes(active, ['agent-query-reach-']);
205
+ const outbound = byIds(active, ['agent-outbound-actions-unconfirmed', 'agent-outbound-actions-unverified']);
206
+ if (reach.length === 0 || outbound.length === 0)
207
+ return null;
208
+ return [...reach, ...outbound];
209
+ },
210
+ },
192
211
  {
193
212
  id: 'sandbox-pii-exposure',
194
213
  title: 'Unmasked production PII in a weakly-controlled sandbox',
@@ -54,7 +54,8 @@ export class AgentInventoryCheck {
54
54
  let versions;
55
55
  let agentUsers;
56
56
  try {
57
- versions = await ctx.tooling.query(`SELECT Id, BotDefinitionId, Status, VersionNumber FROM BotVersion WHERE Status = 'Active'`);
57
+ // BotVersion, like BotDefinition, is a data API object: Tooling answers INVALID_TYPE.
58
+ versions = await ctx.soql.queryAll(`SELECT Id, BotDefinitionId, Status, VersionNumber FROM BotVersion WHERE Status = 'Active'`);
58
59
  // GenAiPlannerDefinition is queried for completeness of the agent picture (Phase 2
59
60
  // action-surface work joins on it); a failure here still counts as an incomplete build.
60
61
  await ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel FROM GenAiPlannerDefinition`);
@@ -159,13 +160,17 @@ export class AgentInventoryCheck {
159
160
  // BotDefinition query with a defensive fallback: if Type/BotUserId are not queryable in
160
161
  // this org/release (MALFORMED_QUERY on the field), retry with the minimal field set rather
161
162
  // than throw. A genuinely missing object still throws and is handled by the caller.
163
+ //
164
+ // BotDefinition is a data API object. The Tooling API answers INVALID_TYPE for it even in
165
+ // orgs with active agents (verified 2026-10-09 on a v67.0 org), which the caller reads as
166
+ // "Agentforce not enabled" — so querying it through Tooling silenced every AI & Agents check.
162
167
  async queryBotDefinitions(ctx) {
163
168
  try {
164
- return await ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel, Type, BotUserId FROM BotDefinition`);
169
+ return await ctx.soql.queryAll(`SELECT Id, DeveloperName, MasterLabel, Type, BotUserId FROM BotDefinition`);
165
170
  }
166
171
  catch (e) {
167
172
  if (isApiError(e) && /MALFORMED_QUERY|INVALID_FIELD/i.test(e.errorCode)) {
168
- return ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel FROM BotDefinition`);
173
+ return ctx.soql.queryAll(`SELECT Id, DeveloperName, MasterLabel FROM BotDefinition`);
169
174
  }
170
175
  throw e;
171
176
  }
@@ -0,0 +1,13 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class AgentOutboundActionsCheck implements SecurityCheck {
4
+ readonly id = "agent-outbound-actions";
5
+ readonly name = "Agent Outbound Actions";
6
+ readonly category = "AI & Agents";
7
+ readonly description = "Flags agent actions that send data out of the org (Slack messages, email, external services and MCP tools, including Flow actions whose flow sends email or calls an external service) without requiring user confirmation. An injected prompt can use them to carry data out: PipeLeak (Capsule Security, 2026) used the email action, and SalesBleed posted through Slack.";
8
+ readonly dependsOnCache: readonly ['agentInventory', 'agentAccess'];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ private outboundFlows;
11
+ private inspectFlow;
12
+ }
13
+ //# sourceMappingURL=AgentOutboundActionsCheck.d.ts.map
@@ -0,0 +1,155 @@
1
+ import { loadAgentGraph } from '../support/agentGraph.js';
2
+ // Invocation types that hand data to something outside the org.
3
+ const EXTERNAL_TYPES = new Set(['slack', 'externalservice', 'externalconnector', 'mcptool', 'platformmcptool']);
4
+ // Standard invocable actions that send email (Flow's core "Send Email" and email alerts).
5
+ const EMAIL_TARGETS = new Set(['emailsimple', 'emailalert']);
6
+ // Standard Slack actions that post a message somewhere. Names verified from the
7
+ // GenAiPluginFunctionDef.Function picklist (v67.0).
8
+ const SLACK_SEND = /(^|__)(ReplyInThread|SendMessageAsAgent|SendMessageToSlackChannel|SendSlackDirectMessage)(_|$)/i;
9
+ // "SendClaimEmail", "SendVisitSummaryEmail": a name that sends rather than drafts an email.
10
+ const SEND_EMAIL_NAME = /(^|__|_)Send\w*Email/i;
11
+ // Flow action types that send data out. Read from the active flow version's metadata, because
12
+ // an agent's Flow action names the FlowDefinition Id, not what the flow does.
13
+ const FLOW_OUTBOUND = {
14
+ emailsimple: 'email',
15
+ emailalert: 'email',
16
+ externalservice: 'external service',
17
+ };
18
+ // Flows inspected per run. Each needs two Tooling reads; past this the rest are skipped.
19
+ const MAX_FLOWS = 25;
20
+ function outboundKind(fn) {
21
+ const type = (fn.InvocationTargetType ?? '').toLowerCase();
22
+ const target = (fn.InvocationTarget ?? '').toLowerCase();
23
+ const names = [fn.Source, fn.DeveloperName].filter((n) => !!n);
24
+ if (type === 'slack' || names.some((n) => SLACK_SEND.test(n)))
25
+ return 'Slack message';
26
+ if (EMAIL_TARGETS.has(target) || names.some((n) => SEND_EMAIL_NAME.test(n)))
27
+ return 'email';
28
+ if (EXTERNAL_TYPES.has(type))
29
+ return 'external service';
30
+ return null;
31
+ }
32
+ export class AgentOutboundActionsCheck {
33
+ id = 'agent-outbound-actions';
34
+ name = 'Agent Outbound Actions';
35
+ category = 'AI & Agents';
36
+ description = 'Flags agent actions that send data out of the org (Slack messages, email, external services and MCP tools, including Flow actions whose flow sends email or calls an external service) without requiring user confirmation. An injected prompt can use them to carry data out: PipeLeak (Capsule Security, 2026) used the email action, and SalesBleed posted through Slack.';
37
+ dependsOnCache = ['agentInventory', 'agentAccess'];
38
+ async run(ctx) {
39
+ const findings = [];
40
+ if (ctx.cache.agentAccess !== 'ok')
41
+ return { findings };
42
+ const activeAgents = (ctx.cache.agentInventory ?? []).filter((a) => a.type === 'agent' && a.isActive);
43
+ if (activeAgents.length === 0)
44
+ return { findings };
45
+ const graph = await loadAgentGraph(ctx, activeAgents);
46
+ if (!graph)
47
+ return { findings };
48
+ // Every action on a live topic, once each.
49
+ const live = new Map();
50
+ for (const topicId of graph.liveTopicIds)
51
+ for (const fn of graph.actionsByTopic.get(topicId) ?? [])
52
+ live.set(fn.Id, fn);
53
+ const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/EinsteinCopilot/home`;
54
+ const unconfirmed = [];
55
+ const flowActions = [];
56
+ for (const fn of live.values()) {
57
+ if (fn.IsConfirmationRequired === true)
58
+ continue;
59
+ const kind = outboundKind(fn);
60
+ if (kind)
61
+ unconfirmed.push({ label: fn.MasterLabel ?? fn.DeveloperName, kind });
62
+ else if ((fn.InvocationTargetType ?? '').toLowerCase() === 'flow' && fn.InvocationTarget)
63
+ flowActions.push(fn);
64
+ }
65
+ for (const { fn, kind, flowName } of await this.outboundFlows(ctx, flowActions)) {
66
+ unconfirmed.push({ label: fn.MasterLabel ?? fn.DeveloperName, kind, via: flowName });
67
+ }
68
+ if (unconfirmed.length > 0) {
69
+ findings.push({
70
+ id: 'agent-outbound-actions-unconfirmed',
71
+ category: this.category,
72
+ riskLevel: 'HIGH',
73
+ title: `${unconfirmed.length} agent action(s) can send data out of the org without user confirmation`,
74
+ detail: `${unconfirmed.length} action(s) on active agents send a Slack message, an email or a call to an ` +
75
+ `external service, and none of them requires the user to confirm first. If an agent reads text an ` +
76
+ `outsider wrote (a lead, a case, an email), an injected instruction can use these actions to send ` +
77
+ `whatever the agent can read to an address or channel the attacker chooses. PipeLeak used the email ` +
78
+ `action this way; SalesBleed used Slack. Flow actions are judged by what the active flow version does; ` +
79
+ `Apex actions are not inspected. Rendered links and Slack link previews are further ways out that this ` +
80
+ `metadata audit cannot see.`,
81
+ remediation: 'Turn on "Require user confirmation" for each of these actions, or remove them from agents that read ' +
82
+ 'untrusted input. Keep agents that send messages separate from agents that can query broadly.',
83
+ affectedItems: unconfirmed.map((u) => ({
84
+ label: u.label,
85
+ url: setupUrl,
86
+ note: `${u.kind}${u.via ? ` (flow ${u.via})` : ''}, no confirmation required`,
87
+ })),
88
+ });
89
+ }
90
+ // Standard outbound actions a live topic names with no local definition to read the setting from.
91
+ const unverified = [...new Set([...graph.liveTopicIds]
92
+ .flatMap((id) => graph.unresolvedActionsByTopic.get(id) ?? [])
93
+ .filter((n) => outboundKind({ DeveloperName: n, Source: null, InvocationTargetType: null, InvocationTarget: null }) !== null))];
94
+ if (unverified.length > 0) {
95
+ findings.push({
96
+ id: 'agent-outbound-actions-unverified',
97
+ category: this.category,
98
+ riskLevel: 'MEDIUM',
99
+ title: `${unverified.length} standard outbound action(s) in use; confirmation setting not readable`,
100
+ detail: `Topics on active agents use ${unverified.length} standard action(s) that post to Slack or send email ` +
101
+ `(${unverified.join(', ')}). The platform does not expose their confirmation setting through Tooling, ` +
102
+ `so this audit cannot tell whether a user must approve each message. Salesforce changed the default for ` +
103
+ `some Agentforce Slack actions to require confirmation after SalesBleed; agents configured earlier may ` +
104
+ `not have picked that up.`,
105
+ remediation: 'Open each agent that uses these actions in Agentforce Builder and confirm that user confirmation is ' +
106
+ 'required before a message is sent. Remove the action where the agent does not need to post.',
107
+ affectedItems: unverified.map((n) => ({ label: n, url: setupUrl, note: 'standard action, confirmation not verified' })),
108
+ });
109
+ }
110
+ return { findings };
111
+ }
112
+ // For Flow actions, read the active version of each flow and report the first outbound step.
113
+ // An agent's Flow action targets the FlowDefinition by Id (300...) or by API name.
114
+ async outboundFlows(ctx, actions) {
115
+ const out = [];
116
+ const seen = new Map();
117
+ for (const fn of actions) {
118
+ const target = fn.InvocationTarget;
119
+ if (!seen.has(target)) {
120
+ if (seen.size >= MAX_FLOWS)
121
+ break;
122
+ seen.set(target, await this.inspectFlow(ctx, target));
123
+ }
124
+ const hit = seen.get(target);
125
+ if (hit)
126
+ out.push({ fn, ...hit });
127
+ }
128
+ return out;
129
+ }
130
+ async inspectFlow(ctx, target) {
131
+ try {
132
+ const where = /^300[A-Za-z0-9]{12}([A-Za-z0-9]{3})?$/.test(target)
133
+ ? `Id = '${target}'`
134
+ : `DeveloperName = '${target.split('__').pop().replace(/'/g, '')}'`;
135
+ const [def] = await ctx.tooling.query(`SELECT Id, DeveloperName, ActiveVersionId FROM FlowDefinition WHERE ${where}`);
136
+ if (!def?.ActiveVersionId)
137
+ return null;
138
+ // Tooling returns Metadata for one Flow row per query.
139
+ const [version] = await ctx.tooling.query(`SELECT Id, Metadata FROM Flow WHERE Id = '${def.ActiveVersionId}'`);
140
+ for (const call of version?.Metadata?.actionCalls ?? []) {
141
+ const type = (call.actionType ?? '').toLowerCase();
142
+ const name = (call.actionName ?? '').toLowerCase();
143
+ const kind = FLOW_OUTBOUND[type] ?? (type.includes('slack') || name.includes('slack') ? 'Slack message' : undefined);
144
+ if (kind)
145
+ return { kind, flowName: def.DeveloperName };
146
+ }
147
+ return null;
148
+ }
149
+ catch {
150
+ // Flow metadata unreadable: make no claim about this action.
151
+ return null;
152
+ }
153
+ }
154
+ }
155
+ //# sourceMappingURL=AgentOutboundActionsCheck.js.map
@@ -0,0 +1,11 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class AgentQueryReachCheck implements SecurityCheck {
4
+ readonly id = "agent-query-reach";
5
+ readonly name = "Agent Query Reach";
6
+ readonly category = "AI & Agents";
7
+ readonly description = "Flags agents that carry the standard General CRM topic or a Query Records action, which lets an injected prompt query any object the run-as user can read. This open-ended query is how SalesBleed (Zenity Labs, 2026) read Account data from a poisoned Web-to-Lead record.";
8
+ readonly dependsOnCache: readonly ['agentInventory', 'agentAccess'];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ }
11
+ //# sourceMappingURL=AgentQueryReachCheck.d.ts.map
@@ -0,0 +1,88 @@
1
+ import { loadAgentGraph } from '../support/agentGraph.js';
2
+ // Standard names are namespaced (EmployeeCopilot__GeneralCRM); local copies carry them in Source
3
+ // or as a DeveloperName prefix with an id suffix (GeneralCRM_16jgK000002FoUn). Match by suffix
4
+ // so the namespace and local suffixes are not load-bearing.
5
+ const GENERAL_CRM = /(^|__)GeneralCRM(_|$)/i;
6
+ const QUERY_RECORDS = /(^|__)QueryRecords(WithAggregate)?(_|$)/i;
7
+ const matches = (re, ...names) => names.some((n) => !!n && re.test(n));
8
+ const isQueryAction = (fn) => matches(QUERY_RECORDS, fn.Source, fn.DeveloperName);
9
+ const topicLabel = (t) => t.MasterLabel ?? t.DeveloperName;
10
+ export class AgentQueryReachCheck {
11
+ id = 'agent-query-reach';
12
+ name = 'Agent Query Reach';
13
+ category = 'AI & Agents';
14
+ description = 'Flags agents that carry the standard General CRM topic or a Query Records action, which lets an injected prompt query any object the run-as user can read. This open-ended query is how SalesBleed (Zenity Labs, 2026) read Account data from a poisoned Web-to-Lead record.';
15
+ dependsOnCache = ['agentInventory', 'agentAccess'];
16
+ async run(ctx) {
17
+ const findings = [];
18
+ if (ctx.cache.agentAccess !== 'ok')
19
+ return { findings };
20
+ const activeAgents = (ctx.cache.agentInventory ?? []).filter((a) => a.type === 'agent' && a.isActive);
21
+ if (activeAgents.length === 0)
22
+ return { findings };
23
+ const graph = await loadAgentGraph(ctx, activeAgents);
24
+ if (!graph)
25
+ return { findings };
26
+ const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/EinsteinCopilot/home`;
27
+ for (const planner of graph.planners) {
28
+ const reasons = new Set();
29
+ for (const topic of graph.topicsByPlanner.get(planner.Id) ?? []) {
30
+ if (matches(GENERAL_CRM, topic.Source, topic.DeveloperName))
31
+ reasons.add('General CRM topic');
32
+ const actions = graph.actionsByTopic.get(topic.Id) ?? [];
33
+ const unresolved = graph.unresolvedActionsByTopic.get(topic.Id) ?? [];
34
+ if (actions.some(isQueryAction) || unresolved.some((n) => QUERY_RECORDS.test(n))) {
35
+ reasons.add(topic.Id.startsWith('planner:') ? 'Query Records action' : `Query Records action (topic ${topicLabel(topic)})`);
36
+ }
37
+ }
38
+ if (reasons.size === 0)
39
+ continue;
40
+ const label = planner.MasterLabel ?? planner.DeveloperName;
41
+ const why = [...reasons].join(', ');
42
+ findings.push({
43
+ id: `agent-query-reach-${planner.DeveloperName}`,
44
+ category: this.category,
45
+ riskLevel: 'HIGH',
46
+ title: `Agent "${label}" can run open-ended record queries`,
47
+ detail: `The agent "${label}" (${planner.DeveloperName}) has: ${why}. The standard General CRM topic and its ` +
48
+ `Query Records action let the model decide at run time which object to query, so an instruction ` +
49
+ `hidden in any record the agent reads (a Web-to-Lead or Web-to-Case submission, an inbound email, a ` +
50
+ `chat transcript) can make it query any object its run-as user can see. This is how SalesBleed read ` +
51
+ `Account data from a poisoned lead. Whether that data can then leave depends on the agent's output ` +
52
+ `channels; see agent-outbound-actions.` +
53
+ (graph.activeOnly ? '' : ' (Active versions could not be told apart, so every agent version was checked.)'),
54
+ remediation: 'Remove the General CRM topic or the Query Records action from agents that do not need open-ended ' +
55
+ 'querying, and replace it with actions that read only the records the job needs. Where it must stay, ' +
56
+ 'keep the agent away from untrusted input and trim its run-as user\'s object and field access.',
57
+ affectedItems: [{ label: `${label} (${planner.DeveloperName})`, url: setupUrl, note: why }],
58
+ });
59
+ }
60
+ // Query Records on topics no agent references. Only meaningful when every planner was in
61
+ // scope: once narrowed to active versions, inactive versions' topics are expected here.
62
+ if (findings.length === 0 && !graph.activeOnly) {
63
+ const orphans = [...graph.actionsByTopic.entries()]
64
+ .filter(([topicId, fns]) => !graph.liveTopicIds.has(topicId) && fns.some(isQueryAction))
65
+ .map(([topicId]) => topicId);
66
+ for (const [topicId, names] of graph.unresolvedActionsByTopic) {
67
+ if (!graph.liveTopicIds.has(topicId) && names.some((n) => QUERY_RECORDS.test(n)) && !orphans.includes(topicId))
68
+ orphans.push(topicId);
69
+ }
70
+ if (orphans.length > 0) {
71
+ findings.push({
72
+ id: 'agent-query-reach-unmapped',
73
+ category: this.category,
74
+ riskLevel: 'MEDIUM',
75
+ title: `Query Records is configured on ${orphans.length} topic(s) not tied to a specific agent`,
76
+ detail: `The open-ended Query Records action is attached to ${orphans.length} topic(s), but the platform did ` +
77
+ `not expose a link from those topics to an agent. ${activeAgents.length} active agent(s) exist, so ` +
78
+ `confirm in Agentforce Builder whether any of them uses these topics.`,
79
+ remediation: 'Open each active agent in Agentforce Builder and check its topics for Query Records. Remove it where ' +
80
+ 'the agent does not need open-ended querying.',
81
+ affectedItems: orphans.map((id) => ({ label: id, url: setupUrl, note: 'topic with Query Records' })),
82
+ });
83
+ }
84
+ }
85
+ return { findings };
86
+ }
87
+ }
88
+ //# sourceMappingURL=AgentQueryReachCheck.js.map
@@ -98,6 +98,8 @@ import { AgentUserPrivilegeCheck } from './impl/AgentUserPrivilegeCheck.js';
98
98
  import { AgentActionSurfaceCheck } from './impl/AgentActionSurfaceCheck.js';
99
99
  import { AgentChannelExposureCheck } from './impl/AgentChannelExposureCheck.js';
100
100
  import { AgentMonitoringCoverageCheck } from './impl/AgentMonitoringCoverageCheck.js';
101
+ import { AgentQueryReachCheck } from './impl/AgentQueryReachCheck.js';
102
+ import { AgentOutboundActionsCheck } from './impl/AgentOutboundActionsCheck.js';
101
103
  import { TrustedUrlHygieneCheck } from './impl/TrustedUrlHygieneCheck.js';
102
104
  // Order matters: a check's dependsOnCache must be satisfied by a preceding check's populatesCache.
103
105
  // CheckEngine.validateCacheOrdering() enforces this at startup.
@@ -203,6 +205,8 @@ export const CHECKS = [
203
205
  new AgentActionSurfaceCheck(), // reads agentInventory, agentAccess
204
206
  new AgentChannelExposureCheck(), // reads agentInventory, agentAccess
205
207
  new AgentMonitoringCoverageCheck(), // reads agentInventory, agentAccess, eventLogSummary
208
+ new AgentQueryReachCheck(), // reads agentInventory, agentAccess
209
+ new AgentOutboundActionsCheck(), // reads agentInventory, agentAccess
206
210
  new TrustedUrlHygieneCheck(), // reads cspTrustedSites (runs even without Agentforce)
207
211
  ];
208
212
  //# sourceMappingURL=registry.js.map
@@ -0,0 +1,49 @@
1
+ import type { AuditContext, AgentDefinition } from '@cclabsnz/sf-core';
2
+ export interface PlannerRow {
3
+ Id: string;
4
+ DeveloperName: string;
5
+ MasterLabel?: string | null;
6
+ }
7
+ export interface PlannerTopicRow {
8
+ PlannerId: string;
9
+ Plugin: string | null;
10
+ }
11
+ export interface PluginRow {
12
+ Id: string;
13
+ DeveloperName: string;
14
+ MasterLabel?: string | null;
15
+ Source?: string | null;
16
+ PlannerId?: string | null;
17
+ }
18
+ export interface PluginActionRow {
19
+ PluginId: string;
20
+ Function: string | null;
21
+ }
22
+ export interface FunctionRow {
23
+ Id: string;
24
+ DeveloperName: string;
25
+ MasterLabel?: string | null;
26
+ Source?: string | null;
27
+ PlannerId?: string | null;
28
+ PluginId?: string | null;
29
+ InvocationTargetType?: string | null;
30
+ InvocationTarget?: string | null;
31
+ IsConfirmationRequired?: boolean | null;
32
+ }
33
+ export interface AgentGraph {
34
+ /** Planners of active agent versions; every planner when versions cannot be matched. */
35
+ planners: PlannerRow[];
36
+ /** Whether `planners` was narrowed to active versions (false = fell back to all). */
37
+ activeOnly: boolean;
38
+ /** Topics attached to each planner in `planners`, by planner Id. */
39
+ topicsByPlanner: Map<string, PluginRow[]>;
40
+ /** Actions attached to each topic, by topic Id. */
41
+ actionsByTopic: Map<string, FunctionRow[]>;
42
+ /** Standard action names a topic references with no local definition row, by topic Id. */
43
+ unresolvedActionsByTopic: Map<string, string[]>;
44
+ /** Every topic Id reachable from `planners`. */
45
+ liveTopicIds: Set<string>;
46
+ }
47
+ /** Null when the planner object itself is unavailable (feature absent or no access). */
48
+ export declare function loadAgentGraph(ctx: AuditContext, activeAgents: AgentDefinition[]): Promise<AgentGraph | null>;
49
+ //# sourceMappingURL=agentGraph.d.ts.map
@@ -0,0 +1,87 @@
1
+ async function optional(ctx, soql) {
2
+ try {
3
+ return await ctx.tooling.query(soql);
4
+ }
5
+ catch {
6
+ return [];
7
+ }
8
+ }
9
+ /** Null when the planner object itself is unavailable (feature absent or no access). */
10
+ export async function loadAgentGraph(ctx, activeAgents) {
11
+ let allPlanners;
12
+ try {
13
+ allPlanners = await ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel FROM GenAiPlannerDefinition`);
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ const plannerTopics = await optional(ctx, `SELECT PlannerId, Plugin FROM GenAiPlannerFunctionDef`);
19
+ const plugins = await optional(ctx, `SELECT Id, DeveloperName, MasterLabel, Source, PlannerId FROM GenAiPluginDefinition`);
20
+ const pluginActions = await optional(ctx, `SELECT PluginId, Function FROM GenAiPluginFunctionDef`);
21
+ const functions = await optional(ctx, `SELECT Id, DeveloperName, MasterLabel, Source, PlannerId, PluginId, InvocationTargetType, InvocationTarget, IsConfirmationRequired FROM GenAiFunctionDefinition`);
22
+ // Narrow to the planner of each agent's active version. If no planner follows the
23
+ // `<agent>_v<n>` convention, keep them all rather than report nothing.
24
+ const activeNames = new Set(activeAgents.filter((a) => a.activeVersion !== undefined).map((a) => `${a.developerName}_v${a.activeVersion}`.toLowerCase()));
25
+ const active = allPlanners.filter((p) => activeNames.has(p.DeveloperName.toLowerCase()));
26
+ const planners = active.length > 0 ? active : allPlanners;
27
+ const plannerIds = new Set(planners.map((p) => p.Id));
28
+ // A topic reference may be the topic's Id or its developer name.
29
+ const pluginByRef = new Map();
30
+ for (const p of plugins) {
31
+ pluginByRef.set(p.Id, p);
32
+ pluginByRef.set(p.DeveloperName, p);
33
+ }
34
+ const topicsByPlanner = new Map();
35
+ const attach = (plannerId, topic) => {
36
+ const list = topicsByPlanner.get(plannerId) ?? [];
37
+ if (!list.some((t) => t.Id === topic.Id))
38
+ list.push(topic);
39
+ topicsByPlanner.set(plannerId, list);
40
+ };
41
+ for (const t of plannerTopics) {
42
+ if (!plannerIds.has(t.PlannerId) || !t.Plugin)
43
+ continue;
44
+ // An unresolved reference is a standard topic named directly (no local copy).
45
+ attach(t.PlannerId, pluginByRef.get(t.Plugin) ?? { Id: t.Plugin, DeveloperName: t.Plugin, Source: t.Plugin });
46
+ }
47
+ for (const p of plugins)
48
+ if (p.PlannerId && plannerIds.has(p.PlannerId))
49
+ attach(p.PlannerId, p);
50
+ const liveTopicIds = new Set([...topicsByPlanner.values()].flat().map((t) => t.Id));
51
+ // Actions per topic: definition rows by PluginId, plus link rows resolved by Id.
52
+ const functionById = new Map(functions.map((f) => [f.Id, f]));
53
+ const actionsByTopic = new Map();
54
+ const unresolvedActionsByTopic = new Map();
55
+ const addAction = (topicId, fn) => {
56
+ const list = actionsByTopic.get(topicId) ?? [];
57
+ if (!list.some((x) => x.Id === fn.Id))
58
+ list.push(fn);
59
+ actionsByTopic.set(topicId, list);
60
+ };
61
+ for (const fn of functions)
62
+ if (fn.PluginId)
63
+ addAction(fn.PluginId, fn);
64
+ for (const pa of pluginActions) {
65
+ if (!pa.Function)
66
+ continue;
67
+ const fn = functionById.get(pa.Function);
68
+ if (fn)
69
+ addAction(pa.PluginId, fn);
70
+ else {
71
+ const list = unresolvedActionsByTopic.get(pa.PluginId) ?? [];
72
+ list.push(pa.Function);
73
+ unresolvedActionsByTopic.set(pa.PluginId, list);
74
+ }
75
+ }
76
+ // Actions attached straight to a planner (no topic) count under a pseudo-topic per planner.
77
+ for (const fn of functions) {
78
+ if (fn.PlannerId && plannerIds.has(fn.PlannerId) && !fn.PluginId) {
79
+ const pseudo = `planner:${fn.PlannerId}`;
80
+ attach(fn.PlannerId, { Id: pseudo, DeveloperName: pseudo });
81
+ liveTopicIds.add(pseudo);
82
+ addAction(pseudo, fn);
83
+ }
84
+ }
85
+ return { planners, activeOnly: active.length > 0, topicsByPlanner, actionsByTopic, unresolvedActionsByTopic, liveTopicIds };
86
+ }
87
+ //# sourceMappingURL=agentGraph.js.map
@@ -110,6 +110,11 @@ const BASE_CHECK_CONTROL_MAP = {
110
110
  'agent-channel-exposure': ['OWASP-A01', 'SOC2-CC6.1', 'ISO-A.8.3', 'LLM01'],
111
111
  'agent-monitoring-coverage': ['OWASP-A09', 'SOC2-CC7.2', 'ISO-A.8.15', 'LLM02'],
112
112
  'trusted-url-hygiene': ['OWASP-A05', 'OWASP-A10', 'SOC2-CC6.6', 'ISO-A.8.26', 'LLM01', 'LLM05'],
113
+ // agent-query-reach: open-ended querying is excess agency, and it is what an injection reads
114
+ // through (LLM02). agent-outbound-actions: an unconfirmed send is the output channel an
115
+ // injected payload leaves by (LLM05) and an action taken without human approval (LLM06).
116
+ 'agent-query-reach': ['OWASP-A01', 'SOC2-CC6.3', 'ISO-A.8.3', 'LLM06', 'LLM02'],
117
+ 'agent-outbound-actions': ['OWASP-A01', 'SOC2-CC6.6', 'ISO-A.8.3', 'LLM05', 'LLM06'],
113
118
  };
114
119
  // Domain groupings. Each check belongs to exactly one domain, and a domain's control ids are
115
120
  // layered onto every base entry in it. Shared by the NZ pack and the HIPAA/GDPR crosswalk below
@@ -142,7 +147,7 @@ const DOMAIN = {
142
147
  // have no chapter that fits); HIPAA and GDPR do, because an over-privileged agent user reading
143
148
  // PHI or personal data is squarely an access-control and security-of-processing question.
144
149
  aiAgents: ['agent-inventory', 'agent-user-privilege', 'agent-action-surface', 'agent-channel-exposure',
145
- 'agent-monitoring-coverage', 'trusted-url-hygiene'],
150
+ 'agent-monitoring-coverage', 'trusted-url-hygiene', 'agent-query-reach', 'agent-outbound-actions'],
146
151
  };
147
152
  // NZ pack crosswalk — HISO/NZISM are domain/chapter-level; Privacy Act IPPs are statute-level.
148
153
  const NZ_CROSSWALK = [
@@ -212,6 +217,8 @@ const REGULATORY_PRECISE = {
212
217
  'agent-channel-exposure': ['HIPAA-164.312(a)(1)', 'GDPR-Art25', 'GDPR-Art5(1)(f)'],
213
218
  'agent-monitoring-coverage': ['HIPAA-164.312(b)', 'HIPAA-164.308(a)(1)(ii)(D)', 'GDPR-Art33'],
214
219
  'trusted-url-hygiene': ['HIPAA-164.312(e)(1)', 'GDPR-Art44'],
220
+ 'agent-query-reach': ['HIPAA-164.312(a)(1)', 'HIPAA-164.308(a)(4)', 'GDPR-Art25', 'GDPR-Art5(1)(f)'],
221
+ 'agent-outbound-actions': ['HIPAA-164.312(e)(1)', 'GDPR-Art25', 'GDPR-Art32(1)(b)'],
215
222
  };
216
223
  function buildCheckControlMap() {
217
224
  const map = {};
@@ -91,6 +91,8 @@ export const CHECK_META = {
91
91
  'agent-action-surface': { effort: 'moderate', impact: 'Write-capable agent actions (Apex/Flow that create, update, or delete) let an injected prompt take state-changing operations, not just read data — the difference between a leak and active tampering on an exposed agent.' },
92
92
  'agent-channel-exposure': { effort: 'moderate', impact: 'An agent bound to a guest-reachable channel lets any unauthenticated visitor send prompt-injection input to an agent that executes with its run-as user\'s data access: the public-input half of the ForcedLeak pattern.' },
93
93
  'agent-monitoring-coverage': { effort: 'moderate', impact: 'Active agents with no Event Monitoring capture and no Transaction Security policy leave prompt injection, mass reads, and exfiltration with no auditable trail and no automated response.' },
94
+ 'agent-query-reach': { effort: 'moderate', impact: 'The General CRM topic and Query Records action let an injected prompt choose which object to query, so one poisoned lead or case can read any object the run-as user can see: the SalesBleed read path.' },
95
+ 'agent-outbound-actions': { effort: 'quick', impact: 'Slack, email and external-service actions with no user confirmation give an injected prompt a ready way to send data out of the org: the PipeLeak and SalesBleed exit path.' },
94
96
  'trusted-url-hygiene': { effort: 'quick', impact: 'A non-Salesforce CSP-trusted domain that has lapsed or been parked is an allowlisted exfiltration channel: whoever re-registers it can receive prompt-injected data from Lightning and Agentforce output — the exact ForcedLeak exfil vector.' },
95
97
  };
96
98
  export function getCheckMeta(id) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-audit",
3
- "version": "1.15.1",
3
+ "version": "1.16.0",
4
4
  "description": "Read-only Salesforce security audit for the sf CLI: 93 checks, attack-chain correlation, A-F risk grading, compliance mapping, free EventLogFile capture, and Guest User Anomaly investigation.",
5
5
  "keywords": [
6
6
  "salesforce",