@openai/codex-security 0.10.0 → 0.10.1

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 (130) hide show
  1. package/_bundled_plugin/.mcp.json +1 -0
  2. package/_bundled_plugin/mcp/helpers.mjs.br +0 -0
  3. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  4. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  5. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  6. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  7. package/_bundled_plugin/mcp/server.mjs.br +0 -0
  8. package/_bundled_plugin/references/access-advisory.md +1 -1
  9. package/_bundled_plugin/references/threat-model.md +1 -0
  10. package/_bundled_plugin/scripts/deep_scan_workbench.py +1 -0
  11. package/_bundled_plugin/scripts/finalize_scan_contract.py +18 -6
  12. package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +2 -0
  13. package/_bundled_plugin/scripts/workbench_db.py +16 -54
  14. package/_bundled_plugin/scripts/workbench_scan_history.py +23 -28
  15. package/_bundled_plugin/scripts/workbench_scan_start.py +65 -2
  16. package/_bundled_plugin/scripts/workbench_source_scopes.py +8 -0
  17. package/_bundled_plugin/scripts/workbench_target.py +17 -3
  18. package/_bundled_plugin/shared/workbench-history-repairs.json +5 -1
  19. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -2
  20. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +2 -2
  21. package/_bundled_plugin/skills/publish-findings/SKILL.md +3 -1
  22. package/dist/api.d.ts +1 -0
  23. package/dist/api.d.ts.map +1 -1
  24. package/dist/api.js +23 -4
  25. package/dist/api.js.map +1 -1
  26. package/dist/classify-severity-diagnostics.d.ts +10 -0
  27. package/dist/classify-severity-diagnostics.d.ts.map +1 -0
  28. package/dist/classify-severity-diagnostics.js +57 -0
  29. package/dist/classify-severity-diagnostics.js.map +1 -0
  30. package/dist/classify-severity-records.d.ts +4 -0
  31. package/dist/classify-severity-records.d.ts.map +1 -1
  32. package/dist/classify-severity-records.js +35 -8
  33. package/dist/classify-severity-records.js.map +1 -1
  34. package/dist/cli.d.ts +3 -0
  35. package/dist/cli.d.ts.map +1 -1
  36. package/dist/cli.js +99 -11
  37. package/dist/cli.js.map +1 -1
  38. package/dist/component-plan.d.ts.map +1 -1
  39. package/dist/component-plan.js +3 -3
  40. package/dist/component-plan.js.map +1 -1
  41. package/dist/continuum-aws.d.ts +6 -0
  42. package/dist/continuum-aws.d.ts.map +1 -0
  43. package/dist/continuum-aws.js +202 -0
  44. package/dist/continuum-aws.js.map +1 -0
  45. package/dist/continuum-collector.d.ts +44 -0
  46. package/dist/continuum-collector.d.ts.map +1 -0
  47. package/dist/continuum-collector.js +266 -0
  48. package/dist/continuum-collector.js.map +1 -0
  49. package/dist/continuum-findings.d.ts +31 -2
  50. package/dist/continuum-findings.d.ts.map +1 -1
  51. package/dist/continuum-findings.js +440 -64
  52. package/dist/continuum-findings.js.map +1 -1
  53. package/dist/contract.d.ts +1 -0
  54. package/dist/contract.d.ts.map +1 -1
  55. package/dist/contract.js +3 -0
  56. package/dist/contract.js.map +1 -1
  57. package/dist/crowdstrike-findings.d.ts +7 -0
  58. package/dist/crowdstrike-findings.d.ts.map +1 -0
  59. package/dist/crowdstrike-findings.js +210 -0
  60. package/dist/crowdstrike-findings.js.map +1 -0
  61. package/dist/external-findings-local.d.ts.map +1 -1
  62. package/dist/external-findings-local.js +26 -8
  63. package/dist/external-findings-local.js.map +1 -1
  64. package/dist/external-findings-publish.d.ts.map +1 -1
  65. package/dist/external-findings-publish.js +5 -1
  66. package/dist/external-findings-publish.js.map +1 -1
  67. package/dist/external-findings-read.d.ts +10 -2
  68. package/dist/external-findings-read.d.ts.map +1 -1
  69. package/dist/external-findings-read.js +26 -3
  70. package/dist/external-findings-read.js.map +1 -1
  71. package/dist/external-import-contract.d.ts +3 -0
  72. package/dist/external-import-contract.d.ts.map +1 -1
  73. package/dist/external-import-contract.js +6 -1
  74. package/dist/external-import-contract.js.map +1 -1
  75. package/dist/host-protocol.d.ts +6 -0
  76. package/dist/host-protocol.d.ts.map +1 -1
  77. package/dist/host-protocol.js +11 -1
  78. package/dist/host-protocol.js.map +1 -1
  79. package/dist/host-records-protocol.d.ts +2 -0
  80. package/dist/host-records-protocol.d.ts.map +1 -1
  81. package/dist/host-records-protocol.js +4 -0
  82. package/dist/host-records-protocol.js.map +1 -1
  83. package/dist/index.d.ts +2 -1
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +1 -0
  86. package/dist/index.js.map +1 -1
  87. package/dist/multiscan.d.ts.map +1 -1
  88. package/dist/multiscan.js +4 -2
  89. package/dist/multiscan.js.map +1 -1
  90. package/dist/project-config-schema.d.ts +2 -0
  91. package/dist/project-config-schema.d.ts.map +1 -1
  92. package/dist/project-config-schema.js +1 -0
  93. package/dist/project-config-schema.js.map +1 -1
  94. package/dist/project-config.d.ts +1 -0
  95. package/dist/project-config.d.ts.map +1 -1
  96. package/dist/project-config.js +3 -0
  97. package/dist/project-config.js.map +1 -1
  98. package/dist/runtime.d.ts.map +1 -1
  99. package/dist/runtime.js +4 -0
  100. package/dist/runtime.js.map +1 -1
  101. package/dist/scan-comparison.d.ts +20 -2
  102. package/dist/scan-comparison.d.ts.map +1 -1
  103. package/dist/scan-comparison.js +20 -3
  104. package/dist/scan-comparison.js.map +1 -1
  105. package/dist/scan-settings.d.ts +1 -0
  106. package/dist/scan-settings.d.ts.map +1 -1
  107. package/dist/scan-settings.js +1 -0
  108. package/dist/scan-settings.js.map +1 -1
  109. package/dist/severity-review.d.ts.map +1 -1
  110. package/dist/severity-review.js +1 -0
  111. package/dist/severity-review.js.map +1 -1
  112. package/dist/stored-finding-projection.d.ts.map +1 -1
  113. package/dist/stored-finding-projection.js +30 -5
  114. package/dist/stored-finding-projection.js.map +1 -1
  115. package/dist/targets.d.ts +2 -0
  116. package/dist/targets.d.ts.map +1 -1
  117. package/dist/targets.js +27 -0
  118. package/dist/targets.js.map +1 -1
  119. package/dist/trusted-executable.d.ts +1 -0
  120. package/dist/trusted-executable.d.ts.map +1 -1
  121. package/dist/trusted-executable.js +11 -3
  122. package/dist/trusted-executable.js.map +1 -1
  123. package/dist/value.js +3 -1
  124. package/dist/value.js.map +1 -1
  125. package/docs/classify-severity-records.md +30 -0
  126. package/docs/cli.md +164 -18
  127. package/docs/sdk.md +23 -8
  128. package/package.json +7 -2
  129. package/schemas/project-config.schema.json +5 -0
  130. package/_bundled_plugin/skills/publish-findings/scripts/collect_continuum.py +0 -224
@@ -1 +1 @@
1
- {"version":3,"file":"continuum-findings.js","sourceRoot":"","sources":["../src/continuum-findings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EACL,oBAAoB,EACpB,0BAA0B,EAE1B,gCAAgC,EAChC,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EACL,KAAK,EACL,mBAAmB,EACnB,eAAe,EACf,gBAAgB,EAChB,iBAAiB,EACjB,MAAM,EACN,kBAAkB,EAClB,YAAY,EACZ,OAAO,EACP,IAAI,GACL,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,4BAA4B,EAC5B,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAErC,MAAM,MAAM,GAAG,gCAAgC,CAAC;AAChD,MAAM,UAAU,GACd,uGAAuG,CAAC;AAE1G,SAAS,QAAQ,CAAC,KAAc;IAC9B,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,EAAE,mBAAmB,CAAC,CAAC;IAC/C,MAAM,GAAG,GAAG,YAAY,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,uBAAuB,CAAC,CAAC;IACrE,MAAM,KAAK,GAAG,UAAU,CA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,CAAC,SAAS,EACb,QAAQ,CACT,CACF,CAAC;IACJ,CAAC,EACD,CAAC,KAAK,EAAE,EAAE;QACR,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,QAAQ,CAC7B,CAAC,OAAO,IAAI,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAC7D,CAAC;QACF,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAClB,OAAO,GAAG,CAAC;IACb,CAAC,EACD,MAAM,CACP,CAAC;IACF,IAAI,MAAM,CAAC,IAAI,GAAG,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IAC7E,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,MAAM,qBAAqB,GAAG,iBAAiB,CACpD,0BAA0B,CAC3B,CAAC","sourcesContent":["import { hash } from \"node:crypto\";\nimport { CodexSecurityError } from \"./errors.js\";\nimport type { ExternalFinding, ExternalFindings } from \"./external-findings.js\";\nimport {\n CLOUD_EVIDENCE_BYTES,\n DEFAULT_CLOUD_STRING_BYTES,\n type ExternalImportTarget,\n validateEnrichedExternalEvidence,\n validateExternalEvidenceJson,\n} from \"./external-import-contract.js\";\nimport type { ImportedPackage, Provider } from \"./external-import-models.js\";\nimport { isRecord } from \"./record.js\";\nimport {\n array,\n awsTimestampSeconds,\n concreteVersion,\n normalizeRecords,\n scannerJsonReader,\n record,\n repositoryFilePath,\n requiredText,\n strings,\n text,\n} from \"./scanner-import.js\";\nimport {\n declaredScannerRepositoryUrl,\n repositoryScopeValidator,\n} from \"./scanner-repository-url.js\";\n\nconst format = \"aws-continuum-code-findings/v1\";\nconst findingArn =\n /^(arn:[a-z0-9-]+:continuum:[a-z0-9-]+:\\d{12}:environments\\/([a-z0-9]+))\\/code-findings\\/([a-z0-9]+)$/u;\n\nfunction identity(value: unknown) {\n const row = record(value, \"Continuum finding\");\n const arn = requiredText(row[\"findingArn\"], \"Continuum finding ARN\");\n const match = findingArn.exec(arn);\n if (\n !match ||\n row[\"environmentId\"] !== match[2] ||\n row[\"findingId\"] !== match[3]\n )\n throw new Error(\n \"Expected a Continuum finding ARN matching its environmentId and findingId.\",\n );\n return { arn, scope: match[1]! };\n}\n\nfunction retainedRepository(\n provider: Provider,\n finding: ExternalFinding,\n target: ExternalImportTarget,\n) {\n const {\n source_finding_id: id,\n evidence: { source_data: data },\n } = finding;\n const native = data?.[\"finding\"];\n const marked = data?.[\"format\"] === format;\n const nativeArn =\n isRecord(native) && findingArn.test(text(native[\"findingArn\"]) ?? \"\");\n if (provider !== \"continuum\") {\n if (\n marked ||\n (data?.[\"sourceRepositoryUrl\"] &&\n nativeArn &&\n native[\"findingArn\"] === id)\n )\n throw new CodexSecurityError(\n \"Retained AWS Continuum evidence requires the continuum provider.\",\n );\n return;\n }\n if (!marked && !nativeArn && !findingArn.test(id)) return;\n const { arn, scope } = identity(native);\n if (arn !== id)\n throw new Error(\n \"Continuum source finding ID does not match the retained finding ARN.\",\n );\n return {\n url: declaredScannerRepositoryUrl(\n data?.[\"sourceRepositoryUrl\"],\n \"Continuum\",\n target,\n ),\n scope,\n };\n}\n\nexport const continuumReportRepositories = repositoryScopeValidator(\n { provider: \"continuum\", label: \"AWS Continuum\", scope: \"environment\" },\n retainedRepository,\n);\n\nfunction codeLocations(\n row: Record<string, unknown>,\n vulnerabilities: Record<string, unknown>[],\n) {\n const locations: { path: string; line: number | null }[] = [];\n const seen = new Set<string>();\n let endLine: number | null = null;\n let snippet: string | null = null;\n function add(\n value: unknown,\n start: unknown,\n end: unknown,\n fragment: unknown,\n ) {\n const path = repositoryFilePath(value);\n if (!path) return;\n const line =\n typeof start === \"number\" && Number.isSafeInteger(start) && start > 0\n ? start\n : null;\n const key = JSON.stringify([path, line]);\n if (!seen.has(key)) {\n seen.add(key);\n locations.push({ path, line });\n }\n // The flat location and first nested location can describe the same range.\n if (locations[0]!.path === path && locations[0]!.line === line) {\n if (\n line !== null &&\n typeof end === \"number\" &&\n Number.isSafeInteger(end) &&\n end >= line\n )\n endLine ??= end;\n snippet ??= text(fragment);\n }\n }\n add(\n row[\"filePath\"],\n row[\"lineNumber\"],\n row[\"endLine\"],\n row[\"vulnerableCode\"],\n );\n for (const vulnerability of vulnerabilities) {\n for (const value of array(\n vulnerability[\"locations\"] ?? [],\n \"Continuum vulnerability locations\",\n )) {\n const location = record(value, \"Continuum vulnerability location\");\n add(\n location[\"filePath\"],\n location[\"startLine\"],\n location[\"endLine\"],\n vulnerability[\"code\"],\n );\n }\n }\n return { locations, code: { end_line: endLine, snippet } };\n}\n\nfunction reportRows(input: unknown) {\n if (Array.isArray(input)) return { rows: input, summary: false };\n const document = record(input, \"Continuum report\");\n if (\n Object.hasOwn(document, \"nextToken\") ||\n Object.hasOwn(document, \"NextToken\")\n )\n throw new Error(\n \"Continuum export has a continuation token; supply the complete paginated CLI output.\",\n );\n if (!(\n \"items\" in document ||\n \"findingArn\" in document ||\n \"finding\" in document\n ))\n throw new Error(\n \"Expected a Continuum ListCodeFindings, GetCodeFinding, or finding with patch artifacts.\",\n );\n const summary = \"items\" in document;\n return {\n rows: summary ? array(document[\"items\"], \"Continuum items\") : [document],\n summary,\n };\n}\n\nfunction isPatchCapture(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && !(\"findingArn\" in value) && \"finding\" in value;\n}\n\nfunction readPatch(value: unknown) {\n const artifact = record(value, \"Continuum patch artifact\");\n const patch = requiredText(artifact[\"patch\"], \"Continuum patch content\");\n const sizeBytes = Buffer.byteLength(patch);\n const patchSha256 = hash(\"sha256\", patch);\n if (\n artifact[\"sizeBytes\"] !== sizeBytes ||\n artifact[\"patchSha256\"] !== patchSha256\n )\n throw new Error(\n \"Continuum patch content does not match its sizeBytes or patchSha256.\",\n );\n return {\n artifactId: requiredText(\n artifact[\"artifactId\"],\n \"Continuum patch artifact ID\",\n ),\n patch,\n patchSha256,\n sizeBytes,\n ...(artifact[\"format\"] !== undefined && {\n format: requiredText(artifact[\"format\"], \"Continuum patch format\"),\n }),\n ...(artifact[\"repositoryName\"] !== undefined && {\n repositoryName: requiredText(\n artifact[\"repositoryName\"],\n \"Continuum patch repository\",\n ),\n }),\n };\n}\n\nfunction projectPatches(\n patches: ReturnType<typeof readPatch>[],\n target: ExternalImportTarget,\n project: (artifacts: object[]) => ExternalFinding[\"evidence\"],\n) {\n if (!patches.length || target === \"local\") return project(patches);\n try {\n return project(patches);\n } catch {\n // Complete patches can exceed the Cloud evidence budget.\n }\n\n // Reserve each artifact's lookup information, then include whole patches that fit.\n const marker = { contentOmitted: \"cloud_evidence_limit\" };\n const markerBytes = Buffer.byteLength(JSON.stringify(marker));\n const sizes = patches.map(\n ({ patch }) => Buffer.byteLength(JSON.stringify({ patch })) - markerBytes,\n );\n const projected = patches.map(({ patch, ...descriptor }, index) =>\n sizes[index]! > 0 ? { ...descriptor, ...marker } : patches[index]!,\n );\n const result = project(projected);\n let remaining =\n CLOUD_EVIDENCE_BYTES - validateExternalEvidenceJson(result, target);\n for (const [index, bytes] of sizes.entries()) {\n if (bytes > 0 && bytes <= remaining) {\n projected[index] = patches[index]!;\n remaining -= bytes;\n }\n }\n result.source_data![\"patches\"] = projected;\n return result;\n}\n\nfunction subcategoryCwe(row: Record<string, unknown>) {\n return /^(CWE-[1-9]\\d*):/u.exec(text(row[\"subCategory\"]) ?? \"\")?.[1];\n}\n\nfunction statusUpdatedAt(value: unknown) {\n const seconds = Math.floor(awsTimestampSeconds(value));\n return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : null;\n}\n\nconst versionEcosystems = new Map([\n [\"gradle\", \"maven\"],\n [\"pnpm\", \"npm\"],\n [\"yarn\", \"npm\"],\n]);\n\nfunction affectedPackages(\n items: unknown[],\n target: ExternalImportTarget,\n): ImportedPackage[] {\n const unique = new Map<string, ImportedPackage>();\n const field = (value: unknown) => {\n const result = text(value);\n return result &&\n !result.includes(\"\\0\") &&\n (target === \"local\" ||\n Buffer.byteLength(result) <= DEFAULT_CLOUD_STRING_BYTES)\n ? result\n : null;\n };\n for (const item of items) {\n if (!isRecord(item)) continue;\n const name = field(item[\"name\"]);\n if (!name) continue;\n const ecosystem = field(item[\"packageManager\"]);\n const manager = ecosystem?.toLowerCase();\n const syntax = manager ? (versionEcosystems.get(manager) ?? manager) : null;\n const version = (value: unknown) =>\n concreteVersion(field(value), syntax, false);\n const fixed = version(item[\"fixedInVersion\"]);\n const pkg = {\n name,\n ecosystem,\n installed_version: version(item[\"version\"]),\n fixed_versions: fixed ? [fixed] : [],\n };\n unique.set(JSON.stringify(pkg), pkg);\n // The Cloud contract accepts 100 structured packages. The native row keeps them all.\n if (target === \"cloud\" && unique.size === 100) break;\n }\n return [...unique.values()];\n}\n\nexport function normalizeContinuumFindings(\n input: unknown,\n sourceRepositoryUrl: string,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n const repository = declaredScannerRepositoryUrl(\n sourceRepositoryUrl,\n \"Continuum\",\n target,\n );\n const { rows, summary } = reportRows(input);\n const scopes = new Set<string>();\n const output = normalizeRecords(\n rows,\n (value) => {\n const capture = !summary && isPatchCapture(value) ? value : undefined;\n const row = record(\n capture ? capture[\"finding\"] : value,\n \"Continuum finding\",\n );\n const patches = capture\n ? array(capture[\"patches\"], \"Continuum patches\").map(readPatch)\n : [];\n if (\n patches.length &&\n !(text(row[\"createdIssueId\"]) || text(row[\"duplicateOfIssueId\"]))\n )\n throw new Error(\n \"Continuum patches require a finding linked to an issue.\",\n );\n if (\n row[\"type\"] !== \"CONTINUUM_CODE_VULN\" &&\n row[\"type\"] !== \"CUSTOMER_CODE_VULN\"\n )\n throw new Error(\n \"Expected a Continuum code vulnerability finding type.\",\n );\n const severity = requiredText(\n row[\"severity\"],\n \"Continuum severity\",\n ).toLowerCase();\n const vulnerabilities = array(\n row[\"vulnerabilities\"] ?? [],\n \"Continuum vulnerabilities\",\n ).map((item) => record(item, \"Continuum vulnerability\"));\n const { locations, code } = codeLocations(row, vulnerabilities);\n const source = requiredText(row[\"source\"], \"Continuum source\");\n const status = requiredText(row[\"status\"], \"Continuum status\");\n const validation = record(\n row[\"validation\"] ?? {},\n \"Continuum validation\",\n );\n const all = [row, ...vulnerabilities];\n const advisoryIds = [\n ...new Set(strings(all.map((item) => item[\"cveId\"]))),\n ];\n const packages = all.flatMap((item) =>\n Array.isArray(item[\"affectedPackages\"]) ? item[\"affectedPackages\"] : [],\n );\n const packageFinding = advisoryIds.length > 0 || packages.length > 0;\n const posture =\n row[\"ocsfClass\"] === \"APPLICATION_SECURITY_POSTURE_FINDING\" ||\n row[\"posture\"] != null;\n const codeFinding =\n !summary &&\n !posture &&\n !packageFinding &&\n (code.snippet !== null ||\n locations.some((location) => location.line !== null));\n const evidence = {\n title: requiredText(row[\"title\"], \"Continuum title\"),\n severity:\n severity === \"fatal\"\n ? \"critical\"\n : severity === \"other\"\n ? \"unknown\"\n : severity,\n description: text(row[\"detailedDescription\"]) ?? text(row[\"summary\"]),\n locations,\n advisory_ids: advisoryIds,\n source_scan_id: text(row[\"scanRunId\"]),\n ...(codeFinding && {\n details: {\n kind: \"sast\",\n repository: { url: repository },\n scanner_origin: source,\n scanner_verdict: text(validation[\"verdict\"]),\n source_status: status,\n weakness_ids: strings(row[\"cweIds\"]),\n remediation_instructions: text(row[\"mitigation\"]),\n code,\n },\n }),\n source_data: {\n format,\n sourceRepositoryUrl: repository,\n finding: structuredClone(row),\n },\n };\n const updatedAt = statusUpdatedAt(row[\"statusUpdatedAt\"]);\n const enrichment = {\n packages: affectedPackages(packages, target),\n source_updated_at: updatedAt,\n };\n // Native code findings can identify a CWE only in subCategory.\n const namedCwe =\n evidence.details?.weakness_ids.length === 0\n ? subcategoryCwe(row)\n : undefined;\n const inferred = namedCwe\n ? { details: { ...evidence.details, weakness_ids: [namedCwe] } }\n : undefined;\n // Keep previously admissible evidence if an optional projection exceeds the Cloud budget.\n return projectPatches(patches, target, (artifacts) =>\n validateEnrichedExternalEvidence(\n artifacts.length\n ? {\n ...evidence,\n source_data: { ...evidence.source_data, patches: artifacts },\n }\n : evidence,\n target,\n inferred ? { ...enrichment, ...inferred } : undefined,\n enrichment,\n packages.length && updatedAt !== null\n ? { source_updated_at: updatedAt }\n : undefined,\n inferred,\n ),\n );\n },\n (value) => {\n const { arn, scope } = identity(\n !summary && isPatchCapture(value) ? value[\"finding\"] : value,\n );\n scopes.add(scope);\n return arn;\n },\n target,\n );\n if (scopes.size > 1)\n throw new Error(\"Continuum findings must belong to the same environment.\");\n return output;\n}\n\nexport const readContinuumFindings = scannerJsonReader(\n normalizeContinuumFindings,\n);\n"]}
1
+ {"version":3,"file":"continuum-findings.js","sourceRoot":"","sources":["../src/continuum-findings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,0BAA0B,EAE1B,gBAAgB,EAChB,gCAAgC,EAChC,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EACL,KAAK,EACL,mBAAmB,EACnB,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,MAAM,EACN,kBAAkB,EAClB,YAAY,EACZ,OAAO,EACP,IAAI,GACL,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,4BAA4B,EAC5B,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AAErC,MAAM,MAAM,GAAG,gCAAgC,CAAC;AAChD,MAAM,CAAC,MAAM,oBAAoB,GAAG,8BAA8B,CAAC;AACnE,MAAM,UAAU,GACd,uGAAuG,CAAC;AAC1G,MAAM,QAAQ,GACZ,qGAAqG,CAAC;AAExG,MAAM,UAAU,eAAe,CAAC,KAAc;IAC5C,MAAM,GAAG,GAAG,MAA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KAAK,IAAI;YACnC,CAAC,CAAC,EAAE,iBAAiB,EAAE,SAAS,EAAE;YAClC,CAAC,CAAC,SAAS,EACb,QAAQ,CACT,CACJ,CAAC;IACJ,CAAC,EACD,CAAC,KAAK,EAAE,EAAE;QACR,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,eAAe,CACpC,CAAC,OAAO,IAAI,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAC/D,CAAC;QACF,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAClB,OAAO,GAAG,CAAC;IACb,CAAC,EACD,MAAM,CACP,CAAC;IACF,IAAI,MAAM,CAAC,IAAI,GAAG,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IAC7E,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,MAAM,qBAAqB,GAAG,iBAAiB,CACpD,0BAA0B,CAC3B,CAAC","sourcesContent":["import { hash } from \"node:crypto\";\nimport { CodexSecurityError } from \"./errors.js\";\nimport type { ExternalFinding, ExternalFindings } from \"./external-findings.js\";\nimport {\n CLOUD_EVIDENCE_BYTES,\n CloudEvidenceSizeError,\n DEFAULT_CLOUD_STRING_BYTES,\n type ExternalImportTarget,\n repositoryUrlKey,\n validateEnrichedExternalEvidence,\n validateExternalEvidence,\n validateExternalEvidenceJson,\n} from \"./external-import-contract.js\";\nimport type { ImportedPackage, Provider } from \"./external-import-models.js\";\nimport { isRecord } from \"./record.js\";\nimport {\n array,\n awsTimestampSeconds,\n concreteVersion,\n normalizeRecords,\n optionalArray,\n scannerJsonReader,\n record,\n repositoryFilePath,\n requiredText,\n strings,\n text,\n} from \"./scanner-import.js\";\nimport {\n declaredScannerRepositoryUrl,\n repositoryScopeValidator,\n} from \"./scanner-repository-url.js\";\n\nconst format = \"aws-continuum-code-findings/v1\";\nexport const continuumIssueFormat = \"aws-continuum-code-issues/v1\";\nconst findingArn =\n /^(arn:[a-z0-9-]+:continuum:[a-z0-9-]+:\\d{12}:environments\\/([a-z0-9]+))\\/code-findings\\/([a-z0-9]+)$/u;\nconst issueArn =\n /^(arn:[a-z0-9-]+:continuum:[a-z0-9-]+:\\d{12}:environments\\/([a-z0-9]+))\\/code-issues\\/([a-z0-9]+)$/u;\n\nexport function findingIdentity(value: unknown) {\n const row = record(value, \"Continuum finding\");\n const arn = requiredText(row[\"findingArn\"], \"Continuum finding ARN\");\n const match = findingArn.exec(arn);\n if (\n !match ||\n row[\"environmentId\"] !== match[2] ||\n row[\"findingId\"] !== match[3]\n )\n throw new Error(\n \"Expected a Continuum finding ARN matching its environmentId and findingId.\",\n );\n return { arn, scope: match[1]!, id: match[3]! };\n}\n\nexport function issueIdentity(value: unknown) {\n const issue = record(value, \"Continuum issue\");\n const arn = requiredText(issue[\"issueArn\"], \"Continuum issue ARN\");\n const match = issueArn.exec(arn);\n if (!match || issue[\"issueId\"] !== match[3])\n throw new Error(\"Expected a Continuum issue ARN matching its issueId.\");\n return { arn, scope: match[1]!, environmentId: match[2]!, id: match[3]! };\n}\n\nfunction retainedRepository(\n provider: Provider,\n finding: ExternalFinding,\n target: ExternalImportTarget,\n) {\n const {\n source_finding_id: id,\n evidence: { source_data: data },\n } = finding;\n const isIssue =\n data?.[\"format\"] === continuumIssueFormat || issueArn.test(id);\n const native = data?.[isIssue ? \"issue\" : \"finding\"];\n const marked = isIssue || data?.[\"format\"] === format;\n const nativeArn =\n isRecord(native) && findingArn.test(text(native[\"findingArn\"]) ?? \"\");\n if (provider !== \"continuum\") {\n if (\n marked ||\n (data?.[\"sourceRepositoryUrl\"] &&\n nativeArn &&\n native[\"findingArn\"] === id)\n )\n throw new CodexSecurityError(\n \"Retained AWS Continuum evidence requires the continuum provider.\",\n );\n return;\n }\n if (!marked && !nativeArn && !findingArn.test(id)) return;\n const { arn, scope } = isIssue\n ? issueIdentity(native)\n : findingIdentity(native);\n if (arn !== id)\n throw new Error(\n `Continuum source finding ID does not match the retained ${isIssue ? \"issue\" : \"finding\"} ARN.`,\n );\n return {\n url: declaredScannerRepositoryUrl(\n data?.[\"sourceRepositoryUrl\"],\n \"Continuum\",\n target,\n ),\n scope,\n };\n}\n\nexport const continuumReportRepositories = repositoryScopeValidator(\n { provider: \"continuum\", label: \"AWS Continuum\", scope: \"environment\" },\n retainedRepository,\n);\n\nfunction findingVulnerabilities(row: Record<string, unknown>) {\n return array(row[\"vulnerabilities\"] ?? [], \"Continuum vulnerabilities\").map(\n (item) => record(item, \"Continuum vulnerability\"),\n );\n}\n\nfunction* findingCodeLocations(\n row: Record<string, unknown>,\n vulnerabilities: Record<string, unknown>[],\n) {\n yield {\n filePath: row[\"filePath\"],\n startLine: row[\"lineNumber\"],\n endLine: row[\"endLine\"],\n code: row[\"vulnerableCode\"],\n };\n for (const vulnerability of vulnerabilities) {\n for (const value of array(\n vulnerability[\"locations\"] ?? [],\n \"Continuum vulnerability locations\",\n )) {\n const location = record(value, \"Continuum vulnerability location\");\n yield {\n filePath: location[\"filePath\"],\n startLine: location[\"startLine\"],\n endLine: location[\"endLine\"],\n code: vulnerability[\"code\"],\n };\n }\n }\n}\n\nfunction locationLine(value: unknown): number | null {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0\n ? value\n : null;\n}\n\nfunction codeLocations(\n ranges: Iterable<{\n filePath: unknown;\n startLine: unknown;\n endLine: unknown;\n code?: unknown;\n }>,\n) {\n const locations: { path: string; line: number | null }[] = [];\n const seen = new Set<string>();\n let endLine: number | null = null;\n let snippet: string | null = null;\n for (const range of ranges) {\n const path = repositoryFilePath(range.filePath);\n if (!path) continue;\n const line = locationLine(range.startLine);\n const end = locationLine(range.endLine);\n const key = JSON.stringify([path, line]);\n if (!seen.has(key)) {\n seen.add(key);\n locations.push({ path, line });\n }\n // The flat location and first nested location can describe the same range.\n if (locations[0]!.path === path && locations[0]!.line === line) {\n if (line !== null && end !== null && end >= line) endLine ??= end;\n snippet ??= text(range.code);\n }\n }\n return { locations, code: { end_line: endLine, snippet } };\n}\n\nfunction reportRows(input: unknown) {\n if (Array.isArray(input)) return { rows: input, summary: false };\n const document = record(input, \"Continuum report\");\n if (\n Object.hasOwn(document, \"nextToken\") ||\n Object.hasOwn(document, \"NextToken\")\n )\n throw new Error(\n \"Continuum export has a continuation token; supply the complete paginated CLI output.\",\n );\n if (!(\n \"items\" in document ||\n \"findingArn\" in document ||\n \"finding\" in document\n ))\n throw new Error(\n \"Expected a Continuum ListCodeFindings, GetCodeFinding, or finding with artifacts.\",\n );\n const summary = \"items\" in document;\n return {\n rows: summary ? array(document[\"items\"], \"Continuum items\") : [document],\n summary,\n };\n}\n\nfunction isFindingCapture(value: unknown): value is Record<string, unknown> {\n return isRecord(value) && !(\"findingArn\" in value) && \"finding\" in value;\n}\n\nexport function readPatch(value: unknown) {\n const artifact = record(value, \"Continuum patch artifact\");\n const patch = requiredText(artifact[\"patch\"], \"Continuum patch content\");\n const sizeBytes = Buffer.byteLength(patch);\n const patchSha256 = hash(\"sha256\", patch);\n if (\n artifact[\"sizeBytes\"] !== sizeBytes ||\n artifact[\"patchSha256\"] !== patchSha256\n )\n throw new Error(\n \"Continuum patch content does not match its sizeBytes or patchSha256.\",\n );\n return {\n artifactId: requiredText(\n artifact[\"artifactId\"],\n \"Continuum patch artifact ID\",\n ),\n patch,\n patchSha256,\n sizeBytes,\n ...(artifact[\"format\"] !== undefined && {\n format: requiredText(artifact[\"format\"], \"Continuum patch format\"),\n }),\n ...(artifact[\"repositoryName\"] !== undefined && {\n repositoryName: requiredText(\n artifact[\"repositoryName\"],\n \"Continuum patch repository\",\n ),\n }),\n };\n}\n\ninterface ArtifactGroups {\n evidence_artifacts?: Record<string, unknown>[];\n patches?: Record<string, unknown>[];\n}\n\nfunction projectArtifactBodies(\n artifacts: ArtifactGroups,\n target: ExternalImportTarget,\n project: (artifacts: ArtifactGroups) => ExternalFinding[\"evidence\"],\n) {\n if (!Object.keys(artifacts).length || target === \"local\")\n return project(artifacts);\n try {\n return project(artifacts);\n } catch (error) {\n if (!(error instanceof CloudEvidenceSizeError)) throw error;\n }\n\n // Reserve all descriptors. Fit whole validation bodies before optional patches.\n const marker = { contentOmitted: \"cloud_evidence_limit\" };\n const projected: ArtifactGroups = {};\n const omitted = [];\n for (const key of [\"evidence_artifacts\", \"patches\"] as const) {\n const group = artifacts[key];\n if (!group) continue;\n const bodyKey = key === \"patches\" ? \"patch\" : \"body\";\n const wireBytes = (entry: object) =>\n validateExternalEvidenceJson({ source_data: { [key]: [entry] } }, target);\n const markerBytes = wireBytes(marker);\n const compact: Record<string, unknown>[] = [];\n projected[key] = compact;\n for (const [index, artifact] of group.entries()) {\n const { [bodyKey]: body, ...descriptor } = artifact;\n try {\n const bytes = wireBytes({ [bodyKey]: body }) - markerBytes;\n if (bytes <= 0) {\n compact.push(artifact);\n continue;\n }\n omitted.push({ compact, index, bytes, artifact });\n } catch (error) {\n if (!(error instanceof CloudEvidenceSizeError)) throw error;\n }\n compact.push({ ...descriptor, ...marker });\n }\n }\n let result: ExternalFinding[\"evidence\"];\n try {\n result = project(projected);\n } catch (error) {\n if (\n !(error instanceof CloudEvidenceSizeError) ||\n !artifacts.evidence_artifacts?.length\n )\n throw error;\n // Even the validation descriptors exceed the budget. Retry the original finding and patches.\n return projectArtifactBodies(\n artifacts.patches ? { patches: artifacts.patches } : {},\n target,\n project,\n );\n }\n let remaining =\n CLOUD_EVIDENCE_BYTES - validateExternalEvidenceJson(result, target);\n for (const { compact, index, bytes, artifact } of omitted) {\n if (bytes > remaining) continue;\n compact[index] = artifact;\n remaining -= bytes;\n }\n return result;\n}\n\nfunction subcategoryCwe(row: Record<string, unknown>) {\n return /^(CWE-[1-9]\\d*):/u.exec(text(row[\"subCategory\"]) ?? \"\")?.[1];\n}\n\nfunction statusUpdatedAt(value: unknown) {\n const seconds = Math.floor(awsTimestampSeconds(value));\n return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : null;\n}\n\nconst versionEcosystems = new Map([\n [\"gradle\", \"maven\"],\n [\"pnpm\", \"npm\"],\n [\"yarn\", \"npm\"],\n]);\n\nfunction affectedPackages(\n items: unknown[],\n target: ExternalImportTarget,\n): ImportedPackage[] {\n const unique = new Map<string, ImportedPackage>();\n const field = (value: unknown) => {\n const result = text(value);\n return result &&\n !result.includes(\"\\0\") &&\n (target === \"local\" ||\n Buffer.byteLength(result) <= DEFAULT_CLOUD_STRING_BYTES)\n ? result\n : null;\n };\n for (const item of items) {\n if (!isRecord(item)) continue;\n const name = field(item[\"name\"]);\n if (!name) continue;\n const ecosystem = field(item[\"packageManager\"]);\n const manager = ecosystem?.toLowerCase();\n const syntax = manager ? (versionEcosystems.get(manager) ?? manager) : null;\n const version = (value: unknown) =>\n concreteVersion(field(value), syntax, false);\n const fixed = version(item[\"fixedInVersion\"]);\n const pkg = {\n name,\n ecosystem,\n installed_version: version(item[\"version\"]),\n fixed_versions: fixed ? [fixed] : [],\n };\n unique.set(JSON.stringify(pkg), pkg);\n // The Cloud contract accepts 100 structured packages. The native row keeps them all.\n if (target === \"cloud\" && unique.size === 100) break;\n }\n return [...unique.values()];\n}\n\nfunction linkedIssueFindings(\n value: unknown,\n issue: Record<string, unknown>,\n scope: string,\n) {\n const ids = array(issue[\"findingIds\"], \"Continuum issue findingIds\").map(\n (id) => requiredText(id, \"Continuum issue finding ID\"),\n );\n const missing = new Set(ids);\n const findings = new Map<string, Record<string, unknown>>();\n const invalidLinks =\n \"Supply exactly one detail response per Continuum issue finding ID.\";\n if (ids.length === 0 || missing.size !== ids.length)\n throw new Error(invalidLinks);\n for (const item of array(value, \"Continuum issue findings\")) {\n const { id, scope: findingScope } = findingIdentity(item);\n if (findingScope !== scope)\n throw new Error(\n \"Continuum issue and linked finding must share an environment.\",\n );\n if (!missing.delete(id)) throw new Error(invalidLinks);\n findings.set(id, record(item, \"Continuum finding\"));\n }\n if (missing.size) throw new Error(invalidLinks);\n return ids.map((id) => findings.get(id)!);\n}\n\nfunction issueFindingEvidence(\n finding: Record<string, unknown>,\n includeReviewEvidence: boolean,\n) {\n const dependencyFields = (row: Record<string, unknown>) => ({\n cveId: text(row[\"cveId\"]),\n affectedPackages: Array.isArray(row[\"affectedPackages\"])\n ? row[\"affectedPackages\"]\n : [],\n });\n const vulnerableCode =\n includeReviewEvidence && text(finding[\"vulnerableCode\"]);\n const mitigation = includeReviewEvidence && text(finding[\"mitigation\"]);\n const validation = finding[\"validation\"];\n // Retain the inputs needed to replay the stored issue. The export on disk\n // retains the full finding details.\n return {\n findingArn: finding[\"findingArn\"],\n findingId: finding[\"findingId\"],\n environmentId: finding[\"environmentId\"],\n ocsfClass:\n finding[\"posture\"] != null\n ? \"APPLICATION_SECURITY_POSTURE_FINDING\"\n : text(finding[\"ocsfClass\"]),\n ...dependencyFields(finding),\n filePath: text(finding[\"filePath\"]),\n lineNumber: locationLine(finding[\"lineNumber\"]),\n endLine: locationLine(finding[\"endLine\"]),\n ...(vulnerableCode && { vulnerableCode }),\n ...(mitigation && { mitigation }),\n ...(includeReviewEvidence && isRecord(validation) && { validation }),\n vulnerabilities: findingVulnerabilities(finding).map((vulnerability) => {\n const code = includeReviewEvidence && text(vulnerability[\"code\"]);\n return {\n ...dependencyFields(vulnerability),\n locations: vulnerability[\"locations\"] ?? [],\n ...(code && { code }),\n };\n }),\n };\n}\n\nfunction issueEvidenceBody(artifact: Record<string, unknown>) {\n const body = artifact[\"body\"];\n if (!isRecord(body)) return;\n if (artifact[\"artifactType\"] === \"VALIDATION_EVIDENCE\") {\n if (isRecord(body[\"validationEvidence\"]))\n return { validationEvidence: body[\"validationEvidence\"] };\n if (typeof body[\"raw\"] === \"string\") return { raw: body[\"raw\"] };\n }\n const projection = body[\"prevalidationSignals\"];\n if (artifact[\"artifactType\"] !== \"EVIDENCE\" || !isRecord(projection)) return;\n const signals = array(\n projection[\"signals\"] ?? [],\n \"Continuum evidence signals\",\n ).map((signal) => record(signal, \"Continuum evidence signal\"));\n return { prevalidationSignals: { ...projection, signals } };\n}\n\nfunction issueEvidenceDescriptor(artifact: Record<string, unknown>) {\n return {\n artifactId: requiredText(\n artifact[\"artifactId\"],\n \"Continuum evidence artifact ID\",\n ),\n artifactType: artifact[\"artifactType\"],\n ...(artifact[\"createdAt\"] != null && { createdAt: artifact[\"createdAt\"] }),\n ...(artifact[\"mediaType\"] != null && { mediaType: artifact[\"mediaType\"] }),\n ...(artifact[\"producer\"] != null && { producer: artifact[\"producer\"] }),\n };\n}\n\nexport function singleFindingValidationIssue(\n issue: unknown,\n issueId: unknown,\n finding: ReturnType<typeof findingIdentity>,\n) {\n if (!isRecord(issue) || typeof issueId !== \"string\") return null;\n const arn = `${finding.scope}/code-issues/${issueId}`;\n const ids = issue[\"findingIds\"];\n if (\n issue[\"issueArn\"] !== arn ||\n issue[\"issueId\"] !== issueId ||\n !Array.isArray(ids) ||\n ids.length !== 1 ||\n ids[0] !== finding.id\n )\n return null;\n return { issueArn: arn, issueId, findingIds: [finding.id] };\n}\n\nexport function selectFindingValidationArtifact(\n artifact: Record<string, unknown>,\n findingId: unknown,\n) {\n if (artifact[\"artifactType\"] !== \"VALIDATION_EVIDENCE\") return;\n const body = issueEvidenceBody(artifact);\n if (!body) return;\n const results = body.validationEvidence?.[\"perFindingResults\"];\n if (results === undefined) return { scope: \"issue\", artifact };\n // A bundle's top-level proof can belong to a different finding.\n const matches = array(results, \"Continuum per-finding results\")\n .map((value) => record(value, \"Continuum per-finding result\"))\n .filter((result) => result[\"findingId\"] === findingId);\n if (matches.length === 0) return;\n return {\n scope: \"finding\",\n artifact: {\n ...issueEvidenceDescriptor(artifact),\n body: {\n validationEvidence: {\n ...(matches.length === 1 &&\n \"exploitable\" in matches[0]! && {\n exploitable: matches[0]![\"exploitable\"],\n }),\n perFindingResults: matches,\n },\n },\n },\n };\n}\n\nfunction issueEvidenceArtifacts(artifacts: Record<string, unknown>[]) {\n return artifacts.flatMap((artifact) => {\n const body = issueEvidenceBody(artifact);\n return body ? [{ ...issueEvidenceDescriptor(artifact), body }] : [];\n });\n}\n\nfunction normalizeContinuumIssues(\n document: Record<string, unknown>,\n repository: string,\n target: ExternalImportTarget,\n): ExternalFindings {\n const environmentId = requiredText(\n document[\"environmentId\"],\n \"Continuum environment ID\",\n );\n const rows = array(document[\"issues\"], \"Continuum issues\");\n const scopes = new Set<string>();\n const result = normalizeRecords(\n rows,\n (value) => {\n const row = record(value, \"Continuum issue record\");\n const { artifacts, ...issue } = record(row[\"issue\"], \"Continuum issue\");\n const { arn, id, scope } = issueIdentity(issue);\n const issueArtifacts = array(\n artifacts ?? row[\"evidenceArtifacts\"] ?? [],\n \"Continuum issue artifacts\",\n ).map((artifact) => record(artifact, \"Continuum issue artifact\"));\n const evidenceArtifacts = issueEvidenceArtifacts(issueArtifacts);\n const patches = issueArtifacts\n .filter((artifact) => artifact[\"artifactType\"] === \"PATCH\")\n .map((artifact) => {\n const body = record(artifact[\"body\"], \"Continuum patch body\");\n return readPatch({\n ...record(body[\"patch\"], \"Continuum patch\"),\n artifactId: artifact[\"artifactId\"],\n });\n });\n const verdicts = new Set<string>();\n for (const artifact of evidenceArtifacts) {\n for (const signal of artifact.body.prevalidationSignals?.signals ??\n []) {\n const subject = signal[\"subjectRef\"];\n const exploitability = signal[\"exploitability\"];\n if (\n signal[\"dimension\"] !== \"EXPLOITABILITY\" ||\n (subject !== id && subject !== arn) ||\n !isRecord(exploitability)\n )\n continue;\n const verdict = text(exploitability[\"verdict\"]);\n if (verdict) verdicts.add(verdict);\n }\n }\n const scannerVerdict = verdicts.size > 1 ? \"MIXED\" : [...verdicts][0];\n const linked = linkedIssueFindings(row[\"findings\"], issue, scope);\n const findings = linked.map((finding) =>\n issueFindingEvidence(finding, true),\n );\n const ranges = findings.flatMap((finding) =>\n Array.from(findingCodeLocations(finding, finding.vulnerabilities)),\n );\n const { locations, code } = codeLocations([\n ...ranges.filter(({ startLine }) => locationLine(startLine) !== null),\n ...ranges.filter(({ startLine }) => locationLine(startLine) === null),\n ]);\n const all = findings.flatMap((finding) => [\n finding,\n ...finding.vulnerabilities,\n ]);\n const advisories = [...new Set(strings(all.map((row) => row.cveId)))];\n const packages = all.flatMap((row) => row.affectedPackages);\n const dependency = advisories.length > 0 || packages.length > 0;\n const posture = findings.some(\n (finding) =>\n finding.ocsfClass === \"APPLICATION_SECURITY_POSTURE_FINDING\",\n );\n const status = requiredText(issue[\"status\"], \"Continuum issue status\");\n const synopsis = requiredText(\n issue[\"synopsis\"],\n \"Continuum issue synopsis\",\n );\n const details =\n posture || (!scannerVerdict && locations[0]?.line == null)\n ? undefined\n : {\n details: {\n kind: dependency ? \"advisory\" : \"sast\",\n ...(dependency && { advisory: { source: \"repository\" } }),\n repository: { url: repository },\n source_status: status,\n ...(scannerVerdict && { scanner_verdict: scannerVerdict }),\n remediation_instructions: text(issue[\"summary\"]),\n code: { ...code, snippet: null },\n },\n };\n const reviewDetails = details && {\n details: {\n ...details.details,\n remediation_instructions:\n details.details.remediation_instructions ??\n findings.find(({ mitigation }) => mitigation)?.mitigation ??\n null,\n code,\n },\n };\n const dependencyEvidence = dependency\n ? {\n advisory_ids:\n target === \"cloud\" ? advisories.slice(0, 100) : advisories,\n packages: affectedPackages(packages, target),\n }\n : undefined;\n const source = {\n format: continuumIssueFormat,\n sourceRepositoryUrl: repository,\n environmentId,\n issue,\n ...(evidenceArtifacts.length && {\n evidence_artifacts: evidenceArtifacts,\n }),\n };\n const compactSource = structuredClone({\n ...source,\n findings: linked.map((finding) => issueFindingEvidence(finding, false)),\n });\n const findingsWithVerdicts = compactSource.findings.map(\n (finding, index) => {\n const verdict = text(findings[index]?.validation?.[\"verdict\"]);\n return verdict ? { ...finding, validation: { verdict } } : finding;\n },\n );\n const evidence = validateEnrichedExternalEvidence(\n {\n title: requiredText(issue[\"name\"], \"Continuum issue name\"),\n severity: text(issue[\"severity\"])?.toLowerCase() ?? \"unknown\",\n description: [synopsis, text(issue[\"severityReasoning\"])]\n .filter(Boolean)\n .join(\"\\n\\n\"),\n // Keep every reported range in source_data, including ranges beyond\n // the Cloud limit for navigable locations.\n locations: target === \"cloud\" ? locations.slice(0, 100) : locations,\n source_updated_at:\n statusUpdatedAt(issue[\"updatedAt\"]) ??\n statusUpdatedAt(issue[\"statusUpdatedAt\"]),\n source_data: compactSource,\n ...(scannerVerdict &&\n details && {\n details: {\n ...details.details,\n remediation_instructions: null,\n code: null,\n },\n }),\n },\n target,\n {\n ...reviewDetails,\n ...dependencyEvidence,\n source_data: structuredClone({ ...source, findings }),\n },\n // Bulky linked validation evidence can exceed the Cloud record limit.\n // Keep the per-finding verdicts with the structured review fields if they fit.\n {\n ...reviewDetails,\n ...dependencyEvidence,\n source_data: { ...compactSource, findings: findingsWithVerdicts },\n },\n dependencyEvidence\n ? { ...reviewDetails, ...dependencyEvidence }\n : undefined,\n reviewDetails,\n dependencyEvidence ? { ...details, ...dependencyEvidence } : undefined,\n details,\n dependencyEvidence,\n );\n if (!patches.length) return evidence;\n // Fit optional patch bodies after selecting the scanner evidence to retain.\n return projectArtifactBodies({ patches }, target, (artifacts) =>\n validateExternalEvidence(\n {\n ...evidence,\n source_data: { ...evidence.source_data, ...artifacts },\n },\n target,\n ),\n );\n },\n (value) => {\n const issue = issueIdentity(\n record(value, \"Continuum issue record\")[\"issue\"],\n );\n if (issue.environmentId !== environmentId)\n throw new Error(\n \"Continuum issue ARN does not match the export environment.\",\n );\n scopes.add(issue.scope);\n return issue.arn;\n },\n target,\n );\n if (scopes.size > 1)\n throw new Error(\"Continuum issues must belong to the same environment.\");\n return result;\n}\n\nexport function normalizeContinuumFindings(\n input: unknown,\n sourceRepositoryUrl?: string,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n const issueReport =\n isRecord(input) && input[\"format\"] === continuumIssueFormat;\n const capturedSource =\n issueReport && input[\"sourceRepositoryUrl\"] !== undefined\n ? declaredScannerRepositoryUrl(\n input[\"sourceRepositoryUrl\"],\n \"Continuum\",\n target,\n )\n : undefined;\n const repository = declaredScannerRepositoryUrl(\n sourceRepositoryUrl || capturedSource,\n \"Continuum\",\n target,\n );\n if (issueReport) {\n if (\n capturedSource &&\n repositoryUrlKey(capturedSource) !== repositoryUrlKey(repository)\n )\n throw new Error(\n \"The Continuum export repository does not match the declared source repository.\",\n );\n const findings = normalizeContinuumIssues(\n input,\n capturedSource ?? repository,\n target,\n );\n return capturedSource\n ? { ...findings, report: { sourceRepositoryUrl: capturedSource } }\n : findings;\n }\n const { rows, summary } = reportRows(input);\n const scopes = new Set<string>();\n const output = normalizeRecords(\n rows,\n (value) => {\n const capture = !summary && isFindingCapture(value) ? value : undefined;\n const row = record(\n capture ? capture[\"finding\"] : value,\n \"Continuum finding\",\n );\n const patches = optionalArray(\n capture?.[\"patches\"],\n \"Continuum patches\",\n ).map(readPatch);\n const linkedIssue =\n text(row[\"createdIssueId\"]) ?? text(row[\"duplicateOfIssueId\"]);\n let validationIssue:\n ReturnType<typeof singleFindingValidationIssue> | undefined;\n const evidenceArtifacts = issueEvidenceArtifacts(\n optionalArray(\n capture?.[\"evidenceArtifacts\"],\n \"Continuum evidence artifacts\",\n ).flatMap((value) => {\n const selected = selectFindingValidationArtifact(\n record(value, \"Continuum validation artifact\"),\n row[\"findingId\"],\n );\n if (!selected) return [];\n if (selected.scope === \"issue\") {\n validationIssue ??= singleFindingValidationIssue(\n capture?.[\"validationIssue\"],\n linkedIssue,\n findingIdentity(row),\n );\n if (!validationIssue) return [];\n }\n return [selected.artifact];\n }),\n );\n if ((patches.length || evidenceArtifacts.length) && !linkedIssue)\n throw new Error(\n `Continuum ${patches.length ? \"patches\" : \"validation artifacts\"} require a finding linked to an issue.`,\n );\n if (\n row[\"type\"] !== \"CONTINUUM_CODE_VULN\" &&\n row[\"type\"] !== \"CUSTOMER_CODE_VULN\"\n )\n throw new Error(\n \"Expected a Continuum code vulnerability finding type.\",\n );\n const severity = requiredText(\n row[\"severity\"],\n \"Continuum severity\",\n ).toLowerCase();\n const vulnerabilities = findingVulnerabilities(row);\n const { locations, code } = codeLocations(\n findingCodeLocations(row, vulnerabilities),\n );\n const source = requiredText(row[\"source\"], \"Continuum source\");\n const status = requiredText(row[\"status\"], \"Continuum status\");\n const validation = record(\n row[\"validation\"] ?? {},\n \"Continuum validation\",\n );\n const all = [row, ...vulnerabilities];\n const advisoryIds = [\n ...new Set(strings(all.map((item) => item[\"cveId\"]))),\n ];\n const packages = all.flatMap((item) =>\n Array.isArray(item[\"affectedPackages\"]) ? item[\"affectedPackages\"] : [],\n );\n const packageFinding = advisoryIds.length > 0 || packages.length > 0;\n const posture =\n row[\"ocsfClass\"] === \"APPLICATION_SECURITY_POSTURE_FINDING\" ||\n row[\"posture\"] != null;\n const codeFinding =\n !summary &&\n !posture &&\n !packageFinding &&\n (code.snippet !== null ||\n locations.some((location) => location.line !== null));\n const evidence = {\n title: requiredText(row[\"title\"], \"Continuum title\"),\n severity:\n severity === \"fatal\"\n ? \"critical\"\n : severity === \"other\"\n ? \"unknown\"\n : severity,\n description: text(row[\"detailedDescription\"]) ?? text(row[\"summary\"]),\n locations,\n advisory_ids: advisoryIds,\n source_scan_id: text(row[\"scanRunId\"]),\n ...(codeFinding && {\n details: {\n kind: \"sast\",\n repository: { url: repository },\n scanner_origin: source,\n scanner_verdict: text(validation[\"verdict\"]),\n source_status: status,\n weakness_ids: strings(row[\"cweIds\"]),\n remediation_instructions: text(row[\"mitigation\"]),\n code,\n },\n }),\n source_data: {\n format,\n sourceRepositoryUrl: repository,\n finding: structuredClone(row),\n },\n };\n const updatedAt = statusUpdatedAt(row[\"statusUpdatedAt\"]);\n const enrichment = {\n packages: affectedPackages(packages, target),\n source_updated_at: updatedAt,\n };\n // Native code findings can identify a CWE only in subCategory.\n const namedCwe =\n evidence.details?.weakness_ids.length === 0\n ? subcategoryCwe(row)\n : undefined;\n const inferred = namedCwe\n ? { details: { ...evidence.details, weakness_ids: [namedCwe] } }\n : undefined;\n // Keep previously admissible evidence if an optional projection exceeds the Cloud budget.\n return projectArtifactBodies(\n {\n ...(evidenceArtifacts.length && {\n evidence_artifacts: structuredClone(evidenceArtifacts),\n }),\n ...(patches.length && { patches }),\n },\n target,\n (artifacts) =>\n validateEnrichedExternalEvidence(\n {\n ...evidence,\n source_data: {\n ...evidence.source_data,\n ...(validationIssue &&\n artifacts.evidence_artifacts?.length && {\n validation_issue: validationIssue,\n }),\n ...artifacts,\n },\n },\n target,\n inferred ? { ...enrichment, ...inferred } : undefined,\n enrichment,\n packages.length && updatedAt !== null\n ? { source_updated_at: updatedAt }\n : undefined,\n inferred,\n ),\n );\n },\n (value) => {\n const { arn, scope } = findingIdentity(\n !summary && isFindingCapture(value) ? value[\"finding\"] : value,\n );\n scopes.add(scope);\n return arn;\n },\n target,\n );\n if (scopes.size > 1)\n throw new Error(\"Continuum findings must belong to the same environment.\");\n return output;\n}\n\nexport const readContinuumFindings = scannerJsonReader(\n normalizeContinuumFindings,\n);\n"]}
@@ -8,6 +8,7 @@ export interface ScanExpectation {
8
8
  repository: string;
9
9
  repositoryRevision: string | null;
10
10
  target: NormalizedTarget;
11
+ excludePaths?: readonly string[];
11
12
  mode: ScanMode;
12
13
  pluginVersion: string;
13
14
  }
@@ -1 +1 @@
1
- {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,KAAK,WAAW,EAAE,KAAK,KAAK,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAe,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAGhE,OAAO,EAAE,uBAAuB,EAAe,MAAM,aAAa,CAAC;AACnE,OAAO,KAAK,EAEV,gBAAgB,EAChB,YAAY,EACb,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAG/D,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,sBAAsB,CAAC;AAK9B,MAAM,WAAW,eAAe;IAC9B,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E,WAAW,GACnB,OAAO,CAAC,MAAM,CAAC,CAWjB;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CASnD;AA8FD,wBAAsB,qBAAqB,CACzC,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,GAAG,WAAW,EAAE,KAAK,GAAG,KAAK,CAAC,CAAA;CAAE,EAC7E,MAAM,EAAE,IAAI,CAAC,KAAK,GAAG,WAAW,EAAE,KAAK,GAAG,KAAK,CAAC,EAChD,QAAQ,GAAE,MAAM,CAAC,QAA2B,EAC5C,aAAa,GAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,UAAU,CAAQ,GACzE,OAAO,CAAC,OAAO,CAAC,CA+BlB"}
package/dist/contract.js CHANGED
@@ -90,6 +90,9 @@ function validateExpectation(manifest, mode, expectation, workbenchValidated = f
90
90
  throw new ContractValidationError(`Coverage mode must be ${expectedMode}, got ${mode}.`);
91
91
  }
92
92
  const requested = expectation.target;
93
+ if (JSON.stringify(scan.scope.excludePaths) !==
94
+ JSON.stringify(expectation.excludePaths ?? []))
95
+ throw new ContractValidationError("Manifest exclusions do not match the requested scan scope.");
93
96
  if (!workbenchValidated) {
94
97
  const target = scan.target;
95
98
  if (requested.kind === "refs" || requested.kind === "working_tree") {
@@ -1 +1 @@
1
- {"version":3,"file":"contract.js","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":";;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAgC,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAmB,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,WAAW,EAAE,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,GAAG;QAAE,OAAO,IAAI,CAAC;IACrD,IAAI,QAAQ,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IAEvC,MAAM,CAAC,cAAc,EAAE,eAAe,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QAC1D,IAAI,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QAC3B,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;KACtC,CAAC,CAAC;IACH,IACE,CAAC,cAAc,CAAC,MAAM,EAAE;QACxB,CAAC,eAAe,CAAC,MAAM,EAAE;QACzB,cAAc,CAAC,GAAG,KAAK,eAAe,CAAC,GAAG,EAC1C,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,SAAS,GAAG,MAAM,aAAa,CACnC,OAAO,CAAC,IAAI,EACZ,SAAS,CAAC,QAAQ,GAAG,SAAS,CAAC,UAAU,GAAG,SAAS,CAAC,UAAU,CACjE,CAAC;IACF,IAAI,CAAC;QACH,MAAM,iBAAiB,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACjE,OAAO,CACL,iBAAiB,CAAC,MAAM,EAAE;YAC1B,cAAc,CAAC,GAAG,KAAK,iBAAiB,CAAC,GAAG;YAC5C,cAAc,CAAC,GAAG,KAAK,iBAAiB,CAAC,GAAG,CAC7C,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;IAC1B,CAAC;AACH,CAAC","sourcesContent":["import { constants, type BigIntStats, type Stats } from \"node:fs\";\nimport { lstat, open, type FileHandle } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { ContractValidationError, abortReason } from \"./errors.js\";\nimport type {\n CoverageDocument,\n FindingsDocument,\n ScanManifest,\n} from \"./models.js\";\nimport type { NormalizedTarget, ScanMode } from \"./targets.js\";\nimport { bundledPluginRoot } from \"./runtime.js\";\nimport { safeScopePath as sharedSafeScopePath } from \"./contract-values.js\";\nexport {\n DEFERRED_PATH_LOCATION,\n SEALED_DEFERRED_PATH_RULE,\n deriveFindingIdentity,\n hasRequiredFindingText,\n} from \"./contract-values.js\";\n/** @internal */\nexport { sha256Text } from \"./contract-values.js\";\n\nconst PRODUCER_NAME = \"codex-security-plugin\";\nexport interface ScanExpectation {\n repository: string;\n repositoryRevision: string | null;\n target: NormalizedTarget;\n mode: ScanMode;\n pluginVersion: string;\n}\n\nexport interface LoadedContract {\n mode: NonNullable<ScanManifest[\"scan\"][\"mode\"]>;\n manifest: ScanManifest;\n findings: FindingsDocument;\n review: NonNullable<ScanManifest[\"scan\"][\"review\"]>;\n}\n\n// Hosted receipts compare reread files with the bytes that passed validation.\nexport const validatedFileDigests = new WeakMap<\n ScanManifest,\n ReadonlyMap<string, string>\n>();\n\nexport class ContractSchemaError extends ContractValidationError {}\n\ntype LoadContractOptions = {\n pluginRoot: string;\n expectedScanId?: string;\n expectation?: ScanExpectation;\n workbenchValidated?: boolean;\n signal?: AbortSignal;\n};\n\nasync function contractHelper() {\n return (\n await import(\n pathToFileURL(join(await bundledPluginRoot(), \"mcp/helpers.mjs\")).href\n )\n ).default;\n}\n\nasync function translateContractError<T>(\n operation: () => Promise<T>,\n signal?: AbortSignal,\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (signal?.aborted) throw abortReason(signal);\n if (error instanceof ContractValidationError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n if (error instanceof Error && error.name === \"SealedContractSchemaError\")\n throw new ContractSchemaError(message, { cause: error.cause });\n throw new ContractValidationError(message, {\n cause:\n error instanceof Error && error.name === \"SealedContractError\"\n ? error.cause\n : error,\n });\n }\n}\n\nexport async function loadContract(\n scanDirectory: string,\n options: LoadContractOptions,\n): Promise<LoadedContract> {\n return (await loadContractWithScanDirectory(scanDirectory, options)).contract;\n}\n\nexport async function loadContractWithScanDirectory(\n scanDirectory: string,\n options: LoadContractOptions,\n): Promise<{ contract: LoadedContract; scanDirectory: string }> {\n return translateContractError(async () => {\n const helper = await contractHelper();\n const result = (await helper.loadSealedContract(scanDirectory, {\n pluginRoot: options.pluginRoot,\n expectedScanId: options.expectedScanId,\n signal: options.signal,\n })) as {\n contract: LoadedContract;\n scanDirectory: string;\n fileDigests: ReadonlyMap<string, string>;\n };\n if (options.expectation !== undefined)\n validateExpectation(\n result.contract.manifest,\n result.contract.mode,\n options.expectation,\n options.workbenchValidated === true,\n );\n validatedFileDigests.set(result.contract.manifest, result.fileDigests);\n return {\n contract: result.contract,\n scanDirectory: result.scanDirectory,\n };\n }, options.signal);\n}\n\nexport async function requireScanFile(\n scanDirectory: string,\n relativePath: string,\n context: string,\n signal?: AbortSignal,\n): Promise<string> {\n return translateContractError(\n async () =>\n (await contractHelper()).requireSealedScanFile(\n scanDirectory,\n relativePath,\n context,\n signal,\n ),\n signal,\n );\n}\n\nexport async function readScanFile(\n scanDirectory: string,\n relativePath: string,\n context: string,\n signal?: AbortSignal,\n): Promise<Buffer> {\n return translateContractError(\n async () =>\n (await contractHelper()).readSealedScanFile(\n scanDirectory,\n relativePath,\n context,\n signal,\n ),\n signal,\n );\n}\n\nexport function safeScopePath(value: string): string {\n try {\n return sharedSafeScopePath(value);\n } catch (error) {\n throw new ContractValidationError(\n error instanceof Error ? error.message : String(error),\n { cause: error },\n );\n }\n}\n\nfunction validateExpectation(\n manifest: ScanManifest,\n mode: LoadedContract[\"mode\"],\n expectation: ScanExpectation,\n workbenchValidated = false,\n): void {\n const scan = manifest.scan;\n if (scan.producer.name !== PRODUCER_NAME) {\n throw new ContractValidationError(\n `Manifest producer must be ${PRODUCER_NAME}, got ${scan.producer.name}.`,\n );\n }\n if (scan.producer.version !== expectation.pluginVersion) {\n throw new ContractValidationError(\n \"Manifest producer version does not match the installed Codex Security plugin.\",\n );\n }\n\n const expectedMode = expectedCoverageMode(\n expectation.target,\n expectation.mode,\n );\n if (mode !== expectedMode) {\n throw new ContractValidationError(\n `Coverage mode must be ${expectedMode}, got ${mode}.`,\n );\n }\n\n const requested = expectation.target;\n if (!workbenchValidated) {\n const target = scan.target;\n if (requested.kind === \"refs\" || requested.kind === \"working_tree\") {\n if (target.kind !== \"git_diff\") {\n throw new ContractValidationError(\n \"Diff scan manifest target must be git_diff.\",\n );\n }\n if (target.baseRevision !== requested.base) {\n throw new ContractValidationError(\n \"Diff scan base revision does not match the request.\",\n );\n }\n if (target.headRevision !== requested.head) {\n throw new ContractValidationError(\n \"Diff scan head revision does not match the request.\",\n );\n }\n } else if (target.kind === \"git_diff\") {\n throw new ContractValidationError(\n \"Repository scan manifest target must not be git_diff.\",\n );\n } else if (\n target.kind !== \"directory_snapshot\" &&\n expectation.repositoryRevision !== null &&\n target.revision !== expectation.repositoryRevision\n ) {\n throw new ContractValidationError(\n \"Scan target revision does not match the repository.\",\n );\n }\n }\n\n if (requested.kind === \"paths\") {\n const actualPaths = scan.scope.includePaths.map(safeScopePath);\n const actual = new Set(actualPaths);\n if (actualPaths.length === actual.size) {\n const expected = new Set(requested.paths);\n if (actual.size === expected.size && actual.isSubsetOf(expected)) return;\n }\n throw new ContractValidationError(\n \"Manifest include paths do not match the requested path target.\",\n );\n }\n}\n\nfunction expectedCoverageMode(\n target: NormalizedTarget,\n mode: ScanMode,\n): CoverageDocument[\"mode\"] {\n if (target.kind === \"paths\") return \"scoped_path\";\n if (target.kind === \"refs\") return \"branch_diff\";\n if (target.kind === \"working_tree\") return \"working_tree\";\n return mode === \"deep\" ? \"deep_repository\" : \"repository\";\n}\n\nexport async function sameCheckedFileDevice(\n file: FileHandle,\n checked: { path: string; metadata: Pick<Stats | BigIntStats, \"dev\" | \"ino\"> },\n opened: Pick<Stats | BigIntStats, \"dev\" | \"ino\">,\n platform: NodeJS.Platform = process.platform,\n openReference: (path: string, flags: number) => Promise<FileHandle> = open,\n): Promise<boolean> {\n if (opened.ino !== checked.metadata.ino) return false;\n if (opened.dev === checked.metadata.dev) return true;\n if (platform !== \"win32\") return false;\n\n const [openedIdentity, checkedIdentity] = await Promise.all([\n file.stat({ bigint: true }),\n lstat(checked.path, { bigint: true }),\n ]);\n if (\n !openedIdentity.isFile() ||\n !checkedIdentity.isFile() ||\n openedIdentity.ino !== checkedIdentity.ino\n ) {\n return false;\n }\n\n const reference = await openReference(\n checked.path,\n constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,\n );\n try {\n const referenceIdentity = await reference.stat({ bigint: true });\n return (\n referenceIdentity.isFile() &&\n openedIdentity.dev === referenceIdentity.dev &&\n openedIdentity.ino === referenceIdentity.ino\n );\n } finally {\n await reference.close();\n }\n}\n"]}
1
+ {"version":3,"file":"contract.js","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":";;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAgC,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAmB,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAOnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,aAAa,IAAI,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,sBAAsB,CAAC;AAC9B,gBAAgB;AAChB,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,MAAM,aAAa,GAAG,uBAAuB,CAAC;AAiB9C,8EAA8E;AAC9E,MAAM,CAAC,MAAM,oBAAoB,GAAG,IAAI,OAAO,EAG5C,CAAC;AAEJ,MAAM,OAAO,mBAAoB,SAAQ,uBA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C,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;KACtC,CAAC,CAAC;IACH,IACE,CAAC,cAAc,CAAC,MAAM,EAAE;QACxB,CAAC,eAAe,CAAC,MAAM,EAAE;QACzB,cAAc,CAAC,GAAG,KAAK,eAAe,CAAC,GAAG,EAC1C,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,SAAS,GAAG,MAAM,aAAa,CACnC,OAAO,CAAC,IAAI,EACZ,SAAS,CAAC,QAAQ,GAAG,SAAS,CAAC,UAAU,GAAG,SAAS,CAAC,UAAU,CACjE,CAAC;IACF,IAAI,CAAC;QACH,MAAM,iBAAiB,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACjE,OAAO,CACL,iBAAiB,CAAC,MAAM,EAAE;YAC1B,cAAc,CAAC,GAAG,KAAK,iBAAiB,CAAC,GAAG;YAC5C,cAAc,CAAC,GAAG,KAAK,iBAAiB,CAAC,GAAG,CAC7C,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,SAAS,CAAC,KAAK,EAAE,CAAC;IAC1B,CAAC;AACH,CAAC","sourcesContent":["import { constants, type BigIntStats, type Stats } from \"node:fs\";\nimport { lstat, open, type FileHandle } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { ContractValidationError, abortReason } from \"./errors.js\";\nimport type {\n CoverageDocument,\n FindingsDocument,\n ScanManifest,\n} from \"./models.js\";\nimport type { NormalizedTarget, ScanMode } from \"./targets.js\";\nimport { bundledPluginRoot } from \"./runtime.js\";\nimport { safeScopePath as sharedSafeScopePath } from \"./contract-values.js\";\nexport {\n DEFERRED_PATH_LOCATION,\n SEALED_DEFERRED_PATH_RULE,\n deriveFindingIdentity,\n hasRequiredFindingText,\n} from \"./contract-values.js\";\n/** @internal */\nexport { sha256Text } from \"./contract-values.js\";\n\nconst PRODUCER_NAME = \"codex-security-plugin\";\nexport interface ScanExpectation {\n repository: string;\n repositoryRevision: string | null;\n target: NormalizedTarget;\n excludePaths?: readonly string[];\n mode: ScanMode;\n pluginVersion: string;\n}\n\nexport interface LoadedContract {\n mode: NonNullable<ScanManifest[\"scan\"][\"mode\"]>;\n manifest: ScanManifest;\n findings: FindingsDocument;\n review: NonNullable<ScanManifest[\"scan\"][\"review\"]>;\n}\n\n// Hosted receipts compare reread files with the bytes that passed validation.\nexport const validatedFileDigests = new WeakMap<\n ScanManifest,\n ReadonlyMap<string, string>\n>();\n\nexport class ContractSchemaError extends ContractValidationError {}\n\ntype LoadContractOptions = {\n pluginRoot: string;\n expectedScanId?: string;\n expectation?: ScanExpectation;\n workbenchValidated?: boolean;\n signal?: AbortSignal;\n};\n\nasync function contractHelper() {\n return (\n await import(\n pathToFileURL(join(await bundledPluginRoot(), \"mcp/helpers.mjs\")).href\n )\n ).default;\n}\n\nasync function translateContractError<T>(\n operation: () => Promise<T>,\n signal?: AbortSignal,\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (signal?.aborted) throw abortReason(signal);\n if (error instanceof ContractValidationError) throw error;\n const message = error instanceof Error ? error.message : String(error);\n if (error instanceof Error && error.name === \"SealedContractSchemaError\")\n throw new ContractSchemaError(message, { cause: error.cause });\n throw new ContractValidationError(message, {\n cause:\n error instanceof Error && error.name === \"SealedContractError\"\n ? error.cause\n : error,\n });\n }\n}\n\nexport async function loadContract(\n scanDirectory: string,\n options: LoadContractOptions,\n): Promise<LoadedContract> {\n return (await loadContractWithScanDirectory(scanDirectory, options)).contract;\n}\n\nexport async function loadContractWithScanDirectory(\n scanDirectory: string,\n options: LoadContractOptions,\n): Promise<{ contract: LoadedContract; scanDirectory: string }> {\n return translateContractError(async () => {\n const helper = await contractHelper();\n const result = (await helper.loadSealedContract(scanDirectory, {\n pluginRoot: options.pluginRoot,\n expectedScanId: options.expectedScanId,\n signal: options.signal,\n })) as {\n contract: LoadedContract;\n scanDirectory: string;\n fileDigests: ReadonlyMap<string, string>;\n };\n if (options.expectation !== undefined)\n validateExpectation(\n result.contract.manifest,\n result.contract.mode,\n options.expectation,\n options.workbenchValidated === true,\n );\n validatedFileDigests.set(result.contract.manifest, result.fileDigests);\n return {\n contract: result.contract,\n scanDirectory: result.scanDirectory,\n };\n }, options.signal);\n}\n\nexport async function requireScanFile(\n scanDirectory: string,\n relativePath: string,\n context: string,\n signal?: AbortSignal,\n): Promise<string> {\n return translateContractError(\n async () =>\n (await contractHelper()).requireSealedScanFile(\n scanDirectory,\n relativePath,\n context,\n signal,\n ),\n signal,\n );\n}\n\nexport async function readScanFile(\n scanDirectory: string,\n relativePath: string,\n context: string,\n signal?: AbortSignal,\n): Promise<Buffer> {\n return translateContractError(\n async () =>\n (await contractHelper()).readSealedScanFile(\n scanDirectory,\n relativePath,\n context,\n signal,\n ),\n signal,\n );\n}\n\nexport function safeScopePath(value: string): string {\n try {\n return sharedSafeScopePath(value);\n } catch (error) {\n throw new ContractValidationError(\n error instanceof Error ? error.message : String(error),\n { cause: error },\n );\n }\n}\n\nfunction validateExpectation(\n manifest: ScanManifest,\n mode: LoadedContract[\"mode\"],\n expectation: ScanExpectation,\n workbenchValidated = false,\n): void {\n const scan = manifest.scan;\n if (scan.producer.name !== PRODUCER_NAME) {\n throw new ContractValidationError(\n `Manifest producer must be ${PRODUCER_NAME}, got ${scan.producer.name}.`,\n );\n }\n if (scan.producer.version !== expectation.pluginVersion) {\n throw new ContractValidationError(\n \"Manifest producer version does not match the installed Codex Security plugin.\",\n );\n }\n\n const expectedMode = expectedCoverageMode(\n expectation.target,\n expectation.mode,\n );\n if (mode !== expectedMode) {\n throw new ContractValidationError(\n `Coverage mode must be ${expectedMode}, got ${mode}.`,\n );\n }\n\n const requested = expectation.target;\n if (\n JSON.stringify(scan.scope.excludePaths) !==\n JSON.stringify(expectation.excludePaths ?? [])\n )\n throw new ContractValidationError(\n \"Manifest exclusions do not match the requested scan scope.\",\n );\n if (!workbenchValidated) {\n const target = scan.target;\n if (requested.kind === \"refs\" || requested.kind === \"working_tree\") {\n if (target.kind !== \"git_diff\") {\n throw new ContractValidationError(\n \"Diff scan manifest target must be git_diff.\",\n );\n }\n if (target.baseRevision !== requested.base) {\n throw new ContractValidationError(\n \"Diff scan base revision does not match the request.\",\n );\n }\n if (target.headRevision !== requested.head) {\n throw new ContractValidationError(\n \"Diff scan head revision does not match the request.\",\n );\n }\n } else if (target.kind === \"git_diff\") {\n throw new ContractValidationError(\n \"Repository scan manifest target must not be git_diff.\",\n );\n } else if (\n target.kind !== \"directory_snapshot\" &&\n expectation.repositoryRevision !== null &&\n target.revision !== expectation.repositoryRevision\n ) {\n throw new ContractValidationError(\n \"Scan target revision does not match the repository.\",\n );\n }\n }\n\n if (requested.kind === \"paths\") {\n const actualPaths = scan.scope.includePaths.map(safeScopePath);\n const actual = new Set(actualPaths);\n if (actualPaths.length === actual.size) {\n const expected = new Set(requested.paths);\n if (actual.size === expected.size && actual.isSubsetOf(expected)) return;\n }\n throw new ContractValidationError(\n \"Manifest include paths do not match the requested path target.\",\n );\n }\n}\n\nfunction expectedCoverageMode(\n target: NormalizedTarget,\n mode: ScanMode,\n): CoverageDocument[\"mode\"] {\n if (target.kind === \"paths\") return \"scoped_path\";\n if (target.kind === \"refs\") return \"branch_diff\";\n if (target.kind === \"working_tree\") return \"working_tree\";\n return mode === \"deep\" ? \"deep_repository\" : \"repository\";\n}\n\nexport async function sameCheckedFileDevice(\n file: FileHandle,\n checked: { path: string; metadata: Pick<Stats | BigIntStats, \"dev\" | \"ino\"> },\n opened: Pick<Stats | BigIntStats, \"dev\" | \"ino\">,\n platform: NodeJS.Platform = process.platform,\n openReference: (path: string, flags: number) => Promise<FileHandle> = open,\n): Promise<boolean> {\n if (opened.ino !== checked.metadata.ino) return false;\n if (opened.dev === checked.metadata.dev) return true;\n if (platform !== \"win32\") return false;\n\n const [openedIdentity, checkedIdentity] = await Promise.all([\n file.stat({ bigint: true }),\n lstat(checked.path, { bigint: true }),\n ]);\n if (\n !openedIdentity.isFile() ||\n !checkedIdentity.isFile() ||\n openedIdentity.ino !== checkedIdentity.ino\n ) {\n return false;\n }\n\n const reference = await openReference(\n checked.path,\n constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,\n );\n try {\n const referenceIdentity = await reference.stat({ bigint: true });\n return (\n referenceIdentity.isFile() &&\n openedIdentity.dev === referenceIdentity.dev &&\n openedIdentity.ino === referenceIdentity.ino\n );\n } finally {\n await reference.close();\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { ExternalFindings, ExternalSourceRepository } from "./external-findings.js";
2
+ export declare const crowdstrikeReportFormat = "crowdstrike-fcs-iac/v1";
3
+ /** Check repository claims, and that each finding's file is the scanned version in the selected checkout. */
4
+ export declare function crowdstrikeCheckout(input: ExternalFindings, declared: string | undefined, references: readonly ExternalSourceRepository[], repository: string): Promise<ExternalSourceRepository | undefined>;
5
+ /** Read a saved FCS CLI 4.x IaC JSON report. */
6
+ export declare function readCrowdStrikeFindings(path: string, sourceRepositoryUrl?: string): Promise<ExternalFindings>;
7
+ //# sourceMappingURL=crowdstrike-findings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crowdstrike-findings.d.ts","sourceRoot":"","sources":["../src/crowdstrike-findings.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,gBAAgB,EAChB,wBAAwB,EACzB,MAAM,wBAAwB,CAAC;AAsBhC,eAAO,MAAM,uBAAuB,2BAA2B,CAAC;AAgFhE,6GAA6G;AAC7G,wBAAsB,mBAAmB,CACvC,KAAK,EAAE,gBAAgB,EACvB,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,UAAU,EAAE,SAAS,wBAAwB,EAAE,EAC/C,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,CAmF/C;AAED,gDAAgD;AAChD,wBAAsB,uBAAuB,CAC3C,IAAI,EAAE,MAAM,EACZ,mBAAmB,CAAC,EAAE,MAAM,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAuG3B"}
@@ -0,0 +1,210 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { CodexSecurityError } from "./errors.js";
5
+ import { repositoryUrlKey, validateExternalEvidence, } from "./external-import-contract.js";
6
+ import { isGitHubCloudHost } from "./git-remote.js";
7
+ import { array, normalizeRecords, readScannerJson, record, repositoryFilePath, requiredText, scannerSeverity, stableId, text, } from "./scanner-import.js";
8
+ import { declaredScannerRepositoryUrl, validScannerRepositoryUrl, } from "./scanner-repository-url.js";
9
+ export const crowdstrikeReportFormat = "crowdstrike-fcs-iac/v1";
10
+ function joined(...values) {
11
+ return values.filter((value) => value !== null).join("\n\n") || null;
12
+ }
13
+ function positive(value) {
14
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0
15
+ ? value
16
+ : null;
17
+ }
18
+ // A git:: scan path without its ?ref= query. When the scanned URL has a user
19
+ // name, FCS writes each detection path after this prefix.
20
+ function gitScan(path) {
21
+ const value = text(path);
22
+ return value?.startsWith("git::") ? value.split("?", 1)[0] : undefined;
23
+ }
24
+ // The repository of an HTTPS git:: scan, without its //subdirectory. Checkouts
25
+ // fetch over HTTPS or SSH, which do not match an http:// URL.
26
+ function gitScanRepository(scan) {
27
+ const source = scan.slice("git::".length);
28
+ const scheme = /^https:\/\//iu.exec(source)?.[0];
29
+ if (!scheme)
30
+ return undefined;
31
+ const subdirectory = source.indexOf("//", scheme.length);
32
+ const url = subdirectory === -1 ? source : source.slice(0, subdirectory);
33
+ return validScannerRepositoryUrl(url, "local") ? url : undefined;
34
+ }
35
+ // FCS writes paths relative to its working directory. A git:: scan writes them
36
+ // from the scan root, after a slash or after the scan path.
37
+ function detectionPath(detection, scan) {
38
+ const raw = text(detection["file"]);
39
+ const relative = scan === undefined || !raw
40
+ ? raw
41
+ : raw.startsWith(`${scan}/`)
42
+ ? raw.slice(scan.length + 1)
43
+ : raw.replace(/^\//u, "");
44
+ const path = repositoryFilePath(relative);
45
+ if (!path)
46
+ throw new CodexSecurityError("CrowdStrike detection file must be checkout-relative. Run the FCS CLI from the checkout root.");
47
+ return path;
48
+ }
49
+ // A detection in a registry or Git module names the calling file, but its line
50
+ // is inside the module. FCS states the call line only in module_remediation.
51
+ // FCS writes the file, module source and calling file in one form, so compare them as written.
52
+ function detectionLine(detection) {
53
+ const line = positive(detection["line"]);
54
+ const file = text(detection["file"]);
55
+ const source = text(detection["module_source"]);
56
+ if (detection["is_from_module"] !== true ||
57
+ !file ||
58
+ !source ||
59
+ file.startsWith(`${source}/`))
60
+ return line;
61
+ // Search for this file's exact phrase; the remediation text comes from the report.
62
+ const remediation = text(detection["module_remediation"]) ?? "";
63
+ const marker = `called by ${file} at line `;
64
+ const start = remediation.indexOf(marker);
65
+ const call = start === -1
66
+ ? null
67
+ : /^\d+\b/u.exec(remediation.slice(start + marker.length));
68
+ return call ? positive(Number(call[0])) : null;
69
+ }
70
+ /** Check repository claims, and that each finding's file is the scanned version in the selected checkout. */
71
+ export async function crowdstrikeCheckout(input, declared, references, repository) {
72
+ if (input.report?.["format"] !== crowdstrikeReportFormat)
73
+ throw new CodexSecurityError("CrowdStrike imports require a report from the crowdstrike reader.");
74
+ // Only a declared URL binds the checkout to its fetch remotes. A git:: report's
75
+ // own repository is recorded and must agree with it.
76
+ const declarations = [
77
+ declared,
78
+ input.report["repositoryUrl"],
79
+ ...references.map(({ url }) => url),
80
+ ];
81
+ const reportScan = gitScan(input.report["git_scan"]);
82
+ const claims = [...declarations, reportScan && gitScanRepository(reportScan)];
83
+ const files = new Map();
84
+ for (const { evidence } of input.findings) {
85
+ validateExternalEvidence(evidence, "local");
86
+ const data = evidence.source_data;
87
+ if (data?.["format"] !== crowdstrikeReportFormat)
88
+ throw new CodexSecurityError("CrowdStrike findings must retain their native detection.");
89
+ const scan = gitScan(data["git_scan"]);
90
+ claims.push(data["repository_url"], evidence.details?.repository?.url, scan && gitScanRepository(scan));
91
+ // Check the retained detection's file, and that the shown location is the same.
92
+ const detection = record(data["detection"], "CrowdStrike detection");
93
+ const file = detectionPath(detection, scan);
94
+ const [location, ...others] = evidence.locations ?? [];
95
+ if (!location ||
96
+ others.length > 0 ||
97
+ location.path !== file ||
98
+ (location.line ?? null) !== detectionLine(detection))
99
+ throw new CodexSecurityError("CrowdStrike finding locations must match the native detection file and line.");
100
+ files.set(file, (files.get(file) ?? new Set()).add(detection["file_sha256"]));
101
+ }
102
+ const urls = claims
103
+ .filter((claim) => claim != null)
104
+ .map((claim) => declaredScannerRepositoryUrl(claim, "CrowdStrike", "local"));
105
+ if (new Set(urls.map((url) => repositoryUrlKey(url))).size > 1)
106
+ throw new CodexSecurityError("CrowdStrike findings name a different repository than --source-repository-url.");
107
+ // Paths are relative to where FCS ran, so a missing file means a different root or checkout.
108
+ // FCS follows file symlinks and records each file's SHA-256; another version gives stale lines.
109
+ for (const [file, hashes] of files) {
110
+ const path = join(repository, ...file.split("/"));
111
+ if (!(await stat(path).catch(() => null))?.isFile())
112
+ throw new CodexSecurityError(`${JSON.stringify(file)} is not in ${JSON.stringify(repository)}. Select the checkout that FCS scanned, and run the FCS CLI from its root.`);
113
+ const hash = createHash("sha256")
114
+ .update(await readFile(path))
115
+ .digest("hex");
116
+ if ([...hashes].some((expected) => expected !== hash))
117
+ throw new CodexSecurityError(`${JSON.stringify(file)} changed after the FCS scan. Select a checkout of the scanned commit, or scan again.`);
118
+ }
119
+ const url = urls[0];
120
+ if (url === undefined || declarations.every((claim) => claim == null))
121
+ return undefined;
122
+ const { hostname } = new URL(url);
123
+ return {
124
+ url,
125
+ platform: isGitHubCloudHost(hostname)
126
+ ? "github"
127
+ : hostname === "gitlab.com"
128
+ ? "gitlab"
129
+ : undefined,
130
+ };
131
+ }
132
+ /** Read a saved FCS CLI 4.x IaC JSON report. */
133
+ export async function readCrowdStrikeFindings(path, sourceRepositoryUrl) {
134
+ const document = record(await readScannerJson(path), "CrowdStrike report");
135
+ if (!Array.isArray(document["rule_detections"]))
136
+ throw new CodexSecurityError("Expected an FCS CLI 4.x IaC JSON report with rule_detections.");
137
+ const version = text(document["fcs_version"]);
138
+ const scan = gitScan(document["path"]);
139
+ const declared = sourceRepositoryUrl === undefined
140
+ ? undefined
141
+ : declaredScannerRepositoryUrl(sourceRepositoryUrl, "CrowdStrike", "local");
142
+ // A git:: report names the repository that FCS cloned.
143
+ const repositoryUrl = declared ?? (scan && gitScanRepository(scan));
144
+ const entries = array(document["rule_detections"], "CrowdStrike rule_detections").flatMap((value) => {
145
+ const { detections, ...rule } = record(value, "CrowdStrike rule");
146
+ return array(detections ?? [], "CrowdStrike detections").map((detection) => ({
147
+ rule,
148
+ detection: record(detection, "CrowdStrike detection"),
149
+ }));
150
+ });
151
+ return normalizeRecords(entries, ({ rule, detection }) => {
152
+ const kind = rule["rule_category"] === "Secret Management" ? "secret" : "iac";
153
+ const reason = text(detection["reason"]);
154
+ const recommendation = text(detection["recommendation"]);
155
+ const file = detectionPath(detection, scan);
156
+ return validateExternalEvidence({
157
+ title: requiredText(rule["rule_name"], "CrowdStrike rule_name"),
158
+ severity: scannerSeverity(text(rule["severity"])?.toLowerCase()),
159
+ description: joined(text(rule["description"]), reason),
160
+ locations: [{ path: file, line: detectionLine(detection) }],
161
+ source_scan_id: text(document["scan_uuid"]),
162
+ // Typed IaC and secret details must name their source repository.
163
+ details: repositoryUrl && {
164
+ kind,
165
+ repository: { url: repositoryUrl },
166
+ rule: {
167
+ id: text(rule["rule_uuid"]),
168
+ name: text(rule["rule_name"]),
169
+ },
170
+ configuration: kind === "iac"
171
+ ? {
172
+ platform: text(rule["platform"]),
173
+ cloud_platform: text(rule["cloud_provider"]),
174
+ expected: recommendation,
175
+ actual: reason,
176
+ }
177
+ : null,
178
+ remediation_instructions: joined(recommendation, text(detection["module_remediation"])),
179
+ scanner_origin: version
180
+ ? `CrowdStrike FCS CLI ${version}`
181
+ : "CrowdStrike FCS CLI",
182
+ },
183
+ source_data: structuredClone({
184
+ format: crowdstrikeReportFormat,
185
+ fcs_version: version,
186
+ ...(repositoryUrl && { repository_url: repositoryUrl }),
187
+ ...(scan !== undefined && { git_scan: scan }),
188
+ rule,
189
+ detection,
190
+ }),
191
+ }, "local");
192
+ }, ({ rule, detection }) => stableId("crowdstrike", [
193
+ requiredText(rule["rule_uuid"], "CrowdStrike rule_uuid"),
194
+ detectionPath(detection, scan),
195
+ positive(detection["line"]),
196
+ detection["resource_type"] ?? null,
197
+ detection["resource_name"] ?? null,
198
+ detection["reason"] ?? null,
199
+ detection["module_path"] ?? null,
200
+ ]), "local", {
201
+ report: {
202
+ format: crowdstrikeReportFormat,
203
+ ...(declared && { repositoryUrl: declared }),
204
+ ...(scan !== undefined && { git_scan: scan }),
205
+ fcs_version: version,
206
+ scan_uuid: text(document["scan_uuid"]),
207
+ },
208
+ });
209
+ }
210
+ //# sourceMappingURL=crowdstrike-findings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crowdstrike-findings.js","sourceRoot":"","sources":["../src/crowdstrike-findings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAKjD,OAAO,EACL,gBAAgB,EAChB,wBAAwB,GACzB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EACL,KAAK,EACL,gBAAgB,EAChB,eAAe,EACf,MAAM,EACN,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,QAAQ,EACR,IAAI,GACL,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,6BAA6B,CAAC;AAErC,MA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C,MAAM,CAAC,CAAC;QAC3B,SAAS,CAAC,eAAe,CAAC,IAAI,IAAI;QAClC,SAAS,CAAC,eAAe,CAAC,IAAI,IAAI;QAClC,SAAS,CAAC,QAAQ,CAAC,IAAI,IAAI;QAC3B,SAAS,CAAC,aAAa,CAAC,IAAI,IAAI;KACjC,CAAC,EACJ,OAAO,EACP;QACE,MAAM,EAAE;YACN,MAAM,EAAE,uBAAuB;YAC/B,GAAG,CAAC,QAAQ,IAAI,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC;YAC5C,GAAG,CAAC,IAAI,KAAK,SAAS,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;YAC7C,WAAW,EAAE,OAAO;YACpB,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;SACvC;KACF,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { CodexSecurityError } from \"./errors.js\";\nimport type {\n ExternalFindings,\n ExternalSourceRepository,\n} from \"./external-findings.js\";\nimport {\n repositoryUrlKey,\n validateExternalEvidence,\n} from \"./external-import-contract.js\";\nimport { isGitHubCloudHost } from \"./git-remote.js\";\nimport {\n array,\n normalizeRecords,\n readScannerJson,\n record,\n repositoryFilePath,\n requiredText,\n scannerSeverity,\n stableId,\n text,\n} from \"./scanner-import.js\";\nimport {\n declaredScannerRepositoryUrl,\n validScannerRepositoryUrl,\n} from \"./scanner-repository-url.js\";\n\nexport const crowdstrikeReportFormat = \"crowdstrike-fcs-iac/v1\";\n\ntype NativeRecord = Record<string, unknown>;\n\ninterface Entry {\n rule: NativeRecord;\n detection: NativeRecord;\n}\n\nfunction joined(...values: (string | null)[]): string | null {\n return values.filter((value) => value !== null).join(\"\\n\\n\") || null;\n}\n\nfunction positive(value: unknown): number | null {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0\n ? value\n : null;\n}\n\n// A git:: scan path without its ?ref= query. When the scanned URL has a user\n// name, FCS writes each detection path after this prefix.\nfunction gitScan(path: unknown): string | undefined {\n const value = text(path);\n return value?.startsWith(\"git::\") ? value.split(\"?\", 1)[0] : undefined;\n}\n\n// The repository of an HTTPS git:: scan, without its //subdirectory. Checkouts\n// fetch over HTTPS or SSH, which do not match an http:// URL.\nfunction gitScanRepository(scan: string): string | undefined {\n const source = scan.slice(\"git::\".length);\n const scheme = /^https:\\/\\//iu.exec(source)?.[0];\n if (!scheme) return undefined;\n const subdirectory = source.indexOf(\"//\", scheme.length);\n const url = subdirectory === -1 ? source : source.slice(0, subdirectory);\n return validScannerRepositoryUrl(url, \"local\") ? url : undefined;\n}\n\n// FCS writes paths relative to its working directory. A git:: scan writes them\n// from the scan root, after a slash or after the scan path.\nfunction detectionPath(detection: NativeRecord, scan: string | undefined) {\n const raw = text(detection[\"file\"]);\n const relative =\n scan === undefined || !raw\n ? raw\n : raw.startsWith(`${scan}/`)\n ? raw.slice(scan.length + 1)\n : raw.replace(/^\\//u, \"\");\n const path = repositoryFilePath(relative);\n if (!path)\n throw new CodexSecurityError(\n \"CrowdStrike detection file must be checkout-relative. Run the FCS CLI from the checkout root.\",\n );\n return path;\n}\n\n// A detection in a registry or Git module names the calling file, but its line\n// is inside the module. FCS states the call line only in module_remediation.\n// FCS writes the file, module source and calling file in one form, so compare them as written.\nfunction detectionLine(detection: NativeRecord): number | null {\n const line = positive(detection[\"line\"]);\n const file = text(detection[\"file\"]);\n const source = text(detection[\"module_source\"]);\n if (\n detection[\"is_from_module\"] !== true ||\n !file ||\n !source ||\n file.startsWith(`${source}/`)\n )\n return line;\n // Search for this file's exact phrase; the remediation text comes from the report.\n const remediation = text(detection[\"module_remediation\"]) ?? \"\";\n const marker = `called by ${file} at line `;\n const start = remediation.indexOf(marker);\n const call =\n start === -1\n ? null\n : /^\\d+\\b/u.exec(remediation.slice(start + marker.length));\n return call ? positive(Number(call[0])) : null;\n}\n\n/** Check repository claims, and that each finding's file is the scanned version in the selected checkout. */\nexport async function crowdstrikeCheckout(\n input: ExternalFindings,\n declared: string | undefined,\n references: readonly ExternalSourceRepository[],\n repository: string,\n): Promise<ExternalSourceRepository | undefined> {\n if (input.report?.[\"format\"] !== crowdstrikeReportFormat)\n throw new CodexSecurityError(\n \"CrowdStrike imports require a report from the crowdstrike reader.\",\n );\n // Only a declared URL binds the checkout to its fetch remotes. A git:: report's\n // own repository is recorded and must agree with it.\n const declarations: unknown[] = [\n declared,\n input.report[\"repositoryUrl\"],\n ...references.map(({ url }) => url),\n ];\n const reportScan = gitScan(input.report[\"git_scan\"]);\n const claims = [...declarations, reportScan && gitScanRepository(reportScan)];\n const files = new Map<string, Set<unknown>>();\n for (const { evidence } of input.findings) {\n validateExternalEvidence(evidence, \"local\");\n const data = evidence.source_data;\n if (data?.[\"format\"] !== crowdstrikeReportFormat)\n throw new CodexSecurityError(\n \"CrowdStrike findings must retain their native detection.\",\n );\n const scan = gitScan(data[\"git_scan\"]);\n claims.push(\n data[\"repository_url\"],\n evidence.details?.repository?.url,\n scan && gitScanRepository(scan),\n );\n // Check the retained detection's file, and that the shown location is the same.\n const detection = record(data[\"detection\"], \"CrowdStrike detection\");\n const file = detectionPath(detection, scan);\n const [location, ...others] = evidence.locations ?? [];\n if (\n !location ||\n others.length > 0 ||\n location.path !== file ||\n (location.line ?? null) !== detectionLine(detection)\n )\n throw new CodexSecurityError(\n \"CrowdStrike finding locations must match the native detection file and line.\",\n );\n files.set(\n file,\n (files.get(file) ?? new Set()).add(detection[\"file_sha256\"]),\n );\n }\n const urls = claims\n .filter((claim) => claim != null)\n .map((claim) =>\n declaredScannerRepositoryUrl(claim, \"CrowdStrike\", \"local\"),\n );\n if (new Set(urls.map((url) => repositoryUrlKey(url))).size > 1)\n throw new CodexSecurityError(\n \"CrowdStrike findings name a different repository than --source-repository-url.\",\n );\n // Paths are relative to where FCS ran, so a missing file means a different root or checkout.\n // FCS follows file symlinks and records each file's SHA-256; another version gives stale lines.\n for (const [file, hashes] of files) {\n const path = join(repository, ...file.split(\"/\"));\n if (!(await stat(path).catch(() => null))?.isFile())\n throw new CodexSecurityError(\n `${JSON.stringify(file)} is not in ${JSON.stringify(repository)}. Select the checkout that FCS scanned, and run the FCS CLI from its root.`,\n );\n const hash = createHash(\"sha256\")\n .update(await readFile(path))\n .digest(\"hex\");\n if ([...hashes].some((expected) => expected !== hash))\n throw new CodexSecurityError(\n `${JSON.stringify(file)} changed after the FCS scan. Select a checkout of the scanned commit, or scan again.`,\n );\n }\n const url = urls[0];\n if (url === undefined || declarations.every((claim) => claim == null))\n return undefined;\n const { hostname } = new URL(url);\n return {\n url,\n platform: isGitHubCloudHost(hostname)\n ? \"github\"\n : hostname === \"gitlab.com\"\n ? \"gitlab\"\n : undefined,\n };\n}\n\n/** Read a saved FCS CLI 4.x IaC JSON report. */\nexport async function readCrowdStrikeFindings(\n path: string,\n sourceRepositoryUrl?: string,\n): Promise<ExternalFindings> {\n const document = record(await readScannerJson(path), \"CrowdStrike report\");\n if (!Array.isArray(document[\"rule_detections\"]))\n throw new CodexSecurityError(\n \"Expected an FCS CLI 4.x IaC JSON report with rule_detections.\",\n );\n const version = text(document[\"fcs_version\"]);\n const scan = gitScan(document[\"path\"]);\n const declared =\n sourceRepositoryUrl === undefined\n ? undefined\n : declaredScannerRepositoryUrl(\n sourceRepositoryUrl,\n \"CrowdStrike\",\n \"local\",\n );\n // A git:: report names the repository that FCS cloned.\n const repositoryUrl = declared ?? (scan && gitScanRepository(scan));\n const entries: Entry[] = array(\n document[\"rule_detections\"],\n \"CrowdStrike rule_detections\",\n ).flatMap((value) => {\n const { detections, ...rule } = record(value, \"CrowdStrike rule\");\n return array(detections ?? [], \"CrowdStrike detections\").map(\n (detection) => ({\n rule,\n detection: record(detection, \"CrowdStrike detection\"),\n }),\n );\n });\n return normalizeRecords(\n entries,\n ({ rule, detection }) => {\n const kind =\n rule[\"rule_category\"] === \"Secret Management\" ? \"secret\" : \"iac\";\n const reason = text(detection[\"reason\"]);\n const recommendation = text(detection[\"recommendation\"]);\n const file = detectionPath(detection, scan);\n return validateExternalEvidence(\n {\n title: requiredText(rule[\"rule_name\"], \"CrowdStrike rule_name\"),\n severity: scannerSeverity(text(rule[\"severity\"])?.toLowerCase()),\n description: joined(text(rule[\"description\"]), reason),\n locations: [{ path: file, line: detectionLine(detection) }],\n source_scan_id: text(document[\"scan_uuid\"]),\n // Typed IaC and secret details must name their source repository.\n details: repositoryUrl && {\n kind,\n repository: { url: repositoryUrl },\n rule: {\n id: text(rule[\"rule_uuid\"]),\n name: text(rule[\"rule_name\"]),\n },\n configuration:\n kind === \"iac\"\n ? {\n platform: text(rule[\"platform\"]),\n cloud_platform: text(rule[\"cloud_provider\"]),\n expected: recommendation,\n actual: reason,\n }\n : null,\n remediation_instructions: joined(\n recommendation,\n text(detection[\"module_remediation\"]),\n ),\n scanner_origin: version\n ? `CrowdStrike FCS CLI ${version}`\n : \"CrowdStrike FCS CLI\",\n },\n source_data: structuredClone({\n format: crowdstrikeReportFormat,\n fcs_version: version,\n ...(repositoryUrl && { repository_url: repositoryUrl }),\n ...(scan !== undefined && { git_scan: scan }),\n rule,\n detection,\n }),\n },\n \"local\",\n );\n },\n ({ rule, detection }) =>\n stableId(\"crowdstrike\", [\n requiredText(rule[\"rule_uuid\"], \"CrowdStrike rule_uuid\"),\n detectionPath(detection, scan),\n positive(detection[\"line\"]),\n detection[\"resource_type\"] ?? null,\n detection[\"resource_name\"] ?? null,\n detection[\"reason\"] ?? null,\n detection[\"module_path\"] ?? null,\n ]),\n \"local\",\n {\n report: {\n format: crowdstrikeReportFormat,\n ...(declared && { repositoryUrl: declared }),\n ...(scan !== undefined && { git_scan: scan }),\n fcs_version: version,\n scan_uuid: text(document[\"scan_uuid\"]),\n },\n },\n );\n}\n"]}