generated from leanix/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
9f2fadb
commit 70cd1ed
Showing
12 changed files
with
222 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 4 additions & 0 deletions
4
src/main/kotlin/net/leanix/githubagent/GithubAgentApplication.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 15 additions & 0 deletions
15
src/main/kotlin/net/leanix/githubagent/client/GithubClient.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package net.leanix.githubagent.client | ||
|
||
import org.springframework.cloud.openfeign.FeignClient | ||
import org.springframework.web.bind.annotation.GetMapping | ||
import org.springframework.web.bind.annotation.RequestHeader | ||
|
||
@FeignClient(name = "githubClient", url = "\${github-enterprise.baseUrl}") | ||
interface GithubClient { | ||
|
||
@GetMapping("/api/v3/app") | ||
fun getApp( | ||
@RequestHeader("Authorization") jwt: String, | ||
@RequestHeader("Accept") accept: String = "application/vnd.github.v3+json" | ||
): String | ||
} |
30 changes: 30 additions & 0 deletions
30
src/main/kotlin/net/leanix/githubagent/config/AgentSetupValidation.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package net.leanix.githubagent.config | ||
|
||
import jakarta.annotation.PostConstruct | ||
import net.leanix.githubagent.exceptions.GithubEnterpriseConfigurationMissingException | ||
import org.springframework.stereotype.Component | ||
|
||
@Component | ||
class AgentSetupValidation( | ||
private val githubEnterpriseProperties: GithubEnterpriseProperties | ||
) { | ||
|
||
@PostConstruct | ||
fun validateConfiguration() { | ||
val missingProperties = mutableListOf<String>() | ||
|
||
if (githubEnterpriseProperties.baseUrl.isBlank()) { | ||
missingProperties.add("GITHUB_ENTERPRISE_BASE_URL") | ||
} | ||
if (githubEnterpriseProperties.githubAppId.isBlank()) { | ||
missingProperties.add("GITHUB_ENTERPRISE_GITHUB_APP_ID") | ||
} | ||
if (githubEnterpriseProperties.pemFile.isBlank()) { | ||
missingProperties.add("GITHUB_ENTERPRISE_PEM_FILE") | ||
} | ||
|
||
if (missingProperties.isNotEmpty()) { | ||
throw GithubEnterpriseConfigurationMissingException(missingProperties.joinToString(", ")) | ||
} | ||
} | ||
} |
10 changes: 10 additions & 0 deletions
10
src/main/kotlin/net/leanix/githubagent/config/GithubEnterpriseProperties.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package net.leanix.githubagent.config | ||
|
||
import org.springframework.boot.context.properties.ConfigurationProperties | ||
|
||
@ConfigurationProperties(prefix = "github-enterprise") | ||
data class GithubEnterpriseProperties( | ||
val baseUrl: String, | ||
val githubAppId: String, | ||
val pemFile: String, | ||
) |
9 changes: 9 additions & 0 deletions
9
src/main/kotlin/net/leanix/githubagent/dto/GithubAppResponse.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package net.leanix.githubagent.dto | ||
|
||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties | ||
import com.fasterxml.jackson.annotation.JsonProperty | ||
|
||
@JsonIgnoreProperties(ignoreUnknown = true) | ||
data class GithubAppResponse( | ||
@JsonProperty("name") val name: String | ||
) |
7 changes: 7 additions & 0 deletions
7
src/main/kotlin/net/leanix/githubagent/exceptions/Exceptions.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
package net.leanix.githubagent.exceptions | ||
|
||
class GithubEnterpriseConfigurationMissingException(properties: String) : RuntimeException( | ||
"Github Enterprise properties '$properties' are not set" | ||
) | ||
class AuthenticationFailedException(message: String) : RuntimeException(message) | ||
class ConnectingToGithubEnterpriseFailedException(message: String) : RuntimeException(message) |
14 changes: 14 additions & 0 deletions
14
src/main/kotlin/net/leanix/githubagent/runners/PostStartupRunner.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
package net.leanix.githubagent.runners | ||
|
||
import net.leanix.githubagent.services.GithubAuthenticationService | ||
import org.springframework.boot.ApplicationArguments | ||
import org.springframework.boot.ApplicationRunner | ||
import org.springframework.stereotype.Component | ||
|
||
@Component | ||
class PostStartupRunner(private val githubAuthenticationService: GithubAuthenticationService) : ApplicationRunner { | ||
|
||
override fun run(args: ApplicationArguments?) { | ||
githubAuthenticationService.generateJwtToken() | ||
} | ||
} |
26 changes: 26 additions & 0 deletions
26
src/main/kotlin/net/leanix/githubagent/services/CachingService.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
package net.leanix.githubagent.services | ||
|
||
import jakarta.annotation.PostConstruct | ||
import net.leanix.githubagent.config.GithubEnterpriseProperties | ||
import org.springframework.stereotype.Service | ||
|
||
@Service | ||
class CachingService( | ||
private val githubEnterpriseProperties: GithubEnterpriseProperties | ||
) { | ||
private val cache = HashMap<String, String?>() | ||
|
||
@PostConstruct | ||
private fun init() { | ||
cache["baseUrl"] = githubEnterpriseProperties.baseUrl | ||
cache["githubAppId"] = githubEnterpriseProperties.githubAppId | ||
} | ||
|
||
fun set(key: String, value: String) { | ||
cache[key] = value | ||
} | ||
|
||
fun get(key: String): String? { | ||
return cache[key] | ||
} | ||
} |
83 changes: 83 additions & 0 deletions
83
src/main/kotlin/net/leanix/githubagent/services/GithubAuthenticationService.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
package net.leanix.githubagent.services | ||
|
||
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper | ||
import io.jsonwebtoken.Jwts | ||
import io.jsonwebtoken.SignatureAlgorithm | ||
import net.leanix.githubagent.client.GithubClient | ||
import net.leanix.githubagent.config.GithubEnterpriseProperties | ||
import net.leanix.githubagent.dto.GithubAppResponse | ||
import net.leanix.githubagent.exceptions.AuthenticationFailedException | ||
import net.leanix.githubagent.exceptions.ConnectingToGithubEnterpriseFailedException | ||
import org.bouncycastle.jce.provider.BouncyCastleProvider | ||
import org.slf4j.LoggerFactory | ||
import org.springframework.core.io.ResourceLoader | ||
import org.springframework.stereotype.Service | ||
import java.io.File | ||
import java.io.IOException | ||
import java.nio.charset.Charset | ||
import java.nio.file.Files | ||
import java.security.KeyFactory | ||
import java.security.PrivateKey | ||
import java.security.Security | ||
import java.security.spec.PKCS8EncodedKeySpec | ||
import java.util.* | ||
|
||
@Service | ||
class GithubAuthenticationService( | ||
private val cachingService: CachingService, | ||
private val githubClient: GithubClient, | ||
private val githubEnterpriseProperties: GithubEnterpriseProperties, | ||
private val resourceLoader: ResourceLoader | ||
) { | ||
|
||
companion object { | ||
private const val JWT_EXPIRATION_DURATION = 600000L | ||
private val logger = LoggerFactory.getLogger(GithubAuthenticationService::class.java) | ||
} | ||
|
||
fun generateJwtToken() { | ||
runCatching { | ||
logger.info("Generating JWT token") | ||
Security.addProvider(BouncyCastleProvider()) | ||
val rsaPrivateKey: String = readPrivateKey(loadPemFile()) | ||
val keySpec = PKCS8EncodedKeySpec(Base64.getDecoder().decode(rsaPrivateKey)) | ||
val privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec) | ||
createJwtToken(privateKey)?.also { | ||
cachingService.set("jwtToken", it) | ||
verifyJwt(it) | ||
} ?: throw AuthenticationFailedException("Failed to generate a valid JWT token") | ||
} | ||
} | ||
|
||
private fun createJwtToken(privateKey: PrivateKey): String? { | ||
return Jwts.builder() | ||
.setIssuedAt(Date()) | ||
.setExpiration(Date(System.currentTimeMillis() + JWT_EXPIRATION_DURATION)) | ||
.setIssuer(cachingService.get("githubAppId")) | ||
.signWith(privateKey, SignatureAlgorithm.RS256) | ||
.compact() | ||
} | ||
|
||
@Throws(IOException::class) | ||
private fun readPrivateKey(file: File): String { | ||
return String(Files.readAllBytes(file.toPath()), Charset.defaultCharset()) | ||
.replace("-----BEGIN RSA PRIVATE KEY-----", "") | ||
.replace(System.lineSeparator().toRegex(), "") | ||
.replace("-----END RSA PRIVATE KEY-----", "") | ||
} | ||
|
||
private fun verifyJwt(jwt: String) { | ||
runCatching { | ||
val githubApp = jacksonObjectMapper().readValue( | ||
githubClient.getApp("Bearer $jwt"), | ||
GithubAppResponse::class.java | ||
) | ||
logger.info("Authenticated as GitHub App: ${githubApp.name}") | ||
}.onFailure { | ||
throw ConnectingToGithubEnterpriseFailedException("Failed to verify JWT token") | ||
} | ||
} | ||
|
||
private fun loadPemFile() = | ||
File(resourceLoader.getResource("file:${githubEnterpriseProperties.pemFile}").uri) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
github-enterprise: | ||
baseUrl: ${GITHUB_ENTERPRISE_BASE_URL:} | ||
githubAppId: ${GITHUB_APP_ID:} | ||
pemFile: ${PEM_FILE:} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
github-enterprise: | ||
baseUrl: ${GITHUB_ENTERPRISE_BASE_URL:dummy} | ||
githubAppId: ${GITHUB_APP_ID:dummy} | ||
pemFile: ${PEM_FILE:dummy} |