diff --git a/README.md b/README.md index fdce967..45e2ba7 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Environment variables with the same meaning are also supported: - `GITHUB_APP_INSTALLATION_IDS` (JSON object or `OWNER=ID,OWNER2=ID2` mapping) - `GITHUB_APP_PRIVATE_KEY_PATH` - `GITHUB_APP_PRIVATE_KEY` (PEM contents; useful for CI) +- `GITHUB_APP_TOKEN_BROKER=nono` (no private key in this environment; see [Running inside nono](#running-inside-nono-token-broker-mode)) Repository access is controlled by the GitHub App installation scope in GitHub. If an agent should not access a repository, remove that repository from the GitHub App installation scope. @@ -83,6 +84,35 @@ git-app --repo OWNER/REPO push origin my-branch `gh-app` injects an ephemeral installation token as `GH_TOKEN` and `GITHUB_TOKEN` for the child `gh` process. `git-app` injects a temporary askpass helper so HTTPS Git operations authenticate as the GitHub App installation token without writing credentials into the remote URL. +## Running inside nono (token broker mode) + +[nono](https://nono.sh) can run the agent in a sandbox that never holds the GitHub App private key. Enable broker mode with `GITHUB_APP_TOKEN_BROKER=nono` or `github_app.token_broker: nono`: + +```yaml +github_app: + client_id: "Iv1.exampleclientid" + installation_ids: + ExampleOrg: "123456" + token_broker: nono +``` + +```bash +hermes-github-app setup --token-broker nono --client-id Iv1.exampleclientid --installation-id 987654 +``` + +In broker mode the plugin reads no private key; `private_key_path` and `GITHUB_APP_PRIVATE_KEY*` are ignored. Installation tokens are not minted locally. The plugin sends the placeholder `nono-phantom-github-app` as its token, and nono's supervisor, outside the sandbox, handles the real credentials: + +- Its TLS-intercepting proxy replaces the `Authorization` header on requests to `api.github.com`, `uploads.github.com`, and `github.com` with an installation token chosen by owner from the request path. Git HTTPS uses the same token as Basic `x-access-token`. +- The app JWT is injected for exactly `GET /app`. + +What this means for agents: + +- `github_app_*` tools, `hermes-github-app api`, `gh-app`, and `git-app` work unchanged; the placeholder flows through. +- Plain `git push` over HTTPS and plain `gh` also work, because the proxy injects credentials into those requests. Keep remotes HTTPS. SSH remotes use local SSH keys and are not covered. +- The agent cannot obtain a real token, by design. `hermes-github-app token` prints the placeholder with a note on stderr. +- `client_id` is still required in broker mode. It is non-secret and is reported in auth metadata. +- `hermes-github-app doctor` shows a `token broker` check and an `HTTPS_PROXY set` check. If the proxy variable is missing, the agent is not running inside nono and no credentials will be injected. + ## Migrating existing Hermes skills and jobs To keep agents from falling back to local human credentials, update existing GitHub-related Hermes skills, cron jobs, and subagent prompts with these rules: @@ -116,8 +146,8 @@ Before the first release, configure PyPI Trusted Publishing for this repository Release example: ```bash -git tag 0.2.0 -git push origin 0.2.0 +git tag 0.3.0 +git push origin 0.3.0 ``` Tags like `v0.1.0`, `0.1`, or `0.1.0rc1` will not publish. diff --git a/plugin.yaml b/plugin.yaml index efb86d4..a8fd92e 100644 --- a/plugin.yaml +++ b/plugin.yaml @@ -1,5 +1,5 @@ name: github-app -version: 0.1.0 +version: 0.3.0 description: "GitHub App identity integration for Hermes: per-agent app token minting, GitHub API tools, gh/git wrappers, CLI, and workflow skill." author: Hermes GitHub App Plugin Contributors provides_tools: @@ -26,5 +26,8 @@ requires_env: description: "Optional owner-to-installation-ID mapping for apps installed in multiple orgs. JSON object or OWNER=ID,OWNER2=ID2. Can also be set under github_app.installation_ids." secret: false - name: GITHUB_APP_PRIVATE_KEY_PATH - description: "Path to the GitHub App private key PEM. Can also be set in ~/.hermes/config.yaml under github_app.private_key_path." + description: "Path to the GitHub App private key PEM. Can also be set in ~/.hermes/config.yaml under github_app.private_key_path. Not used when GITHUB_APP_TOKEN_BROKER is set." secret: true + - name: GITHUB_APP_TOKEN_BROKER + description: "Set to nono when the agent runs in the nono sandbox and the token broker injects credentials. No private key is read in this mode. Can also be set in ~/.hermes/config.yaml under github_app.token_broker." + secret: false diff --git a/pyproject.toml b/pyproject.toml index 760c942..5f58bbb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "hermes-github-app-plugin" -version = "0.2.0" +version = "0.3.0" description = "Hermes plugin for per-agent GitHub App identity, gh/git wrappers, and GitHub App-aware tools." readme = "README.md" requires-python = ">=3.10" diff --git a/skills/github-app-workflow/SKILL.md b/skills/github-app-workflow/SKILL.md index 57597bd..7b1ab0f 100644 --- a/skills/github-app-workflow/SKILL.md +++ b/skills/github-app-workflow/SKILL.md @@ -36,6 +36,14 @@ After setup, run `hermes-github-app doctor --repo OWNER/REPO` to verify console 7. Expect comments, PRs, and API writes to appear as `[bot]`. 8. Treat the GitHub App installation scope as the repository access boundary. The plugin does not maintain a separate local repository/owner allowlist. +## Running inside nono (token broker mode) + +If `hermes-github-app doctor` reports `token broker: nono`, this agent runs in the nono sandbox. By design it holds no GitHub App private key and cannot obtain a real installation token. + +- Do not search for, copy, or request a private key or a real token. `hermes-github-app token` prints a placeholder; nono's proxy outside the sandbox injects the real credentials into GitHub requests. +- `github_app_*` tools, `gh-app`, and `git-app` work as described above. Plain `gh` and HTTPS `git push` also work because the proxy injects credentials, so keep remotes HTTPS. +- If `doctor` reports `HTTPS_PROXY set` as failed, the agent is not running inside nono and no credentials will be injected. Stop and report that. Do not fall back to local human credentials or SSH keys. + ## Updating existing Hermes skills Patch any GitHub-related skill, cron prompt, or subagent instruction that mentions `gh`, `git push`, GitHub SSH remotes, or `@me` assumptions: diff --git a/src/hermes_github_app_plugin/auth.py b/src/hermes_github_app_plugin/auth.py index 2046266..0a44880 100644 --- a/src/hermes_github_app_plugin/auth.py +++ b/src/hermes_github_app_plugin/auth.py @@ -12,9 +12,10 @@ import httpx import jwt -from .config import GitHubAppConfig +from .config import NONO_PHANTOM_TOKEN, GitHubAppConfig _MIN_REDACT_LENGTH = 8 +_BROKERED_TOKEN_LIFETIME = timedelta(hours=1) @dataclass(frozen=True) @@ -26,6 +27,7 @@ class InstallationToken: installation_id: str client_id: str app_slug: str | None + token_broker: str | None = None @property def redacted(self) -> str: @@ -48,7 +50,13 @@ def config(self) -> GitHubAppConfig: return self._config def create_jwt(self) -> str: - """Create a GitHub App JWT for installation-token exchange.""" + """Create a GitHub App JWT for installation-token exchange. + + In token broker mode there is no key to sign with; the placeholder is sent and the + broker replaces it outside the sandbox. + """ + if self._config.token_broker: + return NONO_PHANTOM_TOKEN now = int(time.time()) payload = {"iat": now - 60, "exp": now + 9 * 60, "iss": self._config.client_id} encoded = jwt.encode(payload, self._config.private_key, algorithm="RS256") @@ -67,6 +75,26 @@ def get_installation_token( ): return cached_token + if self._config.token_broker: + token = self._brokered_token(installation_id) + else: + token = self._exchange_app_jwt(installation_id) + self._cached_tokens[installation_id] = token + return token + + def _brokered_token(self, installation_id: str) -> InstallationToken: + """Return the placeholder token with no network call; the broker injects the real one.""" + return InstallationToken( + token=NONO_PHANTOM_TOKEN, + expires_at=datetime.now(timezone.utc) + _BROKERED_TOKEN_LIFETIME, + installation_id=installation_id, + client_id=self._config.client_id, + app_slug=self._config.app_slug, + token_broker=self._config.token_broker, + ) + + def _exchange_app_jwt(self, installation_id: str) -> InstallationToken: + """Exchange the app JWT for an installation access token.""" response = self._client.post( f"{self._config.github_api_url}/app/installations/{installation_id}/access_tokens", headers={ @@ -79,15 +107,13 @@ def get_installation_token( data = response.json() expires_at_raw = str(data["expires_at"]) expires_at = datetime.fromisoformat(expires_at_raw.replace("Z", "+00:00")) - token = InstallationToken( + return InstallationToken( token=str(data["token"]), expires_at=expires_at, installation_id=installation_id, client_id=self._config.client_id, app_slug=self._config.app_slug, ) - self._cached_tokens[installation_id] = token - return token def app_request( self, @@ -125,6 +151,7 @@ def app_request( "app_slug": self._config.app_slug, "installation_id": self._config.installation_id, "installation_ids": dict(self._config.installation_ids), + "token_broker": self._config.token_broker, }, "status_code": response.status_code, "result": response.json() if response.content else {"ok": True}, @@ -197,6 +224,7 @@ def auth_metadata(token: InstallationToken, *, repo: str | None = None) -> dict[ "actor_expected": actor, "repository": repo, "token": token.redacted, + "token_broker": token.token_broker, "expires_at": token.expires_at.isoformat(), } diff --git a/src/hermes_github_app_plugin/cli.py b/src/hermes_github_app_plugin/cli.py index 5aa76de..2ffdc80 100644 --- a/src/hermes_github_app_plugin/cli.py +++ b/src/hermes_github_app_plugin/cli.py @@ -16,7 +16,13 @@ import httpx from .auth import GitHubAppAuth, auth_metadata, requires_app_jwt -from .config import ConfigurationError, load_config, write_github_app_config +from .config import ( + ConfigurationError, + GitHubAppConfig, + load_config, + parse_token_broker, + write_github_app_config, +) def register_cli(parser: argparse.ArgumentParser) -> None: @@ -38,6 +44,12 @@ def register_cli(parser: argparse.ArgumentParser) -> None: help="Owner-specific installation ID mapping; repeat for multiple orgs", ) setup.add_argument("--private-key-path", help="Path to GitHub App private key PEM") + setup.add_argument( + "--token-broker", + metavar="NAME", + help="Credentials are injected outside the sandbox by this broker (supported: nono); " + "no private key is configured", + ) setup.add_argument("--app-slug", help="Optional GitHub App slug, e.g. my-agent") setup.add_argument( "--skip-verify", action="store_true", help="Write config without minting a token" @@ -134,6 +146,15 @@ def _setup(args: argparse.Namespace) -> int: """Interactively write GitHub App configuration.""" print("Hermes GitHub App setup") print("Required values are unmarked. Optional prompts include '(optional)'.") + token_broker = parse_token_broker( + getattr(args, "token_broker", None) or os.environ.get("GITHUB_APP_TOKEN_BROKER"), + source="--token-broker or GITHUB_APP_TOKEN_BROKER", + ) + if token_broker and args.private_key_path: + raise ConfigurationError( + "--private-key-path cannot be combined with --token-broker; " + "the private key must stay outside the agent's sandbox" + ) installation_ids = _parse_installation_id_for_args(list(args.installation_id_for)) values = { "client_id": _value_or_prompt( @@ -151,7 +172,11 @@ def _setup(args: argparse.Namespace) -> int: non_interactive=bool(args.non_interactive), ), "installation_ids": installation_ids, - "private_key_path": _value_or_prompt( + "token_broker": token_broker, + # An empty value removes any private_key_path left by an earlier non-brokered setup. + "private_key_path": "" + if token_broker + else _value_or_prompt( args.private_key_path, "GitHub App private key path", env="GITHUB_APP_PRIVATE_KEY_PATH", @@ -166,10 +191,11 @@ def _setup(args: argparse.Namespace) -> int: non_interactive=bool(args.non_interactive), ), } - key_path = Path(str(values["private_key_path"])).expanduser() - if not key_path.exists(): - raise ConfigurationError(f"private key file does not exist: {key_path}") - _warn_private_key_permissions(key_path) + if not token_broker: + key_path = Path(str(values["private_key_path"])).expanduser() + if not key_path.exists(): + raise ConfigurationError(f"private key file does not exist: {key_path}") + _warn_private_key_permissions(key_path) written = write_github_app_config(values) print(f"Wrote GitHub App config to {written}") if args.skip_verify: @@ -189,22 +215,19 @@ def _doctor(repo: str | None, *, skip_network: bool) -> int: try: config = load_config() checks.append(("GitHub App config loaded", True, "client_id and installation_id present")) - key_source = Path(config.private_key_source).expanduser() - if config.private_key_source == "GITHUB_APP_PRIVATE_KEY": - checks.append(("private key loaded", True, "inline environment variable")) + if config.token_broker: + checks.extend(_token_broker_checks(config.token_broker)) else: - checks.append(("private key file exists", key_source.exists(), str(key_source))) - checks.append( - ( - "private key file permissions", - _private_key_permissions_ok(key_source), - _mode(key_source), - ) - ) + checks.extend(_private_key_checks(config)) if not skip_network: auth = GitHubAppAuth(config) token = auth.get_installation_token(repo=repo, force_refresh=True) - checks.append(("installation token minted", True, token.redacted)) + minted_label = ( + f"installation token brokered by {config.token_broker}" + if config.token_broker + else "installation token minted" + ) + checks.append((minted_label, True, token.redacted)) app_result = auth.app_request("GET", "/app")["result"] checks.append(("/app API reachable", True, str(app_result.get("slug", "ok")))) if repo: @@ -230,6 +253,35 @@ def _doctor(repo: str | None, *, skip_network: bool) -> int: return 1 +def _private_key_checks(config: GitHubAppConfig) -> list[tuple[str, bool, str]]: + if config.private_key_source == "GITHUB_APP_PRIVATE_KEY": + return [("private key loaded", True, "inline environment variable")] + key_source = Path(config.private_key_source).expanduser() + return [ + ("private key file exists", key_source.exists(), str(key_source)), + ( + "private key file permissions", + _private_key_permissions_ok(key_source), + _mode(key_source), + ), + ] + + +def _token_broker_checks(broker: str) -> list[tuple[str, bool, str]]: + proxy_set = bool(os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy")) + return [ + ("token broker", True, f"{broker}; credentials are injected outside the sandbox"), + ( + "HTTPS_PROXY set", + proxy_set, + "set" + if proxy_set + else "not set; agent does not appear to be running inside nono, " + "so no credentials will be injected", + ), + ] + + def _status(repo: str | None) -> int: config = load_config() auth = GitHubAppAuth(config) @@ -258,6 +310,12 @@ def _token(repo: str | None, *, json_output: bool) -> int: print(json.dumps({"token": token.token, "auth": auth_metadata(token, repo=repo)}, indent=2)) else: print(token.token) + if config.token_broker: + print( + "note: token broker mode. The printed value is a placeholder; the real installation " + "token lives outside the sandbox and the nono proxy injects it into GitHub requests.", + file=sys.stderr, + ) return 0 diff --git a/src/hermes_github_app_plugin/config.py b/src/hermes_github_app_plugin/config.py index 79eaa93..483c433 100644 --- a/src/hermes_github_app_plugin/config.py +++ b/src/hermes_github_app_plugin/config.py @@ -11,6 +11,11 @@ import yaml +# Token brokers keep the private key outside the agent's sandbox. The broker injects real +# credentials into outbound requests, so the agent only ever sends this placeholder. +SUPPORTED_TOKEN_BROKERS: tuple[str, ...] = ("nono",) +NONO_PHANTOM_TOKEN = "nono-phantom-github-app" + class ConfigurationError(RuntimeError): """Raised when GitHub App configuration is missing or invalid.""" @@ -18,7 +23,10 @@ class ConfigurationError(RuntimeError): @dataclass(frozen=True) class GitHubAppConfig: - """Per-agent GitHub App configuration.""" + """Per-agent GitHub App configuration. + + In token broker mode `private_key` is empty and `token_broker` names the broker. + """ client_id: str installation_id: str @@ -27,6 +35,7 @@ class GitHubAppConfig: private_key_source: str app_slug: str | None = None github_api_url: str = "https://api.github.com" + token_broker: str | None = None def installation_id_for_repo(self, repo: str | None = None) -> str: """Return the installation ID for an optional OWNER/REPO target.""" @@ -118,6 +127,21 @@ def _parse_installation_ids(raw: Any) -> dict[str, str]: return result +def parse_token_broker(raw: object, *, source: str) -> str | None: + """Normalize a token broker name; empty values mean no broker.""" + if raw is None: + return None + text = str(raw).strip().lower() + if not text: + return None + if text not in SUPPORTED_TOKEN_BROKERS: + supported = ", ".join(SUPPORTED_TOKEN_BROKERS) + raise ConfigurationError( + f"unsupported token broker {str(raw)!r} from {source}; supported: {supported}" + ) + return text + + def _read_private_key(section: Mapping[str, Any]) -> tuple[str, str]: inline_key = os.environ.get("GITHUB_APP_PRIVATE_KEY") or str(section.get("private_key", "")) if inline_key: @@ -159,7 +183,16 @@ def load_config() -> GitHubAppConfig: if not installation_id: # Use a deterministic fallback for commands that cannot infer an OWNER/REPO. installation_id = next(iter(installation_ids.values())) - private_key, private_key_source = _read_private_key(section) + broker_env = os.environ.get("GITHUB_APP_TOKEN_BROKER") + token_broker = parse_token_broker( + broker_env or section.get("token_broker"), + source="GITHUB_APP_TOKEN_BROKER" if broker_env else "github_app.token_broker", + ) + if token_broker: + # The private key never enters a brokered agent's environment; ignore any key settings. + private_key, private_key_source = "", f"token broker: {token_broker}" + else: + private_key, private_key_source = _read_private_key(section) return GitHubAppConfig( client_id=client_id, installation_id=installation_id, @@ -169,4 +202,5 @@ def load_config() -> GitHubAppConfig: app_slug=os.environ.get("GITHUB_APP_SLUG") or section.get("app_slug"), github_api_url=os.environ.get("GITHUB_API_URL") or str(section.get("github_api_url", "https://api.github.com")).rstrip("/"), + token_broker=token_broker, ) diff --git a/src/hermes_github_app_plugin/skills/github-app-workflow/SKILL.md b/src/hermes_github_app_plugin/skills/github-app-workflow/SKILL.md index 57597bd..7b1ab0f 100644 --- a/src/hermes_github_app_plugin/skills/github-app-workflow/SKILL.md +++ b/src/hermes_github_app_plugin/skills/github-app-workflow/SKILL.md @@ -36,6 +36,14 @@ After setup, run `hermes-github-app doctor --repo OWNER/REPO` to verify console 7. Expect comments, PRs, and API writes to appear as `[bot]`. 8. Treat the GitHub App installation scope as the repository access boundary. The plugin does not maintain a separate local repository/owner allowlist. +## Running inside nono (token broker mode) + +If `hermes-github-app doctor` reports `token broker: nono`, this agent runs in the nono sandbox. By design it holds no GitHub App private key and cannot obtain a real installation token. + +- Do not search for, copy, or request a private key or a real token. `hermes-github-app token` prints a placeholder; nono's proxy outside the sandbox injects the real credentials into GitHub requests. +- `github_app_*` tools, `gh-app`, and `git-app` work as described above. Plain `gh` and HTTPS `git push` also work because the proxy injects credentials, so keep remotes HTTPS. +- If `doctor` reports `HTTPS_PROXY set` as failed, the agent is not running inside nono and no credentials will be injected. Stop and report that. Do not fall back to local human credentials or SSH keys. + ## Updating existing Hermes skills Patch any GitHub-related skill, cron prompt, or subagent instruction that mentions `gh`, `git push`, GitHub SSH remotes, or `@me` assumptions: diff --git a/src/hermes_github_app_plugin/tools.py b/src/hermes_github_app_plugin/tools.py index 8ab5c90..f136016 100644 --- a/src/hermes_github_app_plugin/tools.py +++ b/src/hermes_github_app_plugin/tools.py @@ -42,6 +42,7 @@ def run() -> dict[str, Any]: "installation_ids": dict(config.installation_ids), "app_slug": config.app_slug, "private_key_source": config.private_key_source, + "token_broker": config.token_broker, "github_api_url": config.github_api_url, "scope_management": "github_app_installation", } diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..2da1c3f --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,18 @@ +"""Shared test isolation: never read the developer's real Hermes config or GitHub App env.""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + + +@pytest.fixture(autouse=True) +def isolated_environment(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "isolated-hermes-home")) + for name in list(os.environ): + if name.startswith(("GITHUB_APP_", "GITHUB_API_URL")): + monkeypatch.delenv(name) + for name in ("HTTPS_PROXY", "https_proxy"): + monkeypatch.delenv(name, raising=False) diff --git a/tests/test_auth.py b/tests/test_auth.py index 1d00675..4eff505 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -3,9 +3,10 @@ from __future__ import annotations import json -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone import httpx +import pytest from hermes_github_app_plugin.auth import ( GitHubAppAuth, @@ -14,7 +15,7 @@ repo_from_path, requires_app_jwt, ) -from hermes_github_app_plugin.config import GitHubAppConfig +from hermes_github_app_plugin.config import NONO_PHANTOM_TOKEN, GitHubAppConfig PRIVATE_KEY = "[REDACTED PRIVATE KEY]\n" @@ -141,3 +142,94 @@ def test_repo_from_path_infers_rest_repo_paths() -> None: assert repo_from_path("/repos/OWNER/REPO/issues") == "OWNER/REPO" assert repo_from_path("https://api.github.com/repos/OWNER/REPO") == "OWNER/REPO" assert repo_from_path("/installation/repositories") is None + + +def _broker_config() -> GitHubAppConfig: + return GitHubAppConfig( + client_id="123", + installation_id="456", + private_key="", + installation_ids={"exampleinfra": "789"}, + private_key_source="token broker: nono", + app_slug="hermes-test-agent", + token_broker="nono", + ) + + +def _fail_on_network(request: httpx.Request) -> httpx.Response: + raise AssertionError(f"unexpected network call in token broker mode: {request.url}") + + +def test_broker_installation_token_makes_no_network_call() -> None: + client = httpx.Client(transport=httpx.MockTransport(_fail_on_network)) + auth = GitHubAppAuth(_broker_config(), client=client) + before = datetime.now(timezone.utc) + + token = auth.get_installation_token(repo="ExampleInfra/automation-config") + + assert token.token == NONO_PHANTOM_TOKEN + assert token.installation_id == "789" + assert token.app_slug == "hermes-test-agent" + assert token.client_id == "123" + assert token.token_broker == "nono" + assert timedelta(hours=1) <= token.expires_at - before < timedelta(hours=1, minutes=1) + # The brokered token is cached like a minted one, so repeat calls stay offline too. + assert auth.get_installation_token(repo="ExampleInfra/automation-config") is token + + +def test_broker_create_jwt_returns_placeholder_without_signing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fail_if_signing(*_: object, **__: object) -> str: + raise AssertionError("token broker mode must not sign with a private key") + + monkeypatch.setattr("jwt.encode", fail_if_signing) + client = httpx.Client(transport=httpx.MockTransport(_fail_on_network)) + + assert GitHubAppAuth(_broker_config(), client=client).create_jwt() == NONO_PHANTOM_TOKEN + + +def test_broker_request_sends_placeholder_and_reports_broker() -> None: + seen: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + return httpx.Response(200, json={"full_name": "ExampleInfra/automation-config"}) + + client = httpx.Client(transport=httpx.MockTransport(handler)) + result = GitHubAppAuth(_broker_config(), client=client).request( + "GET", "/repos/ExampleInfra/automation-config" + ) + + assert len(seen) == 1 + assert seen[0].url.path == "/repos/ExampleInfra/automation-config" + assert seen[0].headers["authorization"] == "Bearer nono-phantom-github-app" + assert result["auth"]["installation_id"] == "789" + assert result["auth"]["token_broker"] == "nono" + assert result["auth"]["token"] == "nono…-app" + + +def test_broker_app_request_sends_placeholder() -> None: + seen: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + return httpx.Response(200, json={"slug": "hermes-test-agent"}) + + client = httpx.Client(transport=httpx.MockTransport(handler)) + result = GitHubAppAuth(_broker_config(), client=client).app_request("GET", "/app") + + assert seen[0].headers["authorization"] == "Bearer nono-phantom-github-app" + assert result["auth"]["token_broker"] == "nono" + + +def test_auth_metadata_without_broker_reports_null_token_broker() -> None: + token = InstallationToken( + token="ghu_ab...wxyz", + expires_at=datetime(2030, 1, 1, tzinfo=timezone.utc), + installation_id="456", + client_id="123", + app_slug=None, + ) + + assert auth_metadata(token)["token_broker"] is None diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c8ca55..4d8dd44 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -5,13 +5,48 @@ import argparse from pathlib import Path +import httpx import pytest import yaml from hermes_github_app_plugin import cli +from hermes_github_app_plugin.auth import GitHubAppAuth +from hermes_github_app_plugin.config import NONO_PHANTOM_TOKEN, GitHubAppConfig PRIVATE_KEY = "[REDACTED PRIVATE KEY]\n" +BROKER_CONFIG = """ +github_app: + client_id: Iv1.exampleclientid + installation_id: 987654 + token_broker: nono +""" + + +def _write_hermes_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, body: str) -> Path: + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir(parents=True, exist_ok=True) + (hermes_home / "config.yaml").write_text(body, encoding="utf-8") + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + return hermes_home + + +def _setup_args(**overrides: object) -> argparse.Namespace: + values: dict[str, object] = { + "github_app_command": "setup", + "client_id": "Iv1.exampleclientid", + "installation_id": "987654", + "installation_id_for": [], + "private_key_path": None, + "app_slug": None, + "non_interactive": True, + "repo": None, + "skip_verify": True, + "token_broker": None, + } + values.update(overrides) + return argparse.Namespace(**values) + def test_setup_non_interactive_writes_config_and_skips_verify( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] @@ -190,3 +225,139 @@ def test_setup_non_interactive_writes_owner_installation_ids( "exampleorg": "111", "exampleinfra": "222", } + + +def test_setup_token_broker_writes_config_without_private_key_path( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + stale_key = tmp_path / "stale.pem" + hermes_home = _write_hermes_config( + tmp_path, + monkeypatch, + f"github_app:\n private_key_path: {stale_key}\n", + ) + monkeypatch.setattr( + "builtins.input", lambda prompt: pytest.fail(f"unexpected prompt: {prompt}") + ) + + assert cli.main(_setup_args(token_broker="nono", app_slug=None)) == 0 + + section = yaml.safe_load((hermes_home / "config.yaml").read_text(encoding="utf-8"))[ + "github_app" + ] + assert section == { + "client_id": "Iv1.exampleclientid", + "installation_id": "987654", + "token_broker": "nono", + } + + +def test_setup_token_broker_rejects_private_key_path( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + key_path = tmp_path / "app.pem" + key_path.write_text(PRIVATE_KEY, encoding="utf-8") + monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) + + assert cli.main(_setup_args(token_broker="nono", private_key_path=str(key_path))) == 1 + + assert "cannot be combined with --token-broker" in capsys.readouterr().err + assert not (tmp_path / ".hermes" / "config.yaml").exists() + + +def test_setup_rejects_unsupported_token_broker( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes")) + + assert cli.main(_setup_args(token_broker="vault")) == 1 + + assert "supported: nono" in capsys.readouterr().err + + +def test_setup_without_broker_clears_stale_token_broker( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + key_path = tmp_path / "app.pem" + key_path.write_text(PRIVATE_KEY, encoding="utf-8") + key_path.chmod(0o600) + hermes_home = _write_hermes_config(tmp_path, monkeypatch, BROKER_CONFIG) + + assert cli.main(_setup_args(private_key_path=str(key_path))) == 0 + + section = yaml.safe_load((hermes_home / "config.yaml").read_text(encoding="utf-8"))[ + "github_app" + ] + assert "token_broker" not in section + assert section["private_key_path"] == str(key_path) + + +def test_doctor_token_broker_skip_network_checks_proxy( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _write_hermes_config(tmp_path, monkeypatch, BROKER_CONFIG) + monkeypatch.setenv("HTTPS_PROXY", "http://nono-proxy.test:8080") + monkeypatch.setattr(cli.shutil, "which", lambda command: f"/usr/bin/{command}") + + assert cli._doctor(None, skip_network=True) == 0 + + output = capsys.readouterr().out + assert "✓ token broker: nono" in output + assert "✓ HTTPS_PROXY set: set" in output + assert "private key" not in output + assert "Local doctor passed" in output + + +def test_doctor_token_broker_without_proxy_hints_not_inside_nono( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _write_hermes_config(tmp_path, monkeypatch, BROKER_CONFIG) + monkeypatch.setattr(cli.shutil, "which", lambda command: f"/usr/bin/{command}") + + assert cli._doctor(None, skip_network=True) == 1 + + output = capsys.readouterr().out + assert "✗ HTTPS_PROXY set: not set; agent does not appear to be running inside nono" in output + + +def test_doctor_token_broker_network_checks_send_placeholder( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _write_hermes_config(tmp_path, monkeypatch, BROKER_CONFIG) + monkeypatch.setenv("HTTPS_PROXY", "http://nono-proxy.test:8080") + monkeypatch.setattr(cli.shutil, "which", lambda command: f"/usr/bin/{command}") + seen_auth: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + assert not request.url.path.endswith("/access_tokens"), "broker mode must not mint" + seen_auth.append(request.headers["authorization"]) + if request.url.path == "/app": + return httpx.Response(200, json={"slug": "hermes-test-agent"}) + return httpx.Response(200, json={"full_name": "OWNER/REPO"}) + + class BrokerAuth(GitHubAppAuth): + def __init__(self, config: GitHubAppConfig) -> None: + super().__init__(config, client=httpx.Client(transport=httpx.MockTransport(handler))) + + monkeypatch.setattr(cli, "GitHubAppAuth", BrokerAuth) + + assert cli._doctor("OWNER/REPO", skip_network=False) == 0 + + assert seen_auth == [f"Bearer {NONO_PHANTOM_TOKEN}"] * 2 + output = capsys.readouterr().out + assert "✓ installation token brokered by nono" in output + assert "✓ /app API reachable: hermes-test-agent" in output + assert "✓ repository access verified: OWNER/REPO" in output + + +def test_token_command_in_broker_mode_prints_placeholder( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + _write_hermes_config(tmp_path, monkeypatch, BROKER_CONFIG) + args = argparse.Namespace(github_app_command="token", repo=None, json=False) + + assert cli.main(args) == 0 + + captured = capsys.readouterr() + assert captured.out == f"{NONO_PHANTOM_TOKEN}\n" + assert "the nono proxy injects it" in captured.err diff --git a/tests/test_config.py b/tests/test_config.py index 3a2fd59..be80259 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,7 +6,7 @@ import pytest -from hermes_github_app_plugin.config import load_config +from hermes_github_app_plugin.config import ConfigurationError, load_config PRIVATE_KEY = "[REDACTED PRIVATE KEY]\n" @@ -74,3 +74,83 @@ def test_load_config_installation_ids_from_environment( assert config.installation_id == "456" assert config.installation_id_for_repo("ExampleInfra/automation-config") == "789" + + +def test_token_broker_from_environment_ignores_missing_private_key( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("GITHUB_APP_CLIENT_ID", "123") + monkeypatch.setenv("GITHUB_APP_INSTALLATION_ID", "456") + monkeypatch.setenv("GITHUB_APP_TOKEN_BROKER", "nono") + monkeypatch.setenv("GITHUB_APP_PRIVATE_KEY_PATH", str(tmp_path / "missing.pem")) + monkeypatch.setenv("GITHUB_APP_PRIVATE_KEY", PRIVATE_KEY) + + config = load_config() + + assert config.token_broker == "nono" + assert config.private_key == "" + assert config.private_key_source == "token broker: nono" + assert config.client_id == "123" + assert config.installation_id == "456" + + +def test_token_broker_from_hermes_yaml_ignores_private_key_path( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + (hermes_home / "config.yaml").write_text( + f""" +github_app: + client_id: "111" + installation_id: "222" + private_key_path: {tmp_path / "missing.pem"} + token_broker: nono +""", + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + + config = load_config() + + assert config.token_broker == "nono" + assert config.private_key == "" + assert config.private_key_source == "token broker: nono" + + +def test_private_key_still_required_without_token_broker( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("GITHUB_APP_CLIENT_ID", "123") + monkeypatch.setenv("GITHUB_APP_INSTALLATION_ID", "456") + monkeypatch.setenv("GITHUB_APP_PRIVATE_KEY_PATH", str(tmp_path / "missing.pem")) + + with pytest.raises(ConfigurationError, match="private key file does not exist"): + load_config() + + +@pytest.mark.parametrize("value", ["vault", "false"]) +def test_unsupported_token_broker_from_environment_is_rejected( + monkeypatch: pytest.MonkeyPatch, value: str +) -> None: + monkeypatch.setenv("GITHUB_APP_CLIENT_ID", "123") + monkeypatch.setenv("GITHUB_APP_INSTALLATION_ID", "456") + monkeypatch.setenv("GITHUB_APP_TOKEN_BROKER", value) + + with pytest.raises(ConfigurationError, match="supported: nono"): + load_config() + + +def test_unsupported_token_broker_from_hermes_yaml_is_rejected( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + hermes_home = tmp_path / ".hermes" + hermes_home.mkdir() + (hermes_home / "config.yaml").write_text( + 'github_app:\n client_id: "111"\n installation_id: "222"\n token_broker: vault\n', + encoding="utf-8", + ) + monkeypatch.setenv("HERMES_HOME", str(hermes_home)) + + with pytest.raises(ConfigurationError, match=r"github_app\.token_broker.*supported: nono"): + load_config()