From 822fc05cd5aaf20c87317b32cd897b5a95bd8c60 Mon Sep 17 00:00:00 2001 From: Enrico Minack Date: Fri, 17 Mar 2023 11:40:48 +0100 Subject: [PATCH] Add expiration argument back to GithubIntegration.create_jwt (#2439) * Add expiration argument back to create_jwt --- github/GithubIntegration.py | 10 ++++++++-- github/GithubIntegration.pyi | 2 +- tests/GithubIntegration.py | 21 +++++++++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/github/GithubIntegration.py b/github/GithubIntegration.py index ecc136c6..82c85bc9 100644 --- a/github/GithubIntegration.py +++ b/github/GithubIntegration.py @@ -90,17 +90,23 @@ class GithubIntegration: completed=True, ) - def create_jwt(self): + def create_jwt(self, expiration=None): """ 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: """ + if expiration is not None: + assert isinstance(expiration, int), expiration + assert ( + Consts.MIN_JWT_EXPIRY <= expiration <= Consts.MAX_JWT_EXPIRY + ), expiration + now = int(time.time()) payload = { "iat": now + self.jwt_issued_at, - "exp": now + self.jwt_expiry, + "exp": now + (expiration if expiration is not None else self.jwt_expiry), "iss": self.integration_id, } encrypted = jwt.encode(payload, key=self.private_key, algorithm="RS256") diff --git a/github/GithubIntegration.pyi b/github/GithubIntegration.pyi index 52a5c019..f1f202c5 100644 --- a/github/GithubIntegration.pyi +++ b/github/GithubIntegration.pyi @@ -22,7 +22,7 @@ class GithubIntegration: ) -> None: ... def _get_installed_app(self, url: str) -> Installation: ... def _get_headers(self) -> Dict[str, str]: ... - def create_jwt(self, expiration: int = ...) -> str: ... + def create_jwt(self, expiration: Optional[int] = ...) -> str: ... def get_access_token( self, installation_id: int, permissions: Optional[Dict[str, str]] = ... ) -> InstallationAuthorization: ... diff --git a/tests/GithubIntegration.py b/tests/GithubIntegration.py index 37b14344..c93c9c01 100644 --- a/tests/GithubIntegration.py +++ b/tests/GithubIntegration.py @@ -61,6 +61,27 @@ class GithubIntegration(Framework.BasicTestCase): ) sys.modules["time"].time = self.origin_time + def testCreateJWTWithExpiration(self): + self.origin_time = sys.modules["time"].time + sys.modules["time"].time = lambda: 1550055331.7435968 + github_integration = github.GithubIntegration( + integration_id=APP_ID, + private_key=PRIVATE_KEY, + jwt_expiry=120, + jwt_issued_at=-30, + ) + token = github_integration.create_jwt(60) + payload = jwt.decode( + token, + key=PUBLIC_KEY, + algorithms=["RS256"], + options={"verify_exp": False}, + ) + self.assertDictEqual( + payload, {"iat": 1550055301, "exp": 1550055391, "iss": APP_ID} + ) + sys.modules["time"].time = self.origin_time + def testGetInstallations(self): github_integration = github.GithubIntegration( integration_id=APP_ID, private_key=PRIVATE_KEY