Skip to content

Commit

Permalink
Add expiration argument back to GithubIntegration.create_jwt (#2439)
Browse files Browse the repository at this point in the history
* Add expiration argument back to create_jwt
  • Loading branch information
EnricoMi committed Mar 17, 2023
1 parent 554b2b2 commit 822fc05
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
10 changes: 8 additions & 2 deletions github/GithubIntegration.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,23 @@ def _get_installed_app(self, url):
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")
Expand Down
2 changes: 1 addition & 1 deletion github/GithubIntegration.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -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: ...
Expand Down
21 changes: 21 additions & 0 deletions tests/GithubIntegration.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,27 @@ def testCreateJWT(self):
)
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
Expand Down

0 comments on commit 822fc05

Please sign in to comment.