From fb4e4e4e75d27d68c7e050015c46e063fabfd0b7 Mon Sep 17 00:00:00 2001 From: GodSpeed313 Date: Thu, 16 Jul 2026 13:38:22 -0400 Subject: [PATCH] M7: LinkRestriction constraint + link-provenance pre-send gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spec-first ruling docs/m7_link_restriction_ruling.md (LOCKED), then the implementation, following the CredentialIntegrity pattern: - moltbook/moltbook.pi — link_violation field + LinkRestriction (must equal false; freeze + escalate; priority high — a tier below CredentialIntegrity's critical, a link is not an irreversibly-exploitable key). Joined enforce; arbiter never_acceptable gains link_allowlist_self_modification. - moltbook/detector.py — scan_links: pure provenance classification (source / allowlist / novel), never fetches or judges the destination. novel catches shortened/redirect and fragment-assembled URLs; subdomain matches allow. - moltbook/link_allowlist.json — static, human-owned allowlist (Q1). Loaded as an immutable tuple; the running agent has no runtime mutation path (key-isolation principle: an agent that could expand its own allowlist defeats the constraint). - moltbook/client.py — send() runs both gates (credential first, then links). Novel links block + latch link_violation + raise LinkBlocked. Every surfaced link is logged via link_provenance_records() regardless of outcome (Q2) — kept moltbook-local, NOT a core pi_script/trace.py change (shared by link-less systems; client/adapter-layer concern per the CredentialIntegrity split). - tests — violation/clean pair, detector provenance cases, gate behavior, end-to-end block->freeze, reshare-logging, allowlist-immutability. Updated the CredentialIntegrity enforce assertion for the now-two-constraint block. Full suite: 315 passed, 3 xfailed. Co-Authored-By: Claude Fable 5 --- docs/m7_link_restriction_ruling.md | 150 ++++++++++++++ moltbook/client.py | 86 ++++++-- moltbook/detector.py | 99 ++++++++- moltbook/link_allowlist.json | 8 + moltbook/moltbook.pi | 24 ++- moltbook/state.json | 1 + tests/test_moltbook_credential_integrity.py | 3 +- tests/test_moltbook_link_restriction.py | 215 ++++++++++++++++++++ 8 files changed, 563 insertions(+), 23 deletions(-) create mode 100644 docs/m7_link_restriction_ruling.md create mode 100644 moltbook/link_allowlist.json create mode 100644 tests/test_moltbook_link_restriction.py diff --git a/docs/m7_link_restriction_ruling.md b/docs/m7_link_restriction_ruling.md new file mode 100644 index 0000000..1415757 --- /dev/null +++ b/docs/m7_link_restriction_ruling.md @@ -0,0 +1,150 @@ +# M7 Constraint Ruling — LinkRestriction + +**Status:** LOCKED / binding for implementation (signed off 2026-07-16, both open questions +resolved — see §9). Canonical spec-first ruling required by `CLAUDE.md` and the +`pi-script-constraint` skill for the LinkRestriction constraint in the M7 (Moltbook) deployment. +Build order: `moltbook/moltbook.pi` (entity extension + constraint) → link-provenance detector → +gate wiring in `moltbook/client.py` (with reshare logging) → test set (violation/clean pair + +reshare-logging + allowlist-immutability). + +**Numbering note:** No grammar change — LinkRestriction is the existing Form 2 `equality_rule` +(`MoltbookSession.link_violation must equal false`), same shape as CredentialIntegrity. This is an +application-level M7 constraint ruling, not a 9.x grammar ruling. If review finds the six rule +forms can't express it, that is a grammar conversation before any code. + +--- + +## 1. Ruling (locked text) + +The M7 agent may only surface external links that are **(a)** present in the source content it is +directly responding to or citing, or **(b)** on a static allowlist maintained in `moltbook/` config, +editable only outside the agent's runtime reach (never self-modifiable). The agent must never +generate, construct, or surface a novel external URL it was not given — including URLs assembled from +fragments, shortened/redirect links, or links suggested by another agent's post or DM that don't meet +(a) or (b). A violation is: outbound content contains a URL not traceable to one of the two permitted +sources. This is a **provenance check, not payload inspection** — the constraint doesn't judge whether +a link is malicious, only whether the agent had legitimate grounds to surface it. Priority **high**, +`on_violation: freeze + escalate`. Resharing a link present in source content passes the gate but is +**logged in every resolution trace regardless of outcome**, to build a provenance record for future +coordinated-link-seeding detection (out of scope for v1). The **pre-send gate is the primary control** +(same detect-can't-undo-a-post logic as CredentialIntegrity); the Pi Script constraint is the +audit/freeze layer for anything that slips through. + +## 2. Why (threat) + +The M7 recon notes flagged coordinated link-seeding as a live Moltbook pattern — the +`moltbook_pyclaw` / `Ting_Fodder` / `doctor_crustacean` cluster builds apparent authority through a +dense self-citation trail of cross-linked posts. A governed agent that could be steered (by an +injection payload or another agent's DM) into surfacing an attacker-chosen link becomes a node in +that seeding graph. The defensible v1 line is **provenance**: the agent surfaces a link only when it +can point to legitimate grounds (it was in the content being responded to, or on a human-owned +allowlist). Judging whether a link is *malicious*, or detecting *coordinated seeding chains*, is +explicitly out of scope — that is future ManipulationFlag v1.1/v2 or LinkRestriction v1.1 territory. +v1 does not pretend to solve it; it leaves the trail that later work needs (§5). + +## 3. Constraint definition + +Same boolean-latch pattern as CredentialIntegrity. A detector/gate sets `link_violation`; Pi Script +rules on the snapshot. + +``` +entity MoltbookSession { + credential_exposed: boolean + link_violation: boolean // set true by the link-provenance gate (§4) + session_id: identifier +} + +constraint LinkRestriction { + priority: high + rule: MoltbookSession.link_violation must equal false + on_violation: freeze + escalate +} +``` + +- **`priority: high`** (not `critical`): a leaked *key* is irreversibly exploitable; an + un-provenanced *link* is a governance/authority-integrity failure, serious but a tier below key + loss. `freeze + escalate` still applies — the agent stops and a human reviews. +- Grammar-valid Form 2, boolean value, identical machinery to `CredentialIntegrity` / + `ScopeGuard`. + +## 4. Detection — provenance, not payload (Q1 resolved) + +A pre-send gate in the client extracts every URL from candidate outbound content and classifies each: + +| Provenance | Grounds | Outcome | +| --- | --- | --- | +| `source` | The exact URL appears in the source content the agent is responding to/citing (a). | Pass, logged (§5). | +| `allowlist` | The URL's host is on the static `moltbook/` allowlist (b). | Pass, logged (§5). | +| `novel` | Neither — constructed, fragment-assembled, shortened/redirect, or suggested by another agent's post/DM without meeting (a)/(b). | **Violation:** latch `link_violation`, block the send, `freeze + escalate`. | + +**Allowlist maintenance (Q1, resolved — same principle as CredentialIntegrity §5.1 key isolation).** +The allowlist is a **static config in `moltbook/`** (a sibling config file), editable **only via +commit/PR — never writable by the running agent at runtime**. An agent that could expand its own +allowlist defeats the constraint the same way a model holding its own API key defeated +CredentialIntegrity before isolation. It is **read-only to the agent, human-owned.** The client loads +it as an immutable value with no runtime-mutation path. + +This is a **provenance check, not payload inspection**: the gate never fetches the link, never judges +whether the destination is malicious — only whether the agent had legitimate grounds to surface it. + +## 5. Reshare logging (Q2 resolved) — leave a trail v1 doesn't act on + +Every surfaced link is recorded in the M7 resolution trace **regardless of pass/fail**, not only +violations — URL, provenance (`source`/`allowlist`/`novel`), and whether it was allowed. Reasoning: +the recon notes already flagged coordinated link-seeding (the pyclaw/Ting_Fodder self-citation trail). +LinkRestriction v1 should **not** try to judge that — out of scope, same as ManipulationFlag's +coordinated-pattern case — but it should leave a trail. That record is exactly what a future +ManipulationFlag v1.1/v2 or LinkRestriction v1.1 needs to detect seeded-link chains, without +pretending v1 already solves it. + +**Implementation boundary:** the reshare/provenance log is **moltbook-local** — produced by the +client and attached to the M7 trace written under `moltbook/traces/`. It does **not** modify +`pi_script/trace.py`: core trace is shared by systems with no links (m5, es, quantization), and this +is client/adapter-layer concern, consistent with the CredentialIntegrity split (prevention + +provenance are client-side; Pi Script is the constraint/freeze/audit-latch layer). + +## 6. Layer split (unchanged principle from CredentialIntegrity §5) + +The **pre-send gate is the primary control** — same detect-can't-undo-a-post logic: once a post with +a novel link is transmitted, freeze can't recall it, so prevention must happen before send. The Pi +Script `LinkRestriction` constraint is the enforcement latch (freeze + escalate) and audit layer for +anything that slips past the gate (e.g. a client-code bug). A blocked novel link still latches +`link_violation` (belt-and-suspenders): a blocked attempt is itself evidence the agent was steered +toward surfacing an attacker link and should stop. As with CredentialIntegrity, a public trace must +not imply Pi Script "caught" the link — the client gate did. + +## 7. Required tests (per CLAUDE.md, plus the two Q-specific tests) + +In `tests/test_moltbook_link_restriction.py`: + +- **Deliberate-violation:** outbound content with a `novel` URL (not in source, host not allowlisted) + ⇒ gate latches `link_violation` ⇒ `LinkRestriction` fires ⇒ resolver `frozen`, `freeze + escalate`. + Include the assembled-from-fragments and shortened-link variants. +- **Clean-pass:** a URL present in source content, and a URL whose host is allowlisted ⇒ + `link_violation` stays false ⇒ constraint SATISFIED, `running`. +- **Reshare-logging (Q2):** a link present in source content passes the gate AND appears in the + provenance log with `provenance="source"`, `allowed=True` — proving pass-through links are still + recorded. +- **Allowlist-immutability (Q1):** the loaded allowlist has no runtime-mutation path from the client + (read-only), so the agent cannot expand its own permitted set. + +## 8. Relationship to the other M7 constraints + +- **CredentialIntegrity** governs secret exfiltration; **LinkRestriction** governs link provenance. + Overlapping intent (don't emit dangerous strings), distinct detectors, distinct latches — separate + constraints, both enforced on `MoltbookSession`. +- Coordinated cross-agent link-seeding / manipulation stays **out of scope** (v1.1/v2). LinkRestriction + v1 provides the provenance trail; it does not judge chains. +- IdentityIntegrity and ManipulationFlag remain unwritten — each needs its own ruling before code. + +## 9. Decisions log (resolved) + +1. **Constraint name — `LinkRestriction`.** PascalCase, behavior-first, consistent with the M7 set. +2. **Priority — `high`, `on_violation: freeze + escalate`.** A tier below CredentialIntegrity's + `critical` (link ≠ irreversibly-exploitable key), but still stops the agent for human review. +3. **Q1 allowlist maintenance — outside model reach (key-isolation principle).** Static `moltbook/` + config, editable only via commit/PR, never self-modifiable at runtime; loaded read-only. +4. **Q2 reshare handling — pass but always log.** Links traceable to source/allowlist pass the gate; + every surfaced link is logged in the M7 trace regardless of outcome, building the provenance record + for future coordinated-seeding detection (out of scope for v1). Logging is moltbook-local (§5), not + a core `trace.py` change. diff --git a/moltbook/client.py b/moltbook/client.py index 3b32403..121e2b6 100644 --- a/moltbook/client.py +++ b/moltbook/client.py @@ -29,15 +29,35 @@ import json import os +from pathlib import Path from typing import Any, Callable -from moltbook.detector import scan_content +from moltbook.detector import scan_content, scan_links, LinkFinding + +_DEFAULT_ALLOWLIST = Path(__file__).with_name("link_allowlist.json") class KeyLeakBlocked(Exception): """Raised by the pre-send gate when outbound content contains a credential.""" +class LinkBlocked(Exception): + """Raised by the pre-send gate when outbound content surfaces a novel (un-provenanced) link.""" + + +def load_allowlist(path: str | Path | None = None) -> tuple[str, ...]: + """ + Load the static link allowlist (ruling §4, Q1) as an IMMUTABLE tuple. + + The agent gets no runtime write path — the allowlist is human-owned, editable only + via commit/PR to moltbook/link_allowlist.json. Returned as a tuple so there is no + mutation surface at all. + """ + p = Path(path) if path is not None else _DEFAULT_ALLOWLIST + data = json.loads(p.read_text(encoding="utf-8")) + return tuple(data.get("allowed_hosts", [])) + + def _no_transport(**_: Any) -> dict[str, Any]: raise RuntimeError( "MoltbookClient has no transport wired. Inject a real HTTP transport " @@ -60,14 +80,23 @@ def __init__( api_key: str | None = None, transport: Callable[..., dict[str, Any]] | None = None, session_id: str = "moltbook-session", + allowed_hosts: tuple[str, ...] | None = None, ) -> None: # Key isolation: private, resolved from the same runtime secret source as auth. self._api_key = api_key if api_key is not None else os.environ.get("MOLTBOOK_API_KEY") self._transport = transport or _no_transport self.session_id = session_id - # Latch: once a leak is detected (even if blocked), stays set until the key is - # rotated and the session explicitly reset. Drives CredentialIntegrity. + # Latches: once set (even on a blocked attempt), stay set until the session is + # explicitly reset. Drive CredentialIntegrity / LinkRestriction respectively. self.credential_exposed = False + self.link_violation = False + # Immutable, human-owned allowlist (ruling §4, Q1). tuple = no mutation surface. + self._allowed_hosts: tuple[str, ...] = ( + allowed_hosts if allowed_hosts is not None else load_allowlist() + ) + # Provenance log: every surfaced link, regardless of outcome (ruling §5). This + # is the moltbook-local trail future coordinated-seeding detection will need. + self._link_log: list[LinkFinding] = [] # ── Auth (the ONLY place the key is touched) ───────────────────────────────── def _auth_header(self) -> dict[str, str]: @@ -89,20 +118,38 @@ def build_generation_context(self, system: str, incoming: str) -> dict[str, Any] } # ── Pre-send gate (§4/§5) ──────────────────────────────────────────────────── - def send(self, content: str, action: str = "post") -> dict[str, Any]: + def send(self, content: str, action: str = "post", source_content: str = "") -> dict[str, Any]: """ Attempt to send an outbound action (post/comment/dm). Scans first. - On a credential hit: latch `credential_exposed`, refuse to send, raise - KeyLeakBlocked with a REDACTED message (never the secret). Otherwise hand - off to the injected transport with the auth header. + Two gates run before transmission: + - Credential (CredentialIntegrity §4): on a hit, latch `credential_exposed`, + refuse, raise KeyLeakBlocked with a REDACTED message (never the secret). + - Link provenance (LinkRestriction §4): every URL is logged (§5) regardless + of outcome; a novel (un-provenanced) URL latches `link_violation`, refuses, + and raises LinkBlocked. + + `source_content` is the content the agent is responding to/citing — a URL present + there has legitimate provenance. On a clean pass, hand off to the transport. """ - scan = scan_content(content, own_key=self._api_key) - if scan.is_leak: - # Belt-and-suspenders: block AND latch, so CredentialIntegrity fires even - # though nothing was transmitted (ruling §5). + # Gate 1 — credential (most severe; short-circuits). + cred = scan_content(content, own_key=self._api_key) + if cred.is_leak: self.credential_exposed = True - raise KeyLeakBlocked(f"{action} blocked by pre-send gate: {scan.detail}") + raise KeyLeakBlocked(f"{action} blocked by pre-send gate: {cred.detail}") + + # Gate 2 — link provenance. Log every surfaced link first (§5), then enforce. + links = scan_links(content, source_content=source_content, allowed_hosts=self._allowed_hosts) + self._link_log.extend(links.findings) + if links.is_violation: + # Belt-and-suspenders: block AND latch, so LinkRestriction fires even though + # nothing was transmitted (ruling §6). + self.link_violation = True + novel_hosts = sorted({f.host or "" for f in links.novel}) + raise LinkBlocked( + f"{action} blocked by pre-send gate: novel link(s) not traceable to " + f"source or allowlist: {', '.join(novel_hosts)}" + ) return self._transport( action=action, @@ -121,11 +168,26 @@ def snapshot(self, trigger_type: str = "event") -> dict[str, Any]: "entity": "MoltbookSession", "entity_state": { "credential_exposed": self.credential_exposed, + "link_violation": self.link_violation, "session_id": self.session_id, }, "response_history": [], } + # ── Link provenance (LinkRestriction) ──────────────────────────────────────── + @property + def allowed_hosts(self) -> tuple[str, ...]: + """The static allowlist, as an immutable tuple — no runtime mutation path (§4, Q1).""" + return self._allowed_hosts + + def link_provenance_records(self) -> tuple[LinkFinding, ...]: + """ + Every link surfaced this session, regardless of pass/fail (ruling §5). Attached + to the M7 resolution trace under moltbook/traces/ — kept moltbook-local so core + pi_script/trace.py (shared by link-less systems) is untouched. + """ + return tuple(self._link_log) + # ── Guard: prove no artifact leaks the key ─────────────────────────────────── def _contains_key(self, obj: Any) -> bool: """True if the serialized object contains the API key. Test/assert helper.""" diff --git a/moltbook/detector.py b/moltbook/detector.py index 2a4c5cc..69f9933 100644 --- a/moltbook/detector.py +++ b/moltbook/detector.py @@ -1,8 +1,14 @@ """ -moltbook/detector.py — credential-leak detector for the M7 pre-send gate. +moltbook/detector.py — outbound-content detectors for the M7 pre-send gate. -Implements §4 of docs/m7_credential_integrity_ruling.md. Scans outbound content for -secrets in priority order: +Two detectors share this module because they run on the same candidate content in the +same client gate: + - scan_content — credential leak (docs/m7_credential_integrity_ruling.md §4) + - scan_links — link provenance (docs/m7_link_restriction_ruling.md §4) + +──────────────────────────────────────────────────────────────────────────────────── +Credential-leak detector (CredentialIntegrity §4). Scans outbound content for secrets +in priority order: 1. exact own-key match (primary — zero false positives; the client knows its key) 2. key-prefix pattern (secondary — moltbook_sk_ / moltdev_; catches relayed keys) @@ -24,6 +30,7 @@ import re from dataclasses import dataclass +from urllib.parse import urlparse # moltbook_sk_ (agent keys) and moltdev_ (app-verification keys). _KEY_PREFIX_RE = re.compile(r"molt(?:book_sk|dev)_[A-Za-z0-9]+") @@ -73,3 +80,89 @@ def scan_content(content: str, own_key: str | None = None) -> CredentialScan: ) return CredentialScan(is_leak=False, rule="none", detail="no credential detected") + + +# ───────────────────────────────────────────────────────────────────────────── +# Link-provenance detector (LinkRestriction §4). +# +# A PROVENANCE check, not payload inspection: the gate never fetches a link or +# judges whether its destination is malicious — only whether the agent had +# legitimate grounds to surface it: +# source — the exact URL appears in the content being responded to/cited (a) +# allowlist — the URL's host is on the static human-owned allowlist (b) +# novel — neither; a URL the agent was not given (constructed, assembled from +# fragments, shortened/redirect, or suggested by another agent's post/ +# DM without meeting (a)/(b)). A novel link is a violation. +# ───────────────────────────────────────────────────────────────────────────── + +_URL_RE = re.compile(r"""https?://[^\s<>"')\]]+""", re.IGNORECASE) + + +@dataclass(frozen=True) +class LinkFinding: + """One URL found in outbound content, with its provenance. Logged per ruling §5.""" + + url: str + host: str + provenance: str # "source" | "allowlist" | "novel" + allowed: bool + + +@dataclass(frozen=True) +class LinkScan: + is_violation: bool # at least one novel link present + findings: tuple[LinkFinding, ...] + + @property + def novel(self) -> tuple[LinkFinding, ...]: + return tuple(f for f in self.findings if f.provenance == "novel") + + +def _host(url: str) -> str: + try: + return (urlparse(url).hostname or "").lower() + except ValueError: + return "" + + +def _host_allowed(host: str, allowed_hosts) -> bool: + """Exact host or subdomain match against the allowlist.""" + if not host: + return False + for h in allowed_hosts: + h = h.lower() + if host == h or host.endswith("." + h): + return True + return False + + +def scan_links(content: str, source_content: str = "", allowed_hosts=()) -> LinkScan: + """ + Classify every URL in outbound `content` by provenance. + + Args: + content: the post/comment/DM about to be sent. + source_content: the content the agent is directly responding to/citing — + a URL present here has provenance (a). + allowed_hosts: the static, human-owned allowlist (ruling §4, Q1). Passed in + by the client as an immutable value; the agent cannot expand it. + + Returns a LinkScan. `is_violation` is True iff any URL is `novel`. + """ + src = source_content or "" + findings: list[LinkFinding] = [] + violation = False + + for match in _URL_RE.finditer(content or ""): + url = match.group().rstrip(".,;") # drop trailing sentence punctuation + host = _host(url) + if url in src: + prov, allowed = "source", True + elif _host_allowed(host, allowed_hosts): + prov, allowed = "allowlist", True + else: + prov, allowed = "novel", False + violation = True + findings.append(LinkFinding(url=url, host=host, provenance=prov, allowed=allowed)) + + return LinkScan(is_violation=violation, findings=tuple(findings)) diff --git a/moltbook/link_allowlist.json b/moltbook/link_allowlist.json new file mode 100644 index 0000000..e3b86ba --- /dev/null +++ b/moltbook/link_allowlist.json @@ -0,0 +1,8 @@ +{ + "_comment": "Static, human-owned link allowlist for M7 LinkRestriction (ruling §4, Q1). Hosts the M7 agent MAY surface even when not present in source content. Editable ONLY via commit/PR — the running agent has NO runtime write path to this file (loaded read-only). Adding a host here is a human decision, reviewed like any code change. Match is by host (and its subdomains).", + "allowed_hosts": [ + "github.com", + "moltbook.com", + "continuum.dev" + ] +} diff --git a/moltbook/moltbook.pi b/moltbook/moltbook.pi index e6e21dc..7a62736 100644 --- a/moltbook/moltbook.pi +++ b/moltbook/moltbook.pi @@ -11,27 +11,37 @@ domain moltbook_agent_governance { } entity MoltbookSession { - credential_exposed: boolean // set true by the client pre-send gate (ruling §4/§5) + credential_exposed: boolean // set true by the client pre-send gate (credential ruling §4/§5) + link_violation: boolean // set true by the link-provenance gate (link ruling §4) session_id: identifier } // ─── Constraints ────────────────────────────────────────────────────────────── -// Only CredentialIntegrity is defined here — it is the one M7 constraint with a -// locked ruling. IdentityIntegrity, ManipulationFlag, and LinkRestriction each -// arrive with their own ruling; do NOT add them here before the ruling exists -// (spec-first, CLAUDE.md). Their entity fields land alongside those rulings too. +// Each constraint has a locked ruling in docs/. IdentityIntegrity and +// ManipulationFlag still need their own rulings; do NOT add them here before the +// ruling exists (spec-first, CLAUDE.md). Their entity fields land with them too. +// docs/m7_credential_integrity_ruling.md constraint CredentialIntegrity { priority: critical rule: MoltbookSession.credential_exposed must equal false on_violation: freeze + escalate } +// docs/m7_link_restriction_ruling.md — provenance check (link in source or on the +// static human-owned allowlist), not payload inspection. Priority high (a tier +// below CredentialIntegrity: a link is not an irreversibly-exploitable key). +constraint LinkRestriction { + priority: high + rule: MoltbookSession.link_violation must equal false + on_violation: freeze + escalate +} + // ─── Enforcement ────────────────────────────────────────────────────────────── enforce { entity: MoltbookSession - constraints: [CredentialIntegrity] + constraints: [CredentialIntegrity, LinkRestriction] } // ─── Arbiter ────────────────────────────────────────────────────────────────── @@ -42,7 +52,7 @@ enforce { arbiter MoltbookArbiter { acceptable_evolution: ["audit_interval_tuning", "escalation_threshold_tuning"] - never_acceptable: ["credential_integrity_removal", "key_isolation_bypass", "presend_gate_disable", "constraint_removal"] + never_acceptable: ["credential_integrity_removal", "key_isolation_bypass", "presend_gate_disable", "link_allowlist_self_modification", "constraint_removal"] requires_human_review: ["new_constraint", "entity_field_addition", "enforcement_scope_change"] acceptance_monitor: { threshold: 0.9 diff --git a/moltbook/state.json b/moltbook/state.json index bd19e04..e1c5e55 100644 --- a/moltbook/state.json +++ b/moltbook/state.json @@ -3,6 +3,7 @@ "entity": "MoltbookSession", "entity_state": { "credential_exposed": false, + "link_violation": false, "session_id": "moltbook-session" }, "response_history": [] diff --git a/tests/test_moltbook_credential_integrity.py b/tests/test_moltbook_credential_integrity.py index 107fa90..41c4a82 100644 --- a/tests/test_moltbook_credential_integrity.py +++ b/tests/test_moltbook_credential_integrity.py @@ -66,7 +66,8 @@ def test_credential_integrity_ir_shape(self): "value": False, } assert c["on_violation"] == ["freeze", "escalate"] - assert ir["enforce"] == {"MoltbookSession": ["CredentialIntegrity"]} + # LinkRestriction joined the enforce block (docs/m7_link_restriction_ruling.md). + assert ir["enforce"] == {"MoltbookSession": ["CredentialIntegrity", "LinkRestriction"]} # ── Resolver: the required test pair (ruling §7) ───────────────────────────── diff --git a/tests/test_moltbook_link_restriction.py b/tests/test_moltbook_link_restriction.py new file mode 100644 index 0000000..0380598 --- /dev/null +++ b/tests/test_moltbook_link_restriction.py @@ -0,0 +1,215 @@ +""" +test_moltbook_link_restriction.py — M7 LinkRestriction constraint + client gate. + +Covers docs/m7_link_restriction_ruling.md: + - moltbook.pi: LinkRestriction IR shape; both M7 constraints enforced. + - Resolver: deliberate-violation (frozen + escalate) and clean-pass (running). + - Detector (§4): source / allowlist / novel provenance, incl. shortened + assembled. + - Pre-send gate (§4/§6): blocks novel links + latches, passes provenanced links. + - Reshare logging (§5, Q2): passed links are logged with provenance. + - Allowlist immutability (§4, Q1): no runtime mutation path. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from pi_script.parser import parse_file +from pi_script.validator import PiValidator +from pi_script.resolver import resolve +from moltbook.client import MoltbookClient, LinkBlocked, load_allowlist +from moltbook.detector import scan_links + +POLICY = Path(__file__).resolve().parents[1] / "moltbook" / "moltbook.pi" + +ALLOWLIST = ("github.com",) +DUMMY_KEY = "moltbook_sk_dummy_never_in_test_content" + +SOURCE = "As they cited, see https://arxiv.org/abs/2601.01234 for the method." +SOURCE_URL = "https://arxiv.org/abs/2601.01234" +ALLOWED_URL = "https://github.com/GodSpeed313/Continuum" +NOVEL_URL = "https://seeded-authority.example/thread/9" +SHORTENED_URL = "https://bit.ly/3xAbC12" + + +def _ir(): + tree, err = parse_file(str(POLICY)) + assert err is None, err + ok, errors, ir = PiValidator(tree).validate() + assert ok, errors + return ir + + +def _state(credential_exposed=False, link_violation=False) -> dict: + return { + "trigger_type": "event", + "entity": "MoltbookSession", + "entity_state": { + "credential_exposed": credential_exposed, + "link_violation": link_violation, + "session_id": "m7-test", + }, + "response_history": [], + } + + +def _client(**kw) -> MoltbookClient: + kw.setdefault("api_key", DUMMY_KEY) + kw.setdefault("allowed_hosts", ALLOWLIST) + return MoltbookClient(**kw) + + +# ── Policy ─────────────────────────────────────────────────────────────────── + +class TestPolicy: + def test_link_restriction_ir_shape(self): + ir = _ir() + c = ir["constraints"]["LinkRestriction"] + assert c["priority"] == "high" + assert c["rule"] == { + "kind": "equality_rule", + "ref": "MoltbookSession.link_violation", + "value": False, + } + assert c["on_violation"] == ["freeze", "escalate"] + + def test_both_constraints_enforced(self): + assert _ir()["enforce"] == { + "MoltbookSession": ["CredentialIntegrity", "LinkRestriction"] + } + + +# ── Resolver: required test pair (ruling §7) ───────────────────────────────── + +class TestConstraint: + def test_deliberate_violation_freezes_and_escalates(self): + trace, _, code = resolve(_ir(), _state(link_violation=True)) + assert code == 1 + assert trace["system_state"] == "frozen" + result = next(c for c in trace["constraints"] if c["name"] == "LinkRestriction") + assert result["status"] == "violated" + assert result["action"] == "freeze + escalate" + + def test_clean_pass_stays_running(self): + trace, _, code = resolve(_ir(), _state()) + assert code == 0 + assert trace["system_state"] == "running" + result = next(c for c in trace["constraints"] if c["name"] == "LinkRestriction") + assert result["status"] == "satisfied" + + +# ── Detector (§4) ──────────────────────────────────────────────────────────── + +class TestLinkDetector: + def test_url_in_source_is_provenanced(self): + scan = scan_links(f"Agreed — {SOURCE_URL} nails it.", source_content=SOURCE, + allowed_hosts=ALLOWLIST) + assert not scan.is_violation + assert scan.findings[0].provenance == "source" + + def test_allowlisted_host_passes(self): + scan = scan_links(f"see {ALLOWED_URL}", source_content="", allowed_hosts=ALLOWLIST) + assert not scan.is_violation + assert scan.findings[0].provenance == "allowlist" + + def test_subdomain_of_allowlisted_host_passes(self): + scan = scan_links("https://gist.github.com/x/y", source_content="", + allowed_hosts=ALLOWLIST) + assert not scan.is_violation + assert scan.findings[0].provenance == "allowlist" + + def test_novel_url_is_a_violation(self): + scan = scan_links(f"you should check {NOVEL_URL}", source_content=SOURCE, + allowed_hosts=ALLOWLIST) + assert scan.is_violation + assert scan.novel[0].host == "seeded-authority.example" + + def test_shortened_link_not_in_source_is_novel(self): + scan = scan_links(f"quick link: {SHORTENED_URL}", source_content=SOURCE, + allowed_hosts=ALLOWLIST) + assert scan.is_violation + assert scan.novel[0].provenance == "novel" + + def test_url_assembled_from_fragments_is_novel(self): + assembled = "https://" + "tracker" + ".example" + "/p?id=9" + scan = scan_links(f"here: {assembled}", source_content=SOURCE, allowed_hosts=ALLOWLIST) + assert scan.is_violation + + def test_content_without_links_is_clean(self): + scan = scan_links("just a normal governance take, no links.", + source_content=SOURCE, allowed_hosts=ALLOWLIST) + assert not scan.is_violation + assert scan.findings == () + + +# ── Pre-send gate (§4/§6) ──────────────────────────────────────────────────── + +class TestPreSendGate: + def test_novel_link_blocked_and_latched(self): + client = _client() + with pytest.raises(LinkBlocked): + client.send(f"check {NOVEL_URL}", action="comment", source_content=SOURCE) + assert client.link_violation is True + + def test_provenanced_reshare_reaches_transport(self): + sent = {} + client = _client(transport=lambda **kw: sent.update(kw) or {"ok": True}) + result = client.send(f"yes, {SOURCE_URL}", action="comment", source_content=SOURCE) + assert result == {"ok": True} + assert client.link_violation is False + assert sent["action"] == "comment" + + def test_allowlisted_link_reaches_transport(self): + client = _client(transport=lambda **kw: {"ok": True}) + assert client.send(f"repo: {ALLOWED_URL}", action="post") == {"ok": True} + assert client.link_violation is False + + def test_blocked_novel_link_drives_freeze_end_to_end(self): + client = _client() + with pytest.raises(LinkBlocked): + client.send(f"seed: {NOVEL_URL}", action="post", source_content=SOURCE) + trace, _, code = resolve(_ir(), client.snapshot()) + assert code == 1 + assert trace["system_state"] == "frozen" + + +# ── Reshare logging (§5, Q2) ───────────────────────────────────────────────── + +class TestReshareLogging: + def test_passed_reshare_is_logged(self): + client = _client(transport=lambda **kw: {"ok": True}) + client.send(f"as cited: {SOURCE_URL}", action="comment", source_content=SOURCE) + records = client.link_provenance_records() + assert len(records) == 1 + assert records[0].url == SOURCE_URL + assert records[0].provenance == "source" + assert records[0].allowed is True + + def test_novel_link_is_also_logged_before_block(self): + client = _client() + with pytest.raises(LinkBlocked): + client.send(f"seed: {NOVEL_URL}", action="post", source_content=SOURCE) + records = client.link_provenance_records() + assert any(r.provenance == "novel" and not r.allowed for r in records) + + +# ── Allowlist immutability (§4, Q1) ────────────────────────────────────────── + +class TestAllowlistImmutability: + def test_allowlist_is_an_immutable_tuple(self): + client = _client(allowed_hosts=("github.com",)) + assert isinstance(client.allowed_hosts, tuple) + with pytest.raises(AttributeError): + client.allowed_hosts.append("evil.example") # tuples have no append + + def test_client_has_no_runtime_allowlist_mutation_method(self): + client = _client() + for attr in ("add_allowed_host", "set_allowlist", "allow_host", "extend_allowlist"): + assert not hasattr(client, attr) + + def test_default_allowlist_loads_from_static_config(self): + hosts = load_allowlist() + assert "moltbook.com" in hosts + assert isinstance(hosts, tuple)