@openai/codex-security 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/README.md +45 -9
  2. package/_bundled_plugin/.codex-plugin/plugin.json +5 -5
  3. package/_bundled_plugin/.mcp.json +1 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +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/permission-profile-preflight.mjs +13 -20
  8. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  9. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  10. package/_bundled_plugin/references/core-scan.md +2 -0
  11. package/_bundled_plugin/references/final-report.md +5 -1
  12. package/_bundled_plugin/references/investigation-time-budget.md +11 -0
  13. package/_bundled_plugin/references/sarif-adapter.md +1 -0
  14. package/_bundled_plugin/references/scan-prologue.md +2 -6
  15. package/_bundled_plugin/references/scan-runtime.md +15 -0
  16. package/_bundled_plugin/references/threat-model.md +2 -0
  17. package/_bundled_plugin/schemas/coverage.schema.json +45 -126
  18. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +5 -1
  19. package/_bundled_plugin/schemas/findings.schema.json +140 -427
  20. package/_bundled_plugin/schemas/patch-risk-assessment.schema.json +106 -119
  21. package/_bundled_plugin/schemas/scan-manifest.schema.json +73 -188
  22. package/_bundled_plugin/scripts/deep_scan_workbench.py +7 -0
  23. package/_bundled_plugin/scripts/finalize_scan_contract.py +87 -49
  24. package/_bundled_plugin/scripts/finding_preview.py +5 -3
  25. package/_bundled_plugin/scripts/generate_rank_input.py +26 -106
  26. package/_bundled_plugin/scripts/launch_codex_security_mcp +39 -4
  27. package/_bundled_plugin/scripts/report_projection.py +35 -13
  28. package/_bundled_plugin/scripts/snapshot_sqlite.py +7 -0
  29. package/_bundled_plugin/scripts/windows_scan_local_files.py +43 -1
  30. package/_bundled_plugin/scripts/workbench_cli.py +9 -9
  31. package/_bundled_plugin/scripts/workbench_constants.py +4 -0
  32. package/_bundled_plugin/scripts/workbench_db.py +103 -45
  33. package/_bundled_plugin/scripts/workbench_progress.py +0 -50
  34. package/_bundled_plugin/scripts/workbench_publication.py +216 -247
  35. package/_bundled_plugin/scripts/workbench_scan_history.py +3 -2
  36. package/_bundled_plugin/scripts/workbench_scan_start.py +12 -4
  37. package/_bundled_plugin/scripts/workbench_scan_usage.py +360 -37
  38. package/_bundled_plugin/scripts/workbench_schema.py +1 -1
  39. package/_bundled_plugin/scripts/workbench_source_excerpt.py +74 -51
  40. package/_bundled_plugin/scripts/workbench_source_scopes.py +388 -0
  41. package/_bundled_plugin/scripts/workbench_target.py +7 -5
  42. package/_bundled_plugin/scripts/workbench_validation.py +52 -2
  43. package/_bundled_plugin/shared/workbench-history-repairs.json +19 -0
  44. package/_bundled_plugin/shared/workbench-migrations.json +22 -0
  45. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +1 -1
  46. package/_bundled_plugin/skills/deep-security-scan/agents/openai.yaml +1 -1
  47. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +4 -2
  48. package/_bundled_plugin/skills/security-diff-scan/agents/openai.yaml +1 -1
  49. package/_bundled_plugin/skills/security-scan/SKILL.md +4 -2
  50. package/_bundled_plugin/skills/security-scan/agents/openai.yaml +1 -1
  51. package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +3 -3
  52. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +2 -0
  53. package/_bundled_plugin/skills/track-findings/SKILL.md +8 -4
  54. package/_bundled_plugin/skills/track-findings/agents/openai.yaml +1 -1
  55. package/_bundled_plugin/skills/track-findings/references/github-security-advisories.md +1 -1
  56. package/dist/api.d.ts +6 -2
  57. package/dist/api.d.ts.map +1 -1
  58. package/dist/api.js +266 -39
  59. package/dist/api.js.map +1 -1
  60. package/dist/artifact-export.d.ts +2 -1
  61. package/dist/artifact-export.d.ts.map +1 -1
  62. package/dist/artifact-export.js +38 -23
  63. package/dist/artifact-export.js.map +1 -1
  64. package/dist/classify-severity-records.d.ts +76 -0
  65. package/dist/classify-severity-records.d.ts.map +1 -0
  66. package/dist/classify-severity-records.js +141 -0
  67. package/dist/classify-severity-records.js.map +1 -0
  68. package/dist/classify-severity.d.ts +1 -23
  69. package/dist/classify-severity.d.ts.map +1 -1
  70. package/dist/classify-severity.js +3 -24
  71. package/dist/classify-severity.js.map +1 -1
  72. package/dist/cli-help.d.ts.map +1 -1
  73. package/dist/cli-help.js +2 -0
  74. package/dist/cli-help.js.map +1 -1
  75. package/dist/cli.d.ts +4 -2
  76. package/dist/cli.d.ts.map +1 -1
  77. package/dist/cli.js +148 -149
  78. package/dist/cli.js.map +1 -1
  79. package/dist/cloud-publish.js +1 -1
  80. package/dist/cloud-publish.js.map +1 -1
  81. package/dist/codex-sdk-environment.js +1 -1
  82. package/dist/codex-sdk-environment.js.map +1 -1
  83. package/dist/component-plan.js +1 -1
  84. package/dist/component-plan.js.map +1 -1
  85. package/dist/component-scan.d.ts.map +1 -1
  86. package/dist/component-scan.js +5 -4
  87. package/dist/component-scan.js.map +1 -1
  88. package/dist/config.d.ts +12 -0
  89. package/dist/config.d.ts.map +1 -1
  90. package/dist/config.js +10 -4
  91. package/dist/config.js.map +1 -1
  92. package/dist/contract.d.ts +6 -0
  93. package/dist/contract.d.ts.map +1 -1
  94. package/dist/contract.js +69 -20
  95. package/dist/contract.js.map +1 -1
  96. package/dist/cost-model.d.ts.map +1 -1
  97. package/dist/cost-model.js +7 -2
  98. package/dist/cost-model.js.map +1 -1
  99. package/dist/custom-validation-prompt.js +3 -3
  100. package/dist/custom-validation-prompt.js.map +1 -1
  101. package/dist/deduplication/codex-review.d.ts +1 -5
  102. package/dist/deduplication/codex-review.d.ts.map +1 -1
  103. package/dist/deduplication/codex-review.js +2 -2
  104. package/dist/deduplication/codex-review.js.map +1 -1
  105. package/dist/deduplication/deduplication-prompts.d.ts +1 -1
  106. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  107. package/dist/deduplication/deduplication-prompts.js +2 -2
  108. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  109. package/dist/deduplication/deduplication-reviewer.d.ts +1 -1
  110. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  111. package/dist/deduplication/deduplication-reviewer.js +1 -1
  112. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  113. package/dist/deduplication/records-protocol.d.ts +3 -8
  114. package/dist/deduplication/records-protocol.d.ts.map +1 -1
  115. package/dist/deduplication/records-protocol.js +11 -171
  116. package/dist/deduplication/records-protocol.js.map +1 -1
  117. package/dist/deduplication/records.js +1 -1
  118. package/dist/deduplication/records.js.map +1 -1
  119. package/dist/deduplication/scan.d.ts.map +1 -1
  120. package/dist/deduplication/scan.js +10 -9
  121. package/dist/deduplication/scan.js.map +1 -1
  122. package/dist/deep-config.d.ts +4 -1
  123. package/dist/deep-config.d.ts.map +1 -1
  124. package/dist/deep-config.js +21 -1
  125. package/dist/deep-config.js.map +1 -1
  126. package/dist/deep-progress.d.ts +15 -1
  127. package/dist/deep-progress.d.ts.map +1 -1
  128. package/dist/deep-progress.js +15 -16
  129. package/dist/deep-progress.js.map +1 -1
  130. package/dist/executable-path.d.ts +2 -0
  131. package/dist/executable-path.d.ts.map +1 -0
  132. package/dist/executable-path.js +12 -0
  133. package/dist/executable-path.js.map +1 -0
  134. package/dist/feedback.d.ts +1 -4
  135. package/dist/feedback.d.ts.map +1 -1
  136. package/dist/feedback.js +1 -1
  137. package/dist/feedback.js.map +1 -1
  138. package/dist/findings-import.d.ts +1 -1
  139. package/dist/findings-import.d.ts.map +1 -1
  140. package/dist/findings-import.js +3 -3
  141. package/dist/findings-import.js.map +1 -1
  142. package/dist/git-remote.d.ts +10 -0
  143. package/dist/git-remote.d.ts.map +1 -0
  144. package/dist/git-remote.js +24 -0
  145. package/dist/git-remote.js.map +1 -0
  146. package/dist/github.d.ts.map +1 -1
  147. package/dist/github.js +5 -7
  148. package/dist/github.js.map +1 -1
  149. package/dist/host-protocol.d.ts +19 -0
  150. package/dist/host-protocol.d.ts.map +1 -0
  151. package/dist/host-protocol.js +270 -0
  152. package/dist/host-protocol.js.map +1 -0
  153. package/dist/host-records-protocol.d.ts +15 -0
  154. package/dist/host-records-protocol.d.ts.map +1 -0
  155. package/dist/host-records-protocol.js +15 -0
  156. package/dist/host-records-protocol.js.map +1 -0
  157. package/dist/hosted-scan-protocol.d.ts +4 -0
  158. package/dist/hosted-scan-protocol.d.ts.map +1 -0
  159. package/dist/hosted-scan-protocol.js +25 -0
  160. package/dist/hosted-scan-protocol.js.map +1 -0
  161. package/dist/hosted-scan.d.ts +112 -0
  162. package/dist/hosted-scan.d.ts.map +1 -0
  163. package/dist/hosted-scan.js +260 -0
  164. package/dist/hosted-scan.js.map +1 -0
  165. package/dist/index.d.ts +7 -0
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.js +3 -0
  168. package/dist/index.js.map +1 -1
  169. package/dist/knowledge-base.d.ts.map +1 -1
  170. package/dist/knowledge-base.js +87 -7
  171. package/dist/knowledge-base.js.map +1 -1
  172. package/dist/multiscan.d.ts.map +1 -1
  173. package/dist/multiscan.js +108 -36
  174. package/dist/multiscan.js.map +1 -1
  175. package/dist/patch-publication.d.ts +26 -0
  176. package/dist/patch-publication.d.ts.map +1 -0
  177. package/dist/patch-publication.js +105 -0
  178. package/dist/patch-publication.js.map +1 -0
  179. package/dist/patch-tui.d.ts.map +1 -1
  180. package/dist/patch-tui.js +4 -1
  181. package/dist/patch-tui.js.map +1 -1
  182. package/dist/project-config-schema.d.ts +2 -0
  183. package/dist/project-config-schema.d.ts.map +1 -1
  184. package/dist/project-config-schema.js +1 -0
  185. package/dist/project-config-schema.js.map +1 -1
  186. package/dist/project-config.d.ts +1 -0
  187. package/dist/project-config.d.ts.map +1 -1
  188. package/dist/project-config.js +16 -6
  189. package/dist/project-config.js.map +1 -1
  190. package/dist/publication-store.d.ts.map +1 -1
  191. package/dist/publication-store.js +73 -63
  192. package/dist/publication-store.js.map +1 -1
  193. package/dist/publication.d.ts +0 -2
  194. package/dist/publication.d.ts.map +1 -1
  195. package/dist/publication.js +135 -24
  196. package/dist/publication.js.map +1 -1
  197. package/dist/publish.d.ts.map +1 -1
  198. package/dist/publish.js +39 -25
  199. package/dist/publish.js.map +1 -1
  200. package/dist/runtime.d.ts +5 -2
  201. package/dist/runtime.d.ts.map +1 -1
  202. package/dist/runtime.js +86 -58
  203. package/dist/runtime.js.map +1 -1
  204. package/dist/scan-executor.d.ts +104 -0
  205. package/dist/scan-executor.d.ts.map +1 -0
  206. package/dist/scan-executor.js +62 -0
  207. package/dist/scan-executor.js.map +1 -0
  208. package/dist/scan-settings.d.ts +1 -0
  209. package/dist/scan-settings.d.ts.map +1 -1
  210. package/dist/scan-settings.js +7 -1
  211. package/dist/scan-settings.js.map +1 -1
  212. package/dist/scan-time-budget.d.ts +9 -0
  213. package/dist/scan-time-budget.d.ts.map +1 -0
  214. package/dist/scan-time-budget.js +16 -0
  215. package/dist/scan-time-budget.js.map +1 -0
  216. package/dist/severity-review.d.ts +29 -0
  217. package/dist/severity-review.d.ts.map +1 -0
  218. package/dist/severity-review.js +47 -0
  219. package/dist/severity-review.js.map +1 -0
  220. package/dist/targets.d.ts.map +1 -1
  221. package/dist/targets.js +17 -25
  222. package/dist/targets.js.map +1 -1
  223. package/dist/validation-records.d.ts +38 -0
  224. package/dist/validation-records.d.ts.map +1 -0
  225. package/dist/validation-records.js +76 -0
  226. package/dist/validation-records.js.map +1 -0
  227. package/dist/version.d.ts.map +1 -1
  228. package/dist/version.js +4 -2
  229. package/dist/version.js.map +1 -1
  230. package/dist/worker-progress.d.ts +43 -15
  231. package/dist/worker-progress.d.ts.map +1 -1
  232. package/dist/worker-progress.js +22 -80
  233. package/dist/worker-progress.js.map +1 -1
  234. package/docs/classify-severity-records.md +89 -0
  235. package/docs/cli.md +281 -35
  236. package/docs/hosted-scans.md +242 -0
  237. package/docs/validate-records.md +69 -0
  238. package/package.json +18 -14
  239. package/schemas/hosted-scan-v2.fixture.json +145 -0
  240. package/schemas/project-config.schema.json +7 -1
  241. package/_bundled_plugin/preflight/capability-profiles.toml +0 -76
  242. package/_bundled_plugin/references/config-preflight.md +0 -93
  243. package/_bundled_plugin/references/desktop-config-preflight.md +0 -11
  244. package/_bundled_plugin/scripts/config_preflight.py +0 -911
@@ -1,10 +1,11 @@
1
- """Validate, record, and export findings from completed scans."""
1
+ """Validate, record, and export findings from sealed scans."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
5
  import argparse
6
6
  import csv
7
7
  import io
8
+ import json
8
9
  import os
9
10
  import sqlite3
10
11
  import sys
@@ -26,88 +27,50 @@ from finalize_scan_contract import (
26
27
  write_export_output,
27
28
  write_sarif_projection,
28
29
  )
30
+ from validate_scan_contract import validate_contract
29
31
 
30
32
 
31
- def linear_publication_input(
32
- payload: dict[str, Any],
33
- *,
34
- recording: bool,
35
- ) -> tuple[dict[str, Any], dict[str, str], list[dict[str, str]]]:
36
- required = {"scanId", "scanDirectory", "destination", "findings"}
37
- if recording:
38
- required.add("publications")
39
- if set(payload) != required:
40
- raise SystemExit("Linear publication input contains unexpected or missing fields.")
41
-
42
- scan_id = payload["scanId"]
43
- scan_directory = payload["scanDirectory"]
44
- destination = payload["destination"]
45
- findings = payload["findings"]
46
- if not isinstance(scan_id, str) or not isinstance(scan_directory, str):
47
- raise SystemExit("Linear publication input must identify the exact completed scan.")
48
- if (
49
- not isinstance(destination, dict)
50
- or not {"type", "teamId"}.issubset(destination)
51
- or not set(destination).issubset({"type", "teamId", "projectId"})
52
- or destination.get("type") != "linear"
53
- or not isinstance(destination.get("teamId"), str)
54
- or not destination["teamId"].strip()
55
- or (
56
- "projectId" in destination
57
- and (
58
- not isinstance(destination["projectId"], str)
59
- or not destination["projectId"].strip()
60
- )
61
- )
62
- ):
63
- raise SystemExit(
64
- "Linear publication input must identify the exact team and optional project."
65
- )
66
- if not isinstance(findings, list):
67
- raise SystemExit("Linear publication input must include the planned scan findings.")
68
-
69
- seen_finding_ids: set[str] = set()
70
- seen_occurrence_ids: set[str] = set()
71
- for finding in findings:
72
- if (
73
- not isinstance(finding, dict)
74
- or set(finding) != {"findingId", "occurrenceId"}
75
- or not isinstance(finding.get("findingId"), str)
76
- or not finding["findingId"].strip()
77
- or not isinstance(finding.get("occurrenceId"), str)
78
- or not finding["occurrenceId"].strip()
79
- ):
80
- raise SystemExit("Linear publication input contains an invalid finding identity.")
81
- if (
82
- finding["findingId"] in seen_finding_ids
83
- or finding["occurrenceId"] in seen_occurrence_ids
84
- ):
85
- raise SystemExit("Linear publication input repeats a finding or occurrence.")
86
- seen_finding_ids.add(finding["findingId"])
87
- seen_occurrence_ids.add(finding["occurrenceId"])
88
-
89
- return payload, destination, findings
33
+ def destination_key(destination: Any) -> str:
34
+ if not isinstance(destination, dict):
35
+ raise SystemExit("Finding issues require an exact tracker destination.")
36
+ kind = destination.get("type")
37
+ if kind == "linear":
38
+ required, optional = {"type", "teamId"}, {"projectId"}
39
+ parts = [kind, destination.get("teamId"), destination.get("projectId")]
40
+ elif kind == "jira":
41
+ required, optional = {"type", "cloudId", "projectId"}, set()
42
+ parts = [kind, destination.get("cloudId"), destination.get("projectId")]
43
+ elif kind in {"github-issue", "github-advisory"}:
44
+ required, optional = {"type", "hostname", "repository"}, set()
45
+ parts = [kind, destination.get("hostname"), destination.get("repository")]
46
+ else:
47
+ raise SystemExit("Unsupported finding issue destination.")
48
+ if not required.issubset(destination) or not set(destination).issubset(required | optional):
49
+ raise SystemExit("Finding issues require the exact provider destination fields.")
50
+ if any(not isinstance(value, str) or not value.strip() for value in destination.values()):
51
+ raise SystemExit("Finding issue destination fields must be nonempty strings.")
52
+ return json.dumps(parts, ensure_ascii=False, separators=(",", ":"))
90
53
 
91
54
 
92
- def verify_linear_publication_scan(
55
+ def verify_publication_history(
93
56
  db: Any,
94
57
  connection: sqlite3.Connection,
95
- payload: dict[str, Any],
96
- findings: list[dict[str, str]],
97
- ) -> sqlite3.Row:
58
+ scan_id: str,
59
+ scan_directory: str,
60
+ findings: list[dict[str, Any]],
61
+ ) -> None:
98
62
  try:
99
- scan = db.require_scan(connection, payload["scanId"])
63
+ scan = db.require_scan(connection, scan_id)
100
64
  except SystemExit as exc:
101
65
  raise SystemExit(
102
66
  "The completed scan is not present in the local Codex Security scan-history database. "
103
67
  "Use the state directory where the scan was completed."
104
68
  ) from exc
105
- if scan["id"] != payload["scanId"]:
106
- raise SystemExit("Linear publication must use the exact completed scan identifier.")
69
+ if scan["id"] != scan_id:
70
+ raise SystemExit("Publication must use the exact completed scan identifier.")
107
71
  if scan["status"] != "complete":
108
72
  raise SystemExit("Only completed scans can publish findings to Linear.")
109
-
110
- requested_directory = db.require_canonical_scan_directory(Path(payload["scanDirectory"]))
73
+ requested_directory = db.require_canonical_scan_directory(Path(scan_directory))
111
74
  recorded_directory = db.require_canonical_scan_directory(Path(scan["scan_dir"]))
112
75
  if os.path.normcase(requested_directory) != os.path.normcase(recorded_directory):
113
76
  raise SystemExit(
@@ -115,212 +78,218 @@ def verify_linear_publication_scan(
115
78
  )
116
79
  if "seal_manifest_digest" in scan.keys():
117
80
  db.require_recorded_manifest_digest(scan, recorded_directory)
118
-
119
81
  stored_findings = {
120
82
  row["id"]: row["finding_id"]
121
83
  for row in connection.execute(
122
- "SELECT id, finding_id FROM finding_occurrences WHERE scan_id = ?",
123
- (scan["id"],),
84
+ "SELECT id, finding_id FROM finding_occurrences WHERE scan_id = ?", (scan_id,)
124
85
  )
125
86
  }
126
- for finding in findings:
127
- if stored_findings.get(finding["occurrenceId"]) != finding["findingId"]:
128
- raise SystemExit(
129
- "A selected finding or occurrence does not belong to the completed scan "
130
- "in local Codex Security scan history."
131
- )
132
- if len(stored_findings) != len(findings):
87
+ expected = {finding["occurrenceId"]: finding["findingId"] for finding in findings}
88
+ if stored_findings != expected:
133
89
  raise SystemExit(
134
90
  "The completed scan findings do not exactly match local Codex Security scan history."
135
91
  )
136
- return scan
137
92
 
138
93
 
139
- def _linear_publication_record(row: sqlite3.Row) -> dict[str, str]:
94
+ def issue_receipt(row: sqlite3.Row) -> dict[str, Any]:
140
95
  return {
96
+ "scanId": row["scan_id"],
141
97
  "findingId": row["finding_id"],
142
98
  "occurrenceId": row["occurrence_id"],
143
99
  "issueIdentifier": row["external_id"],
100
+ "operation": row["operation"],
144
101
  **({"url": row["external_url"]} if row["external_url"] is not None else {}),
102
+ **({"readback": json.loads(row["readback_json"])} if row["readback_json"] else {}),
145
103
  }
146
104
 
147
105
 
148
- def inspect_linear_publication(
149
- db: Any,
150
- payload: dict[str, Any],
151
- ) -> dict[str, Any]:
152
- payload, destination, findings = linear_publication_input(payload, recording=False)
153
- database_uri = f"file:{quote(str(db.database_path()), safe='')}?mode=ro"
154
- with closing(sqlite3.connect(database_uri, uri=True, timeout=5)) as connection:
155
- connection.row_factory = sqlite3.Row
156
- connection.execute("BEGIN")
157
- scan = verify_linear_publication_scan(db, connection, payload, findings)
158
- recorded: dict[str, dict[str, str]] = {}
159
- if connection.execute(
160
- "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'finding_publications'"
161
- ).fetchone():
162
- for row in connection.execute(
163
- """
164
- SELECT finding_id, occurrence_id, external_id, external_url
165
- FROM finding_publications
166
- WHERE scan_id = ? AND destination_type = ? AND team_id = ? AND project_id IS ?
167
- ORDER BY created_at, external_id
168
- """,
169
- (
170
- scan["id"],
171
- destination["type"],
172
- destination["teamId"],
173
- destination.get("projectId"),
174
- ),
175
- ):
176
- recorded.setdefault(row["occurrence_id"], _linear_publication_record(row))
177
- return {
178
- "scanId": scan["id"],
179
- "destination": destination,
180
- "findingCount": len(findings),
181
- "recorded": [
182
- recorded[finding["occurrenceId"]]
183
- for finding in findings
184
- if finding["occurrenceId"] in recorded
185
- ],
186
- }
187
-
188
-
189
- def prepare_linear_publication(
190
- db: Any,
106
+ def inspect_issue_receipts(
191
107
  connection: sqlite3.Connection,
192
- payload: dict[str, Any],
193
- ) -> dict[str, Any]:
194
- payload, destination, findings = linear_publication_input(payload, recording=False)
195
- connection.execute("BEGIN IMMEDIATE")
196
- with connection:
197
- scan = verify_linear_publication_scan(db, connection, payload, findings)
198
- return {
199
- "scanId": scan["id"],
200
- "destination": destination,
201
- "findingCount": len(findings),
202
- }
108
+ destination: dict[str, str],
109
+ key: str,
110
+ finding_ids: list[str],
111
+ ) -> list[dict[str, Any]]:
112
+ tables = {
113
+ row[0] for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'table'")
114
+ }
115
+ selection = json.dumps(finding_ids)
116
+ if "finding_issue_receipts" in tables:
117
+ rows = connection.execute(
118
+ "SELECT * FROM finding_issue_receipts WHERE destination_key = ? "
119
+ "AND finding_id IN (SELECT value FROM json_each(?)) ORDER BY id",
120
+ (key, selection),
121
+ )
122
+ elif "finding_publications" in tables and destination["type"] == "linear":
123
+ rows = connection.execute(
124
+ "SELECT *, 'create' AS operation, NULL AS readback_json FROM finding_publications "
125
+ "WHERE destination_type = 'linear' AND team_id = ? AND project_id IS ? "
126
+ "AND finding_id IN (SELECT value FROM json_each(?)) ORDER BY id",
127
+ (destination["teamId"], destination.get("projectId"), selection),
128
+ )
129
+ else:
130
+ return []
131
+ return [issue_receipt(row) for row in rows]
203
132
 
204
133
 
205
- def record_linear_publications(
206
- db: Any,
207
- connection: sqlite3.Connection,
208
- payload: dict[str, Any],
209
- ) -> dict[str, Any]:
210
- payload, destination, findings = linear_publication_input(payload, recording=True)
211
- publications = payload["publications"]
212
- if not isinstance(publications, list):
213
- raise SystemExit("Linear publication results must be an array.")
214
- planned = {finding["findingId"]: finding["occurrenceId"] for finding in findings}
215
- current: dict[str, dict[str, str]] = {}
216
- external_ids: set[str] = set()
217
- for publication in publications:
218
- if (
219
- not isinstance(publication, dict)
220
- or not {"findingId", "occurrenceId", "issueIdentifier"}.issubset(publication)
221
- or not set(publication).issubset(
222
- {"findingId", "occurrenceId", "issueIdentifier", "url"}
223
- )
224
- or not isinstance(publication.get("findingId"), str)
225
- or not isinstance(publication.get("occurrenceId"), str)
226
- or not isinstance(publication.get("issueIdentifier"), str)
227
- or not publication["issueIdentifier"].strip()
228
- or (
229
- "url" in publication
230
- and (not isinstance(publication["url"], str) or not publication["url"].strip())
231
- )
134
+ def validate_issue_receipts(receipts: Any, selected: dict[str, str]) -> list[dict[str, Any]]:
135
+ if not isinstance(receipts, list):
136
+ raise SystemExit("Finding issue receipts must be an array.")
137
+ for receipt in receipts:
138
+ if not isinstance(receipt, dict):
139
+ raise SystemExit("Each finding issue receipt must be an object.")
140
+ if any(
141
+ not isinstance(receipt.get(field), str) or not receipt[field].strip()
142
+ for field in ("findingId", "occurrenceId", "issueIdentifier")
232
143
  ):
233
- raise SystemExit("Linear publication results contain an invalid issue association.")
234
- finding_id = publication["findingId"]
235
- issue_identifier = publication["issueIdentifier"]
236
- if planned.get(finding_id) != publication["occurrenceId"]:
144
+ raise SystemExit("A finding issue receipt is missing its source or issue identity.")
145
+ if selected.get(receipt["findingId"]) != receipt["occurrenceId"]:
237
146
  raise SystemExit(
238
- "A created Linear issue does not match its planned finding and occurrence."
147
+ "A finding issue receipt does not belong to the selected sealed findings."
239
148
  )
240
- if finding_id in current or issue_identifier in external_ids:
241
- raise SystemExit("Linear publication results repeat a finding or issue identifier.")
242
- current[finding_id] = publication
243
- external_ids.add(issue_identifier)
244
-
245
- connection.execute("BEGIN IMMEDIATE")
246
- with connection:
247
- scan = verify_linear_publication_scan(db, connection, payload, findings)
248
- timestamp = db.now()
249
- for publication in publications:
250
- conflicting = connection.execute(
251
- """
252
- SELECT occurrence_id, external_url
253
- FROM finding_publications
254
- WHERE destination_type = ? AND team_id = ? AND project_id IS ?
255
- AND external_id = ?
256
- """,
257
- (
258
- destination["type"],
259
- destination["teamId"],
260
- destination.get("projectId"),
261
- publication["issueIdentifier"],
262
- ),
263
- ).fetchone()
264
- if (
265
- conflicting is not None
266
- and conflicting["occurrence_id"] != publication["occurrenceId"]
267
- ):
268
- raise SystemExit(
269
- "This Linear issue is already associated with a different finding."
270
- )
149
+ if receipt.get("operation") not in {"create", "update", "reuse"}:
150
+ raise SystemExit("A finding issue receipt requires create, update, or reuse.")
151
+ if "url" in receipt and (not isinstance(receipt["url"], str) or not receipt["url"].strip()):
152
+ raise SystemExit("A finding issue URL must be a nonempty string when supplied.")
153
+ if "readback" in receipt:
154
+ readback = receipt["readback"]
271
155
  if (
272
- conflicting is not None
273
- and "url" in publication
274
- and conflicting["external_url"] != publication["url"]
156
+ not isinstance(readback, dict)
157
+ or readback.get("status") not in {"verified", "failed"}
158
+ or ("error" in readback and not isinstance(readback["error"], str))
275
159
  ):
276
- raise SystemExit("This Linear issue is already associated with a different URL.")
160
+ raise SystemExit("A finding issue readback requires verified or failed status.")
161
+ return receipts
277
162
 
278
- connection.execute(
279
- """
280
- INSERT INTO finding_publications (
281
- scan_id, finding_id, occurrence_id, destination_type,
282
- team_id, project_id, external_id, external_url, created_at
283
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
284
- ON CONFLICT DO NOTHING
285
- """,
286
- (
287
- scan["id"],
288
- publication["findingId"],
289
- publication["occurrenceId"],
290
- destination["type"],
291
- destination["teamId"],
292
- destination.get("projectId"),
293
- publication["issueIdentifier"],
294
- publication.get("url"),
295
- timestamp,
296
- ),
297
- )
298
163
 
299
- created = []
300
- for finding in findings:
301
- publication = current.get(finding["findingId"])
302
- if publication is None:
303
- continue
304
- row = connection.execute(
305
- """
306
- SELECT finding_id, occurrence_id, external_id, external_url
307
- FROM finding_publications
308
- WHERE scan_id = ? AND occurrence_id = ? AND destination_type = ?
309
- AND team_id = ? AND project_id IS ? AND external_id = ?
310
- """,
311
- (
312
- scan["id"],
313
- publication["occurrenceId"],
314
- destination["type"],
315
- destination["teamId"],
316
- destination.get("projectId"),
317
- publication["issueIdentifier"],
318
- ),
319
- ).fetchone()
320
- if row is None:
321
- raise SystemExit("A created Linear issue could not be read from scan history.")
322
- created.append(_linear_publication_record(row))
323
- return {"scanId": scan["id"], "destination": destination, "created": created}
164
+ def finding_issues(db: Any, payload: Any) -> dict[str, Any]:
165
+ if not isinstance(payload, dict) or payload.get("action") not in {
166
+ "inspect",
167
+ "prepare",
168
+ "record",
169
+ }:
170
+ raise SystemExit("Finding issues require inspect, prepare, or record action.")
171
+ if not isinstance(payload.get("scanDirectory"), str):
172
+ raise SystemExit("Finding issues require a sealed scan directory.")
173
+ require_history = payload.get("requireHistory", False)
174
+ if not isinstance(require_history, bool):
175
+ raise SystemExit("requireHistory must be a boolean.")
176
+ key = destination_key(payload.get("destination"))
177
+ try:
178
+ validated = validate_contract(Path(payload["scanDirectory"]))
179
+ except (OSError, ValueError, RecursionError) as exc:
180
+ raise SystemExit(f"Finding issue source validation failed: {exc}") from exc
181
+ scan_id = validated["manifest"]["scan"]["id"]
182
+ if "expectedScanId" in payload and payload["expectedScanId"] != scan_id:
183
+ raise SystemExit("Scan artifacts do not match the selected scan identifier.")
184
+ findings = validated["findings"]["findings"]
185
+ available = {finding["findingId"]: finding["occurrenceId"] for finding in findings}
186
+ finding_ids = payload.get("findingIds", list(available))
187
+ if not isinstance(finding_ids, list) or any(
188
+ not isinstance(finding_id, str) or finding_id not in available for finding_id in finding_ids
189
+ ):
190
+ raise SystemExit("Selected finding IDs must belong to the sealed scan.")
191
+ selected = {finding_id: available[finding_id] for finding_id in finding_ids}
192
+ receipts = (
193
+ validate_issue_receipts(payload.get("receipts"), selected)
194
+ if payload["action"] == "record"
195
+ else []
196
+ )
197
+ result = {
198
+ "scanId": scan_id,
199
+ "destination": payload["destination"],
200
+ "findingCount": len(selected),
201
+ "storeExists": True,
202
+ "receipts": [],
203
+ }
204
+ path = db.database_path()
205
+ if payload["action"] == "inspect" or require_history:
206
+ try:
207
+ path.stat()
208
+ except FileNotFoundError:
209
+ if require_history:
210
+ raise SystemExit(
211
+ "Cannot publish findings because the local Codex Security scan-history database "
212
+ "does not exist. Use the state directory where this scan was completed."
213
+ ) from None
214
+ result["storeExists"] = False
215
+ return result
216
+ except PermissionError:
217
+ pass # Let SQLite report the open failure used by the host's state fallback.
218
+ if payload["action"] == "inspect":
219
+ database_uri = f"file:{quote(str(path), safe='')}?mode=ro"
220
+ try:
221
+ connection = sqlite3.connect(database_uri, uri=True, timeout=5)
222
+ except sqlite3.OperationalError as exc:
223
+ if str(exc) == "unable to open database file":
224
+ exc._codex_security_state_unavailable = True
225
+ raise
226
+ connection.row_factory = sqlite3.Row
227
+ else:
228
+ connection = db.connect()
229
+ with closing(connection):
230
+ connection.execute("BEGIN" if payload["action"] == "inspect" else "BEGIN IMMEDIATE")
231
+ with connection:
232
+ if require_history:
233
+ verify_publication_history(db, connection, scan_id, validated["scanDir"], findings)
234
+ if payload["action"] == "inspect":
235
+ result["receipts"] = inspect_issue_receipts(
236
+ connection, payload["destination"], key, list(selected)
237
+ )
238
+ elif payload["action"] == "record":
239
+ timestamp = db.now()
240
+ for receipt in receipts:
241
+ conflicting = connection.execute(
242
+ "SELECT 1 FROM finding_issue_receipts "
243
+ "WHERE destination_key = ? AND external_id = ? AND finding_id != ? LIMIT 1",
244
+ (key, receipt["issueIdentifier"], receipt["findingId"]),
245
+ ).fetchone()
246
+ if conflicting is not None:
247
+ raise SystemExit(
248
+ "The issue identifier is already associated with another finding "
249
+ "in this destination."
250
+ )
251
+ readback = (
252
+ json.dumps(receipt["readback"], ensure_ascii=False)
253
+ if "readback" in receipt
254
+ else None
255
+ )
256
+ connection.execute(
257
+ """
258
+ INSERT INTO finding_issue_receipts (
259
+ scan_id, finding_id, occurrence_id, destination_key,
260
+ external_id, external_url, operation, readback_json, created_at, updated_at
261
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
262
+ ON CONFLICT (occurrence_id, destination_key, external_id, operation)
263
+ DO UPDATE SET
264
+ external_url = COALESCE(external_url, excluded.external_url),
265
+ readback_json = COALESCE(excluded.readback_json, readback_json),
266
+ updated_at = excluded.updated_at
267
+ """,
268
+ (
269
+ scan_id,
270
+ receipt["findingId"],
271
+ receipt["occurrenceId"],
272
+ key,
273
+ receipt["issueIdentifier"],
274
+ receipt.get("url"),
275
+ receipt["operation"],
276
+ readback,
277
+ timestamp,
278
+ timestamp,
279
+ ),
280
+ )
281
+ row = connection.execute(
282
+ "SELECT * FROM finding_issue_receipts WHERE occurrence_id = ? "
283
+ "AND destination_key = ? AND external_id = ? AND operation = ?",
284
+ (
285
+ receipt["occurrenceId"],
286
+ key,
287
+ receipt["issueIdentifier"],
288
+ receipt["operation"],
289
+ ),
290
+ ).fetchone()
291
+ result["receipts"].append(issue_receipt(row))
292
+ return result
324
293
 
325
294
 
326
295
  def export_findings(
@@ -19,8 +19,9 @@ from report_projection import SEVERITY_ORDER
19
19
  from workbench_constants import ARTIFACTS, FINDINGS_PAGE_MAX
20
20
  from workbench_scan_start import scan_target_identity
21
21
  from workbench_scan_usage import stored_scan_cost_fields
22
+ from workbench_source_scopes import public_scan_recipe
22
23
  from workbench_target import git_output, require_scan_target_identity
23
- from workbench_validation import reject_non_finite_json, timestamp_key
24
+ from workbench_validation import timestamp_key
24
25
 
25
26
 
26
27
  def rename_scan(connection: sqlite3.Connection, scan: sqlite3.Row, name: str) -> dict[str, Any]:
@@ -37,7 +38,7 @@ def scan_recipe(scan: sqlite3.Row) -> dict[str, Any]:
37
38
  raise SystemExit("This scan does not have a saved launch recipe.")
38
39
  return {
39
40
  "parentScanId": scan["parent_scan_id"],
40
- "recipe": json.loads(scan["recipe_json"], parse_constant=reject_non_finite_json),
41
+ "recipe": public_scan_recipe(scan),
41
42
  "scanId": scan["id"],
42
43
  }
43
44
 
@@ -13,6 +13,7 @@ from collections.abc import Callable, Iterator
13
13
  from contextlib import contextmanager
14
14
  from datetime import datetime, timezone
15
15
  from pathlib import Path
16
+ from typing import Any
16
17
 
17
18
  # Some plugin hosts launch Python with safe-path isolation enabled.
18
19
  sys.path.insert(0, str(Path(__file__).resolve().parent))
@@ -160,8 +161,13 @@ def archive_scan(
160
161
  archived_scan_dir.rmdir()
161
162
  scan_dir.rename(archived_scan_dir)
162
163
  moved = True
163
- scan_dir.mkdir(mode=0o700)
164
- scan_dir.chmod(0o700)
164
+ if os.name == "nt":
165
+ from windows_scan_local_files import create_directory_with_same_dacl
166
+
167
+ create_directory_with_same_dacl(scan_dir, archived_scan_dir)
168
+ else:
169
+ scan_dir.mkdir(mode=0o700)
170
+ scan_dir.chmod(0o700)
165
171
  if previous_scan is not None:
166
172
  connection.execute(
167
173
  "UPDATE scans SET scan_dir = ?, updated_at = ? WHERE id = ?",
@@ -221,6 +227,7 @@ def insert_running_scan(
221
227
  scope: str,
222
228
  diff_target: dict[str, str] | None,
223
229
  target_identity: tuple[str, str | None, int | str, int | str],
230
+ source_scopes: dict[str, Any],
224
231
  target_root: Path,
225
232
  target_summary: str | None,
226
233
  scope_file_count: int,
@@ -244,11 +251,11 @@ def insert_running_scan(
244
251
  """
245
252
  INSERT INTO scans (
246
253
  id, workspace_id, target_id, target_path, target_revision, target_snapshot_digest,
247
- target_device, target_inode, scope, mode, user_context,
254
+ target_device, target_inode, source_scopes_json, scope, mode, user_context,
248
255
  deep_scan_owner_thread_id, diff_target_kind, diff_base_revision,
249
256
  diff_head_revision, diff_content_digest, target_summary, scan_dir, model,
250
257
  reasoning_effort, status, phase, handoff_status, started_at, created_at, updated_at
251
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
258
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
252
259
  'running', 'preflight', ?, ?, ?, ?)
253
260
  """,
254
261
  (
@@ -257,6 +264,7 @@ def insert_running_scan(
257
264
  workspace["target_id"],
258
265
  str(target),
259
266
  *target_identity,
267
+ json.dumps(source_scopes, allow_nan=False, separators=(",", ":"), sort_keys=True),
260
268
  scope,
261
269
  workspace["default_mode"],
262
270
  user_context,