Skip to content

Free, open source blog writer for Claude Code. Researches current sources, writes answer-first posts for Google and AI answers, has an independent reviewer score each one out of 100 and ships only after five delivery gates. 32 skills, 30 /blog commands, 5 agents. Active development at AI-Marketing-Hub/claude-blog; public releases ship here.

fix(security): nonce-bound review.md provenance (VULN-803)

Daniel2422526e241d
diff --git a/agents/blog-reviewer.md b/agents/blog-reviewer.md
index d2d3887..580c0e8 100644
--- a/agents/blog-reviewer.md
+++ b/agents/blog-reviewer.md
@@ -176,9 +176,18 @@ When reviewing citations, verify against this tier system:
2. [Second priority]
3. [Third priority]
+Nonce: [paste the 32-hex value from <draft>/.review-nonce here verbatim]
BLOCKING: true|false (one-line reason)
```
+## Nonce-bound provenance (v1.9.1)
+
+Before dispatching this agent, the orchestrator runs `blog_preflight.py --init-review-nonce --draft <dir>` which writes a fresh CSPRNG nonce to `<draft>/.review-nonce`. The agent MUST include a `Nonce: <32-hex>` line in `review.md` that matches the file. Gate 4 reads `.review-nonce` and verifies the match; mismatch or absence rejects the review.
+
+This binds `review.md` to the agent invocation. Without it, any process with write access to the draft folder could satisfy Gate 4 by hand-writing `BLOCKING: false`.
+
+To find the nonce, the agent must read `<draft>/.review-nonce` (the orchestrator passes the draft folder as part of the agent prompt) and emit the value verbatim, lowercase, in the `Nonce:` line of the scorecard.
+
## Blocking Decision (v1.9.0)
The scorecard MUST end with a `BLOCKING: true|false (reason)` line. This line is machine-readable by `scripts/blog_preflight.py` Gate 4 and drives the iteration loop in the orchestrator.
diff --git a/scripts/blog_preflight.py b/scripts/blog_preflight.py
index 61de724..b88b0ce 100644
--- a/scripts/blog_preflight.py
+++ b/scripts/blog_preflight.py
@@ -60,6 +60,42 @@ ITERATION_COUNTER_FILE = ".iteration-count"
MAX_ITERATIONS = 3
EXIT_ITERATION_CAP = 2
+# VULN-803 nonce-bound review.md provenance (v1.9.1).
+# Before v1.9.1, Gate 4 trusted any writer of <draft>/review.md. A malicious
+# sub-skill or prompt-injected sibling agent could satisfy the gate by
+# writing one line. v1.9.1 binds the review to a CSPRNG nonce written by
+# the orchestrator before agent dispatch; the agent must echo the nonce
+# back in review.md. Backwards-compat: drafts initialised before v1.9.1
+# (no nonce file) pass with a deprecation warning until v1.10.0.
+REVIEW_NONCE_FILE = ".review-nonce"
+NONCE_PATTERN = re.compile(r"^Nonce:\s*([0-9a-f]{32})\s*$", re.MULTILINE | re.IGNORECASE)
+
+
+def _init_review_nonce(draft: Path) -> str:
+ """Generate a CSPRNG nonce and write it to <draft>/.review-nonce.
+
+ Returns the nonce hex string. Overwrites any prior nonce so each
+ review attempt has fresh provenance.
+ """
+ import secrets
+ nonce = secrets.token_hex(16)
+ nonce_path = draft / REVIEW_NONCE_FILE
+ import tempfile
+ fd, tmp = tempfile.mkstemp(
+ dir=str(nonce_path.parent), prefix=f".{nonce_path.name}.", suffix=".tmp"
+ )
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ f.write(f"{nonce}\n")
+ os.replace(tmp, str(nonce_path))
+ except Exception:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ raise
+ return nonce
+
def _iteration_check(draft: Path, reset: bool = False) -> int:
"""Read/increment the per-draft iteration counter; refuse past cap.
@@ -526,8 +562,17 @@ def gate_5_asset_link_integrity(draft_dir: Path) -> dict:
def gate_4_content_review(draft_dir: Path) -> dict:
"""Check that the blog-reviewer agent has run and emitted review.md
- with `BLOCKING: false`. The agent itself is dispatched by the
- orchestrator, not by this script."""
+ with `BLOCKING: false` AND a matching Nonce (v1.9.1).
+
+ Nonce-bound provenance (VULN-803, v1.9.1):
+ * If <draft>/.review-nonce exists, review.md MUST contain a line
+ `Nonce: <matching-32-hex>` (case-insensitive, anchored to line).
+ Missing or mismatched -> gate fails with explicit violation.
+ * If <draft>/.review-nonce is absent, the gate emits a deprecation
+ warning and falls back to v1.9.0 behavior (BLOCKING line only).
+ This preserves backwards compatibility for drafts created before
+ v1.9.1. v1.10.0 will make the nonce mandatory.
+ """
review = draft_dir / "review.md"
if not review.is_file():
return _gate_result(
@@ -535,17 +580,71 @@ def gate_4_content_review(draft_dir: Path) -> dict:
["review.md absent; orchestrator must dispatch blog-reviewer agent before preflight Gate 4"],
)
text = review.read_text(encoding="utf-8")
+
+ # Nonce check (v1.9.1)
+ nonce_warnings: list[str] = []
+ nonce_path = draft_dir / REVIEW_NONCE_FILE
+ if nonce_path.is_file():
+ try:
+ expected_nonce = nonce_path.read_text(encoding="utf-8").strip().lower()
+ except OSError as e:
+ return _gate_result(
+ 4, "Content Review", False,
+ [f"failed to read {REVIEW_NONCE_FILE}: {e}"],
+ )
+ if not re.fullmatch(r"[0-9a-f]{32}", expected_nonce):
+ return _gate_result(
+ 4, "Content Review", False,
+ [f"{REVIEW_NONCE_FILE} contents are not a 32-hex nonce"],
+ )
+ nonce_match = NONCE_PATTERN.search(text)
+ if not nonce_match:
+ return _gate_result(
+ 4, "Content Review", False,
+ [
+ "review.md is missing the `Nonce: <hex>` line required for v1.9.1+ "
+ "provenance. The orchestrator must include the nonce from "
+ f"{REVIEW_NONCE_FILE} in the blog-reviewer agent's output."
+ ],
+ )
+ actual_nonce = nonce_match.group(1).lower()
+ if actual_nonce != expected_nonce:
+ return _gate_result(
+ 4, "Content Review", False,
+ [
+ "review.md Nonce does not match "
+ f"{REVIEW_NONCE_FILE}; provenance check failed (potential "
+ "review.md forgery)."
+ ],
+ )
+ else:
+ nonce_warnings.append(
+ f"{REVIEW_NONCE_FILE} not found; falling back to v1.9.0 BLOCKING-only "
+ "gate (deprecation: v1.10.0 will make the nonce mandatory). Run "
+ "`blog_preflight.py --init-review-nonce --draft <dir>` before dispatching "
+ "the blog-reviewer agent."
+ )
+
m = re.search(r"^BLOCKING:\s*(true|false)\s*(?:\((.*?)\))?\s*$", text, re.IGNORECASE | re.MULTILINE)
if not m:
return _gate_result(
4, "Content Review", False,
["review.md present but no `BLOCKING: true|false` line found at end of scorecard"],
+ nonce_warnings,
)
blocking = m.group(1).lower() == "true"
reason = (m.group(2) or "").strip()
if blocking:
- return _gate_result(4, "Content Review", False, [f"reviewer blocked: {reason or 'see review.md'}"], [], blocking=True, reason=reason)
- return _gate_result(4, "Content Review", True, [], [], blocking=False, reason=reason)
+ return _gate_result(
+ 4, "Content Review", False,
+ [f"reviewer blocked: {reason or 'see review.md'}"],
+ nonce_warnings,
+ blocking=True, reason=reason,
+ )
+ return _gate_result(
+ 4, "Content Review", True, [], nonce_warnings,
+ blocking=False, reason=reason,
+ )
def main() -> int:
@@ -560,6 +659,16 @@ def main() -> int:
action="store_true",
help="Reset the per-draft iteration counter to 1 (this run counts as the first).",
)
+ parser.add_argument(
+ "--init-review-nonce",
+ action="store_true",
+ help=(
+ "Generate a fresh CSPRNG nonce and write it to <draft>/.review-nonce, "
+ "then exit. The orchestrator runs this before dispatching the "
+ "blog-reviewer agent; Gate 4 verifies the agent's review.md contains "
+ "the matching nonce (VULN-803, v1.9.1)."
+ ),
+ )
args = parser.parse_args()
draft = Path(args.draft).resolve()
@@ -567,6 +676,11 @@ def main() -> int:
print(f"ERROR: {draft} is not a directory", file=sys.stderr)
return 1
+ if args.init_review_nonce:
+ nonce = _init_review_nonce(draft)
+ print(nonce)
+ return 0
+
# VULN-802 (v1.9.1): code-enforced iteration cap. Refuse past MAX_ITERATIONS.
iteration_exit = _iteration_check(draft, reset=args.reset_iterations)
if iteration_exit != 0:
diff --git a/tests/test_review_nonce.py b/tests/test_review_nonce.py
new file mode 100644
index 0000000..33b5070
--- /dev/null
+++ b/tests/test_review_nonce.py
@@ -0,0 +1,138 @@
+"""Nonce-bound review.md provenance tests (VULN-803, v1.9.1).
+
+Gate 4 v1.9.0 trusted any writer of <draft>/review.md. The 5-gate
+contract collapsed to '4 gates + 1 filesystem write the orchestrator
+trusts.' v1.9.1 adds nonce-bound provenance:
+
+ 1. Before dispatching the blog-reviewer agent, the orchestrator runs
+ `blog_preflight.py --init-review-nonce --draft <dir>` which writes
+ a CSPRNG nonce to <draft>/.review-nonce.
+ 2. The agent's prompt template includes the nonce; the agent emits
+ `Nonce: <NONCE>` somewhere in review.md.
+ 3. Gate 4 reads .review-nonce, then verifies review.md contains
+ `Nonce: <matching value>`. Missing or mismatched -> gate fails.
+
+Backwards compat for v1.9.x: if .review-nonce is absent, Gate 4 emits
+a deprecation warning but does not block. v1.10.0 will make the nonce
+mandatory.
+"""
+from __future__ import annotations
+
+import importlib.util
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+PREFLIGHT = ROOT / "scripts" / "blog_preflight.py"
+
+
+def preflight_module(monkeypatch):
+ spec = importlib.util.spec_from_file_location("blog_preflight", PREFLIGHT)
+ mod = importlib.util.module_from_spec(spec)
+ sys.modules["blog_preflight_test_mod"] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _make_draft(tmp_path: Path, review_text: str = "", nonce_text: str | None = None) -> Path:
+ draft = tmp_path / "post"
+ draft.mkdir()
+ if review_text:
+ (draft / "review.md").write_text(review_text, encoding="utf-8")
+ if nonce_text is not None:
+ (draft / ".review-nonce").write_text(nonce_text, encoding="utf-8")
+ return draft
+
+
+def test_init_review_nonce_creates_file_with_csprng_value(tmp_path, preflight_module):
+ draft = tmp_path / "post"
+ draft.mkdir()
+ preflight_module._init_review_nonce(draft)
+ nonce_file = draft / ".review-nonce"
+ assert nonce_file.exists()
+ nonce_value = nonce_file.read_text(encoding="utf-8").strip()
+ # 32 hex chars (16 bytes via secrets.token_hex(16))
+ assert re.fullmatch(r"[0-9a-f]{32}", nonce_value), (
+ f"nonce must be 32 hex chars, got {nonce_value!r}"
+ )
+
+
+def test_init_review_nonce_overwrites_existing(tmp_path, preflight_module):
+ draft = tmp_path / "post"
+ draft.mkdir()
+ (draft / ".review-nonce").write_text("OLDNONCE", encoding="utf-8")
+ preflight_module._init_review_nonce(draft)
+ assert (draft / ".review-nonce").read_text(encoding="utf-8").strip() != "OLDNONCE"
+
+
+def test_gate_4_passes_when_nonce_matches(tmp_path, preflight_module):
+ nonce = "a" * 32
+ review = f"Scorecard...\nNonce: {nonce}\nBLOCKING: false (cleared)\n"
+ draft = _make_draft(tmp_path, review_text=review, nonce_text=nonce)
+ result = preflight_module.gate_4_content_review(draft)
+ assert result["passed"] is True, f"Gate should pass with matching nonce: {result}"
+
+
+def test_gate_4_fails_when_nonce_file_present_but_review_lacks_nonce(tmp_path, preflight_module):
+ nonce = "b" * 32
+ review = "Scorecard...\nBLOCKING: false (cleared)\n" # no Nonce: line
+ draft = _make_draft(tmp_path, review_text=review, nonce_text=nonce)
+ result = preflight_module.gate_4_content_review(draft)
+ assert result["passed"] is False, "Gate should fail when nonce file exists but review lacks Nonce: line"
+ assert any("nonce" in v.lower() for v in result.get("violations", []))
+
+
+def test_gate_4_fails_when_review_has_wrong_nonce(tmp_path, preflight_module):
+ real_nonce = "c" * 32
+ fake_nonce = "d" * 32
+ review = f"Scorecard...\nNonce: {fake_nonce}\nBLOCKING: false (cleared)\n"
+ draft = _make_draft(tmp_path, review_text=review, nonce_text=real_nonce)
+ result = preflight_module.gate_4_content_review(draft)
+ assert result["passed"] is False, "Gate should fail on nonce mismatch"
+ assert any("nonce" in v.lower() for v in result.get("violations", []))
+
+
+def test_gate_4_soft_pass_when_nonce_file_absent_backwards_compat(tmp_path, preflight_module):
+ """v1.9.x backwards compat: drafts initialised before v1.9.1 (no nonce file)
+ pass with a deprecation warning, do not block."""
+ review = "Scorecard...\nBLOCKING: false (cleared)\n"
+ draft = _make_draft(tmp_path, review_text=review) # no nonce file
+ assert not (draft / ".review-nonce").exists()
+ result = preflight_module.gate_4_content_review(draft)
+ assert result["passed"] is True, "Backwards-compat path must not block on missing nonce file"
+ assert any("nonce" in w.lower() for w in result.get("warnings", [])), (
+ "Must emit deprecation warning when nonce file is absent"
+ )
+
+
+def test_gate_4_nonce_must_be_exact_match_no_suffix_attack(tmp_path, preflight_module):
+ """Nonce match must be word-bounded; substring match shouldn't fool the gate."""
+ nonce = "e" * 32
+ # Attacker emits a different 32-char string that contains the real nonce as
+ # a prefix or suffix in raw text.
+ leaked = nonce + "f" * 4 # 36 chars, starts with the real nonce
+ review = f"Some text containing the leaked nonce.\nNonce: {leaked}\nBLOCKING: false\n"
+ draft = _make_draft(tmp_path, review_text=review, nonce_text=nonce)
+ result = preflight_module.gate_4_content_review(draft)
+ assert result["passed"] is False, "Suffix attack on nonce match must be refused"
+
+
+def test_init_review_nonce_cli_flag(tmp_path):
+ """`blog_preflight.py --init-review-nonce --draft <dir>` exits 0 and writes the file."""
+ draft = tmp_path / "post"
+ draft.mkdir()
+ result = subprocess.run(
+ [sys.executable, str(PREFLIGHT), "--init-review-nonce", "--draft", str(draft)],
+ capture_output=True, text=True, cwd=str(ROOT),
+ )
+ assert result.returncode == 0, (
+ f"--init-review-nonce should exit 0; stdout={result.stdout!r} stderr={result.stderr!r}"
+ )
+ assert (draft / ".review-nonce").exists()
+ value = (draft / ".review-nonce").read_text(encoding="utf-8").strip()
+ assert re.fullmatch(r"[0-9a-f]{32}", value)