| 1 | """Security regression tests for PR01 (HIGH-049 through HIGH-054). |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-049: Safe URL validation for feed_url / entry_urls in render_library_index |
| 5 | - HIGH-050: Single-pass HTML template substitution (no chained placeholder expansion) |
| 6 | - HIGH-051: HTML-context-safe META: marker and engine-footer token handling |
| 7 | - HIGH-052: Strict HTTPS endpoint validation and no-redirect transport in html_publish |
| 8 | - HIGH-053: Symlink/FIFO rejection and TOCTOU-free fchmod in prepare_private_sqlite_files |
| 9 | - HIGH-054: Atomic symlink/FIFO-safe writes and BaseException FD cleanup in write_private_text |
| 10 | """ |
| 11 | |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | import errno |
| 15 | import http.client |
| 16 | import io |
| 17 | import json |
| 18 | import os |
| 19 | import stat |
| 20 | import time |
| 21 | import urllib.error |
| 22 | import urllib.request |
| 23 | from datetime import date, datetime, timezone |
| 24 | from pathlib import Path |
| 25 | from unittest.mock import patch |
| 26 | |
| 27 | import pytest |
| 28 | |
| 29 | from lib import html_publish, html_render, private_files, schema |
| 30 | from lib.library import LibraryEntry |
| 31 | |
| 32 | |
| 33 | def _sample_entry( |
| 34 | *, |
| 35 | topic: str = "AI agents", |
| 36 | headline: str = "Agent loops are durable", |
| 37 | source_name: str = "ai-agents.md", |
| 38 | ) -> LibraryEntry: |
| 39 | return LibraryEntry( |
| 40 | slug="ai-agents", |
| 41 | topic=topic, |
| 42 | published_date=date(2026, 7, 10), |
| 43 | headline=headline, |
| 44 | summary="Summary text.", |
| 45 | source_path=Path(f"/tmp/{source_name}"), |
| 46 | content="# Brief\n\nBody text.", |
| 47 | source_updated_at=datetime(2026, 7, 10, 12, 0, tzinfo=timezone.utc), |
| 48 | source_format="finished-brief", |
| 49 | ) |
| 50 | |
| 51 | |
| 52 | def _sample_report(topic: str = "AI agents") -> schema.Report: |
| 53 | item = schema.SourceItem( |
| 54 | item_id="item-1", |
| 55 | source="grounding", |
| 56 | title="Sample result", |
| 57 | body="Body text", |
| 58 | url="https://example.test/1", |
| 59 | container="example.test", |
| 60 | published_at="2026-04-20", |
| 61 | date_confidence="high", |
| 62 | engagement={"views": 100}, |
| 63 | snippet="Sample snippet", |
| 64 | ) |
| 65 | return schema.Report( |
| 66 | topic=topic, |
| 67 | range_from="2026-03-30", |
| 68 | range_to="2026-04-29", |
| 69 | generated_at="2026-04-29T12:00:00+00:00", |
| 70 | provider_runtime=schema.ProviderRuntime( |
| 71 | reasoning_provider="local", |
| 72 | planner_model="mock-planner", |
| 73 | rerank_model="mock-rerank", |
| 74 | ), |
| 75 | query_plan=schema.QueryPlan( |
| 76 | intent="research", |
| 77 | freshness_mode="balanced_recent", |
| 78 | cluster_mode="story", |
| 79 | raw_topic=topic, |
| 80 | subqueries=[ |
| 81 | schema.SubQuery( |
| 82 | label="primary", |
| 83 | search_query=topic, |
| 84 | ranking_query=topic, |
| 85 | sources=["grounding"], |
| 86 | ) |
| 87 | ], |
| 88 | source_weights={"grounding": 1.0}, |
| 89 | ), |
| 90 | clusters=[], |
| 91 | ranked_candidates=[], |
| 92 | items_by_source={"grounding": [item]}, |
| 93 | errors_by_source={}, |
| 94 | artifacts={"pre_research_flags_present": True}, |
| 95 | ) |
| 96 | |
| 97 | |
| 98 | # --------------------------------------------------------------------------- |
| 99 | # HIGH-049: render_library_index feed_url & entry_urls validation |
| 100 | # --------------------------------------------------------------------------- |
| 101 | |
| 102 | |
| 103 | @pytest.mark.parametrize( |
| 104 | "bad_url", |
| 105 | [ |
| 106 | "javascript:alert(1)", |
| 107 | "JAVASCRIPT:alert(1)", |
| 108 | " javascript:alert(1)", |
| 109 | "java\nscript:alert(1)", |
| 110 | "java\tscript:alert(1)", |
| 111 | "java\rscript:alert(1)", |
| 112 | "data:text/html,<script>alert(1)</script>", |
| 113 | "vbscript:msgbox(1)", |
| 114 | "file:///etc/passwd", |
| 115 | "mailto:attacker@example.com", |
| 116 | "//evil.example/feed.xml", |
| 117 | "/\\evil.example/feed.xml", |
| 118 | "\\\\evil.example\\feed.xml", |
| 119 | "\\evil.example/feed.xml", |
| 120 | "https:evil.example", |
| 121 | "https:///evil.example", |
| 122 | "https://example.com\x7f/x", |
| 123 | " ", |
| 124 | "", |
| 125 | ], |
| 126 | ) |
| 127 | def test_high049_render_library_index_rejects_unsafe_feed_and_entry_urls(bad_url: str): |
| 128 | entry = _sample_entry() |
| 129 | rendered = html_render.render_library_index( |
| 130 | [entry], |
| 131 | feed_url=bad_url, |
| 132 | entry_urls={entry.entry_id: bad_url}, |
| 133 | ) |
| 134 | assert 'class="subscribe"' not in rendered |
| 135 | assert ">Latest</a>" not in rendered |
| 136 | assert f"<h3>{entry.headline}</h3>" in rendered |
| 137 | assert "<a " not in rendered |
| 138 | |
| 139 | |
| 140 | def test_high049_render_library_index_allows_safe_relative_and_http_urls(): |
| 141 | e1 = _sample_entry(headline="First brief", source_name="ai-agents-1.md") |
| 142 | e2 = _sample_entry(headline="Second brief", source_name="ai-agents-2.md") |
| 143 | rendered = html_render.render_library_index( |
| 144 | [e1, e2], |
| 145 | feed_url="https://example.com/feed.xml?a=1&b=2", |
| 146 | entry_urls={ |
| 147 | e1.entry_id: "https://site.ht-ml.app/brief/1?x=1&y=2", |
| 148 | e2.entry_id: "briefs/second.html", |
| 149 | }, |
| 150 | ) |
| 151 | assert 'href="https://example.com/feed.xml?a=1&b=2"' in rendered |
| 152 | assert 'href="https://site.ht-ml.app/brief/1?x=1&y=2">Latest</a>' in rendered |
| 153 | assert 'href="https://site.ht-ml.app/brief/1?x=1&y=2">First brief</a>' in rendered |
| 154 | assert 'href="briefs/second.html">Second brief</a>' in rendered |
| 155 | |
| 156 | |
| 157 | def test_high049_markdown_links_reject_protocol_relative_and_backslash_urls(): |
| 158 | for payload in ( |
| 159 | "[click](//evil.example/phish)", |
| 160 | "[click](/\\evil.example/phish)", |
| 161 | "[click](\\\\evil.example/phish)", |
| 162 | "[click](https:evil.example)", |
| 163 | "[click](https:///evil.example)", |
| 164 | ): |
| 165 | rendered = html_render._markdown_to_html(payload) |
| 166 | assert "<a " not in rendered, payload |
| 167 | assert "href=" not in rendered, payload |
| 168 | |
| 169 | |
| 170 | def test_high049_render_library_index_escapes_quotes_in_safe_url(): |
| 171 | entry = _sample_entry() |
| 172 | rendered = html_render.render_library_index( |
| 173 | [entry], |
| 174 | feed_url='feed.xml?q="onclick="alert(1)', |
| 175 | entry_urls={entry.entry_id: 'https://example.com/p?x="onclick="alert(1)'}, |
| 176 | ) |
| 177 | assert 'onclick="alert(1)"' not in rendered |
| 178 | assert """ in rendered |
| 179 | |
| 180 | |
| 181 | @pytest.mark.parametrize( |
| 182 | "entity_payload", |
| 183 | [ |
| 184 | "javascript:alert(1)", |
| 185 | "javascript:alert(1)", |
| 186 | "javascript:alert(1)", |
| 187 | "java	script:alert(1)", |
| 188 | ], |
| 189 | ) |
| 190 | def test_high049_entity_encoded_xss_urls_rejected_in_markdown_and_library_index(entity_payload: str): |
| 191 | md_rendered = html_render._markdown_to_html(f"[click]({entity_payload})") |
| 192 | assert "<a " not in md_rendered |
| 193 | assert "href=" not in md_rendered |
| 194 | |
| 195 | entry = _sample_entry() |
| 196 | idx_rendered = html_render.render_library_index( |
| 197 | [entry], |
| 198 | feed_url=entity_payload, |
| 199 | entry_urls={entry.entry_id: entity_payload}, |
| 200 | ) |
| 201 | assert "<a " not in idx_rendered |
| 202 | assert "href=" not in idx_rendered |
| 203 | |
| 204 | |
| 205 | # --------------------------------------------------------------------------- |
| 206 | # HIGH-050: Single-pass template placeholder substitution |
| 207 | # --------------------------------------------------------------------------- |
| 208 | |
| 209 | |
| 210 | def test_high050_body_containing_colophon_placeholder_is_not_expanded(): |
| 211 | md = ( |
| 212 | "Read [this link](https://example.com/__COLOPHON__) " |
| 213 | "and `__CSS__` and `__BODY__` and `__TITLE__`." |
| 214 | ) |
| 215 | rendered = html_render.render_html( |
| 216 | _sample_report("Placeholder test"), |
| 217 | synthesis_md=md, |
| 218 | ) |
| 219 | assert '<a href="https://example.com/__COLOPHON__" rel="noopener noreferrer">this link</a>' in rendered |
| 220 | assert rendered.count('<div class="colophon">') == 1 |
| 221 | assert "<code>__CSS__</code>" in rendered |
| 222 | assert "<code>__BODY__</code>" in rendered |
| 223 | assert "<code>__TITLE__</code>" in rendered |
| 224 | |
| 225 | |
| 226 | def test_high050_title_containing_template_placeholders_is_not_expanded(): |
| 227 | topic = "__CSS__ __BODY__ __COLOPHON__ __TITLE__" |
| 228 | rendered = html_render.render_html(_sample_report(topic)) |
| 229 | title_start = rendered.index("<title>") + len("<title>") |
| 230 | title_end = rendered.index("</title>") |
| 231 | title_text = rendered[title_start:title_end] |
| 232 | assert title_text == f"last30days · {topic}" |
| 233 | assert ":root {" not in title_text |
| 234 | assert '<div class="colophon">' not in title_text |
| 235 | |
| 236 | |
| 237 | def test_high050_colophon_escapes_generated_date_and_library_brief_handles_closing_body(): |
| 238 | report = _sample_report("Colophon escape") |
| 239 | report.generated_at = "<img src=x>2026-04-29" |
| 240 | rendered = html_render.render_html(report) |
| 241 | assert "<img src=x>" not in rendered |
| 242 | assert "<img src=x" in rendered |
| 243 | |
| 244 | entry = _sample_entry(headline="Body tag test") |
| 245 | entry = LibraryEntry( |
| 246 | slug=entry.slug, |
| 247 | topic=entry.topic, |
| 248 | published_date=entry.published_date, |
| 249 | headline=entry.headline, |
| 250 | summary=entry.summary, |
| 251 | source_path=entry.source_path, |
| 252 | content="Literal </body> tag in prose and `code` next to __CODE_0__.", |
| 253 | source_updated_at=entry.source_updated_at, |
| 254 | source_format="finished-brief", |
| 255 | ) |
| 256 | brief_html = html_render.render_library_brief(entry) |
| 257 | assert "</body>" in brief_html |
| 258 | assert "<code>code</code> next to __CODE_0__" in brief_html |
| 259 | assert brief_html.endswith(f"{html_render.LIBRARY_BRIEF_MARKER}\n</body>\n</html>\n") |
| 260 | |
| 261 | |
| 262 | # --------------------------------------------------------------------------- |
| 263 | # HIGH-051: HTML-context-safe META: markers & engine-footer tokens |
| 264 | # --------------------------------------------------------------------------- |
| 265 | |
| 266 | |
| 267 | def test_high051_meta_marker_inside_link_href_or_code_does_not_break_out(): |
| 268 | md = ( |
| 269 | "Link: [x](https://example.com/<!--META:hi-->)\n\n" |
| 270 | "Backticked in URL: [y](https://example.com/`<!-- META: hi -->`)\n\n" |
| 271 | "Inline prose: before <!-- META: inline --> after\n\n" |
| 272 | "Inline code: `<!-- META: inline-code -->`\n\n" |
| 273 | "```html\n" |
| 274 | "<!-- META: fenced-code -->\n" |
| 275 | "<!-- regular comment stays in code -->\n" |
| 276 | "```" |
| 277 | ) |
| 278 | rendered = html_render.render_html(_sample_report("Meta safety"), synthesis_md=md) |
| 279 | # Exactly one legitimate <div class="meta"> from the report metadata line. |
| 280 | assert rendered.count('<div class="meta">') == 1 |
| 281 | assert '<a href="https://example.com/<!--META:hi-->" rel="noopener noreferrer">x</a>' in rendered |
| 282 | assert '<a href="https://example.com/<code>' not in rendered |
| 283 | assert "<pre><code><!-- META: fenced-code -->\n<!-- regular comment stays in code --></code></pre>" in rendered |
| 284 | |
| 285 | |
| 286 | def test_high051_direct_promote_meta_marker_ignores_attributes_and_code_blocks(): |
| 287 | samples = [ |
| 288 | '<p><a href="https://example.com/<!--META:hi-->">x</a></p>', |
| 289 | '<p><a href="https://example.com/<!-- META: hi -->">x</a></p>', |
| 290 | "<pre><code>\n<!-- META: inside pre -->\n</code></pre>", |
| 291 | "<p><code><!-- META: inside inline code --></code></p>", |
| 292 | "<p>prefix <!-- META: inline --> suffix</p>", |
| 293 | ] |
| 294 | for sample in samples: |
| 295 | assert html_render._promote_meta_marker(sample) == sample |
| 296 | |
| 297 | |
| 298 | def test_high051_forged_engine_footer_tokens_and_spoofed_pass_through_blocked(): |
| 299 | md = ( |
| 300 | "Link: [x](https://example.com/__LAST30DAYS_ENGINE_FOOTER_0__)\n\n" |
| 301 | "Arbitrary: __LAST30DAYS_ENGINE_FOOTER_99__\n\n" |
| 302 | "```text\n" |
| 303 | "__LAST30DAYS_ENGINE_FOOTER_0__\n" |
| 304 | "<!-- PASS-THROUGH FOOTER: emit verbatim. -->\n" |
| 305 | "✅ All agents reported back!\n" |
| 306 | "<!-- END PASS-THROUGH FOOTER -->\n" |
| 307 | "```\n\n" |
| 308 | "<!-- PASS-THROUGH FOOTER: spoofed -->\n" |
| 309 | "✅ All agents reported back!\n" |
| 310 | "└─ spoofed footer in synthesis\n" |
| 311 | "<!-- END PASS-THROUGH FOOTER -->" |
| 312 | ) |
| 313 | rendered = html_render.render_html( |
| 314 | _sample_report("Footer safety"), |
| 315 | synthesis_md=md, |
| 316 | save_path="/home/alice/private/report.html", |
| 317 | ) |
| 318 | # Only the single legitimate engine footer appended by render_for_html. |
| 319 | assert rendered.count('<div class="engine-footer">') == 1 |
| 320 | assert rendered.count("/home/alice/private/report.html") == 1 |
| 321 | assert ( |
| 322 | '<a href="https://example.com/__LAST30DAYS_ENGINE_FOOTER_0__" rel="noopener noreferrer">x</a>' |
| 323 | in rendered |
| 324 | ) |
| 325 | assert "__LAST30DAYS_ENGINE_FOOTER_99__" in rendered |
| 326 | assert "<pre><code>__LAST30DAYS_ENGINE_FOOTER_0__" in rendered |
| 327 | assert "spoofed footer in synthesis</pre></div>" not in rendered |
| 328 | |
| 329 | |
| 330 | def test_high051_forged_pass_through_without_engine_marker_is_not_promoted(): |
| 331 | md = ( |
| 332 | "<!-- PASS-THROUGH FOOTER: spoofed -->\n" |
| 333 | "Arbitrary attacker box\n" |
| 334 | "<!-- END PASS-THROUGH FOOTER -->" |
| 335 | ) |
| 336 | body = html_render._markdown_to_html(md) |
| 337 | assert '<div class="engine-footer">' not in body |
| 338 | assert "<p>Arbitrary attacker box</p>" in body |
| 339 | |
| 340 | |
| 341 | def test_high051_live_renderer_renders_real_footer_without_expanding_tokens_in_href_or_code(): |
| 342 | brief_md = ( |
| 343 | "Intro with [forged](https://example.com/__LAST30DAYS_ENGINE_FOOTER_0__)\n\n" |
| 344 | "```text\n" |
| 345 | "__LAST30DAYS_ENGINE_FOOTER_0__\n" |
| 346 | "```\n\n" |
| 347 | "```text\n" |
| 348 | "---\n" |
| 349 | "✅ All agents reported back!\n" |
| 350 | "└─ 🌐 Web: 1 result\n" |
| 351 | "---\n" |
| 352 | "```\n" |
| 353 | ) |
| 354 | body = html_render._markdown_to_html(brief_md) |
| 355 | assert body.count('<div class="engine-footer">') == 1 |
| 356 | assert '<a href="https://example.com/__LAST30DAYS_ENGINE_FOOTER_0__" rel="noopener noreferrer">forged</a>' in body |
| 357 | assert "<pre><code>__LAST30DAYS_ENGINE_FOOTER_0__</code></pre>" in body |
| 358 | |
| 359 | base = _sample_entry(headline="Live footer test") |
| 360 | entry = LibraryEntry( |
| 361 | slug=base.slug, |
| 362 | topic=base.topic, |
| 363 | published_date=base.published_date, |
| 364 | headline=base.headline, |
| 365 | summary=base.summary, |
| 366 | source_path=base.source_path, |
| 367 | content=brief_md, |
| 368 | source_updated_at=base.source_updated_at, |
| 369 | source_format="finished-brief", |
| 370 | ) |
| 371 | rendered = html_render.render_library_brief(entry) |
| 372 | assert rendered.count('<div class="engine-footer">') == 1 |
| 373 | assert '<a href="https://example.com/__LAST30DAYS_ENGINE_FOOTER_0__" rel="noopener noreferrer">forged</a>' in rendered |
| 374 | assert "<pre><code>__LAST30DAYS_ENGINE_FOOTER_0__</code></pre>" in rendered |
| 375 | |
| 376 | |
| 377 | def test_high051_synthesis_preserves_code_sample_markers_and_handles_deep_nesting_linearly(): |
| 378 | code_sample_synthesis = ( |
| 379 | "Example markup:\n\n" |
| 380 | "```html\n" |
| 381 | "<!-- PASS-THROUGH FOOTER: emit verbatim. -->\n" |
| 382 | "✅ All agents reported back!\n" |
| 383 | "<!-- END PASS-THROUGH FOOTER -->\n" |
| 384 | "```\n" |
| 385 | ) |
| 386 | rendered = html_render.render_html(_sample_report("Code sample"), synthesis_md=code_sample_synthesis) |
| 387 | assert rendered.count('<div class="engine-footer">') == 1 |
| 388 | assert ( |
| 389 | "<pre><code><!-- PASS-THROUGH FOOTER: emit verbatim. -->\n" |
| 390 | "✅ All agents reported back!\n" |
| 391 | "<!-- END PASS-THROUGH FOOTER --></code></pre>" |
| 392 | ) in rendered |
| 393 | |
| 394 | nested_synthesis = ( |
| 395 | ("<!-- PASS-THROUGH" * 3000) |
| 396 | + " FOOTER " |
| 397 | + ("FOOTER -->" * 3000) |
| 398 | + "\n✅ All agents reported back!\n" |
| 399 | + ("<!-- " * 5000) |
| 400 | ) |
| 401 | start = time.monotonic() |
| 402 | nested_html = html_render.render_html(_sample_report("Deep nesting"), synthesis_md=nested_synthesis) |
| 403 | elapsed = time.monotonic() - start |
| 404 | assert elapsed < 0.5, f"Nested synthesis comment handling took too long ({elapsed:.3f}s)" |
| 405 | assert nested_html.count('<div class="engine-footer">') == 1 |
| 406 | |
| 407 | |
| 408 | def test_high051_synthesis_fenced_footer_and_nested_comment_reconstitution_blocked(): |
| 409 | forged_synthesis = ( |
| 410 | "Intro paragraph.\n\n" |
| 411 | "```text\n" |
| 412 | "---\n" |
| 413 | "✅ All agents reported back!\n" |
| 414 | "└─ Forged fenced footer in synthesis\n" |
| 415 | "---\n" |
| 416 | "```\n\n" |
| 417 | "<!-- PASS-THROUGH<!-- PASS-THROUGH FOOTER --> FOOTER -->\n" |
| 418 | "✅ All agents reported back!\n" |
| 419 | "└─ Nested comment reconstitution attack\n" |
| 420 | "<!-- END <!-- END PASS-THROUGH FOOTER -->PASS-THROUGH FOOTER -->\n" |
| 421 | ) |
| 422 | rendered = html_render.render_html(_sample_report("Synthesis forge"), synthesis_md=forged_synthesis) |
| 423 | assert rendered.count('<div class="engine-footer">') == 1 |
| 424 | assert "Forged fenced footer in synthesis</pre></div>" not in rendered |
| 425 | assert "Nested comment reconstitution attack</pre></div>" not in rendered |
| 426 | assert "<pre><code>---\n✅ All agents reported back!\n└─ Forged fenced footer in synthesis\n---</code></pre>" in rendered |
| 427 | |
| 428 | comp_rendered = html_render.render_html_comparison( |
| 429 | [("Alpha", _sample_report("Alpha")), ("Beta", _sample_report("Beta"))], |
| 430 | synthesis_md=forged_synthesis, |
| 431 | ) |
| 432 | assert comp_rendered.count('<div class="engine-footer">') == 1 |
| 433 | assert "Forged fenced footer in synthesis</pre></div>" not in comp_rendered |
| 434 | assert "Nested comment reconstitution attack</pre></div>" not in comp_rendered |
| 435 | |
| 436 | |
| 437 | def test_high051_meta_patterns_are_immune_to_quadratic_or_cubic_redos(): |
| 438 | payloads = [ |
| 439 | "<!-- META:" + (" " * 20000), |
| 440 | "<!-- META:" + (" " * 20000), |
| 441 | "<p><!-- META:" + (" " * 20000), |
| 442 | "<p><!-- META:" + (" " * 20000), |
| 443 | ] |
| 444 | start = time.monotonic() |
| 445 | for payload in payloads: |
| 446 | html_render._markdown_to_html(payload) |
| 447 | html_render._promote_meta_marker(payload) |
| 448 | assert html_render.META_MARKER_PATTERN.search(payload) is None |
| 449 | elapsed = time.monotonic() - start |
| 450 | assert elapsed < 0.5, f"META regexes took too long ({elapsed:.3f}s)" |
| 451 | |
| 452 | |
| 453 | # --------------------------------------------------------------------------- |
| 454 | # HIGH-052: html_publish strict HTTPS endpoint & no-redirect transport |
| 455 | # --------------------------------------------------------------------------- |
| 456 | |
| 457 | |
| 458 | @pytest.mark.parametrize( |
| 459 | "bad_endpoint", |
| 460 | [ |
| 461 | "http://api.ht-ml.app/v1/sites", |
| 462 | "http://127.0.0.1:8080/v1/sites", |
| 463 | "file:///etc/passwd", |
| 464 | "FILE:///etc/passwd", |
| 465 | "ftp://example.com/upload", |
| 466 | "data:text/html,<h1>hi</h1>", |
| 467 | "javascript:alert(1)", |
| 468 | "https://", |
| 469 | "https:///v1/sites", |
| 470 | "https://user:pass@api.ht-ml.app/v1/sites", |
| 471 | "https://api.ht-ml.app@evil.example/v1/sites", |
| 472 | "https://api.ht-ml.app\\evil.example/v1/sites", |
| 473 | "https://evil.example\\@api.ht-ml.app/v1/sites", |
| 474 | "https://api.ht-ml.app/v1/sites\r\nX-Injected: 1", |
| 475 | " https://api.ht-ml.app/v1/sites", |
| 476 | "https://api.ht-ml.app/v1/sites ", |
| 477 | "https://api.ht-ml.app/v1/sites with space", |
| 478 | "https://api.ht-ml.app:notaport/v1/sites", |
| 479 | "", |
| 480 | ], |
| 481 | ) |
| 482 | def test_high052_publish_html_rejects_non_https_and_malformed_endpoints(bad_endpoint: str): |
| 483 | called = False |
| 484 | |
| 485 | def fail_if_called(_req, timeout): |
| 486 | nonlocal called |
| 487 | called = True |
| 488 | raise AssertionError("opener must not be called for invalid endpoint") |
| 489 | |
| 490 | with pytest.raises(html_publish.HtmlPublishError): |
| 491 | html_publish.publish_html("<html>ok</html>", endpoint=bad_endpoint, opener=fail_if_called) |
| 492 | assert called is False |
| 493 | |
| 494 | |
| 495 | def test_high052_default_publish_opener_omits_insecure_handlers_and_blocks_redirects(): |
| 496 | with patch.object(urllib.request, "getproxies", return_value={}): |
| 497 | opener = html_publish._build_publish_opener() |
| 498 | for banned_scheme in ("file", "ftp", "data", "http"): |
| 499 | assert banned_scheme not in opener.handle_open |
| 500 | assert "https" in opener.handle_open |
| 501 | |
| 502 | # Even if HTTP_PROXY / FTP_PROXY are configured in the environment, |
| 503 | # _build_publish_opener only binds https proxies and never enables http/ftp. |
| 504 | with patch.object( |
| 505 | urllib.request, |
| 506 | "getproxies", |
| 507 | return_value={ |
| 508 | "http": "http://127.0.0.1:8888", |
| 509 | "ftp": "http://127.0.0.1:8888", |
| 510 | "https": "http://127.0.0.1:8888", |
| 511 | }, |
| 512 | ): |
| 513 | proxied_opener = html_publish._build_publish_opener() |
| 514 | for banned_scheme in ("file", "ftp", "data", "http"): |
| 515 | assert banned_scheme not in proxied_opener.handle_open |
| 516 | assert "https" in proxied_opener.handle_open |
| 517 | with pytest.raises(html_publish.HtmlPublishError): |
| 518 | html_publish.publish_html("<html>ok</html>", endpoint="http://api.ht-ml.app/v1/sites") |
| 519 | |
| 520 | handler = html_publish._NoRedirectHandler() |
| 521 | req = urllib.request.Request("https://api.ht-ml.app/v1/sites", method="POST") |
| 522 | for code, target in ( |
| 523 | (301, "https://api.ht-ml.app/v2/sites"), |
| 524 | (302, "http://api.ht-ml.app/v1/sites"), |
| 525 | (303, "https://evil.example/see-other"), |
| 526 | (307, "https://evil.example/steal"), |
| 527 | (308, "http://127.0.0.1/internal"), |
| 528 | ): |
| 529 | with pytest.raises(urllib.error.HTTPError) as exc_info: |
| 530 | handler.redirect_request(req, None, code, "Redirect", {}, target) |
| 531 | assert exc_info.value.code == code |
| 532 | assert "redirect" in str(exc_info.value.reason).lower() |
| 533 | |
| 534 | |
| 535 | def test_high052_publish_html_refuses_303_without_reading_body_and_closes_fp(): |
| 536 | class _SpyBody: |
| 537 | def __init__(self) -> None: |
| 538 | self.read_called = False |
| 539 | self.closed = False |
| 540 | |
| 541 | def read(self, *_args): |
| 542 | self.read_called = True |
| 543 | return b"redirect body must not be read" |
| 544 | |
| 545 | def close(self) -> None: |
| 546 | self.closed = True |
| 547 | |
| 548 | spy = _SpyBody() |
| 549 | |
| 550 | def redirect_opener(request, timeout): |
| 551 | raise urllib.error.HTTPError( |
| 552 | request.full_url, |
| 553 | 303, |
| 554 | "publish endpoint redirects are not allowed", |
| 555 | {}, |
| 556 | spy, |
| 557 | ) |
| 558 | |
| 559 | with pytest.raises(html_publish.HtmlPublishError, match="303:.*redirect"): |
| 560 | html_publish.publish_html("<html>ok</html>", password="secret", opener=redirect_opener) |
| 561 | assert spy.read_called is False |
| 562 | assert spy.closed is True |
| 563 | |
| 564 | |
| 565 | def test_high052_publish_html_bounds_response_and_wraps_decode_and_http_errors(): |
| 566 | class _BytesResp: |
| 567 | def __init__(self, data: bytes): |
| 568 | self._buf = io.BytesIO(data) |
| 569 | |
| 570 | def __enter__(self): |
| 571 | return self |
| 572 | |
| 573 | def __exit__(self, *_args): |
| 574 | return False |
| 575 | |
| 576 | def read(self, n: int = -1) -> bytes: |
| 577 | return self._buf.read(n) |
| 578 | |
| 579 | oversized = b'{"url":"https://ok.ht-ml.app","pad":"' + (b"x" * (html_publish._MAX_RESPONSE_BYTES + 100)) + b'"}' |
| 580 | with pytest.raises(html_publish.HtmlPublishError, match="exceeded"): |
| 581 | html_publish.publish_html("<html>ok</html>", opener=lambda _req, timeout: _BytesResp(oversized)) |
| 582 | |
| 583 | with pytest.raises(html_publish.HtmlPublishError): |
| 584 | html_publish.publish_html("<html>ok</html>", opener=lambda _req, timeout: _BytesResp(b"\xff\xfe\xfd")) |
| 585 | |
| 586 | def incomplete_opener(_req, timeout): |
| 587 | raise http.client.IncompleteRead(b"partial") |
| 588 | |
| 589 | with pytest.raises(html_publish.HtmlPublishError): |
| 590 | html_publish.publish_html("<html>ok</html>", opener=incomplete_opener) |
| 591 | |
| 592 | class _HugeErrBody: |
| 593 | def __init__(self) -> None: |
| 594 | self.requested_sizes: list[int] = [] |
| 595 | self.closed = False |
| 596 | |
| 597 | def read(self, n: int = -1) -> bytes: |
| 598 | self.requested_sizes.append(n) |
| 599 | return b"E" * (html_publish._MAX_ERROR_BYTES + 500) |
| 600 | |
| 601 | def close(self) -> None: |
| 602 | self.closed = True |
| 603 | |
| 604 | err_fp = _HugeErrBody() |
| 605 | |
| 606 | def err_opener(request, timeout): |
| 607 | raise urllib.error.HTTPError(request.full_url, 502, "Bad Gateway", {}, err_fp) |
| 608 | |
| 609 | with pytest.raises(html_publish.HtmlPublishError, match="^502:"): |
| 610 | html_publish.publish_html("<html>ok</html>", opener=err_opener) |
| 611 | assert err_fp.requested_sizes == [html_publish._MAX_ERROR_BYTES + 1] |
| 612 | assert err_fp.closed is True |
| 613 | |
| 614 | |
| 615 | @pytest.mark.parametrize( |
| 616 | "read_exc", |
| 617 | [http.client.IncompleteRead(b"cut"), ConnectionResetError("connection reset")], |
| 618 | ) |
| 619 | def test_high052_publish_html_error_body_drop_falls_back_to_status_and_preserves_batch(read_exc): |
| 620 | class _DroppingBody: |
| 621 | def __init__(self) -> None: |
| 622 | self.closed = False |
| 623 | |
| 624 | def read(self, *_args): |
| 625 | raise read_exc |
| 626 | |
| 627 | def close(self) -> None: |
| 628 | self.closed = True |
| 629 | |
| 630 | class _OkResp: |
| 631 | def __enter__(self): |
| 632 | return self |
| 633 | |
| 634 | def __exit__(self, *_args): |
| 635 | return False |
| 636 | |
| 637 | def read(self, *_args) -> bytes: |
| 638 | return b'{"url":"https://first.ht-ml.app"}' |
| 639 | |
| 640 | dropping_fp = _DroppingBody() |
| 641 | calls = 0 |
| 642 | |
| 643 | def batch_opener(request, timeout): |
| 644 | nonlocal calls |
| 645 | calls += 1 |
| 646 | if calls == 1: |
| 647 | return _OkResp() |
| 648 | raise urllib.error.HTTPError(request.full_url, 503, "Service Unavailable", {}, dropping_fp) |
| 649 | |
| 650 | batch = html_publish.publish_html_documents( |
| 651 | {"first": "<html>1</html>", "second": "<html>2</html>"}, |
| 652 | opener=batch_opener, |
| 653 | ) |
| 654 | assert dict(batch) == {"first": {"url": "https://first.ht-ml.app"}} |
| 655 | assert isinstance(batch.error, html_publish.HtmlPublishError) |
| 656 | assert "503" in str(batch.error) |
| 657 | assert "Service Unavailable" in str(batch.error) |
| 658 | assert dropping_fp.closed is True |
| 659 | |
| 660 | |
| 661 | def test_high052_publish_html_surfaces_redirect_refusal_as_publish_error(): |
| 662 | def redirect_opener(request, timeout): |
| 663 | raise urllib.error.HTTPError( |
| 664 | request.full_url, |
| 665 | 307, |
| 666 | "publish endpoint redirects are not allowed", |
| 667 | {}, |
| 668 | None, |
| 669 | ) |
| 670 | |
| 671 | with pytest.raises(html_publish.HtmlPublishError, match="307:.*redirect"): |
| 672 | html_publish.publish_html("<html>ok</html>", password="secret", opener=redirect_opener) |
| 673 | |
| 674 | |
| 675 | def test_high052_publish_html_rejects_malicious_response_url(): |
| 676 | class _Resp: |
| 677 | def __init__(self, url: str): |
| 678 | self._url = url |
| 679 | |
| 680 | def __enter__(self): |
| 681 | return self |
| 682 | |
| 683 | def __exit__(self, *_args): |
| 684 | return False |
| 685 | |
| 686 | def read(self) -> bytes: |
| 687 | return json.dumps({"url": self._url}).encode("utf-8") |
| 688 | |
| 689 | for bad_url in ( |
| 690 | "javascript:alert(1)", |
| 691 | "http://example.ht-ml.app", |
| 692 | "https://user@evil.example", |
| 693 | "https://evil.example/\r\nfoo", |
| 694 | "https://", |
| 695 | ): |
| 696 | with pytest.raises(html_publish.HtmlPublishError, match="valid url"): |
| 697 | html_publish.publish_html( |
| 698 | "<html>ok</html>", |
| 699 | opener=lambda _req, timeout: _Resp(bad_url), |
| 700 | ) |
| 701 | |
| 702 | |
| 703 | def test_high052_publish_html_honors_monkeypatched_urlopen(): |
| 704 | class _Resp: |
| 705 | def __enter__(self): |
| 706 | return self |
| 707 | |
| 708 | def __exit__(self, *_args): |
| 709 | return False |
| 710 | |
| 711 | def read(self) -> bytes: |
| 712 | return b'{"url": "https://patched.ht-ml.app"}' |
| 713 | |
| 714 | with patch.object(html_publish, "urlopen", return_value=_Resp()) as patched: |
| 715 | result = html_publish.publish_html("<html>ok</html>") |
| 716 | assert result == {"url": "https://patched.ht-ml.app"} |
| 717 | patched.assert_called_once() |
| 718 | |
| 719 | |
| 720 | # --------------------------------------------------------------------------- |
| 721 | # HIGH-053: prepare_private_sqlite_files symlink, FIFO, and TOCTOU hardening |
| 722 | # --------------------------------------------------------------------------- |
| 723 | |
| 724 | |
| 725 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks and permissions") |
| 726 | def test_high053_prepare_sqlite_rejects_symlink_to_existing_file_without_chmod(tmp_path: Path): |
| 727 | victim = tmp_path / "victim.txt" |
| 728 | victim.write_text("keep untouched", encoding="utf-8") |
| 729 | victim.chmod(0o644) |
| 730 | |
| 731 | link = tmp_path / "research.db" |
| 732 | link.symlink_to(victim) |
| 733 | |
| 734 | with pytest.raises(OSError): |
| 735 | private_files.prepare_private_sqlite_files(link, create=False) |
| 736 | with pytest.raises(OSError): |
| 737 | private_files.prepare_private_sqlite_files(link, create=True) |
| 738 | |
| 739 | assert stat.S_IMODE(victim.stat().st_mode) == 0o644 |
| 740 | assert victim.read_text(encoding="utf-8") == "keep untouched" |
| 741 | |
| 742 | |
| 743 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks") |
| 744 | def test_high053_prepare_sqlite_rejects_dangling_symlink_without_creating_target(tmp_path: Path): |
| 745 | target = tmp_path / "must-not-be-created.db" |
| 746 | link = tmp_path / "dangling.db" |
| 747 | link.symlink_to(target) |
| 748 | |
| 749 | with pytest.raises(OSError): |
| 750 | private_files.prepare_private_sqlite_files(link, create=True) |
| 751 | |
| 752 | assert not target.exists() |
| 753 | |
| 754 | |
| 755 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks and permissions") |
| 756 | def test_high053_prepare_sqlite_rejects_symlinked_sidecar_without_chmod(tmp_path: Path): |
| 757 | db = tmp_path / "research.db" |
| 758 | db.write_bytes(b"") |
| 759 | db.chmod(0o644) |
| 760 | |
| 761 | victim = tmp_path / "victim-sidecar.txt" |
| 762 | victim.write_text("victim", encoding="utf-8") |
| 763 | victim.chmod(0o644) |
| 764 | |
| 765 | wal = Path(f"{db}-wal") |
| 766 | wal.symlink_to(victim) |
| 767 | |
| 768 | with pytest.raises(OSError): |
| 769 | private_files.prepare_private_sqlite_files(db, create=False) |
| 770 | |
| 771 | assert stat.S_IMODE(victim.stat().st_mode) == 0o644 |
| 772 | |
| 773 | |
| 774 | @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="POSIX FIFO test") |
| 775 | def test_high053_prepare_sqlite_rejects_fifo_without_blocking(tmp_path: Path): |
| 776 | db = tmp_path / "research.db" |
| 777 | os.mkfifo(db) |
| 778 | |
| 779 | with pytest.raises(OSError): |
| 780 | private_files.prepare_private_sqlite_files(db, create=False) |
| 781 | |
| 782 | real_db = tmp_path / "real.db" |
| 783 | real_db.write_bytes(b"") |
| 784 | os.mkfifo(Path(f"{real_db}-wal")) |
| 785 | with pytest.raises(OSError): |
| 786 | private_files.prepare_private_sqlite_files(real_db, create=False) |
| 787 | |
| 788 | |
| 789 | @pytest.mark.skipif(os.name != "posix", reason="POSIX fchmod hardening") |
| 790 | def test_high053_prepare_sqlite_uses_nofollow_and_fchmod_not_path_chmod(tmp_path: Path): |
| 791 | db = tmp_path / "research.db" |
| 792 | db.write_bytes(b"sqlite") |
| 793 | db.chmod(0o644) |
| 794 | |
| 795 | open_calls: list[int] = [] |
| 796 | fchmod_calls: list[int] = [] |
| 797 | real_open = os.open |
| 798 | real_fchmod = os.fchmod |
| 799 | |
| 800 | def spy_open(path, flags, *args, **kwargs): |
| 801 | open_calls.append(flags) |
| 802 | return real_open(path, flags, *args, **kwargs) |
| 803 | |
| 804 | def spy_fchmod(fd, mode): |
| 805 | fchmod_calls.append(mode) |
| 806 | return real_fchmod(fd, mode) |
| 807 | |
| 808 | with patch.object(private_files.os, "open", side_effect=spy_open), \ |
| 809 | patch.object(private_files.os, "fchmod", side_effect=spy_fchmod), \ |
| 810 | patch.object(Path, "chmod", side_effect=AssertionError("path-based chmod is TOCTOU-unsafe")): |
| 811 | returned = private_files.prepare_private_sqlite_files(db, create=False) |
| 812 | |
| 813 | assert returned == db.parent.resolve() / db.name |
| 814 | assert stat.S_IMODE(db.stat().st_mode) == 0o600 |
| 815 | assert fchmod_calls == [0o600] |
| 816 | if hasattr(os, "O_NOFOLLOW"): |
| 817 | assert all(flags & os.O_NOFOLLOW for flags in open_calls) |
| 818 | |
| 819 | |
| 820 | @pytest.mark.skipif(os.name != "posix", reason="POSIX directory permissions") |
| 821 | def test_high053_prepare_sqlite_rejects_world_writable_parent_or_non_sticky_ancestor(tmp_path: Path): |
| 822 | # Immediate parent world-writable without sticky bit (0o777) -> rejected. |
| 823 | world_dir = tmp_path / "world-parent" |
| 824 | world_dir.mkdir() |
| 825 | world_dir.chmod(0o777) |
| 826 | try: |
| 827 | db_world = world_dir / "research.db" |
| 828 | db_world.write_bytes(b"") |
| 829 | with pytest.raises(OSError, match="writable by other users"): |
| 830 | private_files.prepare_private_sqlite_files(db_world, create=False) |
| 831 | with pytest.raises(OSError, match="writable by other users"): |
| 832 | private_files.prepare_private_sqlite_files(world_dir / "new.db", create=True) |
| 833 | finally: |
| 834 | world_dir.chmod(0o700) |
| 835 | |
| 836 | # Immediate parent world-writable WITH sticky bit (0o1777) -> still rejected |
| 837 | # because another user could pre-create -wal/-shm sidecars. |
| 838 | sticky_dir = tmp_path / "sticky-parent" |
| 839 | sticky_dir.mkdir() |
| 840 | sticky_dir.chmod(0o1777) |
| 841 | try: |
| 842 | db_sticky = sticky_dir / "research.db" |
| 843 | db_sticky.write_bytes(b"") |
| 844 | with pytest.raises(OSError, match="writable by other users"): |
| 845 | private_files.prepare_private_sqlite_files(db_sticky, create=False) |
| 846 | finally: |
| 847 | sticky_dir.chmod(0o700) |
| 848 | |
| 849 | # Untrusted writable non-sticky ancestor -> rejected even if immediate child is 0o700. |
| 850 | unsafe_ancestor = tmp_path / "unsafe-ancestor" |
| 851 | unsafe_ancestor.mkdir() |
| 852 | child_dir = unsafe_ancestor / "private-child" |
| 853 | child_dir.mkdir(mode=0o700) |
| 854 | db_nested = child_dir / "research.db" |
| 855 | db_nested.write_bytes(b"") |
| 856 | unsafe_ancestor.chmod(0o777) |
| 857 | try: |
| 858 | with pytest.raises(OSError, match="writable non-sticky ancestor"): |
| 859 | private_files.prepare_private_sqlite_files(db_nested, create=False) |
| 860 | finally: |
| 861 | unsafe_ancestor.chmod(0o700) |
| 862 | |
| 863 | # Sticky world-writable ancestor (like /tmp) + owner-only child (0o700) -> allowed. |
| 864 | sticky_ancestor = tmp_path / "sticky-ancestor" |
| 865 | sticky_ancestor.mkdir() |
| 866 | safe_child = sticky_ancestor / "owned-child" |
| 867 | safe_child.mkdir(mode=0o700) |
| 868 | db_safe = safe_child / "research.db" |
| 869 | db_safe.write_bytes(b"") |
| 870 | sticky_ancestor.chmod(0o1777) |
| 871 | try: |
| 872 | returned = private_files.prepare_private_sqlite_files(db_safe, create=False) |
| 873 | assert returned == db_safe.parent.resolve() / db_safe.name |
| 874 | assert stat.S_IMODE(db_safe.stat().st_mode) == 0o600 |
| 875 | finally: |
| 876 | sticky_ancestor.chmod(0o700) |
| 877 | |
| 878 | |
| 879 | # --------------------------------------------------------------------------- |
| 880 | # HIGH-054: write_private_text symlink/FIFO rejection, atomicity, BaseException |
| 881 | # --------------------------------------------------------------------------- |
| 882 | |
| 883 | |
| 884 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks and permissions") |
| 885 | def test_high054_write_private_text_rejects_symlink_and_preserves_target(tmp_path: Path): |
| 886 | victim = tmp_path / "victim.txt" |
| 887 | victim.write_text("original secret", encoding="utf-8") |
| 888 | victim.chmod(0o644) |
| 889 | |
| 890 | link = tmp_path / "state.json" |
| 891 | link.symlink_to(victim) |
| 892 | |
| 893 | with pytest.raises(OSError): |
| 894 | private_files.write_private_text(link, "overwritten", encoding="utf-8") |
| 895 | |
| 896 | assert victim.read_text(encoding="utf-8") == "original secret" |
| 897 | assert stat.S_IMODE(victim.stat().st_mode) == 0o644 |
| 898 | |
| 899 | dangling_target = tmp_path / "never-created.json" |
| 900 | dangling = tmp_path / "dangling.json" |
| 901 | dangling.symlink_to(dangling_target) |
| 902 | with pytest.raises(OSError): |
| 903 | private_files.write_private_text(dangling, "payload", encoding="utf-8") |
| 904 | assert not dangling_target.exists() |
| 905 | |
| 906 | |
| 907 | @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="POSIX FIFO test") |
| 908 | def test_high054_write_private_text_rejects_fifo_without_blocking(tmp_path: Path): |
| 909 | fifo = tmp_path / "pipe.json" |
| 910 | os.mkfifo(fifo) |
| 911 | |
| 912 | with pytest.raises(OSError): |
| 913 | private_files.write_private_text(fifo, "secret payload", encoding="utf-8") |
| 914 | |
| 915 | |
| 916 | @pytest.mark.skipif(os.name != "posix", reason="POSIX file descriptors") |
| 917 | def test_high054_write_private_text_closes_fd_and_preserves_file_on_base_exception(tmp_path: Path): |
| 918 | path = tmp_path / "state.json" |
| 919 | path.write_text("previous intact content", encoding="utf-8") |
| 920 | path.chmod(0o600) |
| 921 | |
| 922 | opened_fds: list[int] = [] |
| 923 | real_open = os.open |
| 924 | |
| 925 | def spy_open(*args, **kwargs): |
| 926 | fd = real_open(*args, **kwargs) |
| 927 | opened_fds.append(fd) |
| 928 | return fd |
| 929 | |
| 930 | with patch.object(private_files.os, "open", side_effect=spy_open), \ |
| 931 | patch.object(private_files.os, "fchmod", side_effect=KeyboardInterrupt("ctrl-c")): |
| 932 | with pytest.raises(KeyboardInterrupt): |
| 933 | private_files.write_private_text(path, "new content", encoding="utf-8") |
| 934 | |
| 935 | assert len(opened_fds) == 1 |
| 936 | with pytest.raises(OSError) as exc_info: |
| 937 | os.fstat(opened_fds[0]) |
| 938 | assert exc_info.value.errno == errno.EBADF |
| 939 | assert path.read_text(encoding="utf-8") == "previous intact content" |
| 940 | assert list(tmp_path.iterdir()) == [path] |
| 941 | |
| 942 | |
| 943 | @pytest.mark.skipif(os.name != "posix", reason="POSIX atomic replacement") |
| 944 | def test_high054_write_private_text_is_atomic_on_mid_write_failure(tmp_path: Path): |
| 945 | path = tmp_path / "state.json" |
| 946 | path.write_text("good previous state", encoding="utf-8") |
| 947 | path.chmod(0o600) |
| 948 | |
| 949 | class _FailingStream: |
| 950 | def __init__(self, inner): |
| 951 | self._inner = inner |
| 952 | |
| 953 | def __enter__(self): |
| 954 | return self |
| 955 | |
| 956 | def __exit__(self, *args): |
| 957 | return self._inner.__exit__(*args) |
| 958 | |
| 959 | def write(self, _data: str) -> int: |
| 960 | self._inner.write("partial") |
| 961 | raise OSError(errno.ENOSPC, "No space left on device") |
| 962 | |
| 963 | real_fdopen = os.fdopen |
| 964 | with patch.object( |
| 965 | private_files.os, |
| 966 | "fdopen", |
| 967 | side_effect=lambda fd, *a, **kw: _FailingStream(real_fdopen(fd, *a, **kw)), |
| 968 | ): |
| 969 | with pytest.raises(OSError, match="No space left"): |
| 970 | private_files.write_private_text(path, "new state", encoding="utf-8") |
| 971 | |
| 972 | assert path.read_text(encoding="utf-8") == "good previous state" |
| 973 | assert list(tmp_path.iterdir()) == [path] |
| 974 | |
| 975 | |
| 976 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlink check") |
| 977 | def test_high054_replace_private_text_rejects_symlink_and_preserves_target(tmp_path: Path): |
| 978 | victim = tmp_path / "victim.env" |
| 979 | victim.write_text("KEEP=1\n", encoding="utf-8") |
| 980 | victim.chmod(0o644) |
| 981 | |
| 982 | link = tmp_path / ".env" |
| 983 | link.symlink_to(victim) |
| 984 | |
| 985 | with pytest.raises(OSError): |
| 986 | private_files.replace_private_text(link, "PWNED=1\n") |
| 987 | |
| 988 | assert victim.read_text(encoding="utf-8") == "KEEP=1\n" |
| 989 | assert stat.S_IMODE(victim.stat().st_mode) == 0o644 |
| 990 | |
| 991 | |
| 992 | @pytest.mark.skipif(os.name != "posix", reason="POSIX directory permissions and symlinks") |
| 993 | def test_high054_replace_private_text_uses_resolved_parent_and_rejects_untrusted_dirs(tmp_path: Path): |
| 994 | from types import SimpleNamespace |
| 995 | |
| 996 | # 1. User-owned dotfiles symlink inside a private user-owned directory pointing to a |
| 997 | # private destination MUST succeed and write via the canonical resolved destination. |
| 998 | home = tmp_path / "home" |
| 999 | home.mkdir(mode=0o700) |
| 1000 | dotfiles_cfg = home / "dotfiles" / ".config" / "last30days" |
| 1001 | dotfiles_cfg.mkdir(parents=True, mode=0o700) |
| 1002 | (home / "dotfiles").chmod(0o700) |
| 1003 | (home / "dotfiles" / ".config").chmod(0o700) |
| 1004 | cfg_link = home / ".config" |
| 1005 | cfg_link.symlink_to(home / "dotfiles" / ".config", target_is_directory=True) |
| 1006 | |
| 1007 | seen_destinations: list[Path] = [] |
| 1008 | real_replace = os.replace |
| 1009 | |
| 1010 | def spy_replace(src, dst): |
| 1011 | seen_destinations.append(Path(dst)) |
| 1012 | return real_replace(src, dst) |
| 1013 | |
| 1014 | with patch.object(private_files.os, "replace", side_effect=spy_replace): |
| 1015 | private_files.replace_private_text(cfg_link / "last30days" / ".env", "API_KEY=ok\n") |
| 1016 | |
| 1017 | expected_env = dotfiles_cfg.resolve() / ".env" |
| 1018 | assert seen_destinations == [expected_env] |
| 1019 | assert expected_env.read_text(encoding="utf-8") == "API_KEY=ok\n" |
| 1020 | |
| 1021 | # 2. User-owned symlink in a trusted dir pointing to a world-writable destination -> rejected. |
| 1022 | world_target = tmp_path / "world-target" |
| 1023 | world_target.mkdir() |
| 1024 | world_target.chmod(0o777) |
| 1025 | bad_link = home / "bad-link" |
| 1026 | bad_link.symlink_to(world_target, target_is_directory=True) |
| 1027 | try: |
| 1028 | with pytest.raises(OSError, match="writable"): |
| 1029 | private_files.replace_private_text(bad_link / "settings.env", "A=1\n") |
| 1030 | assert not (world_target / "settings.env").exists() |
| 1031 | finally: |
| 1032 | world_target.chmod(0o700) |
| 1033 | |
| 1034 | # 3. Symlink sitting inside a world-writable (even sticky) directory -> rejected (even as root). |
| 1035 | sticky_shared = tmp_path / "sticky-shared" |
| 1036 | sticky_shared.mkdir() |
| 1037 | sticky_shared.chmod(0o1777) |
| 1038 | real_dir = home / "real" |
| 1039 | real_dir.mkdir(mode=0o700) |
| 1040 | shared_sym = sticky_shared / "sym-parent" |
| 1041 | shared_sym.symlink_to(real_dir, target_is_directory=True) |
| 1042 | try: |
| 1043 | with pytest.raises(OSError, match="writable by other users"): |
| 1044 | private_files.replace_private_text(shared_sym / "settings.env", "A=1\n") |
| 1045 | assert not (real_dir / "settings.env").exists() |
| 1046 | finally: |
| 1047 | sticky_shared.chmod(0o700) |
| 1048 | |
| 1049 | # 4. Symlink owned by another non-root user inside a trusted dir -> rejected (even as root). |
| 1050 | other_sym = home / "other-owner-link" |
| 1051 | other_sym.symlink_to(real_dir, target_is_directory=True) |
| 1052 | real_lstat = os.lstat |
| 1053 | foreign_uid = os.geteuid() + 1000 |
| 1054 | |
| 1055 | def fake_lstat(p): |
| 1056 | st = real_lstat(p) |
| 1057 | if Path(p) == other_sym: |
| 1058 | return SimpleNamespace( |
| 1059 | st_mode=st.st_mode, |
| 1060 | st_uid=foreign_uid, |
| 1061 | st_gid=st.st_gid, |
| 1062 | ) |
| 1063 | return st |
| 1064 | |
| 1065 | with patch.object(private_files, "_OS_LSTAT", side_effect=fake_lstat): |
| 1066 | with pytest.raises(OSError, match="owned by another user"): |
| 1067 | private_files.replace_private_text(other_sym / "settings.env", "A=1\n") |
| 1068 | assert not (real_dir / "settings.env").exists() |
| 1069 | |
| 1070 | # 5. Path with `..` resolves to the canonical verified parent for BOTH staging and os.replace. |
| 1071 | sub = real_dir / "sub" |
| 1072 | sub.mkdir(mode=0o700) |
| 1073 | unnormalized = sub / ".." / "settings.env" |
| 1074 | seen_destinations.clear() |
| 1075 | with patch.object(private_files.os, "replace", side_effect=spy_replace): |
| 1076 | private_files.replace_private_text(unnormalized, "OK=1\n") |
| 1077 | |
| 1078 | expected = real_dir.resolve() / "settings.env" |
| 1079 | assert seen_destinations == [expected] |
| 1080 | assert expected.read_text(encoding="utf-8") == "OK=1\n" |
| 1081 | |
| 1082 | |
| 1083 | @pytest.mark.skipif(os.name != "posix", reason="POSIX traverse-only directory test") |
| 1084 | def test_high053_traverse_only_ancestor_directory_allows_sqlite_and_private_writes(tmp_path: Path): |
| 1085 | ancestor = tmp_path / "traverse-only" |
| 1086 | ancestor.mkdir(mode=0o700) |
| 1087 | private_dir = ancestor / "store-dir" |
| 1088 | private_dir.mkdir(mode=0o700) |
| 1089 | db_path = private_dir / "research.db" |
| 1090 | db_path.write_bytes(b"") |
| 1091 | text_path = private_dir / "state.json" |
| 1092 | |
| 1093 | # Mode 0o111 (execute/traverse only, no read/list permission). |
| 1094 | ancestor.chmod(0o111) |
| 1095 | try: |
| 1096 | resolved = private_files.prepare_private_sqlite_files(db_path, create=False) |
| 1097 | assert resolved == db_path.parent.resolve() / db_path.name |
| 1098 | assert stat.S_IMODE(db_path.stat().st_mode) == 0o600 |
| 1099 | |
| 1100 | written = private_files.write_private_text(text_path, "traverse-ok", encoding="utf-8") |
| 1101 | assert written == len("traverse-ok") |
| 1102 | assert text_path.read_text(encoding="utf-8") == "traverse-ok" |
| 1103 | |
| 1104 | private_files.replace_private_text(text_path, "traverse-replaced") |
| 1105 | assert text_path.read_text(encoding="utf-8") == "traverse-replaced" |
| 1106 | finally: |
| 1107 | ancestor.chmod(0o700) |
| 1108 | |
| 1109 | |
| 1110 | @pytest.mark.skipif(os.name != "posix", reason="POSIX directory and group checks") |
| 1111 | def test_high053_shared_primary_gid_and_store_connect_blocked_before_sqlite_open(tmp_path: Path): |
| 1112 | import pwd |
| 1113 | import store |
| 1114 | from types import SimpleNamespace |
| 1115 | |
| 1116 | # 1. Shared primary GID (even when gr_mem is empty) must be rejected on group-writable dir. |
| 1117 | shared_dir = tmp_path / "shared-gid" |
| 1118 | shared_dir.mkdir(mode=0o700) |
| 1119 | shared_dir.chmod(0o770) |
| 1120 | db_shared = shared_dir / "research.db" |
| 1121 | db_shared.write_bytes(b"") |
| 1122 | euid = os.geteuid() |
| 1123 | real_pw = pwd.getpwuid(euid) |
| 1124 | fake_users = [ |
| 1125 | real_pw, |
| 1126 | SimpleNamespace(pw_name="otheruser", pw_uid=euid + 1000, pw_gid=shared_dir.lstat().st_gid), |
| 1127 | ] |
| 1128 | try: |
| 1129 | with patch.object(pwd, "getpwall", return_value=fake_users), \ |
| 1130 | patch.object(store.sqlite3, "connect", side_effect=AssertionError("sqlite3.connect must not run")): |
| 1131 | with pytest.raises(OSError, match="writable by other users"): |
| 1132 | store._connect(db_shared) |
| 1133 | finally: |
| 1134 | shared_dir.chmod(0o700) |
| 1135 | |
| 1136 | # 2. World-writable scoped store dir fails before sqlite3.connect. |
| 1137 | world_dir = tmp_path / "world-store" |
| 1138 | world_dir.mkdir() |
| 1139 | world_dir.chmod(0o777) |
| 1140 | try: |
| 1141 | with patch.object(store.sqlite3, "connect", side_effect=AssertionError("sqlite3.connect must not run")): |
| 1142 | with pytest.raises(OSError, match="writable by other users"): |
| 1143 | store._connect(world_dir / "research.db") |
| 1144 | finally: |
| 1145 | world_dir.chmod(0o700) |
| 1146 | |
| 1147 | # 3. Symlink inside a world-writable/sticky dir fails before sqlite3.connect (root-safe). |
| 1148 | owned_dir = tmp_path / "owned-store" |
| 1149 | owned_dir.mkdir(mode=0o700) |
| 1150 | sticky_dir = tmp_path / "sticky-store-parent" |
| 1151 | sticky_dir.mkdir() |
| 1152 | sticky_dir.chmod(0o1777) |
| 1153 | sym_in_shared = sticky_dir / "sym-store" |
| 1154 | sym_in_shared.symlink_to(owned_dir, target_is_directory=True) |
| 1155 | try: |
| 1156 | with patch.object(store.sqlite3, "connect", side_effect=AssertionError("sqlite3.connect must not run")): |
| 1157 | with pytest.raises(OSError, match="writable by other users"): |
| 1158 | store._connect(sym_in_shared / "research.db") |
| 1159 | finally: |
| 1160 | sticky_dir.chmod(0o700) |
| 1161 | |
| 1162 | # 4. Symlink owned by another non-root user fails before sqlite3.connect (root-safe). |
| 1163 | sym_foreign = tmp_path / "foreign-sym-store" |
| 1164 | sym_foreign.symlink_to(owned_dir, target_is_directory=True) |
| 1165 | real_lstat = os.lstat |
| 1166 | |
| 1167 | def fake_lstat(p): |
| 1168 | st = real_lstat(p) |
| 1169 | if Path(p) == sym_foreign: |
| 1170 | return SimpleNamespace( |
| 1171 | st_mode=st.st_mode, |
| 1172 | st_uid=euid + 1000, |
| 1173 | st_gid=st.st_gid, |
| 1174 | ) |
| 1175 | return st |
| 1176 | |
| 1177 | with patch.object(private_files, "_OS_LSTAT", side_effect=fake_lstat), \ |
| 1178 | patch.object(store.sqlite3, "connect", side_effect=AssertionError("sqlite3.connect must not run")): |
| 1179 | with pytest.raises(OSError, match="owned by another user"): |
| 1180 | store._connect(sym_foreign / "research.db") |
| 1181 |