@openai/codex-security 0.1.21 → 0.1.24

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 (183) hide show
  1. package/README.md +549 -1
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/.mcp.json +1 -0
  4. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  5. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  6. package/_bundled_plugin/references/config-preflight.md +2 -30
  7. package/_bundled_plugin/references/core-scan.md +1 -1
  8. package/_bundled_plugin/references/final-report.md +1 -1
  9. package/_bundled_plugin/references/finding-detail-fields.md +5 -10
  10. package/_bundled_plugin/references/sarif-adapter.md +1 -1
  11. package/_bundled_plugin/references/scan-contract.md +10 -0
  12. package/_bundled_plugin/scripts/config_preflight.py +2 -8
  13. package/_bundled_plugin/scripts/deep_scan_workbench.py +6 -1
  14. package/_bundled_plugin/scripts/finalize_scan_contract.py +115 -76
  15. package/_bundled_plugin/scripts/finding_preview.py +22 -4
  16. package/_bundled_plugin/scripts/generate_in_scope_files.py +29 -9
  17. package/_bundled_plugin/scripts/generate_rank_input.py +1 -5
  18. package/_bundled_plugin/scripts/rank_preview.py +1 -0
  19. package/_bundled_plugin/scripts/report_projection.py +8 -14
  20. package/_bundled_plugin/scripts/validate_scan_contract.py +1 -3
  21. package/_bundled_plugin/scripts/windows_scan_local_files.py +90 -6
  22. package/_bundled_plugin/scripts/workbench_cli.py +27 -1
  23. package/_bundled_plugin/scripts/workbench_dashboard.py +138 -0
  24. package/_bundled_plugin/scripts/workbench_db.py +110 -539
  25. package/_bundled_plugin/scripts/workbench_finding_index.py +42 -24
  26. package/_bundled_plugin/scripts/workbench_finding_workflows.py +208 -0
  27. package/_bundled_plugin/scripts/workbench_findings.py +221 -0
  28. package/_bundled_plugin/scripts/workbench_native_indexes.py +1 -2
  29. package/_bundled_plugin/scripts/workbench_publication.py +520 -0
  30. package/_bundled_plugin/scripts/workbench_remediation.py +37 -0
  31. package/_bundled_plugin/scripts/workbench_saved_results.py +322 -89
  32. package/_bundled_plugin/scripts/workbench_scan_history.py +1 -2
  33. package/_bundled_plugin/scripts/workbench_scan_usage.py +9 -33
  34. package/_bundled_plugin/scripts/workbench_schema.py +276 -58
  35. package/_bundled_plugin/scripts/workbench_target.py +30 -6
  36. package/_bundled_plugin/scripts/workbench_validation.py +1 -5
  37. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +1 -5
  38. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +6 -1
  39. package/_bundled_plugin/skills/track-findings/SKILL.md +2 -0
  40. package/dist/api.d.ts +5 -1
  41. package/dist/api.d.ts.map +1 -1
  42. package/dist/api.js +135 -27
  43. package/dist/api.js.map +1 -1
  44. package/dist/cli.d.ts +4 -0
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +158 -62
  47. package/dist/cli.js.map +1 -1
  48. package/dist/cloud-publish.js +5 -1
  49. package/dist/cloud-publish.js.map +1 -1
  50. package/dist/contract.d.ts +1 -0
  51. package/dist/contract.d.ts.map +1 -1
  52. package/dist/contract.js +9 -0
  53. package/dist/contract.js.map +1 -1
  54. package/dist/custom-publish.d.ts +22 -0
  55. package/dist/custom-publish.d.ts.map +1 -0
  56. package/dist/custom-publish.js +47 -0
  57. package/dist/custom-publish.js.map +1 -0
  58. package/dist/custom-validation-prompt.js +1 -1
  59. package/dist/custom-validation-prompt.js.map +1 -1
  60. package/dist/deduplication/checkpointed-review.d.ts +16 -0
  61. package/dist/deduplication/checkpointed-review.d.ts.map +1 -0
  62. package/dist/deduplication/checkpointed-review.js +76 -0
  63. package/dist/deduplication/checkpointed-review.js.map +1 -0
  64. package/dist/deduplication/codex-review.d.ts +21 -0
  65. package/dist/deduplication/codex-review.d.ts.map +1 -0
  66. package/dist/deduplication/codex-review.js +252 -0
  67. package/dist/deduplication/codex-review.js.map +1 -0
  68. package/dist/deduplication/deduplication-prompts.d.ts +8 -0
  69. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -0
  70. package/dist/deduplication/deduplication-prompts.js +35 -0
  71. package/dist/deduplication/deduplication-prompts.js.map +1 -0
  72. package/dist/deduplication/deduplication-reviewer.d.ts +46 -0
  73. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -0
  74. package/dist/deduplication/deduplication-reviewer.js +105 -0
  75. package/dist/deduplication/deduplication-reviewer.js.map +1 -0
  76. package/dist/deduplication/deduplication.d.ts +6 -0
  77. package/dist/deduplication/deduplication.d.ts.map +1 -0
  78. package/dist/deduplication/deduplication.js +85 -0
  79. package/dist/deduplication/deduplication.js.map +1 -0
  80. package/dist/deduplication/scan.d.ts +16 -0
  81. package/dist/deduplication/scan.d.ts.map +1 -0
  82. package/dist/deduplication/scan.js +101 -0
  83. package/dist/deduplication/scan.js.map +1 -0
  84. package/dist/deep-progress.d.ts +21 -0
  85. package/dist/deep-progress.d.ts.map +1 -0
  86. package/dist/deep-progress.js +108 -0
  87. package/dist/deep-progress.js.map +1 -0
  88. package/dist/finding-dedupe-groups.d.ts +7 -0
  89. package/dist/finding-dedupe-groups.d.ts.map +1 -0
  90. package/dist/finding-dedupe-groups.js +2 -0
  91. package/dist/finding-dedupe-groups.js.map +1 -0
  92. package/dist/finding-retrieval.d.ts +13 -0
  93. package/dist/finding-retrieval.d.ts.map +1 -0
  94. package/dist/finding-retrieval.js +2 -0
  95. package/dist/finding-retrieval.js.map +1 -0
  96. package/dist/finding-workflow.d.ts +53 -0
  97. package/dist/finding-workflow.d.ts.map +1 -0
  98. package/dist/finding-workflow.js +117 -0
  99. package/dist/finding-workflow.js.map +1 -0
  100. package/dist/findings-client.d.ts +15 -0
  101. package/dist/findings-client.d.ts.map +1 -0
  102. package/dist/findings-client.js +60 -0
  103. package/dist/findings-client.js.map +1 -0
  104. package/dist/index.d.ts +5 -0
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +2 -0
  107. package/dist/index.js.map +1 -1
  108. package/dist/publication.js +28 -40
  109. package/dist/publication.js.map +1 -1
  110. package/dist/runtime.d.ts +5 -1
  111. package/dist/runtime.d.ts.map +1 -1
  112. package/dist/runtime.js +119 -13
  113. package/dist/runtime.js.map +1 -1
  114. package/dist/saved-scan.d.ts +15 -0
  115. package/dist/saved-scan.d.ts.map +1 -0
  116. package/dist/saved-scan.js +68 -0
  117. package/dist/saved-scan.js.map +1 -0
  118. package/dist/scan-activity.d.ts.map +1 -1
  119. package/dist/scan-activity.js +12 -2
  120. package/dist/scan-activity.js.map +1 -1
  121. package/dist/scan-comparison.d.ts +3 -2
  122. package/dist/scan-comparison.d.ts.map +1 -1
  123. package/dist/scan-comparison.js +1 -1
  124. package/dist/scan-comparison.js.map +1 -1
  125. package/dist/server/dashboard/THIRD_PARTY_NOTICES.txt +276 -0
  126. package/dist/server/dashboard/app.css +2 -0
  127. package/dist/server/dashboard/app.js +66 -0
  128. package/dist/server/dashboard/index.html +18 -0
  129. package/dist/server/dashboard-types.d.ts +45 -0
  130. package/dist/server/dashboard-types.d.ts.map +1 -0
  131. package/dist/server/dashboard-types.js +2 -0
  132. package/dist/server/dashboard-types.js.map +1 -0
  133. package/dist/server/dashboard.d.ts +6 -0
  134. package/dist/server/dashboard.d.ts.map +1 -0
  135. package/dist/server/dashboard.js +45 -0
  136. package/dist/server/dashboard.js.map +1 -0
  137. package/dist/server/embeddings.d.ts +16 -0
  138. package/dist/server/embeddings.d.ts.map +1 -0
  139. package/dist/server/embeddings.js +114 -0
  140. package/dist/server/embeddings.js.map +1 -0
  141. package/dist/server/errors.d.ts +5 -0
  142. package/dist/server/errors.d.ts.map +1 -0
  143. package/dist/server/errors.js +8 -0
  144. package/dist/server/errors.js.map +1 -0
  145. package/dist/server/findings-service.d.ts +20 -0
  146. package/dist/server/findings-service.d.ts.map +1 -0
  147. package/dist/server/findings-service.js +31 -0
  148. package/dist/server/findings-service.js.map +1 -0
  149. package/dist/server/index.d.ts +2 -0
  150. package/dist/server/index.d.ts.map +1 -0
  151. package/dist/server/index.js +6 -0
  152. package/dist/server/index.js.map +1 -0
  153. package/dist/server/routes.d.ts +6 -0
  154. package/dist/server/routes.d.ts.map +1 -0
  155. package/dist/server/routes.js +86 -0
  156. package/dist/server/routes.js.map +1 -0
  157. package/dist/server/serve.d.ts +2 -0
  158. package/dist/server/serve.d.ts.map +1 -0
  159. package/dist/server/serve.js +28 -0
  160. package/dist/server/serve.js.map +1 -0
  161. package/dist/server/server.d.ts +10 -0
  162. package/dist/server/server.d.ts.map +1 -0
  163. package/dist/server/server.js +17 -0
  164. package/dist/server/server.js.map +1 -0
  165. package/dist/server/sqlite-store.d.ts +22 -0
  166. package/dist/server/sqlite-store.d.ts.map +1 -0
  167. package/dist/server/sqlite-store.js +82 -0
  168. package/dist/server/sqlite-store.js.map +1 -0
  169. package/dist/server/storage.d.ts +32 -0
  170. package/dist/server/storage.d.ts.map +1 -0
  171. package/dist/server/storage.js +2 -0
  172. package/dist/server/storage.js.map +1 -0
  173. package/dist/server/validation.d.ts +17 -0
  174. package/dist/server/validation.d.ts.map +1 -0
  175. package/dist/server/validation.js +53 -0
  176. package/dist/server/validation.js.map +1 -0
  177. package/dist/trusted-executable.d.ts.map +1 -1
  178. package/dist/trusted-executable.js +2 -1
  179. package/dist/trusted-executable.js.map +1 -1
  180. package/dist/version.d.ts +1 -1
  181. package/dist/version.js +1 -1
  182. package/dist/version.js.map +1 -1
  183. package/package.json +17 -5
@@ -0,0 +1,520 @@
1
+ """Validate, record, and export findings from completed scans."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import io
8
+ import os
9
+ import sqlite3
10
+ from collections.abc import Callable
11
+ from contextlib import closing
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Any
15
+ from urllib.parse import quote
16
+
17
+ from finalize_scan_contract import (
18
+ ContractError,
19
+ csv_cell,
20
+ finalize_scan,
21
+ finding_candidate_id,
22
+ write_sarif_projection,
23
+ write_scan_local_bytes,
24
+ )
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class WorkbenchPublicationContext:
29
+ ARTIFACTS: dict[str, str]
30
+ artifact_path: Callable[..., Path | None]
31
+ available_artifact_path: Callable[[Path, Path], Path | None]
32
+ database_path: Callable[[], Path]
33
+ expected_coverage_mode: Callable[[sqlite3.Row], str]
34
+ now: Callable[[], str]
35
+ pin_legacy_manifest_digest: Callable[[sqlite3.Connection, str, str], None]
36
+ published_manifest_digest: Callable[[Path, dict[str, Any]], str]
37
+ read_json_object: Callable[[Path], dict[str, Any]]
38
+ require_canonical_scan_directory: Callable[[Path], Path]
39
+ require_recorded_manifest_digest: Callable[[sqlite3.Row, Path], str]
40
+ require_scan: Callable[[sqlite3.Connection, str], sqlite3.Row]
41
+ scan_result: Callable[[sqlite3.Connection, sqlite3.Row], dict[str, Any]]
42
+ verify_manifest_binding: Callable[[sqlite3.Row, dict[str, Any]], None]
43
+ workspace_state: Callable[[sqlite3.Connection, str], dict[str, Any]]
44
+
45
+
46
+ def linear_publication_input(
47
+ db: WorkbenchPublicationContext,
48
+ args: argparse.Namespace,
49
+ *,
50
+ recording: bool,
51
+ ) -> tuple[dict[str, Any], dict[str, str], list[dict[str, str]]]:
52
+ payload = db.read_json_object(Path(args.input_file))
53
+ required = {"scanId", "scanDirectory", "destination", "findings"}
54
+ if recording:
55
+ required.add("publications")
56
+ if set(payload) != required:
57
+ raise SystemExit("Linear publication input contains unexpected or missing fields.")
58
+
59
+ scan_id = payload["scanId"]
60
+ scan_directory = payload["scanDirectory"]
61
+ destination = payload["destination"]
62
+ findings = payload["findings"]
63
+ if not isinstance(scan_id, str) or not isinstance(scan_directory, str):
64
+ raise SystemExit("Linear publication input must identify the exact completed scan.")
65
+ if (
66
+ not isinstance(destination, dict)
67
+ or not {"type", "teamId"}.issubset(destination)
68
+ or not set(destination).issubset({"type", "teamId", "projectId"})
69
+ or destination.get("type") != "linear"
70
+ or not isinstance(destination.get("teamId"), str)
71
+ or not destination["teamId"].strip()
72
+ or (
73
+ "projectId" in destination
74
+ and (
75
+ not isinstance(destination["projectId"], str)
76
+ or not destination["projectId"].strip()
77
+ )
78
+ )
79
+ ):
80
+ raise SystemExit(
81
+ "Linear publication input must identify the exact team and optional project."
82
+ )
83
+ if not isinstance(findings, list):
84
+ raise SystemExit("Linear publication input must include the planned scan findings.")
85
+
86
+ seen_finding_ids: set[str] = set()
87
+ seen_occurrence_ids: set[str] = set()
88
+ for finding in findings:
89
+ if (
90
+ not isinstance(finding, dict)
91
+ or set(finding) != {"findingId", "occurrenceId"}
92
+ or not isinstance(finding.get("findingId"), str)
93
+ or not finding["findingId"].strip()
94
+ or not isinstance(finding.get("occurrenceId"), str)
95
+ or not finding["occurrenceId"].strip()
96
+ ):
97
+ raise SystemExit("Linear publication input contains an invalid finding identity.")
98
+ if (
99
+ finding["findingId"] in seen_finding_ids
100
+ or finding["occurrenceId"] in seen_occurrence_ids
101
+ ):
102
+ raise SystemExit("Linear publication input repeats a finding or occurrence.")
103
+ seen_finding_ids.add(finding["findingId"])
104
+ seen_occurrence_ids.add(finding["occurrenceId"])
105
+
106
+ return payload, destination, findings
107
+
108
+
109
+ def verify_linear_publication_scan(
110
+ db: WorkbenchPublicationContext,
111
+ connection: sqlite3.Connection,
112
+ payload: dict[str, Any],
113
+ findings: list[dict[str, str]],
114
+ ) -> sqlite3.Row:
115
+ try:
116
+ scan = db.require_scan(connection, payload["scanId"])
117
+ except SystemExit as exc:
118
+ raise SystemExit(
119
+ "The completed scan is not present in the local Codex Security scan-history database. "
120
+ "Use the state directory where the scan was completed."
121
+ ) from exc
122
+ if scan["id"] != payload["scanId"]:
123
+ raise SystemExit("Linear publication must use the exact completed scan identifier.")
124
+ if scan["status"] != "complete":
125
+ raise SystemExit("Only completed scans can publish findings to Linear.")
126
+
127
+ requested_directory = db.require_canonical_scan_directory(Path(payload["scanDirectory"]))
128
+ recorded_directory = db.require_canonical_scan_directory(Path(scan["scan_dir"]))
129
+ if os.path.normcase(requested_directory) != os.path.normcase(recorded_directory):
130
+ raise SystemExit(
131
+ "The selected scan directory does not match its local Codex Security scan history."
132
+ )
133
+ if "seal_manifest_digest" in scan.keys():
134
+ db.require_recorded_manifest_digest(scan, recorded_directory)
135
+
136
+ stored_findings = {
137
+ row["id"]: row["finding_id"]
138
+ for row in connection.execute(
139
+ "SELECT id, finding_id FROM finding_occurrences WHERE scan_id = ?",
140
+ (scan["id"],),
141
+ )
142
+ }
143
+ for finding in findings:
144
+ if stored_findings.get(finding["occurrenceId"]) != finding["findingId"]:
145
+ raise SystemExit(
146
+ "A selected finding or occurrence does not belong to the completed scan "
147
+ "in local Codex Security scan history."
148
+ )
149
+ if len(stored_findings) != len(findings):
150
+ raise SystemExit(
151
+ "The completed scan findings do not exactly match local Codex Security scan history."
152
+ )
153
+ return scan
154
+
155
+
156
+ def inspect_linear_publication(
157
+ db: WorkbenchPublicationContext,
158
+ args: argparse.Namespace,
159
+ ) -> dict[str, Any]:
160
+ payload, destination, findings = linear_publication_input(db, args, recording=False)
161
+ database_uri = f"file:{quote(str(db.database_path()), safe='')}?mode=ro"
162
+ with closing(sqlite3.connect(database_uri, uri=True, timeout=5)) as connection:
163
+ connection.row_factory = sqlite3.Row
164
+ connection.execute("BEGIN")
165
+ scan = verify_linear_publication_scan(db, connection, payload, findings)
166
+ recorded: dict[str, dict[str, str]] = {}
167
+ if connection.execute(
168
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'finding_publications'"
169
+ ).fetchone():
170
+ for row in connection.execute(
171
+ """
172
+ SELECT finding_id, occurrence_id, external_id, external_url
173
+ FROM finding_publications
174
+ WHERE scan_id = ? AND destination_type = ? AND team_id = ? AND project_id IS ?
175
+ ORDER BY created_at, external_id
176
+ """,
177
+ (
178
+ scan["id"],
179
+ destination["type"],
180
+ destination["teamId"],
181
+ destination.get("projectId"),
182
+ ),
183
+ ):
184
+ recorded.setdefault(
185
+ row["occurrence_id"],
186
+ {
187
+ "findingId": row["finding_id"],
188
+ "occurrenceId": row["occurrence_id"],
189
+ "issueIdentifier": row["external_id"],
190
+ **({"url": row["external_url"]} if row["external_url"] is not None else {}),
191
+ },
192
+ )
193
+ return {
194
+ "scanId": scan["id"],
195
+ "destination": destination,
196
+ "findingCount": len(findings),
197
+ "recorded": [
198
+ recorded[finding["occurrenceId"]]
199
+ for finding in findings
200
+ if finding["occurrenceId"] in recorded
201
+ ],
202
+ }
203
+
204
+
205
+ def prepare_linear_publication(
206
+ db: WorkbenchPublicationContext,
207
+ connection: sqlite3.Connection,
208
+ args: argparse.Namespace,
209
+ ) -> dict[str, Any]:
210
+ payload, destination, findings = linear_publication_input(db, args, recording=False)
211
+ connection.execute("BEGIN IMMEDIATE")
212
+ try:
213
+ scan = verify_linear_publication_scan(db, connection, payload, findings)
214
+ result = {
215
+ "scanId": scan["id"],
216
+ "destination": destination,
217
+ "findingCount": len(findings),
218
+ }
219
+ connection.commit()
220
+ except BaseException:
221
+ connection.rollback()
222
+ raise
223
+ return result
224
+
225
+
226
+ def record_linear_publications(
227
+ db: WorkbenchPublicationContext,
228
+ connection: sqlite3.Connection,
229
+ args: argparse.Namespace,
230
+ ) -> dict[str, Any]:
231
+ payload, destination, findings = linear_publication_input(db, args, recording=True)
232
+ publications = payload["publications"]
233
+ if not isinstance(publications, list):
234
+ raise SystemExit("Linear publication results must be an array.")
235
+ planned = {finding["findingId"]: finding["occurrenceId"] for finding in findings}
236
+ current: dict[str, dict[str, str]] = {}
237
+ external_ids: set[str] = set()
238
+ for publication in publications:
239
+ if (
240
+ not isinstance(publication, dict)
241
+ or not {"findingId", "occurrenceId", "issueIdentifier"}.issubset(publication)
242
+ or not set(publication).issubset(
243
+ {"findingId", "occurrenceId", "issueIdentifier", "url"}
244
+ )
245
+ or not isinstance(publication.get("findingId"), str)
246
+ or not isinstance(publication.get("occurrenceId"), str)
247
+ or not isinstance(publication.get("issueIdentifier"), str)
248
+ or not publication["issueIdentifier"].strip()
249
+ or (
250
+ "url" in publication
251
+ and (not isinstance(publication["url"], str) or not publication["url"].strip())
252
+ )
253
+ ):
254
+ raise SystemExit("Linear publication results contain an invalid issue association.")
255
+ finding_id = publication["findingId"]
256
+ issue_identifier = publication["issueIdentifier"]
257
+ if planned.get(finding_id) != publication["occurrenceId"]:
258
+ raise SystemExit(
259
+ "A created Linear issue does not match its planned finding and occurrence."
260
+ )
261
+ if finding_id in current or issue_identifier in external_ids:
262
+ raise SystemExit("Linear publication results repeat a finding or issue identifier.")
263
+ current[finding_id] = publication
264
+ external_ids.add(issue_identifier)
265
+
266
+ connection.execute("BEGIN IMMEDIATE")
267
+ try:
268
+ scan = verify_linear_publication_scan(db, connection, payload, findings)
269
+ timestamp = db.now()
270
+ for publication in publications:
271
+ conflicting = connection.execute(
272
+ """
273
+ SELECT occurrence_id, external_url
274
+ FROM finding_publications
275
+ WHERE destination_type = ? AND team_id = ? AND project_id IS ?
276
+ AND external_id = ?
277
+ """,
278
+ (
279
+ destination["type"],
280
+ destination["teamId"],
281
+ destination.get("projectId"),
282
+ publication["issueIdentifier"],
283
+ ),
284
+ ).fetchone()
285
+ if (
286
+ conflicting is not None
287
+ and conflicting["occurrence_id"] != publication["occurrenceId"]
288
+ ):
289
+ raise SystemExit(
290
+ "This Linear issue is already associated with a different finding."
291
+ )
292
+ if (
293
+ conflicting is not None
294
+ and "url" in publication
295
+ and conflicting["external_url"] != publication["url"]
296
+ ):
297
+ raise SystemExit("This Linear issue is already associated with a different URL.")
298
+
299
+ connection.execute(
300
+ """
301
+ INSERT INTO finding_publications (
302
+ scan_id, finding_id, occurrence_id, destination_type,
303
+ team_id, project_id, external_id, external_url, created_at
304
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
305
+ ON CONFLICT DO NOTHING
306
+ """,
307
+ (
308
+ scan["id"],
309
+ publication["findingId"],
310
+ publication["occurrenceId"],
311
+ destination["type"],
312
+ destination["teamId"],
313
+ destination.get("projectId"),
314
+ publication["issueIdentifier"],
315
+ publication.get("url"),
316
+ timestamp,
317
+ ),
318
+ )
319
+
320
+ created = []
321
+ for finding in findings:
322
+ publication = current.get(finding["findingId"])
323
+ if publication is None:
324
+ continue
325
+ row = connection.execute(
326
+ """
327
+ SELECT finding_id, occurrence_id, external_id, external_url
328
+ FROM finding_publications
329
+ WHERE scan_id = ? AND occurrence_id = ? AND destination_type = ?
330
+ AND team_id = ? AND project_id IS ? AND external_id = ?
331
+ """,
332
+ (
333
+ scan["id"],
334
+ publication["occurrenceId"],
335
+ destination["type"],
336
+ destination["teamId"],
337
+ destination.get("projectId"),
338
+ publication["issueIdentifier"],
339
+ ),
340
+ ).fetchone()
341
+ if row is None:
342
+ raise SystemExit("A created Linear issue could not be read from scan history.")
343
+ created.append(
344
+ {
345
+ "findingId": row["finding_id"],
346
+ "occurrenceId": row["occurrence_id"],
347
+ "issueIdentifier": row["external_id"],
348
+ **({"url": row["external_url"]} if row["external_url"] is not None else {}),
349
+ }
350
+ )
351
+ result = {"scanId": scan["id"], "destination": destination, "created": created}
352
+ connection.commit()
353
+ except BaseException:
354
+ connection.rollback()
355
+ raise
356
+ return result
357
+
358
+
359
+ def export_findings(
360
+ db: WorkbenchPublicationContext,
361
+ connection: sqlite3.Connection,
362
+ args: argparse.Namespace,
363
+ ) -> dict[str, Any]:
364
+ scan = db.require_scan(connection, args.scan_id)
365
+ if scan["status"] != "complete" and not (
366
+ scan["status"] == "failed" and scan["seal_manifest_digest"]
367
+ ):
368
+ raise SystemExit(
369
+ "Findings can be exported after the scan completes or preserves stopped results."
370
+ )
371
+ scan_dir = db.require_canonical_scan_directory(Path(scan["scan_dir"]))
372
+ db.require_recorded_manifest_digest(scan, scan_dir)
373
+ db.verify_manifest_binding(scan, db.read_json_object(scan_dir / db.ARTIFACTS["manifest"]))
374
+ try:
375
+ manifest, _, _ = finalize_scan(
376
+ scan_dir,
377
+ expected_coverage_mode=db.expected_coverage_mode(scan),
378
+ )
379
+ except ContractError as exc:
380
+ raise SystemExit(str(exc)) from exc
381
+ db.verify_manifest_binding(scan, manifest)
382
+ manifest_digest = db.published_manifest_digest(scan_dir, manifest)
383
+ db.pin_legacy_manifest_digest(connection, scan["id"], manifest_digest)
384
+ if args.format == "json":
385
+ path = db.artifact_path(scan_dir, db.ARTIFACTS["findings"], required=True)
386
+ elif args.format == "sarif":
387
+ try:
388
+ write_sarif_projection(scan_dir)
389
+ except ContractError as exc:
390
+ raise SystemExit(str(exc)) from exc
391
+ path = db.artifact_path(scan_dir, "exports/results.sarif", required=True)
392
+ else:
393
+ path = write_csv_export(db, connection, scan)
394
+ if path is None:
395
+ raise SystemExit(f"Could not export Codex Security findings as {args.format.upper()}.")
396
+ return {
397
+ "export": {"format": args.format, "path": str(path)},
398
+ "scan": db.scan_result(connection, scan),
399
+ "workspace": db.workspace_state(connection, scan["workspace_id"]),
400
+ }
401
+
402
+
403
+ def write_csv_export(
404
+ db: WorkbenchPublicationContext,
405
+ connection: sqlite3.Connection,
406
+ scan: sqlite3.Row,
407
+ ) -> Path:
408
+ scan_dir = db.require_canonical_scan_directory(Path(scan["scan_dir"]))
409
+ output = io.StringIO(newline="")
410
+ writer = csv.writer(output)
411
+ deep_scan = scan["mode"] == "deep"
412
+ candidate_ids_by_occurrence: dict[str, str] = {}
413
+ if deep_scan:
414
+ findings_document = db.read_json_object(scan_dir / db.ARTIFACTS["findings"])
415
+ findings = findings_document.get("findings")
416
+ if not isinstance(findings, list):
417
+ raise SystemExit("findings.json must contain a findings array.")
418
+ for finding in findings:
419
+ if not isinstance(finding, dict):
420
+ raise SystemExit("findings.json entries must be objects.")
421
+ occurrence_id = finding.get("occurrenceId")
422
+ candidate_id = finding_candidate_id(finding)
423
+ if isinstance(occurrence_id, str) and isinstance(candidate_id, str):
424
+ candidate_ids_by_occurrence[occurrence_id] = candidate_id
425
+ columns = (
426
+ "occurrence_id",
427
+ "finding_id",
428
+ *(("candidate_id",) if deep_scan else ()),
429
+ "title",
430
+ "summary",
431
+ "severity",
432
+ "confidence",
433
+ "status",
434
+ "close_reason",
435
+ "note",
436
+ "remediation",
437
+ "path",
438
+ "start_line",
439
+ "end_line",
440
+ )
441
+ writer.writerow(columns)
442
+ for row in finding_export_rows(connection, scan["id"]):
443
+ writer.writerow(
444
+ (
445
+ csv_cell(row["occurrence_id"]),
446
+ csv_cell(row["finding_id"]),
447
+ *(
448
+ (csv_cell(candidate_ids_by_occurrence.get(row["occurrence_id"])),)
449
+ if deep_scan
450
+ else ()
451
+ ),
452
+ csv_cell(row["title"]),
453
+ csv_cell(row["summary"]),
454
+ csv_cell(row["severity"]),
455
+ csv_cell(row["confidence"]),
456
+ csv_cell(row["status"]),
457
+ csv_cell(row["close_reason"]),
458
+ csv_cell(row["note"]),
459
+ csv_cell(row["remediation"]),
460
+ csv_cell(row["relative_path"]),
461
+ row["start_line"],
462
+ row["end_line"],
463
+ )
464
+ )
465
+ try:
466
+ write_scan_local_bytes(
467
+ scan_dir,
468
+ "exports/findings.csv",
469
+ output.getvalue().encode("utf-8"),
470
+ )
471
+ except ContractError as exc:
472
+ raise SystemExit(
473
+ "exports: expected a regular directory inside the scan directory."
474
+ ) from exc
475
+ destination = scan_dir / "exports" / "findings.csv"
476
+ path = db.available_artifact_path(scan_dir, destination)
477
+ if path is None:
478
+ raise SystemExit("findings.csv: expected a regular file inside the scan directory.")
479
+ return path
480
+
481
+
482
+ def finding_export_rows(connection: sqlite3.Connection, scan_id: str) -> sqlite3.Cursor:
483
+ return connection.execute(
484
+ """
485
+ SELECT
486
+ occurrences.id AS occurrence_id,
487
+ occurrences.finding_id,
488
+ occurrences.title,
489
+ occurrences.summary,
490
+ occurrences.severity,
491
+ occurrences.confidence,
492
+ occurrences.remediation,
493
+ COALESCE(triage.status, 'open') AS status,
494
+ triage.close_reason,
495
+ triage.note,
496
+ locations.relative_path,
497
+ locations.start_line,
498
+ locations.end_line
499
+ FROM finding_occurrences AS occurrences
500
+ LEFT JOIN finding_triage AS triage ON triage.occurrence_id = occurrences.id
501
+ LEFT JOIN finding_locations AS locations
502
+ ON locations.occurrence_id = occurrences.id
503
+ AND locations.sort_order = (
504
+ SELECT primary_location.sort_order
505
+ FROM finding_locations AS primary_location
506
+ WHERE primary_location.occurrence_id = occurrences.id
507
+ ORDER BY
508
+ CASE WHEN primary_location.role = 'root_control' THEN 0 ELSE 1 END,
509
+ primary_location.sort_order
510
+ LIMIT 1
511
+ )
512
+ WHERE occurrences.scan_id = ?
513
+ ORDER BY occurrences.created_at, occurrences.id
514
+ """,
515
+ (scan_id,),
516
+ )
517
+
518
+
519
+ if __name__ == "__main__":
520
+ argparse.ArgumentParser(description=__doc__).parse_args()
@@ -53,6 +53,43 @@ def remediation_claim_is_active(remediation: sqlite3.Row) -> bool:
53
53
  return parsed > datetime.now(timezone.utc) - timedelta(seconds=lease_seconds)
54
54
 
55
55
 
56
+ def require_transition(current: str, requested: str) -> None:
57
+ allowed = {
58
+ "requested": {"requested", "generated", "failed"},
59
+ "generated": {"generated", "applied", "failed"},
60
+ "applied": {"applied", "verifying", "failed"},
61
+ "verifying": {"verifying", "verified", "failed"},
62
+ "verified": {"verifying", "verified"},
63
+ "failed": {"generated", "applied", "verifying", "verified", "failed"},
64
+ }
65
+ if requested not in allowed.get(current, set()):
66
+ raise SystemExit(f"Finding remediation cannot move from {current} to {requested}.")
67
+
68
+
69
+ def require_pending_action(current: sqlite3.Row, requested: str) -> None:
70
+ pending_action = current["pending_action"]
71
+ if pending_action is not None:
72
+ allowed = {
73
+ "generate": {"generated", "failed"},
74
+ "apply": {"applied", "failed"},
75
+ "verify": {"verifying", "verified", "failed"},
76
+ }
77
+ if requested not in allowed[pending_action]:
78
+ raise SystemExit(
79
+ f"Pending remediation action {pending_action} cannot record state {requested}."
80
+ )
81
+ return
82
+ required_action = {
83
+ ("requested", "generated"): "generate",
84
+ ("generated", "applied"): "apply",
85
+ ("applied", "verifying"): "verify",
86
+ }.get((current["state"], requested))
87
+ if required_action is not None:
88
+ raise SystemExit(
89
+ f"Request {required_action} before recording remediation state {requested}."
90
+ )
91
+
92
+
56
93
  def register_cancel_finding_remediation_request(subparsers: Any) -> None:
57
94
  parser = subparsers.add_parser("cancel-finding-remediation-request")
58
95
  parser.add_argument("--occurrence-id", required=True)