diff --git a/README.rst b/README.rst index 5dcef950..3121d56d 100644 --- a/README.rst +++ b/README.rst @@ -171,116 +171,111 @@ Customise the permissions for your use case, but for a personal account full bac **Repository permissions**: Read access to contents, issues, metadata, pull requests, and webhooks. -Prefer SSH -~~~~~~~~~~ -If cloning repos is enabled with ``--repositories``, ``--all-starred``, ``--wikis``, ``--gists``, ``--starred-gists`` using the ``--prefer-ssh`` argument will use ssh for cloning the git repos, but all other connections will still use their own protocol, e.g. API requests for issues uses HTTPS. - -To clone with SSH, you'll need SSH authentication setup `as usual with Github `_, e.g. via SSH public and private keys. - - -Using the Keychain on Mac OSX -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Note: On Mac OSX the token can be stored securely in the user's keychain. To do this: - -1. Open Keychain from "Applications -> Utilities -> Keychain Access" -2. Add a new password item using "File -> New Password Item" -3. Enter a name in the "Keychain Item Name" box. You must provide this name to github-backup using the --keychain-name argument. -4. Enter an account name in the "Account Name" box, enter your Github username as set above. You must provide this name to github-backup using the --keychain-account argument. -5. Enter your Github personal access token in the "Password" box - -Note: When you run github-backup, you will be asked whether you want to allow "security" to use your confidential information stored in your keychain. You have two options: - -1. **Allow:** In this case you will need to click "Allow" each time you run `github-backup` -2. **Always Allow:** In this case, you will not be asked for permission when you run `github-backup` in future. This is less secure, but is required if you want to schedule `github-backup` to run automatically - - -Github Rate-limit and Throttling --------------------------------- - -"github-backup" will automatically throttle itself based on feedback from the Github API. - -Their API is usually rate-limited to 5000 calls per hour. The API will ask github-backup to pause until a specific time when the limit is reset again (at the start of the next hour). This continues until the backup is complete. - -During a large backup, such as ``--all-starred``, and on a fast connection this can result in (~20 min) pauses with bursts of API calls periodically maxing out the API limit. If this is not suitable `it has been observed `_ under real-world conditions that overriding the throttle with ``--throttle-limit 5000 --throttle-pause 0.6`` provides a smooth rate across the hour, although a ``--throttle-pause 0.72`` (3600 seconds [1 hour] / 5000 limit) is theoretically safer to prevent large rate-limit pauses. - - -About Git LFS -------------- - -When you use the ``--lfs`` option, you will need to make sure you have Git LFS installed. - -Instructions on how to do this can be found on https://git-lfs.github.com. - - -Run in Docker container ------------------------ - -To run the tool in a Docker container use the following command: - - sudo docker run --rm -v /path/to/backup:/data --name github-backup ghcr.io/josegonzalez/python-github-backup -o /data $OPTIONS $USER - -Gotchas / Known-issues -====================== - -All is not everything ---------------------- - -The ``--all`` argument does not include: cloning private repos (``-P, --private``), cloning forks (``-F, --fork``), cloning starred repositories (``--all-starred``), ``--pull-details``, cloning LFS repositories (``--lfs``), cloning gists (``--gists``) or cloning starred gist repos (``--starred-gists``). See examples for more. - -Cloning all starred size ------------------------- - -Using the ``--all-starred`` argument to clone all starred repositories may use a large amount of storage space, especially if ``--all`` or more arguments are used. e.g. commonly starred repos can have tens of thousands of issues, many large assets and the repo itself etc. Consider just storing links to starred repos in JSON format with ``--starred``. - -Incremental Backup ------------------- - -Using (``-i, --incremental``) will only request new data from the API **since the last run (successful or not)**. e.g. only request issues from the API since the last run. - -This means any blocking errors on previous runs can cause a large amount of missing data in backups. - -Using (``--incremental-by-files``) will request new data from the API **based on when the file was modified on filesystem**. e.g. if you modify the file yourself you may miss something. - -Still saver than the previous version. - -Specifically, issues and pull requests are handled like this. - -Known blocking errors ---------------------- - -Some errors will block the backup run by exiting the script. e.g. receiving a 403 Forbidden error from the Github API. - -If the incremental argument is used, this will result in the next backup only requesting API data since the last blocked/failed run. Potentially causing unexpected large amounts of missing data. - -It's therefore recommended to only use the incremental argument if the output/result is being actively monitored, or complimented with periodic full non-incremental runs, to avoid unexpected missing data in a regular backup runs. - -1. **Starred public repo hooks blocking** - - Since the ``--all`` argument includes ``--hooks``, if you use ``--all`` and ``--all-starred`` together to clone a users starred public repositories, the backup will likely error and block the backup continuing. - - This is due to needing the correct permission for ``--hooks`` on public repos. - - -"bare" is actually "mirror" ---------------------------- - -Using the bare clone argument (``--bare``) will actually call git's ``clone --mirror`` command. There's a subtle difference between `bare `_ and `mirror `_ clone. - -*From git docs "Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote-tracking branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository."* - - -Starred gists vs starred repo behaviour ---------------------------------------- - -The starred normal repo cloning (``--all-starred``) argument stores starred repos separately to the users own repositories. However, using ``--starred-gists`` will store starred gists within the same directory as the users own gists ``--gists``. Also, all gist repo directory names are IDs not the gist's name. +GitHub App Authentication +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For backing up entire organizations, **GitHub App authentication** (``--as-app``) is the recommended approach as it provides: + +* **Higher rate limits**: 5000 requests/hour per installation vs standard personal token limits +* **Broader access**: Organization-wide repository access when installed with "All repositories" +* **Enterprise-friendly**: Proper app-based authentication for organizational backup scenarios +* **Automated token management**: No need to manually handle token expiry during long backups + +Creating a GitHub App for Organization Backup +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +1. **Create the GitHub App**: + + * Go to your organization's settings: ``https://github.com/organizations/YOUR_ORG/settings/apps`` + * Click "New GitHub App" + * Fill in basic information: + - App name: e.g., "Organization Backup Tool" + - Homepage URL: Can be your organization's website + - Webhook URL: Not required, can leave blank or use a placeholder + +2. **Configure Permissions**: + + **Repository permissions** (select "Read" access for): + + * Contents + * Issues + * Metadata + * Pull requests + * Webhooks + * Repository projects (if backing up projects) + + **Organization permissions** (select "Read" access for): + + * Members + * Metadata + + **Account permissions** (select "Read" access for): + + * Starring + * Watching + +3. **Installation Settings**: + + * Set "Where can this GitHub App be installed?" to "Only on this account" for security + * Under "Repository access", choose "All repositories" to backup the entire organization + +4. **Generate Private Key**: + + * After creating the app, scroll down to "Private keys" section + * Click "Generate a private key" + * Download the ``.pem`` file and store it securely + +5. **Install the App**: + + * Go to the "Install App" tab in your GitHub App settings + * Click "Install" next to your organization + * Choose "All repositories" for comprehensive backup access + +6. **Get Required Information**: + + * **App ID**: Found in your GitHub App settings under "General" tab (the number at the top) + * **Installation ID**: After installing, the URL will show the installation ID: ``/organizations/YOUR_ORG/settings/installations/INSTALLATION_ID`` + * **Private Key**: The ``.pem`` file you downloaded + +Using GitHub App Authentication +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +With the GitHub App created and installed, you can use it directly with github-backup:: + + github-backup YOUR_ORG \ + --app-id 123456 \ + --installation-id 789012 \ + --private-key /path/to/your-app.pem \ + --organization \ + --repositories \ + --output-directory /tmp/backup + +Or using environment variables for security:: + + export GITHUB_APP_ID=123456 + export GITHUB_INSTALLATION_ID=789012 + export GITHUB_PRIVATE_KEY=/path/to/your-app.pem + + github-backup YOUR_ORG \ + --app-id $GITHUB_APP_ID \ + --installation-id $GITHUB_INSTALLATION_ID \ + --private-key $GITHUB_PRIVATE_KEY \ + --organization \ + --repositories \ + --all +**Key Benefits**: -Skip existing on incomplete backups ------------------------------------ +* **Automatic token management**: The tool automatically generates and refreshes installation access tokens as needed +* **No manual token handling**: No need for external scripts or cron job token generation +* **Handles long backups**: Token expiry is automatically handled during multi-hour organization backups +* **Docker-friendly**: Simple to use in containerized environments with mounted private key files -The ``--skip-existing`` argument will skip a backup if the directory already exists, even if the backup in that directory failed (perhaps due to a blocking error). This may result in unexpected missing data in a regular backup. +**For automated/cron backups**, simply set up the same command in your cron job:: + # Daily backup at 2 AM + 0 2 * * * github-backup YOUR_ORG --app-id $GITHUB_APP_ID --installation-id $GITHUB_INSTALLATION_ID --private-key $GITHUB_PRIVATE_KEY --organization --repositories --output-directory /backup/github Github Backup Examples ====================== @@ -314,6 +309,59 @@ Debug an error/block or incomplete backup into a temporary directory. Omit "incr +GitHub App Organization Backup Examples +======================================== + +Backup entire organization using GitHub App (recommended for organizations):: + + github-backup mycompany \ + --app-id 123456 \ + --installation-id 789012 \ + --private-key /path/to/app-private-key.pem \ + --organization \ + --repositories \ + --issues \ + --pulls \ + --wikis \ + --output-directory /backup/github-org + +Incremental organization backup with GitHub App for automated/cron scenarios:: + + github-backup mycompany \ + --app-id 123456 \ + --installation-id 789012 \ + --private-key /path/to/app-private-key.pem \ + --organization \ + --repositories \ + --incremental \ + --output-directory /backup/github-org + +Backup specific organization repository with comprehensive data using GitHub App:: + + github-backup mycompany \ + --app-id 123456 \ + --installation-id 789012 \ + --private-key /path/to/app-private-key.pem \ + --organization \ + --repository main-project \ + --repositories \ + --issues \ + --pulls \ + --wikis \ + --issue-comments \ + --pull-comments \ + --output-directory /backup/github-repo + +Organization backup excluding certain repositories:: + + github-backup mycompany \ + --app-id 123456 \ + --installation-id 789012 \ + --private-key /path/to/app-private-key.pem \ + --organization \ + --repositories \ + --exclude repo-to-skip another-repo-to-skip \ + --output-directory /backup/github-org Development =========== diff --git a/activate_dev.sh b/activate_dev.sh new file mode 100755 index 00000000..31b8c6f8 --- /dev/null +++ b/activate_dev.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +# Development Environment Activation Script +# This script activates the virtual environment and sets up the development environment + +echo "🐍 Activating python-github-backup development environment..." + +# Check if virtual environment exists +if [ ! -d "venv" ]; then + echo "❌ Virtual environment not found. Please run the setup first:" + echo " python3 -m venv venv" + echo " source venv/bin/activate" + echo " pip install -r requirements.txt" + echo " pip install -r release-requirements.txt" + echo " pip install -e ." + exit 1 +fi + +# Activate virtual environment +echo "✅ Activating virtual environment..." +source venv/bin/activate + +# Check if package is installed +if ! python -c "import github_backup" 2>/dev/null; then + echo "❌ Package not installed in development mode. Installing..." + pip install -e . +fi + +echo "✅ Development environment ready!" +echo "" +echo "Available commands:" +echo " github-backup -h # Show help" +echo " flake8 --ignore=E501 github_backup/ # Run linting" +echo " black --check github_backup/ # Check code formatting" +echo " black github_backup/ # Format code" +echo "" +echo "To deactivate: deactivate" diff --git a/bin/github-backup b/bin/github-backup index b33d19ff..555c119a 100755 --- a/bin/github-backup +++ b/bin/github-backup @@ -14,6 +14,7 @@ from github_backup.github_backup import ( mkdir_p, parse_args, retrieve_repositories, + validate_args, ) logging.basicConfig( @@ -25,6 +26,7 @@ logging.basicConfig( def main(): args = parse_args() + validate_args(args) if args.quiet: logger.setLevel(logging.WARNING) diff --git a/github_backup/github_backup.py b/github_backup/github_backup.py index 4b2d7905..886bfd24 100644 --- a/github_backup/github_backup.py +++ b/github_backup/github_backup.py @@ -19,13 +19,22 @@ import subprocess import sys import time -from datetime import datetime +from datetime import datetime, timedelta from http.client import IncompleteRead from urllib.error import HTTPError, URLError from urllib.parse import quote as urlquote from urllib.parse import urlencode, urlparse from urllib.request import HTTPRedirectHandler, Request, build_opener, urlopen +# GitHub App authentication imports +try: + import jwt +except ImportError: + raise ImportError( + "PyJWT library is required for GitHub App authentication. " + "Install it with: pip install PyJWT>=2.0.0 cryptography>=3.0.0" + ) + try: from . import __version__ @@ -37,6 +46,11 @@ FILE_URI_PREFIX = "file://" logger = logging.getLogger(__name__) +# Global variables for GitHub App token management +_github_app_token = None +_github_app_token_expires = None +_github_app_credentials = None + https_ctx = ssl.create_default_context() if not https_ctx.get_ca_certs(): import warnings @@ -82,7 +96,9 @@ def check_io(): if not logger: continue if not (io == child.stderr and not line): - logger.log(log_level[io], line[:-1]) + # Decode bytes to string for proper logging + line_str = line.decode('utf-8', errors='replace').rstrip('\n') + logger.log(log_level[io], line_str) # keep checking stdout/stderr until the child exits while child.poll() is None: @@ -160,6 +176,21 @@ def parse_args(args=None): dest="as_app", help="authenticate as github app instead of as a user.", ) + parser.add_argument( + "--app-id", + dest="app_id", + help="GitHub App ID for app authentication", + ) + parser.add_argument( + "--installation-id", + dest="installation_id", + help="GitHub App Installation ID for app authentication", + ) + parser.add_argument( + "--private-key", + dest="private_key", + help="GitHub App private key (PEM format) or path to private key file (file://...)", + ) parser.add_argument( "-o", "--output-directory", @@ -440,9 +471,82 @@ def parse_args(args=None): return parser.parse_args(args) +def validate_args(args): + """Validate argument combinations and dependencies.""" + # Auto-enable --as-app when GitHub App credentials are provided + if args.app_id and args.installation_id and args.private_key: + if not args.as_app: + logger.info("GitHub App credentials provided. Automatically enabling --as-app mode.") + args.as_app = True + + # GitHub App authentication validation + if args.as_app: + # Check if user provided GitHub App credentials + app_creds_provided = bool(args.app_id and args.installation_id and args.private_key) + # Check if user provided a token + token_provided = bool(args.token_classic) + + if not app_creds_provided and not token_provided: + raise Exception( + "When using --as-app, you must provide either:\n" + " 1. GitHub App credentials: --app-id, --installation-id, --private-key, OR\n" + " 2. A pre-generated installation token: --token" + ) + + if app_creds_provided and token_provided: + raise Exception( + "Cannot use both GitHub App credentials (--app-id, --installation-id, --private-key) " + "and pre-generated token (--token) simultaneously. Choose one approach." + ) + + # Validate that GitHub App credentials are complete if any are provided + app_cred_args = [args.app_id, args.installation_id, args.private_key] + app_creds_partial = any(app_cred_args) and not all(app_cred_args) + + if app_creds_partial: + missing = [] + if not args.app_id: + missing.append("--app-id") + if not args.installation_id: + missing.append("--installation-id") + if not args.private_key: + missing.append("--private-key") + + raise Exception( + f"Incomplete GitHub App credentials. Missing: {', '.join(missing)}\n" + "All three are required: --app-id, --installation-id, --private-key" + ) + + def get_auth(args, encode=True, for_git_cli=False): + global _github_app_credentials auth = None + # Handle GitHub App authentication + if args.app_id and args.installation_id and args.private_key: + if not args.as_app: + logger.warning("GitHub App credentials provided but --as-app not specified. Enabling app authentication.") + args.as_app = True + + # Store credentials globally for token refresh (only if not already set) + if not _github_app_credentials: + _github_app_credentials = (args.app_id, args.installation_id, args.private_key) + + # Get fresh token + token = get_or_refresh_github_app_token() + if not token: + raise Exception("Failed to generate GitHub App installation token") + + if not for_git_cli: + auth = token + else: + auth = "x-access-token:" + token + + # For GitHub App tokens, we don't need to encode + if not encode or not for_git_cli: + return auth + return base64.b64encode(auth.encode("ascii")) + if args.osx_keychain_item_name: if not args.osx_keychain_item_account: raise Exception( @@ -516,6 +620,82 @@ def get_auth(args, encode=True, for_git_cli=False): return base64.b64encode(auth.encode("ascii")) +def generate_github_app_token(app_id, installation_id, private_key): + """Generate an installation access token for GitHub App authentication.""" + try: + # Load private key + if private_key.startswith(FILE_URI_PREFIX): + private_key = read_file_contents(private_key) + elif os.path.exists(private_key): + # If it's a file path, convert to file:// format + file_uri = f"{FILE_URI_PREFIX}{private_key}" + private_key = read_file_contents(file_uri) + + # Create JWT payload + now = int(time.time()) + payload = { + "iat": now - 60, # Issued at (1 minute ago to account for clock skew) + "exp": now + 600, # Expires in 10 minutes (max allowed) + "iss": int(app_id) # Issuer (GitHub App ID) + } + # Generate JWT + jwt_token = jwt.encode(payload, private_key, algorithm="RS256") + + # Request installation access token + url = f"https://api.github.com/app/installations/{installation_id}/access_tokens" + headers = { + "Authorization": f"Bearer {jwt_token}", + "Accept": "application/vnd.github.v3+json", + "User-Agent": f"github-backup/{VERSION}" + } + + request = Request(url, headers=headers, method="POST") + request.data = b"" # Empty POST body + + response = urlopen(request, context=https_ctx) + data = json.loads(response.read().decode("utf-8")) + + token = data["token"] + expires_at = datetime.fromisoformat(data["expires_at"].replace("Z", "+00:00")) + + logger.info(f"Generated GitHub App installation token (expires at {expires_at})") + return token, expires_at + + except Exception as e: + raise Exception(f"Failed to generate GitHub App token: {str(e)}") + + +def get_or_refresh_github_app_token(): + """Get current GitHub App token or refresh it if expired/missing.""" + global _github_app_token, _github_app_token_expires, _github_app_credentials + + if not _github_app_credentials: + return None + + app_id, installation_id, private_key = _github_app_credentials + + # Simple approach: Check if token exists and is not expired (with 5-minute buffer) + # Convert both times to UTC for comparison (GitHub API returns UTC times) + now_utc = datetime.utcnow() + expires_utc = _github_app_token_expires.replace(tzinfo=None) if _github_app_token_expires else None + + # Generate new token if: + # 1. No token exists + # 2. Token is expired or will expire within 5 minutes + if (_github_app_token is None or + expires_utc is None or + now_utc >= (expires_utc - timedelta(minutes=5))): + + logger.info("Generating new GitHub App token...") + _github_app_token, _github_app_token_expires = generate_github_app_token( + app_id, installation_id, private_key + ) + else: + logger.debug(f"Using cached token, expires at: {_github_app_token_expires}") + + return _github_app_token + + def get_github_api_host(args): if args.github_host: host = args.github_host + "/api/v3" @@ -535,7 +715,7 @@ def get_github_host(args): def read_file_contents(file_uri): - return open(file_uri[len(FILE_URI_PREFIX) :], "rt").readline().strip() + return open(file_uri[len(FILE_URI_PREFIX) :], "rt").read() def get_github_repo_url(args, repository): @@ -572,7 +752,6 @@ def get_github_repo_url(args, repository): def retrieve_data_gen(args, template, query_args=None, single_request=False): - auth = get_auth(args, encode=not args.as_app) query_args = get_query_args(query_args) per_page = 100 page = 0 @@ -583,7 +762,10 @@ def retrieve_data_gen(args, template, query_args=None, single_request=False): else: page = page + 1 request_page, request_per_page = page, per_page - + + # Always get fresh auth before each API call - caching handles optimization + auth = get_auth(args, encode=not args.as_app) + request = _construct_request( request_per_page, request_page, @@ -593,7 +775,7 @@ def retrieve_data_gen(args, template, query_args=None, single_request=False): as_app=args.as_app, fine=True if args.token_fine is not None else False, ) # noqa - r, errors = _get_response(request, auth, template) + r, errors = _get_response(request, auth, template, args) status_code = int(r.getcode()) # Check if we got correct data @@ -687,7 +869,7 @@ def get_query_args(query_args=None): return query_args -def _get_response(request, auth, template): +def _get_response(request, auth, template, args=None): retry_timeout = 3 errors = [] # We'll make requests in a loop so we can @@ -697,7 +879,7 @@ def _get_response(request, auth, template): try: r = urlopen(request, context=https_ctx) except HTTPError as exc: - errors, should_continue = _request_http_error(exc, auth, errors) # noqa + errors, should_continue = _request_http_error(exc, auth, errors, args) # noqa r = exc except URLError as e: logger.warning(e.reason) @@ -756,7 +938,7 @@ def _construct_request( return request -def _request_http_error(exc, auth, errors): +def _request_http_error(exc, auth, errors, args=None): # HTTPError behaves like a Response so we can # check the status code and headers to see exactly # what failed. @@ -765,7 +947,24 @@ def _request_http_error(exc, auth, errors): headers = exc.headers limit_remaining = int(headers.get("x-ratelimit-remaining", 0)) - if exc.code == 403 and limit_remaining < 1: + # Handle GitHub App token expiry (401 Unauthorized) + if exc.code == 401 and _github_app_credentials is not None: + logger.warning("GitHub App token expired (401 Unauthorized). Refreshing token...") + try: + # Force refresh the token + global _github_app_token, _github_app_token_expires + _github_app_token = None # Force regeneration + _github_app_token_expires = None + + new_token = get_or_refresh_github_app_token() + if new_token: + logger.info("Successfully refreshed GitHub App token") + should_continue = True + else: + logger.error("Failed to refresh GitHub App token") + except Exception as e: + logger.error(f"Error refreshing GitHub App token: {str(e)}") + elif exc.code == 403 and limit_remaining < 1: # The X-RateLimit-Reset header includes a # timestamp telling us when the limit will reset # so we can calculate how long to wait rather diff --git a/requirements.txt b/requirements.txt index 8b137891..7d277623 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,2 @@ - +PyJWT>=2.0.0 +cryptography>=3.0.0