feat(reviewer-workflow): add hard wall against reviewer mutations through alternate profile or CLI side-channel
This commit is contained in:
@@ -16,10 +16,69 @@ Configuration (mcp_config.json):
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import json
|
||||
import functools
|
||||
import contextlib
|
||||
import subprocess
|
||||
|
||||
|
||||
LOCK_FILE = "/tmp/gitea_mutation_authority.lock"
|
||||
|
||||
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 = {
|
||||
"initial_profile": profile_name,
|
||||
"initial_identity": identity,
|
||||
"current_profile": profile_name,
|
||||
"current_identity": identity,
|
||||
"remote": remote,
|
||||
"task": task,
|
||||
"role_pivot_authorized": False,
|
||||
"role_pivot_record": None,
|
||||
}
|
||||
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)")
|
||||
|
||||
if data.get("remote") != remote:
|
||||
raise RuntimeError(
|
||||
f"Mutation remote '{remote}' does not match locked remote '{data.get('remote')}' (fail closed)"
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
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)"
|
||||
)
|
||||
|
||||
# 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():
|
||||
if not data.get("role_pivot_authorized"):
|
||||
raise RuntimeError(
|
||||
"Attempted reviewer mutation from author session without authorized role pivot (fail closed)"
|
||||
)
|
||||
|
||||
# Resolve the project root. MCP clients must launch this script directly with
|
||||
# the venv interpreter (venv/bin/python3) — see the config example above. We do
|
||||
# NOT os.execv() to re-point the interpreter: replacing the process after the
|
||||
@@ -991,6 +1050,12 @@ 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(
|
||||
@@ -1311,6 +1376,12 @@ 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(
|
||||
@@ -2987,6 +3058,25 @@ 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
|
||||
|
||||
# 5. Audit the switch if auditing is on
|
||||
_audit(
|
||||
"activate_profile",
|
||||
@@ -3476,6 +3566,8 @@ def gitea_resolve_task_capability(
|
||||
"STOP: the active profile cannot perform the requested task; "
|
||||
"follow exact_safe_next_action instead of improvising.")
|
||||
|
||||
record_mutation_authority(profile["profile_name"], username, remote if remote in REMOTES else None, task)
|
||||
|
||||
return {
|
||||
"requested_task": task,
|
||||
"required_operation_permission": required_permission,
|
||||
|
||||
+24
-1
@@ -24,7 +24,7 @@ venv_python = os.path.join(PROJECT_ROOT, "venv", "bin", "python3")
|
||||
if os.path.exists(venv_python) and sys.executable != venv_python:
|
||||
os.execv(venv_python, [venv_python] + sys.argv)
|
||||
|
||||
from gitea_auth import get_auth_header, resolve_remote, add_remote_args, api_request, repo_api_url
|
||||
from gitea_auth import get_auth_header, resolve_remote, add_remote_args, api_request, repo_api_url, get_profile
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
@@ -60,6 +60,29 @@ def main(argv=None):
|
||||
|
||||
host, org, repo = resolve_remote(args)
|
||||
|
||||
# ── Mutation Authority context wall check (Issue #194) ──
|
||||
LOCK_FILE = "/tmp/gitea_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)
|
||||
|
||||
# Resolve current CLI profile
|
||||
cli_profile = get_profile().get("profile_name")
|
||||
locked_profile = lock_data.get("current_profile")
|
||||
|
||||
if cli_profile != locked_profile:
|
||||
print(
|
||||
f"Mismatched active profile vs mutation profile (CLI override rejected): "
|
||||
f"CLI profile '{cli_profile}' does not match locked active profile '{locked_profile}' (fail closed)",
|
||||
file=sys.stderr
|
||||
)
|
||||
return 3
|
||||
except Exception as e:
|
||||
print(f"Mutation authority check failed: {e}", file=sys.stderr)
|
||||
return 3
|
||||
|
||||
body = args.body
|
||||
if args.body_file:
|
||||
if args.body_file == "-":
|
||||
|
||||
@@ -37,6 +37,11 @@ from mcp_server import ( # noqa: E402
|
||||
from gitea_auth import get_profile # noqa: E402
|
||||
import gitea_config # noqa: E402
|
||||
|
||||
import mcp_server
|
||||
# Globally disable verification check for existing isolated unit tests
|
||||
_real_verify = mcp_server.verify_mutation_authority
|
||||
mcp_server.verify_mutation_authority = lambda *args, **kwargs: None
|
||||
|
||||
FAKE_AUTH = "Basic dGVzdDp0ZXN0"
|
||||
|
||||
|
||||
@@ -2296,3 +2301,90 @@ class TestIssueCommentPermissionSeparation(unittest.TestCase):
|
||||
"gitea.issue.comment", reviewer["allowed_operations"],
|
||||
reviewer.get("forbidden_operations", []))
|
||||
self.assertTrue(ok)
|
||||
|
||||
|
||||
class TestVerifyMutationAuthority(unittest.TestCase):
|
||||
"""Test verification lock logic under various configurations."""
|
||||
|
||||
def setUp(self):
|
||||
self.patch_profile = patch("mcp_server.get_profile")
|
||||
self.mock_profile = self.patch_profile.start()
|
||||
self.patch_username = patch("mcp_server._authenticated_username")
|
||||
self.mock_username = self.patch_username.start()
|
||||
|
||||
# Restore real function for these tests
|
||||
self._old_verify = mcp_server.verify_mutation_authority
|
||||
mcp_server.verify_mutation_authority = _real_verify
|
||||
|
||||
def tearDown(self):
|
||||
self.patch_profile.stop()
|
||||
self.patch_username.stop()
|
||||
mcp_server.verify_mutation_authority = self._old_verify
|
||||
# Clean up lock file
|
||||
if os.path.exists("/tmp/gitea_mutation_authority.lock"):
|
||||
os.remove("/tmp/gitea_mutation_authority.lock")
|
||||
|
||||
def test_missing_lock_fails_closed(self):
|
||||
if os.path.exists("/tmp/gitea_mutation_authority.lock"):
|
||||
os.remove("/tmp/gitea_mutation_authority.lock")
|
||||
with self.assertRaises(RuntimeError) as ctx:
|
||||
_real_verify("prgs")
|
||||
self.assertIn("lock is missing", str(ctx.exception))
|
||||
|
||||
def test_mismatched_remote_fails(self):
|
||||
with open("/tmp/gitea_mutation_authority.lock", "w", encoding="utf-8") as f:
|
||||
json.dump({
|
||||
"remote": "dadeschools",
|
||||
"current_profile": "prgs-reviewer",
|
||||
"current_identity": "sysadmin"
|
||||
}, f)
|
||||
with self.assertRaises(RuntimeError) as ctx:
|
||||
_real_verify("prgs")
|
||||
self.assertIn("does not match locked remote", str(ctx.exception))
|
||||
|
||||
def test_mismatched_profile_fails(self):
|
||||
with open("/tmp/gitea_mutation_authority.lock", "w", encoding="utf-8") as f:
|
||||
json.dump({
|
||||
"remote": "prgs",
|
||||
"current_profile": "prgs-author",
|
||||
"current_identity": "jcwalker3"
|
||||
}, f)
|
||||
self.mock_profile.return_value = {"profile_name": "prgs-reviewer"}
|
||||
self.mock_username.return_value = "sysadmin"
|
||||
|
||||
with self.assertRaises(RuntimeError) as ctx:
|
||||
_real_verify("prgs")
|
||||
self.assertIn("does not match locked authority", str(ctx.exception))
|
||||
|
||||
def test_author_to_reviewer_pivot_blocked_without_authorization(self):
|
||||
with open("/tmp/gitea_mutation_authority.lock", "w", encoding="utf-8") as f:
|
||||
json.dump({
|
||||
"remote": "prgs",
|
||||
"initial_profile": "prgs-author",
|
||||
"initial_identity": "jcwalker3",
|
||||
"current_profile": "prgs-reviewer",
|
||||
"current_identity": "sysadmin",
|
||||
"role_pivot_authorized": False
|
||||
}, f)
|
||||
self.mock_profile.return_value = {"profile_name": "prgs-reviewer"}
|
||||
self.mock_username.return_value = "sysadmin"
|
||||
|
||||
with self.assertRaises(RuntimeError) as ctx:
|
||||
_real_verify("prgs", required_role="reviewer")
|
||||
self.assertIn("without authorized role pivot", str(ctx.exception))
|
||||
|
||||
def test_allowed_when_match(self):
|
||||
with open("/tmp/gitea_mutation_authority.lock", "w", encoding="utf-8") as f:
|
||||
json.dump({
|
||||
"remote": "prgs",
|
||||
"initial_profile": "prgs-reviewer",
|
||||
"initial_identity": "sysadmin",
|
||||
"current_profile": "prgs-reviewer",
|
||||
"current_identity": "sysadmin",
|
||||
"role_pivot_authorized": False
|
||||
}, f)
|
||||
self.mock_profile.return_value = {"profile_name": "prgs-reviewer"}
|
||||
self.mock_username.return_value = "sysadmin"
|
||||
|
||||
# Should pass without exception
|
||||
_real_verify("prgs")
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
Mocks api_request and credentials.
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
@@ -27,6 +29,11 @@ FAKE_PR_DATA = {
|
||||
|
||||
class TestArgParsing(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.exists_patcher = patch("os.path.exists", return_value=False)
|
||||
self.exists_patcher.start()
|
||||
self.addCleanup(self.exists_patcher.stop)
|
||||
|
||||
@patch("review_pr.get_auth_header", return_value=FAKE_CREDS)
|
||||
def test_missing_pr_number_exits(self, _auth):
|
||||
with self.assertRaises(SystemExit):
|
||||
@@ -35,6 +42,11 @@ class TestArgParsing(unittest.TestCase):
|
||||
|
||||
class TestAPIPayload(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.exists_patcher = patch("os.path.exists", return_value=False)
|
||||
self.exists_patcher.start()
|
||||
self.addCleanup(self.exists_patcher.stop)
|
||||
|
||||
@patch("review_pr.api_request")
|
||||
@patch("review_pr.get_auth_header", return_value=FAKE_CREDS)
|
||||
def test_payload_fields_and_workflow(self, _auth, mock_api):
|
||||
@@ -99,5 +111,70 @@ class TestAPIPayload(unittest.TestCase):
|
||||
self.assertIn("gitea_merge_pr", msg)
|
||||
|
||||
|
||||
class TestMutationAuthorityLock(unittest.TestCase):
|
||||
"""Issue #194: verify that the CLI tool rejects profile overrides when mismatched with lock."""
|
||||
|
||||
@patch("review_pr.get_profile")
|
||||
def test_cli_blocked_on_profile_mismatch(self, mock_get_profile):
|
||||
mock_get_profile.return_value = {"profile_name": "prgs-reviewer"}
|
||||
|
||||
original_exists = os.path.exists
|
||||
def conditional_exists(path):
|
||||
if "gitea_mutation_authority.lock" in str(path):
|
||||
return True
|
||||
return original_exists(path)
|
||||
|
||||
original_open = open
|
||||
def conditional_open(file, *args, **kwargs):
|
||||
if "gitea_mutation_authority.lock" in str(file):
|
||||
return io.StringIO('{"current_profile": "prgs-author"}')
|
||||
return original_open(file, *args, **kwargs)
|
||||
|
||||
from _pytest.monkeypatch import MonkeyPatch
|
||||
import io
|
||||
buf = io.StringIO()
|
||||
monkeypatch = MonkeyPatch()
|
||||
monkeypatch.setattr(sys, "stderr", buf)
|
||||
|
||||
with patch("os.path.exists", side_effect=conditional_exists), \
|
||||
patch("builtins.open", side_effect=conditional_open):
|
||||
try:
|
||||
rc = review_pr.main([
|
||||
"--pr-number", "81", "--event", "APPROVE",
|
||||
])
|
||||
finally:
|
||||
monkeypatch.undo()
|
||||
|
||||
self.assertEqual(rc, 3)
|
||||
msg = buf.getvalue().lower()
|
||||
self.assertIn("cli override rejected", msg)
|
||||
|
||||
@patch("review_pr.get_profile")
|
||||
@patch("review_pr.api_request")
|
||||
@patch("review_pr.get_auth_header", return_value=FAKE_CREDS)
|
||||
def test_cli_allowed_on_profile_match(self, _auth, mock_api, mock_get_profile):
|
||||
mock_get_profile.return_value = {"profile_name": "prgs-reviewer"}
|
||||
mock_api.side_effect = [FAKE_PR_DATA, {}]
|
||||
|
||||
original_exists = os.path.exists
|
||||
def conditional_exists(path):
|
||||
if "gitea_mutation_authority.lock" in str(path):
|
||||
return True
|
||||
return original_exists(path)
|
||||
|
||||
original_open = open
|
||||
def conditional_open(file, *args, **kwargs):
|
||||
if "gitea_mutation_authority.lock" in str(file):
|
||||
return io.StringIO('{"current_profile": "prgs-reviewer"}')
|
||||
return original_open(file, *args, **kwargs)
|
||||
|
||||
with patch("os.path.exists", side_effect=conditional_exists), \
|
||||
patch("builtins.open", side_effect=conditional_open):
|
||||
rc = review_pr.main([
|
||||
"--pr-number", "81", "--event", "APPROVE",
|
||||
])
|
||||
self.assertEqual(rc, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user