fix(reviewer-workflow): address review — in-process mutation authority, no /tmp lock (#199)
Addresses the sysadmin REQUEST_CHANGES on PR #203 (reviewed head10d2644790): 1. Lock redesigned; /tmp file removed entirely. The mutation authority is now an in-process record (_MUTATION_AUTHORITY) plus an environment session lock (GITEA_SESSION_PROFILE_LOCK) exported at server launch: - in-process record cannot be spoofed by other local processes, cannot go stale across sessions, and cannot race concurrent agents; - the env lock is inherited by child CLI processes, so review_pr.py can refuse an ad-hoc GITEA_MCP_PROFILE role escalation without any shared file; a missing env lock (direct operator CLI use) stays allowed; - silent except-pass writes are gone; an unresolvable profile fails closed. 2. Standard reviewer workflow unbroken: verify_mutation_authority seeds itself from the live config-resolved context at the first mutation gate (approved preflight path whoami -> eligibility -> review/merge), and now runs as the final gate after eligibility, reusing the identity that eligibility proved (no extra /user call). 3. Trailing whitespace removed from review_pr.py (git diff --check clean). 4. Module-global verify_mutation_authority no-op bypass removed from tests/test_mcp_server.py; replaced with a tests/conftest.py autouse fixture that only resets per-process state (_MUTATION_AUTHORITY, _IDENTITY_CACHE, session lock env) between tests — the gate itself stays live in every test. 5. Tests rewritten for the new design: seeding on first verify, unresolved profile fails closed, remote/profile/identity mismatches fail closed, session-lock env mismatch rejected, foreign-pid authority reseeded, unauthorized author->reviewer pivot blocked, authorized pivot allowed; CLI: mismatch blocked, match allowed, no-lock allowed. 6. Rebased onto current master (c6fd0fd). Closes #199 Refs #194 Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
+136
-59
@@ -22,11 +22,42 @@ import contextlib
|
||||
import subprocess
|
||||
|
||||
|
||||
LOCK_FILE = "/tmp/gitea_mutation_authority.lock"
|
||||
# Mutation-authority record (#199, refs #194). Deliberately in-process, NOT a
|
||||
# file: a /tmp lock is host-global, writable (spoofable) by any local process,
|
||||
# goes silently stale across sessions, and races between concurrent agent
|
||||
# sessions. This record lives and dies with the MCP server process, so it can
|
||||
# never be forged from outside or leak between sessions. The CLI side-channel
|
||||
# (a subprocess overriding GITEA_MCP_PROFILE to escalate roles) is covered by
|
||||
# SESSION_PROFILE_LOCK_ENV below: the server exports its launch profile into
|
||||
# the environment, children inherit it, and reviewer CLIs (review_pr.py)
|
||||
# refuse to run under a different resolved profile.
|
||||
_MUTATION_AUTHORITY: dict | None = None
|
||||
|
||||
def record_mutation_authority(profile_name: str | None, identity: str | None, remote: str | None, task: str | None):
|
||||
"""Record the resolved capability context to fail-closed lock file."""
|
||||
data = {
|
||||
SESSION_PROFILE_LOCK_ENV = "GITEA_SESSION_PROFILE_LOCK"
|
||||
|
||||
|
||||
def _export_session_profile_lock():
|
||||
"""Export this process's launch profile for child CLI processes.
|
||||
|
||||
setdefault: an already-locked environment (outer session) wins, so a
|
||||
nested launch cannot relabel the session.
|
||||
"""
|
||||
try:
|
||||
name = (get_profile().get("profile_name") or "").strip()
|
||||
if name:
|
||||
os.environ.setdefault(SESSION_PROFILE_LOCK_ENV, name)
|
||||
except Exception:
|
||||
# Profile resolution problems surface loudly on the first real call;
|
||||
# the lock export must not mask them here at import time.
|
||||
pass
|
||||
|
||||
|
||||
def record_mutation_authority(profile_name: str | None, identity: str | None,
|
||||
remote: str | None, task: str | None):
|
||||
"""Record the resolved capability context for this process (fail-closed
|
||||
consumers in verify_mutation_authority)."""
|
||||
global _MUTATION_AUTHORITY
|
||||
_MUTATION_AUTHORITY = {
|
||||
"initial_profile": profile_name,
|
||||
"initial_identity": identity,
|
||||
"current_profile": profile_name,
|
||||
@@ -35,48 +66,83 @@ def record_mutation_authority(profile_name: str | None, identity: str | None, re
|
||||
"task": task,
|
||||
"role_pivot_authorized": False,
|
||||
"role_pivot_record": None,
|
||||
"pid": os.getpid(),
|
||||
}
|
||||
try:
|
||||
with open(LOCK_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def verify_mutation_authority(remote: str | None, host: str | None = None, required_role: str = "reviewer"):
|
||||
"""Verify that the current mutation matches the locked capability context."""
|
||||
if not os.path.exists(LOCK_FILE):
|
||||
raise RuntimeError("Mutation authority lock is missing (fail closed)")
|
||||
|
||||
try:
|
||||
with open(LOCK_FILE, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Could not read mutation authority lock: {e} (fail closed)")
|
||||
def verify_mutation_authority(remote: str | None, host: str | None = None,
|
||||
required_role: str = "reviewer",
|
||||
active_identity: str | None = None):
|
||||
"""Verify the current mutation matches this process's recorded authority.
|
||||
|
||||
if data.get("remote") != remote:
|
||||
raise RuntimeError(
|
||||
f"Mutation remote '{remote}' does not match locked remote '{data.get('remote')}' (fail closed)"
|
||||
)
|
||||
Fail-closed rules:
|
||||
- No recorded authority (or one from another process after a fork) is
|
||||
seeded from the live, config-resolved context — the approved preflight
|
||||
path (whoami → eligibility → mutation) therefore works without an
|
||||
explicit resolve call — but an unresolvable profile still fails closed.
|
||||
- GITEA_SESSION_PROFILE_LOCK (set by the launching session) must match
|
||||
the active profile: a mid-session GITEA_MCP_PROFILE override flips the
|
||||
active profile away from the lock and is refused.
|
||||
- Remote, profile, and identity must match the recorded authority.
|
||||
- An author→reviewer pivot requires an authorized pivot record
|
||||
(gitea_activate_profile in dynamic mode); it can never be improvised.
|
||||
"""
|
||||
global _MUTATION_AUTHORITY
|
||||
|
||||
profile = get_profile()
|
||||
active_profile = profile.get("profile_name")
|
||||
h = host or (REMOTES.get(remote, {}).get("host") if remote in REMOTES else None)
|
||||
active_identity = _authenticated_username(h) if h else None
|
||||
if active_identity is None:
|
||||
# Callers that already proved the identity (eligibility gate) pass it
|
||||
# in; otherwise resolve it here (cached, read-only).
|
||||
h = host or (REMOTES.get(remote, {}).get("host") if remote in REMOTES else None)
|
||||
active_identity = _authenticated_username(h) if h else None
|
||||
|
||||
if not active_profile:
|
||||
raise RuntimeError(
|
||||
"Mutation authority unavailable: active profile unresolved (fail closed)"
|
||||
)
|
||||
|
||||
session_lock = (os.environ.get(SESSION_PROFILE_LOCK_ENV) or "").strip()
|
||||
if session_lock and session_lock != active_profile:
|
||||
raise RuntimeError(
|
||||
f"Active profile '{active_profile}' does not match the session "
|
||||
f"profile lock '{session_lock}' — profile side-channel override "
|
||||
"rejected (fail closed)"
|
||||
)
|
||||
|
||||
data = _MUTATION_AUTHORITY
|
||||
if data is None or data.get("pid") != os.getpid():
|
||||
# First mutation gate in this process (approved preflight path):
|
||||
# seed the authority from the live context, then verify against it.
|
||||
record_mutation_authority(
|
||||
active_profile, active_identity, remote, "seeded-at-mutation-gate"
|
||||
)
|
||||
data = _MUTATION_AUTHORITY
|
||||
|
||||
if data.get("remote") != remote:
|
||||
raise RuntimeError(
|
||||
f"Mutation remote '{remote}' does not match locked remote "
|
||||
f"'{data.get('remote')}' (fail closed)"
|
||||
)
|
||||
|
||||
locked_profile = data.get("current_profile")
|
||||
locked_identity = data.get("current_identity")
|
||||
|
||||
if active_profile != locked_profile or active_identity != locked_identity:
|
||||
raise RuntimeError(
|
||||
f"Mutation profile '{active_profile}' or identity '{active_identity}' "
|
||||
f"does not match locked authority (profile: '{locked_profile}', identity: '{locked_identity}') (fail closed)"
|
||||
f"does not match locked authority (profile: '{locked_profile}', "
|
||||
f"identity: '{locked_identity}') (fail closed)"
|
||||
)
|
||||
|
||||
# Check reviewer/author role pivot boundaries
|
||||
if required_role == "reviewer" and "author" in str(data.get("initial_profile")).lower() and "reviewer" in str(active_profile).lower():
|
||||
# Reviewer/author role pivot boundary: only an authorized pivot
|
||||
# (recorded by gitea_activate_profile) may cross author → reviewer.
|
||||
if (required_role == "reviewer"
|
||||
and "author" in str(data.get("initial_profile")).lower()
|
||||
and "reviewer" in str(active_profile).lower()):
|
||||
if not data.get("role_pivot_authorized"):
|
||||
raise RuntimeError(
|
||||
"Attempted reviewer mutation from author session without authorized role pivot (fail closed)"
|
||||
"Attempted reviewer mutation from author session without "
|
||||
"authorized role pivot (fail closed)"
|
||||
)
|
||||
|
||||
# Resolve the project root. MCP clients must launch this script directly with
|
||||
@@ -1050,12 +1116,6 @@ def gitea_submit_pr_review(
|
||||
}
|
||||
reasons = result["reasons"]
|
||||
|
||||
try:
|
||||
verify_mutation_authority(remote, host, required_role="reviewer")
|
||||
except RuntimeError as e:
|
||||
reasons.append(str(e))
|
||||
return result
|
||||
|
||||
# Gate 1 — valid review action (no mutation on unknown action).
|
||||
if action not in _REVIEW_ACTIONS:
|
||||
reasons.append(
|
||||
@@ -1108,6 +1168,17 @@ def gitea_submit_pr_review(
|
||||
reasons.append("PR head SHA unavailable (fail closed)")
|
||||
return result
|
||||
|
||||
# Gate 5 — in-process mutation authority (#199): the last check before
|
||||
# the mutating POST, using the identity the eligibility gate proved.
|
||||
# A profile/identity flip or side-channel override between preflight
|
||||
# and mutation fails closed here.
|
||||
try:
|
||||
verify_mutation_authority(remote, host, required_role="reviewer",
|
||||
active_identity=auth_user)
|
||||
except RuntimeError as e:
|
||||
reasons.append(str(e))
|
||||
return result
|
||||
|
||||
# All gates passed — perform the single mutating call.
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
try:
|
||||
@@ -1376,12 +1447,6 @@ def gitea_merge_pr(
|
||||
}
|
||||
reasons = result["reasons"]
|
||||
|
||||
try:
|
||||
verify_mutation_authority(remote, host, required_role="reviewer")
|
||||
except RuntimeError as e:
|
||||
reasons.append(str(e))
|
||||
return result
|
||||
|
||||
# Gate 1 — valid merge method (no API call on a bad method).
|
||||
if do not in _MERGE_METHODS:
|
||||
reasons.append(
|
||||
@@ -1460,6 +1525,17 @@ def gitea_merge_pr(
|
||||
reasons.append("self-merge blocked (authenticated user is PR author)")
|
||||
return result
|
||||
|
||||
# Gate 7 — in-process mutation authority (#199): the last check before
|
||||
# the merge mutation, using the identity the eligibility gate proved.
|
||||
# A profile/identity flip or side-channel override between preflight
|
||||
# and merge fails closed here.
|
||||
try:
|
||||
verify_mutation_authority(remote, host, required_role="reviewer",
|
||||
active_identity=auth_user)
|
||||
except RuntimeError as e:
|
||||
reasons.append(str(e))
|
||||
return result
|
||||
|
||||
# All gates passed — perform the single merge mutation.
|
||||
try:
|
||||
auth = _auth(h)
|
||||
@@ -3058,24 +3134,21 @@ def gitea_activate_profile(
|
||||
after_profile = get_profile()["profile_name"]
|
||||
after_identity = _authenticated_username(h) if h else None
|
||||
|
||||
# 4.5 Record pivot in mutation authority lock
|
||||
if os.path.exists(LOCK_FILE):
|
||||
try:
|
||||
with open(LOCK_FILE, "r", encoding="utf-8") as f:
|
||||
lock_data = json.load(f)
|
||||
lock_data["current_profile"] = after_profile
|
||||
lock_data["current_identity"] = after_identity
|
||||
lock_data["role_pivot_authorized"] = True
|
||||
lock_data["role_pivot_record"] = {
|
||||
"from_profile": before_profile,
|
||||
"to_profile": after_profile,
|
||||
"from_identity": before_identity,
|
||||
"to_identity": after_identity
|
||||
}
|
||||
with open(LOCK_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(lock_data, f)
|
||||
except Exception:
|
||||
pass
|
||||
# 4.5 Record the authorized pivot in the in-process mutation authority
|
||||
# and keep the session profile lock in sync — this is the ONLY path that
|
||||
# may authorize an author→reviewer role pivot.
|
||||
if _MUTATION_AUTHORITY is not None:
|
||||
_MUTATION_AUTHORITY["current_profile"] = after_profile
|
||||
_MUTATION_AUTHORITY["current_identity"] = after_identity
|
||||
_MUTATION_AUTHORITY["role_pivot_authorized"] = True
|
||||
_MUTATION_AUTHORITY["role_pivot_record"] = {
|
||||
"from_profile": before_profile,
|
||||
"to_profile": after_profile,
|
||||
"from_identity": before_identity,
|
||||
"to_identity": after_identity,
|
||||
}
|
||||
if os.environ.get(SESSION_PROFILE_LOCK_ENV) and after_profile:
|
||||
os.environ[SESSION_PROFILE_LOCK_ENV] = after_profile
|
||||
|
||||
# 5. Audit the switch if auditing is on
|
||||
_audit(
|
||||
@@ -3588,4 +3661,8 @@ def gitea_resolve_task_capability(
|
||||
# ── Entry point ───────────────────────────────────────────────────────────────
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Lock this session's launch profile into the environment so child CLI
|
||||
# processes (e.g. review_pr.py) can detect and refuse profile
|
||||
# side-channel overrides (#199).
|
||||
_export_session_profile_lock()
|
||||
mcp.run(transport="stdio")
|
||||
|
||||
Reference in New Issue
Block a user