Merge branch 'prgs/master' into feat/issue-211-single-terminal-review-decision
This commit is contained in:
+303
-11
@@ -17,10 +17,135 @@ import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import json
|
||||
import functools
|
||||
import contextlib
|
||||
import subprocess
|
||||
|
||||
|
||||
# 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
|
||||
|
||||
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,
|
||||
"current_identity": identity,
|
||||
"remote": remote,
|
||||
"task": task,
|
||||
"role_pivot_authorized": False,
|
||||
"role_pivot_record": None,
|
||||
"pid": os.getpid(),
|
||||
}
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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")
|
||||
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}', "
|
||||
f"identity: '{locked_identity}') (fail closed)"
|
||||
)
|
||||
|
||||
# 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)"
|
||||
)
|
||||
|
||||
# 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
|
||||
@@ -46,6 +171,7 @@ from gitea_auth import ( # noqa: E402
|
||||
)
|
||||
import gitea_audit # noqa: E402
|
||||
import gitea_config # noqa: E402
|
||||
import role_session_router # noqa: E402
|
||||
|
||||
|
||||
def _reveal_endpoints() -> bool:
|
||||
@@ -325,6 +451,16 @@ def gitea_create_issue(
|
||||
Returns:
|
||||
dict with 'number' of the created issue ('url' only with the reveal opt-in).
|
||||
"""
|
||||
ok, block_reasons = role_session_router.check_author_mutation_after_reviewer_stop(
|
||||
"create_issue"
|
||||
)
|
||||
if not ok:
|
||||
return {
|
||||
"success": False,
|
||||
"performed": False,
|
||||
"number": None,
|
||||
"reasons": block_reasons,
|
||||
}
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
auth = _auth(h)
|
||||
url = f"{repo_api_url(h, o, r)}/issues"
|
||||
@@ -957,7 +1093,7 @@ def gitea_get_pr_review_feedback(
|
||||
'feedback_not_attempted' True, 'reasons', and 'permission_report' —
|
||||
deliberately distinct from a successful "no reviews yet" result.
|
||||
"""
|
||||
reasons = _issue_comment_gate("gitea.read")
|
||||
reasons = _profile_operation_gate("gitea.read")
|
||||
if reasons:
|
||||
return {
|
||||
"success": False,
|
||||
@@ -1133,6 +1269,18 @@ def _evaluate_pr_review_submission(
|
||||
)
|
||||
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:
|
||||
auth = _auth(h)
|
||||
@@ -1289,11 +1437,20 @@ def gitea_edit_pr(
|
||||
) -> dict:
|
||||
"""Edit an existing pull request on a Gitea repository.
|
||||
|
||||
Closing a PR (``state='closed'``) is a distinct capability from other
|
||||
edits (#216): it requires the ``gitea.pr.close`` operation (resolver
|
||||
task ``close_pr``), fails closed with a structured permission report
|
||||
when the active profile lacks it, and is audited as a distinct
|
||||
``close_pr`` action. Title/body/base edits and reopening stay on the
|
||||
ordinary edit path, so the edit tool can never be used as an untracked
|
||||
close fallback.
|
||||
|
||||
Args:
|
||||
pr_number: The pull request index/number (required).
|
||||
title: New PR title.
|
||||
body: New PR description.
|
||||
state: New state — 'open' or 'closed'.
|
||||
state: New state — 'open' or 'closed'. 'closed' requires the
|
||||
``gitea.pr.close`` capability.
|
||||
base: Target branch name.
|
||||
remote: Known instance — 'dadeschools' or 'prgs'.
|
||||
host: Override the Gitea host.
|
||||
@@ -1301,7 +1458,10 @@ def gitea_edit_pr(
|
||||
repo: Override the repository name.
|
||||
|
||||
Returns:
|
||||
dict with success status and details of the edited PR.
|
||||
dict with success status and details of the edited PR. A close
|
||||
attempt without ``gitea.pr.close`` returns 'success'/'performed'
|
||||
False with 'reasons' and a structured 'permission_report' and makes
|
||||
no API call.
|
||||
"""
|
||||
# Validate inputs BEFORE any auth/profile resolution or API setup: a
|
||||
# no-fields call is a pure validation error and must not depend on
|
||||
@@ -1312,6 +1472,9 @@ def gitea_edit_pr(
|
||||
if body is not None:
|
||||
payload["body"] = body
|
||||
if state is not None:
|
||||
if state not in ("open", "closed"):
|
||||
raise ValueError(
|
||||
f"Invalid state {state!r}: must be 'open' or 'closed' (fail closed).")
|
||||
payload["state"] = state
|
||||
if base is not None:
|
||||
payload["base"] = base
|
||||
@@ -1319,12 +1482,33 @@ def gitea_edit_pr(
|
||||
if not payload:
|
||||
raise ValueError("At least one field to edit (title, body, state, base) must be provided.")
|
||||
|
||||
# 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.
|
||||
closing = payload.get("state") == "closed"
|
||||
if closing:
|
||||
gate_reasons = _profile_operation_gate("gitea.pr.close")
|
||||
if gate_reasons:
|
||||
return {
|
||||
"success": False,
|
||||
"performed": False,
|
||||
"pr_number": pr_number,
|
||||
"requested_state": "closed",
|
||||
"required_permission": "gitea.pr.close",
|
||||
"reasons": gate_reasons,
|
||||
"permission_report": _permission_block_report("gitea.pr.close"),
|
||||
}
|
||||
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
auth = _auth(h)
|
||||
url = f"{repo_api_url(h, o, r)}/pulls/{pr_number}"
|
||||
|
||||
with _audited("edit_pr", host=h, remote=remote, org=o, repo=r,
|
||||
pr_number=pr_number, request_metadata={"fields": sorted(payload)}):
|
||||
request_metadata = {"fields": sorted(payload)}
|
||||
if closing:
|
||||
request_metadata["required_permission"] = "gitea.pr.close"
|
||||
with _audited("close_pr" if closing else "edit_pr",
|
||||
host=h, remote=remote, org=o, repo=r,
|
||||
pr_number=pr_number, request_metadata=request_metadata):
|
||||
data = api_request("PATCH", url, auth, payload)
|
||||
|
||||
cleanup_status = None
|
||||
@@ -1605,6 +1789,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)
|
||||
@@ -2085,13 +2280,14 @@ def _permission_block_report(required_operation: str,
|
||||
return report
|
||||
|
||||
|
||||
def _issue_comment_gate(op: str) -> list[str]:
|
||||
"""Profile permission check for issue-comment tools (#126).
|
||||
def _profile_operation_gate(op: str) -> list[str]:
|
||||
"""Profile permission check for a single gated operation (#126, #216).
|
||||
|
||||
Issue discussion comments are gated separately from the gitea.pr.*
|
||||
review/merge family: listing requires ``gitea.read``, creating requires
|
||||
``gitea.issue.comment``. Returns a list of block reasons (empty = allowed);
|
||||
an unreadable profile fails closed.
|
||||
``gitea.issue.comment``. Closing a PR requires the distinct
|
||||
``gitea.pr.close`` (#216). Returns a list of block reasons (empty =
|
||||
allowed); an unreadable profile fails closed.
|
||||
"""
|
||||
try:
|
||||
profile = get_profile()
|
||||
@@ -2143,7 +2339,7 @@ def gitea_list_issue_comments(
|
||||
'success' False, 'reasons', and a structured 'permission_report'
|
||||
(#142) with no API call made.
|
||||
"""
|
||||
reasons = _issue_comment_gate("gitea.read")
|
||||
reasons = _profile_operation_gate("gitea.read")
|
||||
if reasons:
|
||||
return {"success": False, "issue_number": issue_number,
|
||||
"reasons": reasons,
|
||||
@@ -2205,7 +2401,7 @@ def gitea_create_issue_comment(
|
||||
(permission blocks also carry a structured 'permission_report',
|
||||
#142).
|
||||
"""
|
||||
gate_reasons = _issue_comment_gate("gitea.issue.comment")
|
||||
gate_reasons = _profile_operation_gate("gitea.issue.comment")
|
||||
reasons = list(gate_reasons)
|
||||
if not (body or "").strip():
|
||||
reasons.append("comment body must be a non-empty string")
|
||||
@@ -3203,6 +3399,22 @@ def gitea_activate_profile(
|
||||
after_profile = get_profile()["profile_name"]
|
||||
after_identity = _authenticated_username(h) if h else None
|
||||
|
||||
# 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(
|
||||
"activate_profile",
|
||||
@@ -3520,6 +3732,60 @@ def build_validation_report(commands: list[dict]) -> dict:
|
||||
}
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def gitea_route_task_session(
|
||||
task_type: str,
|
||||
remote: str = "dadeschools",
|
||||
host: str | None = None,
|
||||
) -> dict:
|
||||
"""Pre-task role/session router (#206).
|
||||
|
||||
Classify *task_type* against the active MCP profile before any mutation.
|
||||
Returns ``route_result`` — only ``allowed_current_session`` permits
|
||||
downstream tool use. Reviewer tasks under an author-bound session return
|
||||
``wrong_role_stop`` with no fallback to author mutations.
|
||||
"""
|
||||
task_type = (task_type or "").strip()
|
||||
profile = get_profile()
|
||||
allowed = profile.get("allowed_operations") or []
|
||||
forbidden = profile.get("forbidden_operations") or []
|
||||
active_role = _role_kind(allowed, forbidden)
|
||||
|
||||
if not task_type:
|
||||
return role_session_router.route_task_session(
|
||||
"",
|
||||
active_profile=profile["profile_name"],
|
||||
active_role_kind=active_role,
|
||||
allowed_in_current_session=False,
|
||||
)
|
||||
|
||||
capability = None
|
||||
try:
|
||||
capability = gitea_resolve_task_capability(
|
||||
task=task_type,
|
||||
remote=remote,
|
||||
host=host,
|
||||
)
|
||||
except ValueError:
|
||||
capability = None
|
||||
|
||||
if capability is not None:
|
||||
return role_session_router.route_task_session(
|
||||
task_type,
|
||||
active_profile=capability["active_profile"],
|
||||
active_role_kind=active_role,
|
||||
allowed_in_current_session=capability["allowed_in_current_session"],
|
||||
runtime_switching_supported=capability["runtime_switching_supported"],
|
||||
)
|
||||
|
||||
return role_session_router.route_task_session(
|
||||
task_type,
|
||||
active_profile=profile["profile_name"],
|
||||
active_role_kind=active_role,
|
||||
allowed_in_current_session=False,
|
||||
)
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def gitea_resolve_task_capability(
|
||||
task: str,
|
||||
@@ -3569,6 +3835,14 @@ def gitea_resolve_task_capability(
|
||||
"permission": "gitea.pr.comment",
|
||||
"role": "author",
|
||||
},
|
||||
# PR closure is a first-class capability (#216): distinct from
|
||||
# comment_pr (gitea.pr.comment) and from ordinary PR edits, which
|
||||
# need no dedicated capability. gitea_edit_pr(state='closed') is
|
||||
# gated on the same operation, so no edit-path fallback exists.
|
||||
"close_pr": {
|
||||
"permission": "gitea.pr.close",
|
||||
"role": "author",
|
||||
},
|
||||
"address_pr_change_requests": {
|
||||
"permission": "gitea.branch.push",
|
||||
"role": "author",
|
||||
@@ -3581,6 +3855,18 @@ def gitea_resolve_task_capability(
|
||||
"permission": "gitea.pr.merge",
|
||||
"role": "reviewer",
|
||||
},
|
||||
"blind_pr_queue_review": {
|
||||
"permission": "gitea.pr.review",
|
||||
"role": "reviewer",
|
||||
},
|
||||
"request_changes_pr": {
|
||||
"permission": "gitea.pr.request_changes",
|
||||
"role": "reviewer",
|
||||
},
|
||||
"approve_pr": {
|
||||
"permission": "gitea.pr.approve",
|
||||
"role": "reviewer",
|
||||
},
|
||||
"delete_branch": {
|
||||
"permission": "gitea.branch.delete",
|
||||
"role": "author",
|
||||
@@ -3698,6 +3984,8 @@ def gitea_resolve_task_capability(
|
||||
task,
|
||||
)
|
||||
|
||||
record_mutation_authority(profile["profile_name"], username, remote if remote in REMOTES else None, task)
|
||||
|
||||
return {
|
||||
"requested_task": task,
|
||||
"required_operation_permission": required_permission,
|
||||
@@ -3718,4 +4006,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