Skip to content

Commit 300a6d4

Browse files
committed
Harden service and add extended GitHub backups
1 parent 88a4553 commit 300a6d4

31 files changed

Lines changed: 2978 additions & 206 deletions

‎.github/dependabot.yml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
version: 2
2+
updates:
3+
- package-ecosystem: pip
4+
directory: "/"
5+
schedule:
6+
interval: weekly
7+
groups:
8+
python-dependencies:
9+
patterns: ["*"]
10+
- package-ecosystem: github-actions
11+
directory: "/"
12+
schedule:
13+
interval: weekly

‎.github/workflows/ci.yml‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,14 @@ jobs:
1616
matrix:
1717
python-version: ["3.11", "3.12", "3.13"]
1818
steps:
19-
- uses: actions/checkout@v4
20-
- uses: actions/setup-python@v5
19+
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
20+
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
2121
with:
2222
python-version: ${{ matrix.python-version }}
2323
cache: pip
24-
- run: python -m pip install '.[dev,s3]'
25-
- run: ruff check .
26-
- run: mypy src
27-
- run: pytest --cov=github_backup --cov-report=term-missing --cov-fail-under=80
24+
- run: python -m pip install "uv==0.11.24"
25+
- run: uv sync --frozen --extra dev --extra s3
26+
- run: uv run ruff check .
27+
- run: uv run mypy src
28+
- run: uv run pytest --cov=github_backup --cov-report=term-missing --cov-fail-under=80
29+
- run: uv run pip-audit

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ __pycache__/
66
.pytest_cache/
77
.ruff_cache/
88
.venv/
9+
.uv-cache/
910
build/
1011
dist/
1112
htmlcov/

‎Dockerfile‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,25 @@
1-
FROM python:3.13-slim-bookworm AS builder
1+
FROM python:3.13-slim-bookworm@sha256:a1165e272e578941b84abc79e4ab38a0305cd12803a5c4247979ac7655f4d641 AS builder
22

33
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \
44
PIP_NO_CACHE_DIR=1
55

66
WORKDIR /build
7-
COPY pyproject.toml README.md LICENSE ./
7+
RUN python -m pip install "uv==0.11.24"
8+
COPY pyproject.toml uv.lock README.md LICENSE ./
9+
RUN uv export --frozen --no-dev --extra s3 --no-emit-project --output-file /tmp/requirements.txt \
10+
&& python -m pip wheel --wheel-dir /wheels -r /tmp/requirements.txt
811
COPY src ./src
9-
RUN python -m pip wheel --wheel-dir /wheels '.[s3]'
12+
RUN python -m pip wheel --no-deps --wheel-dir /wheels .
1013

11-
FROM python:3.13-slim-bookworm
14+
FROM python:3.13-slim-bookworm@sha256:a1165e272e578941b84abc79e4ab38a0305cd12803a5c4247979ac7655f4d641
1215

1316
ENV PYTHONDONTWRITEBYTECODE=1 \
1417
PYTHONUNBUFFERED=1 \
15-
GITHUB_BACKUP_DESTINATION=/backups
18+
GITHUB_BACKUP_DESTINATION=/backups \
19+
DEBIAN_FRONTEND=noninteractive
1620

1721
RUN apt-get update \
18-
&& apt-get install --no-install-recommends -y ca-certificates git \
22+
&& apt-get install --no-install-recommends -y ca-certificates git git-lfs \
1923
&& rm -rf /var/lib/apt/lists/* \
2024
&& groupadd --gid 10001 ghbackup \
2125
&& useradd --uid 10001 --gid ghbackup --create-home ghbackup

‎README.md‎

Lines changed: 77 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,75 @@
11
# github-backup
22

3-
`github-backup` discovers every repository visible to an authenticated GitHub user and backs up its complete Git object database and refs. It also backs up the authenticated user's public and secret gists.
3+
`github-backup` discovers every repository visible to an authenticated GitHub user and backs up its complete Git object database and refs. It also backs up the authenticated user's public and secret gists. Version 1.1 can optionally add repository wikis, pull requests and other API metadata, release assets, Actions artifacts and logs, and Git LFS objects. It is designed for unattended, security-sensitive production operation.
44

55
The defaults match the safest low-overhead setup:
66

77
- local disk or a mounted NAS;
88
- every repository the token can access (owned, collaborator, and organization membership);
99
- incremental bare mirrors;
10-
- public and secret gists included.
10+
- public and secret gists included;
11+
- additional GitHub service data disabled unless explicitly selected.
1112

1213
The user can select filesystem or S3-compatible storage, repository scope, and incremental or immutable snapshot mode at execution time or in TOML.
1314

14-
## What is backed up
15+
## Backup coverage
16+
17+
The default run backs up:
1518

1619
- all Git refs and objects exposed by each repository's clone endpoint;
1720
- owned, collaborator, and organization repositories allowed by the token;
1821
- public and private repositories;
1922
- public and secret gists belonging to the authenticated user;
2023
- resource metadata and a detailed manifest for every run.
2124

22-
GitHub issues, pull-request discussions, releases, Actions artifacts, packages, wikis, and Git LFS payloads are separate services and are not included in version `0.1`. Normal Git commits, branches, tags, notes, and pull-request refs exposed by the clone endpoint are included. Submodule pointers are included; the referenced repository is backed up when the token can discover it independently.
25+
Normal Git commits, branches, tags, notes, and pull-request refs exposed by the clone endpoint are included. Submodule pointers are included; the referenced repository is backed up when the token can discover it independently.
26+
27+
Additional components are opt-in with repeatable `--include` flags or `backup.additional_data`:
28+
29+
| Component | Data | Restore format and cost |
30+
|---|---|---|
31+
| `wikis` | Wiki Git history and refs | Separate bare mirror/bundle. Low overhead; an enabled but empty wiki is recorded as skipped. |
32+
| `metadata` | Repository settings plus issues, issue events/comments, PRs, reviews/review comments, labels, milestones, branches, rulesets, collaborators, teams, deploy keys, webhook metadata, deployments, environments, secret names, and accessible security alerts/advisories | JSON/JSONL in a checksummed `tar.gz`. API-intensive; secret values are never available. |
33+
| `releases` | Release metadata and every accessible binary release asset | JSONL plus binary files in `tar.gz`; may consume substantial bandwidth and storage. |
34+
| `actions` | Metadata and downloads for non-expired Actions artifacts and completed-run logs still retained by GitHub | JSONL plus ZIP files in `tar.gz`; historical files already expired upstream cannot be recovered. |
35+
| `lfs` | All reachable Git LFS objects | `tar.gz`; requires `git-lfs` and can be much larger than the Git repository. |
36+
37+
Select individual components:
38+
39+
```bash
40+
github-backup run \
41+
--include wikis \
42+
--include metadata \
43+
--destination /mnt/backups/github
44+
```
45+
46+
Or select every supported optional component:
47+
48+
```bash
49+
github-backup run --include all --destination /mnt/backups/github
50+
```
51+
52+
`all` means all data classes this application can read and archive; it does not override GitHub's API restrictions. Every component archive contains `coverage.json`. Endpoints unavailable because of token permissions, feature availability, or GitHub edition are listed there and in the run manifest. Such a component has status `partial`, and the process returns exit code `2`, so monitoring cannot mistake a coverage gap for a complete backup.
53+
54+
### Enterprise completeness boundary
55+
56+
A token-based export cannot be a byte-for-byte backup of GitHub.com or GitHub Enterprise Cloud. GitHub does not return secret values, expired artifacts, deleted objects, all internal platform state, or every package-registry blob through a single backup API. Package contents should additionally be mirrored with the native npm, Maven, NuGet, RubyGems, or OCI/container registry client; secret values must be backed up at their source secret manager.
57+
58+
For GitHub Enterprise Server, a complete instance backup—including configuration and user data—must use the GitHub Enterprise Server Backup Service (preferred on GHES 3.17+) or the compatible legacy Backup Utilities. This project is a portable, token-authenticated complement and is useful for independent repository-level recovery, but it must not claim appliance-level completeness. See GitHub's [backup service documentation](https://docs.github.com/en/enterprise-server/admin/backing-up-and-restoring-your-instance/about-the-backup-service-for-github-enterprise-server) and [restore documentation](https://docs.github.com/en/enterprise-server/admin/backing-up-and-restoring-your-instance/restoring-from-a-backup).
2359

2460
## Requirements
2561

2662
- Python 3.11 or later;
2763
- Git 2.30 or later;
64+
- Git LFS when `--include lfs` is selected;
2865
- a GitHub token;
2966
- `boto3` only when using S3-compatible storage.
3067

3168
For GitHub.com, a classic personal access token normally needs `repo` for private repositories and `gist` for secret gists. Fine-grained tokens must be granted access to the intended repositories with read access to repository metadata and contents. Organization SAML/SSO policies may require the token to be authorized separately.
3269

33-
Never put the token in the TOML file or a command argument. The application reads it from an environment variable, injects it into Git only for the matching HTTPS host, and does not save it in remotes, logs, metadata, or manifests.
70+
Optional data requires matching read permissions—for example Actions read for artifacts/logs, administration-related read permissions for settings, and security-event access for alert data. Classic PATs used for broad organization backups commonly require `repo`, `read:org`, `read:packages`, and `security_events`; grant only the components you actually enable. The manifest is the authoritative record of what the token could retrieve.
71+
72+
Never put the token in the TOML file or a command argument. The application reads it from an environment variable, injects it into Git only for the matching HTTPS host, refuses authenticated redirects, and does not save it in remotes, logs, metadata, or manifests. Plain HTTP is rejected unless an explicit testing-only override is enabled.
3473

3574
## Installation
3675

@@ -84,7 +123,7 @@ github-backup run \
84123
--cache-dir /var/cache/github-backup
85124
```
86125

87-
For MinIO, Ceph, Backblaze B2, or another S3-compatible service, also pass `--s3-endpoint-url`. Standard AWS credential environment variables, profiles, instance roles, and workload identities are handled by the AWS SDK.
126+
For MinIO, Ceph, Backblaze B2, or another S3-compatible service, also pass `--s3-endpoint-url`. Custom endpoints must use HTTPS by default; `--allow-insecure-s3-endpoint` is available only for deliberately isolated test or LAN deployments. Standard AWS credential environment variables, profiles, instance roles, and workload identities are handled by the AWS SDK.
88127

89128
## Configuration
90129

@@ -106,6 +145,9 @@ The token variable name itself is configurable with `github.token_env`; its defa
106145
| Scope | `accessible`, `owned`, `organizations` | `accessible` | Accessible is comprehensive. Owned is narrower. Organizations requires one or more `--organization` values. |
107146
| Mode | `incremental`, `snapshot` | `incremental` | Incremental keeps the latest mirror and prunes refs deleted upstream. Snapshot creates immutable point-in-time artifacts and uses more storage. |
108147
| Gists | `--gists`, `--no-gists` | included | Secret gists require suitable token access. |
148+
| Extra data | repeatable `--include`, or `--include all` | none | Adds coverage, API calls, transfer time, and storage. Components remain independent in the manifest. |
149+
150+
Snapshot retention defaults to unlimited (`0`). Set `backup.snapshot_retention` or `--snapshot-retention` to retain only the newest successful snapshots. For S3, retention requires list and delete permissions on the configured prefix. Bucket lifecycle policies remain recommended as a second control.
109151

110152
On S3, Git cannot update a remote bundle in place. A persistent local bare-mirror cache still makes GitHub downloads incremental. The application only packages and uploads a new `latest` artifact when refs changed or the remote object is absent. Snapshot mode uploads an immutable artifact on every run.
111153

@@ -123,14 +165,22 @@ backups/
123165
│ └── gists/GIST_ID.json
124166
├── mirrors/
125167
│ ├── repos/OWNER/REPOSITORY.git/
168+
│ ├── wikis/OWNER/REPOSITORY.wiki.git/
126169
│ └── gists/GIST_ID.git/
170+
├── supplemental/latest/repos/OWNER/REPOSITORY/
171+
│ ├── metadata.tar.gz
172+
│ ├── releases.tar.gz
173+
│ ├── actions.tar.gz
174+
│ └── lfs.tar.gz
127175
└── snapshots/ # snapshot mode only
128-
└── RUN_ID/.../*.git.bundle
176+
└── RUN_ID/... # Git bundles and component archives
129177
```
130178

131-
Empty repositories have no refs and cannot be represented by a Git bundle, so snapshot mode stores them as `.empty.tar.gz` archives. Writes to JSON and local snapshot artifacts use same-filesystem atomic replacement. A process lock prevents overlapping runs against the same destination/cache. Stale local locks are recovered when their process no longer exists.
179+
Empty repositories have no refs and cannot be represented by a Git bundle, so snapshot mode stores them as `.empty.tar.gz` archives. Writes to JSON and local snapshot artifacts use same-filesystem atomic replacement. Local/NAS runs use a process lock; S3 runs additionally use a renewable, conditional ETag lease so separate hosts cannot update the same prefix concurrently. Expired S3 leases are recovered with compare-and-swap deletion.
180+
181+
New local files are created under a `0077` umask, and the destination/cache must not be group- or world-accessible. Existing destinations with broader Unix mode bits are rejected. Set `allow_insecure_permissions=true` only when access is deliberately controlled by another mechanism such as a reviewed NAS ACL. The application also checks configurable minimum free space before starting.
132182

133-
Every completed run writes an immutable manifest and replaces `latest.json`. A partial per-resource failure returns exit code `2`, records the failure in the manifest, and leaves successful backups usable. Configuration, authentication, discovery, or storage setup failures return exit code `1`.
183+
Every completed run writes an immutable manifest and replaces `latest.json`. A partial component or per-resource failure returns exit code `2`, records the exact result in the manifest, and leaves successful backups usable. Skipped resources such as an enabled but empty wiki are recorded without failing the run. Configuration, authentication, discovery, or storage setup failures return exit code `1`.
134184

135185
## Restore
136186

@@ -155,6 +205,16 @@ git clone /mnt/backups/github/snapshots/RUN_ID/repos/OWNER/REPOSITORY.git.bundle
155205

156206
For S3, download the selected `.bundle` first and use the same command. Extract an `.empty.tar.gz` archive directly when restoring an empty repository. Always test restores periodically; a successful upload is not a substitute for a restore drill.
157207

208+
Verify every local mirror and snapshot artifact without requiring a GitHub token:
209+
210+
```bash
211+
github-backup verify --destination /mnt/backups/github
212+
```
213+
214+
This runs Git connectivity checks on mirrors, verifies bundles against their corresponding mirrors, and validates empty-repository and supplementary archives.
215+
216+
Wiki mirrors and bundles use the same Git restore process. Supplementary archives are portable `tar.gz` files with JSON/JSONL metadata and original binary downloads. They deliberately preserve source records rather than attempting destructive automatic recreation through GitHub APIs; restoration should be rehearsed with an organization-specific importer and identity mapping. `verify` validates each tar container and checks its SHA-256 digest against the latest manifest.
217+
158218
## Scheduling
159219

160220
Use an external scheduler so credentials remain under the platform's secret-management policy. A systemd service can execute:
@@ -182,25 +242,28 @@ docker run --rm \
182242
github-backup:local run --destination /backups
183243
```
184244

185-
The image runs as an unprivileged user. Ensure the mounted directory is writable by UID/GID `10001` or adapt ownership to your container platform.
245+
The image runs as an unprivileged user. Ensure the mounted directory is owned by UID/GID `10001`, is writable, and normally has mode `0700`, or adapt ownership to your container platform.
186246

187247
## Operational behavior
188248

189-
- GitHub API calls are paginated and serialized to reduce secondary-rate-limit pressure.
249+
- GitHub API calls are paginated; discovery is serialized to reduce secondary-rate-limit pressure.
250+
- Optional repository components use a bounded worker pool. JSON list responses are streamed to JSONL so large issue or pull-request histories do not need to reside in memory.
190251
- `Retry-After` and primary rate-limit reset headers are honored; transient API failures use bounded retries.
191-
- Git transfers run in a bounded worker pool. Four workers is the default; lower it on a slow NAS or constrained GitHub Enterprise Server.
252+
- Git transfers run in a bounded worker pool and retry transient failures with backoff. Four workers and three Git retries are the defaults; lower concurrency on a slow NAS or constrained GitHub Enterprise Server.
192253
- Initial clones are written to a temporary sibling and atomically renamed only after Git succeeds.
193-
- Existing backups are verified as bare repositories before update.
254+
- Existing backups are verified as bare repositories and checked with `git fsck --connectivity-only` after update.
194255
- Deleted upstream refs are pruned in incremental mode. Use snapshots when you must retain deleted branches or tags.
195-
- S3 uploads use the AWS SDK's adaptive retries and optional server-side encryption/storage-class settings.
256+
- S3 uploads use adaptive retries, AES-256 server-side encryption by default, and renewable distributed leases. KMS or an explicitly disabled encryption setting can be configured when required.
196257
- Human-readable logs are the default; `--json-logs` emits one JSON object per line.
258+
- Application dependencies are resolved by `uv.lock`; CI uses frozen installs, audits dependencies, and pins third-party Actions to immutable commits.
197259

198260
## Development
199261

200262
```bash
201263
python -m unittest discover -s tests -v
202264
ruff check .
203265
mypy src
266+
pip-audit
204267
```
205268

206269
The integration tests create real local repositories and exercise initial mirror creation, incremental updates, bundle verification, manifest writing, and credential non-persistence.

‎SECURITY.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Security policy
2+
3+
## Supported versions
4+
5+
Security fixes are provided for the latest `1.x` release. Older versions should be upgraded before reporting operational problems.
6+
7+
## Reporting a vulnerability
8+
9+
Do not open a public issue for a suspected vulnerability that could expose GitHub tokens, private repository data, backup credentials, or storage contents. Use GitHub's private vulnerability reporting feature for this repository. Include the affected version, deployment model, reproduction steps, and impact. Do not include live credentials or private source code.
10+
11+
## Deployment requirements
12+
13+
- Inject GitHub and storage credentials through a secret manager or protected environment file.
14+
- Use HTTPS GitHub and S3 endpoints. HTTP overrides exist only for deliberately isolated test systems.
15+
- Keep filesystem destinations and S3 cache directories private to the service account. The application rejects broad Unix mode bits by default, but operators must also review ACLs and mount-level permissions.
16+
- Enable encryption at rest for NAS volumes. S3 uploads request AES-256 server-side encryption by default; use KMS when policy requires managed keys.
17+
- Grant the GitHub token read-only repository access and gist access. Do not grant write or administration permissions.
18+
- Scope S3 credentials to the configured bucket prefix. Snapshot retention additionally requires list and delete permissions.
19+
- Treat manifests and logs as sensitive metadata because they contain private repository names and failure details.
20+
- Treat optional metadata archives as highly sensitive: they can contain private issues and pull requests, collaborator and deployment metadata, and security alerts. Secret names are exported when accessible, but GitHub never returns secret values.
21+
- Treat release, Actions, and LFS archives as untrusted user-controlled files. Do not execute or extract them outside an isolated restore workflow.
22+
- Monitor nonzero exit codes and test restoration on a schedule.

0 commit comments

Comments
 (0)