@cclabsnz/sf-audit 1.19.0 → 1.21.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 (44) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/lib/apps/apiLogSource.js +3 -2
  3. package/lib/chains/AttackChain.d.ts +14 -0
  4. package/lib/chains/CapabilityRegistry.d.ts +5 -0
  5. package/lib/chains/CapabilityRegistry.js +31 -31
  6. package/lib/chains/ChainEngine.d.ts +2 -0
  7. package/lib/chains/ChainEngine.js +31 -6
  8. package/lib/chains/namedChains.d.ts +85 -0
  9. package/lib/chains/namedChains.js +404 -210
  10. package/lib/checks/CheckEngine.js +5 -2
  11. package/lib/checks/impl/AgentActionSurfaceCheck.js +2 -13
  12. package/lib/checks/impl/AgentInventoryCheck.js +2 -15
  13. package/lib/checks/impl/ApexLoggingCheck.js +2 -0
  14. package/lib/checks/impl/GuestApiAccessCheck.js +2 -0
  15. package/lib/checks/impl/GuestUserAccessCheck.js +2 -0
  16. package/lib/checks/impl/UsersAndAdminsCheck.js +5 -5
  17. package/lib/checks/registry.js +1 -1
  18. package/lib/checks/support/missingObject.js +2 -1
  19. package/lib/checks/support/schema.js +1 -1
  20. package/lib/commands/audit/incident/collect.js +2 -1
  21. package/lib/findings/Finding.d.ts +7 -0
  22. package/lib/incident/collect/orgErrors.js +3 -1
  23. package/lib/incident/collect/streamGuestLogs.js +3 -2
  24. package/lib/lib/apiErrorText.d.ts +8 -0
  25. package/lib/lib/apiErrorText.js +15 -0
  26. package/lib/renderers/AttackChainDagRenderer.d.ts +5 -1
  27. package/lib/renderers/AttackChainDagRenderer.js +16 -31
  28. package/lib/renderers/ClientReportRenderer.js +4 -1
  29. package/lib/renderers/HtmlRenderer.js +12 -2
  30. package/lib/renderers/MarkdownRenderer.js +67 -2
  31. package/lib/renderers/SarifRenderer.js +16 -2
  32. package/lib/threats/attack.d.ts +63 -0
  33. package/lib/threats/attack.js +156 -0
  34. package/lib/threats/linddun.d.ts +3 -0
  35. package/lib/threats/linddun.js +40 -0
  36. package/lib/threats/resolve.d.ts +11 -0
  37. package/lib/threats/resolve.js +27 -0
  38. package/lib/threats/stride.d.ts +3 -0
  39. package/lib/threats/stride.js +120 -0
  40. package/lib/threats/types.d.ts +20 -0
  41. package/lib/threats/types.js +22 -0
  42. package/lib/threats/view.d.ts +27 -0
  43. package/lib/threats/view.js +51 -0
  44. package/package.json +3 -3
@@ -1,5 +1,6 @@
1
1
  import { buildAuditResult } from '../findings/scoring.js';
2
2
  import { getComplianceTags } from '../compliance/resolve.js';
3
+ import { threatsFor, withAttack } from '../threats/resolve.js';
3
4
  import { ChainEngine } from '../chains/ChainEngine.js';
4
5
  import { applyWaivers } from '../waivers/applyWaivers.js';
5
6
  import { permissionLabelsFor } from '../preflight/permissions.js';
@@ -93,13 +94,15 @@ export class CheckEngine {
93
94
  try {
94
95
  const result = await check.run(this.ctx);
95
96
  const tags = getComplianceTags(check.id);
96
- findings.push(...result.findings.map((f) => ({ ...f, checkId: check.id, complianceTags: tags })));
97
+ findings.push(...result.findings.map((f) => ({
98
+ ...f, checkId: check.id, complianceTags: tags, threats: withAttack(f, threatsFor(check.id, f.threats)),
99
+ })));
97
100
  if (result.metrics) {
98
101
  metrics = { ...metrics, ...result.metrics };
99
102
  }
100
103
  }
101
104
  catch (err) {
102
- findings.push(buildErrorFinding(check, err));
105
+ findings.push({ ...buildErrorFinding(check, err), threats: threatsFor(check.id) });
103
106
  }
104
107
  }
105
108
  // Waivers apply before correlation but do not remove findings from it: an accepted weakness
@@ -1,4 +1,5 @@
1
- import { isApiError } from '@cclabsnz/sf-core';
1
+ // Shared, so MALFORMED_QUERY (a bug in the query) is never read as an absent feature.
2
+ import { isMissingObjectError } from '../support/missingObject.js';
2
3
  // An agent carrying more than this many actions has a large, hard-to-review surface. Info
3
4
  // only — a big surface is not a vulnerability by itself, but it is worth surfacing.
4
5
  const ACTION_COUNT_THRESHOLD = 15;
@@ -6,18 +7,6 @@ const ACTION_COUNT_THRESHOLD = 15;
6
7
  // them as write-capable). Apex and Flow can both mutate data; where the type string is
7
8
  // unknown/ambiguous we deliberately err toward flagging and say so in the finding.
8
9
  const WRITE_CAPABLE_TYPE_HINTS = ['apex', 'flow'];
9
- function isMissingObjectError(err) {
10
- if (isApiError(err)) {
11
- if (/INVALID_TYPE|NOT_FOUND|MALFORMED_QUERY/i.test(err.errorCode))
12
- return true;
13
- if (err.statusCode === 404)
14
- return true;
15
- }
16
- const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
17
- return (msg.includes('not supported') ||
18
- msg.includes('invalid type') ||
19
- msg.includes('sobject type'));
20
- }
21
10
  export class AgentActionSurfaceCheck {
22
11
  id = 'agent-action-surface';
23
12
  name = 'Agent Action Surface';
@@ -1,4 +1,6 @@
1
1
  import { isApiError } from '@cclabsnz/sf-core';
2
+ // Shared, so MALFORMED_QUERY (a bug in the query) is never read as an absent feature.
3
+ import { isMissingObjectError } from '../support/missingObject.js';
2
4
  // BotDefinition.Type values that denote an Agentforce / GenAI agent rather than a
3
5
  // classic Einstein Bot. Matched case-insensitively; anything else (typically 'Bot')
4
6
  // is treated as a classic bot. LIKE-style matching so exact enum spellings across
@@ -7,21 +9,6 @@ const AGENT_TYPE_HINTS = ['agent', 'einsteinservice', 'einsteincopilot', 'genai'
7
9
  // Permission set license labels that grant Agentforce / Einstein Agent capability.
8
10
  // Substring match so exact SKU names are not load-bearing.
9
11
  const AGENT_LICENSE_HINTS = ['agentforce', 'einstein agent'];
10
- // A Tooling error whose cause is "the object does not exist" (feature absent) rather
11
- // than a transient/permission failure. Mirrors classifyEventLogAccessError's not-enabled arm.
12
- function isMissingObjectError(err) {
13
- if (isApiError(err)) {
14
- if (/INVALID_TYPE|NOT_FOUND|MALFORMED_QUERY/i.test(err.errorCode))
15
- return true;
16
- if (err.statusCode === 404)
17
- return true;
18
- }
19
- const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
20
- return (msg.includes('not supported') ||
21
- msg.includes('invalid type') ||
22
- msg.includes('is not supported') ||
23
- msg.includes('sobject type'));
24
- }
25
12
  export class AgentInventoryCheck {
26
13
  id = 'agent-inventory';
27
14
  name = 'Agentforce Agent Inventory';
@@ -96,6 +96,8 @@ export class ApexLoggingCheck {
96
96
  findings.push({
97
97
  id: 'apex-logging-sensitive-data',
98
98
  category: this.category,
99
+ // A disclosure, not a repudiation gap: its fix removes logging (RULE-103).
100
+ threats: { stride: ['I'] },
99
101
  riskLevel: 'HIGH',
100
102
  title: `${sensitiveLogClasses.length} Apex class(es) may log sensitive data: SBS-CODE-004`,
101
103
  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.',
@@ -75,6 +75,8 @@ export class GuestApiAccessCheck {
75
75
  findings.push({
76
76
  id: 'guest-api-hard-delete',
77
77
  category: this.category,
78
+ // Irreversible deletion takes the data away; it is not a disclosure.
79
+ threats: { stride: ['D', 'T'] },
78
80
  riskLevel: 'CRITICAL',
79
81
  title: `${hardDeleteGuests.size} guest user(s) have Bulk API Hard Delete`,
80
82
  detail: '"Bulk API Hard Delete" lets the holder permanently delete records, skipping the recycle bin. On a guest user this hands an unauthenticated visitor an irreversible destructive capability.',
@@ -97,6 +97,8 @@ export class GuestUserAccessCheck {
97
97
  findings.push({
98
98
  id: 'guest-user-write-access',
99
99
  category: this.category,
100
+ // Writing is tampering, not the disclosure the rest of this check reports.
101
+ threats: { stride: ['T', 'I'] },
100
102
  riskLevel: 'CRITICAL',
101
103
  title: 'Guest user profile(s) have write access to Salesforce objects',
102
104
  affectedItems: writeViolations.map((v) => {
@@ -22,8 +22,8 @@ export class UsersAndAdminsCheck {
22
22
  OR PermissionSet.PermissionsAuthorApex = true)
23
23
  AND Assignee.IsActive = true
24
24
  AND AssigneeId NOT IN (SELECT UserId FROM UserLogin WHERE IsFrozen = true)`;
25
- // queryAll fetches every batch, but the client caps how many rows it will fetch and returns the
26
- // rest silently. The COUNT() says how many rows there are, so a capped read is detected (INT-004).
25
+ // queryAll reads every page (sf-core 0.12+), but assignments can change between the read and the
26
+ // COUNT(). The COUNT() says how many rows there are, so a short read is detected (INT-004).
27
27
  const broadPerms = await ctx.soql.queryAll(`SELECT Assignee.Id, Assignee.Username, Assignee.Name, Assignee.Profile.Name,
28
28
  PermissionSet.Name, PermissionSet.IsOwnedByProfile,
29
29
  PermissionSet.PermissionsModifyAllData, PermissionSet.PermissionsViewAllData,
@@ -97,11 +97,11 @@ export class UsersAndAdminsCheck {
97
97
  const unknownDetail = (perm) => partial
98
98
  ? `No ${perm} holder was found, but ${readNote}, so holders may be in the rows not read.`
99
99
  : `No active user was found holding ${perm}, yet every org with an active System Administrator has at least one. The audit user most likely cannot see PermissionSetAssignment rows, so this is unknown, not clean.`;
100
- const RAISE_LIMIT = 'Raise the query row limit (sf config set org-max-query-limit, or SF_ORG_MAX_QUERY_LIMIT) above the assignment count and re-run.';
100
+ const RE_RUN = 'Re-run the audit: permission set assignments changed while it was reading them, or the count of them could not be read.';
101
101
  const SEE_ROWS = 'Re-run as a user with View Setup and Configuration (or View All Users) so permission set assignments are visible.';
102
- // A capped read needs a higher limit; a failed COUNT says nothing about the limit, so the
102
+ // A short read needs a fresh read; a failed COUNT may also mean the rows are not visible, so the
103
103
  // visibility advice applies too.
104
- const unknownRemediation = !partial ? SEE_ROWS : psaTotal === undefined ? `${SEE_ROWS} ${RAISE_LIMIT}` : RAISE_LIMIT;
104
+ const unknownRemediation = !partial ? SEE_ROWS : psaTotal === undefined ? `${SEE_ROWS} ${RE_RUN}` : RE_RUN;
105
105
  // On a partial read, a count can also fall under its reporting threshold and not appear at all.
106
106
  // This finding is the machine-readable signal for every count from the read (INT-004).
107
107
  if (partial) {
@@ -172,7 +172,7 @@ export const CHECKS = [
172
172
  new CustomLabelsCredentialCheck(), // credentials stored in globally-readable labels
173
173
  new ReportFolderAccessCheck(), // public report folders — mass data exfiltration risk
174
174
  new EscalationPermsCheck(), // priv-esc permission cluster (chain ingredient)
175
- new CorsAllowlistCheck(), // wildcard/broad CORS origins (chain ingredient)
175
+ new CorsAllowlistCheck(), // wildcard/broad CORS origins
176
176
  new EmailSecurityCheck(), // inbound email services + send-as spoofing
177
177
  new OutboundMessagesCheck(), // outbound message session-id leak + cleartext endpoints
178
178
  new PublicContentExposureCheck(), // externally available Documents + public static resources
@@ -14,7 +14,8 @@ export function isMissingObjectError(err) {
14
14
  // would report an unchecked area as clean.
15
15
  if (/INVALID_TYPE|NOT_FOUND/i.test(err.errorCode))
16
16
  return true;
17
- if (err.statusCode === 404)
17
+ // sf-core 0.12: a Connection-path 404 with no Salesforce code carries no statusCode.
18
+ if (err.statusCode === 404 || err.errorCode === 'ERROR_HTTP_404')
18
19
  return true;
19
20
  }
20
21
  const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
@@ -1,7 +1,7 @@
1
1
  import { isApiError } from '@cclabsnz/sf-core';
2
2
  const cache = new WeakMap();
3
3
  function isNotFound(err) {
4
- if (isApiError(err) && (err.statusCode === 404 || /NOT_FOUND|INVALID_TYPE/i.test(err.errorCode)))
4
+ if (isApiError(err) && (err.statusCode === 404 || /NOT_FOUND|INVALID_TYPE|^ERROR_HTTP_404$/i.test(err.errorCode)))
5
5
  return true;
6
6
  const msg = err instanceof Error ? err.message : String(err);
7
7
  return /NOT_FOUND|requested resource does not exist|is not supported/i.test(msg);
@@ -1,6 +1,7 @@
1
1
  import * as path from 'node:path';
2
2
  import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
3
3
  import { buildAuditContext, resolveOrgInfo } from '../../../lib/wire.js';
4
+ import { apiErrorText } from '../../../lib/apiErrorText.js';
4
5
  import { collectBundle, defaultIncidentRoot } from '../../../incident/collect/collectBundle.js';
5
6
  export default class AuditIncidentCollectCommand extends SfCommand {
6
7
  static summary = 'Collect a guest-filtered evidence bundle for a Guest User Anomaly investigation';
@@ -35,7 +36,7 @@ export default class AuditIncidentCollectCommand extends SfCommand {
35
36
  ({ manifest } = await collectBundle({ soql: ctx.soql, rest: ctx.rest, orgId: orgInfo.id, orgName: orgInfo.name }, { sinceDays: flags.since, window: flags.window, event: flags.event, ipRangeFiles: flags['ip-ranges'] ?? [], outputDir: dir, warn: (m) => this.warn(m) }));
36
37
  }
37
38
  catch (e) {
38
- const message = e instanceof Error ? e.message : String(e);
39
+ const message = apiErrorText(e);
39
40
  this.error(`${message} (partial bundle kept at ${dir}; re-run with --output "${dir}" to resume)`, { exit: 1 });
40
41
  }
41
42
  const collected = manifest.logs.filter((l) => l.status === 'collected').length;
@@ -1,5 +1,6 @@
1
1
  import type { RiskLevel } from '@cclabsnz/sf-core';
2
2
  import type { Capability } from '../chains/Capability.js';
3
+ import type { FindingThreats } from '../threats/types.js';
3
4
  export interface AffectedItem {
4
5
  label: string;
5
6
  url?: string;
@@ -30,6 +31,12 @@ export interface Finding {
30
31
  * Populated by CheckEngine from ComplianceMapping after each check runs.
31
32
  */
32
33
  complianceTags?: string[];
34
+ /**
35
+ * STRIDE and LINDDUN categories. Populated by CheckEngine from the threat maps; a check may set
36
+ * either list inline to override its check-level entry for this finding. Carries no weight in
37
+ * scoring, grading or --fail-on (RULE-105).
38
+ */
39
+ threats?: FindingThreats;
33
40
  /**
34
41
  * True when the check could not gather evidence due to insufficient permissions.
35
42
  * Scored as INFO (no impact on health score) but displayed distinctly.
@@ -1,6 +1,8 @@
1
+ // src/incident/collect/orgErrors.ts
2
+ import { apiErrorText } from '../../lib/apiErrorText.js';
1
3
  /** Only 'unavailable' and 'no-permission' may degrade collection; everything else must abort it. */
2
4
  export function classifyOrgError(e) {
3
- const m = e instanceof Error ? e.message : String(e);
5
+ const m = apiErrorText(e);
4
6
  if (/INVALID_TYPE|is not supported|not supported/i.test(m))
5
7
  return 'unavailable';
6
8
  if (/INSUFFICIENT_ACCESS|HTTP 403/i.test(m))
@@ -2,6 +2,7 @@
2
2
  import { rmSync, renameSync, statfsSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { secureFs } from '@cclabsnz/sf-core';
5
+ import { apiErrorText } from '../../lib/apiErrorText.js';
5
6
  import { degrades } from './orgErrors.js';
6
7
  import { filterLogFile, MissingColumnsError } from '../csv.js';
7
8
  import { logPath } from '../bundleIo.js';
@@ -92,7 +93,7 @@ onLogDone = () => { }) {
92
93
  settled = { type, day, status: 'collected', ...r, file: rel };
93
94
  }
94
95
  catch (e) {
95
- if (e?.code === 'ENOSPC' || /HTTP 401/.test(String(e))) {
96
+ if (e?.code === 'ENOSPC' || /HTTP 401/.test(apiErrorText(e))) {
96
97
  rmSync(part, { force: true });
97
98
  rmSync(raw, { force: true });
98
99
  rmSync(tmp, { recursive: true, force: true });
@@ -101,7 +102,7 @@ onLogDone = () => { }) {
101
102
  warn(`Could not collect ${type} for ${day}: ${e instanceof MissingColumnsError ? e.message : String(e)}`);
102
103
  settled = e instanceof MissingColumnsError
103
104
  ? blank(type, day, 'failed', e.message)
104
- : blank(type, day, /INSUFFICIENT_ACCESS|HTTP 403/i.test(String(e)) ? 'no-permission' : 'failed', String(e));
105
+ : blank(type, day, /INSUFFICIENT_ACCESS|HTTP 403/i.test(apiErrorText(e)) ? 'no-permission' : 'failed', apiErrorText(e));
105
106
  rmSync(part, { force: true });
106
107
  }
107
108
  finally {
@@ -0,0 +1,8 @@
1
+ /**
2
+ * An error's Salesforce code, HTTP status and message as one string, for classifiers that match
3
+ * on text. sf-core 0.12 keeps the code out of the message (`INVALID_SESSION_ID` arrives as
4
+ * "Session expired or invalid"), and an error body with no Salesforce code is
5
+ * `ERROR_HTTP_<status>` with no status on the Connection path; both read here as "HTTP <status>".
6
+ */
7
+ export declare function apiErrorText(e: unknown): string;
8
+ //# sourceMappingURL=apiErrorText.d.ts.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * An error's Salesforce code, HTTP status and message as one string, for classifiers that match
3
+ * on text. sf-core 0.12 keeps the code out of the message (`INVALID_SESSION_ID` arrives as
4
+ * "Session expired or invalid"), and an error body with no Salesforce code is
5
+ * `ERROR_HTTP_<status>` with no status on the Connection path; both read here as "HTTP <status>".
6
+ */
7
+ export function apiErrorText(e) {
8
+ if (!(e instanceof Error))
9
+ return String(e);
10
+ const { errorCode, statusCode } = e;
11
+ const code = typeof errorCode === 'string' ? errorCode : '';
12
+ const status = typeof statusCode === 'number' ? statusCode : /^ERROR_HTTP_(\d{3})$/.exec(code)?.[1];
13
+ return [code, status === undefined ? '' : `HTTP ${status}`, e.message].filter(Boolean).join(' ');
14
+ }
15
+ //# sourceMappingURL=apiErrorText.js.map
@@ -2,6 +2,10 @@ import type { AttackChain } from '../chains/AttackChain.js';
2
2
  export interface DagRenderOptions {
3
3
  theme?: 'dark' | 'light';
4
4
  }
5
- export declare function identifyCutPointIndex(chain: AttackChain): number;
5
+ /**
6
+ * Indices of the steps in the chain's break point: removing every one of them stops a named chain.
7
+ * Empty for potential chains, which have no proven break point (MN-060).
8
+ */
9
+ export declare function breakPointIndices(chain: AttackChain): number[];
6
10
  export declare function renderAttackChainDagSvg(chain: AttackChain, opts?: DagRenderOptions): string;
7
11
  //# sourceMappingURL=AttackChainDagRenderer.d.ts.map
@@ -1,7 +1,7 @@
1
1
  // src/renderers/AttackChainDagRenderer.ts
2
2
  //
3
- // Draws an attack chain as an inline SVG strip of step cards joined by arrows, with the step whose
4
- // fix breaks the chain marked as the cut-point. The executive report runs under a strict CSP (no
3
+ // Draws an attack chain as an inline SVG strip of step cards joined by arrows, with the steps that
4
+ // make up a named chain's proven break point marked (RULE-111). Potential chains have none. The executive report runs under a strict CSP (no
5
5
  // script, inline style only), so the output is self-contained: no <script>, no event handlers, no
6
6
  // <foreignObject>, no external references. Every chain/step string is escaped before it is placed
7
7
  // in text or an attribute; colours come only from fixed lookup tables.
@@ -14,28 +14,12 @@ const SEV_COLORS = {
14
14
  };
15
15
  /** Cards per row before the strip wraps, so long chains stay readable when scaled to page width. */
16
16
  const MAX_PER_ROW = 4;
17
- export function identifyCutPointIndex(chain) {
18
- if (!chain.steps || chain.steps.length === 0)
19
- return 0;
20
- const rem = (chain.remediation || '').toLowerCase();
21
- for (let i = 0; i < chain.steps.length; i++) {
22
- const s = chain.steps[i];
23
- if (s.findingId && rem.includes(s.findingId.toLowerCase()))
24
- return i;
25
- if (s.title && rem.includes(s.title.toLowerCase()))
26
- return i;
27
- }
28
- const sevRank = { CRITICAL: 4, HIGH: 3, MEDIUM: 2, LOW: 1, INFO: 0 };
29
- let bestIdx = 0;
30
- let bestRank = -1;
31
- for (let i = 0; i < chain.steps.length; i++) {
32
- const rank = sevRank[chain.steps[i].severity ?? 'LOW'] ?? 1;
33
- if (rank > bestRank) {
34
- bestRank = rank;
35
- bestIdx = i;
36
- }
37
- }
38
- return bestIdx;
17
+ /**
18
+ * Indices of the steps in the chain's break point: removing every one of them stops a named chain.
19
+ * Empty for potential chains, which have no proven break point (MN-060).
20
+ */
21
+ export function breakPointIndices(chain) {
22
+ return (chain.steps ?? []).flatMap((s, i) => (s.breaksChain ? [i] : []));
39
23
  }
40
24
  /** Truncate by code point (never splitting a surrogate pair); escaping happens after. */
41
25
  function truncate(str, maxLen) {
@@ -47,7 +31,7 @@ export function renderAttackChainDagSvg(chain, opts = {}) {
47
31
  const steps = chain.steps ?? [];
48
32
  if (steps.length === 0)
49
33
  return '';
50
- const cutPointIdx = identifyCutPointIndex(chain);
34
+ const cutPoints = new Set(breakPointIndices(chain));
51
35
  const cardW = 220;
52
36
  const cardH = 96;
53
37
  const gap = 52;
@@ -75,23 +59,24 @@ export function renderAttackChainDagSvg(chain, opts = {}) {
75
59
  const nodesSvg = steps
76
60
  .map((step, idx) => {
77
61
  const { x, y } = posOf(idx);
78
- const isCut = idx === cutPointIdx;
62
+ const isCut = cutPoints.has(idx);
79
63
  const sevRaw = String(step.severity ?? 'LOW');
80
64
  const sevCol = sevColors[sevRaw] ?? sevColors.INFO;
81
65
  const sev = esc(truncate(sevRaw, 10));
82
66
  const title = esc(truncate(String(step.title || step.findingId || ''), 26));
83
- const cap = esc(truncate(String(step.capability ?? ''), 24));
67
+ // An inferred capability is a fallback, not something the finding grants (RULE-110).
68
+ const cap = step.capabilityInferred ? '' : esc(truncate(String(step.capability ?? ''), 24));
84
69
  const stroke = isCut ? cutAccent : cardBorder;
85
70
  const strokeWidth = isCut ? '2.5' : '1';
86
71
  const dash = isCut ? ' stroke-dasharray="4 2"' : '';
87
72
  const cutBadge = isCut
88
73
  ? `<g transform="translate(${x + cardW - 84}, ${y - 10})">
89
74
  <rect width="80" height="18" rx="4" fill="${cutAccent}" />
90
- <text x="40" y="12" fill="#ffffff" font-size="9" font-weight="700" text-anchor="middle" font-family="system-ui, sans-serif">✂ CUT-POINT</text>
75
+ <text x="40" y="12" fill="#ffffff" font-size="9" font-weight="700" text-anchor="middle" font-family="system-ui, sans-serif">✂ BREAK POINT</text>
91
76
  </g>`
92
77
  : '';
93
78
  const cutNote = isCut
94
- ? `<text x="${x + 10}" y="${y + cardH - 10}" fill="${cutAccent}" font-size="9" font-weight="600" font-family="system-ui, sans-serif">★ Remediating breaks chain</text>`
79
+ ? `<text x="${x + 10}" y="${y + cardH - 10}" fill="${cutAccent}" font-size="9" font-weight="600" font-family="system-ui, sans-serif">${cutPoints.size > 1 ? 'Fix every ✂ step' : 'Fixing this breaks it'}</text>`
95
80
  : '';
96
81
  return `<g class="dag-node${isCut ? ' dag-cut-point' : ''}">
97
82
  <rect x="${x}" y="${y}" width="${cardW}" height="${cardH}" rx="8" fill="${cardBg}" stroke="${stroke}" stroke-width="${strokeWidth}"${dash} />
@@ -99,8 +84,8 @@ export function renderAttackChainDagSvg(chain, opts = {}) {
99
84
  <circle cx="${x + 18}" cy="${y + 20}" r="4" fill="${sevCol}" />
100
85
  <text x="${x + 28}" y="${y + 24}" fill="${sevCol}" font-size="10" font-weight="700" font-family="system-ui, sans-serif">STEP ${idx + 1} · ${sev}</text>
101
86
  <text x="${x + 10}" y="${y + 44}" fill="${textColor}" font-size="12" font-weight="600" font-family="system-ui, sans-serif">${title}</text>
102
- <rect x="${x + 10}" y="${y + 54}" width="${cardW - 20}" height="18" rx="4" fill="${pillBg}" />
103
- <text x="${x + 16}" y="${y + 67}" fill="${mutedColor}" font-size="10" font-family="ui-monospace, monospace">grants: ${cap}</text>
87
+ ${cap ? `<rect x="${x + 10}" y="${y + 54}" width="${cardW - 20}" height="18" rx="4" fill="${pillBg}" />
88
+ <text x="${x + 16}" y="${y + 67}" fill="${mutedColor}" font-size="10" font-family="ui-monospace, monospace">grants: ${cap}</text>` : ''}
104
89
  ${cutNote}
105
90
  </g>`;
106
91
  })
@@ -183,9 +183,12 @@ ${impact}${chained}<p><strong>Fix:</strong> ${esc(f.remediation)}</p></div>`;
183
183
  const dagSvg = renderAttackChainDagSvg(c, { theme: 'light' });
184
184
  return `<div class="card scenario" style="--c:${SEV_COLOR[c.severity]}">
185
185
  <div class="row"><h3>${esc(c.title)}</h3>${this.chip(c.severity, c.severity)}</div>
186
+ ${c.abuseCase ? `<p><strong>Abuse case:</strong> ${esc(c.abuseCase.actor)} wants to ${esc(c.abuseCase.goal)}.</p>` : ''}
186
187
  <p>${esc(c.narrative)}</p>
187
188
  ${dagSvg}
188
- <p><strong>Breaks the chain:</strong> ${esc(c.remediation)}</p></div>`;
189
+ ${c.abuseCase
190
+ ? `<p><strong>Breaks the chain:</strong> ${esc(c.abuseCase.breakPoint)}</p><p class="muted"><strong>Full remediation:</strong> ${esc(c.remediation)}</p>`
191
+ : `<p><strong>Recommended fixes:</strong> ${esc(c.remediation)}</p>`}</div>`;
189
192
  }).join('');
190
193
  return `${this.sectionHead(numStr, 'Attack Scenarios')}<p class="muted">How findings combine into real attack paths.</p>${items}`;
191
194
  }
@@ -1,6 +1,7 @@
1
1
  import { esc, firaFontFaceCss, INTERACTIVE_CSP_META } from '@cclabsnz/sf-core';
2
2
  import { renderAttackChainDagSvg } from './AttackChainDagRenderer.js';
3
3
  import { coverageSummary, coverageAdvice } from '../findings/coverage.js';
4
+ import { techniqueLabel } from '../threats/attack.js';
4
5
  import { unknownMetrics } from '../findings/unknownMetrics.js';
5
6
  const RISK_COLORS = {
6
7
  CRITICAL: '#dc2626',
@@ -193,14 +194,23 @@ export class HtmlRenderer {
193
194
  const conf = c.confidence === 'named' ? '' : ' (potential)';
194
195
  const dagSvg = renderAttackChainDagSvg(c, { theme: 'dark' });
195
196
  const steps = c.steps
196
- .map((s) => `<li><strong>${esc(s.title ?? s.findingId)}</strong> (${esc(s.severity ?? '—')}): grants <code>${esc(s.capability)}</code></li>`)
197
+ .map((s) => {
198
+ const technique = s.techniques?.length ? ` → ${esc(s.techniques.map(techniqueLabel).join(' · '))}` : '';
199
+ const grants = s.capabilityInferred ? '' : `: grants <code>${esc(s.capability)}</code>${technique}`;
200
+ const cut = s.breaksChain ? ' <strong>✂ break point</strong>' : '';
201
+ return `<li><strong>${esc(s.title ?? s.findingId)}</strong> (${esc(s.severity ?? '—')})${grants}${cut}</li>`;
202
+ })
197
203
  .join('');
198
204
  return `<div class="attack-chain severity-${c.severity.toLowerCase()}">
199
205
  <h3>[${esc(c.severity)}] ${esc(c.title)}${conf}</h3>
206
+ ${c.abuseCase ? `<p><strong>Abuse case:</strong> ${esc(c.abuseCase.actor)} wants to ${esc(c.abuseCase.goal)}.</p>` : ''}
200
207
  <p>${esc(c.narrative)}</p>
201
208
  ${dagSvg}
202
209
  <ol>${steps}</ol>
203
- <p class="remediation"><strong>Remediation:</strong> ${esc(c.remediation)}</p>
210
+ ${c.abuseCase
211
+ ? `<p class="remediation"><strong>Breaks the chain:</strong> ${esc(c.abuseCase.breakPoint)}</p>
212
+ <p class="remediation"><strong>Remediation:</strong> ${esc(c.remediation)}</p>`
213
+ : `<p class="remediation"><strong>Recommended fixes:</strong> ${esc(c.remediation)}</p>`}
204
214
  </div>`;
205
215
  })
206
216
  .join('\n');
@@ -1,7 +1,29 @@
1
1
  import { coverageSummary, coverageAdvice } from '../findings/coverage.js';
2
+ import { techniqueLabel } from '../threats/attack.js';
3
+ import { buildThreatView, threatRowStatusText, PRIVACY_COST_OF_LOGGING } from '../threats/view.js';
2
4
  function escapeMdCell(s) {
3
5
  return s.replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/\n/g, ' ');
4
6
  }
7
+ function threatTags(f) {
8
+ const parts = [];
9
+ if (f.threats?.stride?.length)
10
+ parts.push(`STRIDE ${f.threats.stride.join(' · ')}`);
11
+ if (f.threats?.linddun?.length)
12
+ parts.push(`LINDDUN ${f.threats.linddun.join(' · ')}`);
13
+ if (f.threats?.attack?.length)
14
+ parts.push(`ATT&CK ${f.threats.attack.join(' · ')}`);
15
+ if (f.threats?.detects?.length)
16
+ parts.push(`leaves unobserved: ${f.threats.detects.map(techniqueLabel).join(' · ')}`);
17
+ return parts.join(' | ');
18
+ }
19
+ function threatTable(lines, rows) {
20
+ lines.push('| Category | Coverage | Findings |');
21
+ lines.push('| --- | --- | --- |');
22
+ for (const r of rows) {
23
+ const titles = r.findings.map((f) => escapeMdCell(f.title)).join('; ') || '—';
24
+ lines.push(`| ${r.category}: ${r.name} | ${threatRowStatusText(r)} | ${titles} |`);
25
+ }
26
+ }
5
27
  export class MarkdownRenderer {
6
28
  format = 'md';
7
29
  fileExtension = '.md';
@@ -31,15 +53,29 @@ export class MarkdownRenderer {
31
53
  const conf = c.confidence === 'named' ? '' : ' _(potential)_';
32
54
  lines.push(`### [${c.severity}] ${c.title}${conf}`);
33
55
  lines.push('');
56
+ if (c.abuseCase) {
57
+ lines.push(`**Abuse case:** ${c.abuseCase.actor} wants to ${c.abuseCase.goal}.`);
58
+ lines.push('');
59
+ }
34
60
  lines.push(c.narrative);
35
61
  lines.push('');
36
62
  lines.push('**Steps:**');
37
63
  lines.push('');
38
64
  c.steps.forEach((s, i) => {
39
- lines.push(`${i + 1}. **${s.title ?? s.findingId}** (${s.severity ?? '—'}): grants \`${s.capability}\``);
65
+ const technique = s.techniques?.length ? ` → ${s.techniques.map(techniqueLabel).join(' · ')}` : '';
66
+ const grants = s.capabilityInferred ? '' : `: grants \`${s.capability}\`${technique}`;
67
+ const cut = s.breaksChain ? ' ✂ _break point_' : '';
68
+ lines.push(`${i + 1}. **${s.title ?? s.findingId}** (${s.severity ?? '—'})${grants}${cut}`);
40
69
  });
41
70
  lines.push('');
42
- lines.push(`**Remediation:** ${c.remediation}`);
71
+ if (c.abuseCase) {
72
+ lines.push(`**Breaks the chain:** ${c.abuseCase.breakPoint}`);
73
+ lines.push('');
74
+ lines.push(`**Remediation:** ${c.remediation}`);
75
+ }
76
+ else {
77
+ lines.push(`**Recommended fixes:** ${c.remediation}`);
78
+ }
43
79
  lines.push('');
44
80
  lines.push('---');
45
81
  lines.push('');
@@ -63,6 +99,11 @@ export class MarkdownRenderer {
63
99
  lines.push('');
64
100
  lines.push(`**Compliance:** ${f.complianceTags.join(' · ')}`);
65
101
  }
102
+ const threats = threatTags(f);
103
+ if (threats) {
104
+ lines.push('');
105
+ lines.push(`**Threats:** ${threats}`);
106
+ }
66
107
  if (f.affectedItems?.length) {
67
108
  const hasUrls = f.affectedItems.some((i) => i.url);
68
109
  const hasNotes = f.affectedItems.some((i) => i.note);
@@ -86,6 +127,30 @@ export class MarkdownRenderer {
86
127
  lines.push('');
87
128
  }
88
129
  }
130
+ const view = buildThreatView(result.findings);
131
+ lines.push('');
132
+ lines.push('## Threat View');
133
+ lines.push('');
134
+ lines.push('_Findings grouped by threat category. Coverage shows what this run looked at, not that a threat is absent._');
135
+ lines.push('');
136
+ lines.push('### STRIDE');
137
+ lines.push('');
138
+ threatTable(lines, view.stride);
139
+ if (view.linddun) {
140
+ lines.push('');
141
+ lines.push('### LINDDUN (privacy)');
142
+ lines.push('');
143
+ threatTable(lines, view.linddun);
144
+ }
145
+ if (view.dualReadings.length > 0) {
146
+ lines.push('');
147
+ lines.push('### Logging, read both ways');
148
+ lines.push('');
149
+ lines.push(`Each of these is a repudiation gap (STRIDE R). ${PRIVACY_COST_OF_LOGGING}`);
150
+ lines.push('');
151
+ for (const f of view.dualReadings)
152
+ lines.push(`- ${f.title}`);
153
+ }
89
154
  lines.push('');
90
155
  lines.push('---');
91
156
  lines.push('');
@@ -101,7 +101,11 @@ export class SarifRenderer {
101
101
  }
102
102
  const acc = this.ruleFor(rules, ruleId, f);
103
103
  acc.worst = acc.worst ? maxRisk(acc.worst, f.riskLevel) : f.riskLevel;
104
- for (const tag of f.complianceTags ?? []) {
104
+ const threatTags = [
105
+ ...(f.threats?.stride ?? []).map((c) => `stride:${c}`),
106
+ ...(f.threats?.linddun ?? []).map((c) => `linddun:${c}`),
107
+ ];
108
+ for (const tag of [...(f.complianceTags ?? []), ...threatTags]) {
105
109
  if (!acc.rule.properties.tags.includes(tag))
106
110
  acc.rule.properties.tags.push(tag);
107
111
  }
@@ -221,10 +225,19 @@ export class SarifRenderer {
221
225
  rules.set(ruleId, acc);
222
226
  }
223
227
  acc.worst = acc.worst ? maxRisk(acc.worst, chain.severity) : chain.severity;
228
+ for (const id of chain.steps.flatMap((s) => s.techniques ?? [])) {
229
+ const tag = `attack:${id}`;
230
+ if (!acc.rule.properties.tags.includes(tag))
231
+ acc.rule.properties.tags.push(tag);
232
+ }
224
233
  const stepLocation = (step, idx) => ({
225
234
  message: { text: `Step ${idx + 1}: ${step.title ?? step.findingId} (${step.findingId})` },
226
235
  logicalLocations: logicalLocations([step.findingId]),
227
- properties: { capability: step.capability },
236
+ properties: {
237
+ ...(step.capabilityInferred ? {} : { capability: step.capability }),
238
+ ...(step.breaksChain ? { breaksChain: true } : {}),
239
+ ...(step.techniques?.length ? { attackTechniques: step.techniques } : {}),
240
+ },
228
241
  });
229
242
  return {
230
243
  ruleId,
@@ -243,6 +256,7 @@ export class SarifRenderer {
243
256
  confidence: chain.confidence,
244
257
  attackChainId: chain.id,
245
258
  remediation: chain.remediation,
259
+ ...(chain.abuseCase ? { abuseCase: chain.abuseCase } : {}),
246
260
  },
247
261
  };
248
262
  }