feat(launcher): trusted client-instance identity for project-scoped launches

Issue #985. The production launcher could mint one trusted
GITEA_MCP_CLIENT_INSTANCE per launch, but two gaps kept real launches on
untrusted legacy-pid-* identities:

1. build_application_mcp_servers required a profile for all five sanctioned
   namespaces, so a project-scoped configuration exposing only author,
   reviewer, and merger could not use it without inventing controller and
   reconciler profiles that must not exist.
2. The module produced configuration data but had no runnable entry point, so
   every real launch bypassed it entirely.

Changes:

- resolve_launch_namespaces() validates an explicit namespace subset as an
  allow-list; unknown, duplicate, and empty selections are refused rather than
  silently narrowing a launch. Omitting it preserves five-namespace behaviour.
- build_application_mcp_servers() accepts that subset, requires profiles only
  for the launched namespaces, starts only those workers, and reports
  excluded_namespaces / project_scoped.
- collect_instance_ids_from_mcp_servers() inspects the launch's own namespaces
  instead of an assumed five, and reports missing_servers, so a three-namespace
  launch can prove shared attribution without reading as two absent workers.
- Runnable entry point: python3 -m mcp_application_launcher mints one trusted
  identity, writes a per-launch 0600 mcpServers config, and execs the client.
  CLIENT_LAUNCH_SPECS is a data-driven registry so other supported clients use
  the same mint-once/propagate-to-all mechanism. --dry-run prints the plan.
- Provenance sealing now fails closed. The inst- format is public and
  reproducible, so format alone could previously let anyone who set one
  environment variable manufacture a trusted identity. Trust now additionally
  requires GITEA_MCP_INSTANCE_PROVENANCE=trusted_launcher, which only the
  launcher writes; a well-formed but unsealed value is classified
  unsealed_launcher and refused, while still being reported for diagnosis.

Deliberate behaviour change: tests/test_issue_978_instance_fleet_snapshot.py
test_client_hints_trusted_when_set previously asserted that a well-formed ID
alone was trusted. It now supplies the launcher seal, and a new companion test
asserts the unsealed case fails closed. This tightens the contract; no
assertion was weakened.

No static or persistent per-project instance IDs are introduced, duplicate
worker and cohort detection are untouched, and no fleet or mutation gate is
relaxed.

Tests: tests/test_issue_985_project_scoped_launcher.py, 47 passed, 3 subtests.
Full suite from a branches/ worktree: 28 failed, 6252 passed, 6 skipped against
a master baseline at 32ab8392 of 28 failed, 6204 passed, 6 skipped; the failing
sets are byte-identical, so zero regressions and zero masked failures.

Closes #985

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This commit is contained in:
2026-07-31 03:15:53 -05:00
co-authored by Claude Opus 4.8
parent 32ab839289
commit 7e19079b5c
6 changed files with 1185 additions and 25 deletions
+379 -19
View File
@@ -15,7 +15,7 @@ from __future__ import annotations
import os
import secrets
from typing import Any, Mapping
from typing import Any, Mapping, Sequence
import mcp_fleet_snapshot as fleet
import mcp_worker_identity as mwi
@@ -152,10 +152,54 @@ def namespace_worker_env(
return env
def resolve_launch_namespaces(
namespaces: "Sequence[str] | None" = None,
) -> tuple[str, ...]:
"""Validate an explicit project-scoped namespace subset (#985).
``None`` keeps the historical whole-fleet behaviour and resolves to all five
sanctioned namespaces. An explicit sequence is validated against
:data:`SANCTIONED_NAMESPACES` and returned in canonical fleet order, so a
project-scoped configuration (for example author/reviewer/merger only) can
launch without inventing controller or reconciler profiles.
This is an allow-list, not a filter: anything outside the sanctioned set is
refused rather than silently dropped, so a typo can never quietly shrink a
launch to fewer workers than the operator intended.
"""
if namespaces is None:
return tuple(SANCTIONED_NAMESPACES)
requested = [str(ns).strip().lower() for ns in namespaces]
if not requested or any(not ns for ns in requested):
raise ValueError(
"namespaces must be a non-empty sequence of sanctioned namespace "
f"names; choose from {list(SANCTIONED_NAMESPACES)}"
)
unknown = sorted({ns for ns in requested if ns not in SANCTIONED_NAMESPACES})
if unknown:
raise ValueError(
f"unsanctioned namespace(s) {unknown} requested; sanctioned "
f"namespaces are {list(SANCTIONED_NAMESPACES)}"
)
duplicates = sorted({ns for ns in requested if requested.count(ns) > 1})
if duplicates:
raise ValueError(
f"duplicate namespace(s) {duplicates} requested; each sanctioned "
"namespace may appear at most once in one launch"
)
selected = set(requested)
return tuple(ns for ns in SANCTIONED_NAMESPACES if ns in selected)
def build_application_mcp_servers(
profile_by_namespace: Mapping[str, str],
*,
client_type: str | None,
namespaces: "Sequence[str] | None" = None,
config_path: str | None = None,
client_instance_id: str | None = None,
fleet_run_id: str | None = None,
@@ -175,14 +219,22 @@ def build_application_mcp_servers(
Every namespace server entry receives the **same** instance ID. Separate
calls with no supplied ID receive distinct IDs.
*namespaces* selects an explicitly validated project-scoped subset (#985).
Omitting it preserves the original whole-fleet behaviour, so existing
five-namespace callers are unaffected. Only the resolved namespaces need a
profile, and only they are started; excluded namespaces are reported so a
caller can prove a controller/reconciler worker was never launched.
"""
resolved_namespaces = resolve_launch_namespaces(namespaces)
missing = [
ns for ns in SANCTIONED_NAMESPACES if not profile_by_namespace.get(ns)
ns for ns in resolved_namespaces if not profile_by_namespace.get(ns)
]
if missing:
raise ValueError(
"build_application_mcp_servers requires a profile for every "
f"sanctioned namespace; missing: {missing}"
f"requested namespace; missing: {missing}"
)
if client_instance_id is None:
@@ -213,6 +265,13 @@ def build_application_mcp_servers(
"namespace_server_names": list(NAMESPACE_SERVER_NAMES),
}
# The launch record describes only the namespaces this launch actually
# starts, so downstream attribution never implies an unstarted worker.
launch["namespaces"] = list(resolved_namespaces)
launch["namespace_server_names"] = [
f"gitea-{ns}" for ns in resolved_namespaces
]
# Resolve command/args from the production server entry when not provided.
if command is None or args is None:
import gitea_config
@@ -223,7 +282,7 @@ def build_application_mcp_servers(
servers: dict[str, Any] = {}
shared_id = launch["client_instance_id"]
for namespace in SANCTIONED_NAMESPACES:
for namespace in resolved_namespaces:
server_name = f"gitea-{namespace}"
profile = profile_by_namespace[namespace]
env = namespace_worker_env(
@@ -240,14 +299,17 @@ def build_application_mcp_servers(
"env": env,
}
excluded = [ns for ns in SANCTIONED_NAMESPACES if ns not in resolved_namespaces]
return {
"mcpServers": servers,
"launch": launch,
"client_instance_id": shared_id,
"client_type": launch["client_type"],
"namespaces": list(SANCTIONED_NAMESPACES),
"namespaces": list(resolved_namespaces),
"excluded_namespaces": excluded,
"project_scoped": bool(excluded),
"shared_instance_id_across_namespaces": True,
"namespace_count": len(SANCTIONED_NAMESPACES),
"namespace_count": len(resolved_namespaces),
}
@@ -316,15 +378,33 @@ def launcher_entry_for_profile(
def collect_instance_ids_from_mcp_servers(
mcp_servers: Mapping[str, Any],
*,
namespaces: "Sequence[str] | None" = None,
) -> dict[str, Any]:
"""Inspect a production mcpServers map for shared instance attribution.
Returns the unique set of client_instance_id values across gitea-* servers
and whether all five namespaces share exactly one trusted ID.
Returns the unique set of client_instance_id values across the gitea-*
servers of one launch and whether every worker of that launch shares
exactly one trusted ID.
The inspected set is the launch's own namespaces, not an assumed five
(#985): a project-scoped author/reviewer/merger launch must be able to
prove shared attribution without a controller or reconciler entry counting
as a missing worker. Pass *namespaces* to assert an exact expected subset;
omit it to inspect whichever sanctioned namespace servers are present.
"""
if namespaces is None:
expected_servers = [
name for name in NAMESPACE_SERVER_NAMES if name in mcp_servers
]
else:
expected_servers = [
f"gitea-{ns}" for ns in resolve_launch_namespaces(namespaces)
]
ids: list[str] = []
by_server: dict[str, str | None] = {}
for name in NAMESPACE_SERVER_NAMES:
for name in expected_servers:
entry = mcp_servers.get(name) or {}
env = entry.get("env") or {}
raw = (env.get(CLIENT_INSTANCE_ENV) or "").strip() or None
@@ -337,14 +417,19 @@ def collect_instance_ids_from_mcp_servers(
for i in unique
if fleet.assess_instance_identity(i)["trusted"]
]
missing_servers = [n for n in expected_servers if n not in mcp_servers]
return {
"server_instance_ids": by_server,
"unique_instance_ids": unique,
"trusted_instance_ids": trusted,
"inspected_servers": list(expected_servers),
"missing_servers": missing_servers,
"shared_single_trusted_id": (
len(unique) == 1
bool(expected_servers)
and not missing_servers
and len(unique) == 1
and len(trusted) == 1
and all(by_server.get(n) == unique[0] for n in NAMESPACE_SERVER_NAMES)
and all(by_server.get(n) == unique[0] for n in expected_servers)
),
"namespace_server_count": sum(
1 for n in NAMESPACE_SERVER_NAMES if n in mcp_servers
@@ -365,20 +450,23 @@ def inherit_or_refuse_client_instance(
source = dict(env if env is not None else os.environ)
raw = (source.get(CLIENT_INSTANCE_ENV) or "").strip() or None
provenance_marker = (source.get(INSTANCE_PROVENANCE_ENV) or "").strip()
assessment = fleet.assess_instance_identity(raw)
# Ordinary user-supplied values without launcher provenance marker are
# still format-checked by assess_instance_identity. When the format is
# trusted but the launcher marker is absent, keep the ID but note that
# provenance is not launcher-sealed (operator hand-set or legacy config).
assessment = dict(fleet.assess_instance_identity(raw))
# The ``inst-…`` format is public and reproducible, so format alone cannot
# establish trust: anyone able to set one env var could otherwise hand-write
# a well-formed ID and be believed. Trust therefore requires the launcher's
# own seal as well, and a well-formed but unsealed identity fails closed
# rather than degrading to a mere annotation (#985).
if assessment["trusted"] and provenance_marker != LAUNCHER_PROVENANCE_VALUE:
assessment = dict(assessment)
assessment["launcher_sealed"] = False
assessment["trusted"] = False
assessment["complete"] = False
assessment["provenance"] = fleet.INSTANCE_ID_PROVENANCE_UNSEALED
assessment["reasons"] = list(assessment.get("reasons") or []) + [
f"{INSTANCE_PROVENANCE_ENV} is not {LAUNCHER_PROVENANCE_VALUE!r}; "
"identity format is valid but not sealed by the production launcher"
"identity format is valid but not sealed by the production "
"launcher, so trusted attribution is refused"
]
else:
assessment = dict(assessment)
assessment["launcher_sealed"] = bool(
assessment["trusted"]
and provenance_marker == LAUNCHER_PROVENANCE_VALUE
@@ -391,3 +479,275 @@ def inherit_or_refuse_client_instance(
(source.get("GITEA_MCP_CLIENT") or "").strip() or None
)
return assessment
# ---------------------------------------------------------------------------
# Runnable launch path (#985)
# ---------------------------------------------------------------------------
#: How each supported LLM client is started with a per-launch MCP config.
#:
#: The launch interface is deliberately a data-driven registry rather than a
#: Claude-specific code path: adding another supported client is one entry, and
#: every client necessarily goes through the same mint-once/propagate-to-all
#: identity mechanism because the argv builder only ever receives a config file
#: this module wrote.
CLIENT_LAUNCH_SPECS: dict[str, dict[str, Any]] = {
"claude_code": {
"command": "claude",
"config_args": lambda path: ["--mcp-config", path, "--strict-mcp-config"],
"docs": "claude --mcp-config <per-launch.json> --strict-mcp-config",
},
}
def supported_launch_clients() -> tuple[str, ...]:
"""Client types with a sanctioned runnable launch path."""
return tuple(sorted(CLIENT_LAUNCH_SPECS))
def build_client_launch_argv(
client_type: str,
config_path: str,
*,
extra_args: "Sequence[str] | None" = None,
) -> list[str]:
"""Build the argv that starts *client_type* against a per-launch config."""
client = mwi.normalize_client_name(client_type)
spec = CLIENT_LAUNCH_SPECS.get(client)
if spec is None:
raise ValueError(
f"no sanctioned runnable launch path for client {client!r}; "
f"supported clients: {list(supported_launch_clients())}"
)
argv = [str(spec["command"])] + list(spec["config_args"](str(config_path)))
if extra_args:
argv.extend(str(a) for a in extra_args)
return argv
def write_launch_config(
mcp_servers: Mapping[str, Any],
*,
directory: str | None = None,
) -> str:
"""Write one launch's ``mcpServers`` config to a fresh per-launch file.
The file is per-launch and owner-readable only. #985 explicitly rules out
persisting an instance ID into a shared, reused ``.mcp.json``: two
concurrent sessions reading one static trusted ID is precisely the reuse
case the duplicate guard must reject. A distinct file per launch keeps the
minted identity bound to the launch that minted it.
"""
import json
import tempfile
fd, path = tempfile.mkstemp(
prefix="gitea-mcp-launch-", suffix=".json", dir=directory
)
try:
os.fchmod(fd, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump({"mcpServers": dict(mcp_servers)}, handle, indent=2)
handle.write("\n")
except Exception:
try:
os.unlink(path)
except OSError:
pass
raise
return path
def prepare_application_launch(
profile_by_namespace: Mapping[str, str],
*,
client_type: str,
namespaces: "Sequence[str] | None" = None,
config_path: str | None = None,
fleet_run_id: str | None = None,
session_id: str | None = None,
launch_nonce: str | None = None,
extra_args: "Sequence[str] | None" = None,
config_directory: str | None = None,
now=None,
) -> dict[str, Any]:
"""Mint one launch and produce everything needed to exec the client.
Returns the built servers, the per-launch config file path, the argv to
exec, and the shared trusted identity — without starting anything, so the
same preparation is testable and inspectable via ``--dry-run``.
"""
built = build_application_mcp_servers(
profile_by_namespace,
client_type=client_type,
namespaces=namespaces,
config_path=config_path,
fleet_run_id=fleet_run_id,
session_id=session_id,
launch_nonce=launch_nonce,
now=now,
)
# Fail before writing anything if this client has no runnable path.
argv_probe = build_client_launch_argv(
client_type, "<pending>", extra_args=extra_args
)
launch_config_path = write_launch_config(
built["mcpServers"], directory=config_directory
)
argv = build_client_launch_argv(
client_type, launch_config_path, extra_args=extra_args
)
proof = collect_instance_ids_from_mcp_servers(
built["mcpServers"], namespaces=built["namespaces"]
)
return {
"client_type": built["client_type"],
"client_instance_id": built["client_instance_id"],
"namespaces": built["namespaces"],
"excluded_namespaces": built["excluded_namespaces"],
"project_scoped": built["project_scoped"],
"launch_config_path": launch_config_path,
"argv": argv,
"argv_template": argv_probe,
"mcpServers": built["mcpServers"],
"launch": built["launch"],
"shared_single_trusted_id": proof["shared_single_trusted_id"],
"attribution_proof": proof,
}
def _parse_profile_assignments(values: "Sequence[str]") -> dict[str, str]:
"""Parse ``namespace=profile`` CLI pairs into a mapping."""
profiles: dict[str, str] = {}
for raw in values or ():
text = str(raw)
if "=" not in text:
raise ValueError(
f"invalid --profile {text!r}; expected namespace=profile-name"
)
namespace, _, profile = text.partition("=")
namespace = namespace.strip().lower()
profile = profile.strip()
if not namespace or not profile:
raise ValueError(
f"invalid --profile {text!r}; expected namespace=profile-name"
)
if namespace in profiles:
raise ValueError(f"duplicate --profile entry for namespace {namespace!r}")
profiles[namespace] = profile
return profiles
def main(argv: "Sequence[str] | None" = None) -> int:
"""Runnable entry point: start a supported LLM client for one launch.
Example (project-scoped, three namespaces)::
python3 -m mcp_application_launcher \\
--client claude_code \\
--namespaces author,reviewer,merger \\
--profile author=prgs-author \\
--profile reviewer=prgs-reviewer \\
--profile merger=prgs-merger
"""
import argparse
import json
parser = argparse.ArgumentParser(
prog="mcp_application_launcher",
description=(
"Start a supported LLM client with one trusted, per-launch "
"GITEA_MCP_CLIENT_INSTANCE shared by every MCP namespace worker."
),
)
parser.add_argument(
"--client",
default="claude_code",
help=f"client to launch; supported: {list(supported_launch_clients())}",
)
parser.add_argument(
"--namespaces",
default=None,
help=(
"comma-separated sanctioned namespace subset (e.g. "
"'author,reviewer,merger'); omit to launch all five"
),
)
parser.add_argument(
"--profile",
action="append",
default=[],
metavar="NAMESPACE=PROFILE",
help="profile for one namespace; repeat once per launched namespace",
)
parser.add_argument("--config-path", default=None, help="profiles.json path")
parser.add_argument("--fleet-run-id", default=None)
parser.add_argument("--session-id", default=None)
parser.add_argument(
"--dry-run",
action="store_true",
help="print the launch plan as JSON and exit without starting anything",
)
parser.add_argument(
"client_args",
nargs=argparse.REMAINDER,
help="arguments forwarded to the client after '--'",
)
ns = parser.parse_args(list(argv) if argv is not None else None)
try:
profiles = _parse_profile_assignments(ns.profile)
requested = (
[part.strip() for part in ns.namespaces.split(",") if part.strip()]
if ns.namespaces
else None
)
resolved = resolve_launch_namespaces(requested)
# Profiles for namespaces that are not being launched are almost always
# a mistake (a stale five-namespace invocation), so refuse rather than
# silently ignore them.
stray = sorted(set(profiles) - set(resolved))
if stray:
raise ValueError(
f"--profile given for namespace(s) {stray} that this launch "
f"does not start; launched namespaces are {list(resolved)}"
)
forwarded = [a for a in (ns.client_args or []) if a != "--"]
prepared = prepare_application_launch(
profiles,
client_type=ns.client,
namespaces=requested,
config_path=ns.config_path,
fleet_run_id=ns.fleet_run_id,
session_id=ns.session_id,
extra_args=forwarded,
)
except ValueError as exc:
parser.error(str(exc))
return 2 # pragma: no cover - argparse.error raises SystemExit
if ns.dry_run:
plan = {
key: prepared[key]
for key in (
"client_type",
"client_instance_id",
"namespaces",
"excluded_namespaces",
"project_scoped",
"launch_config_path",
"argv",
"shared_single_trusted_id",
)
}
print(json.dumps(plan, indent=2))
return 0
argv_to_exec = prepared["argv"]
os.execvp(argv_to_exec[0], argv_to_exec)
return 0 # pragma: no cover - execvp does not return
if __name__ == "__main__": # pragma: no cover - process entry point
raise SystemExit(main())