Skip to content
Open
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
113 changes: 113 additions & 0 deletions bundlebees_plugin/app_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""GitHub App installation authentication with private-key permission checks."""

from __future__ import annotations

import stat
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Mapping, MutableMapping


_TOKEN_CACHE: dict[tuple[Any, Any], dict[str, Any]] = {}


class AppAuthError(Exception):
def __init__(self, code: str, message: str, fix: str = "") -> None:
super().__init__(message)
self.code, self.message, self.fix = code, message, fix


def build_claims(app_id: Any, now: float) -> dict[str, Any]:
return {"iss": app_id, "iat": now - 60, "exp": now + 540}


def _check_key_permissions(path: Path) -> None:
mode = stat.S_IMODE(path.stat().st_mode)
if mode & 0o077:
raise AppAuthError(
"app_key_permissions",
f"GitHub App private key {path} is accessible by group or other users",
"Set the private key file mode to 0600.",
)


def load_private_key(path: str | Path) -> bytes:
key_path = Path(path)
_check_key_permissions(key_path)
return key_path.read_bytes()


def _expiry_epoch(value: Any, now: float) -> float:
try:
if isinstance(value, (int, float)) and not isinstance(value, bool):
expires = float(value)
else:
parsed = datetime.fromisoformat(str(value).strip().replace("Z", "+00:00"))
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
expires = parsed.timestamp()
except (TypeError, ValueError, OverflowError):
return now + 3600
return expires if expires > now else now + 3600


def _public_token(entry: Mapping[str, Any]) -> dict[str, Any]:
return {"token": entry["token"], "expires_at": entry["expires_at"]}


def installation_token(
app_id: Any,
installation_id: Any,
signer: Any,
http: Any,
cache: MutableMapping[tuple[Any, Any], dict[str, Any]],
now: float,
) -> dict[str, Any]:
key = (app_id, installation_id)
cached = cache.get(key)
if cached is not None and float(cached.get("_expires_epoch", 0)) > now + 60:
return _public_token(cached)

assertion = signer(build_claims(app_id, now))
response = http(
f"https://api.github.com/app/installations/{installation_id}/access_tokens",
{
"Authorization": f"Bearer {assertion}",
"Accept": "application/vnd.github+json",
},
{},
)
entry = {
"token": response["token"],
"expires_at": response["expires_at"],
"_expires_epoch": _expiry_epoch(response["expires_at"], now),
}
cache[key] = entry
return _public_token(entry)


def _configured_app(config: Mapping[str, Any], name: str, fields: tuple[str, ...]) -> Mapping[str, Any]:
apps = config.get("github_apps") if isinstance(config, Mapping) else None
app = apps.get(name) if isinstance(apps, Mapping) else None
if not isinstance(app, Mapping) or any(not app.get(field) for field in fields):
raise AppAuthError(
"app_not_configured",
f"GitHub App {name} is not configured",
f"Configure github_apps.{name} with {', '.join(fields)}.",
)
return app


def token_for(config: Mapping[str, Any], signer: Any, http: Any, now: float) -> dict[str, Any]:
app = _configured_app(config, "coordinator", ("app_id", "installation_id", "key_path"))
load_private_key(app["key_path"])
return installation_token(
app["app_id"], app["installation_id"], signer, http, _TOKEN_CACHE, now
)


def reviewer_key_path(config: Mapping[str, Any]) -> Path:
app = _configured_app(config, "reviewer", ("key_path", "poster_user"))
key_path = Path(app["key_path"])
_check_key_permissions(key_path)
return key_path
1 change: 1 addition & 0 deletions bundlebees_plugin/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"allow_private": False,
"orbit_url": "http://127.0.0.1:4318",
"coordinator": "",
"github_apps": {},
"worktree": "",
"branch": "",
"deploy_host_alias": "",
Expand Down
7 changes: 7 additions & 0 deletions plugin.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@ config_schema:
default: ""
description: >-
Optional label sent to Orbit; ownership is the per-attempt capability.
github_apps:
type: dict
default: {}
description: >-
GitHub App identities. coordinator requires app_id, installation_id and
key_path; reviewer requires key_path and poster_user. Private key files
must be mode 0600 and key material is never returned with tokens.
worktree:
type: str
default: ""
Expand Down
105 changes: 105 additions & 0 deletions tests/test_app_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""GitHub App identities for the coordinator and the reviewer (program: Phase 3).

The coordinator's GitHub calls move to installation tokens minted from the coordinator app's
private key; the verdict poster runs as its own OS user and is the only reader of the
reviewer app's key. A key file that is group/other readable is refused, the token never
carries the key material back to the caller, and tokens are reused until 60 s before expiry.

Run: python -m pytest tests/test_app_auth.py -q
"""

from __future__ import annotations

import os
import stat
from pathlib import Path

import pytest


NOW = 1_800_000_000


def _key(tmp_path: Path, mode: int = 0o600) -> Path:
path = tmp_path / "app.pem"
# Assembled at runtime so the fixture never carries a key-shaped literal in history.
header = "-----BEGIN " + "PRIVATE KEY-----"
footer = "-----END " + "PRIVATE KEY-----"
path.write_text(header + "\nfake\n" + footer + "\n")
os.chmod(path, mode)
return path


def _load():
import importlib

return importlib.import_module("bundlebees_plugin.app_auth")


def test_claims_are_short_lived_and_issued_for_the_app():
m = _load()
claims = m.build_claims(1234, NOW)
assert claims["iss"] == 1234
assert claims["iat"] == NOW - 60
assert claims["exp"] == NOW + 540


def test_installation_token_is_cached_until_just_before_expiry():
m = _load()
calls = []

def signer(claims):
return "jwt"

def http(url, headers, body):
calls.append((url, body))
return {"token": "ghs_abc", "expires_at": "2026-11-27T21:00:00Z"}

cache: dict = {}
first = m.installation_token(1234, 99, signer, http, cache, now=NOW)
second = m.installation_token(1234, 99, signer, http, cache, now=NOW + 30)
assert first["token"] == second["token"] == "ghs_abc"
assert len(calls) == 1
third = m.installation_token(1234, 99, signer, http, cache, now=NOW + 7200)
assert len(calls) == 2
assert third["token"] == "ghs_abc"


def test_group_readable_key_is_refused(tmp_path: Path):
m = _load()
path = _key(tmp_path, 0o644)
with pytest.raises(m.AppAuthError) as caught:
m.load_private_key(path)
assert caught.value.code == "app_key_permissions"


def test_token_for_reads_the_configured_app_without_leaking_the_key(tmp_path: Path):
m = _load()
config = {
"github_apps": {
"coordinator": {
"app_id": 1234,
"installation_id": 99,
"key_path": str(_key(tmp_path)),
}
}
}
result = m.token_for(config, lambda claims: "jwt",
lambda url, headers, body: {"token": "ghs_abc", "expires_at": "2026-11-27T21:00:00Z"},
now=NOW)
assert result["token"] == "ghs_abc"
assert "private" not in str(result).lower()
with pytest.raises(m.AppAuthError) as caught:
m.token_for({}, lambda c: "jwt", lambda *a: {}, now=NOW)
assert caught.value.code == "app_not_configured"


def test_reviewer_key_is_only_readable_by_the_poster_user(tmp_path: Path):
m = _load()
path = _key(tmp_path, 0o600)
config = {"github_apps": {"reviewer": {"key_path": str(path), "poster_user": "rizzstack-reviewer"}}}
assert m.reviewer_key_path(config) == path
os.chmod(path, 0o640)
with pytest.raises(m.AppAuthError) as caught:
m.reviewer_key_path(config)
assert caught.value.code == "app_key_permissions"