feat(#829): enforce whole mutator-class lease gate
All checks were successful
ci/woodpecker/pr/ci Pipeline was successful

This commit is contained in:
ms-lead-reviewer
2026-07-17 22:35:18 -05:00
parent 439f5f4bc9
commit 77b137ccc0
12 changed files with 476 additions and 19 deletions

View File

@@ -2,6 +2,16 @@
"model": "opus",
"hooks": {
"PreToolUse": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "python3 ~/.config/mosaic/tools/lease-broker/mutator-gate.py --runtime claude",
"timeout": 3
}
]
},
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [

View File

@@ -28,6 +28,7 @@ import { execSync, spawnSync } from 'node:child_process';
// ---------------------------------------------------------------------------
const MOSAIC_HOME = process.env['MOSAIC_HOME'] ?? join(homedir(), '.config', 'mosaic');
const MUTATOR_GATE = join(MOSAIC_HOME, 'tools', 'lease-broker', 'mutator-gate.py');
// ---------------------------------------------------------------------------
// Helpers
@@ -106,6 +107,23 @@ function nowIso(): string {
return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
}
function checkPiMutatorGate(toolName: string): { block: true; reason: string } | undefined {
const result = spawnSync('python3', [MUTATOR_GATE, '--runtime', 'pi'], {
input: `${JSON.stringify({ tool_name: toolName })}\n`,
encoding: 'utf8',
timeout: 2_000,
env: process.env,
});
if (result.status === 0) return undefined;
const detail = String(result.stderr ?? '')
.trim()
.split('\n')[0];
return {
block: true,
reason: detail || 'BLOCKED: Mosaic mutator gate is unavailable or the lease is UNVERIFIED.',
};
}
// ---------------------------------------------------------------------------
// Mission detection
// ---------------------------------------------------------------------------
@@ -250,6 +268,11 @@ export default function register(pi: ExtensionAPI) {
let hbModel: string | null = null;
let hbTimer: ReturnType<typeof setInterval> | null = null;
// ── Whole mutator-class authorization gate ────────────────────────────
// Every Pi tool, including unknown/custom tools, reaches the broker-backed
// class gate before execution. Broker/script failure blocks fail-closed.
pi.on('tool_call', async (event) => checkPiMutatorGate(event.toolName));
// ── Session Start ─────────────────────────────────────────────────────
pi.on('session_start', async (_event, ctx) => {
sessionCwd = process.cwd();

View File

@@ -24,9 +24,19 @@ MAX_FRAME: Final = 64 * 1024
MAX_STATE: Final = 4 * 1024 * 1024
MAX_PENDING_TOKENS: Final = 256
MAX_IN_FLIGHT_CONNECTIONS: Final = 16
MAX_LEASE_TTL_SECONDS: Final = 300
STATE_VERSION: Final = 1
CONNECTION_DEADLINE_SECONDS: Final = 1.0
HEX_256_LENGTH: Final = 64
LEASE_UNVERIFIED: Final = "UNVERIFIED"
LEASE_PENDING: Final = "PENDING_VERIFICATION"
LEASE_PENDING_PROMOTION: Final = "PENDING_PROMOTION"
LEASE_VERIFIED: Final = "VERIFIED"
READ_ONLY_TOOLS: Final = {
"claude": frozenset({"Read", "Grep", "Glob", "Ls", "Find"}),
"pi": frozenset({"read", "grep", "find", "ls"}),
}
RECOVERY_TOOL: Final = "mosaic_context_recover"
class BrokerFailure(Exception):
@@ -265,6 +275,9 @@ class StateStore:
class Broker:
def __init__(self, store: StateStore) -> None:
self.store = store
# VERIFIED authority is deliberately volatile: broker restart revokes all
# leases while preserving WI-1 identity and pending-token integrity.
self.leases: dict[str, dict[str, object]] = {}
def authenticate(self, peer_pid: int, request: dict[str, object]) -> tuple[str, dict[str, object]]:
session_id = request.get("session_id")
@@ -289,7 +302,7 @@ class Broker:
raise BrokerFailure("STALE_GENERATION")
if generation > current_generation:
session["runtime_generation"] = generation
self.revoke_session_tokens(session_id)
self.revoke_session_authority(session_id)
return session_id, session
def session_for_anchor(
@@ -310,19 +323,59 @@ class Broker:
]:
del tokens[token_value]
def revoke_session_authority(self, session_id: str) -> None:
self.revoke_session_tokens(session_id)
session = self.store.sessions().get(session_id)
generation = session.get("runtime_generation") if isinstance(session, dict) else None
self.leases[session_id] = {
"state": LEASE_UNVERIFIED,
"runtime_generation": generation,
}
def mint_token(
self,
session_id: str,
generation: int,
binding: dict[str, object],
) -> str:
if len(self.store.tokens()) >= MAX_PENDING_TOKENS:
raise BrokerFailure("TOKEN_CAPACITY")
token = secrets.token_hex(32)
self.store.tokens()[token] = {
"session_id": session_id,
"runtime_generation": generation,
"binding": copy.deepcopy(binding),
"consumed": False,
}
return token
def finish_promotion(self, session_id: str) -> None:
lease = self.leases.get(session_id)
if not isinstance(lease, dict) or lease.get("state") != LEASE_PENDING_PROMOTION:
raise BrokerFailure("STATE_INTEGRITY")
lease["state"] = LEASE_VERIFIED
def handle(self, peer: tuple[int, int, int], request: dict[str, object]) -> dict[str, object]:
if self.store.poisoned:
raise StateCommitUncertain()
previous = copy.deepcopy(self.store.value)
previous_leases = copy.deepcopy(self.leases)
try:
response = self._handle(peer, request)
if self.store.value != previous:
self.store.commit()
if request.get("action") == "promote_lease":
session_id = request.get("session_id")
if not isinstance(session_id, str):
raise BrokerFailure("INVALID_IDENTITY")
self.finish_promotion(session_id)
response["state"] = LEASE_VERIFIED
return response
except StateCommitUncertain:
raise
except Exception:
self.store.value = previous
self.leases = previous_leases
raise
def _handle(self, peer: tuple[int, int, int], request: dict[str, object]) -> dict[str, object]:
@@ -351,7 +404,7 @@ class Broker:
raise BrokerFailure("STALE_GENERATION")
if generation > current_generation:
session["runtime_generation"] = generation
self.revoke_session_tokens(session_id)
self.revoke_session_authority(session_id)
return {"ok": True, "session_id": session_id, "peer": {"pid": peer_pid, "uid": peer_uid, "gid": peer_gid, "starttime": anchor["starttime"]}}
if action == "authenticate":
self.authenticate(peer_pid, request)
@@ -361,15 +414,7 @@ class Broker:
binding = request.get("binding")
if not valid_binding(binding):
raise BrokerFailure("INVALID_BINDING")
if len(self.store.tokens()) >= MAX_PENDING_TOKENS:
raise BrokerFailure("TOKEN_CAPACITY")
token = secrets.token_hex(32)
self.store.tokens()[token] = {
"session_id": session_id,
"runtime_generation": request["runtime_generation"],
"binding": binding,
"consumed": False,
}
token = self.mint_token(session_id, request["runtime_generation"], binding)
return {"ok": True, "token": token}
if action == "consume_token":
session_id, _ = self.authenticate(peer_pid, request)
@@ -379,6 +424,112 @@ class Broker:
raise BrokerFailure("TOKEN_REPLAY")
del self.store.tokens()[token_value]
return {"ok": True}
if action == "begin_verification":
session_id, _ = self.authenticate(peer_pid, request)
runtime = request.get("runtime")
binding = request.get("binding")
ttl_seconds = request.get("ttl_seconds", MAX_LEASE_TTL_SECONDS)
if runtime not in READ_ONLY_TOOLS:
raise BrokerFailure("INVALID_RUNTIME")
if not valid_binding(binding):
raise BrokerFailure("INVALID_BINDING")
if (
type(ttl_seconds) is not int
or ttl_seconds <= 0
or ttl_seconds > MAX_LEASE_TTL_SECONDS
):
raise BrokerFailure("INVALID_LEASE_TTL")
# Revoke-first is a broker operation, not advisory adapter order.
self.revoke_session_authority(session_id)
token = self.mint_token(session_id, request["runtime_generation"], binding)
self.leases[session_id] = {
"state": LEASE_PENDING,
"runtime": runtime,
"runtime_generation": request["runtime_generation"],
"binding": copy.deepcopy(binding),
"promotion_token": token,
"ttl_seconds": ttl_seconds,
}
return {
"ok": True,
"state": LEASE_PENDING,
"promotion_token": token,
}
if action == "promote_lease":
session_id, _ = self.authenticate(peer_pid, request)
promotion_token = request.get("promotion_token")
lease = self.leases.get(session_id)
if not isinstance(lease, dict) or lease.get("state") != LEASE_PENDING:
raise BrokerFailure("INVALID_LEASE_TRANSITION")
expected_token = lease.get("promotion_token")
if (
not isinstance(promotion_token, str)
or not isinstance(expected_token, str)
or not secrets.compare_digest(promotion_token, expected_token)
):
raise BrokerFailure("PROMOTION_TOKEN_MISMATCH")
token = self.store.tokens().get(promotion_token)
if (
not isinstance(token, dict)
or token.get("session_id") != session_id
or token.get("runtime_generation") != request.get("runtime_generation")
or token.get("binding") != lease.get("binding")
or token.get("consumed") is not False
):
raise BrokerFailure("PROMOTION_TOKEN_INVALID")
del self.store.tokens()[promotion_token]
lease["state"] = LEASE_PENDING_PROMOTION
lease["expires_at"] = time.monotonic() + int(lease["ttl_seconds"])
# handle() commits token consumption before finish_promotion() makes
# VERIFIED externally visible: promote-last by construction.
return {"ok": True, "state": LEASE_PENDING_PROMOTION}
if action == "revoke_lease":
session_id, _ = self.authenticate(peer_pid, request)
self.revoke_session_authority(session_id)
return {"ok": True, "state": LEASE_UNVERIFIED}
if action == "authorize_tool":
session_id, _ = self.authenticate(peer_pid, request)
runtime = request.get("runtime")
tool_name = request.get("tool_name")
if runtime not in READ_ONLY_TOOLS:
raise BrokerFailure("INVALID_RUNTIME")
if not isinstance(tool_name, str) or not tool_name or len(tool_name) > 256:
raise BrokerFailure("INVALID_TOOL")
lease = self.leases.get(session_id)
state = lease.get("state") if isinstance(lease, dict) else LEASE_UNVERIFIED
if tool_name in READ_ONLY_TOOLS[runtime] or tool_name == RECOVERY_TOOL:
return {"ok": True, "decision": "allow", "state": state}
if not isinstance(lease, dict) or lease.get("state") != LEASE_VERIFIED:
return {
"ok": False,
"code": "MUTATOR_UNVERIFIED",
"decision": "deny",
"state": LEASE_UNVERIFIED,
}
if (
lease.get("runtime") != runtime
or lease.get("runtime_generation") != request.get("runtime_generation")
):
return {
"ok": False,
"code": "MUTATOR_UNVERIFIED",
"decision": "deny",
"state": LEASE_UNVERIFIED,
}
expires_at = lease.get("expires_at")
if not isinstance(expires_at, (int, float)) or time.monotonic() >= expires_at:
self.revoke_session_authority(session_id)
return {
"ok": False,
"code": "LEASE_EXPIRED",
"decision": "deny",
"state": LEASE_UNVERIFIED,
}
return {
"ok": True,
"decision": "allow",
"state": LEASE_VERIFIED,
}
raise BrokerFailure("UNKNOWN_ACTION")

View File

@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Register a runtime parent with the lease broker, then exec without changing PID."""
from __future__ import annotations
import argparse
import json
import os
import socket
import sys
from pathlib import Path
from typing import Final
MAX_FRAME: Final = 64 * 1024
BROKER_TIMEOUT_SECONDS: Final = 1.5
def broker_request(socket_path: Path, request: dict[str, object]) -> dict[str, object]:
payload = (json.dumps(request, separators=(",", ":")) + "\n").encode()
response = bytearray()
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
connection.settimeout(BROKER_TIMEOUT_SECONDS)
connection.connect(str(socket_path))
connection.sendall(payload)
connection.shutdown(socket.SHUT_WR)
while len(response) <= MAX_FRAME:
chunk = connection.recv(min(4096, MAX_FRAME + 1 - len(response)))
if not chunk:
break
response.extend(chunk)
if len(response) > MAX_FRAME or not response.endswith(b"\n"):
raise ValueError("invalid broker reply")
value = json.loads(response)
if not isinstance(value, dict):
raise ValueError("invalid broker reply")
return value
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--runtime", required=True, choices=("claude", "pi"))
parser.add_argument("command", nargs=argparse.REMAINDER)
arguments = parser.parse_args()
command = arguments.command
if command and command[0] == "--":
command = command[1:]
if not command:
print("lease-gated runtime command is required", file=sys.stderr)
return 64
try:
socket_path = Path(os.environ["MOSAIC_LEASE_BROKER_SOCKET"])
generation = int(os.environ.get("MOSAIC_RUNTIME_GENERATION", "1"))
if generation < 0:
raise ValueError("invalid generation")
reply = broker_request(
socket_path,
{
"action": "register_anchor",
"runtime_generation": generation,
},
)
session_id = reply.get("session_id")
if (
reply.get("ok") is not True
or not isinstance(session_id, str)
or len(session_id) != 64
or any(character not in "0123456789abcdef" for character in session_id)
):
raise ValueError("registration refused")
except (KeyError, ValueError, OSError, json.JSONDecodeError):
print("Mosaic lease broker registration failed; runtime launch denied.", file=sys.stderr)
return 1
environment = dict(os.environ)
environment["MOSAIC_LEASE_SESSION_ID"] = session_id
environment["MOSAIC_RUNTIME_GENERATION"] = str(generation)
environment["MOSAIC_LEASE_RUNTIME"] = arguments.runtime
try:
os.execvpe(command[0], command, environment)
except OSError:
print("Mosaic lease-gated runtime exec failed.", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Runtime-neutral whole mutator-class gate backed by the Mosaic lease broker."""
from __future__ import annotations
import argparse
import json
import os
import socket
import sys
from pathlib import Path
from typing import Final
MAX_FRAME: Final = 64 * 1024
BROKER_TIMEOUT_SECONDS: Final = 1.5
def deny(code: str) -> int:
print(f"BLOCKED: Mosaic mutator gate denied this tool ({code}).", file=sys.stderr)
return 2
def read_tool_name() -> str:
raw = sys.stdin.buffer.read(MAX_FRAME + 1)
if len(raw) > MAX_FRAME:
raise ValueError("INVALID_GATE_INPUT")
value = json.loads(raw)
if not isinstance(value, dict):
raise ValueError("INVALID_GATE_INPUT")
tool_name = value.get("tool_name")
if not isinstance(tool_name, str) or not tool_name or len(tool_name) > 256:
raise ValueError("INVALID_GATE_INPUT")
return tool_name
def broker_request(socket_path: Path, request: dict[str, object]) -> dict[str, object]:
payload = (json.dumps(request, separators=(",", ":")) + "\n").encode()
if len(payload) > MAX_FRAME:
raise ValueError("INVALID_GATE_INPUT")
response = bytearray()
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
connection.settimeout(BROKER_TIMEOUT_SECONDS)
connection.connect(str(socket_path))
connection.sendall(payload)
connection.shutdown(socket.SHUT_WR)
while len(response) <= MAX_FRAME:
chunk = connection.recv(min(4096, MAX_FRAME + 1 - len(response)))
if not chunk:
break
response.extend(chunk)
if len(response) > MAX_FRAME or not response.endswith(b"\n"):
raise ValueError("INVALID_BROKER_REPLY")
value = json.loads(response)
if not isinstance(value, dict):
raise ValueError("INVALID_BROKER_REPLY")
return value
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--runtime", required=True, choices=("claude", "pi"))
arguments = parser.parse_args()
try:
tool_name = read_tool_name()
socket_value = os.environ["MOSAIC_LEASE_BROKER_SOCKET"]
session_id = os.environ["MOSAIC_LEASE_SESSION_ID"]
generation = int(os.environ["MOSAIC_RUNTIME_GENERATION"])
if generation < 0:
raise ValueError("INVALID_GENERATION")
reply = broker_request(
Path(socket_value),
{
"action": "authorize_tool",
"session_id": session_id,
"runtime_generation": generation,
"runtime": arguments.runtime,
"tool_name": tool_name,
},
)
except (KeyError, ValueError, OSError, json.JSONDecodeError):
return deny("GATE_UNAVAILABLE")
if reply.get("ok") is True and reply.get("decision") == "allow":
return 0
code = reply.get("code")
return deny(code if isinstance(code, str) else "MUTATOR_UNVERIFIED")
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -115,7 +115,7 @@ function auditClaudeSettings(): SettingsAudit {
// Check required hooks
const hooks = settings['hooks'] as Record<string, unknown[]> | undefined;
const requiredPreToolUse = ['prevent-memory-write.sh'];
const requiredPreToolUse = ['mutator-gate.py', 'prevent-memory-write.sh'];
const requiredPostToolUse = ['qa-hook-stdin.sh', 'typecheck-hook.sh'];
const preHooks = (hooks?.['PreToolUse'] ?? []) as Array<Record<string, unknown>>;
@@ -763,7 +763,7 @@ function launchRuntime(runtime: RuntimeName, args: string[], yolo: boolean): nev
cliArgs.push(...args);
}
console.log(`[mosaic] Launching ${label}${modeStr}${missionStr}...`);
execRuntime('claude', cliArgs);
execLeaseGatedRuntime('claude', cliArgs);
break;
}
@@ -798,7 +798,7 @@ function launchRuntime(runtime: RuntimeName, args: string[], yolo: boolean): nev
cliArgs.push(...args);
}
console.log(`[mosaic] Launching ${label}${modeStr}${missionStr}...`);
execRuntime('pi', cliArgs);
execLeaseGatedRuntime('pi', cliArgs);
break;
}
}
@@ -806,6 +806,23 @@ function launchRuntime(runtime: RuntimeName, args: string[], yolo: boolean): nev
process.exit(0); // Unreachable but satisfies never
}
function defaultLeaseBrokerSocket(env: NodeJS.ProcessEnv = process.env): string {
if (env['MOSAIC_LEASE_BROKER_SOCKET']) return env['MOSAIC_LEASE_BROKER_SOCKET'];
const runtimeDir = env['XDG_RUNTIME_DIR'];
if (runtimeDir) return join(runtimeDir, 'mosaic-lease', 'broker.sock');
const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
return join('/run/user', String(uid), 'mosaic-lease', 'broker.sock');
}
function execLeaseGatedRuntime(runtime: 'claude' | 'pi', args: string[]): void {
const launcher = resolveTool('lease-broker', 'launch-runtime.py');
execRuntime('python3', [launcher, '--runtime', runtime, '--', runtime, ...args], {
...process.env,
MOSAIC_LEASE_BROKER_SOCKET: defaultLeaseBrokerSocket(),
MOSAIC_RUNTIME_GENERATION: process.env['MOSAIC_RUNTIME_GENERATION'] ?? '1',
});
}
/** exec into the runtime, replacing the current process. */
function execRuntime(cmd: string, args: string[], env: NodeJS.ProcessEnv = process.env): void {
try {