Skip to content

Commit ea7c5a0

Browse files
committed
feat: support GitHub App backups across accounts and organizations
1 parent 2566735 commit ea7c5a0

10 files changed

Lines changed: 495 additions & 41 deletions

File tree

‎Dockerfile‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
1919
DEBIAN_FRONTEND=noninteractive
2020

2121
RUN apt-get update \
22-
&& apt-get install --no-install-recommends -y ca-certificates git git-lfs \
22+
&& apt-get install --no-install-recommends -y ca-certificates git git-lfs openssl \
2323
&& rm -rf /var/lib/apt/lists/* \
2424
&& groupadd --gid 10001 ghbackup \
2525
&& useradd --uid 10001 --gid ghbackup --create-home ghbackup

‎README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,14 @@ github-backup verify --destination /mnt/backups/github
176176

177177
Global options (`--config`, `--verbose`, `--json-logs`) go **before** the command. Command options (`--destination`, `--scope`, `--include`) go after `run`, `list`, or `check`.
178178

179+
## GitHub App authentication
180+
181+
To back up all current and future repositories across your accounts and organizations,
182+
use [GitHub App installation authentication](docs/GITHUB_APP.md) and
183+
[`github-backup.app.example.toml`](github-backup.app.example.toml). Install the App with
184+
**All repositories** selected on every owner, then list those owners in `github.app_owners`.
185+
Installation tokens are renewed automatically; set `include_gists = false`.
186+
179187
## Create a GitHub token
180188

181189
GitHub recommends fine-grained PATs when they support the use case. Prefer a separate read-only backup identity, set an expiration, document ownership, and rotate before expiry. See [GitHub's token guide](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens).

‎docs/GITHUB_APP.md‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Back up multiple accounts and organizations with a GitHub App
2+
3+
This feature requires the updated source containing `src/github_backup/app_auth.py`;
4+
older published releases do not support these settings.
5+
6+
Create a GitHub App under GitHub Settings → Developer settings → GitHub Apps.
7+
Disable webhooks. Grant repository **Contents: Read-only** (Metadata read is automatic).
8+
Choose an installation availability that permits your other accounts and organizations.
9+
Install the App separately on each account and organization you administer, choosing
10+
**All repositories** on every installation. New repositories in those installations
11+
are discovered on the next run. A collaborator's repositories require installation on
12+
the owning account; membership alone does not grant an installation access.
13+
14+
Record the App ID and generate a private key. Transfer the PEM file securely to the Pi.
15+
Do not paste it into logs, commits, or this chat. The program uses `openssl` to sign
16+
App JWTs and renews installation tokens before expiry. No personal access token is needed.
17+
Gists are not supported with installation authentication.
18+
19+
On Raspberry Pi OS with Python 3.11 or newer, from the updated source checkout:
20+
21+
```bash
22+
sudo apt update
23+
sudo apt install -y ca-certificates git openssl python3 python3-venv python3-pip
24+
python3 -m venv .venv
25+
.venv/bin/python -m pip install .
26+
sudo install -d -m 700 /etc/github-backup
27+
sudo install -m 600 /path/to/downloaded-private-key.pem /etc/github-backup/app-private-key.pem
28+
```
29+
30+
The process running backups must own and be able to read the private key. For an initial
31+
manual test as your SSH user, use a private directory under your home instead:
32+
33+
```bash
34+
mkdir -p ~/.config/github-backup ~/github-backups
35+
chmod 700 ~/.config/github-backup ~/github-backups
36+
install -m 600 /path/to/downloaded-private-key.pem ~/.config/github-backup/app-private-key.pem
37+
cp github-backup.app.example.toml ~/.config/github-backup/config.toml
38+
nano ~/.config/github-backup/config.toml
39+
```
40+
41+
Set `app_id`, the absolute private-key path, `destination` (your home backup directory),
42+
and `app_owners` (all your personal accounts and organizations). Owner names are explicit
43+
so a revoked or missing installation fails discovery instead of silently disappearing.
44+
Selected-repository installations are rejected to protect the intended complete coverage.
45+
With App authentication, `accessible`/`owned` both cover the configured installation owners;
46+
`organizations` applies the existing explicit organization allowlist.
47+
48+
```bash
49+
.venv/bin/github-backup --config ~/.config/github-backup/config.toml check
50+
.venv/bin/github-backup --config ~/.config/github-backup/config.toml list
51+
.venv/bin/github-backup --config ~/.config/github-backup/config.toml run
52+
.venv/bin/github-backup --config ~/.config/github-backup/config.toml verify
53+
```
54+
55+
Compare the listing to every account's inventory before scheduling. Test a restore from
56+
the actual backup destination. The example uses snapshots and keeps all recovery points;
57+
choose retention and monitor disk space. For unattended service use, follow the README's
58+
systemd setup, make the service user own the PEM (mode 0600), and use this configuration
59+
instead of the token environment file. Optional metadata, Actions, and other components
60+
require their corresponding App read permissions and may have API coverage limitations.
61+
62+
GitHub reference: https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation

‎github-backup.app.example.toml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Install the same GitHub App on every listed user/organization with All repositories.
2+
[backup]
3+
destination = "/srv/github-backup"
4+
scope = "accessible"
5+
include_gists = false
6+
workers = 2
7+
mode = "snapshot"
8+
snapshot_retention = 0
9+
10+
[github]
11+
app_id = "123456"
12+
app_private_key = "/etc/github-backup/app-private-key.pem"
13+
app_owners = ["your-user", "your-organization", "your-second-user"]

‎src/github_backup/app_auth.py‎

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
"""GitHub App authentication for explicitly configured installation owners."""
2+
3+
from __future__ import annotations
4+
5+
import base64
6+
import json
7+
import re
8+
import subprocess
9+
import threading
10+
import time
11+
from collections.abc import Mapping
12+
from datetime import datetime
13+
from pathlib import Path
14+
from typing import Any
15+
from urllib.parse import quote, urlsplit
16+
from urllib.request import Request
17+
18+
from github_backup.config import GitHubConfig, ScopeKind
19+
from github_backup.errors import ConfigurationError, GitHubAPIError
20+
from github_backup.github import GitHubClient
21+
from github_backup.models import Resource
22+
23+
24+
class InstallationClient(GitHubClient):
25+
def authenticated_user(self) -> str:
26+
return "installation"
27+
28+
def repositories(self, scope: ScopeKind, organizations: tuple[str, ...]) -> list[Resource]:
29+
# Reuse the normal resource parser with installation-specific pagination.
30+
return super().repositories(scope, organizations)
31+
32+
def _paginate(
33+
self, path: str, parameters: Mapping[str, str], *, list_key: str | None = None
34+
) -> Any:
35+
if path == "/user/repos":
36+
path, parameters, list_key = "/installation/repositories", {}, "repositories"
37+
return super()._paginate(path, parameters, list_key=list_key)
38+
39+
40+
class AppClient(GitHubClient):
41+
def __init__(self, config: GitHubConfig) -> None:
42+
super().__init__(config, self._jwt)
43+
self._app = GitHubClient(config, self._jwt)
44+
self._lock = threading.RLock()
45+
self._installations: dict[str, int] = {}
46+
self._tokens: dict[str, tuple[str, float]] = {}
47+
self._clients: dict[str, InstallationClient] = {}
48+
for owner in config.app_owners:
49+
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9-]*", owner):
50+
raise ConfigurationError(f"Invalid GitHub installation owner: {owner}")
51+
52+
def _jwt(self) -> str:
53+
def encode(value: bytes) -> str:
54+
return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii")
55+
56+
now = int(time.time())
57+
header = encode(b'{"alg":"RS256","typ":"JWT"}')
58+
payload = encode(
59+
json.dumps({"iat": now - 60, "exp": now + 540, "iss": self._config.app_id}).encode()
60+
)
61+
signing_input = f"{header}.{payload}"
62+
key = Path(self._config.app_private_key).expanduser()
63+
try:
64+
if key.stat().st_mode & 0o077:
65+
raise ConfigurationError("App private key must have permissions 0600 or 0400")
66+
result = subprocess.run(
67+
["openssl", "dgst", "-sha256", "-sign", str(key)],
68+
input=signing_input.encode(),
69+
capture_output=True,
70+
check=True,
71+
timeout=30,
72+
)
73+
except (OSError, subprocess.SubprocessError) as exc:
74+
raise ConfigurationError("Cannot sign App JWT; check private key and openssl") from exc
75+
return f"{signing_input}.{encode(result.stdout)}"
76+
77+
def _client(self, owner: str) -> InstallationClient:
78+
owner = owner.casefold()
79+
with self._lock:
80+
if owner not in self._clients:
81+
try:
82+
installation = self._app.get_json(f"/users/{quote(owner)}/installation")
83+
except GitHubAPIError as exc:
84+
if exc.status_code != 404:
85+
raise
86+
installation = self._app.get_json(f"/orgs/{quote(owner)}/installation")
87+
if not isinstance(installation, dict) or "id" not in installation:
88+
raise GitHubAPIError(f"Invalid installation response for {owner}")
89+
account = installation.get("account", {})
90+
if str(account.get("login", "")).casefold() != owner:
91+
raise GitHubAPIError("Installation account does not match configured owner")
92+
if installation.get("repository_selection") != "all":
93+
raise GitHubAPIError(f"Install the App on All repositories for {owner}")
94+
if installation.get("suspended_at"):
95+
raise GitHubAPIError(f"App installation suspended for {owner}")
96+
self._installations[owner] = int(installation["id"])
97+
self._clients[owner] = InstallationClient(
98+
self._config, lambda: self._installation_token(owner)
99+
)
100+
return self._clients[owner]
101+
102+
def _installation_token(self, owner: str) -> str:
103+
with self._lock:
104+
cached = self._tokens.get(owner)
105+
if cached and cached[1] > time.time() + 300:
106+
return cached[0]
107+
url = self._absolute_api_url(
108+
f"/app/installations/{self._installations[owner]}/access_tokens"
109+
)
110+
request = Request(
111+
url, data=b"{}", headers=self._headers("application/vnd.github+json"), method="POST"
112+
)
113+
try:
114+
with self._open(request, timeout=self._config.timeout_seconds) as response:
115+
payload = json.loads(response.read())
116+
token = payload["token"]
117+
expires = datetime.fromisoformat(payload["expires_at"].replace("Z", "+00:00"))
118+
if (
119+
not isinstance(token, str)
120+
or not token
121+
or expires.timestamp() <= time.time() + 300
122+
):
123+
raise ValueError("invalid token")
124+
except Exception as exc:
125+
raise GitHubAPIError(f"Cannot obtain installation token for {owner}") from exc
126+
self._tokens[owner] = (token, expires.timestamp())
127+
return token
128+
129+
def authenticated_user(self) -> str:
130+
for owner in self._config.app_owners:
131+
self._client(owner)
132+
return ",".join(self._config.app_owners)
133+
134+
def repositories(self, scope: ScopeKind, organizations: tuple[str, ...]) -> list[Resource]:
135+
repos: dict[str, Resource] = {}
136+
for owner in self._config.app_owners:
137+
for repo in self._client(owner).repositories(scope, organizations):
138+
repos[repo.identifier] = repo
139+
return sorted(repos.values(), key=lambda repo: repo.relative_path.casefold())
140+
141+
def _owner_client(self, path: str) -> InstallationClient:
142+
parsed = urlsplit(self._absolute_api_url(path))
143+
api = urlsplit(self._config.api_url)
144+
if (parsed.scheme, parsed.netloc) != (api.scheme, api.netloc):
145+
raise GitHubAPIError("App request attempted to use a different API origin")
146+
relative = parsed.path.removeprefix(api.path.rstrip("/"))
147+
parts = relative.strip("/").split("/")
148+
if len(parts) < 2 or parts[0] not in ("repos", "orgs", "users"):
149+
raise GitHubAPIError("Cannot route App request to an installation")
150+
owner = parts[1].casefold()
151+
if owner not in {value.casefold() for value in self._config.app_owners}:
152+
raise GitHubAPIError("Request owner is outside configured installations")
153+
return self._client(owner)
154+
155+
def _request_json(self, path_or_url: str) -> tuple[Any, Mapping[str, str]]:
156+
return self._owner_client(path_or_url)._request_json(path_or_url)
157+
158+
def download(self, path_or_url: str, destination: Path) -> int:
159+
return self._owner_client(path_or_url).download(path_or_url, destination)
160+
161+
def git_token(self, url: str) -> str:
162+
parsed = urlsplit(url)
163+
api_host = urlsplit(self._config.api_url).hostname
164+
git_host = "github.com" if api_host == "api.github.com" else api_host
165+
if parsed.scheme != "https" or parsed.hostname != git_host:
166+
raise GitHubAPIError("Git remote is outside the configured GitHub host")
167+
owner = parsed.path.strip("/").split("/")[0].casefold()
168+
if owner not in {value.casefold() for value in self._config.app_owners}:
169+
raise GitHubAPIError("Git owner is outside configured installations")
170+
self._client(owner)
171+
return self._installation_token(owner)

‎src/github_backup/cli.py‎

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import json
88
import logging
99
import tarfile
10-
from collections.abc import Sequence
10+
from collections.abc import Callable, Sequence
1111
from dataclasses import replace
1212
from pathlib import Path
1313
from typing import cast
@@ -218,8 +218,16 @@ def main(argv: Sequence[str] | None = None) -> None:
218218
if arguments.command == "verify":
219219
_verify_local(config)
220220
return
221-
token = read_token(config.github)
222-
github = GitHubClient(config.github, token)
221+
github: GitHubClient
222+
token: str | Callable[[str], str]
223+
if config.github.app_id:
224+
from github_backup.app_auth import AppClient
225+
226+
github = AppClient(config.github)
227+
token = github.git_token
228+
else:
229+
token = read_token(config.github)
230+
github = GitHubClient(config.github, token)
223231
git = GitRunner(
224232
token,
225233
timeout_seconds=config.git_timeout_seconds,
@@ -295,9 +303,7 @@ def _apply_cli_overrides(config: BackupConfig, arguments: argparse.Namespace) ->
295303
worker_value = cast(int | None, getattr(arguments, "workers", None))
296304
workers = worker_value if worker_value is not None else config.workers
297305
git_retries_value = cast(int | None, getattr(arguments, "git_retries", None))
298-
git_max_retries = (
299-
git_retries_value if git_retries_value is not None else config.git_max_retries
300-
)
306+
git_max_retries = git_retries_value if git_retries_value is not None else config.git_max_retries
301307
verify_value = cast(bool | None, getattr(arguments, "verify_mirrors", None))
302308
verify_mirrors = verify_value if verify_value is not None else config.verify_mirrors
303309
free_space_value = cast(float | None, getattr(arguments, "minimum_free_space_gib", None))
@@ -333,25 +339,16 @@ def _apply_cli_overrides(config: BackupConfig, arguments: argparse.Namespace) ->
333339
s3_bucket = cast(str | None, getattr(arguments, "s3_bucket", None)) or config.s3.bucket
334340
s3_prefix = cast(str | None, getattr(arguments, "s3_prefix", None)) or config.s3.prefix
335341
s3_endpoint_url = (
336-
cast(str | None, getattr(arguments, "s3_endpoint_url", None))
337-
or config.s3.endpoint_url
342+
cast(str | None, getattr(arguments, "s3_endpoint_url", None)) or config.s3.endpoint_url
338343
)
339344
s3_region = cast(str | None, getattr(arguments, "s3_region", None)) or config.s3.region
340-
encryption_value = cast(
341-
str | None, getattr(arguments, "s3_server_side_encryption", None)
342-
)
345+
encryption_value = cast(str | None, getattr(arguments, "s3_server_side_encryption", None))
343346
s3_encryption = (
344-
None
345-
if encryption_value == "none"
346-
else encryption_value or config.s3.server_side_encryption
347-
)
348-
insecure_s3_value = cast(
349-
bool | None, getattr(arguments, "allow_insecure_s3_endpoint", None)
347+
None if encryption_value == "none" else encryption_value or config.s3.server_side_encryption
350348
)
349+
insecure_s3_value = cast(bool | None, getattr(arguments, "allow_insecure_s3_endpoint", None))
351350
allow_insecure_s3_endpoint = (
352-
insecure_s3_value
353-
if insecure_s3_value is not None
354-
else config.s3.allow_insecure_endpoint
351+
insecure_s3_value if insecure_s3_value is not None else config.s3.allow_insecure_endpoint
355352
)
356353
s3_config = replace(
357354
config.s3,

0 commit comments

Comments
 (0)