| 1 | """Security regression tests for PR09 (HIGH-207, HIGH-210, HIGH-211, HIGH-212, HIGH-215). |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-207: Watchlist webhook SSRF, hostname/userinfo/DNS validation, and no-redirect guards |
| 5 | - HIGH-210: Fail-closed public_markdown redaction (unclosed blocks, legacy sections, drills, clusters) |
| 6 | - HIGH-211: Symlink, FIFO, containment, and size-cap hardening in library scanning |
| 7 | - HIGH-212: Safe FTS5 query tokenization, operator/column injection defense, and dismissed filtering |
| 8 | - HIGH-215: Symlink/FIFO/parent-dir rejection and sidecar 0o600 hardening in library_index._connect |
| 9 | """ |
| 10 | |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import json |
| 14 | import os |
| 15 | import socket |
| 16 | import sqlite3 |
| 17 | import stat |
| 18 | import urllib.error |
| 19 | from contextlib import closing |
| 20 | from pathlib import Path |
| 21 | from unittest.mock import Mock, patch |
| 22 | |
| 23 | import pytest |
| 24 | |
| 25 | import store |
| 26 | import watchlist |
| 27 | from lib import html_render, http, library, library_index, public_host |
| 28 | |
| 29 | |
| 30 | # --------------------------------------------------------------------------- |
| 31 | # HIGH-207: Watchlist webhook SSRF, hostname/userinfo validation, redirects |
| 32 | # --------------------------------------------------------------------------- |
| 33 | |
| 34 | |
| 35 | @pytest.fixture |
| 36 | def isolated_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: |
| 37 | db_path = tmp_path / "research.db" |
| 38 | monkeypatch.setattr(store, "_db_override", db_path) |
| 39 | store.init_db() |
| 40 | return db_path |
| 41 | |
| 42 | |
| 43 | @pytest.mark.parametrize( |
| 44 | "bad_url", |
| 45 | [ |
| 46 | "http://hooks.slack.com/services/T000/B000/XXXX", |
| 47 | "https://", |
| 48 | "https:///path", |
| 49 | "https://user:pass@hooks.slack.com/services/T000/B000/XXXX", |
| 50 | "https://hooks.slack.com@evil.example/hook", |
| 51 | "https://hooks.slack.com\\@127.0.0.1/hook", |
| 52 | "https://localhost/hook", |
| 53 | "https://LOCALHOST/hook", |
| 54 | "https://sub.localhost./hook", |
| 55 | "https://127.0.0.1/hook", |
| 56 | "https://127.0.0.1:8443/hook", |
| 57 | "https://127.1/hook", |
| 58 | "https://0x7f000001/hook", |
| 59 | "https://2130706433/hook", |
| 60 | "https://0177.0.0.1/hook", |
| 61 | "https://[::1]/hook", |
| 62 | "https://10.0.0.1/hook", |
| 63 | "https://172.16.0.1/hook", |
| 64 | "https://192.168.1.1/hook", |
| 65 | "https://169.254.169.254/latest/meta-data/", |
| 66 | "https://100.64.0.1/hook", |
| 67 | "https://0.0.0.0/hook", |
| 68 | "https://[::ffff:127.0.0.1]/hook", |
| 69 | "https://[::ffff:169.254.169.254]/hook", |
| 70 | "https://[64:ff9b::127.0.0.1]/hook", |
| 71 | "https://[fe80::1%25eth0]/hook", |
| 72 | "https://hooks.slack.com/hook\r\nX-Injected: 1", |
| 73 | "https://hooks.slack.com/hook\x85next", |
| 74 | "https://hooks.slack.com/hook\x9b31m", |
| 75 | " https://hooks.slack.com/hook", |
| 76 | "https://hooks.slack.com/hook ", |
| 77 | "https://hooks.slack.com:0/hook", |
| 78 | "https://hooks.slack.com:70000/hook", |
| 79 | "https://hooks.slack.com:notaport/hook", |
| 80 | "https://\uff11\uff12\uff17.\uff10.\uff10.\uff11/hook", |
| 81 | "https://\uff4c\uff4f\uff43\uff41\uff4c\uff48\uff4f\uff53\uff54/hook", |
| 82 | "https://foo\u3002localhost/hook", |
| 83 | "https://intranet/hook", |
| 84 | "https://metadata.google.internal/computeMetadata/v1/", |
| 85 | "https://printer.local/hook", |
| 86 | "https://host.localdomain/hook", |
| 87 | "https://1.0.0.127.in-addr.arpa/hook", |
| 88 | ], |
| 89 | ) |
| 90 | def test_high207_config_and_delivery_reject_unsafe_webhook_urls( |
| 91 | isolated_store: Path, capsys: pytest.CaptureFixture[str], bad_url: str |
| 92 | ): |
| 93 | args = Mock(key="delivery", value=bad_url) |
| 94 | with pytest.raises(SystemExit) as exc_info: |
| 95 | watchlist.cmd_config(args) |
| 96 | if bad_url != "https://": |
| 97 | assert bad_url not in str(exc_info.value) |
| 98 | assert not store.get_setting("delivery_channel") |
| 99 | |
| 100 | store.set_setting("delivery_channel", bad_url) |
| 101 | with patch("watchlist.http.post_raw") as mock_post: |
| 102 | watchlist._deliver_findings("AI agents", {"new": 2, "updated": 0}) |
| 103 | mock_post.assert_not_called() |
| 104 | err = capsys.readouterr().err |
| 105 | assert "Delivery skipped" in err or "Delivery failed" in err |
| 106 | if bad_url != "https://": |
| 107 | assert bad_url not in err |
| 108 | |
| 109 | with patch("watchlist.http.post_raw") as mock_post: |
| 110 | with pytest.raises(ValueError) as val_exc: |
| 111 | watchlist._send_slack_webhook(bad_url, "hi") |
| 112 | if bad_url != "https://": |
| 113 | assert bad_url not in str(val_exc.value) |
| 114 | with pytest.raises(ValueError) as val_exc2: |
| 115 | watchlist._send_generic_webhook(bad_url, "hi") |
| 116 | if bad_url != "https://": |
| 117 | assert bad_url not in str(val_exc2.value) |
| 118 | mock_post.assert_not_called() |
| 119 | |
| 120 | |
| 121 | def test_high207_valid_public_webhook_preserves_query_fragment_and_public_ipv6( |
| 122 | isolated_store: Path, |
| 123 | ): |
| 124 | for valid_url in ( |
| 125 | "https://hooks.slack.com/services/T/B/X?token=abc&mode=1#section", |
| 126 | "https://hooks.slack.com./services/T/B/X", |
| 127 | "https://webhook.example.com:8443/hook?a=1#frag", |
| 128 | "https://[2606:2800:220:1:248:1893:25c8:1946]/hook?k=v#f", |
| 129 | ): |
| 130 | parsed = watchlist._validate_webhook_url(valid_url) |
| 131 | assert parsed.scheme == "https" |
| 132 | args = Mock(key="delivery", value=valid_url) |
| 133 | watchlist.cmd_config(args) |
| 134 | assert store.get_setting("delivery_channel") == valid_url |
| 135 | |
| 136 | |
| 137 | @pytest.mark.parametrize( |
| 138 | "resolved_ips", |
| 139 | [ |
| 140 | ["127.0.0.1"], |
| 141 | ["10.0.0.5"], |
| 142 | ["169.254.169.254"], |
| 143 | ["::1"], |
| 144 | ["::ffff:127.0.0.1"], |
| 145 | ["93.184.216.34", "10.0.0.5"], |
| 146 | ], |
| 147 | ) |
| 148 | def test_high207_dns_resolving_to_private_ip_blocked_at_delivery_before_connect( |
| 149 | isolated_store: Path, |
| 150 | monkeypatch: pytest.MonkeyPatch, |
| 151 | capsys: pytest.CaptureFixture[str], |
| 152 | resolved_ips: list[str], |
| 153 | ): |
| 154 | def fake_getaddrinfo(name, port, *_args, **_kwargs): |
| 155 | results = [] |
| 156 | for ip in resolved_ips: |
| 157 | family = socket.AF_INET6 if ":" in ip else socket.AF_INET |
| 158 | sockaddr = (ip, port or 443, 0, 0) if family == socket.AF_INET6 else (ip, port or 443) |
| 159 | results.append((family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", sockaddr)) |
| 160 | return results |
| 161 | |
| 162 | monkeypatch.setattr(public_host.socket, "getaddrinfo", fake_getaddrinfo) |
| 163 | url = "https://internal-hook.example/notify" |
| 164 | store.set_setting("delivery_channel", url) |
| 165 | |
| 166 | with patch("lib.http.socket.socket") as mock_socket: |
| 167 | watchlist._deliver_findings("AI agents", {"new": 1, "updated": 0}) |
| 168 | mock_socket.assert_not_called() |
| 169 | err = capsys.readouterr().err |
| 170 | assert "Delivery failed" in err |
| 171 | assert url not in err |
| 172 | |
| 173 | with pytest.raises(http.HTTPError, match="non-public"): |
| 174 | watchlist._send_generic_webhook(url, "hi") |
| 175 | mock_socket.assert_not_called() |
| 176 | |
| 177 | |
| 178 | def test_high207_webhook_transport_enforces_public_only_no_redirect_and_rebinding_defense( |
| 179 | monkeypatch: pytest.MonkeyPatch, |
| 180 | ): |
| 181 | captured_requests = [] |
| 182 | with patch("watchlist.http._open_request") as open_request: |
| 183 | response = open_request.return_value.__enter__.return_value |
| 184 | response.status = 200 |
| 185 | response.read.return_value = b"{}" |
| 186 | |
| 187 | watchlist._send_slack_webhook("https://hooks.slack.com/services/T/B/X", "hello") |
| 188 | captured_requests.append(open_request.call_args.args[0]) |
| 189 | watchlist._send_generic_webhook("https://webhook.example/hook", "hello") |
| 190 | captured_requests.append(open_request.call_args.args[0]) |
| 191 | |
| 192 | handler = http._StripAuthOnCrossOriginRedirect() |
| 193 | for req in captured_requests: |
| 194 | assert getattr(req, http._PUBLIC_ONLY_ATTR, False) is True |
| 195 | guard = getattr(req, http._REDIRECT_GUARD_ATTR, None) |
| 196 | assert callable(guard) |
| 197 | for code, target in ( |
| 198 | (301, "https://webhook.example/v2"), |
| 199 | (302, "http://169.254.169.254/latest/meta-data/"), |
| 200 | (303, "http://127.0.0.1:8080/admin"), |
| 201 | (307, "https://other.example/steal"), |
| 202 | (308, "http://[::1]/internal"), |
| 203 | ): |
| 204 | assert guard(target) is False |
| 205 | with pytest.raises(urllib.error.HTTPError) as exc_info: |
| 206 | handler.redirect_request(req, None, code, "Redirect", {}, target) |
| 207 | assert exc_info.value.code == 403 |
| 208 | |
| 209 | # DNS rebinding: connect-time lookup resolves fresh and refuses loopback before socket.socket(). |
| 210 | monkeypatch.setattr( |
| 211 | public_host.socket, |
| 212 | "getaddrinfo", |
| 213 | lambda name, port, *_a, **_kw: [ |
| 214 | (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", port or 443)) |
| 215 | ], |
| 216 | ) |
| 217 | with patch("lib.http.socket.socket") as mock_socket: |
| 218 | with pytest.raises(http.HTTPError, match="non-public"): |
| 219 | watchlist._send_generic_webhook("https://rebind.example/hook", "hello") |
| 220 | mock_socket.assert_not_called() |
| 221 | |
| 222 | |
| 223 | # --------------------------------------------------------------------------- |
| 224 | # HIGH-210: public_markdown fail-open redaction bypasses |
| 225 | # --------------------------------------------------------------------------- |
| 226 | |
| 227 | |
| 228 | def test_high210_unclosed_private_corpus_start_fails_closed(tmp_path: Path): |
| 229 | md = ( |
| 230 | "# last30days v4.5.0: Routing\n\n" |
| 231 | "- Date range: 2026-06-10 to 2026-07-10\n\n" |
| 232 | "## Public Overview\n\n" |
| 233 | "Public routing finding stays visible.\n\n" |
| 234 | f"{library.PRIVATE_CORPUS_START}\n" |
| 235 | "## From your files\n\n" |
| 236 | "UNCLOSED_SECRET_CORPUS_PAYLOAD\n" |
| 237 | "Second secret line at EOF.\n" |
| 238 | ) |
| 239 | sanitized = library.public_markdown(md) |
| 240 | assert "Public routing finding stays visible." in sanitized |
| 241 | assert "UNCLOSED_SECRET_CORPUS_PAYLOAD" not in sanitized |
| 242 | assert "Second secret line at EOF." not in sanitized |
| 243 | assert library.PRIVATE_CORPUS_START not in sanitized |
| 244 | |
| 245 | # Closed block followed by public middle followed by an unclosed block. |
| 246 | mixed = ( |
| 247 | "# last30days v4.5.0: Mixed\n\n" |
| 248 | f"{library.PRIVATE_CORPUS_START}\nFIRST_SECRET\n{library.PRIVATE_CORPUS_END}\n\n" |
| 249 | "## Public Middle\n\nPUBLIC_SURVIVES\n\n" |
| 250 | f"{library.PRIVATE_CORPUS_START}\nSECOND_UNCLOSED_SECRET\n" |
| 251 | ) |
| 252 | sanitized_mixed = library.public_markdown(mixed) |
| 253 | assert "PUBLIC_SURVIVES" in sanitized_mixed |
| 254 | assert "FIRST_SECRET" not in sanitized_mixed |
| 255 | assert "SECOND_UNCLOSED_SECRET" not in sanitized_mixed |
| 256 | |
| 257 | # Verify end-to-end through HTML rendering and library FTS index. |
| 258 | memory = tmp_path / "memory" |
| 259 | memory.mkdir() |
| 260 | report_path = memory / "routing-raw.md" |
| 261 | report_path.write_text(md, encoding="utf-8") |
| 262 | entry = library.parse_markdown_file(report_path) |
| 263 | public_html = html_render.render_library_brief(entry, include_private=False) |
| 264 | assert "Public routing finding stays visible." in public_html |
| 265 | assert "UNCLOSED_SECRET_CORPUS_PAYLOAD" not in public_html |
| 266 | |
| 267 | db_path = tmp_path / "library.db" |
| 268 | library_index.sync_library(memory, tmp_path / "no-briefs", db_path=db_path) |
| 269 | assert not library_index.search( |
| 270 | "UNCLOSED_SECRET_CORPUS_PAYLOAD", db_path=db_path, store_db_path=tmp_path / "none.db" |
| 271 | ) |
| 272 | assert library_index.search( |
| 273 | "Public routing finding", db_path=db_path, store_db_path=tmp_path / "none.db" |
| 274 | ) |
| 275 | |
| 276 | |
| 277 | def test_high210_legacy_unmarked_from_your_files_stripped_across_hr_and_code(): |
| 278 | md = ( |
| 279 | "# last30days: Legacy Notes\n\n" |
| 280 | "- Sources: 2 active (Reddit, Your files)\n\n" |
| 281 | "## From your files\n\n" |
| 282 | "PRIVATE_PART_ONE\n\n" |
| 283 | "---\n\n" |
| 284 | "PRIVATE_AFTER_HR\n\n" |
| 285 | "```text\n" |
| 286 | "PRIVATE_IN_CODE_FENCE\n" |
| 287 | "```\n\n" |
| 288 | "### Nested Private Subheading\n\n" |
| 289 | "PRIVATE_UNDER_H3\n\n" |
| 290 | "## Public Takeaways\n\n" |
| 291 | "PUBLIC_TAKEAWAY_STAYS\n" |
| 292 | ) |
| 293 | sanitized = library.public_markdown(md) |
| 294 | assert "PUBLIC_TAKEAWAY_STAYS" in sanitized |
| 295 | for secret in ( |
| 296 | "PRIVATE_PART_ONE", |
| 297 | "PRIVATE_AFTER_HR", |
| 298 | "PRIVATE_IN_CODE_FENCE", |
| 299 | "PRIVATE_UNDER_H3", |
| 300 | ): |
| 301 | assert secret not in sanitized |
| 302 | |
| 303 | # Case variation at EOF with no following section. |
| 304 | eof_md = "# last30days: Legacy EOF\n\n## Public\n\nKEEP_ME\n\n## from your files\n\nEOF_SECRET" |
| 305 | sanitized_eof = library.public_markdown(eof_md) |
| 306 | assert "KEEP_ME" in sanitized_eof |
| 307 | assert "EOF_SECRET" not in sanitized_eof |
| 308 | |
| 309 | |
| 310 | def test_high210_fenced_fake_heading_inside_from_your_files_does_not_leak(tmp_path: Path): |
| 311 | md = ( |
| 312 | "# last30days v4.5.0: Fence Escape Test\n\n" |
| 313 | "- Date range: 2026-06-10 to 2026-07-10\n\n" |
| 314 | "## Public Intro\n\n" |
| 315 | "PUBLIC_INTRO_SURVIVES\n\n" |
| 316 | "## From your files\n\n" |
| 317 | "SECRET_BEFORE_FENCE\n\n" |
| 318 | "```markdown\n" |
| 319 | "## Fake Heading Inside Fence\n" |
| 320 | "SECRET_INSIDE_FENCE\n" |
| 321 | "```\n" |
| 322 | "SECRET_AFTER_FENCE\n\n" |
| 323 | "~~~markdown\n" |
| 324 | "## Fake Heading Inside Tilde Fence\n" |
| 325 | "SECRET_INSIDE_TILDE\n" |
| 326 | "~~~\n" |
| 327 | "SECRET_AFTER_TILDE\n\n" |
| 328 | "````markdown\n" |
| 329 | "```\n" |
| 330 | "## Fake Heading Inside Four-Tick Fence\n" |
| 331 | "SECRET_INSIDE_FOUR_TICK\n" |
| 332 | "````\n" |
| 333 | "SECRET_AFTER_FOUR_TICK\n\n" |
| 334 | "## Real Public Section\n\n" |
| 335 | "PUBLIC_OUTRO_SURVIVES\n" |
| 336 | ) |
| 337 | sanitized = library.public_markdown(md) |
| 338 | assert "PUBLIC_INTRO_SURVIVES" in sanitized |
| 339 | assert "PUBLIC_OUTRO_SURVIVES" in sanitized |
| 340 | for secret in ( |
| 341 | "SECRET_BEFORE_FENCE", |
| 342 | "Fake Heading Inside Fence", |
| 343 | "SECRET_INSIDE_FENCE", |
| 344 | "SECRET_AFTER_FENCE", |
| 345 | "Fake Heading Inside Tilde Fence", |
| 346 | "SECRET_INSIDE_TILDE", |
| 347 | "SECRET_AFTER_TILDE", |
| 348 | "Fake Heading Inside Four-Tick Fence", |
| 349 | "SECRET_INSIDE_FOUR_TICK", |
| 350 | "SECRET_AFTER_FOUR_TICK", |
| 351 | ): |
| 352 | assert secret not in sanitized |
| 353 | |
| 354 | # End-to-end through HTML brief rendering and library FTS index. |
| 355 | memory = tmp_path / "memory" |
| 356 | memory.mkdir() |
| 357 | report_path = memory / "fence-escape-raw.md" |
| 358 | report_path.write_text(md, encoding="utf-8") |
| 359 | entry = library.parse_markdown_file(report_path) |
| 360 | public_html = html_render.render_library_brief(entry, include_private=False) |
| 361 | assert "PUBLIC_INTRO_SURVIVES" in public_html |
| 362 | assert "PUBLIC_OUTRO_SURVIVES" in public_html |
| 363 | assert "SECRET_INSIDE_FENCE" not in public_html |
| 364 | assert "SECRET_AFTER_FENCE" not in public_html |
| 365 | assert "SECRET_INSIDE_TILDE" not in public_html |
| 366 | |
| 367 | db_path = tmp_path / "library.db" |
| 368 | library_index.sync_library(memory, tmp_path / "no-briefs", db_path=db_path) |
| 369 | for term in ("SECRET_INSIDE_FENCE", "SECRET_AFTER_FENCE", "SECRET_INSIDE_FOUR_TICK"): |
| 370 | assert not library_index.search(term, db_path=db_path, store_db_path=tmp_path / "none.db") |
| 371 | assert library_index.search( |
| 372 | "PUBLIC_OUTRO_SURVIVES", db_path=db_path, store_db_path=tmp_path / "none.db" |
| 373 | ) |
| 374 | |
| 375 | |
| 376 | def test_high210_heading_variants_footer_signal_and_unrepresentative_corpus_cluster(): |
| 377 | # Recognize # From your files, ### From your files, ## From your files:, and **From your files:** |
| 378 | for heading, sibling in ( |
| 379 | ("# From your files", "## Public Sibling"), |
| 380 | ("## From your files:", "## Public Sibling"), |
| 381 | ("### From your files", "### Public Sibling"), |
| 382 | ("**From your files:**", "## Public Sibling"), |
| 383 | ): |
| 384 | md = ( |
| 385 | "# last30days: Variants\n\n" |
| 386 | f"{heading}\n\n" |
| 387 | "VARIANT_SECRET_TEXT\n\n" |
| 388 | f"{sibling}\n\n" |
| 389 | "PUBLIC_SIBLING_TEXT\n" |
| 390 | ) |
| 391 | sanitized = library.public_markdown(md) |
| 392 | assert "VARIANT_SECRET_TEXT" not in sanitized, heading |
| 393 | assert "PUBLIC_SIBLING_TEXT" in sanitized, heading |
| 394 | |
| 395 | # Unrepresentative legacy cluster carrying corpus:// or legacy corpus signal fails closed. |
| 396 | corpus_bullet_md = ( |
| 397 | "# last30days: Legacy Unrepresentative Cluster\n\n" |
| 398 | "- Sources: 2 active (Reddit, Your files)\n\n" |
| 399 | "## Ranked Evidence Clusters\n\n" |
| 400 | "### 1. Secret heading without numbered reps (score 80, 1 item, sources: Your files)\n" |
| 401 | "- Evidence: Internal memo at [note](corpus://notes/secret.md) UNREP_CORPUS_SECRET\n\n" |
| 402 | "### 2. Clean unclassified heading (score 70, 1 item, sources: Reddit)\n" |
| 403 | "- Coverage: PUBLIC_BULLET_STAYS\n" |
| 404 | ) |
| 405 | sanitized_cluster = library.public_markdown(corpus_bullet_md) |
| 406 | assert "UNREP_CORPUS_SECRET" not in sanitized_cluster |
| 407 | assert "corpus://notes/secret.md" not in sanitized_cluster |
| 408 | assert "PUBLIC_BULLET_STAYS" in sanitized_cluster |
| 409 | |
| 410 | # Structured report whose only corpus signal is a footer (`Your files`) or bold heading |
| 411 | # still scrubs unmarked Ranked Evidence Clusters and Freshness Verification. |
| 412 | footer_only_md = ( |
| 413 | "# last30days: Footer Signal Only\n\n" |
| 414 | "## Ranked Evidence Clusters\n\n" |
| 415 | "### 1. Secret cluster title leaked by footer-only doc (score 90, 1 item, sources: Reddit)\n" |
| 416 | "1. [reddit] Public cluster title\n" |
| 417 | " - Evidence: PUBLIC_FOOTER_DOC_EVIDENCE\n\n" |
| 418 | "## Freshness Verification\n\n" |
| 419 | "| Verdict | Claim | Evidence | Checked |\n" |
| 420 | "| --- | --- | --- | --- |\n" |
| 421 | "| **fresh** | FOOTER_DOC_PRIVATE_CLAIM | https://example.test/1 | 2026-07-08 |\n\n" |
| 422 | "## Footer\n\n" |
| 423 | "├─ 📁 Your files: 1 note\n" |
| 424 | ) |
| 425 | sanitized_footer = library.public_markdown(footer_only_md) |
| 426 | assert "Secret cluster title leaked by footer-only doc" not in sanitized_footer |
| 427 | assert "FOOTER_DOC_PRIVATE_CLAIM" not in sanitized_footer |
| 428 | assert "Public cluster title" in sanitized_footer |
| 429 | assert "PUBLIC_FOOTER_DOC_EVIDENCE" in sanitized_footer |
| 430 | |
| 431 | bold_only_md = ( |
| 432 | "# last30days: Bold Signal Only\n\n" |
| 433 | "**From your files:**\n\n" |
| 434 | "BOLD_PRIVATE_SECRET\n\n" |
| 435 | "## Ranked Evidence Clusters\n\n" |
| 436 | "### 1. Secret title in bold-only doc (score 80, 1 item, sources: Reddit)\n" |
| 437 | "1. [reddit] Public bold-doc title\n" |
| 438 | ) |
| 439 | sanitized_bold = library.public_markdown(bold_only_md) |
| 440 | assert "BOLD_PRIVATE_SECRET" not in sanitized_bold |
| 441 | assert "Secret title in bold-only doc" not in sanitized_bold |
| 442 | assert "Public bold-doc title" in sanitized_bold |
| 443 | |
| 444 | |
| 445 | def test_high210_multiple_unmarked_drill_followups_all_stripped(): |
| 446 | md = ( |
| 447 | "# last30days: Multi Drill\n\n" |
| 448 | "## Drill Follow-up\n\n" |
| 449 | "FIRST_UNMARKED_DRILL_SECRET\n\n" |
| 450 | "### Deeper\n\n" |
| 451 | "- 1 new items after dedupe\n" |
| 452 | "- Re-researched sources: Your files\n\n" |
| 453 | "## Public Middle\n\n" |
| 454 | "PUBLIC_MIDDLE_TEXT\n\n" |
| 455 | "## Drill Follow-up\n\n" |
| 456 | "SECOND_TRUNCATED_UNMARKED_DRILL_SECRET\n" |
| 457 | ) |
| 458 | sanitized = library.public_markdown(md) |
| 459 | assert "FIRST_UNMARKED_DRILL_SECRET" not in sanitized |
| 460 | assert "SECOND_TRUNCATED_UNMARKED_DRILL_SECRET" not in sanitized |
| 461 | assert "PUBLIC_MIDDLE_TEXT" in sanitized |
| 462 | |
| 463 | # Marked public drill survives while subsequent unmarked drills are all removed. |
| 464 | md_with_public = ( |
| 465 | "# last30days: Mixed Drills\n\n" |
| 466 | f"{library.PUBLIC_DRILL_MARKER}\n" |
| 467 | "## Drill Follow-up\n\n" |
| 468 | "MARKED_PUBLIC_DRILL_TEXT\n\n" |
| 469 | "### Deeper\n\n" |
| 470 | "- 2 new items after dedupe\n" |
| 471 | "- Re-researched sources: Reddit\n\n" |
| 472 | "## Drill Follow-up\n\n" |
| 473 | "UNMARKED_ONE_SECRET\n\n" |
| 474 | "### Deeper\n\n" |
| 475 | "- 1 new items after dedupe\n" |
| 476 | "- Re-researched sources: Your files\n\n" |
| 477 | "## Drill Follow-up\n\n" |
| 478 | "UNMARKED_TWO_NO_TRAILER_SECRET\n" |
| 479 | ) |
| 480 | sanitized_mixed = library.public_markdown(md_with_public) |
| 481 | assert "MARKED_PUBLIC_DRILL_TEXT" in sanitized_mixed |
| 482 | assert "UNMARKED_ONE_SECRET" not in sanitized_mixed |
| 483 | assert "UNMARKED_TWO_NO_TRAILER_SECRET" not in sanitized_mixed |
| 484 | |
| 485 | # Unmarked legacy drill containing an unclosed PRIVATE_CORPUS_START before a drill |
| 486 | # trailer must strip the explicit private block FIRST so private text after the |
| 487 | # trailer cannot survive drill cleanup. |
| 488 | drill_with_unclosed_private = ( |
| 489 | "# last30days: Drill Unclosed Private\n\n" |
| 490 | "## Public Intro\n\n" |
| 491 | "PUBLIC_BEFORE_DRILL\n\n" |
| 492 | "## Drill Follow-up\n\n" |
| 493 | f"{library.PRIVATE_CORPUS_START}\n" |
| 494 | "SECRET_BEFORE_TRAILER\n\n" |
| 495 | "### Deeper\n\n" |
| 496 | "- 1 new items after dedupe\n" |
| 497 | "- Re-researched sources: Reddit\n\n" |
| 498 | "---\n\n" |
| 499 | "## Section After Trailer\n\n" |
| 500 | "SECRET_AFTER_TRAILER_MUST_NOT_LEAK\n" |
| 501 | ) |
| 502 | sanitized_unclosed = library.public_markdown(drill_with_unclosed_private) |
| 503 | assert "PUBLIC_BEFORE_DRILL" in sanitized_unclosed |
| 504 | assert "SECRET_BEFORE_TRAILER" not in sanitized_unclosed |
| 505 | assert "SECRET_AFTER_TRAILER_MUST_NOT_LEAK" not in sanitized_unclosed |
| 506 | assert "## Drill Follow-up" not in sanitized_unclosed |
| 507 | |
| 508 | # Closed private block placed between PUBLIC_DRILL_MARKER and an unmarked drill |
| 509 | # (whether newline-separated or same-line) must NOT splice the earlier public |
| 510 | # marker onto the unmarked drill. |
| 511 | for sep in ("\n", "", " "): |
| 512 | spliced_marker = ( |
| 513 | "# last30days: Marker Splice Guard\n\n" |
| 514 | f"{library.PUBLIC_DRILL_MARKER}{sep}" |
| 515 | f"{library.PRIVATE_CORPUS_START}\nPRIVATE_SPACER\n{library.PRIVATE_CORPUS_END}\n" |
| 516 | "## Drill Follow-up\n\n" |
| 517 | "UNMARKED_DRILL_AFTER_SPLICE\n" |
| 518 | ) |
| 519 | sanitized_spliced = library.public_markdown(spliced_marker) |
| 520 | assert "PRIVATE_SPACER" not in sanitized_spliced |
| 521 | assert "UNMARKED_DRILL_AFTER_SPLICE" not in sanitized_spliced |
| 522 | |
| 523 | |
| 524 | def test_high210_legacy_cluster_strips_corpus_representatives_from_body(tmp_path: Path): |
| 525 | md = ( |
| 526 | "# last30days: Cluster Privacy\n\n" |
| 527 | "- Date range: 2026-06-10 to 2026-07-10\n\n" |
| 528 | "## Ranked Evidence Clusters\n\n" |
| 529 | "### 1. Secret local cluster title (score 88, 3 items, sources: Your files, Reddit)\n" |
| 530 | "- Uncertainty: single-source\n" |
| 531 | "1. [corpus] Confidential M&A memo\n" |
| 532 | " - URL: corpus://notes/ma.md\n" |
| 533 | " - Evidence: SECRET_MA_VALUATION\n" |
| 534 | "2. Unindented wrapped secret point\n" |
| 535 | "2. [reddit, corpus] Blended private corroboration\n" |
| 536 | " - Evidence: BLENDED_SECRET_LINE\n" |
| 537 | "3. [reddit] Public architecture discussion\n" |
| 538 | " - URL: https://reddit.com/r/arch/1\n" |
| 539 | " - Evidence: PUBLIC_ARCH_EVIDENCE\n\n" |
| 540 | "### 2. Corpus only cluster title (score 75, 1 item, sources: Your files)\n" |
| 541 | "- Uncertainty: single-source\n" |
| 542 | "1. [Your files] Private roadmap draft\n" |
| 543 | " - URL: corpus://notes/roadmap.md\n" |
| 544 | " - Evidence: SECRET_ROADMAP_ONLY\n" |
| 545 | ) |
| 546 | sanitized = library.public_markdown(md) |
| 547 | assert "### 1. Public architecture discussion" in sanitized |
| 548 | assert "PUBLIC_ARCH_EVIDENCE" in sanitized |
| 549 | for secret in ( |
| 550 | "Secret local cluster title", |
| 551 | "Confidential M&A memo", |
| 552 | "corpus://notes/ma.md", |
| 553 | "SECRET_MA_VALUATION", |
| 554 | "Unindented wrapped secret point", |
| 555 | "Blended private corroboration", |
| 556 | "BLENDED_SECRET_LINE", |
| 557 | "Corpus only cluster title", |
| 558 | "Private roadmap draft", |
| 559 | "SECRET_ROADMAP_ONLY", |
| 560 | ): |
| 561 | assert secret not in sanitized |
| 562 | |
| 563 | # Verify through HTML rendering and FTS index. |
| 564 | memory = tmp_path / "memory" |
| 565 | memory.mkdir() |
| 566 | report_path = memory / "cluster-raw.md" |
| 567 | report_path.write_text(md, encoding="utf-8") |
| 568 | entry = library.parse_markdown_file(report_path) |
| 569 | public_html = html_render.render_library_brief(entry, include_private=False) |
| 570 | assert "Public architecture discussion" in public_html |
| 571 | assert "SECRET_MA_VALUATION" not in public_html |
| 572 | assert "SECRET_ROADMAP_ONLY" not in public_html |
| 573 | |
| 574 | db_path = tmp_path / "library.db" |
| 575 | library_index.sync_library(memory, tmp_path / "no-briefs", db_path=db_path) |
| 576 | for term in ("SECRET_MA_VALUATION", "BLENDED_SECRET_LINE", "SECRET_ROADMAP_ONLY"): |
| 577 | assert not library_index.search(term, db_path=db_path, store_db_path=tmp_path / "none.db") |
| 578 | assert library_index.search( |
| 579 | "PUBLIC_ARCH_EVIDENCE", db_path=db_path, store_db_path=tmp_path / "none.db" |
| 580 | ) |
| 581 | |
| 582 | |
| 583 | # --------------------------------------------------------------------------- |
| 584 | # HIGH-211: scan_library symlink escape, FIFO, containment, and size cap |
| 585 | # --------------------------------------------------------------------------- |
| 586 | |
| 587 | |
| 588 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks") |
| 589 | def test_high211_scan_library_skips_symlinks_outside_and_inside_roots(tmp_path: Path): |
| 590 | outside = tmp_path / "outside" |
| 591 | outside.mkdir() |
| 592 | secret_md = outside / "private.md" |
| 593 | secret_md.write_text( |
| 594 | "# Secret Outside Note\n\nOUTSIDE_MD_LEAK_TOKEN\n", encoding="utf-8" |
| 595 | ) |
| 596 | secret_json = outside / "creds.json" |
| 597 | secret_json.write_text( |
| 598 | json.dumps( |
| 599 | { |
| 600 | "status": "ok", |
| 601 | "date": "2026-07-11", |
| 602 | "top_finding": {"title": "OUTSIDE_JSON_LEAK_TOKEN", "source": "reddit"}, |
| 603 | "topics": [{"name": "Secrets", "new_count": 1}], |
| 604 | } |
| 605 | ), |
| 606 | encoding="utf-8", |
| 607 | ) |
| 608 | |
| 609 | memory = tmp_path / "memory" |
| 610 | finished = memory / "finished" |
| 611 | briefs = tmp_path / "briefs" |
| 612 | finished.mkdir(parents=True) |
| 613 | briefs.mkdir() |
| 614 | |
| 615 | (memory / "legit-raw.md").write_text( |
| 616 | "# last30days v4.5.0: Legit Topic\n\n- Date range: 2026-06-10 to 2026-07-10\n\nPublic text.\n", |
| 617 | encoding="utf-8", |
| 618 | ) |
| 619 | (memory / "escape.md").symlink_to(secret_md) |
| 620 | (finished / "finished-escape.md").symlink_to(secret_md) |
| 621 | (briefs / "2026-07-11.json").symlink_to(secret_json) |
| 622 | |
| 623 | entries, notes = library.scan_library(memory, briefs) |
| 624 | assert [e.topic for e in entries] == ["Legit Topic"] |
| 625 | assert all("OUTSIDE_MD_LEAK_TOKEN" not in e.content for e in entries) |
| 626 | assert all("OUTSIDE_JSON_LEAK_TOKEN" not in e.content for e in entries) |
| 627 | assert len(notes) == 3 |
| 628 | assert all("symlink" in note.lower() for note in notes) |
| 629 | |
| 630 | # Direct library_index helpers must also reject symlinks without dereferencing. |
| 631 | db_path = tmp_path / "library.db" |
| 632 | assert library_index.index_entry(memory / "escape.md", db_path=db_path) is False |
| 633 | assert library_index.index_brief(memory / "escape.md", db_path=db_path) is False |
| 634 | assert library_index.index_brief(briefs / "2026-07-11.json", db_path=db_path) is False |
| 635 | |
| 636 | # Symlinked finished/ directory pointing outside memory_dir must be skipped. |
| 637 | memory2 = tmp_path / "memory2" |
| 638 | memory2.mkdir() |
| 639 | (memory2 / "finished").symlink_to(outside) |
| 640 | entries2, notes2 = library.scan_library(memory2, tmp_path / "no-briefs") |
| 641 | assert entries2 == [] |
| 642 | assert any("symlink" in note.lower() for note in notes2) |
| 643 | |
| 644 | |
| 645 | @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="POSIX FIFO test") |
| 646 | def test_high211_scan_library_skips_fifo_and_oversized_files( |
| 647 | tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 648 | ): |
| 649 | memory = tmp_path / "memory" |
| 650 | memory.mkdir() |
| 651 | os.mkfifo(memory / "blocking.md") |
| 652 | |
| 653 | (memory / "small-raw.md").write_text( |
| 654 | "# Small Report\n\nFits under cap.\n", encoding="utf-8" |
| 655 | ) |
| 656 | (memory / "huge-raw.md").write_text( |
| 657 | "# Huge Report\n\n" + ("A" * 512) + "\n", encoding="utf-8" |
| 658 | ) |
| 659 | monkeypatch.setattr(library, "MAX_LIBRARY_FILE_BYTES", 256) |
| 660 | entries, notes = library.scan_library(memory, tmp_path / "no-briefs") |
| 661 | assert [e.topic for e in entries] == ["Small Report"] |
| 662 | assert any("blocking.md" in note for note in notes) |
| 663 | assert any("huge-raw.md" in note and "byte limit" in note for note in notes) |
| 664 | |
| 665 | |
| 666 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks") |
| 667 | def test_high211_get_or_create_library_id_rejects_symlink(tmp_path: Path): |
| 668 | outside = tmp_path / "outside-id" |
| 669 | outside.write_text("a" * 32 + "\n", encoding="utf-8") |
| 670 | memory = tmp_path / "memory" |
| 671 | memory.mkdir() |
| 672 | (memory / library.LIBRARY_ID_FILENAME).symlink_to(outside) |
| 673 | |
| 674 | with pytest.raises(OSError): |
| 675 | library.get_or_create_library_id(memory) |
| 676 | |
| 677 | |
| 678 | @pytest.mark.skipif( |
| 679 | not (library._SUPPORTS_DIR_FD and library._SUPPORTS_LISTDIR_FD), |
| 680 | reason="POSIX dir_fd and fd listdir pinning", |
| 681 | ) |
| 682 | def test_high211_scan_library_pins_finished_dir_fd_across_mid_scan_symlink_swap( |
| 683 | tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 684 | ): |
| 685 | outside = tmp_path / "outside" |
| 686 | outside.mkdir() |
| 687 | (outside / "brief-2026-07-10.md").write_text( |
| 688 | "# External Secret\n\nEVIL_OUTSIDE_SECRET_PAYLOAD\n", |
| 689 | encoding="utf-8", |
| 690 | ) |
| 691 | |
| 692 | memory = tmp_path / "memory" |
| 693 | finished = memory / "finished" |
| 694 | finished.mkdir(parents=True) |
| 695 | (finished / "brief-2026-07-10.md").write_text( |
| 696 | "# Legit Pinned Brief\n\nLEGIT_PINNED_CONTENT\n", |
| 697 | encoding="utf-8", |
| 698 | ) |
| 699 | |
| 700 | real_listdir = os.listdir |
| 701 | swapped = False |
| 702 | |
| 703 | def swap_finished_during_listing(target): |
| 704 | nonlocal swapped |
| 705 | names = real_listdir(target) |
| 706 | if not swapped and isinstance(target, int) and "brief-2026-07-10.md" in names: |
| 707 | swapped = True |
| 708 | moved = tmp_path / "finished-moved" |
| 709 | finished.rename(moved) |
| 710 | finished.symlink_to(outside) |
| 711 | return names |
| 712 | |
| 713 | monkeypatch.setattr(library.os, "listdir", swap_finished_during_listing) |
| 714 | |
| 715 | entries, notes = library.scan_library(memory, tmp_path / "no-briefs") |
| 716 | assert swapped is True |
| 717 | assert notes == [] |
| 718 | assert [e.topic for e in entries] == ["Legit Pinned Brief"] |
| 719 | assert "LEGIT_PINNED_CONTENT" in entries[0].content |
| 720 | assert "EVIL_OUTSIDE_SECRET_PAYLOAD" not in entries[0].content |
| 721 | |
| 722 | # Reset and verify library_index.sync_library also never indexes the external target. |
| 723 | finished.unlink() |
| 724 | (tmp_path / "finished-moved").rename(finished) |
| 725 | swapped = False |
| 726 | db_path = tmp_path / "library.db" |
| 727 | library_index.sync_library(memory, tmp_path / "no-briefs", db_path=db_path) |
| 728 | assert swapped is True |
| 729 | assert not library_index.search( |
| 730 | "EVIL_OUTSIDE_SECRET_PAYLOAD", db_path=db_path, store_db_path=tmp_path / "none.db" |
| 731 | ) |
| 732 | assert library_index.search( |
| 733 | "LEGIT_PINNED_CONTENT", db_path=db_path, store_db_path=tmp_path / "none.db" |
| 734 | ) |
| 735 | |
| 736 | |
| 737 | @pytest.mark.skipif(not library._SUPPORTS_DIR_FD, reason="POSIX dir_fd pinning") |
| 738 | def test_high211_scan_library_pins_finished_dir_fd_with_path_based_listing( |
| 739 | tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 740 | ): |
| 741 | outside = tmp_path / "outside" |
| 742 | outside.mkdir() |
| 743 | (outside / "brief-2026-07-10.md").write_text( |
| 744 | "# External Secret\n\nEVIL_OUTSIDE_SECRET_PAYLOAD\n", |
| 745 | encoding="utf-8", |
| 746 | ) |
| 747 | (outside / "extra-outside-2026-07-10.md").write_text( |
| 748 | "# Extra Outside Secret\n\nEXTRA_EVIL_OUTSIDE_PAYLOAD\n", |
| 749 | encoding="utf-8", |
| 750 | ) |
| 751 | |
| 752 | memory = tmp_path / "memory" |
| 753 | finished = memory / "finished" |
| 754 | finished.mkdir(parents=True) |
| 755 | (finished / "brief-2026-07-10.md").write_text( |
| 756 | "# Legit Pinned Brief\n\nLEGIT_PINNED_CONTENT\n", |
| 757 | encoding="utf-8", |
| 758 | ) |
| 759 | |
| 760 | monkeypatch.setattr(library, "_SUPPORTS_LISTDIR_FD", False) |
| 761 | real_listdir = os.listdir |
| 762 | resolved_finished = finished.resolve() |
| 763 | swapped = False |
| 764 | |
| 765 | def swap_finished_during_path_listing(target): |
| 766 | nonlocal swapped |
| 767 | if not swapped and isinstance(target, Path) and target == resolved_finished: |
| 768 | swapped = True |
| 769 | moved = tmp_path / "finished-moved-path-list" |
| 770 | finished.rename(moved) |
| 771 | finished.symlink_to(outside) |
| 772 | return real_listdir(target) |
| 773 | |
| 774 | monkeypatch.setattr(library.os, "listdir", swap_finished_during_path_listing) |
| 775 | |
| 776 | entries, notes = library.scan_library(memory, tmp_path / "no-briefs") |
| 777 | assert swapped is True |
| 778 | assert [e.topic for e in entries] == ["Legit Pinned Brief"] |
| 779 | assert "LEGIT_PINNED_CONTENT" in entries[0].content |
| 780 | assert "EVIL_OUTSIDE_SECRET_PAYLOAD" not in entries[0].content |
| 781 | assert all("EXTRA_EVIL_OUTSIDE_PAYLOAD" not in e.content for e in entries) |
| 782 | assert any("extra-outside-2026-07-10.md" in note for note in notes) |
| 783 | |
| 784 | |
| 785 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlink+parent traversal") |
| 786 | def test_high211_symlink_parent_dotdot_preserves_canonical_source_path(tmp_path: Path): |
| 787 | vault = tmp_path / "vault" |
| 788 | nested = vault / "nested" |
| 789 | real_dir = vault / "real_dir" |
| 790 | finished = real_dir / "finished" |
| 791 | nested.mkdir(parents=True) |
| 792 | finished.mkdir(parents=True) |
| 793 | |
| 794 | real_file = real_dir / "brief-2026-07-11.md" |
| 795 | real_file.write_text( |
| 796 | "# Canonical Path Topic\n\nUNIQUE_SYMLINK_DOTDOT_TOKEN\n", |
| 797 | encoding="utf-8", |
| 798 | ) |
| 799 | finished_file = finished / "finished-2026-07-12.md" |
| 800 | finished_file.write_text( |
| 801 | "# Finished Canonical Topic\n\nUNIQUE_FINISHED_DOTDOT_TOKEN\n", |
| 802 | encoding="utf-8", |
| 803 | ) |
| 804 | |
| 805 | link_dir = tmp_path / "link_dir" |
| 806 | link_dir.symlink_to(nested) |
| 807 | via_link = link_dir / ".." / "real_dir" |
| 808 | |
| 809 | entries, notes = library.scan_library(via_link, tmp_path / "no-briefs") |
| 810 | assert notes == [] |
| 811 | by_topic = {entry.topic: entry.source_path for entry in entries} |
| 812 | assert by_topic["Canonical Path Topic"] == real_file.resolve() |
| 813 | assert by_topic["Finished Canonical Topic"] == finished_file.resolve() |
| 814 | |
| 815 | db_path = tmp_path / "library.db" |
| 816 | library_index.sync_library(via_link, tmp_path / "no-briefs", db_path=db_path) |
| 817 | matches = library_index.search( |
| 818 | "UNIQUE_SYMLINK_DOTDOT_TOKEN", |
| 819 | db_path=db_path, |
| 820 | store_db_path=tmp_path / "none.db", |
| 821 | ) |
| 822 | assert len(matches) == 1 |
| 823 | assert matches[0].source_path == str(real_file.resolve()) |
| 824 | assert Path(matches[0].source_path).is_file() |
| 825 | |
| 826 | finished_matches = library_index.search( |
| 827 | "UNIQUE_FINISHED_DOTDOT_TOKEN", |
| 828 | db_path=db_path, |
| 829 | store_db_path=tmp_path / "none.db", |
| 830 | ) |
| 831 | assert len(finished_matches) == 1 |
| 832 | assert finished_matches[0].source_path == str(finished_file.resolve()) |
| 833 | |
| 834 | # Direct index_entry through link_dir/../real_dir/brief.md must also record |
| 835 | # the canonical target path rather than lexically collapsing link_dir/.. . |
| 836 | db_entry = tmp_path / "entry.db" |
| 837 | assert library_index.index_entry(via_link / "brief-2026-07-11.md", db_path=db_entry) is True |
| 838 | entry_matches = library_index.search( |
| 839 | "UNIQUE_SYMLINK_DOTDOT_TOKEN", |
| 840 | db_path=db_entry, |
| 841 | store_db_path=tmp_path / "none.db", |
| 842 | ) |
| 843 | assert len(entry_matches) == 1 |
| 844 | assert entry_matches[0].source_path == str(real_file.resolve()) |
| 845 | |
| 846 | |
| 847 | def test_high211_missing_dir_before_dotdot_not_redirected(tmp_path: Path): |
| 848 | vault = tmp_path / "vault" |
| 849 | real_dir = vault / "real_dir" |
| 850 | real_dir.mkdir(parents=True) |
| 851 | brief = real_dir / "brief-2026-07-13.md" |
| 852 | brief.write_text( |
| 853 | "# Real Dir Brief\n\nMUST_NOT_REDIRECT_MISSING_DOTDOT\n", |
| 854 | encoding="utf-8", |
| 855 | ) |
| 856 | |
| 857 | missing_via_dotdot_dir = vault / "missing" / ".." / "real_dir" |
| 858 | missing_via_dotdot_file = missing_via_dotdot_dir / "brief-2026-07-13.md" |
| 859 | |
| 860 | entries, notes = library.scan_library(missing_via_dotdot_dir, tmp_path / "no-briefs") |
| 861 | assert entries == [] |
| 862 | assert notes == [] |
| 863 | |
| 864 | db_path = tmp_path / "library.db" |
| 865 | assert library_index.index_entry(missing_via_dotdot_file, db_path=db_path) is False |
| 866 | assert library_index.index_brief(missing_via_dotdot_file, db_path=db_path) is False |
| 867 | assert not library_index.search( |
| 868 | "MUST_NOT_REDIRECT_MISSING_DOTDOT", |
| 869 | db_path=db_path, |
| 870 | store_db_path=tmp_path / "none.db", |
| 871 | ) |
| 872 | |
| 873 | |
| 874 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlink and directory inode swap") |
| 875 | def test_high211_fallback_scan_rejects_finished_swap_after_check( |
| 876 | tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 877 | ): |
| 878 | monkeypatch.setattr(library, "_SUPPORTS_DIR_FD", False) |
| 879 | |
| 880 | # Sub-case 1: finished/ swapped to symlink pointing outside memory_dir |
| 881 | # right after _checked_subdir_stat approves it. |
| 882 | outside = tmp_path / "outside" |
| 883 | outside.mkdir() |
| 884 | (outside / "secret-2026-07-14.md").write_text( |
| 885 | "# Outside Secret\n\nOUTSIDE_SYMLINK_SWAP_SECRET\n", |
| 886 | encoding="utf-8", |
| 887 | ) |
| 888 | |
| 889 | memory = tmp_path / "memory-symlink-swap" |
| 890 | finished = memory / "finished" |
| 891 | finished.mkdir(parents=True) |
| 892 | (finished / "legit-2026-07-14.md").write_text( |
| 893 | "# Legit Original\n\nLEGIT_ORIGINAL_BODY\n", |
| 894 | encoding="utf-8", |
| 895 | ) |
| 896 | |
| 897 | real_checked_subdir_stat = library._checked_subdir_stat |
| 898 | swapped_symlink = False |
| 899 | |
| 900 | def swap_to_symlink_after_check(subdir: Path, root: Path): |
| 901 | nonlocal swapped_symlink |
| 902 | st = real_checked_subdir_stat(subdir, root) |
| 903 | if not swapped_symlink and subdir.name == library.FINISHED_SUBDIR and st is not None: |
| 904 | swapped_symlink = True |
| 905 | subdir.rename(tmp_path / "finished-orig-1") |
| 906 | subdir.symlink_to(outside) |
| 907 | return st |
| 908 | |
| 909 | monkeypatch.setattr(library, "_checked_subdir_stat", swap_to_symlink_after_check) |
| 910 | entries, notes = library.scan_library(memory, tmp_path / "no-briefs") |
| 911 | assert swapped_symlink is True |
| 912 | assert all("OUTSIDE_SYMLINK_SWAP_SECRET" not in e.content for e in entries) |
| 913 | assert entries == [] |
| 914 | assert any("Skipped" in note for note in notes) |
| 915 | |
| 916 | # Sub-case 2: finished/ swapped to a DIFFERENT real directory moved into place |
| 917 | # right after _checked_subdir_stat approves it (no symlink, only inode changes). |
| 918 | rogue_dir = tmp_path / "rogue-finished" |
| 919 | rogue_dir.mkdir() |
| 920 | (rogue_dir / "rogue-2026-07-14.md").write_text( |
| 921 | "# Rogue Replaced Dir\n\nROGUE_REAL_DIR_SWAP_SECRET\n", |
| 922 | encoding="utf-8", |
| 923 | ) |
| 924 | |
| 925 | memory2 = tmp_path / "memory-realdir-swap" |
| 926 | finished2 = memory2 / "finished" |
| 927 | finished2.mkdir(parents=True) |
| 928 | (finished2 / "legit-2026-07-14.md").write_text( |
| 929 | "# Legit Original 2\n\nLEGIT_ORIGINAL_2_BODY\n", |
| 930 | encoding="utf-8", |
| 931 | ) |
| 932 | |
| 933 | swapped_real = False |
| 934 | |
| 935 | def swap_to_real_dir_after_check(subdir: Path, root: Path): |
| 936 | nonlocal swapped_real |
| 937 | st = real_checked_subdir_stat(subdir, root) |
| 938 | if not swapped_real and subdir == finished2.resolve() and st is not None: |
| 939 | swapped_real = True |
| 940 | subdir.rename(tmp_path / "finished-orig-2") |
| 941 | rogue_dir.rename(subdir) |
| 942 | return st |
| 943 | |
| 944 | monkeypatch.setattr(library, "_checked_subdir_stat", swap_to_real_dir_after_check) |
| 945 | entries2, notes2 = library.scan_library(memory2, tmp_path / "no-briefs") |
| 946 | assert swapped_real is True |
| 947 | assert all("ROGUE_REAL_DIR_SWAP_SECRET" not in e.content for e in entries2) |
| 948 | assert entries2 == [] |
| 949 | assert any("Skipped" in note for note in notes2) |
| 950 | |
| 951 | # Sub-case 3: verify post-open _fd_real_path check catches an opened fd whose |
| 952 | # canonical path escapes the checked directory even if parent lstat looks intact. |
| 953 | monkeypatch.setattr(library, "_checked_subdir_stat", real_checked_subdir_stat) |
| 954 | memory3 = tmp_path / "memory-fd-escape" |
| 955 | finished3 = memory3 / "finished" |
| 956 | finished3.mkdir(parents=True) |
| 957 | legit3 = finished3 / "legit-2026-07-14.md" |
| 958 | legit3.write_text("# Legit 3\n\nLEGIT_3_BODY\n", encoding="utf-8") |
| 959 | |
| 960 | # Happy path under fallback mode (no swap, real _fd_real_path) succeeds. |
| 961 | ok_entries, ok_notes = library.scan_library(memory3, tmp_path / "no-briefs") |
| 962 | assert ok_notes == [] |
| 963 | assert [e.topic for e in ok_entries] == ["Legit 3"] |
| 964 | |
| 965 | monkeypatch.setattr( |
| 966 | library, "_fd_real_path", lambda _fd: outside / "secret-2026-07-14.md" |
| 967 | ) |
| 968 | entries3, notes3 = library.scan_library(memory3, tmp_path / "no-briefs") |
| 969 | assert entries3 == [] |
| 970 | assert any("escapes" in note.lower() for note in notes3) |
| 971 | |
| 972 | |
| 973 | def test_high211_fallback_fails_closed_when_fd_real_path_unavailable( |
| 974 | tmp_path: Path, monkeypatch: pytest.MonkeyPatch |
| 975 | ): |
| 976 | monkeypatch.setattr(library, "_SUPPORTS_DIR_FD", False) |
| 977 | monkeypatch.setattr(library, "_fd_real_path", lambda _fd: None) |
| 978 | |
| 979 | memory = tmp_path / "memory-unverifiable-fd" |
| 980 | finished = memory / "finished" |
| 981 | finished.mkdir(parents=True) |
| 982 | brief = finished / "brief-2026-07-15.md" |
| 983 | brief.write_text("# Unverifiable FD\n\nFALLBACK_FAIL_CLOSED_BODY\n", encoding="utf-8") |
| 984 | |
| 985 | with pytest.raises(OSError, match="Unable to verify opened file location"): |
| 986 | library._read_regular_text(brief, root=memory) |
| 987 | |
| 988 | entries, notes = library.scan_library(memory, tmp_path / "no-briefs") |
| 989 | assert entries == [] |
| 990 | assert any("Unable to verify opened file location" in note for note in notes) |
| 991 | |
| 992 | |
| 993 | # --------------------------------------------------------------------------- |
| 994 | # HIGH-212: Store FTS5 sanitization, injection defense, and dismissed filter |
| 995 | # --------------------------------------------------------------------------- |
| 996 | |
| 997 | |
| 998 | def _seed_store_findings(db_path: Path) -> dict[str, int]: |
| 999 | topic = store.add_topic("FTS Security") |
| 1000 | run_id = store.record_run(topic["id"], source_mode="v3", status="completed") |
| 1001 | store.store_findings( |
| 1002 | run_id, |
| 1003 | topic["id"], |
| 1004 | [ |
| 1005 | { |
| 1006 | "source": "reddit", |
| 1007 | "source_url": "https://example.test/gpt4", |
| 1008 | "source_title": "GPT-4 benchmarks and C++ bindings", |
| 1009 | "author": "alice_dev", |
| 1010 | "content": "Comparing GPT-4 latency, C++ bindings, and what's new at http://example.com/docs.", |
| 1011 | "summary": "alpha beta summary", |
| 1012 | }, |
| 1013 | { |
| 1014 | "source": "hackernews", |
| 1015 | "source_url": "https://example.test/rust", |
| 1016 | "source_title": "Rust async runtime notes", |
| 1017 | "author": "bob_ops", |
| 1018 | "content": "gamma delta benchmarks for async runtimes.", |
| 1019 | "summary": "gamma delta summary", |
| 1020 | }, |
| 1021 | { |
| 1022 | "source": "x", |
| 1023 | "source_url": "https://example.test/dismissed", |
| 1024 | "source_title": "GPT-4 dismissed rumor", |
| 1025 | "author": "charlie", |
| 1026 | "content": "GPT-4 dismissed finding that must stay hidden.", |
| 1027 | "summary": "dismissed summary", |
| 1028 | }, |
| 1029 | ], |
| 1030 | ) |
| 1031 | ids: dict[str, int] = {} |
| 1032 | with closing(sqlite3.connect(str(db_path))) as conn: |
| 1033 | for url, fid in conn.execute("SELECT source_url, id FROM findings"): |
| 1034 | ids[url] = fid |
| 1035 | store.dismiss_finding(ids["https://example.test/dismissed"]) |
| 1036 | return ids |
| 1037 | |
| 1038 | |
| 1039 | def test_high212_search_findings_handles_punctuation_and_filters_dismissed(isolated_store: Path): |
| 1040 | ids = _seed_store_findings(isolated_store) |
| 1041 | |
| 1042 | # Punctuation-bearing ordinary queries must never crash and must find expected active rows. |
| 1043 | gpt4_hits = store.search_findings("GPT-4") |
| 1044 | assert [row["id"] for row in gpt4_hits] == [ids["https://example.test/gpt4"]] |
| 1045 | |
| 1046 | cpp_hits = store.search_findings("C++") |
| 1047 | assert [row["id"] for row in cpp_hits] == [ids["https://example.test/gpt4"]] |
| 1048 | |
| 1049 | url_hits = store.search_findings("http://example.com") |
| 1050 | assert [row["id"] for row in url_hits] == [ids["https://example.test/gpt4"]] |
| 1051 | |
| 1052 | apostrophe_hits = store.search_findings("what's new") |
| 1053 | assert [row["id"] for row in apostrophe_hits] == [ids["https://example.test/gpt4"]] |
| 1054 | |
| 1055 | # Malformed / operator-only / empty queries return [] cleanly without OperationalError. |
| 1056 | for query in ("*", "", " ", 'unclosed "quote', "---", "(())", '"""', "+++", ":"): |
| 1057 | assert store.search_findings(query) == [] |
| 1058 | |
| 1059 | # Non-positive limit returns []. |
| 1060 | assert store.search_findings("GPT-4", limit=0) == [] |
| 1061 | assert store.search_findings("GPT-4", limit=-5) == [] |
| 1062 | |
| 1063 | # library_index store sightings also exclude dismissed findings. |
| 1064 | sighting_matches = library_index.search( |
| 1065 | "dismissed", |
| 1066 | db_path=isolated_store.parent / "missing-library.db", |
| 1067 | store_db_path=isolated_store, |
| 1068 | ) |
| 1069 | assert sighting_matches == [] |
| 1070 | active_matches = library_index.search( |
| 1071 | "GPT-4", |
| 1072 | db_path=isolated_store.parent / "missing-library.db", |
| 1073 | store_db_path=isolated_store, |
| 1074 | ) |
| 1075 | assert len(active_matches) == 1 |
| 1076 | assert active_matches[0].url == "https://example.test/gpt4" |
| 1077 | |
| 1078 | |
| 1079 | def test_high212_search_findings_blocks_fts5_column_and_operator_injection(isolated_store: Path): |
| 1080 | _seed_store_findings(isolated_store) |
| 1081 | |
| 1082 | # Column filter injection: "author:alice_dev" must NOT match by author column |
| 1083 | # because literal token "author" does not appear in the row text. |
| 1084 | assert store.search_findings("author:alice_dev") == [] |
| 1085 | |
| 1086 | # Boolean OR injection must not widen results across unrelated rows. |
| 1087 | assert store.search_findings("alpha OR gamma") == [] |
| 1088 | |
| 1089 | # Boolean NOT injection must not act as FTS5 NOT. |
| 1090 | assert store.search_findings("alpha NOT gamma") == [] |
| 1091 | |
| 1092 | # Proximity NEAR injection must not act as FTS5 NEAR(...). |
| 1093 | assert store.search_findings("NEAR(alpha beta)") == [] |
| 1094 | |
| 1095 | # Defensive catch on OperationalError (e.g. missing FTS table). |
| 1096 | with closing(sqlite3.connect(str(isolated_store))) as conn: |
| 1097 | conn.execute("DROP TABLE findings_fts") |
| 1098 | conn.commit() |
| 1099 | assert store.search_findings("alpha") == [] |
| 1100 | |
| 1101 | |
| 1102 | # --------------------------------------------------------------------------- |
| 1103 | # HIGH-215: library_index._connect symlink/FIFO/parent-dir/sidecar hardening |
| 1104 | # --------------------------------------------------------------------------- |
| 1105 | |
| 1106 | |
| 1107 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks and permissions") |
| 1108 | def test_high215_library_index_connect_rejects_db_and_sidecar_symlinks_without_chmod(tmp_path: Path): |
| 1109 | victim = tmp_path / "victim.txt" |
| 1110 | victim.write_text("do-not-touch", encoding="utf-8") |
| 1111 | victim.chmod(0o644) |
| 1112 | |
| 1113 | memory = tmp_path / "memory" |
| 1114 | memory.mkdir() |
| 1115 | report = memory / "topic-raw.md" |
| 1116 | report.write_text("# Topic\n\nPublic finding.\n", encoding="utf-8") |
| 1117 | |
| 1118 | # Symlink to existing victim file. |
| 1119 | db_link = tmp_path / "library.db" |
| 1120 | db_link.symlink_to(victim) |
| 1121 | |
| 1122 | with pytest.raises(OSError): |
| 1123 | library_index._connect(db_link) |
| 1124 | with pytest.raises(OSError): |
| 1125 | library_index.sync_library(memory, tmp_path / "no-briefs", db_path=db_link) |
| 1126 | with pytest.raises(OSError): |
| 1127 | library_index.index_entry(report, db_path=db_link) |
| 1128 | with pytest.raises(OSError): |
| 1129 | library_index.search("Topic", db_path=db_link, store_db_path=tmp_path / "none.db") |
| 1130 | |
| 1131 | assert stat.S_IMODE(victim.stat().st_mode) == 0o644 |
| 1132 | assert victim.read_text(encoding="utf-8") == "do-not-touch" |
| 1133 | |
| 1134 | # Dangling symlink must not create target. |
| 1135 | dangling_target = tmp_path / "must-not-exist.db" |
| 1136 | dangling_link = tmp_path / "dangling.db" |
| 1137 | dangling_link.symlink_to(dangling_target) |
| 1138 | with pytest.raises(OSError): |
| 1139 | library_index._connect(dangling_link) |
| 1140 | assert not dangling_target.exists() |
| 1141 | |
| 1142 | # Symlinked SQLite sidecars (-wal, -shm, -journal) must be refused without chmodding target. |
| 1143 | for suffix in ("-wal", "-shm", "-journal"): |
| 1144 | real_db = tmp_path / f"real{suffix}.db" |
| 1145 | with closing(library_index._connect(real_db)): |
| 1146 | pass |
| 1147 | sidecar_victim = tmp_path / f"victim{suffix}.txt" |
| 1148 | sidecar_victim.write_text("sidecar-victim", encoding="utf-8") |
| 1149 | sidecar_victim.chmod(0o644) |
| 1150 | Path(f"{real_db}{suffix}").symlink_to(sidecar_victim) |
| 1151 | |
| 1152 | with pytest.raises(OSError): |
| 1153 | library_index._connect(real_db) |
| 1154 | assert stat.S_IMODE(sidecar_victim.stat().st_mode) == 0o644 |
| 1155 | assert sidecar_victim.read_text(encoding="utf-8") == "sidecar-victim" |
| 1156 | |
| 1157 | |
| 1158 | @pytest.mark.skipif(os.name != "posix", reason="POSIX FIFO and directory permissions") |
| 1159 | def test_high215_library_index_hardens_sidecars_and_rejects_fifo_and_world_writable_dir(tmp_path: Path): |
| 1160 | # New DB + nested private dirs get 0o700 dirs and 0o600 DB + sidecars. |
| 1161 | old_umask = os.umask(0o022) |
| 1162 | try: |
| 1163 | nested_db = tmp_path / "nested" / "index" / "library.db" |
| 1164 | with closing(library_index._connect(nested_db)): |
| 1165 | pass |
| 1166 | finally: |
| 1167 | os.umask(old_umask) |
| 1168 | |
| 1169 | assert stat.S_IMODE(nested_db.parent.stat().st_mode) == 0o700 |
| 1170 | assert stat.S_IMODE(nested_db.parent.parent.stat().st_mode) == 0o700 |
| 1171 | assert stat.S_IMODE(nested_db.stat().st_mode) == 0o600 |
| 1172 | |
| 1173 | # Loosened DB and sidecar modes are re-hardened to 0o600 on reconnect. |
| 1174 | sidecars = [Path(f"{nested_db}{s}") for s in ("-wal", "-shm", "-journal")] |
| 1175 | nested_db.chmod(0o644) |
| 1176 | for sc in sidecars: |
| 1177 | sc.write_bytes(b"") |
| 1178 | sc.chmod(0o644) |
| 1179 | |
| 1180 | with closing(library_index._connect(nested_db)): |
| 1181 | pass |
| 1182 | assert stat.S_IMODE(nested_db.stat().st_mode) == 0o600 |
| 1183 | for sc in sidecars: |
| 1184 | assert stat.S_IMODE(sc.stat().st_mode) == 0o600 |
| 1185 | |
| 1186 | # FIFO at DB or sidecar path is rejected without hanging. |
| 1187 | if hasattr(os, "mkfifo"): |
| 1188 | fifo_db = tmp_path / "fifo.db" |
| 1189 | os.mkfifo(fifo_db) |
| 1190 | with pytest.raises(OSError): |
| 1191 | library_index._connect(fifo_db) |
| 1192 | |
| 1193 | # World-writable parent directory is refused. |
| 1194 | world_dir = tmp_path / "world-writable" |
| 1195 | world_dir.mkdir() |
| 1196 | world_dir.chmod(0o777) |
| 1197 | try: |
| 1198 | with pytest.raises(OSError): |
| 1199 | library_index._connect(world_dir / "library.db") |
| 1200 | finally: |
| 1201 | world_dir.chmod(0o700) |
| 1202 | |
| 1203 | # Dangling symlink parent directory is refused by _ensure_private_directory. |
| 1204 | dangling_parent = tmp_path / "dangling-dir" |
| 1205 | dangling_parent.symlink_to(tmp_path / "nonexistent-dir") |
| 1206 | with pytest.raises(OSError): |
| 1207 | library_index._connect(dangling_parent / "library.db") |
| 1208 | assert not (tmp_path / "nonexistent-dir").exists() |
| 1209 | |
| 1210 | # Path beneath a symlink inside a 0o777 directory fails BEFORE creating any |
| 1211 | # target subdirectory or calling chmod on the symlink target. |
| 1212 | victim_dir = tmp_path / "victim-dir" |
| 1213 | victim_dir.mkdir() |
| 1214 | victim_dir.chmod(0o755) |
| 1215 | world_parent = tmp_path / "world-parent" |
| 1216 | world_parent.mkdir() |
| 1217 | world_parent.chmod(0o777) |
| 1218 | try: |
| 1219 | (world_parent / "escape-link").symlink_to(victim_dir) |
| 1220 | with pytest.raises(OSError): |
| 1221 | library_index._connect(world_parent / "escape-link" / "nested-sub" / "library.db") |
| 1222 | assert not (victim_dir / "nested-sub").exists() |
| 1223 | assert stat.S_IMODE(victim_dir.stat().st_mode) == 0o755 |
| 1224 | finally: |
| 1225 | world_parent.chmod(0o700) |
| 1226 |