Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
7 changes: 5 additions & 2 deletions plugin.yaml
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
8 changes: 8 additions & 0 deletions skills/github-app-workflow/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<app-slug>[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:
Expand Down
38 changes: 33 additions & 5 deletions src/hermes_github_app_plugin/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand All @@ -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")
Expand All @@ -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={
Expand All @@ -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,
Expand Down Expand Up @@ -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},
Expand Down Expand Up @@ -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(),
}

Expand Down
94 changes: 76 additions & 18 deletions src/hermes_github_app_plugin/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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"
Expand Down Expand Up @@ -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(
Expand All @@ -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",
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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


Expand Down
Loading
Loading