Skip to content

Commit

Permalink
Add expiration argument back to create_jwt
Browse files Browse the repository at this point in the history
  • Loading branch information
EnricoMi committed Feb 27, 2023
1 parent 5033f5f commit 4f3913f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
8 changes: 6 additions & 2 deletions github/GithubIntegration.py
Expand Up @@ -90,17 +90,21 @@ 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
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
18 changes: 18 additions & 0 deletions tests/GithubIntegration.py
Expand Up @@ -61,6 +61,24 @@ 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 4f3913f

Please sign in to comment.