Merge pull request 'fix(author bootstrap): restore missing runtime identity and session helpers (Closes #943)' (#944) from fix/issue-943-runtime-context-helpers into master
This commit was merged in pull request #944.
This commit is contained in:
+355
-3
@@ -3665,6 +3665,293 @@ def _authenticated_username(host: str):
|
||||
return user
|
||||
|
||||
|
||||
# #943 review 622 F3/F4: one coherent authority snapshot per mutation claim.
|
||||
#
|
||||
# The reviewed implementation read the identity from the pinned #714 session
|
||||
# context and the profile from the live ``get_profile()``, so a sanctioned
|
||||
# rebind could produce a claimant pair whose two halves came from different
|
||||
# snapshots — and that pair is written durably into the issue lock. The
|
||||
# canonical pairing is ``record_mutation_authority``: profile from
|
||||
# ``get_profile()``, identity from ``_authenticated_username(host)``. This
|
||||
# resolver reproduces that pairing, and uses the pinned session context only for
|
||||
# drift detection, never as a value source.
|
||||
_AUTHORITY_PROFILE_UNRESOLVED = "authority_profile_unresolved"
|
||||
_AUTHORITY_IDENTITY_UNRESOLVED = "authority_identity_unresolved"
|
||||
_AUTHORITY_IDENTITY_DRIFT = "authority_identity_drift"
|
||||
_AUTHORITY_PROFILE_DRIFT = "authority_profile_drift"
|
||||
|
||||
|
||||
def _active_mutation_authority(host: str | None) -> dict:
|
||||
"""Resolve one coherent (identity, profile) authority pair, or a refusal.
|
||||
|
||||
Both halves come from the same live snapshot. The immutable #714 session
|
||||
context is consulted only to detect drift: when it disagrees with the live
|
||||
snapshot the result is a fail-closed refusal, never a silently blended pair.
|
||||
|
||||
Returns a dict with ``ok`` True plus ``identity``/``profile_name``, or ``ok``
|
||||
False plus ``reason_code``, ``reasons`` and ``expected``/``actual`` when a
|
||||
drift or resolution failure is detected. Never raises for an unresolved
|
||||
profile: the caller converts the refusal into a structured author block so
|
||||
reason code, retryability and transport survival are preserved (F4).
|
||||
"""
|
||||
try:
|
||||
profile = get_profile() or {}
|
||||
except (RuntimeError, ValueError, TypeError, KeyError, OSError) as exc:
|
||||
# Narrow, and never a silent fallback to a previously cached name: an
|
||||
# unresolvable profile is a fail-closed condition, matching
|
||||
# record_mutation_authority's "active profile unresolved (fail closed)".
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _AUTHORITY_PROFILE_UNRESOLVED,
|
||||
"reasons": [
|
||||
"active profile could not be resolved: "
|
||||
f"{_redact(str(exc))} (fail closed)"
|
||||
],
|
||||
}
|
||||
profile_name = (profile.get("profile_name") or "").strip()
|
||||
if not profile_name:
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _AUTHORITY_PROFILE_UNRESOLVED,
|
||||
"reasons": [
|
||||
"active profile carries no profile_name (fail closed)"
|
||||
],
|
||||
}
|
||||
|
||||
identity = ""
|
||||
if host:
|
||||
identity = (_authenticated_username(host) or "").strip()
|
||||
if not identity:
|
||||
# A profile's expected_username is configuration, not proof of an
|
||||
# authenticated actor, so it is never substituted here.
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _AUTHORITY_IDENTITY_UNRESOLVED,
|
||||
"reasons": [
|
||||
"authenticated identity could not be resolved for the active "
|
||||
"host (fail closed); call gitea_whoami and retry"
|
||||
],
|
||||
}
|
||||
|
||||
ctx = session_ctx.get_session_context() or {}
|
||||
pinned_identity = (ctx.get("identity") or "").strip()
|
||||
pinned_profile = (ctx.get("profile_name") or "").strip()
|
||||
if pinned_identity and pinned_identity != identity:
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _AUTHORITY_IDENTITY_DRIFT,
|
||||
"reasons": [
|
||||
"live authenticated identity disagrees with the bound session "
|
||||
"context identity (fail closed)"
|
||||
],
|
||||
"expected": pinned_identity,
|
||||
"actual": identity,
|
||||
}
|
||||
if pinned_profile and pinned_profile != profile_name:
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _AUTHORITY_PROFILE_DRIFT,
|
||||
"reasons": [
|
||||
"live active profile disagrees with the bound session context "
|
||||
"profile (fail closed)"
|
||||
],
|
||||
"expected": pinned_profile,
|
||||
"actual": profile_name,
|
||||
}
|
||||
return {
|
||||
"ok": True,
|
||||
"identity": identity,
|
||||
"profile_name": profile_name,
|
||||
"session_context_bound": bool(pinned_identity or pinned_profile),
|
||||
}
|
||||
|
||||
|
||||
def _active_username(host: str | None = None) -> str | None:
|
||||
"""Authenticated identity for the active mutation authority, else None.
|
||||
|
||||
Refuses unbound, blank and whitespace-only identities, and never substitutes
|
||||
a profile's ``expected_username`` for an authenticated one.
|
||||
"""
|
||||
authority = _active_mutation_authority(host)
|
||||
return authority.get("identity") if authority.get("ok") else None
|
||||
|
||||
|
||||
def _active_profile_name(host: str | None = None) -> str | None:
|
||||
"""Active profile name for the mutation authority, else None.
|
||||
|
||||
Shares the single snapshot with :func:`_active_username`, so the two can
|
||||
never describe different authority states.
|
||||
"""
|
||||
authority = _active_mutation_authority(host)
|
||||
return authority.get("profile_name") if authority.get("ok") else None
|
||||
|
||||
|
||||
# #943 review 622 B1: the workflow session that owns the work — never a
|
||||
# process-lifetime or PID-derived value.
|
||||
#
|
||||
# The reviewed implementation minted "<profile>-<pid>-<hex>" once per process.
|
||||
# The MCP daemon outlives every task it serves, so that identifier conflates
|
||||
# sequential author tasks and can never equal the control-plane session that
|
||||
# owns an allocator-created lease; ``_verify_assignment_and_lease_ids`` therefore
|
||||
# refused with lease_session_mismatch on the canonical allocated path.
|
||||
# ``issue_lock_store.mint_task_session_id`` states the rule directly: an
|
||||
# ownership key "deliberately contains no process identifier", because the PID
|
||||
# "cannot identify *which* task holds a claim".
|
||||
_SESSION_UNVERIFIED = "workflow_session_unverified"
|
||||
_SESSION_REQUIRED = "workflow_session_required_for_allocated_work"
|
||||
_SESSION_LOCK_OWNER_MISMATCH = "issue_lock_owner_mismatch"
|
||||
|
||||
|
||||
def _resolve_owner_workflow_session(
|
||||
*,
|
||||
issue_number: int,
|
||||
assignment_id: str | None,
|
||||
lease_id: str | None,
|
||||
session_id: str | None,
|
||||
identity: str,
|
||||
profile_name: str,
|
||||
remote: str,
|
||||
org: str | None,
|
||||
repo: str | None,
|
||||
) -> dict:
|
||||
"""Resolve the authoritative workflow session that owns this work.
|
||||
|
||||
Precedence, each step fail-closed:
|
||||
|
||||
1. An explicit ``session_id`` is verified against the control-plane
|
||||
``sessions`` table: it must exist, be active, and match this role and
|
||||
profile. An unverifiable identifier is refused, never trusted.
|
||||
2. Otherwise an existing issue lock for this issue supplies its per-task
|
||||
``task_session_id``, but only when the lock's recorded claimant matches
|
||||
the resolved authority pair.
|
||||
3. Otherwise, when allocator identifiers are supplied, the request is
|
||||
refused: ownership of an allocated assignment cannot be established
|
||||
without its owning session, and the presence of the identifiers is not
|
||||
itself evidence of ownership.
|
||||
4. Otherwise — no allocator identifiers and no existing lock — a fresh
|
||||
per-task key is minted through the canonical
|
||||
``issue_lock_store.mint_task_session_id``. It carries no process
|
||||
identifier and is never memoised, so sequential tasks on one daemon never
|
||||
share an owner.
|
||||
|
||||
Whether the resolved session actually owns a supplied lease stays the
|
||||
decision of ``author_issue_bootstrap._verify_assignment_and_lease_ids``;
|
||||
this function never pre-empts, duplicates or bypasses that gate.
|
||||
"""
|
||||
declared = (session_id or "").strip()
|
||||
if declared:
|
||||
db, errs = _control_plane_db_or_error()
|
||||
if db is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _SESSION_UNVERIFIED,
|
||||
"reasons": errs,
|
||||
}
|
||||
try:
|
||||
rows = db.list_sessions(statuses=("active",))
|
||||
except Exception as exc: # noqa: BLE001 — surface structured
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _SESSION_UNVERIFIED,
|
||||
"reasons": [
|
||||
"could not read control-plane sessions to verify "
|
||||
f"session_id: {_redact(str(exc))} (fail closed)"
|
||||
],
|
||||
}
|
||||
match = next(
|
||||
(r for r in rows if str(r.get("session_id") or "") == declared), None
|
||||
)
|
||||
if match is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _SESSION_UNVERIFIED,
|
||||
"reasons": [
|
||||
f"session_id '{declared}' is not an active control-plane "
|
||||
"session (fail closed)"
|
||||
],
|
||||
}
|
||||
row_role = (match.get("role") or "").strip().lower()
|
||||
row_profile = (match.get("profile") or "").strip()
|
||||
if row_role and row_role != "author":
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _SESSION_UNVERIFIED,
|
||||
"reasons": [
|
||||
f"session_id '{declared}' is recorded for role "
|
||||
f"'{row_role}', not author (fail closed)"
|
||||
],
|
||||
"expected": "author",
|
||||
"actual": row_role,
|
||||
}
|
||||
if row_profile and row_profile != profile_name:
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _SESSION_UNVERIFIED,
|
||||
"reasons": [
|
||||
f"session_id '{declared}' is recorded for profile "
|
||||
f"'{row_profile}', not '{profile_name}' (fail closed)"
|
||||
],
|
||||
"expected": row_profile,
|
||||
"actual": profile_name,
|
||||
}
|
||||
return {"ok": True, "session_id": declared, "session_source": "declared"}
|
||||
|
||||
lock = None
|
||||
try:
|
||||
lock = issue_lock_store.load_issue_lock(
|
||||
remote=remote,
|
||||
org=org or "",
|
||||
repo=repo or "",
|
||||
issue_number=int(issue_number),
|
||||
)
|
||||
except Exception: # noqa: BLE001 — absent/unreadable lock is not fatal here
|
||||
lock = None
|
||||
lock_session = issue_lock_store.lease_task_session_id(lock) if lock else ""
|
||||
if lock_session:
|
||||
lease = (lock or {}).get("work_lease") or {}
|
||||
claimant = lease.get("claimant") or {}
|
||||
lock_identity = (claimant.get("username") or "").strip()
|
||||
lock_profile = (claimant.get("profile") or "").strip()
|
||||
if (lock_identity and lock_identity != identity) or (
|
||||
lock_profile and lock_profile != profile_name
|
||||
):
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _SESSION_LOCK_OWNER_MISMATCH,
|
||||
"reasons": [
|
||||
f"issue #{int(issue_number)} is locked by "
|
||||
f"'{lock_identity or 'unknown'}' ({lock_profile or 'unknown'}), "
|
||||
f"not '{identity}' ({profile_name}) (fail closed)"
|
||||
],
|
||||
"expected": f"{lock_identity}/{lock_profile}",
|
||||
"actual": f"{identity}/{profile_name}",
|
||||
}
|
||||
return {
|
||||
"ok": True,
|
||||
"session_id": lock_session,
|
||||
"session_source": "issue_lock",
|
||||
}
|
||||
|
||||
if (assignment_id or "").strip() or (lease_id or "").strip():
|
||||
return {
|
||||
"ok": False,
|
||||
"reason_code": _SESSION_REQUIRED,
|
||||
"reasons": [
|
||||
"assignment_id/lease_id were supplied but no owning workflow "
|
||||
"session could be established (fail closed); pass the "
|
||||
"session_id that holds the lease, or bind the issue lock first"
|
||||
],
|
||||
}
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"session_id": issue_lock_store.mint_task_session_id(
|
||||
issue_lock_store.AUTHOR_ISSUE_WORK_LEASE
|
||||
),
|
||||
"session_source": "minted_task_key",
|
||||
}
|
||||
|
||||
|
||||
def _authenticated_actor(host: str) -> dict:
|
||||
"""Resolve the authenticated actor's stable identity (#709 F7 review 438).
|
||||
|
||||
@@ -9988,6 +10275,24 @@ def gitea_commit_files(
|
||||
}
|
||||
|
||||
|
||||
def _author_mutation_block(reasons: list[str], **extra) -> dict:
|
||||
"""Uniform fail-closed shape for an author mutation refused after a reviewer stop.
|
||||
|
||||
#943: referenced by ``gitea_bootstrap_author_issue_worktree`` and never
|
||||
defined, so the reviewer-stop refusal path raised ``NameError`` instead of
|
||||
returning its refusal. Mirrors the inline shape the other author mutations
|
||||
return for the same ``check_author_mutation_after_reviewer_stop`` block.
|
||||
"""
|
||||
payload = {
|
||||
"success": False,
|
||||
"performed": False,
|
||||
"outcome": "REFUSED",
|
||||
"reasons": reasons,
|
||||
}
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
def _publication_block(reasons: list[str], **extra) -> dict:
|
||||
"""Uniform fail-closed shape for publication refusals (#812 AC20)."""
|
||||
payload = {
|
||||
@@ -10244,6 +10549,7 @@ def gitea_bootstrap_author_issue_worktree(
|
||||
branch_name: str | None = None,
|
||||
worktree_path: str | None = None,
|
||||
idempotency_key: str | None = None,
|
||||
session_id: str | None = None,
|
||||
remote: str = "dadeschools",
|
||||
host: str | None = None,
|
||||
org: str | None = None,
|
||||
@@ -10265,6 +10571,14 @@ def gitea_bootstrap_author_issue_worktree(
|
||||
branch_name: Optional custom branch name (must match issue-<N> pattern).
|
||||
worktree_path: Optional custom worktree path under branches/.
|
||||
idempotency_key: Optional key for idempotent replay/resume.
|
||||
session_id: Optional workflow session that owns the assignment/lease.
|
||||
Required when assignment_id/lease_id are supplied, because ownership
|
||||
of an allocated lease is compared by session identifier and cannot
|
||||
be derived from the daemon process (#943 review 622 B1). Verified
|
||||
against the control-plane sessions table; an unverifiable value is
|
||||
refused rather than trusted. Omit for an unallocated bootstrap: the
|
||||
owning session is then taken from an existing issue lock, or a fresh
|
||||
per-task key is minted.
|
||||
remote: Known instance — 'dadeschools' or 'prgs'.
|
||||
host: Override Gitea host.
|
||||
org: Override Org.
|
||||
@@ -10303,6 +10617,44 @@ def gitea_bootstrap_author_issue_worktree(
|
||||
h, o, r = _resolve(remote, host, org, repo)
|
||||
canonical_root = _canonical_local_git_root()
|
||||
|
||||
# One authority snapshot supplies both halves of the claimant pair (F3), and
|
||||
# an unresolvable profile becomes a structured refusal rather than a silent
|
||||
# fallback (F4).
|
||||
authority = _active_mutation_authority(h)
|
||||
if not authority.get("ok"):
|
||||
return _author_mutation_block(
|
||||
authority.get("reasons") or ["mutation authority unresolved"],
|
||||
reason_code=authority.get("reason_code"),
|
||||
retryable=False,
|
||||
transport_survives=True,
|
||||
expected=authority.get("expected"),
|
||||
actual=authority.get("actual"),
|
||||
issue_number=int(issue_number),
|
||||
)
|
||||
|
||||
# The owning workflow session — never process- or PID-derived (B1).
|
||||
session = _resolve_owner_workflow_session(
|
||||
issue_number=issue_number,
|
||||
assignment_id=assignment_id,
|
||||
lease_id=lease_id,
|
||||
session_id=session_id,
|
||||
identity=authority["identity"],
|
||||
profile_name=authority["profile_name"],
|
||||
remote=remote,
|
||||
org=o,
|
||||
repo=r,
|
||||
)
|
||||
if not session.get("ok"):
|
||||
return _author_mutation_block(
|
||||
session.get("reasons") or ["owning workflow session unresolved"],
|
||||
reason_code=session.get("reason_code"),
|
||||
retryable=False,
|
||||
transport_survives=True,
|
||||
expected=session.get("expected"),
|
||||
actual=session.get("actual"),
|
||||
issue_number=int(issue_number),
|
||||
)
|
||||
|
||||
import author_issue_bootstrap
|
||||
|
||||
return author_issue_bootstrap.bootstrap_author_issue_worktree(
|
||||
@@ -10318,9 +10670,9 @@ def gitea_bootstrap_author_issue_worktree(
|
||||
host=h,
|
||||
org=o,
|
||||
repo=r,
|
||||
active_identity=_active_username(),
|
||||
active_profile=_active_profile_name(),
|
||||
owner_session=_current_session_id(),
|
||||
active_identity=authority["identity"],
|
||||
active_profile=authority["profile_name"],
|
||||
owner_session=session["session_id"],
|
||||
dry_run=dry_run,
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user