diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 852fbae2..58d3f873 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -91,7 +91,7 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Install (pytest + PyYAML — the whole dependency set) - run: pip install pytest PyYAML + run: pip install pytest PyYAML PyJWT cryptography - name: Run tests working-directory: PyAutoBrain run: pytest tests/ -q diff --git a/AUTONOMY.md b/AUTONOMY.md index b65db77b..7a5c0683 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -879,15 +879,19 @@ is never retried. The watcher also reads `gh pr view --json state,mergedAt,mergedBy` for the PRs its own workers named — the close-out's merge truth (#603) and, once at `review-at:`, the digest's `merges` (#610). It also makes one read-only `gh api user` per shift, under the posting token, -to warn when it equals the mention login (#611). +to warn when it equals the mention login (#611) — as the App, one `GET /app` +with its JWT instead, naming it `[bot]` (#630). The revert condition now reads: one network call outside these, or a comment beyond these (a second digest, a second mention for the same worker and state, a second correction), retires the watcher to fake mode. **Posting identity, ruled by the human 2026-11-12 (PyAutoLabs/PyAutoBrain#611):** the watcher's GitHub -writes use a separate bot or machine account's token, set by the human as -`PYAUTO_SHIFT_GH_TOKEN` (fine-grained, PyAutoMind issues:write only); until it -is set they post as the human's account and the digest warns that the -mention will not notify. +writes use the watcher's App installation token (PyAutoBrain#630), minted by +one `POST /app/installations//access_tokens` call on each tick that makes +a watcher GitHub call and held in memory for that tick only. Without the App, +a separate account's static token, `PYAUTO_SHIFT_GH_TOKEN` (fine-grained, +PyAutoMind issues:write only), is the fallback. With neither set, the writes +post as the human's account and the digest warns that the mention will not +notify. **Amendment — 2026-11-13 (PyAutoBrain#622), authorized by the human.** The human approved the live shift view as drafted on 2026-11-13: a running shift diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 67eab6ee..bf0ac2f5 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -473,15 +473,51 @@ live:` line (`record-key` op, one Mind writer, on a change of state), shown in the batch box. Doctrine: AUTONOMY.md watcher network surface, amendment 2026-11-13. -**The watcher's GitHub identity (human ruling 2026-11-12, #611).** -`PYAUTO_SHIFT_GH_TOKEN` holds a separate bot or machine account's token, -**fine-grained, PyAutoMind issues:write only**, set by the human in the -timer's environment. It is passed as `GH_TOKEN` to the watcher's own -`gh issue comment` and `gh api user` calls and to nothing else (not to workers). -Unset, comments post as the human's account; once a shift, before the first -mention, `gh api user` names the posting account, and if it is the mentioned -login the digest's `### Workers` warns "mention will not notify: posted as the -mentioned account". With nothing pending, the tick is idle. The worker +**The watcher's GitHub identity (human rulings 2026-11-12, #611, and +2026-11-14, #630).** The watcher posts as its own minimal GitHub App, +`pyautolabs-watcher`, set by the human in the timer's environment +(`~/.config/pyauto/orchestrator.env`) with three variables, all or none: + +- `PYAUTO_SHIFT_APP_ID` — the App id; +- `PYAUTO_SHIFT_APP_INSTALLATION_ID` — its installation on PyAutoMind's owner; +- `PYAUTO_SHIFT_APP_KEY` — the path of the App's private key (`.pem`, mode 600). + +The App is minimal on purpose: **Issues read/write on PyAutoMind only** — +all the watcher does is comment on, edit its comment on and read the shift +issue. It is **not `pyautolabs-bot`**: that App is a ruleset bypass actor with +org-wide push, and a laptop timer must hold no bypass power. Posting as an App +also means the @mention of the human comes from another account, so it +notifies them. `_app_token.py` signs an RS256 JWT (`iat` now − 60 s, `exp` now ++ 9 min, `iss` the App id; PyJWT, else `openssl dgst -sha256 -sign` with no +shell) and mints an installation token with one `POST +/app/installations//access_tokens` on the first watcher GitHub call of a +tick, reusing it for the rest of that tick. The token is held **in memory +only** — never written to disk, where a worker running as the same user could +read it; each tick that makes a watcher GitHub call mints its own. The token is +passed as `GH_TOKEN` to the watcher's own `gh` calls and to nothing else: +**every watcher write** (the status comment and its edits, mentions, the digest, +the correction) and the steering read of the shift issue's comments. Two +**reads** deliberately stay under the human's own `gh` auth, because the App +cannot see library repositories: `gh pr view` for the PRs its workers named +(`gh_pr_state`, the close-out's merge truth and the digest's `merges`) and +`gh pr checks` for their CI (`_digest.pr_health`). If minting fails, the tick +carries on but makes none of the App's calls — no write and no steering read, +never under the human's `gh` auth in their place. The reason goes into +`tick.log` (`github_auth`) and the digest ("GitHub writes held"); a held post +costs no try and is retried. A failed mint is not retried for 10 minutes; the +state directory keeps only its time and reason (`app_mint_failure.json`), no +secret. An App +configured in part (one or two variables) is the same failure. Without the +App, `PYAUTO_SHIFT_GH_TOKEN` (a static fine-grained token, PyAutoMind +issues:write only) is the fallback; with neither, comments post as the human's +account. Neither the App variables, the key path, the static token nor a +minted token reaches a worker or close-out (`worker_env`). Once a shift, +before the first mention, the posting account is named — as the App, +`[bot]` from one `GET /app` with the JWT (`gh api user` does not answer +for an installation token), else `gh api user` — and if it is the mentioned +login (never, as the App) the digest's `### Workers` warns "mention will not +notify: posted as the mentioned account". With nothing pending, the tick is +idle. The worker prompt also forbids EnterWorktree (its permission prompt stalls an unattended worker) and requires the `decision-taken` label on any PR carrying a flagged decision (pilot live shift 1, 2026-11-06). diff --git a/agents/conductors/batch/_app_token.py b/agents/conductors/batch/_app_token.py new file mode 100644 index 00000000..dac0d321 --- /dev/null +++ b/agents/conductors/batch/_app_token.py @@ -0,0 +1,306 @@ +"""The shift watcher's own GitHub identity: a minimal GitHub App (PyAutoBrain#630). + +The watcher posts its comments (status, mentions, digest, correction) and reads +the shift issue's comments as its own App, `pyautolabs-watcher` — Issues +read/write on PyAutoMind only — so an @mention of the human notifies the human, +and nothing on the laptop holds bypass powers (it is NOT `pyautolabs-bot`, a +ruleset bypass actor with org-wide push). See `AGENTS.md` "The watcher's +GitHub identity". + +Three settings, all or none: + +- `PYAUTO_SHIFT_APP_ID` — the App id (the JWT issuer); +- `PYAUTO_SHIFT_APP_INSTALLATION_ID` — its installation on PyAutoMind's owner; +- `PYAUTO_SHIFT_APP_KEY` — the path of the App's private key (`.pem`). + +With all three set, the watcher signs an RS256 JWT (PyJWT, else `openssl dgst`, +no shell) and mints an installation token (`POST /app/installations//access_tokens`) +on the first watcher GitHub call of a tick, reuses it for the rest of that tick, +and keeps it **in memory only**: no token is ever written to disk, where a worker +running as the same user could read it (#630 review). A failed mint is +remembered on disk as a timestamp and a reason only (`MINT_FAILURE_FILE`), so +the next mint waits `MINT_BACKOFF_S`. With none set, `PYAUTO_SHIFT_GH_TOKEN` (a +static token) is the fallback, and with neither, `gh`'s own auth, as before. +When the App is configured but no token can be had, the watcher's own GitHub +calls are not made at all: never the human's `gh` auth in their place. No error +message carries the key, a JWT or a token. + +Runs under the systemd unit's `/usr/bin/python3` (3.10): standard library plus +an optional PyJWT. +""" + +from __future__ import annotations + +import base64 +import datetime as _dt +import json +import os +import subprocess +import tempfile +import time +import urllib.error +import urllib.request +from pathlib import Path + +APP_ID_ENV = "PYAUTO_SHIFT_APP_ID" +APP_INSTALLATION_ENV = "PYAUTO_SHIFT_APP_INSTALLATION_ID" +APP_KEY_ENV = "PYAUTO_SHIFT_APP_KEY" +APP_ENVS = (APP_ID_ENV, APP_INSTALLATION_ENV, APP_KEY_ENV) +#: The static fallback: a token given to the watcher's `gh` calls as `GH_TOKEN`. +GH_TOKEN_ENV = "PYAUTO_SHIFT_GH_TOKEN" + +API = "https://api.github.com" +#: The last failed mint, in the watcher's state directory: `{"at", "error"}` — +#: a timestamp and a reason, never a secret. Removed by a successful mint. +MINT_FAILURE_FILE = "app_mint_failure.json" +#: After a failed mint, no new attempt for this long (a tick is ~3 min). +MINT_BACKOFF_S = 600 +#: The JWT: back-dated for clock drift, and inside GitHub's 10-minute cap. +JWT_BACKDATE_S = 60 +JWT_LIFETIME_S = 540 + + +class AppTokenError(Exception): + """No App token could be had; the message is safe to log (no secrets).""" + + +def app_settings(environ=None) -> dict | None: + """The App's three settings; None when none is set. Some but not all set + is a misconfiguration — an error, never a quiet fallback to another identity.""" + env = os.environ if environ is None else environ + vals = {k: str(env.get(k, "") or "").strip() for k in APP_ENVS} + if not any(vals.values()): + return None + missing = [k for k, v in vals.items() if not v] + if missing: + raise AppTokenError("the App is partly configured: " + ", ".join(missing) + + " unset") + return {"app_id": vals[APP_ID_ENV], "installation_id": vals[APP_INSTALLATION_ENV], + "key_path": vals[APP_KEY_ENV]} + + +def _b64url(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def jwt_claims(app_id: str, now: float) -> dict: + now = int(now) + return {"iat": now - JWT_BACKDATE_S, "exp": now + JWT_LIFETIME_S, "iss": str(app_id)} + + +def _sign_openssl(message: bytes, key_path: str, run=None) -> bytes: + """RS256 through `openssl dgst -sha256 -sign ` — an argv, no shell.""" + run = run or subprocess.run + try: + res = run(["openssl", "dgst", "-sha256", "-sign", str(key_path)], input=message, + capture_output=True, timeout=30) + except (OSError, subprocess.SubprocessError) as e: + raise AppTokenError(f"openssl could not run ({type(e).__name__})") from None + if res.returncode != 0 or not res.stdout: + raise AppTokenError(f"openssl could not sign the JWT (is {APP_KEY_ENV} a PEM key?)") + return res.stdout + + +def make_jwt(app_id: str, key_path: str, now: float | None = None, *, + use_pyjwt: bool = True, run=None) -> str: + """The App's JWT: `iat` = now − 60 s, `exp` = now + 9 min, `iss` = the App id. + PyJWT when it imports, else `openssl`.""" + claims = jwt_claims(app_id, time.time() if now is None else now) + if use_pyjwt: + try: + import jwt as _pyjwt + except ImportError: + _pyjwt = None + if _pyjwt is not None: + try: + key = Path(key_path).read_text(encoding="utf-8") + except OSError as e: + raise AppTokenError(f"cannot read {APP_KEY_ENV} ({e.strerror})") from None + try: + token = _pyjwt.encode(claims, key, algorithm="RS256") + except Exception as e: # noqa: BLE001 — a bad key; never echo it + raise AppTokenError(f"PyJWT could not sign the JWT ({type(e).__name__}; " + f"is {APP_KEY_ENV} a PEM key?)") from None + return token.decode("ascii") if isinstance(token, bytes) else token + if not Path(key_path).is_file(): + raise AppTokenError(f"cannot read {APP_KEY_ENV} (no such file)") + header = {"alg": "RS256", "typ": "JWT"} + signing_input = (_b64url(json.dumps(header, separators=(",", ":")).encode()) + "." + + _b64url(json.dumps(claims, separators=(",", ":")).encode())) + return signing_input + "." + _b64url(_sign_openssl(signing_input.encode("ascii"), + key_path, run=run)) + + +def request(method: str, url: str, headers: dict, body: dict | None = None): + """One GitHub API call (urllib); the decoded JSON. The fake-API seam.""" + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=30) as resp: + return json.load(resp) + except urllib.error.HTTPError as e: + raise AppTokenError(f"{method} {url} returned HTTP {e.code}") from None + except (urllib.error.URLError, OSError, ValueError) as e: + raise AppTokenError(f"{method} {url} failed ({type(e).__name__})") from None + + +def _headers(jwt_token: str) -> dict: + return {"Authorization": f"Bearer {jwt_token}", "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "pyauto-shift-watcher"} + + +def _parse_ts(value: str) -> float: + s = str(value or "").strip() + if s.endswith("Z"): + s = s[:-1] + "+00:00" + t = _dt.datetime.fromisoformat(s) # raises ValueError on anything else + if t.tzinfo is None: + t = t.replace(tzinfo=_dt.timezone.utc) + return t.timestamp() + + +def mint(settings: dict, now: float, request=request, **jwt_kw) -> dict: + """One installation token: `{"token", "expires_at"}` (GitHub's own expiry).""" + jwt_token = make_jwt(settings["app_id"], settings["key_path"], now, **jwt_kw) + res = request("POST", f"{API}/app/installations/{settings['installation_id']}" + "/access_tokens", _headers(jwt_token), None) + token = (res or {}).get("token") if isinstance(res, dict) else None + expires = (res or {}).get("expires_at") if isinstance(res, dict) else None + if not token or not expires: + raise AppTokenError("GitHub returned no installation token") + try: + _parse_ts(expires) + except ValueError: + raise AppTokenError("GitHub returned an unreadable expires_at") from None + return {"token": token, "expires_at": expires} + + +def app_login(settings: dict, now: float, request=request, **jwt_kw) -> str: + """The login the App's comments carry: `[bot]` (`GET /app`, with the JWT — + `gh api user` does not answer for an installation token).""" + jwt_token = make_jwt(settings["app_id"], settings["key_path"], now, **jwt_kw) + res = request("GET", f"{API}/app", _headers(jwt_token), None) + slug = (res or {}).get("slug") if isinstance(res, dict) else None + if not slug: + raise AppTokenError("GET /app returned no slug") + return f"{slug}[bot]" + + +def read_failure(state_dir: Path) -> dict: + """The last failed mint, `{"at", "error"}`; {} when none is recorded.""" + try: + rec = json.loads((Path(state_dir) / MINT_FAILURE_FILE).read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return rec if isinstance(rec, dict) else {} + + +def _record_failure(state_dir: Path, now: float, error: str) -> None: + """A timestamp and a reason (no secret), written through a unique temp file.""" + state_dir = Path(state_dir) + state_dir.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=MINT_FAILURE_FILE + ".", dir=state_dir) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump({"at": now, "error": error}, fh, sort_keys=True) + os.replace(tmp, state_dir / MINT_FAILURE_FILE) + except OSError: + Path(tmp).unlink(missing_ok=True) + + +def installation_token(settings: dict, state_dir: Path, now: float, request=request, + **jwt_kw) -> str: + """A freshly minted installation token, held by the caller in memory only. + Within `MINT_BACKOFF_S` of a failed mint no call is made: an error.""" + failure = read_failure(state_dir) + try: + since = now - float(failure.get("at")) + except (TypeError, ValueError): + since = None + if since is not None and 0 <= since < MINT_BACKOFF_S: + raise AppTokenError(f"{failure.get('error') or 'mint failed'} (no new mint for " + f"{MINT_BACKOFF_S // 60} min after a failure)") + try: + minted = mint(settings, now, request=request, **jwt_kw) + except AppTokenError as e: + _record_failure(state_dir, now, str(e)) + raise + (Path(state_dir) / MINT_FAILURE_FILE).unlink(missing_ok=True) + return minted["token"] + + +class WatcherAuth: + """Who the watcher's own `gh` calls run as, for one tick: the App (`mode` + "app"), the static token ("token"), or — with neither configured — `gh`'s + own auth ("gh"). The App's token is minted on the first call that needs it + and held in this object only, for this tick. `error` is why an App + configured could not be used; then `env()` raises and no call is made.""" + + def __init__(self, state_dir: Path, now: float | None = None, environ=None, + request=request, **jwt_kw): + self.state_dir = Path(state_dir) + self.now = time.time() if now is None else float(now) + self.environ = os.environ if environ is None else environ + self.request, self.jwt_kw = request, jwt_kw + self.error: str | None = None + self.token: str | None = None + #: Whether a GitHub call wanted this identity (a failure is reported only then). + self.used = False + self._resolved = False + try: + self.settings = app_settings(self.environ) + except AppTokenError as e: + self.settings, self.error, self._resolved = {}, str(e), True + static = str(self.environ.get(GH_TOKEN_ENV, "") or "").strip() + self.mode = "app" # configured, or partly configured (then `error` is set) + if self.settings is None: + self.mode = "token" if static else "gh" + self.token, self._resolved = static or None, True + + def _resolve(self) -> None: + self.used = True + if self._resolved: + return + self._resolved = True + try: + self.token = installation_token(self.settings, self.state_dir, self.now, + request=self.request, **self.jwt_kw) + except AppTokenError as e: + self.error = str(e) + except Exception as e: # noqa: BLE001 — never a traceback that could carry a secret + self.error = f"unexpected {type(e).__name__} minting the App token" + + def env(self) -> dict | None: + """The environment for one watcher `gh` call; None means `gh`'s own auth + (only when no identity is configured at all). In App mode a token is + required: without one this raises `AppTokenError`, never returns None.""" + self._resolve() + if self.mode == "app": + if self.error or not self.token: + raise AppTokenError(self.error or "no App installation token") + env = {k: v for k, v in self.environ.items() if k != "GITHUB_TOKEN"} + elif self.token is None: + return None + else: + env = dict(self.environ) + env["GH_TOKEN"] = self.token + return env + + def login(self) -> str | None: + """The App's comment login, `[bot]`; None outside App mode or when + it cannot be read (the caller then asks `gh api user`).""" + if self.mode != "app" or not self.settings: + return None + try: + return app_login(self.settings, self.now, request=self.request, **self.jwt_kw) + except Exception: # noqa: BLE001 + return None + + def failed(self) -> bool: + """Whether an App was configured and is unusable — resolved first.""" + self._resolve() + return bool(self.error) or (self.mode == "app" and not self.token) + + def secrets(self) -> set[str]: + """The token this identity holds — stripped from workers' environments.""" + return {self.token} if self.token else set() diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index ab88c4b3..969ec46c 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -310,9 +310,21 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, lines += [f"- {k}: {values[k]}" for k in COUNTERS] lines += ["", WORKERS_HEADING] + (worker_lines(counters, base) or [NO_PICKS]) lines += ["", REFUSALS_HEADING] + (refusal_lines(counters) or [NO_PICKS]) + lines += identity_lines(counters) return "\n".join(lines) + "\n" +def identity_lines(counters: dict) -> list[str]: + """PyAutoBrain#630: the watcher's App identity failed, so its GitHub writes + were held — never made under the human's own gh auth instead.""" + auth = counters.get("github_auth") or {} + if not auth.get("error"): + return [] + return ["", f"- warning: GitHub writes held — the watcher's App token could not be " + f"had on {auth.get('ticks', 1)} tick(s), {auth.get('first', '?')} to " + f"{auth.get('last', '?')}: {auth['error']}"] + + def backlog_gate_lines(counters: dict) -> list[str]: """What the M2.3 gates kept out of the backlog dip (AUTONOMY.md "M2 rulings — 2026-11-12"), as of the watcher's last tick. Not bullets: a @@ -356,7 +368,8 @@ def worker_lines(counters: dict, base: str = "") -> list[str]: poster, mentioned = counters.get("poster_login") or "", counters.get("mention_login") or "" if poster and poster.lower() == mentioned.lower(): out.append(f"- warning: mention will not notify: posted as the mentioned account " - f"({poster}) — set PYAUTO_SHIFT_GH_TOKEN to a separate account") + f"({poster}) — set the watcher's App (PYAUTO_SHIFT_APP_*) or " + "PYAUTO_SHIFT_GH_TOKEN") pushes = counters.get("pushes", 0) if pushes > 1: out.append(f"- finding: {pushes} pushes this shift — the push test budgets " diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 4e1b0c0e..02054f65 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -40,7 +40,8 @@ import sys from pathlib import Path -import _brief # noqa: E402 — the batch conductor puts this directory on sys.path +import _app_token # noqa: E402 — the batch conductor puts this directory on sys.path +import _brief # noqa: E402 import _digest # noqa: E402 import _mind_writer # noqa: E402 @@ -164,6 +165,10 @@ def _write_counters(slot: Path, c: dict) -> None: def _log(slot: Path, now: _dt.datetime, result: dict) -> None: + """Append the tick's result; a GitHub identity that failed this tick is + named in it (and in what the tick returns) — its writes were held.""" + if _AUTH is not None and _AUTH.used and _AUTH.error and "github_auth" not in result: + result["github_auth"] = {"error": _AUTH.error, "writes": "held"} with open(slot / LOG_FILE, "a", encoding="utf-8") as fh: fh.write(json.dumps({"at": _iso(now), **result}, sort_keys=True) + "\n") @@ -285,15 +290,19 @@ def closeout_command(task: str, pr_url: str, prompt_path: str, brief_path: Path, def worker_env(lease_dir: Path, base: dict | None = None) -> dict: """The environment a worker runs in: marked as a shift worker, pointed at the shift's ledger, and with git's hooks path overridden so a commit in - PyAutoMind is refused whatever tool makes it. The watcher's own posting - token (`PYAUTO_SHIFT_GH_TOKEN`) never reaches a worker or close-out, nor - a `GH_TOKEN` / `GITHUB_TOKEN` that carries it; the human's own gh auth - stays (#611 re-review).""" + PyAutoMind is refused whatever tool makes it. The watcher's own GitHub + identity never reaches a worker or close-out: not its static token + (`PYAUTO_SHIFT_GH_TOKEN`), not its App settings (`PYAUTO_SHIFT_APP_*`, + the key's path among them, PyAutoBrain#630), and no variable carrying + either token or an App installation token it minted; the human's own gh + auth stays (#611 re-review).""" env = dict(os.environ if base is None else base) - bot = env.pop(GH_TOKEN_ENV, "").strip() - for key in ("GH_TOKEN", "GITHUB_TOKEN"): - if bot and env.get(key, "").strip() == bot: - env.pop(key) + secrets = {env.pop(GH_TOKEN_ENV, "").strip()} | _auth().secrets() + for key in _app_token.APP_ENVS: + env.pop(key, None) + secrets.discard("") + for key in [k for k, v in env.items() if isinstance(v, str) and v.strip() in secrets]: + env.pop(key) n = int(env.get("GIT_CONFIG_COUNT", "0") or 0) env.update({"PYAUTO_SHIFT_WORKER": "1", "PYAUTO_SHIFT_LEDGER_DIR": str(Path(lease_dir).parent / _mind_writer.LEDGER_DIR), @@ -828,7 +837,25 @@ def _default_pr_state(): def tick(brief_path: Path, mind: Path, *, home: Path | None = None, - now: _dt.datetime | None = None, spawner=None, + now: _dt.datetime | None = None, auth=None, **kw) -> dict: + """One watcher tick, with its GitHub identity bound for the tick's own + `gh` calls (PyAutoBrain#630): a `_app_token.WatcherAuth` over the state + directory — the App's installation token, minted when the tick's first + watcher GitHub call needs it and held in memory for this tick only — + unless a test passes its own `auth`.""" + global _AUTH + now = now or _now() + prev = _AUTH + _AUTH = auth or _app_token.WatcherAuth(slot_dir(Path(brief_path), home).parent, + now=now.timestamp()) + try: + return _tick(brief_path, mind, home=home, now=now, **kw) + finally: + _AUTH = prev + + +def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, + now: _dt.datetime | None = None, spawner=None, grace_s: float = LEASE_GRACE_S, records: list[dict] | None = None, agents: AgentsView | None = None, tokens=transcript_usage, poster=None, health=None, pr_state=None, @@ -920,6 +947,7 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, stopped=out.get("action") == "stopped") if status: out["status"] = status + _note_auth_file(slot, now) return out @@ -1090,25 +1118,72 @@ def _steered(out: dict, commands: list, paused: bool) -> dict: CORRECTION_FILE = "correction.md" -#: An optional separate GitHub token for the watcher's writes (a bot account), -#: given to its own `gh` calls as `GH_TOKEN` and to nothing else: then the -#: human's account is the one notified by an @mention (#611 review). -GH_TOKEN_ENV = "PYAUTO_SHIFT_GH_TOKEN" +#: The watcher's own GitHub identity, for its own `gh` calls and nothing else +#: (then the human's account is the one an @mention notifies, #611 review): +#: its minimal GitHub App (`PYAUTO_SHIFT_APP_*`, PyAutoBrain#630), else this +#: static token as the fallback, else `gh`'s own auth. See `_app_token`. +GH_TOKEN_ENV = _app_token.GH_TOKEN_ENV +#: The identity bound for the current tick (`tick`); outside one, a fresh one. +_AUTH = None + + +def _auth(): + return _AUTH if _AUTH is not None else _app_token.WatcherAuth(orchestrator_home()) def _gh_env() -> dict | None: - token = os.environ.get(GH_TOKEN_ENV, "").strip() - return {**os.environ, "GH_TOKEN": token} if token else None + """The environment for one of the watcher's own `gh` calls. Raises + `_app_token.AppTokenError` when an App is configured and no installation + token can be had: the caller then makes no call — never one under the + human's `gh` auth in its place.""" + return _auth().env() + + +def _note_auth(counters: dict, now: _dt.datetime) -> bool: + """Record in `counters` (and so in the digest) that the watcher's App + identity failed this tick and its GitHub writes were held; once a tick.""" + a = _AUTH + if a is None or not a.used or not a.error: + return False + g = counters.get("github_auth") or {} + if g.get("last") == _iso(now): + return False + counters["github_auth"] = {"error": a.error, "first": g.get("first") or _iso(now), + "last": _iso(now), "ticks": int(g.get("ticks") or 0) + 1} + return True + + +def _note_auth_file(slot: Path, now: _dt.datetime) -> None: + if _AUTH is not None and _AUTH.used and _AUTH.error and (slot / COUNTERS_FILE).exists(): + c = read_counters(slot) + if _note_auth(c, now): + _write_counters(slot, c) + + +def _poster_login(counters: dict, whoami=None) -> None: + """Once per shift: who the watcher's comments post as. An App identity + that cannot be read now is read again later, never recorded as ''.""" + if "poster_login" in counters: + return + who = (whoami or gh_login)() + if who is None and _auth().mode == "app": + return + counters["poster_login"] = who or "" def gh_login(run=None) -> str | None: - """The login the watcher's comments post as (`gh api user`, under the - posting token); None when it cannot say.""" + """The login the watcher's comments post as; None when it cannot say. As + the App, `[bot]` (`GET /app` with its JWT — `gh api user` does not + answer for an installation token); else `gh api user` under the posting + token.""" + a = _auth() + if a.mode == "app": + return None if a.error else a.login() run = run or subprocess.run try: res = run(["gh", "api", "user", "--jq", ".login"], capture_output=True, text=True, timeout=60, env=_gh_env()) - except (OSError, subprocess.SubprocessError): + except (OSError, subprocess.SubprocessError, _app_token.AppTokenError): return None login = (res.stdout or "").strip() return login if res.returncode == 0 and login else None @@ -1116,12 +1191,17 @@ def gh_login(run=None) -> str | None: def gh_comment(issue_url: str, body_file: Path, run=None) -> dict: """The watcher's one kind of write: a comment on the brief's `issue:`, - posted as `PYAUTO_SHIFT_GH_TOKEN`'s account when it is set. `retry: False` - marks a failure after which the comment may have landed.""" + posted as the watcher's own identity (`_gh_env`). `retry: False` marks a + failure after which the comment may have landed; `unsent: True` one where + no call was made (no App token), which costs the post no try.""" + try: + env = _gh_env() + except _app_token.AppTokenError as e: + return {"posted": False, "unsent": True, "error": f"no GitHub identity: {e}"[:300]} run = run or subprocess.run try: res = run(["gh", "issue", "comment", issue_url, "--body-file", str(body_file)], - capture_output=True, text=True, timeout=120, env=_gh_env()) + capture_output=True, text=True, timeout=120, env=env) except subprocess.TimeoutExpired: return {"posted": False, "retry": False, "error": "gh timed out — the comment may have landed; not retried"} @@ -1138,8 +1218,11 @@ def _post_and_record(marker: Path, rec: dict, body_file: Path, poster) -> dict: res = {"posted": False, "retry": False, "error": "the brief names no issue:"} else: res = (poster or gh_comment)(issue, body_file) - rec = {k: v for k, v in rec.items() if k not in ("error", "retry")} + rec = {k: v for k, v in rec.items() if k not in ("error", "retry", "unsent")} rec.update(res) + if res.get("unsent"): + # Nothing reached GitHub (no App token): this try does not count. + rec["tries"] = max(0, int(rec.get("tries", 1)) - 1) rec["state"] = ("posted" if res.get("posted") else "failed" if res.get("retry", True) else "unknown") marker.write_text(json.dumps(rec, sort_keys=True)) @@ -1295,10 +1378,10 @@ def _mentions(slot: Path, counters: dict, shift: dict, poster, now: _dt.datetime if not todo: return out login = mention_login() - if login and "poster_login" not in counters: + if login: # Once per shift: who the comments post as. The human's own login # gets no notification for its own comment (#611 review). - counters["poster_login"] = (whoami or gh_login)() or "" + _poster_login(counters, whoami) if login: counters["mention_login"] = login for task, state, reason, w, key, name in todo: @@ -1351,11 +1434,15 @@ def _mentions(slot: Path, counters: dict, shift: dict, poster, now: _dt.datetime def gh_comment_edit(comment_url: str, body_file: Path, run=None) -> dict: """Edit the watcher's own status comment in place (`gh api PATCH`), as - `PYAUTO_SHIFT_GH_TOKEN`'s account when it is set — the only edit the - watcher makes. An edit is idempotent, so any failure is retried next tick.""" + watcher's own identity (`_gh_env`) — the only edit the watcher makes. An + edit is idempotent, so any failure is retried next tick.""" m = _COMMENT_API_RE.match(comment_url or "") if not m: return {"edited": False, "error": f"not a comment URL: {comment_url!r}"[:300]} + try: + env = _gh_env() + except _app_token.AppTokenError as e: + return {"edited": False, "error": f"no GitHub identity: {e}"[:300]} payload = Path(body_file).with_suffix(".json") payload.write_text(json.dumps({"body": Path(body_file).read_text(encoding="utf-8")}), encoding="utf-8") @@ -1364,7 +1451,7 @@ def gh_comment_edit(comment_url: str, body_file: Path, run=None) -> dict: res = run(["gh", "api", "-X", "PATCH", f"repos/{m.group(1)}/{m.group(2)}/issues/comments/{m.group(3)}", "--input", str(payload), "--jq", ".html_url"], - capture_output=True, text=True, timeout=120, env=_gh_env()) + capture_output=True, text=True, timeout=120, env=env) except (OSError, subprocess.SubprocessError) as e: return {"edited": False, "error": f"gh could not edit: {e}"[:300]} if res.returncode != 0: @@ -1379,12 +1466,16 @@ def gh_issue_comments(issue_url: str, since: str, run=None) -> list[dict] | None m = _ISSUE_API_RE.match(issue_url or "") if not m: return None + try: + env = _gh_env() + except _app_token.AppTokenError: + return None run = run or subprocess.run query = f"?per_page=100&since={since}" if since else "?per_page=100" try: res = run(["gh", "api", f"repos/{m.group(1)}/{m.group(2)}/issues/{m.group(3)}" f"/comments{query}"], - capture_output=True, text=True, timeout=60, env=_gh_env()) + capture_output=True, text=True, timeout=60, env=env) if res.returncode != 0: return None data = json.loads(res.stdout or "") @@ -1488,7 +1579,8 @@ def _steer(slot: Path, counters: dict, shift: dict, now: _dt.datetime, github=No The same read adopts a status comment whose create may have landed — even with no login set, when it is the only reason to read — and only one - written by the posting identity (`gh api user`, once per shift).""" + written by the posting identity (`gh api user`, or the App's + `[bot]`; once per shift).""" issue = shift.get("issue", "") login = mention_login() marker = slot / STATUS_MARKER @@ -1503,8 +1595,8 @@ def _steer(slot: Path, counters: dict, shift: dict, now: _dt.datetime, github=No counters["commands_unread"] = _iso(now) return [] counters.pop("commands_unread", None) - if adopting and "poster_login" not in counters: - counters["poster_login"] = (whoami or gh_login)() or "" + if adopting: + _poster_login(counters, whoami) poster = counters.get("poster_login") or "" seen = set(counters.get("commands_seen") or []) out = [] @@ -1753,6 +1845,7 @@ def late_sweep(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, out = {"action": "late", "reaped": reaped, "late": lines, "ledger": ledger} if posts: out["posts"] = posts + _note_auth_file(slot, now) return out @@ -1803,8 +1896,13 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *, if not _brief.is_shadow(brief): _github_merges(counters, _brief._iso((top.get("review-at") or {}).get("value", "")), pr_state) - _write_counters(slot, counters) issue = (top.get("issue") or {}).get("value", "") + if issue.startswith("http"): + # The digest is about to be posted: an App identity that cannot be had + # is named in the digest itself, which still reaches the record. + _auth().failed() + _note_auth(counters, now) + _write_counters(slot, counters) digest = _digest.build(brief, slot, counters, health=health, issue=issue) (slot / DIGEST_FILE).write_text(digest, encoding="utf-8") result = {"action": "digest", "ledger": None, "post": None, "packet": None} diff --git a/tests/conftest.py b/tests/conftest.py index 0819d012..21c547eb 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -55,6 +55,9 @@ def _no_real_github(monkeypatch): real_read(issue, since, run=run) if run else None) monkeypatch.delenv(orch.MENTION_ENV, raising=False) monkeypatch.delenv(orch.GH_TOKEN_ENV, raising=False) + for key in ("PYAUTO_SHIFT_APP_ID", "PYAUTO_SHIFT_APP_INSTALLATION_ID", + "PYAUTO_SHIFT_APP_KEY"): # PyAutoBrain#630 + monkeypatch.delenv(key, raising=False) if digest is not None: real_health = digest.pr_health monkeypatch.setattr(digest, "pr_health", lambda url, run=None: diff --git a/tests/test_orchestrator_app_identity.py b/tests/test_orchestrator_app_identity.py new file mode 100644 index 00000000..599e09d1 --- /dev/null +++ b/tests/test_orchestrator_app_identity.py @@ -0,0 +1,317 @@ +"""PyAutoBrain#630: the shift watcher posts as its own minimal GitHub App. + +The App (`PYAUTO_SHIFT_APP_ID` / `_INSTALLATION_ID` / `_KEY`) signs an RS256 +JWT, mints an installation token on a tick's first watcher GitHub call, holds +it in memory for that tick only (never on disk), and gives it to the watcher's +own `gh` calls only. A mint that fails holds every watcher call — never the +human's `gh` auth in its place — and backs off 10 min. A +generated RSA key and a fake API stand in for GitHub: nothing here reaches +the network. +""" + +from __future__ import annotations + +import base64 +import datetime as _dt +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding, rsa + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +import test_orchestrator_dispatch as d # noqa: E402 — the 3b fixtures +from test_orchestrator_dispatch import _digest, orch # noqa: E402 +import test_orchestrator_steering as st # noqa: E402 — the fake GitHub +import _app_token # noqa: E402 + +NOW = d.NOW +T0 = NOW.timestamp() +APP_ID, INSTALLATION = "123456", "98765" +SLUG = "pyautolabs-watcher" + + +def _b64decode(part: str) -> bytes: + return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)) + + +def _claims(jwt_token: str) -> dict: + return json.loads(_b64decode(jwt_token.split(".")[1])) + + +@pytest.fixture(scope="module") +def rsa_key(tmp_path_factory): + """A throwaway 2048-bit key: (pem path, public key).""" + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + path = tmp_path_factory.mktemp("app") / "watcher.pem" + path.write_bytes(key.private_bytes(serialization.Encoding.PEM, + serialization.PrivateFormat.TraditionalOpenSSL, + serialization.NoEncryption())) + return path, key.public_key() + + +def _verify(jwt_token: str, public_key) -> None: + head, body, sig = jwt_token.split(".") + public_key.verify(_b64decode(sig), f"{head}.{body}".encode(), padding.PKCS1v15(), + hashes.SHA256()) # raises when the signature is wrong + + +class FakeAPI: + """`POST /app/installations//access_tokens` and `GET /app`. A token + lives `ttl` s from the JWT's own clock (its `iat` + 60); `fail` refuses.""" + + def __init__(self, fail=False, ttl=3600): + self.calls, self.fail, self.ttl, self.minted = [], fail, ttl, 0 + + def __call__(self, method, url, headers, body=None): + self.calls.append((method, url, headers)) + assert headers["Authorization"].startswith("Bearer ") + if self.fail: + raise _app_token.AppTokenError(f"{method} {url} returned HTTP 401") + now = _claims(headers["Authorization"][7:])["iat"] + 60 + if method == "POST" and url.endswith("/access_tokens"): + self.minted += 1 + exp = _dt.datetime.fromtimestamp(now + self.ttl, _dt.timezone.utc) + return {"token": f"ghs_fake{self.minted}", + "expires_at": exp.strftime("%Y-%m-%dT%H:%M:%SZ")} + if (method, url) == ("GET", f"{_app_token.API}/app"): + return {"slug": SLUG} + raise AssertionError(f"unexpected API call {method} {url}") + + +def _app_env(key_path, **extra) -> dict: + return {**os.environ, _app_token.APP_ID_ENV: APP_ID, + _app_token.APP_INSTALLATION_ENV: INSTALLATION, + _app_token.APP_KEY_ENV: str(key_path), **extra} + + +def _settings(key_path) -> dict: + return _app_token.app_settings(_app_env(key_path)) + + +# --- the JWT ------------------------------------------------------------------------ + +def test_the_jwt_claims_are_iss_iat_minus_60_and_exp_plus_9_minutes(rsa_key): + path, public = rsa_key + token = _app_token.make_jwt(APP_ID, str(path), now=1_000_000) + assert json.loads(_b64decode(token.split(".")[0]))["alg"] == "RS256" + assert _claims(token) == {"iss": APP_ID, "iat": 1_000_000 - 60, "exp": 1_000_000 + 540} + _verify(token, public) + + +@pytest.mark.skipif(shutil.which("openssl") is None, reason="openssl not installed") +def test_without_pyjwt_openssl_signs_the_same_claims_with_no_shell(rsa_key, monkeypatch): + path, public = rsa_key + monkeypatch.setitem(sys.modules, "jwt", None) # `import jwt` now fails + calls = [] + + def run(argv, **kw): + calls.append((argv, kw)) + return subprocess.run(argv, **kw) + token = _app_token.make_jwt(APP_ID, str(path), now=2_000_000, run=run) + assert calls and calls[0][0] == ["openssl", "dgst", "-sha256", "-sign", str(path)] + assert "shell" not in calls[0][1] + assert _claims(token) == {"iss": APP_ID, "iat": 2_000_000 - 60, "exp": 2_000_000 + 540} + _verify(token, public) + + +def test_a_key_that_cannot_be_read_is_an_error_naming_no_secret(tmp_path): + with pytest.raises(_app_token.AppTokenError, match="PYAUTO_SHIFT_APP_KEY"): + _app_token.make_jwt(APP_ID, str(tmp_path / "absent.pem"), now=1) + + +# --- mint in memory, once a tick; a failure backs off --------------------------------- + +def _files_holding(root: Path, secret: str) -> list[Path]: + return [f for f in Path(root).rglob("*") if f.is_file() + and secret.encode() in f.read_bytes()] + + +def test_the_token_is_minted_once_a_tick_in_memory_and_never_written(rsa_key, tmp_path): + path, public = rsa_key + api, state = FakeAPI(), tmp_path / "state" + auth = _app_token.WatcherAuth(state, now=T0, environ=_app_env(path), request=api) + assert api.calls == [] # nothing until a call needs it + assert auth.env()["GH_TOKEN"] == "ghs_fake1" + method, url, headers = api.calls[0] + assert (method, url) == ("POST", f"{_app_token.API}/app/installations/{INSTALLATION}" + "/access_tokens") + jwt_token = headers["Authorization"][7:] + _verify(jwt_token, public) + assert _claims(jwt_token)["iss"] == APP_ID + # Reused for the rest of the tick: no second mint. + assert auth.env()["GH_TOKEN"] == auth.env()["GH_TOKEN"] == "ghs_fake1" + assert api.minted == 1 + # Nothing on disk holds it (a worker runs as the same user). + assert _files_holding(tmp_path, "ghs_fake") == [] + # The next tick mints its own. + nxt = _app_token.WatcherAuth(state, now=T0 + 180, environ=_app_env(path), request=api) + assert nxt.env()["GH_TOKEN"] == "ghs_fake2" and api.minted == 2 + + +def test_a_failed_mint_records_only_a_time_and_reason_and_backs_off(rsa_key, tmp_path): + path, _ = rsa_key + api, state = FakeAPI(fail=True), tmp_path / "state" + + def auth(at): + return _app_token.WatcherAuth(state, now=at, environ=_app_env(path), request=api) + a = auth(T0) + with pytest.raises(_app_token.AppTokenError, match="HTTP 401"): + a.env() + assert a.failed() and a.secrets() == set() + rec = json.loads((state / _app_token.MINT_FAILURE_FILE).read_text()) + assert set(rec) == {"at", "error"} and rec["at"] == T0 and rec["error"].endswith("HTTP 401") + assert sorted(f.name for f in state.iterdir()) == [_app_token.MINT_FAILURE_FILE] + # Inside the back-off: no call at all, an error. + n = len(api.calls) + with pytest.raises(_app_token.AppTokenError, match="no new mint"): + auth(T0 + 599).env() + assert len(api.calls) == n + # After it: tried again; a success removes the record and writes nothing. + api.fail = False + assert auth(T0 + 601).env()["GH_TOKEN"] == "ghs_fake1" + assert list(state.iterdir()) == [] and _files_holding(tmp_path, "ghs_fake") == [] + + +def test_in_app_mode_a_missing_token_raises_never_falls_back(rsa_key, tmp_path): + path, _ = rsa_key + a = _app_token.WatcherAuth(tmp_path, now=T0, environ=_app_env(path), request=FakeAPI()) + a._resolved = True # resolved, yet no token + with pytest.raises(_app_token.AppTokenError, match="no App installation token"): + a.env() + assert a.failed() + + +def test_the_app_login_is_its_slug_as_a_bot_never_gh_api_user(rsa_key, tmp_path, + monkeypatch): + path, _ = rsa_key + api = FakeAPI() + monkeypatch.setattr(orch, "_AUTH", _app_token.WatcherAuth( + tmp_path, now=T0, environ=_app_env(path), request=api)) + + def no_gh(argv, **kw): + raise AssertionError(f"gh called: {argv}") + assert orch.gh_login(run=no_gh) == f"{SLUG}[bot]" + assert [c[:2] for c in api.calls] == [("GET", f"{_app_token.API}/app")] + # An App can never be the mentioned human: no self-mention warning. + lines = _digest.worker_lines({"poster_login": f"{SLUG}[bot]", + "mention_login": st.LOGIN}) + assert not any("will not notify" in ln for ln in lines) + + +# --- the watcher's calls: the App token, else nothing --------------------------------- + +def _gh(gh: st.FakeGitHub, envs: list): + def run(argv, **kw): + envs.append(kw.get("env")) + return gh(argv, **kw) + return run + + +def _tick(brief, mind, home, minutes, claude, run, auth): + return orch.tick(brief, mind, home=home, now=st._at(minutes), grace_s=0, auth=auth, + spawner=orch.RealSpawner(brief, "auto", run=claude), + agents=orch.AgentsView([]), tokens=lambda s: 0, + health=lambda u: "RUNNING", github=run, pr_state=lambda u: None, + poster=lambda i, b: orch.gh_comment(i, b, run=run)) + + +def test_a_mint_failure_holds_every_write_and_never_uses_the_human_auth( + rsa_key, tmp_path, monkeypatch): + path, _ = rsa_key + mind, brief, home, slot = st._shift(tmp_path, monkeypatch) + claude, gh, envs = d.FakeClaude(), st.FakeGitHub(), [] + run, api = _gh(gh, envs), FakeAPI(fail=True) + env = _app_env(path, GH_TOKEN="human-token-not-real") + + def auth(minutes): + return _app_token.WatcherAuth(home, now=st._at(minutes).timestamp(), environ=env, + request=api) + r = _tick(brief, mind, home, 0, claude, run, auth(0)) + assert gh.calls == [] and envs == [] # no read, no status, no gh at all + assert r["github_auth"]["writes"] == "held" and "HTTP 401" in r["github_auth"]["error"] + logged = json.loads((slot / orch.LOG_FILE).read_text().splitlines()[-1]) + assert logged["github_auth"]["writes"] == "held" + assert orch.read_counters(slot)["github_auth"]["ticks"] == 1 + assert r["spawned"] == [{"task": "t1", "pid": 0}] # the tick itself carried on + + # review-at: the digest is written and names the failure; its post is held + # and costs no try. + r = _tick(brief, mind, home, 151, claude, run, auth(151)) + assert r["action"] == "digest" and gh.calls == [] and envs == [] + digest = (slot / orch.DIGEST_FILE).read_text() + assert "GitHub writes held — the watcher's App token could not be had" in digest + marker = json.loads((slot / orch.DIGEST_MARKER).read_text()) + assert marker["state"] == "failed" and marker["tries"] == 0 and marker["unsent"] + + # The App recovers: the late sweep posts the digest as the App, and only so. + api.fail = False + r = _tick(brief, mind, home, 162, claude, run, auth(162)) + assert r["action"] == "late" and r["posts"]["digest"] == "posted" + assert set(gh.calls) == {"create"} and len(envs) == len(gh.calls) # + the correction + assert all(e["GH_TOKEN"] == "ghs_fake1" and "GITHUB_TOKEN" not in e for e in envs) + assert api.minted == 1 # one mint, reused within the tick + assert _files_holding(tmp_path, "ghs_fake") == [] # no file holds the token + assert json.loads((slot / orch.DIGEST_MARKER).read_text())["tries"] == 1 + + +def test_an_app_configured_in_part_makes_no_call_at_all(tmp_path, monkeypatch): + monkeypatch.setattr(orch, "_AUTH", _app_token.WatcherAuth( + tmp_path, now=T0, environ={_app_token.APP_ID_ENV: APP_ID, + orch.GH_TOKEN_ENV: "static-not-real"})) + + def no_gh(argv, **kw): + raise AssertionError(f"gh called: {argv}") + body = tmp_path / "b.md" + body.write_text("x") + res = orch.gh_comment(st.ISSUE, body, run=no_gh) + assert res["posted"] is False and res["unsent"] and "partly configured" in res["error"] + assert orch.gh_issue_comments(st.ISSUE, "", run=no_gh) is None + assert orch.gh_comment_edit(f"{st.ISSUE}#issuecomment-1", body, run=no_gh)["edited"] \ + is False + assert orch.gh_login(run=no_gh) is None + + +def test_the_static_token_stays_the_fallback_without_the_app(tmp_path, monkeypatch): + monkeypatch.setattr(orch, "_AUTH", _app_token.WatcherAuth( + tmp_path, now=T0, environ={orch.GH_TOKEN_ENV: "static-not-real"})) + assert orch._gh_env()["GH_TOKEN"] == "static-not-real" + monkeypatch.setattr(orch, "_AUTH", _app_token.WatcherAuth(tmp_path, now=T0, environ={})) + assert orch._gh_env() is None # gh's own auth, as before + + +# --- never in a worker --------------------------------------------------------------- + +def test_app_settings_and_minted_token_never_reach_a_worker_or_closeout( + rsa_key, tmp_path, monkeypatch): + path, _ = rsa_key + home = tmp_path / "home" + api = FakeAPI() + env = _app_env(path) + for key in _app_token.APP_ENVS: + monkeypatch.setenv(key, env[key]) + monkeypatch.setenv(orch.GH_TOKEN_ENV, "static-not-real") + monkeypatch.setenv("GITHUB_TOKEN", "ghs_fake1") # a minted token leaked into env + monkeypatch.setenv("GH_TOKEN", "human-token-not-real") + auth = _app_token.WatcherAuth(home, now=T0, request=api) + auth.env() # this tick's token, in memory + monkeypatch.setattr(orch, "_AUTH", auth) + mind, brief, _ = d._shift(tmp_path) + claude = d.FakeClaude() + sp = orch.RealSpawner(brief, "auto", run=claude) + sp.spawn("t1", "draft/feature/pyautobrain/t1.md", tmp_path / "leases") + sp.spawn_closeout("t1", "https://github.com/o/r/pull/1", "x.md", tmp_path / "leases") + assert len(claude.calls) == 2 + for _argv, kw in claude.calls: + wenv = kw["env"] + assert not set(_app_token.APP_ENVS) & set(wenv) + assert orch.GH_TOKEN_ENV not in wenv and "GITHUB_TOKEN" not in wenv + assert not {"ghs_fake1", "static-not-real", str(path)} & set(wenv.values()) + assert wenv["GH_TOKEN"] == "human-token-not-real" + assert api.minted == 1 # stripping never mints again