Skip to content

Examples and guides for using the OpenAI API

Fix security cookbook comparison table layout (#3038)

hreh-oaia78f3f37bd23
diff --git a/examples/agents_sdk/security_review_helpers.py b/examples/agents_sdk/security_review_helpers.py
index 0bd7b361..5709a2d4 100644
--- a/examples/agents_sdk/security_review_helpers.py
+++ b/examples/agents_sdk/security_review_helpers.py
@@ -1165,37 +1165,66 @@ def _text(value: Any, limit: int | None = 170) -> str:
# Model text stays literal; it cannot create Markdown links or images.
return "".join("\\" + char if char in "\\`*_{}[]()#+-.!|~$" else char for char in value)
-def show_table(title: str, rows: Sequence[Mapping[str, Any]], columns: Sequence[str]):
+def show_table(title: str, rows: Sequence[Mapping[str, Any]], columns: Sequence[str], *,
+ scrollable: bool = False):
rows = list(rows)
lines = [f"**{_text(title)}**", "",
"| " + " | ".join(map(_text, columns)) + " |",
"| " + " | ".join("---" for _ in columns) + " |"]
body = ["| " + " | ".join(_text(row.get(column, "")) for column in columns)
+ " |" for row in rows]
- display(Markdown("\n".join((*lines, *body))))
-
-def show_review_details(reviews: Mapping[str, Any]):
- pending = [
- (target, finding)
- for target, bundle in reviews.items()
- for finding in (bundle.provenance.findings if bundle.provenance else ())
- if finding.disposition == "needs_review"
- ]
- if not pending:
- return
- lines = ["**Findings that need more evidence**", ""]
- for target, finding in pending:
- location = f"{finding.source_path}:{finding.line}"
- lines.extend([
- f"**{_text(target)} — {_text(location, None)}**", "",
- f"Candidate: {_text(finding.candidate_id, None)}", "",
- _text(finding.reason, None), "",
- *(f"- Proof gap: {_text(gap, None)}" for gap in finding.proof_gaps), "",
- ])
+ if scrollable:
+ label = html.escape(f"{title} review results", quote=True)
+ opening = (f'<div role="region" aria-label="{label}" tabindex="0" '
+ 'style="overflow-x: auto;">')
+ lines = [*lines[:2], opening, "", *lines[2:], *body, "", "</div>"]
+ else:
+ lines.extend(body)
display(Markdown("\n".join(lines)))
-def result_rows(target: str, bundle: Any):
- label = f"{target} / {', '.join(bundle.selected_scanners) or 'none'}"
+def _finding_label(finding: Any) -> str:
+ words = finding.category.split("_")
+ category = " ".join(word.upper() if word in {"sql", "jwt", "tls"} else word for word in words)
+ return f"{finding.priority} / {category}"
+
+def _source_link(snapshot: SourceSnapshot, finding: Any) -> Markdown:
+ path = _safe_path(finding.source_path)
+ source = snapshot.file(path)
+ repository = snapshot.source_url.rstrip("/")
+ revision = snapshot.source_revision
+ if (not re.fullmatch(r"https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository)
+ or not re.fullmatch(r"[0-9a-f]{40}", revision)
+ or finding.source_revision != revision or finding.source_sha256 != source.sha256
+ or type(finding.line) is not int or finding.line < 1):
+ raise EvidenceError("Display link does not match a pinned GitHub source record.")
+ file = PurePosixPath(path)
+ label = "/".join(file.parts[-2:])
+ if len(label) > 28:
+ label = file.name
+ if len(label) > 28:
+ label = f"{file.stem[:27 - len(file.suffix)]}…{file.suffix}"
+ url = f"{repository}/blob/{revision}/{quote(path, safe='/')}#L{finding.line}"
+ return Markdown(f"[{_text(label, None)}:{finding.line}]({url})")
+
+def show_review_details(reviews: Mapping[str, Any]):
+ lines = ["**Decision notes**", ""]
+ for target, bundle in reviews.items():
+ repository = bundle.snapshot.source_url.rstrip("/").rsplit("/", 1)[-1] if bundle.snapshot else target
+ for finding in (bundle.provenance.findings if bundle.provenance else ()):
+ location = _source_link(bundle.snapshot, finding).data
+ lines.extend([
+ f"**{_text(repository)} / {_text(_finding_label(finding))} — {location}**", "",
+ f"Candidate: {_text(finding.candidate_id, None)} · {_text(finding.disposition)}", "",
+ _text(finding.reason, None), "",
+ *(f"- Proof gap: {_text(gap, None)}" for gap in finding.proof_gaps), "",
+ ])
+ if not bundle.provenance and bundle.error:
+ lines.extend([f"**{_text(target)} — {_text(bundle.status)}**", "",
+ _text(bundle.error, None), ""])
+ if len(lines) > 2:
+ display(Markdown("\n".join(lines)))
+
+def result_rows(bundle: Any):
role_by_candidate = {
assessment.candidate_id: review.role
for review in bundle.specialist_reviews
@@ -1209,20 +1238,15 @@ def result_rows(target: str, bundle: Any):
for candidate in bundle.candidates:
model_finding = proposed.get(candidate.candidate_id)
final_finding = final.get(candidate.candidate_id)
- reason = getattr(final_finding, "reason", None) or getattr(model_finding, "reason", "not reviewed")
- gaps = getattr(final_finding, "proof_gaps", ()) or getattr(model_finding, "proof_gaps", ())
rows.append({
- "target / scanners": label,
- "signal": f"{candidate.priority} / {candidate.category}",
- "source": f"{candidate.source_path}:{candidate.line}",
+ "finding": _finding_label(candidate),
+ "source": _source_link(bundle.snapshot, candidate),
"specialist": role_by_candidate.get(candidate.candidate_id, "not run"),
"validator": getattr(model_finding, "disposition", "not run"),
"final": getattr(final_finding, "disposition", "not adjudicated"),
- "reason or gap": f"{reason} Proof gap: {', '.join(gaps)}" if gaps else reason,
})
if not rows:
- rows.append({"target / scanners": label, "signal": bundle.status,
+ rows.append({"finding": bundle.status,
"source": "none", "specialist": "not run", "validator": "not run",
- "final": "not adjudicated",
- "reason or gap": bundle.error or "No candidates were reviewed."})
+ "final": "not adjudicated"})
return rows
diff --git a/examples/agents_sdk/security_scanners_with_agents_sdk.ipynb b/examples/agents_sdk/security_scanners_with_agents_sdk.ipynb
index 7fa2bd99..8c089586 100644
--- a/examples/agents_sdk/security_scanners_with_agents_sdk.ipynb
+++ b/examples/agents_sdk/security_scanners_with_agents_sdk.ipynb
@@ -696,7 +696,9 @@
"source": [
"The `specialist` column shows which specialist the manager called, and `final` shows the decision after the evidence checks. Notice the saved JWT result. It stays `needs_review` because the upstream verifier isn't part of the approved source. We'd need to inspect that verifier or show a bypass before making a stronger claim.\n",
"\n",
- "The crAPI SQL candidate needs more evidence too. We can see the serializer check, but not its validation rules.\n"
+ "The crAPI SQL candidate needs more evidence too. We can see the serializer check, but not its validation rules.\n",
+ "\n",
+ "The source links open the pinned files at the reported lines. Full reasons and proof gaps follow the tables. On small screens, scroll the tables horizontally.\n"
]
},
{
@@ -715,20 +717,17 @@
{
"data": {
"text/markdown": [
- "**Observed routing and findings**\n",
+ "**VulnerableApp / semgrep**\n",
"\n",
- "| target / scanners | signal | source | specialist | validator | final | reason or gap |\n",
- "| --- | --- | --- | --- | --- | --- | --- |\n",
- "| vulnerableapp / semgrep | P1 / sql\\_injection | src/main/java/org/sasanlabs/service/vulnerability/sqlInjection/BlindSQLInjectionVulnerability\\.java:58 | injection | confirmed | confirmed | The ID value is read directly from the request\\-parameter map and concatenated into an unquoted SQL expression passed to applicationJdbcTemplate\\.query\\. No validation, esc… |\n",
- "| vulnerableapp / semgrep | P1 / sql\\_injection | src/main/java/org/sasanlabs/service/vulnerability/sqlInjection/BlindSQLInjectionVulnerability\\.java:82 | injection | confirmed | confirmed | The ID value is read from the request\\-parameter map and concatenated inside a quoted SQL literal passed to applicationJdbcTemplate\\.query\\. With no escaping, validation, o… |\n",
- "| vulnerableapp / semgrep | P1 / sql\\_injection | src/main/java/org/sasanlabs/service/vulnerability/sqlInjection/BlindSQLInjectionVulnerability\\.java:132 | injection | not\\_actionable | not\\_actionable | The dominating id\\.matches\\(\"\\\\\\\\d\\+\"\\) check rejects the request unless the entire ID consists of one or more digits\\. Thus, although the accepted value is concatenated into a… |\n",
- "| crapi / semgrep, bandit | P2 / jwt\\_verification\\_disabled | services/workshop/utils/jwt\\.py:61 | authentication | needs\\_review | needs\\_review | The Bearer token is decoded without signature verification and its \\`sub\\` selects the user, but only after the same token is submitted to \\`IDENTITY\\_VERIFY\\` and that servi… |\n",
- "| crapi / semgrep, bandit | P2 / request\\_timeout | services/workshop/crapi/merchant/views\\.py:87 | configuration | confirmed | confirmed | Validated request data supplies the \\`mechanic\\_api\\` destination and can enable repeated calls\\. Although repeats are capped, \\`requests\\.get\\` has no timeout, so any individu… |\n",
- "| crapi / semgrep, bandit | P2 / tls\\_verification\\_disabled | services/workshop/crapi/shop/views\\.py:141 | configuration | confirmed | confirmed | The payment request to the configured gateway explicitly sets \\`verify=False\\`, disabling TLS certificate verification\\. The fixed destination, Basic authentication, and fi… |\n",
- "| crapi / semgrep, bandit | P2 / request\\_timeout | services/workshop/utils/jwt\\.py:53 | configuration | not\\_actionable | not\\_actionable | A Bearer token triggers one timeout\\-free request to the fixed \\`IDENTITY\\_VERIFY\\` destination, but the supplied source shows no request\\-controlled loop or repeated outboun… |\n",
- "| crapi / semgrep, bandit | P2 / tls\\_verification\\_disabled | services/workshop/crapi/merchant/views\\.py:87 | configuration | confirmed | confirmed | After serializer validation, the request\\-controlled \\`mechanic\\_api\\` is passed to \\`requests\\.get\\` with \\`verify=False\\`\\. Validation and the repeat limit do not change the sin… |\n",
- "| crapi / semgrep, bandit | P2 / tls\\_verification\\_disabled | services/workshop/utils/jwt\\.py:53 | configuration | confirmed | confirmed | The Bearer token is posted to the configured identity endpoint using \\`verify=False\\`, explicitly disabling TLS certificate verification\\. The Bearer\\-prefix and HTTP\\-200 ch… |\n",
- "| crapi / semgrep, bandit | P1 / sql\\_injection | services/workshop/crapi/shop/views\\.py:388 | injection | needs\\_review | needs\\_review | The raw \\`coupon\\_code\\` is concatenated inside a quoted SQL predicate and passed to \\`cursor\\.execute\\` without parameter binding\\. However, \\`CouponSerializer\\.is\\_valid\\(\\)\\` domi… |"
+ "<div role=\"region\" aria-label=\"VulnerableApp / semgrep review results\" tabindex=\"0\" style=\"overflow-x: auto;\">\n",
+ "\n",
+ "| finding | source | specialist | validator | final |\n",
+ "| --- | --- | --- | --- | --- |\n",
+ "| P1 / SQL injection | [BlindSQLInjectionVulne…\\.java:58](https://github.com/SasanLabs/VulnerableApp/blob/668ab14704b63d286bc73f5ec302885a5f192c2e/src/main/java/org/sasanlabs/service/vulnerability/sqlInjection/BlindSQLInjectionVulnerability.java#L58) | injection | confirmed | confirmed |\n",
+ "| P1 / SQL injection | [BlindSQLInjectionVulne…\\.java:82](https://github.com/SasanLabs/VulnerableApp/blob/668ab14704b63d286bc73f5ec302885a5f192c2e/src/main/java/org/sasanlabs/service/vulnerability/sqlInjection/BlindSQLInjectionVulnerability.java#L82) | injection | confirmed | confirmed |\n",
+ "| P1 / SQL injection | [BlindSQLInjectionVulne…\\.java:132](https://github.com/SasanLabs/VulnerableApp/blob/668ab14704b63d286bc73f5ec302885a5f192c2e/src/main/java/org/sasanlabs/service/vulnerability/sqlInjection/BlindSQLInjectionVulnerability.java#L132) | injection | not\\_actionable | not\\_actionable |\n",
+ "\n",
+ "</div>"
],
"text/plain": [
"<IPython.core.display.Markdown object>"
@@ -740,19 +739,101 @@
{
"data": {
"text/markdown": [
- "**Findings that need more evidence**\n",
+ "**crAPI / semgrep, bandit**\n",
+ "\n",
+ "<div role=\"region\" aria-label=\"crAPI / semgrep, bandit review results\" tabindex=\"0\" style=\"overflow-x: auto;\">\n",
+ "\n",
+ "| finding | source | specialist | validator | final |\n",
+ "| --- | --- | --- | --- | --- |\n",
+ "| P2 / JWT verification disabled | [utils/jwt\\.py:61](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/utils/jwt.py#L61) | authentication | needs\\_review | needs\\_review |\n",
+ "| P2 / request timeout | [merchant/views\\.py:87](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/crapi/merchant/views.py#L87) | configuration | confirmed | confirmed |\n",
+ "| P2 / TLS verification disabled | [shop/views\\.py:141](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/crapi/shop/views.py#L141) | configuration | confirmed | confirmed |\n",
+ "| P2 / request timeout | [utils/jwt\\.py:53](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/utils/jwt.py#L53) | configuration | not\\_actionable | not\\_actionable |\n",
+ "| P2 / TLS verification disabled | [merchant/views\\.py:87](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/crapi/merchant/views.py#L87) | configuration | confirmed | confirmed |\n",
+ "| P2 / TLS verification disabled | [utils/jwt\\.py:53](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/utils/jwt.py#L53) | configuration | confirmed | confirmed |\n",
+ "| P1 / SQL injection | [shop/views\\.py:388](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/crapi/shop/views.py#L388) | injection | needs\\_review | needs\\_review |\n",
+ "\n",
+ "</div>"
+ ],
+ "text/plain": [
+ "<IPython.core.display.Markdown object>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "data": {
+ "text/markdown": [
+ "**Decision notes**\n",
+ "\n",
+ "**VulnerableApp / P1 / SQL injection — [BlindSQLInjectionVulne…\\.java:58](https://github.com/SasanLabs/VulnerableApp/blob/668ab14704b63d286bc73f5ec302885a5f192c2e/src/main/java/org/sasanlabs/service/vulnerability/sqlInjection/BlindSQLInjectionVulnerability.java#L58)**\n",
+ "\n",
+ "Candidate: cand\\-3a08cb808092a9aa · confirmed\n",
+ "\n",
+ "The ID value is read directly from the request\\-parameter map and concatenated into an unquoted SQL expression passed to applicationJdbcTemplate\\.query\\. No validation, escaping, or parameter binding constrains the input reaching SQL syntax\\.\n",
+ "\n",
+ "\n",
+ "**VulnerableApp / P1 / SQL injection — [BlindSQLInjectionVulne…\\.java:82](https://github.com/SasanLabs/VulnerableApp/blob/668ab14704b63d286bc73f5ec302885a5f192c2e/src/main/java/org/sasanlabs/service/vulnerability/sqlInjection/BlindSQLInjectionVulnerability.java#L82)**\n",
+ "\n",
+ "Candidate: cand\\-b0200b4d7f6369aa · confirmed\n",
+ "\n",
+ "The ID value is read from the request\\-parameter map and concatenated inside a quoted SQL literal passed to applicationJdbcTemplate\\.query\\. With no escaping, validation, or parameter binding, input can terminate the literal and alter SQL syntax\\.\n",
"\n",
- "**crapi — services/workshop/utils/jwt\\.py:61**\n",
"\n",
- "Candidate: cand\\-1742b9ae3963a27c\n",
+ "**VulnerableApp / P1 / SQL injection — [BlindSQLInjectionVulne…\\.java:132](https://github.com/SasanLabs/VulnerableApp/blob/668ab14704b63d286bc73f5ec302885a5f192c2e/src/main/java/org/sasanlabs/service/vulnerability/sqlInjection/BlindSQLInjectionVulnerability.java#L132)**\n",
+ "\n",
+ "Candidate: cand\\-e1a8f6aa6a73b42a · not\\_actionable\n",
+ "\n",
+ "The dominating id\\.matches\\(\"\\\\\\\\d\\+\"\\) check rejects the request unless the entire ID consists of one or more digits\\. Thus, although the accepted value is concatenated into an unquoted numeric position, SQL syntax\\-changing characters cannot reach the query\\.\n",
+ "\n",
+ "\n",
+ "**crAPI / P2 / JWT verification disabled — [utils/jwt\\.py:61](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/utils/jwt.py#L61)**\n",
+ "\n",
+ "Candidate: cand\\-1742b9ae3963a27c · needs\\_review\n",
"\n",
"The Bearer token is decoded without signature verification and its \\`sub\\` selects the user, but only after the same token is submitted to \\`IDENTITY\\_VERIFY\\` and that service returns HTTP 200\\. No verifier implementation or demonstrated bypass establishes whether this upstream control cryptographically validates the token; \\`verify=False\\` disables TLS certificate checks but does not itself prove acceptance of an unsigned token\\.\n",
"\n",
"- Proof gap: The implementation or contract of \\`IDENTITY\\_VERIFY\\` is missing: it is unknown whether it cryptographically verifies the submitted token and returns 200 only when that same token is valid\\.\n",
"\n",
- "**crapi — services/workshop/crapi/shop/views\\.py:388**\n",
+ "**crAPI / P2 / request timeout — [merchant/views\\.py:87](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/crapi/merchant/views.py#L87)**\n",
+ "\n",
+ "Candidate: cand\\-3638cc76cae2d1d0 · confirmed\n",
+ "\n",
+ "Validated request data supplies the \\`mechanic\\_api\\` destination and can enable repeated calls\\. Although repeats are capped, \\`requests\\.get\\` has no timeout, so any individual attempt can wait without that bound and repetition amplifies the source\\-level availability risk\\.\n",
+ "\n",
+ "\n",
+ "**crAPI / P2 / TLS verification disabled — [shop/views\\.py:141](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/crapi/shop/views.py#L141)**\n",
+ "\n",
+ "Candidate: cand\\-4313414a28b1fa7e · confirmed\n",
+ "\n",
+ "The payment request to the configured gateway explicitly sets \\`verify=False\\`, disabling TLS certificate verification\\. The fixed destination, Basic authentication, and five\\-second timeout do not restore peer\\-certificate validation\\.\n",
+ "\n",
+ "\n",
+ "**crAPI / P2 / request timeout — [utils/jwt\\.py:53](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/utils/jwt.py#L53)**\n",
+ "\n",
+ "Candidate: cand\\-4d3e7a03920b3819 · not\\_actionable\n",
+ "\n",
+ "A Bearer token triggers one timeout\\-free request to the fixed \\`IDENTITY\\_VERIFY\\` destination, but the supplied source shows no request\\-controlled loop or repeated outbound call\\. On this narrow evidence, the missing timeout is hardening rather than a demonstrated availability issue\\.\n",
+ "\n",
+ "\n",
+ "**crAPI / P2 / TLS verification disabled — [merchant/views\\.py:87](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/crapi/merchant/views.py#L87)**\n",
+ "\n",
+ "Candidate: cand\\-85661410cf96c620 · confirmed\n",
+ "\n",
+ "After serializer validation, the request\\-controlled \\`mechanic\\_api\\` is passed to \\`requests\\.get\\` with \\`verify=False\\`\\. Validation and the repeat limit do not change the sink's explicitly disabled TLS certificate verification for HTTPS targets\\.\n",
+ "\n",
+ "\n",
+ "**crAPI / P2 / TLS verification disabled — [utils/jwt\\.py:53](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/utils/jwt.py#L53)**\n",
+ "\n",
+ "Candidate: cand\\-896f29e345909523 · confirmed\n",
+ "\n",
+ "The Bearer token is posted to the configured identity endpoint using \\`verify=False\\`, explicitly disabling TLS certificate verification\\. The Bearer\\-prefix and HTTP\\-200 checks do not authenticate the TLS peer\\.\n",
+ "\n",
+ "\n",
+ "**crAPI / P1 / SQL injection — [shop/views\\.py:388](https://github.com/OWASP/crAPI/blob/700f03d12a392d9e408260b4beae72ed02a4a1a4/services/workshop/crapi/shop/views.py#L388)**\n",
"\n",
- "Candidate: cand\\-9c16875f717198fb\n",
+ "Candidate: cand\\-9c16875f717198fb · needs\\_review\n",
"\n",
"The raw \\`coupon\\_code\\` is concatenated inside a quoted SQL predicate and passed to \\`cursor\\.execute\\` without parameter binding\\. However, \\`CouponSerializer\\.is\\_valid\\(\\)\\` dominates the sink, and its missing rules could reject every value capable of altering SQL syntax\\.\n",
"\n",
@@ -767,15 +848,12 @@
}
],
"source": [
- "rows = [\n",
- " row\n",
- " for target, bundle in target_reviews.items()\n",
- " for row in result_rows(target, bundle)\n",
- "]\n",
- "show_table(\"Observed routing and findings\", rows, (\n",
- " \"target / scanners\", \"signal\", \"source\", \"specialist\",\n",
- " \"validator\", \"final\", \"reason or gap\",\n",
- "))\n",
+ "for target, bundle in target_reviews.items():\n",
+ " repository = bundle.snapshot.source_url.rstrip(\"/\").rsplit(\"/\", 1)[-1] if bundle.snapshot else target\n",
+ " scanners = \", \".join(bundle.selected_scanners) or \"none\"\n",
+ " show_table(f\"{repository} / {scanners}\", result_rows(bundle), (\n",
+ " \"finding\", \"source\", \"specialist\", \"validator\", \"final\",\n",
+ " ), scrollable=True)\n",
"show_review_details(target_reviews)\n"
]
},
diff --git a/examples/agents_sdk/tests/test_security_review_repository_labels.py b/examples/agents_sdk/tests/test_security_review_repository_labels.py
new file mode 100644
index 00000000..ad91db85
--- /dev/null
+++ b/examples/agents_sdk/tests/test_security_review_repository_labels.py
@@ -0,0 +1,68 @@
+"""Offline checks for the security notebook's comparison-table labels.
+
+Run with: python -m unittest discover -s examples/agents_sdk/tests
+The metadata fixtures are not scanned or used as evidence; only the display cell runs.
+"""
+
+import json
+import sys
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+EXAMPLE_DIR = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(EXAMPLE_DIR))
+import security_review_helpers as helpers
+
+
+class RepositoryLabelTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ notebook = json.loads((EXAMPLE_DIR / "security_scanners_with_agents_sdk.ipynb").read_text(encoding="utf-8"))
+ cell = next(cell for cell in notebook["cells"] if cell["id"] == "security-swarm-24")
+ cls.display_code = compile("".join(cell["source"]), "<comparison-display>", "exec")
+
+ def render_comparison(self, repository):
+ snapshot = None
+ if repository is not None:
+ manifest = helpers.TargetManifest(
+ target_id="fixture", repository=repository, release="fixture", commit="1" * 40,
+ approved_files=(helpers.ApprovedFile(path="app.py", sha256="0" * 64),),
+ )
+ snapshot = helpers.SourceSnapshot(
+ root=EXAMPLE_DIR, target_id=manifest.target_id, source_url=manifest.repository,
+ source_revision=manifest.commit, snapshot_digest="2" * 64,
+ files=(helpers.SourceFile(path="app.py", sha256="0" * 64,
+ size_bytes=0, production_source=True),),
+ )
+ bundle = helpers.ReviewBundle(
+ status="partial" if snapshot else "not_authorized", target_id="fixture",
+ snapshot=snapshot, selected_scanners=("semgrep", "bandit") if snapshot else (),
+ )
+ captured = []
+ with patch.object(helpers, "display", captured.append):
+ exec(self.display_code, {
+ "target_reviews": {"fixture": bundle}, "show_table": helpers.show_table,
+ "result_rows": helpers.result_rows, "show_review_details": helpers.show_review_details,
+ })
+ self.assertEqual(len(captured), 1)
+ return captured[0].data
+
+ def test_repository_name_without_trailing_slash(self):
+ markdown = self.render_comparison("https://github.com/OWASP/crAPI")
+ self.assertTrue(markdown.startswith("**crAPI / semgrep, bandit**\n"))
+ self.assertIn('aria-label="crAPI / semgrep, bandit review results"', markdown)
+
+ def test_accepted_trailing_slash_preserves_title_and_accessible_label(self):
+ plain = self.render_comparison("https://github.com/OWASP/crAPI")
+ trailing = self.render_comparison("https://github.com/OWASP/crAPI/")
+ self.assertEqual(trailing, plain)
+
+ def test_missing_snapshot_uses_target_identifier(self):
+ markdown = self.render_comparison(None)
+ self.assertTrue(markdown.startswith("**fixture / none**\n"))
+ self.assertIn('aria-label="fixture / none review results"', markdown)
+
+
+if __name__ == "__main__":
+ unittest.main()