Repository navigation
fix: remaining audit findings — content hash, XSS, TOCTOU, detection, site - #504
Conversation
|
Warning Rate limit exceeded
To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThis PR addresses multiple security and data integrity vulnerabilities: implements HTML sanitization to prevent XSS in rendered conversation content, includes content blocks in message hashing to prevent data loss during re-import, fixes a TOCTOU vulnerability in blob store file handling, reorders provider detection to prevent spoofing, registers automatic connection cleanup on exit, enables rendering of messages containing only content blocks, and adds JavaScript escaping in search results. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d295503017
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
… site - Include content blocks in message/conversation content hash (#466) - Eliminate BlobStore write_from_path TOCTOU double-read race (#470) - Register atexit handler for connection cache cleanup (#473) - Reorder provider detection so specific checks run first (#477) - Add sanitize_html filter replacing |safe in all HTML templates (#468) - Escape user data in client-side search innerHTML (#468) - Fix site generator dropping content_block-only messages (#475) Co-Authored-By: Claude Opus 4.7 <[email protected]>
CodeQL flagged the sanitizer's _SCRIPT_RE as incomplete: the closing-tag literal `</script>` did not match `</script >` or `</script\n>`, even though browsers accept whitespace before `>` in HTML closing tags. A crafted payload with `</script >` would survive the sanitizer pass. Replace `</script>` with `</script\s*>` to match the actual HTML grammar. Add tests/unit/rendering/test_html_sanitizer.py covering: - whitespace before > in closing tag (the CodeQL case) - mixed case <SCRIPT>/</SCRIPT > - attributes on opening tag - multiline body - event handler attributes - javascript: URLs - safe markup preserved - empty input Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
d295503 to
5a1dfa4
Compare
The single-pass write_from_path rewrite moved tempfile.mkstemp ahead of
the dest.parent.mkdir call. On a fresh archive (and in tests) the blob
store root does not exist yet, so mkstemp raises FileNotFoundError. The
source-acquisition layer's defensive except FileNotFoundError then
mis-attributed the error as a TOCTOU race on the source file, masking
the real bug behind a misleading log line.
Cause-and-effect chain:
fresh BlobStore.root not yet created
→ tempfile.mkstemp(dir=self.root) raises FileNotFoundError
→ caller in source_acquisition.py:134 catches it as "TOCTOU race"
→ 96 tests fail across source_laws, test_facade,
test_ingestion_interrupts, tail_query_runtime — all pointing at
valid source files that didn't actually disappear.
Fix: ensure self.root exists before mkstemp.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CodeQL flagged py/incomplete-multi-character-sanitization on the followup regex: real browsers accept </script\t\n bar> and similar forms with whitespace + attribute-like junk before >, even though HTML5 is strict. The previous </script\s*> regex still missed these. Match </script\s*[^>]*> so end tags with whitespace, tabs, newlines, trailing attribute-like junk, or non-ASCII whitespace are all stripped. Added test cases covering the CodeQL example </script\t\n bar>, an attribute-like form </script foo='bar'>, and non-breaking space. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
polylogue/storage/backends/connection.py (1)
102-119:⚠️ Potential issue | 🟠 Major
atexitcleanup only reaches the main thread's cache — worker thread connections leak.
_connection_cacheis athreading.local(), so each thread holds its ownconnsdict.atexitcallbacks run in the main thread, which means_clear_connection_cache()here only closes connections the main thread opened. This is demonstrated by the testtest_store_records_concurrently_without_race, which spawns worker threads that each callopen_connectionand cache connections in their own thread-local storage. Those worker thread connections are never closed, leaving their WAL sidecars un-checkpointed.Additionally, connections are opened with
check_same_thread=True(the default), so attempting to close a worker-thread connection from the atexit handler (main thread) raises an exception. Thesuppress(Exception)masks this, preventing actual FD and WAL cleanup.Note: The async production backend (
SQLiteBackend) usesaiosqliteand manages its own connections, bypassing this thread-local cache. The issue primarily affects sync code paths — tests, utilities, and CLI operations — but should still be fixed to ensure proper cleanup in those contexts.Consider tracking every per-thread
connsdict in a module-level registry (guarded by a lock) so the atexit hook can iterate and close all of them, e.g.:🔧 Suggested approach
_connection_cache: threading.local = threading.local() +_all_caches: list[dict[str, sqlite3.Connection]] = [] +_all_caches_lock = threading.Lock() @@ - cache: dict[str, sqlite3.Connection] = getattr(_connection_cache, "conns", {}) - if not hasattr(_connection_cache, "conns"): - _connection_cache.conns = cache + cache: dict[str, sqlite3.Connection] | None = getattr(_connection_cache, "conns", None) + if cache is None: + cache = {} + _connection_cache.conns = cache + with _all_caches_lock: + _all_caches.append(cache) @@ def _clear_connection_cache() -> None: ... - cache: dict[str, sqlite3.Connection] = getattr(_connection_cache, "conns", {}) - for conn in cache.values(): - with suppress(Exception): - conn.close() - _connection_cache.conns = {} + with _all_caches_lock: + caches = list(_all_caches) + for cache in caches: + for conn in list(cache.values()): + with suppress(Exception): + conn.close() + cache.clear() + if hasattr(_connection_cache, "conns"): + _connection_cache.conns = {}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/storage/backends/connection.py` around lines 102 - 119, The atexit cleanup only closes the main thread's thread-local connections because _connection_cache is threading.local(); fix this by introducing a module-level registry (e.g., a dict or weakref.WeakKeyDictionary) plus a threading.Lock to track every thread's conns dict when connections are created, update the function that populates _connection_cache.conns (e.g., open_connection or its helper) to register the thread's conns dict in that registry, and change _clear_connection_cache to iterate the registry under the lock and attempt to close each stored sqlite3.Connection (handling check_same_thread by closing only from the owning thread or using connection.close() inside a try/except and removing entries); finally keep atexit.register(_clear_connection_cache) but ensure the registry is cleaned up as threads exit.polylogue/storage/blob_store.py (1)
48-107: 🛠️ Refactor suggestion | 🟠 MajorEliminate duplication: delegate
write_from_pathtowrite_from_fileobj.After this rewrite,
write_from_pathis functionally identical to opening the source and callingwrite_from_fileobj— same temp dir (self.root), same chunk size, same dedup/replace logic, same cleanup. Maintaining two near-copies of the single-pass write/dedup state machine is risky: any future fix (e.g., addingos.fsyncbeforeos.replace, adjusting cleanup ordering, or tweaking heartbeat semantics) has to be mirrored in both. The two are already drifting slightly (e.g., this method closesfdbefore the dedup check at line 86;write_from_fileobjcloses it inside each branch).♻️ Proposed refactor
def write_from_path( self, source: Path, *, heartbeat: Heartbeat | None = None, ) -> tuple[str, int]: """Stream-hash a file and copy it to the store. Reads the source in 128 KB chunks — never loads the full file into Python memory. Returns ``(sha256_hex, byte_count)``. If a blob with the same hash already exists, the write is skipped (content-addressed deduplication). """ - # Single-pass: hash and write to temp file simultaneously. The temp - # lives at the blob-store root so the final ``os.replace`` to the - # sharded ``aa/bb/...`` destination stays on the same filesystem. - # Ensure the root exists; in a fresh archive (and in tests) it has - # not been created yet, and ``tempfile.mkstemp`` would raise - # ``FileNotFoundError`` — which the source-acquisition layer would - # then mis-attribute as a TOCTOU race against the source file. - self.root.mkdir(parents=True, exist_ok=True) - fd = None - tmp_path: str | None = None - try: - hasher = hashlib.sha256() - size = 0 - fd, tmp_path = tempfile.mkstemp(dir=self.root, prefix=".blob.") - with open(source, "rb") as src: - while True: - chunk = src.read(_CHUNK_SIZE) - if not chunk: - break - hasher.update(chunk) - os.write(fd, chunk) - size += len(chunk) - if heartbeat is not None: - heartbeat() - os.close(fd) - fd = None - - hash_hex = hasher.hexdigest() - dest = self.blob_path(hash_hex) - - if dest.exists(): - os.unlink(tmp_path) - tmp_path = None - return hash_hex, size - - dest.parent.mkdir(parents=True, exist_ok=True) - os.chmod(tmp_path, 0o600) - os.replace(tmp_path, dest) - tmp_path = None - finally: - if fd is not None: - os.close(fd) - if tmp_path is not None and os.path.exists(tmp_path): - os.unlink(tmp_path) - - return hash_hex, size + with open(source, "rb") as src: + return self.write_from_fileobj(src, heartbeat=heartbeat)
write_from_fileobjalready doesself.root.mkdir(parents=True, exist_ok=True)(line 122), so the FileNotFoundError concern from commit 3 is preserved.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/storage/blob_store.py` around lines 48 - 107, write_from_path duplicates the single-pass hashing+temp-write/dedup logic already implemented in write_from_fileobj; refactor write_from_path to open the Path as a binary file and call write_from_fileobj(fileobj, heartbeat=heartbeat) instead of reimplementing the loop and temp-file handling so all behavior (self.root creation, chunking, dedup, chmod/replace, cleanup, heartbeat) is centralized in write_from_fileobj; ensure the method returns the same (sha256_hex, byte_count) tuple and preserves error/cleanup semantics by delegating to write_from_fileobj and not duplicating tempfile or fd management.polylogue/site/search.py (1)
134-145:⚠️ Potential issue | 🟡 MinorDefense-in-depth:
esc()is HTML-context only — also reject non-relative/javascript:URLs fordoc.path.
esccorrectly escapes element/attribute content, but it does not reject dangerous URL schemes. Ifdoc.pathever leaks user-controlled content,href="javascript:..."survivesesc()unchanged. Since this is the only value going into a URL-typed attribute, it's worth a cheap allowlist:🛡️ Proposed hardening
const esc = (s) => String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,'''); + const safeUrl = (u) => { + const s = String(u || ''); + return /^(https?:|\/|\.|[^:]*$)/i.test(s) ? s : '#'; + }; results.innerHTML = matches.map((doc) => ` <li class="conversation-card"> - <a href="${esc(doc.path)}" class="conversation-link"> + <a href="${esc(safeUrl(doc.path))}" class="conversation-link">🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/site/search.py` around lines 134 - 145, The current esc() escapes HTML but does not block dangerous URL schemes in doc.path, so update the code that builds results.innerHTML to validate doc.path before using it in href: allow only relative/fragment paths (e.g. strings that start with "/", "./", "../" or "#") and reject anything else (including strings containing a scheme like "javascript:"); if validation fails replace the href with a safe placeholder (e.g. "#" or omit the link) and then continue to use esc() for escaping. Locate the mapping that generates the anchor (the matches.map callback referencing doc.path, esc, and results.innerHTML) and add a small sanitizer/allowlist check there to enforce the rule.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@polylogue/pipeline/ids.py`:
- Around line 201-212: The conversation hash construction duplicates the
per-message payload used by message_content_hash; fix by extracting the shared
per-message payload logic into a single helper (e.g., _message_hash_payload(msg,
message_id)) and have the loop that builds messages_payload call that helper for
each convo.messages, preserving content_blocks ordering and omitting the key
when empty; update references in conversation_content_hash and
message_content_hash to use this helper so both hashes are structurally
identical.
- Around line 160-174: In _content_block_payload, the optional fields tool_name,
tool_id, and media_type are currently gated by truthiness and thus drop empty
strings instead of preserving sentinel values; change those conditionals to
explicit "is not None" checks and still call _normalize_for_hash on each
(similar to tool_input which already uses "is not None" and hash_payload), so
that None and "" are distinguished in the returned payload by the sentinel
values.
In `@polylogue/rendering/renderers/html_sanitizer.py`:
- Around line 18-35: The current regex-based sanitizer (functions/vars:
sanitize_html, _SCRIPT_RE, _EVENT_ATTR_RE, _JAVASCRIPT_URL_RE) is bypassable;
replace it with a real HTML parser-based allowlist sanitizer (use nh3 or bleach)
configured with an explicit tag allowlist, attribute allowlist, and URL-scheme
allowlist (e.g., http, https, mailto, relative) to block javascript: and
dangerous elements (iframe, object, embed, meta refresh, style payloads,
unquoted attributes, etc.), then return the cleaned string wrapped in
Markup(sanitized) so Jinja2 treats it as safe; remove the fragile regexes and
ensure tests cover edge cases like `<script ...>...</script foo="bar">`,
unquoted onclick, and non-href javascript: URLs.
In `@polylogue/sources/dispatch.py`:
- Around line 85-90: The detection code is making an unnecessary shallow copy by
calling dict(record) before passing it to codex.looks_like and
claude.looks_like_code; remove the dict(...) wrapper and pass the existing
record object directly to codex.looks_like and claude.looks_like_code (leave the
return values Provider.CODEX and Provider.CLAUDE_CODE unchanged), since neither
function mutates its input and avoiding the copy reduces allocations in this hot
path.
In `@polylogue/storage/blob_store.py`:
- Around line 75-95: Update the method's docstring to reflect the new
TOCTOU-safe behavior: clarify that the implementation now always writes the
source into a temporary file under self.root and only skips the final
install/move when the hash already exists (i.e., the write is not truly
skipped). Also consider adding an optional fast pre-check before creating the
temp file inside the same method: perform os.stat(source).st_size vs any
existing blob size from self.blob_path(hash) and a small content sniff (e.g.,
open source and compare the first few KB) to avoid full-source writes for common
duplicate cases, falling back to the current full-write-then-check flow if the
pre-check is inconclusive; reference the functions/variables: self.blob_path,
self.root, heartbeat, hasher, tmp_path to locate and modify the implementation
and docstring.
In `@tests/unit/rendering/test_html_sanitizer.py`:
- Around line 45-47: The test test_sanitize_preserves_safe_markup is brittle
because it asserts exact string equality of sanitize_html(safe); update it to
check structural properties instead: call sanitize_html(safe) (or
str(sanitize_html(safe))) and assert that the expected substrings like "hello"
and "<strong>world</strong>" (or the tag "strong" containing "world") are
present, rather than comparing the entire output exactly, so the test still
passes if sanitizer normalizes quotes/whitespace or uses html5lib/bleach.
- Around line 40-42: The test test_sanitize_strips_javascript_urls currently
only checks for the exact substring "javascript:"; expand it to cover common
bypasses by parameterizing inputs (use sanitize_html) with variants such as
mixed-case "JavaScript:alert(1)", prefixed whitespace or control chars like
"\tjavascript:alert(1)" and encoded forms like "javascript:alert(1)" and
assert the sanitized output does not contain the scheme in any case or encoded
form (e.g., lowercased/normalized check or decode HTML entities first),
referencing the test_sanitize_strips_javascript_urls test and the sanitize_html
helper so you exercise all these inputs and assert rejection consistently.
---
Outside diff comments:
In `@polylogue/site/search.py`:
- Around line 134-145: The current esc() escapes HTML but does not block
dangerous URL schemes in doc.path, so update the code that builds
results.innerHTML to validate doc.path before using it in href: allow only
relative/fragment paths (e.g. strings that start with "/", "./", "../" or "#")
and reject anything else (including strings containing a scheme like
"javascript:"); if validation fails replace the href with a safe placeholder
(e.g. "#" or omit the link) and then continue to use esc() for escaping. Locate
the mapping that generates the anchor (the matches.map callback referencing
doc.path, esc, and results.innerHTML) and add a small sanitizer/allowlist check
there to enforce the rule.
In `@polylogue/storage/backends/connection.py`:
- Around line 102-119: The atexit cleanup only closes the main thread's
thread-local connections because _connection_cache is threading.local(); fix
this by introducing a module-level registry (e.g., a dict or
weakref.WeakKeyDictionary) plus a threading.Lock to track every thread's conns
dict when connections are created, update the function that populates
_connection_cache.conns (e.g., open_connection or its helper) to register the
thread's conns dict in that registry, and change _clear_connection_cache to
iterate the registry under the lock and attempt to close each stored
sqlite3.Connection (handling check_same_thread by closing only from the owning
thread or using connection.close() inside a try/except and removing entries);
finally keep atexit.register(_clear_connection_cache) but ensure the registry is
cleaned up as threads exit.
In `@polylogue/storage/blob_store.py`:
- Around line 48-107: write_from_path duplicates the single-pass
hashing+temp-write/dedup logic already implemented in write_from_fileobj;
refactor write_from_path to open the Path as a binary file and call
write_from_fileobj(fileobj, heartbeat=heartbeat) instead of reimplementing the
loop and temp-file handling so all behavior (self.root creation, chunking,
dedup, chmod/replace, cleanup, heartbeat) is centralized in write_from_fileobj;
ensure the method returns the same (sha256_hex, byte_count) tuple and preserves
error/cleanup semantics by delegating to write_from_fileobj and not duplicating
tempfile or fd management.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 61b2f8f7-e1d7-4c3f-8d55-fd47c9b9c385
📒 Files selected for processing (14)
docs/plans/topology-target.yamldocs/topology-status.mdpolylogue/pipeline/ids.pypolylogue/rendering/renderers/html_sanitizer.pypolylogue/rendering/renderers/html_template.pypolylogue/rendering/templates/conversation.htmlpolylogue/site/conversation_pages.pypolylogue/site/search.pypolylogue/site/template_environment.pypolylogue/site/templates_conversation.pypolylogue/sources/dispatch.pypolylogue/storage/backends/connection.pypolylogue/storage/blob_store.pytests/unit/rendering/test_html_sanitizer.py
| def _content_block_payload(block: ParsedContentBlock) -> dict[str, JSONValue]: | ||
| """Build a hash-stable payload for a single content block.""" | ||
| payload: dict[str, JSONValue] = { | ||
| "type": str(block.type), | ||
| "text": _normalize_for_hash(block.text), | ||
| } | ||
| if block.tool_name: | ||
| payload["tool_name"] = _normalize_for_hash(block.tool_name) | ||
| if block.tool_id: | ||
| payload["tool_id"] = _normalize_for_hash(block.tool_id) | ||
| if block.tool_input is not None: | ||
| payload["tool_input"] = hash_payload(dict(block.tool_input)) | ||
| if block.media_type: | ||
| payload["media_type"] = _normalize_for_hash(block.media_type) | ||
| return payload |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect ParsedContentBlock definition and any default factories / parser assignments.
fd -t f 'base.py' -p 'sources/parsers' --exec cat {}
echo '---'
ast-grep --pattern 'ParsedContentBlock($$$)'
echo '---'
rg -nP --type=py -C2 '\b(tool_name|tool_id|media_type)\s*='Repository: Sinity/polylogue
Length of output: 48562
🏁 Script executed:
fd -type f -name "base.py" | xargs grep -l "class ParsedContentBlock"Repository: Sinity/polylogue
Length of output: 233
🏁 Script executed:
fd -type f -name "*.py" | xargs grep -l "class ParsedContentBlock"Repository: Sinity/polylogue
Length of output: 233
🏁 Script executed:
rg -A 15 "class ParsedContentBlock"Repository: Sinity/polylogue
Length of output: 2454
🏁 Script executed:
cat -n polylogue/sources/parsers/base_models.py | head -100Repository: Sinity/polylogue
Length of output: 4059
🏁 Script executed:
rg -A 30 "class ParsedContentBlock" polylogue/sources/parsers/base_models.pyRepository: Sinity/polylogue
Length of output: 1087
🏁 Script executed:
rg -B 3 -A 8 "_optional_string"Repository: Sinity/polylogue
Length of output: 16013
🏁 Script executed:
rg -B 5 -A 10 "tool_name = " polylogue/sources/parsers/base_support.py | head -80Repository: Sinity/polylogue
Length of output: 809
🏁 Script executed:
rg -B 5 -A 10 "ParsedContentBlock" polylogue/sources/parsers/ | grep -A 8 "tool_name\|media_type" | head -100Repository: Sinity/polylogue
Length of output: 4628
🏁 Script executed:
rg -B 5 -A 15 "def _normalize_for_hash" polylogue/pipeline/ids.pyRepository: Sinity/polylogue
Length of output: 653
Use is not None consistently for all optional fields to preserve sentinel-based disambiguation.
_normalize_for_hash explicitly converts None to _NULL_SENTINEL and "" to _EMPTY_SENTINEL, but tool_name, tool_id, and media_type are gated with truthiness checks (if block.tool_name:), which silently exclude empty strings. This means both None and "" produce identical hash payloads (key absent), defeating the sentinel scheme. Meanwhile, tool_input correctly uses is not None.
Align all fields to is not None:
🛡️ Proposed fix
- if block.tool_name:
- payload["tool_name"] = _normalize_for_hash(block.tool_name)
- if block.tool_id:
- payload["tool_id"] = _normalize_for_hash(block.tool_id)
+ if block.tool_name is not None:
+ payload["tool_name"] = _normalize_for_hash(block.tool_name)
+ if block.tool_id is not None:
+ payload["tool_id"] = _normalize_for_hash(block.tool_id)
if block.tool_input is not None:
payload["tool_input"] = hash_payload(dict(block.tool_input))
- if block.media_type:
- payload["media_type"] = _normalize_for_hash(block.media_type)
+ if block.media_type is not None:
+ payload["media_type"] = _normalize_for_hash(block.media_type)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/pipeline/ids.py` around lines 160 - 174, In _content_block_payload,
the optional fields tool_name, tool_id, and media_type are currently gated by
truthiness and thus drop empty strings instead of preserving sentinel values;
change those conditionals to explicit "is not None" checks and still call
_normalize_for_hash on each (similar to tool_input which already uses "is not
None" and hash_payload), so that None and "" are distinguished in the returned
payload by the sentinel values.
| messages_payload: list[dict[str, JSONValue]] = [] | ||
| for idx, msg in enumerate(convo.messages, start=1): | ||
| message_id = msg.provider_message_id or f"msg-{idx}" | ||
| messages_payload.append( | ||
| { | ||
| "id": message_id, | ||
| "role": str(msg.role), | ||
| "text": _normalize_for_hash(msg.text), | ||
| "timestamp": _normalize_for_hash(msg.timestamp), | ||
| } | ||
| ) | ||
| msg_payload: dict[str, JSONValue] = { | ||
| "id": message_id, | ||
| "role": str(msg.role), | ||
| "text": _normalize_for_hash(msg.text), | ||
| "timestamp": _normalize_for_hash(msg.timestamp), | ||
| } | ||
| if msg.content_blocks: | ||
| msg_payload["content_blocks"] = [_content_block_payload(b) for b in msg.content_blocks] | ||
| messages_payload.append(msg_payload) |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
LGTM — conversation hash inherits the same content-block coverage.
Refactor to msg_payload mirrors the message-level helper exactly, keeping conversation- and message-level hashes structurally consistent. Insertion order of content_blocks is preserved (block ordering is part of identity), and the omit-if-empty guard matches message_content_hash so a single message’s hash component is identical whether computed standalone or as part of the conversation hash.
Minor optional note: this duplicates the per-message payload shape across message_content_hash and conversation_content_hash. If a third call site is ever added, consider extracting a _message_hash_payload(msg, message_id) helper to keep the two definitions in lockstep.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/pipeline/ids.py` around lines 201 - 212, The conversation hash
construction duplicates the per-message payload used by message_content_hash;
fix by extracting the shared per-message payload logic into a single helper
(e.g., _message_hash_payload(msg, message_id)) and have the loop that builds
messages_payload call that helper for each convo.messages, preserving
content_blocks ordering and omitting the key when empty; update references in
conversation_content_hash and message_content_hash to use this helper so both
hashes are structurally identical.
| _SCRIPT_RE = re.compile(r"<script[\s>].*?</script\s*>", re.IGNORECASE | re.DOTALL) | ||
| _EVENT_ATTR_RE = re.compile(r"\s+on\w+\s*=\s*[\"'][^\"']*[\"']", re.IGNORECASE) | ||
| _JAVASCRIPT_URL_RE = re.compile(r"""href\s*=\s*["']javascript:[^"']*["']""", re.IGNORECASE) | ||
|
|
||
|
|
||
| def sanitize_html(html: str) -> Markup: | ||
| """Strip dangerous constructs from pre-rendered HTML. | ||
|
|
||
| Removes ``<script>`` tags, event handler attributes (``onclick``, | ||
| ``onload``, etc.), and ``javascript:`` URLs. Returns a ``Markup`` | ||
| object so Jinja2 autoescaping treats the result as safe HTML. | ||
| """ | ||
| if not html: | ||
| return Markup("") | ||
| sanitized = _SCRIPT_RE.sub("", html) | ||
| sanitized = _EVENT_ATTR_RE.sub("", sanitized) | ||
| sanitized = _JAVASCRIPT_URL_RE.sub("", sanitized) | ||
| return Markup(sanitized) |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
nh3 vs bleach Python HTML sanitizer recommended 2025
💡 Result:
In 2025-2026, nh3 is the recommended Python HTML sanitizer over the deprecated bleach. nh3 is a fast Python binding to the Rust ammonia library, offering 20x better performance, active maintenance (latest release March 2026), and similar API for easy migration. Bleach, deprecated since 2023, receives only security fixes and Python support but lacks new features. nh3 strips disallowed tags entirely (more secure in some views), preserves whitespace better, and adds rel="noopener noreferrer" by default. Key advantages of nh3: - Speed: ~20x faster than bleach on benchmarks. - Maintenance: Actively developed vs. Bleach's limited support. - Security: Strips rather than escapes some elements; customizable allowlists. Migration example (approximate bleach.clean equivalent): import nh3 def clean_html(text): return nh3.clean( text, tags={'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul'}, attributes={'a': {'href', 'title'}, 'abbr': {'title'}, 'acronym': {'title'}}, url_schemes={'http', 'https', 'mailto'}, link_rel=None # Disable if customizing rel ) Bleach still works (last update March 2026, v6.3.0 Oct 2025) but migrate to nh3 for future-proofing. Alternatives like html-sanitizer exist for opinionated cleaning, but nh3 is the direct bleach successor per community discussions.
Citations:
- 1: https://github.com/messense/nh3
- 2: https://www.pydanny.com/posts/2023-06-converting-from-bleach-to-nh3
- 3: bleach is deprecated; statement on project going forward (2023-01-23) mozilla/bleach#698
- 4: https://github.com/mozilla/bleach
- 5: https://nh3.readthedocs.io/
- 6: https://pypi.org/project/nh3/
- 7: https://pypi.org/project/bleach/
🏁 Script executed:
find . -type f -name "html_sanitizer.py" | head -20Repository: Sinity/polylogue
Length of output: 110
🏁 Script executed:
cat -n polylogue/rendering/renderers/html_sanitizer.py 2>/dev/null || echo "File not found at expected path"Repository: Sinity/polylogue
Length of output: 1734
🏁 Script executed:
python3 << 'PYTHON_TEST'
import re
# Test the regexes from the review
_SCRIPT_RE = re.compile(r"<script[\s>].*?</script\s*>", re.IGNORECASE | re.DOTALL)
_EVENT_ATTR_RE = re.compile(r"\s+on\w+\s*=\s*[\"'][^\"']*[\"']", re.IGNORECASE)
_JAVASCRIPT_URL_RE = re.compile(r"""href\s*=\s*["']javascript:[^"']*["']""", re.IGNORECASE)
print("=== Testing _SCRIPT_RE ===")
# Claimed bypass: </script with attributes
test_cases = [
('<script>alert(1)</script>', 'Normal closing'),
('<script>alert(1)</script >', 'Space before >'),
('<script>alert(1)</script foo>', 'Attribute without quotes'),
('<script>alert(1)</script foo="bar">', 'Attribute with quotes'),
('<script>alert(1)</script\tfoo>', 'Tab before attribute'),
]
for test, desc in test_cases:
match = _SCRIPT_RE.search(test)
result = "MATCHED" if match else "NOT MATCHED"
print(f" {desc:30} | {result:12} | Input: {test}")
print("\n=== Testing _EVENT_ATTR_RE ===")
test_cases = [
('<a onclick="alert(1)">', 'Quoted onclick'),
("<a onclick='alert(1)'>", 'Single quoted onclick'),
('<a onclick=alert(1)>', 'Unquoted onclick'),
('<a onclick = alert(1)>', 'Spaces around ='),
]
for test, desc in test_cases:
match = _EVENT_ATTR_RE.search(test)
result = "MATCHED" if match else "NOT MATCHED"
print(f" {desc:30} | {result:12} | Input: {test}")
print("\n=== Testing _JAVASCRIPT_URL_RE ===")
test_cases = [
('<a href="javascript:alert(1)">', 'javascript: in href'),
('<a href=javascript:alert(1)>', 'Unquoted javascript: in href'),
('<iframe src="javascript:alert(1)">', 'javascript: in src (not href)'),
('<form action="javascript:alert(1)">', 'javascript: in action'),
]
for test, desc in test_cases:
match = _JAVASCRIPT_URL_RE.search(test)
result = "MATCHED" if match else "NOT MATCHED"
print(f" {desc:30} | {result:12} | Input: {test}")
PYTHON_TESTRepository: Sinity/polylogue
Length of output: 1266
Regex-based HTML sanitization is bypassable — CodeQL alert #8 is still open and additional XSS sinks are unhandled.
The recent fix tightened the closing-tag regex to </script\s*>, which addresses CodeQL #7 (</script >) but does not address CodeQL #8: HTML5 end tags accept attributes/slashes after the tag name and terminate at >. So <script>alert(1)</script foo="bar"> is closed by the browser at > but _SCRIPT_RE does not match, and the entire block is passed through Markup(...) to the rendered page.
Additional bypass surfaces in the current regexes:
- Unquoted attribute values —
_EVENT_ATTR_RErequires["'], so<a onclick=alert(1)>is not stripped. javascript:only checked onhref—<iframe src="javascript:…">,<form action="javascript:…">,<button formaction=…>,<object data=…>,<embed src=…>,<svg><a xlink:href=…>all bypass. Unquoted forms also bypass.- Other dangerous elements not handled at all —
<iframe>,<iframe srcdoc=…>,<object>,<embed>,<meta http-equiv="refresh" content="0;url=javascript:…">,<link rel="import">,<style>(@import url(javascript:…), IEexpression()), inlinestyle="background:url(javascript:…)".
Markdown→HTML renderers tend not to emit these, but sanitize_html is positioned as defense-in-depth against pre-rendered html_content from arbitrary content blocks — i.e., precisely the case where the input cannot be trusted to be limited to Markdown output. A minimal regex stripper is well-known to be unsafe; the WHATWG/OWASP guidance is to parse-then-allowlist.
Recommendation: replace the regex sanitizer with nh3 (Rust ammonia binding, fast, default-deny, actively maintained as of March 2026) or bleach, configured with an explicit tag/attribute allowlist plus URL-scheme allowlist (http, https, mailto, relative). nh3 is the recommended choice in 2025-2026, offering ~20x better performance and active maintenance compared to the now-deprecated bleach.
🛡️ Suggested replacement using nh3
-import re
-
-from markupsafe import Markup
-
-# Closing tag tolerates whitespace before the final ``>``: ``</script >`` is a
-# legal HTML closing tag and was accepted by the previous regex without being
-# stripped. Match ``</script\s*>`` so end tags with stray whitespace are caught.
-_SCRIPT_RE = re.compile(r"<script[\s>].*?</script\s*>", re.IGNORECASE | re.DOTALL)
-_EVENT_ATTR_RE = re.compile(r"\s+on\w+\s*=\s*[\"'][^\"']*[\"']", re.IGNORECASE)
-_JAVASCRIPT_URL_RE = re.compile(r"""href\s*=\s*["']javascript:[^"']*["']""", re.IGNORECASE)
+import nh3
+from markupsafe import Markup
+
+_ALLOWED_TAGS = {
+ "a", "abbr", "b", "blockquote", "br", "code", "details", "div", "em",
+ "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "img", "li", "ol", "p",
+ "pre", "span", "strong", "summary", "sub", "sup", "table", "tbody",
+ "td", "th", "thead", "tr", "ul",
+}
+_ALLOWED_ATTRS = {
+ "*": {"class", "id"},
+ "a": {"href", "title", "rel"},
+ "img": {"src", "alt", "title", "width", "height"},
+}
+_URL_SCHEMES = {"http", "https", "mailto"}
def sanitize_html(html: str) -> Markup:
- """Strip dangerous constructs from pre-rendered HTML.
-
- Removes ``<script>`` tags, event handler attributes (``onclick``,
- ``onload``, etc.), and ``javascript:`` URLs. Returns a ``Markup``
- object so Jinja2 autoescaping treats the result as safe HTML.
- """
+ """Sanitize pre-rendered HTML with an allowlist parser."""
if not html:
return Markup("")
- sanitized = _SCRIPT_RE.sub("", html)
- sanitized = _EVENT_ATTR_RE.sub("", sanitized)
- sanitized = _JAVASCRIPT_URL_RE.sub("", sanitized)
- return Markup(sanitized)
+ return Markup(
+ nh3.clean(
+ html,
+ tags=_ALLOWED_TAGS,
+ attributes=_ALLOWED_ATTRS,
+ url_schemes=_URL_SCHEMES,
+ link_rel="noopener noreferrer",
+ )
+ )If introducing a new dependency is undesirable for this PR, bleach is already widely used and equivalent for this purpose.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/rendering/renderers/html_sanitizer.py` around lines 18 - 35, The
current regex-based sanitizer (functions/vars: sanitize_html, _SCRIPT_RE,
_EVENT_ATTR_RE, _JAVASCRIPT_URL_RE) is bypassable; replace it with a real HTML
parser-based allowlist sanitizer (use nh3 or bleach) configured with an explicit
tag allowlist, attribute allowlist, and URL-scheme allowlist (e.g., http, https,
mailto, relative) to block javascript: and dangerous elements (iframe, object,
embed, meta refresh, style payloads, unquoted attributes, etc.), then return the
cleaned string wrapped in Markup(sanitized) so Jinja2 treats it as safe; remove
the fragile regexes and ensure tests cover edge cases like `<script
...>...</script foo="bar">`, unquoted onclick, and non-href javascript: URLs.
| # Specific type-level checks first (Codex, Claude Code use Pydantic | ||
| # validation), then weaker dict-key checks (ChatGPT, Claude AI, Gemini). | ||
| if codex.looks_like([dict(record)]): | ||
| return Provider.CODEX | ||
| if claude.looks_like_code([dict(record)]): | ||
| return Provider.CLAUDE_CODE |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Reordering looks correct; minor: drop the unnecessary dict(record) copy.
The new precedence is sound — codex.looks_like and claude.looks_like_code perform schema-level validation (Pydantic / specific key+type markers) and won't false-positive on ChatGPT exports (which use create_time/update_time, not timestamp, and carry mapping) or Claude AI exports (which use uuid/created_at and carry chat_messages), so running them ahead of the weaker dict-key heuristics correctly resolves the spoofing/misclassification issue from #477.
One nit: dict(record) allocates a shallow copy on every call. Neither codex.looks_like nor claude.looks_like_code mutates its input, so wrapping the existing dict directly is sufficient and avoids the per-call copy in this detection hot path.
♻️ Proposed simplification
- # Specific type-level checks first (Codex, Claude Code use Pydantic
- # validation), then weaker dict-key checks (ChatGPT, Claude AI, Gemini).
- if codex.looks_like([dict(record)]):
- return Provider.CODEX
- if claude.looks_like_code([dict(record)]):
- return Provider.CLAUDE_CODE
+ # Specific type-level checks first (Codex, Claude Code use Pydantic
+ # validation), then weaker dict-key checks (ChatGPT, Claude AI, Gemini).
+ single_record_seq: PayloadSequence = [record]
+ if codex.looks_like(single_record_seq):
+ return Provider.CODEX
+ if claude.looks_like_code(single_record_seq):
+ return Provider.CLAUDE_CODE📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| # Specific type-level checks first (Codex, Claude Code use Pydantic | |
| # validation), then weaker dict-key checks (ChatGPT, Claude AI, Gemini). | |
| if codex.looks_like([dict(record)]): | |
| return Provider.CODEX | |
| if claude.looks_like_code([dict(record)]): | |
| return Provider.CLAUDE_CODE | |
| # Specific type-level checks first (Codex, Claude Code use Pydantic | |
| # validation), then weaker dict-key checks (ChatGPT, Claude AI, Gemini). | |
| single_record_seq = [record] | |
| if codex.looks_like(single_record_seq): | |
| return Provider.CODEX | |
| if claude.looks_like_code(single_record_seq): | |
| return Provider.CLAUDE_CODE |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/sources/dispatch.py` around lines 85 - 90, The detection code is
making an unnecessary shallow copy by calling dict(record) before passing it to
codex.looks_like and claude.looks_like_code; remove the dict(...) wrapper and
pass the existing record object directly to codex.looks_like and
claude.looks_like_code (leave the return values Provider.CODEX and
Provider.CLAUDE_CODE unchanged), since neither function mutates its input and
avoiding the copy reduces allocations in this hot path.
| fd, tmp_path = tempfile.mkstemp(dir=self.root, prefix=".blob.") | ||
| with open(source, "rb") as src: | ||
| while True: | ||
| chunk = src.read(_CHUNK_SIZE) | ||
| if not chunk: | ||
| break | ||
| hasher.update(chunk) | ||
| os.write(fd, chunk) | ||
| size += len(chunk) | ||
| if heartbeat is not None: | ||
| heartbeat() | ||
| os.close(fd) | ||
| fd = None | ||
|
|
||
| hash_hex = hasher.hexdigest() | ||
| dest = self.blob_path(hash_hex) | ||
|
|
||
| if dest.exists(): | ||
| os.unlink(tmp_path) | ||
| tmp_path = None | ||
| return hash_hex, size |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Dedup hits now incur a full source-sized write+delete; consider whether that’s acceptable for large blobs.
The TOCTOU fix is correct, but a side effect is that on every call — including ones where the blob already exists — we now copy the entire source into a temp file under self.root, only to os.unlink it after the hash matches an existing blob. For large duplicate files (e.g., re-importing a multi-GB archive), this is a meaningful regression in disk I/O and transient disk-space usage compared to a hash-only-then-skip path. It can also surface as ENOSPC/OSError failures in scenarios that previously succeeded (free space < source size, but blob already present).
This trade-off is fundamental to closing the TOCTOU window, so it’s likely acceptable, but it’s worth:
- Documenting the new behavior in the docstring (currently lines 59–60 still imply the write is "skipped" — strictly speaking only the install step is skipped now).
- Considering whether a fast pre-check (e.g.,
os.statsize + a small content sniff) is worth adding for the common case of re-importing the same artifact, with the single-pass path as the fallback.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/blob_store.py` around lines 75 - 95, Update the method's
docstring to reflect the new TOCTOU-safe behavior: clarify that the
implementation now always writes the source into a temporary file under
self.root and only skips the final install/move when the hash already exists
(i.e., the write is not truly skipped). Also consider adding an optional fast
pre-check before creating the temp file inside the same method: perform
os.stat(source).st_size vs any existing blob size from self.blob_path(hash) and
a small content sniff (e.g., open source and compare the first few KB) to avoid
full-source writes for common duplicate cases, falling back to the current
full-write-then-check flow if the pre-check is inconclusive; reference the
functions/variables: self.blob_path, self.root, heartbeat, hasher, tmp_path to
locate and modify the implementation and docstring.
| def test_sanitize_preserves_safe_markup() -> None: | ||
| safe = "<p>hello <strong>world</strong></p>" | ||
| assert str(sanitize_html(safe)) == safe |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Brittle exact-equality assertion — fine for now, flag if sanitizer ever normalizes.
If a future implementation swaps the regex stripper for bleach/html5lib, attribute-quoting or whitespace normalization may make this assertion fail even though output is still semantically safe. Consider asserting a structural property (e.g. the substrings <strong>world</strong> and hello are present) so the test survives an internal-implementation switch.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/unit/rendering/test_html_sanitizer.py` around lines 45 - 47, The test
test_sanitize_preserves_safe_markup is brittle because it asserts exact string
equality of sanitize_html(safe); update it to check structural properties
instead: call sanitize_html(safe) (or str(sanitize_html(safe))) and assert that
the expected substrings like "hello" and "<strong>world</strong>" (or the tag
"strong" containing "world") are present, rather than comparing the entire
output exactly, so the test still passes if sanitizer normalizes
quotes/whitespace or uses html5lib/bleach.
…ath components (#524) ## Summary Closes #480. Three of the five sub-issues in #480 (blob file permissions, db file permissions, site manifest absolute-path leak) were already resolved on master by the audit-fix wave that landed via #504. This PR addresses the two real outstanding items. ## Problem ### DNS rebinding on webhook delivery `polylogue/pipeline/observers.py:_validate_webhook_url` resolved the hostname against the SSRF denylist, but `_post_webhook` handed the *hostname* back to `http.client.HTTPSConnection`, which re-resolves at connect time. An attacker controlling a short-TTL DNS record could resolve to a public address during validation and to `127.0.0.1` (or any private RFC-1918 address) during the actual connection. Validation runs in microseconds; connection establishment is far slower; the rebinding window is real. ### Unicode confusable bypass in path sanitization `polylogue/paths/sanitize.py:safe_path_component` ran an ASCII-only allowlist regex but never normalized the input. `café` written as NFC (`é` U+00E9) and `café` written as NFD (`e` + U+0301) hashed to different prefixes, so two visually-identical inputs landed at two different filesystem paths. ## Solution ### IP-pinned webhook delivery - `_resolve_and_validate` returns the validated IP from the same `getaddrinfo` call that runs the SSRF check. - `_webhook_request_target` returns `(scheme, hostname, validated_ip, port, path)` — the caller now has both hostname (for SNI/cert verification) and IP (for the actual socket). - `_PinnedHTTPSConnection` subclasses `http.client.HTTPSConnection` and overrides `connect()` to `socket.create_connection` against the validated IP, then wraps with TLS using `server_hostname=hostname` so cert verification still binds to the original hostname. - HTTP path connects to the validated IP and sets the `Host` header back to the original hostname (otherwise virtual-hosted servers fail to route). ### NFC normalization for path components `safe_path_component` calls `unicodedata.normalize("NFC", ...)` before the allowlist regex runs. The ASCII allowlist still flattens everything else to `prefix-digest`; normalization just stabilizes the digest across decomposed forms. ## Verification ``` $ nix develop -c devtools verify --quick verify: all checks passed $ nix develop -c pytest -q tests/unit/pipeline/test_observers_runtime.py tests/unit/core/test_paths.py tests/unit/security/ 136 passed in 10.49s $ nix develop -c pytest -q tests/ --ignore=tests/integration 5595 passed, 10 xfailed in 176.75s ``` New tests: - `test_unicode_nfc_normalization_collapses_confusables` — `safe_path_component(NFC) == safe_path_component(NFD)` for `café`. - `test_webhook_request_target_and_post_webhook_cover_http_https_and_hostname_errors` updated for the new 5-tuple shape and to assert the HTTP path restores the `Host` header on the IP-pinned connection. ## Already resolved (no change needed) | #480 sub-item | Status on master | | --- | --- | | `storage/blob_store.py` blob file permissions | Already `os.chmod(0o600)` at line 98 + line 149 | | `storage/backends/connection.py` db permissions | Already `os.chmod(0o600)` at line 92 | | `site/publication_flow.py` manifest path leak | Already serializes `output_dir="."` (line 215), not the absolute path | The token-store note (configurable Drive credential path) is documentation of existing behavior, not a defect — token files themselves are written `0o600` (`token_store.py:73`). Co-authored-by: Claude <[email protected]>
…evel, dedup XDG state (#525) ## Summary Closes #481. Four of the six items in #481 were already resolved on master in earlier audit-fix waves (likely #504 and predecessors). This PR addresses the two real outstanding defects plus tightens \`Config\` construction. ## Problem | Sub-item | Status | | --- | --- | | \`name\` not in content field denylist | Already fixed (\`schemas/privacy.py:97\` includes \`name\`, \`body\`, \`message\`, \`input\`, \`output\`) | | \`max_length=0\` treated as falsy | Already fixed (\`schemas/privacy.py:220\`: \`max_length if max_length is not None else _SAFE_ENUM_MAX_LEN\`) | | \`POLYLOGUE_FORCE_PLAIN\` color suppression | Already fixed (\`logging.py:151\`: \`colors=sys.stderr.isatty() and not force_plain\`) | | \`privacy_config.py\` XDG path duplication | Already fixed (uses \`config_root()\` from \`polylogue.paths\`) | | \`helper_source_state.py\` XDG path duplication | **Outstanding** — duplicates the \`XDG_STATE_HOME\` fallback inline; if \`_roots.py\` changes, it diverges silently | | \`Config\` accepts invalid paths; \`PrivacyConfig\` swallows invalid level | **Outstanding** — relative paths and typo'd levels both succeed silently | ## Solution ### XDG state path duplication \`polylogue/cli/helper_source_state.py:source_state_path\` reimplemented the \`XDG_STATE_HOME\` fallback inline. Replace with \`state_home()\` from \`polylogue.paths\` so the fallback stays single-source. ### Silent fallback on invalid privacy level \`_privacy_level_value\` returned \`"standard"\` for any unrecognized input — a typo in TOML or a CLI flag silently mapped to "standard". Raise \`ValueError\` on unknown levels; preserve the explicit \`None → "standard"\` default. ### \`Config\` path validation \`Config\` dataclass had no post-init validation. Relative paths silently shift meaning across processes (CLI from \`\$PWD\` vs MCP server vs systemd unit) — different archive locations for the same nominal \`Config(...)\`. Add \`__post_init__\` requiring \`archive_root\`, \`render_root\`, and \`db_path\` to be absolute \`Path\`s; raise \`ConfigError\` otherwise. ## Verification \`\`\` $ nix develop -c devtools verify --quick verify: all checks passed $ nix develop -c pytest -q tests/unit/core/test_config.py tests/unit/core/test_privacy_config.py 58 passed in 8.72s $ nix develop -c pytest -q tests/ --ignore=tests/integration 5595 passed, 10 xfailed \`\`\` New tests: - \`test_privacy_level_value_rejects_unknown_level\` + positive cases for known levels including \`None\`. - \`test_config_rejects_relative_{archive_root,render_root,db_path}\`. Co-authored-by: Claude <[email protected]>
… site (#504) ## Summary Six fixes from the adversarial audit that remained after #489, plus a CodeQL-flagged refinement of the new HTML sanitizer. ## Problem The audit pass after #489 surfaced six concrete bugs across hashing, storage durability, lifecycle hygiene, parser ordering, site rendering, and template safety: - **Content-block coverage in content hash (#466)**: tool-use / tool-result / thinking blocks were excluded from `message_content_hash()` and `conversation_content_hash()`, producing silent identity collisions on re-import for any conversation that has structured content blocks. - **BlobStore TOCTOU race (#470)**: `write_from_path()` read the source file twice (once to hash, once to copy). Source mutations between the two reads landed inconsistent (hash, content) pairs in the blob store. - **Connection cache leak on exit (#473)**: cached SQLite connections were not closed on process exit; ResourceWarnings and occasional WAL leftovers in tests. - **Provider detection ordering (#477)**: `codex.looks_like` and `claude.looks_like_code` ran *after* the weaker dict-key heuristics, so codex/claude-code records that also matched a generic shape were misclassified. - **Template XSS surface (#468)**: conversation templates used `{{ msg.html_content | safe }}`; any pre-rendered HTML reached the page unfiltered. Defense-in-depth in the template layer was missing. - **Site dropping content_block-only messages (#475)**: the per-message render guard was `if not msg.text`, so messages whose payload lives entirely in content_blocks (e.g. tool_use without summary text) silently disappeared from generated sites. After the original PR opened, CodeQL further flagged the new sanitizer's `</script>` literal as not matching `</script >` (whitespace before `>`), which browsers accept — a regex bypass. ## Solution One commit per concern, plus the sanitizer regression follow-up: - `pipeline/ids.py` — added `_content_block_payload()`; `message_content_hash()` and `conversation_content_hash()` now include normalized content blocks. Closes #466. - `storage/blob_store.py` — rewrote `write_from_path()` to hash and write to a temp file in a single pass, then rename atomically. Closes #470. - `storage/backends/connection.py` — registered `atexit` handler closing every cached connection. Closes #473. - `sources/dispatch.py` — moved `codex.looks_like` and `claude.looks_like_code` ahead of the dict-key shape checks. Closes #477. - `rendering/renderers/html_sanitizer.py` (new) + `html_template.py` + `templates/conversation.html` + `site/templates_conversation.py` + `site/template_environment.py` + `site/search.py` — Jinja2 `sanitize_html` filter strips `<script>` tags, `on*` event handlers, and `javascript:` URLs. All conversation templates use `| sanitize_html` instead of `| safe`. Client-side search escapes user data before `innerHTML`. Closes #468. - `site/conversation_pages.py` — render guard now respects `msg.content_blocks` (renders when text *or* blocks are present). Closes #475. - `rendering/renderers/html_sanitizer.py` (sanitizer fix-up commit) — closing-tag regex now accepts `</script\s*>` rather than only `</script>`. New `tests/unit/rendering/test_html_sanitizer.py` covers whitespace-before-`>`, mixed case, attributed opening tags, multiline bodies, event handlers, javascript URLs, safe markup, and empty input. ## Verification ``` devtools verify ruff format / check ... ok mypy ... ok (642 source files) render-all ... ok verify-topology / -file-budgets / -test-ownership / -migrations / -cross-cuts ... ok pytest -q --ignore=tests/integration ... 5751 passed (incl. new sanitizer tests) verify: all checks passed ``` CodeQL annotation on the sanitizer regex is addressed by the second commit (closing-tag whitespace tolerance + regression suite). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Release Notes * **Security Enhancements** * HTML content is now sanitized to prevent script injection attacks * Search results are escaped to protect against malicious content injection * **New Features** * Enhanced message rendering with improved content support * **Performance & Stability** * Optimized blob storage operations for faster writes * Improved database connection cleanup on exit * Provider detection refinements <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
…ath components (#524) ## Summary Closes #480. Three of the five sub-issues in #480 (blob file permissions, db file permissions, site manifest absolute-path leak) were already resolved on master by the audit-fix wave that landed via #504. This PR addresses the two real outstanding items. ## Problem ### DNS rebinding on webhook delivery `polylogue/pipeline/observers.py:_validate_webhook_url` resolved the hostname against the SSRF denylist, but `_post_webhook` handed the *hostname* back to `http.client.HTTPSConnection`, which re-resolves at connect time. An attacker controlling a short-TTL DNS record could resolve to a public address during validation and to `127.0.0.1` (or any private RFC-1918 address) during the actual connection. Validation runs in microseconds; connection establishment is far slower; the rebinding window is real. ### Unicode confusable bypass in path sanitization `polylogue/paths/sanitize.py:safe_path_component` ran an ASCII-only allowlist regex but never normalized the input. `café` written as NFC (`é` U+00E9) and `café` written as NFD (`e` + U+0301) hashed to different prefixes, so two visually-identical inputs landed at two different filesystem paths. ## Solution ### IP-pinned webhook delivery - `_resolve_and_validate` returns the validated IP from the same `getaddrinfo` call that runs the SSRF check. - `_webhook_request_target` returns `(scheme, hostname, validated_ip, port, path)` — the caller now has both hostname (for SNI/cert verification) and IP (for the actual socket). - `_PinnedHTTPSConnection` subclasses `http.client.HTTPSConnection` and overrides `connect()` to `socket.create_connection` against the validated IP, then wraps with TLS using `server_hostname=hostname` so cert verification still binds to the original hostname. - HTTP path connects to the validated IP and sets the `Host` header back to the original hostname (otherwise virtual-hosted servers fail to route). ### NFC normalization for path components `safe_path_component` calls `unicodedata.normalize("NFC", ...)` before the allowlist regex runs. The ASCII allowlist still flattens everything else to `prefix-digest`; normalization just stabilizes the digest across decomposed forms. ## Verification ``` $ nix develop -c devtools verify --quick verify: all checks passed $ nix develop -c pytest -q tests/unit/pipeline/test_observers_runtime.py tests/unit/core/test_paths.py tests/unit/security/ 136 passed in 10.49s $ nix develop -c pytest -q tests/ --ignore=tests/integration 5595 passed, 10 xfailed in 176.75s ``` New tests: - `test_unicode_nfc_normalization_collapses_confusables` — `safe_path_component(NFC) == safe_path_component(NFD)` for `café`. - `test_webhook_request_target_and_post_webhook_cover_http_https_and_hostname_errors` updated for the new 5-tuple shape and to assert the HTTP path restores the `Host` header on the IP-pinned connection. ## Already resolved (no change needed) | #480 sub-item | Status on master | | --- | --- | | `storage/blob_store.py` blob file permissions | Already `os.chmod(0o600)` at line 98 + line 149 | | `storage/backends/connection.py` db permissions | Already `os.chmod(0o600)` at line 92 | | `site/publication_flow.py` manifest path leak | Already serializes `output_dir="."` (line 215), not the absolute path | The token-store note (configurable Drive credential path) is documentation of existing behavior, not a defect — token files themselves are written `0o600` (`token_store.py:73`). Co-authored-by: Claude <[email protected]>
…evel, dedup XDG state (#525) ## Summary Closes #481. Four of the six items in #481 were already resolved on master in earlier audit-fix waves (likely #504 and predecessors). This PR addresses the two real outstanding defects plus tightens \`Config\` construction. ## Problem | Sub-item | Status | | --- | --- | | \`name\` not in content field denylist | Already fixed (\`schemas/privacy.py:97\` includes \`name\`, \`body\`, \`message\`, \`input\`, \`output\`) | | \`max_length=0\` treated as falsy | Already fixed (\`schemas/privacy.py:220\`: \`max_length if max_length is not None else _SAFE_ENUM_MAX_LEN\`) | | \`POLYLOGUE_FORCE_PLAIN\` color suppression | Already fixed (\`logging.py:151\`: \`colors=sys.stderr.isatty() and not force_plain\`) | | \`privacy_config.py\` XDG path duplication | Already fixed (uses \`config_root()\` from \`polylogue.paths\`) | | \`helper_source_state.py\` XDG path duplication | **Outstanding** — duplicates the \`XDG_STATE_HOME\` fallback inline; if \`_roots.py\` changes, it diverges silently | | \`Config\` accepts invalid paths; \`PrivacyConfig\` swallows invalid level | **Outstanding** — relative paths and typo'd levels both succeed silently | ## Solution ### XDG state path duplication \`polylogue/cli/helper_source_state.py:source_state_path\` reimplemented the \`XDG_STATE_HOME\` fallback inline. Replace with \`state_home()\` from \`polylogue.paths\` so the fallback stays single-source. ### Silent fallback on invalid privacy level \`_privacy_level_value\` returned \`"standard"\` for any unrecognized input — a typo in TOML or a CLI flag silently mapped to "standard". Raise \`ValueError\` on unknown levels; preserve the explicit \`None → "standard"\` default. ### \`Config\` path validation \`Config\` dataclass had no post-init validation. Relative paths silently shift meaning across processes (CLI from \`\$PWD\` vs MCP server vs systemd unit) — different archive locations for the same nominal \`Config(...)\`. Add \`__post_init__\` requiring \`archive_root\`, \`render_root\`, and \`db_path\` to be absolute \`Path\`s; raise \`ConfigError\` otherwise. ## Verification \`\`\` $ nix develop -c devtools verify --quick verify: all checks passed $ nix develop -c pytest -q tests/unit/core/test_config.py tests/unit/core/test_privacy_config.py 58 passed in 8.72s $ nix develop -c pytest -q tests/ --ignore=tests/integration 5595 passed, 10 xfailed \`\`\` New tests: - \`test_privacy_level_value_rejects_unknown_level\` + positive cases for known levels including \`None\`. - \`test_config_rejects_relative_{archive_root,render_root,db_path}\`. Co-authored-by: Claude <[email protected]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Six fixes from the adversarial audit that remained after #489, plus a CodeQL-flagged refinement of the new HTML sanitizer.
Problem
The audit pass after #489 surfaced six concrete bugs across hashing, storage durability, lifecycle hygiene, parser ordering, site rendering, and template safety:
message_content_hash()andconversation_content_hash(), producing silent identity collisions on re-import for any conversation that has structured content blocks.write_from_path()read the source file twice (once to hash, once to copy). Source mutations between the two reads landed inconsistent (hash, content) pairs in the blob store.codex.looks_likeandclaude.looks_like_coderan after the weaker dict-key heuristics, so codex/claude-code records that also matched a generic shape were misclassified.{{ msg.html_content | safe }}; any pre-rendered HTML reached the page unfiltered. Defense-in-depth in the template layer was missing.if not msg.text, so messages whose payload lives entirely in content_blocks (e.g. tool_use without summary text) silently disappeared from generated sites.After the original PR opened, CodeQL further flagged the new sanitizer's
</script>literal as not matching</script >(whitespace before>), which browsers accept — a regex bypass.Solution
One commit per concern, plus the sanitizer regression follow-up:
pipeline/ids.py— added_content_block_payload();message_content_hash()andconversation_content_hash()now include normalized content blocks. Closes fix(ids): include content blocks in content hash #466.storage/blob_store.py— rewrotewrite_from_path()to hash and write to a temp file in a single pass, then rename atomically. Closes fix(storage): BlobStore TOCTOU — source file read twice, content can change #470.storage/backends/connection.py— registeredatexithandler closing every cached connection. Closes fix(storage): connection leaks, readiness DB path, unbounded queries #473.sources/dispatch.py— movedcodex.looks_likeandclaude.looks_like_codeahead of the dict-key shape checks. Closes fix(parsers): provider detection ordering + broad exception catches #477.rendering/renderers/html_sanitizer.py(new) +html_template.py+templates/conversation.html+site/templates_conversation.py+site/template_environment.py+site/search.py— Jinja2sanitize_htmlfilter strips<script>tags,on*event handlers, andjavascript:URLs. All conversation templates use| sanitize_htmlinstead of| safe. Client-side search escapes user data beforeinnerHTML. Closes fix(site): XSS vectors in generated static site #468.site/conversation_pages.py— render guard now respectsmsg.content_blocks(renders when text or blocks are present). Closes fix(site): drop content_block messages, drop branches, CSV injection, heading escape #475.rendering/renderers/html_sanitizer.py(sanitizer fix-up commit) — closing-tag regex now accepts</script\s*>rather than only</script>. Newtests/unit/rendering/test_html_sanitizer.pycovers whitespace-before->, mixed case, attributed opening tags, multiline bodies, event handlers, javascript URLs, safe markup, and empty input.Verification
CodeQL annotation on the sanitizer regex is addressed by the second commit (closing-tag whitespace tolerance + regression suite).
Summary by CodeRabbit
Release Notes
Security Enhancements
New Features
Performance & Stability