feat(preflight): block workspace edits before identity/capability verification (Closes #210)
This commit is contained in:
@@ -157,6 +157,89 @@ PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
import json
|
||||
|
||||
_preflight_whoami_called = False
|
||||
_preflight_capability_called = False
|
||||
_preflight_whoami_violation = False
|
||||
_preflight_capability_violation = False
|
||||
_preflight_resolved_role = None
|
||||
|
||||
def record_preflight_check(type_name: str, resolved_role: str | None = None):
|
||||
"""Record a pre-flight check (whoami or capability) and check for workspace edits."""
|
||||
global _preflight_whoami_called, _preflight_capability_called
|
||||
global _preflight_whoami_violation, _preflight_capability_violation
|
||||
global _preflight_resolved_role
|
||||
|
||||
in_test = "pytest" in sys.modules or "unittest" in sys.modules
|
||||
if os.environ.get("GITEA_TEST_FORCE_DIRTY"):
|
||||
is_dirty = True
|
||||
elif in_test:
|
||||
is_dirty = False
|
||||
else:
|
||||
is_dirty = False
|
||||
try:
|
||||
res = subprocess.run(
|
||||
["git", "status", "--porcelain"],
|
||||
capture_output=True, text=True, cwd=PROJECT_ROOT
|
||||
)
|
||||
for line in res.stdout.splitlines():
|
||||
if line and not line.startswith("??"):
|
||||
is_dirty = True
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if is_dirty:
|
||||
if type_name == "whoami" and not _preflight_whoami_called:
|
||||
_preflight_whoami_violation = True
|
||||
if type_name == "capability" and not _preflight_capability_called:
|
||||
_preflight_capability_violation = True
|
||||
|
||||
if type_name == "whoami":
|
||||
_preflight_whoami_called = True
|
||||
elif type_name == "capability":
|
||||
_preflight_capability_called = True
|
||||
if resolved_role:
|
||||
_preflight_resolved_role = resolved_role
|
||||
|
||||
def verify_preflight_purity(remote: str | None = None):
|
||||
"""Verify that identity and capability were verified prior to edits, and that reviewers made no edits."""
|
||||
in_test = "pytest" in sys.modules or "unittest" in sys.modules
|
||||
if in_test and not os.environ.get("GITEA_TEST_FORCE_DIRTY"):
|
||||
return
|
||||
|
||||
if not _preflight_whoami_called:
|
||||
raise RuntimeError("Pre-flight order violation: Identity (gitea_whoami) has not been verified (fail closed)")
|
||||
if not _preflight_capability_called:
|
||||
raise RuntimeError("Pre-flight order violation: Task capability (gitea_resolve_task_capability) has not been resolved (fail closed)")
|
||||
|
||||
if _preflight_whoami_violation:
|
||||
raise RuntimeError("Pre-flight order violation: Workspace file edits occurred before gitea_whoami verification (fail closed)")
|
||||
if _preflight_capability_violation:
|
||||
raise RuntimeError("Pre-flight order violation: Workspace file edits occurred before gitea_resolve_task_capability verification (fail closed)")
|
||||
|
||||
if os.environ.get("GITEA_TEST_FORCE_DIRTY"):
|
||||
is_dirty = True
|
||||
elif in_test:
|
||||
is_dirty = False
|
||||
else:
|
||||
is_dirty = False
|
||||
try:
|
||||
res = subprocess.run(
|
||||
["git", "status", "--porcelain"],
|
||||
capture_output=True, text=True, cwd=PROJECT_ROOT
|
||||
)
|
||||
for line in res.stdout.splitlines():
|
||||
if line and not line.startswith("??"):
|
||||
is_dirty = True
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if _preflight_resolved_role == "reviewer" and is_dirty:
|
||||
raise RuntimeError("Reviewer role violation: Reviewer profile is forbidden from modifying tracked workspace files (fail closed)")
|
||||
|
||||
from mcp.server.fastmcp import FastMCP # noqa: E402
|
||||
|
||||
from gitea_auth import ( # noqa: E402
|
||||
@@ -471,6 +554,7 @@ def gitea_create_issue(
|
||||
"number": None,
|
||||
"reasons": block_reasons,
|
||||
}
|
||||
verify_preflight_purity(remote)
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
auth = _auth(h)
|
||||
base = repo_api_url(h, o, r)
|
||||
@@ -615,6 +699,7 @@ def gitea_create_pr(
|
||||
Returns:
|
||||
dict with 'number' of the created PR ('url' only with the reveal opt-in).
|
||||
"""
|
||||
verify_preflight_purity(remote)
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
|
||||
# ── Issue Lock Validation (Issue #194 / #196) ──
|
||||
@@ -1388,6 +1473,7 @@ def _evaluate_pr_review_submission(
|
||||
final_review_decision_ready: bool = False,
|
||||
) -> dict:
|
||||
"""Shared gate chain for live submit and dry-run review tools."""
|
||||
verify_preflight_purity(remote)
|
||||
action = (action or "").strip().lower()
|
||||
result = {
|
||||
"requested_action": action,
|
||||
@@ -1763,6 +1849,8 @@ def gitea_edit_pr(
|
||||
if not payload:
|
||||
raise ValueError("At least one field to edit (title, body, state, base) must be provided.")
|
||||
|
||||
verify_preflight_purity(remote)
|
||||
|
||||
# PR closure is a first-class capability, distinct from retitling or
|
||||
# rebasing edits (#216). Gate BEFORE auth/API setup so a blocked close
|
||||
# never touches the network.
|
||||
@@ -1880,6 +1968,7 @@ def gitea_commit_files(
|
||||
Returns:
|
||||
dict with success status and commit/branch information.
|
||||
"""
|
||||
verify_preflight_purity(remote)
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
auth = _auth(h)
|
||||
url = f"{repo_api_url(h, o, r)}/contents"
|
||||
@@ -1974,6 +2063,7 @@ def gitea_merge_pr(
|
||||
reasons/gates passed or blocked, and merge result / merge commit if
|
||||
available. Never secrets.
|
||||
"""
|
||||
verify_preflight_purity(remote)
|
||||
do = (do or "").strip().lower()
|
||||
result = {
|
||||
"performed": False,
|
||||
@@ -2355,6 +2445,7 @@ def gitea_delete_branch(
|
||||
Returns:
|
||||
dict with 'success' and 'message'.
|
||||
"""
|
||||
verify_preflight_purity(remote)
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
auth = _auth(h)
|
||||
import urllib.parse
|
||||
@@ -2386,6 +2477,7 @@ def gitea_close_issue(
|
||||
Returns:
|
||||
dict with 'success' boolean and 'message'.
|
||||
"""
|
||||
verify_preflight_purity(remote)
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
auth = _auth(h)
|
||||
url = f"{repo_api_url(h, o, r)}/issues/{issue_number}"
|
||||
@@ -2684,6 +2776,7 @@ def gitea_create_issue_comment(
|
||||
(permission blocks also carry a structured 'permission_report',
|
||||
#142).
|
||||
"""
|
||||
verify_preflight_purity(remote)
|
||||
gate_reasons = _profile_operation_gate("gitea.issue.comment")
|
||||
reasons = list(gate_reasons)
|
||||
if not (body or "").strip():
|
||||
@@ -3252,6 +3345,7 @@ def gitea_whoami(
|
||||
'email', 'server', 'remote', and 'profile' (safe runtime profile
|
||||
metadata: profile_name + allowed_operations; never the token).
|
||||
"""
|
||||
record_preflight_check("whoami")
|
||||
if remote not in REMOTES:
|
||||
raise ValueError(f"Unknown remote '{remote}'. Choose from: {list(REMOTES)}")
|
||||
h = host or REMOTES[remote]["host"]
|
||||
@@ -3771,6 +3865,7 @@ def gitea_mark_issue(
|
||||
if action not in ("start", "done"):
|
||||
raise ValueError(f"action must be 'start' or 'done', got '{action}'")
|
||||
|
||||
verify_preflight_purity(remote)
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
auth = _auth(h)
|
||||
base = repo_api_url(h, o, r)
|
||||
@@ -3853,6 +3948,7 @@ def gitea_create_label(
|
||||
Returns:
|
||||
dict containing the created label details.
|
||||
"""
|
||||
verify_preflight_purity(remote)
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
auth = _auth(h)
|
||||
base = repo_api_url(h, o, r)
|
||||
@@ -3892,6 +3988,7 @@ def gitea_set_issue_labels(
|
||||
Returns:
|
||||
list of all labels currently applied to the issue.
|
||||
"""
|
||||
verify_preflight_purity(remote)
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
auth = _auth(h)
|
||||
base = repo_api_url(h, o, r)
|
||||
@@ -4162,6 +4259,8 @@ def gitea_resolve_task_capability(
|
||||
required_permission = TASK_MAP[task]["permission"]
|
||||
required_role = TASK_MAP[task]["role"]
|
||||
|
||||
record_preflight_check("capability", required_role)
|
||||
|
||||
profile = get_profile()
|
||||
config = gitea_config.load_config()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user