Skip to content

Commit

Permalink
Merge branch 'master' into add-repository-to-organization-secret
Browse files Browse the repository at this point in the history
  • Loading branch information
mohy01 committed Feb 6, 2023
2 parents da80a36 + 5e27c10 commit 3f20ef3
Show file tree
Hide file tree
Showing 33 changed files with 829 additions and 295 deletions.
41 changes: 41 additions & 0 deletions github/AppAuthentication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
############################ Copyrights and license ############################
# #
# Copyright 2023 Denis Blanchette <denisblanchette@gmail.com> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################


class AppAuthentication:
def __init__(
self,
app_id,
private_key,
installation_id,
token_permissions=None,
):
assert isinstance(app_id, (int, str)), app_id
assert isinstance(private_key, str)
assert isinstance(installation_id, int), installation_id
assert token_permissions is None or isinstance(
token_permissions, dict
), token_permissions
self.app_id = app_id
self.private_key = private_key
self.installation_id = installation_id
self.token_permissions = token_permissions
10 changes: 10 additions & 0 deletions github/AppAuthentication.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from typing import Optional, Dict, Union

class AppAuthentication:
def __init__(
self,
app_id: Union[int, str],
private_key: str,
installation_id: int,
token_permissions: Optional[Dict[str, str]] = ...,
): ...
17 changes: 17 additions & 0 deletions github/Consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,20 @@

# https://developer.github.com/changes/2019-12-03-internal-visibility-changes/
repoVisibilityPreview = "application/vnd.github.nebula-preview+json"

DEFAULT_BASE_URL = "https://api.github.com"
DEFAULT_STATUS_URL = "https://status.github.com"
# As of 2018-05-17, Github imposes a 10s limit for completion of API requests.
# Thus, the timeout should be slightly > 10s to account for network/front-end
# latency.
DEFAULT_TIMEOUT = 15
DEFAULT_PER_PAGE = 30

# JWT expiry in seconds. Could be set for max 600 seconds (10 minutes).
# https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app
DEFAULT_JWT_EXPIRY = 300
MIN_JWT_EXPIRY = 15
MAX_JWT_EXPIRY = 600
# https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#generating-a-json-web-token-jwt
# "The time the JWT was created. To protect against clock drift, we recommend you set this 60 seconds in the past."
DEFAULT_JWT_ISSUED_AT = -60
13 changes: 13 additions & 0 deletions github/GitRelease.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,14 @@ def zipball_url(self):
self._completeIfNotSet(self._zipball_url)
return self._zipball_url.value

@property
def assets(self):
"""
:type: list of :class:`github.GitReleaseAsset.GitReleaseAsset`
"""
self._completeIfNotSet(self._assets)
return self._assets.value

def delete_release(self):
"""
:calls: `DELETE /repos/{owner}/{repo}/releases/{release_id} <https://docs.github.com/en/rest/reference/repos#delete-a-release>`_
Expand Down Expand Up @@ -333,6 +341,7 @@ def _initAttributes(self):
self._published_at = github.GithubObject.NotSet
self._tarball_url = github.GithubObject.NotSet
self._zipball_url = github.GithubObject.NotSet
self._assets = github.GithubObject.NotSet

def _useAttributes(self, attributes):
if "id" in attributes:
Expand Down Expand Up @@ -369,3 +378,7 @@ def _useAttributes(self, attributes):
self._tarball_url = self._makeStringAttribute(attributes["tarball_url"])
if "zipball_url" in attributes:
self._zipball_url = self._makeStringAttribute(attributes["zipball_url"])
if "assets" in attributes:
self._assets = self._makeListOfClassesAttribute(
github.GitReleaseAsset.GitReleaseAsset, attributes["assets"]
)
2 changes: 2 additions & 0 deletions github/GitRelease.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ class GitRelease(CompletableGithubObject):
def _initAttributes(self) -> None: ...
def _useAttributes(self, attributes: Dict[str, Any]) -> None: ...
@property
def assets(self) -> list[GitReleaseAsset]: ...
@property
def author(self) -> NamedUser: ...
@property
def body(self) -> str: ...
Expand Down
199 changes: 199 additions & 0 deletions github/GithubIntegration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import time

import deprecated
import jwt

from github import Consts
from github.GithubException import GithubException
from github.Installation import Installation
from github.InstallationAuthorization import InstallationAuthorization
from github.PaginatedList import PaginatedList
from github.Requester import Requester


class GithubIntegration:
"""
Main class to obtain tokens for a GitHub integration.
"""

def __init__(
self,
integration_id,
private_key,
base_url=Consts.DEFAULT_BASE_URL,
jwt_expiry=Consts.DEFAULT_JWT_EXPIRY,
jwt_issued_at=Consts.DEFAULT_JWT_ISSUED_AT,
):
"""
:param integration_id: int
:param private_key: string
:param base_url: string
:param jwt_expiry: int. Expiry of the JWT used to get the information about this integration.
The default expiration is in 5 minutes and is capped at 10 minutes according to GitHub documentation
https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#generating-a-json-web-token-jwt
:param jwt_issued_at: int. Number of seconds, relative to now, to set for the "iat" (issued at) parameter.
The default value is -60 to protect against clock drift
"""
assert isinstance(integration_id, (int, str)), integration_id
assert isinstance(private_key, str), "supplied private key should be a string"
assert isinstance(base_url, str), base_url
assert isinstance(jwt_expiry, int), jwt_expiry
assert Consts.MIN_JWT_EXPIRY <= jwt_expiry <= Consts.MAX_JWT_EXPIRY, jwt_expiry
assert isinstance(jwt_issued_at, int)

self.base_url = base_url
self.integration_id = integration_id
self.private_key = private_key
self.jwt_expiry = jwt_expiry
self.jwt_issued_at = jwt_issued_at
self.__requester = Requester(
login_or_token=None,
password=None,
jwt=self.create_jwt(),
app_auth=None,
base_url=self.base_url,
timeout=Consts.DEFAULT_TIMEOUT,
user_agent="PyGithub/Python",
per_page=Consts.DEFAULT_PER_PAGE,
verify=True,
retry=None,
pool_size=None,
)

def _get_headers(self):
"""
Get headers for the requests.
:return: dict
"""
return {
"Authorization": f"Bearer {self.create_jwt()}",
"Accept": Consts.mediaTypeIntegrationPreview,
"User-Agent": "PyGithub/Python",
}

def _get_installed_app(self, url):
"""
Get installation for the given URL.
:param url: str
:rtype: :class:`github.Installation.Installation`
"""
headers, response = self.__requester.requestJsonAndCheck(
"GET", url, headers=self._get_headers()
)

return Installation(
requester=self.__requester,
headers=headers,
attributes=response,
completed=True,
)

def create_jwt(self):
"""
Create a signed JWT
https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app
:return string:
"""
now = int(time.time())
payload = {
"iat": now + self.jwt_issued_at,
"exp": now + self.jwt_expiry,
"iss": self.integration_id,
}
encrypted = jwt.encode(payload, key=self.private_key, algorithm="RS256")

if isinstance(encrypted, bytes):
encrypted = encrypted.decode("utf-8")

return encrypted

def get_access_token(self, installation_id, permissions=None):
"""
:calls: `POST /app/installations/{installation_id}/access_tokens <https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app>`
:param installation_id: int
:param permissions: dict
:return: :class:`github.InstallationAuthorization.InstallationAuthorization`
"""
if permissions is None:
permissions = {}

if not isinstance(permissions, dict):
raise GithubException(
status=400, data={"message": "Invalid permissions"}, headers=None
)

body = {"permissions": permissions}
headers, response = self.__requester.requestJsonAndCheck(
"POST",
f"/app/installations/{installation_id}/access_tokens",
input=body,
)

return InstallationAuthorization(
requester=self.__requester,
headers=headers,
attributes=response,
completed=True,
)

@deprecated.deprecated("Use get_repo_installation")
def get_installation(self, owner, repo):
"""
Deprecated by get_repo_installation
:calls: `GET /repos/{owner}/{repo}/installation <https://docs.github.com/en/rest/reference/apps#get-a-repository-installation-for-the-authenticated-app>`
:param owner: str
:param repo: str
:rtype: :class:`github.Installation.Installation`
"""
return self._get_installed_app(url=f"/repos/{owner}/{repo}/installation")

def get_installations(self):
"""
:calls: GET /app/installations <https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app>
:rtype: :class:`github.PaginatedList.PaginatedList[github.Installation.Installation]`
"""
return PaginatedList(
contentClass=Installation,
requester=self.__requester,
firstUrl="/app/installations",
firstParams=None,
headers=self._get_headers(),
list_item="installations",
)

def get_org_installation(self, org):
"""
:calls: `GET /orgs/{org}/installation <https://docs.github.com/en/rest/apps/apps#get-an-organization-installation-for-the-authenticated-app>`
:param org: str
:rtype: :class:`github.Installation.Installation`
"""
return self._get_installed_app(url=f"/orgs/{org}/installation")

def get_repo_installation(self, owner, repo):
"""
:calls: `GET /repos/{owner}/{repo}/installation <https://docs.github.com/en/rest/reference/apps#get-a-repository-installation-for-the-authenticated-app>`
:param owner: str
:param repo: str
:rtype: :class:`github.Installation.Installation`
"""
return self._get_installed_app(url=f"/repos/{owner}/{repo}/installation")

def get_user_installation(self, username):
"""
:calls: `GET /users/{username}/installation <https://docs.github.com/en/rest/apps/apps#get-a-user-installation-for-the-authenticated-app>`
:param username: str
:rtype: :class:`github.Installation.Installation`
"""
return self._get_installed_app(url=f"/users/{username}/installation")

def get_app_installation(self, installation_id):
"""
:calls: `GET /app/installations/{installation_id} <https://docs.github.com/en/rest/apps/apps#get-an-installation-for-the-authenticated-app>`
:param installation_id: int
:rtype: :class:`github.Installation.Installation`
"""
return self._get_installed_app(url=f"/app/installations/{installation_id}")
34 changes: 34 additions & 0 deletions github/GithubIntegration.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import Union, Optional, Dict

from github.Installation import Installation
from github.InstallationAuthorization import InstallationAuthorization
from github.PaginatedList import PaginatedList
from github.Requester import Requester

class GithubIntegration:
integration_id: Union[int, str] = ...
private_key: str = ...
base_url: str = ...
jwt_expiry: int = ...
jwt_issued_at: int = ...
__requester: Requester = ...
def __init__(
self,
integration_id: Union[int, str],
private_key: str,
base_url: str = ...,
jwt_expiry: int = ...,
jwt_issued_at: int = ...,
) -> None: ...
def _get_installed_app(self, url: str) -> Installation: ...
def _get_headers(self) -> Dict[str, str]: ...
def create_jwt(self, expiration: int = ...) -> str: ...
def get_access_token(
self, installation_id: int, permissions: Optional[Dict[str, str]] = ...
) -> InstallationAuthorization: ...
def get_app_installation(self, installation_id: int) -> Installation: ...
def get_installation(self, owner: str, repo: str) -> Installation: ...
def get_installations(self) -> PaginatedList[Installation]: ...
def get_org_installation(self, org: str) -> Installation: ...
def get_repo_installation(self, owner: str, repo: str) -> Installation: ...
def get_user_installation(self, username: str) -> Installation: ...
22 changes: 22 additions & 0 deletions github/InstallationAuthorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,26 @@ def on_behalf_of(self):
"""
return self._on_behalf_of.value

@property
def permissions(self):
"""
:type: dict
"""
return self._permissions.value

@property
def repository_selection(self):
"""
:type: string
"""
return self._repository_selection.value

def _initAttributes(self):
self._token = github.GithubObject.NotSet
self._expires_at = github.GithubObject.NotSet
self._on_behalf_of = github.GithubObject.NotSet
self._permissions = github.GithubObject.NotSet
self._repository_selection = github.GithubObject.NotSet

def _useAttributes(self, attributes):
if "token" in attributes: # pragma no branch
Expand All @@ -71,3 +87,9 @@ def _useAttributes(self, attributes):
self._on_behalf_of = self._makeClassAttribute(
github.NamedUser.NamedUser, attributes["on_behalf_of"]
)
if "permissions" in attributes: # pragma no branch
self._permissions = self._makeDictAttribute(attributes["permissions"])
if "repository_selection" in attributes: # pragma no branch
self._repository_selection = self._makeStringAttribute(
attributes["repository_selection"]
)
4 changes: 4 additions & 0 deletions github/InstallationAuthorization.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,7 @@ class InstallationAuthorization(NonCompletableGithubObject):
def on_behalf_of(self) -> NamedUser: ...
@property
def token(self) -> str: ...
@property
def permissions(self) -> dict: ...
@property
def repository_selection(self) -> str: ...

0 comments on commit 3f20ef3

Please sign in to comment.