2222import java .time .Instant ;
2323import java .util .Date ;
2424
25+
2526public class GithubAppCheck {
2627 private static final Logger log = LoggerFactory .getLogger (GithubAppCheck .class );
2728
@@ -30,6 +31,8 @@ public class GithubAppCheck {
3031 private String jwt ;
3132 private Instant jwtExpiry ;
3233 private GitHub gitHub ;
34+ private Integer jwtRefreshBuffer = 60 ;
35+ private Integer jwtExpiryTime = 600 ;
3336
3437 public GithubAppCheck (final Namespace ns ){
3538 this .appId = ns .get (Constants .SKIP_GITHUB_APP_ID );
@@ -62,9 +65,11 @@ public GithubAppCheck(final Namespace ns){
6265 * @param fullRepoName = The repository full name, i.e, of the format "owner/repoName". Eg: "Salesforce/dockerfile-image-update"
6366 * @return True if github app is installed, false otherwise.
6467 */
65- protected boolean isGithubAppEnabledOnRepository (String fullRepoName ){
68+ protected boolean isGithubAppEnabledOnRepository (String fullRepoName ) {
6669 refreshJwtIfNeeded (appId , privateKeyPath );
6770 try {
71+ // Return true if the app is found on the repository via JWT token and API call
72+ // Reference: https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app
6873 gitHub .getApp ().getInstallationByRepository (fullRepoName .split ("/" )[0 ], fullRepoName .split ("/" )[1 ]);
6974 return true ;
7075 } catch (HttpException exception ) {
@@ -85,9 +90,10 @@ protected boolean isGithubAppEnabledOnRepository(String fullRepoName){
8590 * @param appId = The id of the Github App to generate the JWT for
8691 * @param privateKeyPath = The path to the private key of the Github App to generate the JWT for
8792 */
88- private void refreshJwtIfNeeded (String appId , String privateKeyPath ){
89- if (jwt == null || jwtExpiry .isBefore (Instant .now ().minusSeconds (60 ))) { // Adding a buffer to ensure token validity
93+ private void refreshJwtIfNeeded (String appId , String privateKeyPath ) {
94+ if (jwt == null || jwtExpiry .isBefore (Instant .now ().minusSeconds (jwtRefreshBuffer ))) { // Adding a buffer to ensure token validity
9095 try {
96+ // Generate JWT token 60 seconds before the expiry to continue Github app check
9197 generateJWT (appId , privateKeyPath );
9298 } catch (IOException | GeneralSecurityException exception ) {
9399 log .warn ("Could not refresh the JWT due to exception: {}" , exception .getMessage ());
@@ -112,9 +118,9 @@ private void generateJWT(String appId, String privateKeyPath) throws IOException
112118 jwt = JWT .create ()
113119 .withIssuer (appId )
114120 .withIssuedAt (Date .from (now ))
115- .withExpiresAt (Date .from (now .plusSeconds (600 ))) // 10 minutes expiration
121+ .withExpiresAt (Date .from (now .plusSeconds (jwtExpiryTime ))) // 10 minutes expiration
116122 .sign (algorithm );
117- jwtExpiry = now .plusSeconds (600 );
123+ jwtExpiry = now .plusSeconds (jwtExpiryTime );
118124 }
119125
120126 /**
0 commit comments