fix(session): pin immutable MCP context; ban cross-host profile substitution (Closes #714)

Capability resolution and mutation gates no longer auto-switch profiles.
Session profile/remote/host/identity are bound after pin or first seed,
and drift or cross-host resolution fails closed before writes.

Co-Authored-By: Grok <[email protected]>
This commit is contained in:
2026-07-14 23:05:41 -04:00
co-authored by Grok
parent 1eafb757a9
commit 632c568865
4 changed files with 1164 additions and 165 deletions
+360 -130
View File
@@ -1118,6 +1118,34 @@ import workflow_scope_guard # noqa: E402 # #683 production scope / force-on gu
import stable_branch_push_guard # noqa: E402
import remote_repo_guard # noqa: E402
import issue_claim_heartbeat # noqa: E402
import session_context_binding as session_ctx # noqa: E402 # #714 immutable session context
def _seed_session_context(
*,
profile: dict,
remote: str | None,
host: str | None,
identity: str | None,
repository: str | None = None,
org: str | None = None,
source: str = "seed",
) -> dict:
"""Seed/rebind immutable session context with env/override awareness (#714)."""
expected = (profile.get("username") or "").strip() or None
return session_ctx.seed_session_context_if_unbound(
profile_name=profile.get("profile_name") or "",
remote=remote,
host=host,
identity=identity,
repository=repository,
org=org,
role_kind=_profile_role_kind(profile),
expected_username=expected,
source=source,
active_profile_override=gitea_config._active_profile_override,
env_profile=(os.environ.get("GITEA_MCP_PROFILE") or "").strip() or None,
)
import issue_work_duplicate_gate # noqa: E402
import issue_workflow_labels # noqa: E402
import reviewer_pr_lease # noqa: E402
@@ -1846,61 +1874,44 @@ def _authenticated_username(host: str):
return user
def _ensure_matching_profile(required_permission: str, required_role: str, remote: str | None, host: str | None = None) -> str | None:
"""Check if the active profile is allowed to perform *required_permission*.
If not, automatically switch to the first matching usable configured profile.
def _ensure_matching_profile(
required_permission: str,
required_role: str,
remote: str | None,
host: str | None = None,
) -> str | None:
"""Return the active profile name only when it is allowed for *permission*.
#714: never silently switch profiles (including cross-host substitution).
Capability resolution and mutation gates evaluate only the active profile
for the requested remote. Explicit ``gitea_activate_profile`` is the sole
in-process switch path.
"""
del required_role, host # kept for call-site compatibility
try:
profile = get_profile()
except Exception:
return None
active_profile = profile.get("profile_name")
# Cross-host denial: mdcps profile cannot serve a prgs remote (and vice versa).
config = None
try:
config = gitea_config.load_config()
except Exception:
config = None
contexts = (config or {}).get("contexts") if config else None
remote_ok = session_ctx.profile_allowed_for_remote(
profile, remote, REMOTES, contexts=contexts
)
if remote_ok.get("block"):
return None
active_allowed = profile.get("allowed_operations") or []
active_forbidden = profile.get("forbidden_operations") or []
allowed, _ = gitea_config.check_operation(required_permission, active_allowed, active_forbidden)
allowed, _ = gitea_config.check_operation(
required_permission, active_allowed, active_forbidden
)
if allowed:
return active_profile
# Try to find a matching usable profile in config
if gitea_config.is_runtime_switching_enabled():
config = gitea_config.load_config()
if config and "profiles" in config:
for p_name, p_data in config["profiles"].items():
p_allowed = p_data.get("allowed_operations") or []
p_forbidden = p_data.get("forbidden_operations") or []
p_allowed_n = []
for op in p_allowed:
try:
p_allowed_n.append(gitea_config.normalize_operation(op))
except Exception:
pass
p_forbidden_n = []
for op in p_forbidden:
try:
p_forbidden_n.append(gitea_config.normalize_operation(op))
except Exception:
pass
ok, _ = gitea_config.check_operation(required_permission, p_allowed_n, p_forbidden_n)
if ok:
# Verify credentials/token are available
try:
tok = gitea_config.resolve_token(p_data)
if tok:
# Perform automatic switch
gitea_config._active_profile_override = p_name
h = host or (REMOTES.get(remote, {}).get("host") if remote in REMOTES else None)
if h:
_IDENTITY_CACHE.pop(h, None)
username = _authenticated_username(h) if h else None
# Update mutation authority
global _MUTATION_AUTHORITY
if _MUTATION_AUTHORITY is not None:
_MUTATION_AUTHORITY["current_profile"] = p_name
_MUTATION_AUTHORITY["current_identity"] = username
_MUTATION_AUTHORITY["role_pivot_authorized"] = True
return p_name
except Exception:
pass
return None
@@ -1922,6 +1933,12 @@ def _audit(action: str, *, host, remote, result, org=None, repo=None,
if mutation_task:
ns_ctx = role_namespace_gate.mutation_audit_context(
mutation_task, profile, remote=remote, repository=repo)
# #714: always record the bound session context at mutation time.
session_audit = session_ctx.mutation_context_audit_fields()
if isinstance(request_metadata, dict):
request_metadata = {**request_metadata, **session_audit}
elif request_metadata is None:
request_metadata = dict(session_audit)
event = gitea_audit.build_event(
action=action,
result=result,
@@ -7499,48 +7516,13 @@ def _role_for_operation(op: str) -> str | None:
def _try_auto_switch_for_operation(op: str, host: str | None = None) -> bool:
"""Try to find a profile in config that allows op and has valid credentials.
"""#714: automatic profile substitution is removed (fail closed).
If found, switch to it, clear identity cache, and return True.
Otherwise return False.
Always returns False. Callers must use explicit ``gitea_activate_profile``
to change roles; capability and mutation gates evaluate only the active
profile. Parameters retained for call-site compatibility.
"""
role = _role_for_operation(op)
if not role:
return False
if not gitea_config.is_runtime_switching_enabled():
return False
config = gitea_config.load_config()
if not config or "profiles" not in config:
return False
for p_name, p_data in config["profiles"].items():
# Role classification matching
p_role = p_data.get("role") or _role_kind(p_data.get("allowed_operations", []), p_data.get("forbidden_operations", []))
if p_role != role:
continue
p_allowed = p_data.get("allowed_operations") or []
p_forbidden = p_data.get("forbidden_operations") or []
p_allowed_n = []
for op_val in p_allowed:
try:
p_allowed_n.append(gitea_config.normalize_operation(op_val))
except Exception:
pass
p_forbidden_n = []
for op_val in p_forbidden:
try:
p_forbidden_n.append(gitea_config.normalize_operation(op_val))
except Exception:
pass
ok, _ = gitea_config.check_operation(op, p_allowed_n, p_forbidden_n)
if ok:
try:
tok = gitea_config.resolve_token(p_data)
if tok:
gitea_config._active_profile_override = p_name
_IDENTITY_CACHE.clear()
return True
except Exception:
pass
del op, host
return False
@@ -7607,6 +7589,102 @@ def _profile_operation_gate(op: str) -> list[str]:
return [f"profile is not allowed to {op}"]
def _session_context_mutation_block(
*,
remote: str | None,
host: str | None = None,
org: str | None = None,
repo: str | None = None,
username: str | None = None,
**extra_fields,
) -> dict | None:
"""#714: fail closed on session context / identity / cross-host drift."""
try:
profile = get_profile()
except Exception as exc:
return {
"success": False,
"performed": False,
"reasons": [
f"profile could not be resolved (fail closed): {_redact(str(exc))}"
],
"blocker_kind": "session_context",
**extra_fields,
}
profile_name = profile.get("profile_name")
expected = (profile.get("username") or "").strip() or None
h = host or (REMOTES.get(remote or "", {}).get("host") if remote else None)
identity = username
if identity is None and h:
try:
identity = _authenticated_username(h)
except Exception:
identity = None
config = None
try:
config = gitea_config.load_config()
except Exception:
config = None
contexts = (config or {}).get("contexts") if config else None
remote_gate = session_ctx.profile_allowed_for_remote(
profile, remote, REMOTES, contexts=contexts
)
reasons: list[str] = list(remote_gate.get("reasons") or [])
id_gate = session_ctx.assess_identity_match(
authenticated=identity, expected_username=expected
)
reasons.extend(id_gate.get("reasons") or [])
# Seed if unbound so subsequent tools share one context; then assess.
_seed_session_context(
profile=profile,
remote=remote,
host=h,
identity=identity,
repository=repo,
org=org,
source="mutation-gate-seed",
)
ctx_gate = session_ctx.assess_session_context(
profile_name=profile_name,
remote=remote,
host=h,
identity=identity,
repository=repo,
org=org,
expected_username=expected,
require_bound=True,
)
reasons.extend(ctx_gate.get("reasons") or [])
# De-dupe while preserving order
seen: set[str] = set()
uniq: list[str] = []
for r in reasons:
if r not in seen:
seen.add(r)
uniq.append(r)
if not uniq:
return None
blocked = {
"success": False,
"performed": False,
"reasons": uniq,
"blocker_kind": "session_context",
"session_context_audit": session_ctx.mutation_context_audit_fields(),
"exact_next_action": (
"BLOCKED + DIAGNOSE: session profile/remote/host/identity context "
"is inconsistent or unauthorized for this mutation. Re-pin the "
"correct profile with gitea_activate_profile, re-verify with "
"gitea_whoami for the intended remote, and do not use cross-host "
"fallback profiles."
),
}
blocked.update(extra_fields)
return blocked
def _profile_permission_block(required_operation: str, **extra_fields) -> dict | None:
"""Structured permission denial for gated tools (#69, #142).
@@ -7616,8 +7694,21 @@ def _profile_permission_block(required_operation: str, **extra_fields) -> dict |
req_role = "reviewer" if any(required_operation.startswith(p) for p in (
"gitea.pr.approve", "gitea.pr.merge", "gitea.pr.request_changes", "gitea.pr.review"
)) else "author"
# #714: evaluate active profile only — never auto-switch.
_ensure_matching_profile(required_operation, req_role, extra_fields.get("remote"))
ctx_block = _session_context_mutation_block(
remote=extra_fields.get("remote"),
host=extra_fields.get("host"),
org=extra_fields.get("org"),
repo=extra_fields.get("repo"),
number=extra_fields.get("number"),
issue_number=extra_fields.get("issue_number"),
pr_number=extra_fields.get("pr_number"),
)
if ctx_block is not None:
return ctx_block
reasons = _profile_operation_gate(required_operation)
if not reasons:
return None
@@ -7626,6 +7717,7 @@ def _profile_permission_block(required_operation: str, **extra_fields) -> dict |
"performed": False,
"reasons": reasons,
"permission_report": _permission_block_report(required_operation),
"session_context_audit": session_ctx.mutation_context_audit_fields(),
}
blocked.update(extra_fields)
return blocked
@@ -7635,8 +7727,21 @@ def _namespace_mutation_block(mutation_task: str, **extra_fields) -> dict | None
"""Reviewer/author namespace alignment gate (#209)."""
required_permission = task_capability_map.required_permission(mutation_task)
required_role = task_capability_map.required_role(mutation_task)
# #714: evaluate active profile only — never auto-switch.
_ensure_matching_profile(required_permission, required_role, extra_fields.get("remote"))
ctx_block = _session_context_mutation_block(
remote=extra_fields.get("remote"),
host=extra_fields.get("host"),
org=extra_fields.get("org"),
repo=extra_fields.get("repo"),
number=extra_fields.get("number"),
issue_number=extra_fields.get("issue_number"),
pr_number=extra_fields.get("pr_number"),
)
if ctx_block is not None:
return ctx_block
try:
profile = get_profile()
except Exception as exc:
@@ -9621,9 +9726,22 @@ def gitea_whoami(
# name is the addressing surface; 'server' appears only under the
# GITEA_MCP_REVEAL_ENDPOINTS admin opt-in.
profile = get_profile()
identity = data.get("login")
expected_username = (profile.get("username") or "").strip() or None
# #714: seed immutable session context so later tools share one pin.
_seed_session_context(
profile=profile,
remote=remote,
host=h,
identity=identity,
source="gitea_whoami",
)
id_match = session_ctx.assess_identity_match(
authenticated=identity, expected_username=expected_username
)
result = {
"authenticated": True,
"username": data.get("login"),
"username": identity,
"display_name": data.get("full_name") or None,
"user_id": data.get("id"),
"email": data.get("email") or None,
@@ -9640,7 +9758,11 @@ def gitea_whoami(
"execution_profile": profile.get("execution_profile"),
"audit_label": profile.get("audit_label"),
"auth_source_type": profile.get("auth_source_type"),
"expected_username": expected_username,
},
"session_context_audit": session_ctx.mutation_context_audit_fields(),
"identity_match": not id_match.get("block"),
"identity_match_reasons": id_match.get("reasons") or [],
}
if _reveal_endpoints():
result["server"] = gitea_url(h, "").rstrip("/")
@@ -9766,14 +9888,32 @@ _RUNTIME_CAPABILITY_TASKS = (
def _matching_configured_profiles(
config: dict | None,
required_permission: str,
remote: str | None = None,
) -> list[str]:
"""Profile names that allow *required_permission* (redacted metadata only)."""
"""Profile names that allow *required_permission* (redacted metadata only).
#714: when *remote* is provided, only profiles bound to that remote's host
are returned a dadeschools request never lists prgs profiles.
"""
if not config or "profiles" not in config:
return []
contexts = config.get("contexts") or {}
remote_ok_names: set[str] | None = None
if remote:
remote_ok_names = set(
session_ctx.filter_profiles_for_remote(config, remote, REMOTES)
)
matches: list[str] = []
for p_name, p_data in config["profiles"].items():
if not p_data.get("enabled", True):
continue
if remote_ok_names is not None and p_name not in remote_ok_names:
continue
# Also require host/context match when remote given (defensive).
if remote and not session_ctx.profile_matches_remote(
p_data, remote, REMOTES, contexts=contexts
):
continue
p_allowed = p_data.get("allowed_operations") or []
p_forbidden = p_data.get("forbidden_operations") or []
p_allowed_n = []
@@ -9800,8 +9940,9 @@ def _build_runtime_task_capabilities(
allowed: list[str],
forbidden: list[str],
config: dict | None,
remote: str | None = None,
) -> dict:
"""Per-task capability summary for role-aware runtime context (#139)."""
"""Per-task capability summary for role-aware runtime context (#139, #714)."""
task_entries = []
flags: dict[str, bool] = {}
flag_keys = {
@@ -9825,7 +9966,7 @@ def _build_runtime_task_capabilities(
"required_role_kind": task_capability_map.required_role(task),
"allowed_in_current_session": allowed_here,
"matching_configured_profiles": _matching_configured_profiles(
config, permission
config, permission, remote=remote
),
}
task_entries.append(entry)
@@ -10277,8 +10418,9 @@ def gitea_get_runtime_context(
"or ask the operator to update GITEA_MCP_PROFILE to a reviewer profile."
)
# #714: filter matching profiles by requested remote when building capability summary
session_capabilities = _build_runtime_task_capabilities(
allowed, forbidden, config
allowed, forbidden, config, remote=remote if remote in REMOTES else None
)
preflight = assess_preflight_status(worktree_path)
@@ -10289,6 +10431,16 @@ def gitea_get_runtime_context(
f"Blocked: {'; '.join(preflight['preflight_block_reasons'])}"
)
expected_username = (profile.get("username") or "").strip() or None
h_rt = host or (REMOTES.get(remote, {}).get("host") if remote in REMOTES else None)
_seed_session_context(
profile=profile,
remote=remote if remote in REMOTES else None,
host=h_rt,
identity=username,
source="gitea_get_runtime_context",
)
result = {
"active_profile": profile["profile_name"],
"authenticated_username": username,
@@ -10299,6 +10451,8 @@ def gitea_get_runtime_context(
"forbidden_operations": forbidden,
"runtime_switching_supported": switching,
"profile_mode": profile_mode,
"session_context_audit": session_ctx.mutation_context_audit_fields(),
"auto_profile_substitution": False,
"review_merge_allowed": review_merge_allowed,
"review_merge_blocked_reasons": blocked_reasons,
"suggested_fix": suggested_fix,
@@ -10660,8 +10814,10 @@ def gitea_activate_profile(
_IDENTITY_CACHE.pop(h, None)
# 4. Resolve fresh identity
after_profile = get_profile()["profile_name"]
after_profile_data = get_profile()
after_profile = after_profile_data["profile_name"]
after_identity = _authenticated_username(h) if h else None
expected_username = (after_profile_data.get("username") or "").strip() or 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
@@ -10676,15 +10832,32 @@ def gitea_activate_profile(
"from_identity": before_identity,
"to_identity": after_identity,
}
_MUTATION_AUTHORITY["remote"] = remote
if os.environ.get(SESSION_PROFILE_LOCK_ENV) and after_profile:
os.environ[SESSION_PROFILE_LOCK_ENV] = after_profile
# 4.6 #714: re-bind immutable session context after explicit activation.
session_ctx.bind_session_context(
profile_name=after_profile or profile_name,
remote=remote,
host=h,
identity=after_identity,
role_kind=_profile_role_kind(after_profile_data),
expected_username=expected_username,
source="gitea_activate_profile",
)
# 5. Audit the switch if auditing is on
_audit(
"activate_profile",
host=h,
remote=remote,
result={"success": True, "before": before_profile, "after": after_profile},
result={
"success": True,
"before": before_profile,
"after": after_profile,
"session_context": session_ctx.mutation_context_audit_fields(),
},
username=after_identity,
)
@@ -10695,6 +10868,8 @@ def gitea_activate_profile(
"before_identity": before_identity,
"after_profile": after_profile,
"after_identity": after_identity,
"session_context_audit": session_ctx.mutation_context_audit_fields(),
"auto_profile_substitution": False,
}
@@ -11795,21 +11970,44 @@ def gitea_resolve_task_capability(
record_preflight_check("capability", required_role, resolved_task=task)
# Try automatic dispatch switching
_ensure_matching_profile(required_permission, required_role, remote, host)
# #714: never auto-switch profiles during capability resolution.
profile = get_profile()
config = gitea_config.load_config()
contexts = (config or {}).get("contexts") if config else None
h = host or (REMOTES.get(remote, {}).get("host") if remote in REMOTES else None)
username = _authenticated_username(h) if h else None
expected_username = (profile.get("username") or "").strip() or None
# Seed / re-check immutable session context for consistent multi-tool reads.
_seed_session_context(
profile=profile,
remote=remote,
host=h,
identity=username,
source="resolve_task_capability",
)
ctx_assess = session_ctx.assess_session_context(
profile_name=profile.get("profile_name"),
remote=remote,
host=h,
identity=username,
expected_username=expected_username,
require_bound=False,
)
id_assess = session_ctx.assess_identity_match(
authenticated=username, expected_username=expected_username
)
remote_assess = session_ctx.profile_allowed_for_remote(
profile, remote, REMOTES, contexts=contexts
)
# Load active permissions
active_allowed = profile.get("allowed_operations") or []
active_forbidden = profile.get("forbidden_operations") or []
active_role_kind = _profile_role_kind(profile)
# Check if allowed in current session
# Check if allowed in current session (active profile only — #714)
permission_allowed_in_current_session, _ = gitea_config.check_operation(
required_permission, active_allowed, active_forbidden
)
@@ -11824,8 +12022,15 @@ def gitea_resolve_task_capability(
f"{required_role} task '{task}' even if nearby permissions are "
"present (fail closed)."
)
cross_host_block = bool(remote_assess.get("block"))
identity_block = bool(id_assess.get("block"))
drift_block = bool(ctx_assess.get("block"))
allowed_in_current_session = (
permission_allowed_in_current_session and role_matches_current_session
permission_allowed_in_current_session
and role_matches_current_session
and not cross_host_block
and not identity_block
and not drift_block
)
switching = gitea_config.is_runtime_switching_enabled()
@@ -11834,33 +12039,19 @@ def gitea_resolve_task_capability(
restart_required = False
reason_msg = None
# Find matching configured profiles
matching_profiles = []
if config and "profiles" in config:
for p_name, p_data in config["profiles"].items():
p_allowed = p_data.get("allowed_operations") or []
p_forbidden = p_data.get("forbidden_operations") or []
p_allowed_n = []
for op in p_allowed:
try:
p_allowed_n.append(gitea_config.normalize_operation(op))
except Exception:
pass
p_forbidden_n = []
for op in p_forbidden:
try:
p_forbidden_n.append(gitea_config.normalize_operation(op))
except Exception:
pass
ok, _ = gitea_config.check_operation(required_permission, p_allowed_n, p_forbidden_n)
# Matching profiles: same remote/host only (#714) — advisory, never activated.
matching_profiles = _matching_configured_profiles(
config, required_permission, remote=remote
)
# Role filter for exclusive tasks
if config and "profiles" in config and task in role_exclusive_tasks:
filtered = []
for p_name in matching_profiles:
p_data = (config.get("profiles") or {}).get(p_name) or {}
p_role = (p_data.get("role") or "").strip()
p_role_ok = (
task not in role_exclusive_tasks
or not p_role
or p_role == required_role
)
if ok and p_role_ok:
matching_profiles.append(p_name)
if not p_role or p_role == required_role:
filtered.append(p_name)
matching_profiles = filtered
configured = len(matching_profiles) > 0
available_in_session = allowed_in_current_session
@@ -11876,16 +12067,35 @@ def gitea_resolve_task_capability(
)
if not allowed_in_current_session:
if configured and switching:
restart_required = True
deny_parts: list[str] = []
if cross_host_block:
deny_parts.extend(remote_assess.get("reasons") or [])
if identity_block:
deny_parts.extend(id_assess.get("reasons") or [])
if drift_block:
deny_parts.extend(ctx_assess.get("reasons") or [])
if not permission_allowed_in_current_session and not deny_parts:
deny_parts.append(
f"Active profile '{profile.get('profile_name')}' is not allowed "
f"to '{required_permission}' (no substitute profile activated; fail closed)."
)
if role_mismatch_reason:
deny_parts.append(role_mismatch_reason)
if deny_parts:
reason_msg = "; ".join(deny_parts)
elif configured and switching:
# Same-remote profile exists but is not the active one — explicit switch only.
restart_required = False
available_in_session = False
reason_msg = (
f"{required_role.capitalize()} profile exists but MCP server "
"was added after session startup and is not attached."
f"Active profile cannot perform '{required_permission}'. "
f"Same-remote matching profiles (advisory only, not activated): "
f"{matching_profiles}."
)
elif not configured:
reason_msg = (
f"No profile configured with permission '{required_permission}'."
f"No same-remote profile configured with permission "
f"'{required_permission}' for remote '{remote}'."
)
elif role_mismatch_reason:
reason_msg = role_mismatch_reason
@@ -11893,9 +12103,22 @@ def gitea_resolve_task_capability(
next_safe_action = "None; ready for operations."
if not allowed_in_current_session:
if switching:
if cross_host_block or identity_block or drift_block:
different_namespace_required = False
next_safe_action = f"Switch to a profile that has the required permission by calling gitea_activate_profile (matching configured profiles: {matching_profiles})."
next_safe_action = (
"BLOCKED + DIAGNOSE: session context/host/identity is inconsistent "
"or the active profile cannot serve this remote. Re-pin the correct "
"profile with gitea_activate_profile for the intended remote, verify "
"with gitea_whoami, and do not use cross-host profile substitution."
)
elif switching:
different_namespace_required = False
next_safe_action = (
f"Switch explicitly with gitea_activate_profile to a same-remote "
f"profile that allows '{required_permission}' "
f"(matching configured profiles: {matching_profiles}). "
"Capability resolution never auto-substitutes profiles (#714)."
)
else:
different_namespace_required = True
if required_role == "reviewer":
@@ -11980,6 +12203,13 @@ def gitea_resolve_task_capability(
"runtime_switching_supported": switching,
"different_mcp_namespace_required": different_namespace_required,
"exact_safe_next_action": next_safe_action,
# #714: immutable session context proof (must match whoami / runtime).
"requested_remote": remote,
"resolved_host": h,
"session_context_audit": session_ctx.mutation_context_audit_fields(),
"profile_remote_compatible": not cross_host_block,
"identity_match": not identity_block,
"auto_profile_substitution": False,
}
if reason_msg:
result["reason"] = reason_msg