-
-
Notifications
You must be signed in to change notification settings - Fork 635
Implement GitHub app authentication #1932
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,6 +15,7 @@ __pycache__ | |
| .venv | ||
| .vscode | ||
| *.log | ||
| *.pem | ||
| backend/data | ||
| backend/staticfiles | ||
| build | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| """GitHub App authentication module.""" | ||
|
|
||
| import logging | ||
| import os | ||
| from pathlib import Path | ||
|
|
||
| from django.conf import settings | ||
| from github import Auth, Github | ||
| from github.GithubException import BadCredentialsException | ||
|
|
||
| from apps.github.constants import GITHUB_ITEMS_PER_PAGE | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class GitHubAppAuth: | ||
| """GitHub App authentication handler.""" | ||
|
|
||
| def __init__(self): | ||
| """Initialize GitHub App authentication.""" | ||
| self.app_id = settings.GITHUB_APP_ID | ||
| self.app_installation_id = settings.GITHUB_APP_INSTALLATION_ID | ||
| self.private_key = self._load_private_key() | ||
|
|
||
| self.pat_token = os.getenv("GITHUB_TOKEN") | ||
|
|
||
| if not self._is_app_configured() and not self.pat_token: | ||
| error_message = ( | ||
| "GitHub App configuration is incomplete. " | ||
| "Please set GITHUB_APP_ID and GITHUB_APP_INSTALLATION_ID, " | ||
| "ensure backend/.github.pem file exists, " | ||
| "or provide GITHUB_TOKEN for PAT authentication." | ||
| ) | ||
| raise ValueError(error_message) | ||
|
|
||
| def _is_app_configured(self) -> bool: | ||
| """Check if GitHub App is properly configured.""" | ||
| return all((self.app_id, self.private_key, self.app_installation_id)) | ||
|
|
||
| def _load_private_key(self): | ||
| """Load the GitHub App private key from a local file.""" | ||
| try: | ||
| with (Path(settings.BASE_DIR) / ".github.pem").open("r") as key_file: | ||
| return key_file.read().strip() | ||
| except (FileNotFoundError, PermissionError): | ||
| return None | ||
|
|
||
| def get_github_client(self, per_page: int | None = None) -> Github: | ||
| """Get authenticated GitHub client. | ||
|
|
||
| Args: | ||
| per_page: Number of items per page for pagination. | ||
|
|
||
| Returns: | ||
| Authenticated GitHub client instance. | ||
|
|
||
| Raises: | ||
| BadCredentialsException: If authentication fails. | ||
|
|
||
| """ | ||
| per_page = per_page or GITHUB_ITEMS_PER_PAGE | ||
|
|
||
| if self._is_app_configured(): | ||
| logger.warning("Using GitHub App authentication") | ||
| return Github( | ||
| auth=Auth.AppInstallationAuth( | ||
| app_auth=Auth.AppAuth( | ||
| app_id=self.app_id, | ||
| private_key=self.private_key, | ||
| ), | ||
| installation_id=int(self.app_installation_id), | ||
| ), | ||
| per_page=per_page, | ||
| ) | ||
|
|
||
| if self.pat_token: | ||
| logger.warning("Using GitHub PAT token") | ||
| return Github(self.pat_token, per_page=per_page) | ||
|
|
||
| raise BadCredentialsException(401, "Invalid GitHub credentials", None) | ||
|
|
||
|
|
||
| def get_github_client(per_page: int | None = None) -> Github: | ||
| """Get authenticated GitHub client. | ||
|
|
||
| Args: | ||
| per_page: Number of items per page for pagination. | ||
|
|
||
| Returns: | ||
| Authenticated GitHub client instance. | ||
|
|
||
| """ | ||
| return GitHubAppAuth().get_github_client(per_page=per_page) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
113 changes: 113 additions & 0 deletions
113
backend/apps/github/management/commands/github_get_installation_id.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| """A command to get GitHub App installation ID.""" | ||
|
|
||
| import logging | ||
| import os | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| from django.conf import settings | ||
| from django.core.management.base import BaseCommand | ||
| from github import Auth, GithubIntegration | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = "Get GitHub App installation ID for the configured app." | ||
|
|
||
| def add_arguments(self, parser): | ||
| """Add command-line arguments to the parser. | ||
|
|
||
| Args: | ||
| parser (argparse.ArgumentParser): The argument parser instance. | ||
|
|
||
| """ | ||
| parser.add_argument( | ||
| "--app-id", | ||
| type=int, | ||
| help="GitHub App ID (overrides GITHUB_APP_ID environment variable)", | ||
| ) | ||
| parser.add_argument( | ||
| "--private-key-file", | ||
| type=str, | ||
| help="Path to private key file (overrides default backend/.github.pem)", | ||
| ) | ||
|
|
||
| def handle(self, *args, **options): | ||
| """Handle the command execution. | ||
|
|
||
| Args: | ||
| *args: Variable length argument list. | ||
| **options: Arbitrary keyword arguments containing command options. | ||
|
|
||
| """ | ||
| # Get app ID from arguments or environment | ||
| app_id = options.get("app_id") or os.getenv("GITHUB_APP_ID") | ||
| if not app_id: | ||
| self.stderr.write( | ||
| self.style.ERROR( | ||
| "GitHub App ID is required. " | ||
| "Provide --app-id argument or set GITHUB_APP_ID environment variable." | ||
| ) | ||
| ) | ||
| sys.exit(1) | ||
|
|
||
| # Get private key from file | ||
| private_key_file = ( | ||
| options.get("private_key_file") or Path(settings.BASE_DIR) / ".github.pem" | ||
| ) | ||
| if not Path(private_key_file).exists(): | ||
| self.stderr.write( | ||
| self.style.ERROR( | ||
| f"Private key file not found: {private_key_file}. " | ||
| "Please ensure the file exists and contains your GitHub App private key." | ||
| ) | ||
| ) | ||
| sys.exit(1) | ||
|
|
||
| try: | ||
| with Path(private_key_file).open("r") as key_file: | ||
| private_key = key_file.read().strip() | ||
| if not private_key: | ||
| self.stderr.write( | ||
| self.style.ERROR(f"Private key file is empty: {private_key_file}") | ||
| ) | ||
| sys.exit(1) | ||
| except (FileNotFoundError, PermissionError) as e: | ||
| self.stderr.write(self.style.ERROR(f"Failed to read private key file: {e}")) | ||
| sys.exit(1) | ||
|
|
||
| try: | ||
| # Create GitHub App authentication | ||
| app_auth = Auth.AppAuth(app_id=int(app_id), private_key=private_key) | ||
|
|
||
| # Create GitHub Integration instance | ||
| gi = GithubIntegration(auth=app_auth) | ||
|
|
||
| # Get all installations | ||
| installations = list(gi.get_installations()) | ||
|
|
||
| if not installations: | ||
| self.stdout.write( | ||
| self.style.WARNING(f"No installations found for GitHub App ID: {app_id}") | ||
| ) | ||
| return | ||
|
|
||
| self.stdout.write( | ||
| self.style.SUCCESS( | ||
| f"Found {len(installations)} installation(s) for GitHub App ID: {app_id}" | ||
| ) | ||
| ) | ||
|
|
||
| for installation in installations: | ||
| self.stdout.write(f"Installation ID: {installation.id}") | ||
| if hasattr(installation, "account") and installation.account: | ||
| account_type = installation.account.type | ||
| account_name = getattr(installation.account, "login", "N/A") | ||
| self.stdout.write(f" Account: {account_name} ({account_type})") | ||
| self.stdout.write("") | ||
|
|
||
| except Exception as e: | ||
| self.stderr.write(self.style.ERROR(f"Failed to get installations: {e}")) | ||
| logger.exception("Error getting GitHub App installations") | ||
| sys.exit(1) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.