diff --git a/build.gradle.kts b/build.gradle.kts index 81b221a..08b108f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,12 +1,12 @@ import com.expediagroup.graphql.plugin.gradle.tasks.GraphQLGenerateClientTask plugins { - id("org.springframework.boot") version "3.5.7" + id("org.springframework.boot") version "4.0.5" id("io.spring.dependency-management") version "1.1.7" - id("com.expediagroup.graphql") version "8.8.1" - id("io.gitlab.arturbosch.detekt") version "1.23.8" - kotlin("jvm") version "2.0.21" - kotlin("plugin.spring") version "2.0.21" + id("com.expediagroup.graphql") version "10.0.0-alpha.2" + id("dev.detekt") version "2.0.0-alpha.2" + kotlin("jvm") version "2.3.0" + kotlin("plugin.spring") version "2.3.0" jacoco } @@ -23,7 +23,7 @@ repositories { mavenCentral() } -extra["springCloudVersion"] = "2025.0.0" +extra["springCloudVersion"] = "2025.1.1" dependencyManagement { imports { @@ -33,16 +33,16 @@ dependencyManagement { dependencies { implementation("org.springframework.boot:spring-boot-starter") - implementation("org.springframework.boot:spring-boot-starter-aop") + implementation("org.springframework.boot:spring-boot-starter-aspectj") implementation("org.springframework.boot:spring-boot-starter-actuator") implementation("org.springframework.boot:spring-boot-starter-cache") implementation("com.github.ben-manes.caffeine:caffeine:2.9.3") - implementation("org.springframework.cloud:spring-cloud-starter-openfeign:4.3.0") + implementation("org.springframework.cloud:spring-cloud-starter-openfeign:5.0.1") implementation("org.springframework.boot:spring-boot-starter-websocket") - implementation("io.github.resilience4j:resilience4j-spring-boot3") + implementation("io.github.resilience4j:resilience4j-spring-boot4:2.4.0") implementation("org.jetbrains.kotlin:kotlin-reflect") - implementation("com.fasterxml.jackson.core:jackson-annotations:2.20") - implementation("com.expediagroup:graphql-kotlin-spring-client:8.8.1") + implementation("tools.jackson.module:jackson-module-kotlin") + implementation("com.expediagroup:graphql-kotlin-spring-client:10.0.0-alpha.2") developmentOnly("io.netty:netty-resolver-dns-native-macos:4.2.7.Final") { artifact { classifier = "osx-aarch_64" @@ -54,6 +54,7 @@ dependencies { implementation("io.jsonwebtoken:jjwt-jackson:0.13.0") testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.springframework.boot:spring-boot-webmvc-test") testImplementation("com.ninja-squad:springmockk:4.0.2"){ exclude(module = "mockito-core") } @@ -83,7 +84,7 @@ detekt { parallel = true buildUponDefaultConfig = true dependencies { - detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.8") + detektPlugins("dev.detekt:detekt-rules-ktlint-wrapper:2.0.0-alpha.2") } } diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index e33e155..f3e0aec 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -26,7 +26,11 @@ style: active: true ReturnCount: active: false - UnusedPrivateMember: + UnusedPrivateClass: + active: true + UnusedPrivateFunction: + active: true + UnusedPrivateProperty: active: true ThrowsCount: active: false diff --git a/src/main/kotlin/net/leanix/githubagent/GitHubAgentApplication.kt b/src/main/kotlin/net/leanix/githubagent/GitHubAgentApplication.kt index ec4bfbf..7c69621 100644 --- a/src/main/kotlin/net/leanix/githubagent/GitHubAgentApplication.kt +++ b/src/main/kotlin/net/leanix/githubagent/GitHubAgentApplication.kt @@ -18,13 +18,10 @@ import org.springframework.scheduling.annotation.EnableScheduling @EnableConfigurationProperties( value = [ net.leanix.githubagent.config.GitHubEnterpriseProperties::class, - net.leanix.githubagent.config.LeanIXProperties::class - ] + net.leanix.githubagent.config.LeanIXProperties::class, + ], ) -class GitHubAgentApplication( - private val syncLogService: SyncLogService, - private val cachingService: CachingService -) { +class GitHubAgentApplication(private val syncLogService: SyncLogService, private val cachingService: CachingService) { private val logger = LoggerFactory.getLogger(GitHubAgentApplication::class.java) @@ -43,7 +40,7 @@ class GitHubAgentApplication( syncLogService.sendSyncLog( message = message, logLevel = LogLevel.INFO, - synchronizationProgress = synchronizationProgress + synchronizationProgress = synchronizationProgress, ) logger.info(message) } diff --git a/src/main/kotlin/net/leanix/githubagent/client/GitHubClient.kt b/src/main/kotlin/net/leanix/githubagent/client/GitHubClient.kt index ece194f..3bf71b9 100644 --- a/src/main/kotlin/net/leanix/githubagent/client/GitHubClient.kt +++ b/src/main/kotlin/net/leanix/githubagent/client/GitHubClient.kt @@ -21,14 +21,14 @@ import org.springframework.web.bind.annotation.RequestParam @FeignClient( name = "githubClient", url = "\${github-enterprise.baseUrl}", - configuration = [FeignClientConfig::class] + configuration = [FeignClientConfig::class], ) interface GitHubClient { @GetMapping("/api/v3/app") fun getApp( @RequestHeader("Authorization") jwt: String, - @RequestHeader("Accept") accept: String = "application/vnd.github.v3+json" + @RequestHeader("Accept") accept: String = "application/vnd.github.v3+json", ): GitHubAppResponse @Retry(name = "secondary_rate_limit") @@ -36,14 +36,14 @@ interface GitHubClient { fun getInstallations( @RequestHeader("Authorization") jwt: String, @RequestParam("per_page", defaultValue = "30") perPage: Int, - @RequestParam("page", defaultValue = "1") page: Int + @RequestParam("page", defaultValue = "1") page: Int, ): List @Retry(name = "secondary_rate_limit") @GetMapping("/api/v3/app/installations/{installationId}") fun getInstallation( @PathVariable("installationId") installationId: Long, - @RequestHeader("Authorization") jwt: String + @RequestHeader("Authorization") jwt: String, ): Installation @Retry(name = "secondary_rate_limit") @@ -51,7 +51,7 @@ interface GitHubClient { fun createInstallationToken( @PathVariable("installationId") installationId: Long, @RequestHeader("Authorization") jwt: String, - @RequestBody emptyBody: String = "" + @RequestBody emptyBody: String = "", ): InstallationTokenResponse @Retry(name = "secondary_rate_limit") @@ -59,14 +59,14 @@ interface GitHubClient { fun getOrganizations( @RequestHeader("Authorization") jwt: String, @RequestParam("per_page", defaultValue = "30") perPage: Int, - @RequestParam("since", defaultValue = "1") since: Int + @RequestParam("since", defaultValue = "1") since: Int, ): List @Retry(name = "secondary_rate_limit") @GetMapping("/api/v3/orgs/{org}/repos") fun getRepositories( @PathVariable("org") org: String, - @RequestHeader("Authorization") token: String + @RequestHeader("Authorization") token: String, ): List @Retry(name = "secondary_rate_limit") @@ -82,7 +82,7 @@ interface GitHubClient { @PathVariable("owner") owner: String, @PathVariable("repo") repo: String, @PathVariable("runId") runId: Long, - @RequestHeader("Authorization") token: String + @RequestHeader("Authorization") token: String, ): ArtifactsListResponse @Retry(name = "secondary_rate_limit") @@ -91,6 +91,6 @@ interface GitHubClient { @PathVariable("owner") owner: String, @PathVariable("repo") repo: String, @PathVariable("artifactId") artifactId: Long, - @RequestHeader("Authorization") token: String + @RequestHeader("Authorization") token: String, ): Response } diff --git a/src/main/kotlin/net/leanix/githubagent/client/LeanIXAuthClient.kt b/src/main/kotlin/net/leanix/githubagent/client/LeanIXAuthClient.kt index ed7663a..fb0a14a 100644 --- a/src/main/kotlin/net/leanix/githubagent/client/LeanIXAuthClient.kt +++ b/src/main/kotlin/net/leanix/githubagent/client/LeanIXAuthClient.kt @@ -15,8 +15,5 @@ import org.springframework.web.bind.annotation.RequestHeader fun interface LeanIXAuthClient { @PostMapping(value = ["/oauth2/token"], consumes = [APPLICATION_FORM_URLENCODED_VALUE]) - fun getToken( - @RequestHeader(name = AUTHORIZATION) authorization: String, - @RequestBody body: String, - ): JwtDto + fun getToken(@RequestHeader(name = AUTHORIZATION) authorization: String, @RequestBody body: String): JwtDto } diff --git a/src/main/kotlin/net/leanix/githubagent/config/AgentSetupValidation.kt b/src/main/kotlin/net/leanix/githubagent/config/AgentSetupValidation.kt index d0624bf..8c72462 100644 --- a/src/main/kotlin/net/leanix/githubagent/config/AgentSetupValidation.kt +++ b/src/main/kotlin/net/leanix/githubagent/config/AgentSetupValidation.kt @@ -8,7 +8,7 @@ import org.springframework.stereotype.Component @Component class AgentSetupValidation( private val gitHubEnterpriseProperties: GitHubEnterpriseProperties, - private val leanIXProperties: LeanIXProperties + private val leanIXProperties: LeanIXProperties, ) { @EventListener diff --git a/src/main/kotlin/net/leanix/githubagent/config/FeignClientConfig.kt b/src/main/kotlin/net/leanix/githubagent/config/FeignClientConfig.kt index 67ee070..c279868 100644 --- a/src/main/kotlin/net/leanix/githubagent/config/FeignClientConfig.kt +++ b/src/main/kotlin/net/leanix/githubagent/config/FeignClientConfig.kt @@ -9,7 +9,5 @@ import org.springframework.context.annotation.Configuration class FeignClientConfig { @Bean - fun rateLimitResponseInterceptor(): ResponseInterceptor { - return RateLimitResponseInterceptor() - } + fun rateLimitResponseInterceptor(): ResponseInterceptor = RateLimitResponseInterceptor() } diff --git a/src/main/kotlin/net/leanix/githubagent/config/GitHubEnterpriseProperties.kt b/src/main/kotlin/net/leanix/githubagent/config/GitHubEnterpriseProperties.kt index c1f5762..34a62b6 100644 --- a/src/main/kotlin/net/leanix/githubagent/config/GitHubEnterpriseProperties.kt +++ b/src/main/kotlin/net/leanix/githubagent/config/GitHubEnterpriseProperties.kt @@ -7,5 +7,5 @@ data class GitHubEnterpriseProperties( val baseUrl: String, val gitHubAppId: String, val pemFile: String, - val webhookSecret: String + val webhookSecret: String, ) diff --git a/src/main/kotlin/net/leanix/githubagent/config/LeanIXProperties.kt b/src/main/kotlin/net/leanix/githubagent/config/LeanIXProperties.kt index e9d5985..6f48fd0 100644 --- a/src/main/kotlin/net/leanix/githubagent/config/LeanIXProperties.kt +++ b/src/main/kotlin/net/leanix/githubagent/config/LeanIXProperties.kt @@ -3,12 +3,6 @@ package net.leanix.githubagent.config import org.springframework.boot.context.properties.ConfigurationProperties @ConfigurationProperties(prefix = "leanix") -data class LeanIXProperties( - val wsBaseUrl: String, - val auth: Auth -) { - data class Auth( - val accessTokenUri: String, - val technicalUserToken: String - ) +data class LeanIXProperties(val wsBaseUrl: String, val auth: Auth) { + data class Auth(val accessTokenUri: String, val technicalUserToken: String) } diff --git a/src/main/kotlin/net/leanix/githubagent/config/Resilience4jConfig.kt b/src/main/kotlin/net/leanix/githubagent/config/Resilience4jConfig.kt index 9ec7c35..132530b 100644 --- a/src/main/kotlin/net/leanix/githubagent/config/Resilience4jConfig.kt +++ b/src/main/kotlin/net/leanix/githubagent/config/Resilience4jConfig.kt @@ -37,17 +37,17 @@ class Resilience4jConfig { Locale.getDefault(), "%d minutes, %d seconds", event.waitInterval.toMinutes(), - event.waitInterval.minus(event.waitInterval.toMinutes(), ChronoUnit.MINUTES).seconds + event.waitInterval.minus(event.waitInterval.toMinutes(), ChronoUnit.MINUTES).seconds, ) logger.info( "Retrying call due to ${event.name}, attempt: ${event.numberOfRetryAttempts}, " + - "wait time: $readableWaitTime" + "wait time: $readableWaitTime", ) } .onError { event -> logger.error( "Call failed due to ${event.name}, after attempts: ${event.numberOfRetryAttempts}, " + - "last exception: ${event.lastThrowable.message}" + "last exception: ${event.lastThrowable.message}", ) } diff --git a/src/main/kotlin/net/leanix/githubagent/config/WebSocketClientConfig.kt b/src/main/kotlin/net/leanix/githubagent/config/WebSocketClientConfig.kt index 2af6a9d..6b1c2f3 100644 --- a/src/main/kotlin/net/leanix/githubagent/config/WebSocketClientConfig.kt +++ b/src/main/kotlin/net/leanix/githubagent/config/WebSocketClientConfig.kt @@ -1,10 +1,9 @@ package net.leanix.githubagent.config -import com.fasterxml.jackson.databind.ObjectMapper import io.github.resilience4j.retry.annotation.Retry import net.leanix.githubagent.handler.BrokerStompSessionHandler import net.leanix.githubagent.services.LeanIXAuthService -import net.leanix.githubagent.shared.GitHubAgentProperties.GITHUB_AGENT_VERSION +import net.leanix.githubagent.shared.GitHubAgentProperties.githubAgentVersion import org.slf4j.LoggerFactory import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @@ -21,10 +20,9 @@ import org.springframework.web.socket.sockjs.client.WebSocketTransport @Configuration class WebSocketClientConfig( private val brokerStompSessionHandler: BrokerStompSessionHandler, - private val objectMapper: ObjectMapper, private val leanIXAuthService: LeanIXAuthService, private val leanIXProperties: LeanIXProperties, - private val gitHubEnterpriseProperties: GitHubEnterpriseProperties + private val gitHubEnterpriseProperties: GitHubEnterpriseProperties, ) { private val logger = LoggerFactory.getLogger(WebSocketClientConfig::class.java) @@ -40,7 +38,7 @@ class WebSocketClientConfig( throw it } stompHeaders["GitHub-Enterprise-URL"] = gitHubEnterpriseProperties.baseUrl - stompHeaders["GitHub-Agent-Version"] = GITHUB_AGENT_VERSION + stompHeaders["GitHub-Agent-Version"] = githubAgentVersion return stompClient().connectAsync( leanIXProperties.wsBaseUrl, headers, @@ -52,7 +50,6 @@ class WebSocketClientConfig( @Bean fun stompClient(): WebSocketStompClient { val jsonConverter = MappingJackson2MessageConverter() - jsonConverter.objectMapper = objectMapper val simpleWebSocketClient = StandardWebSocketClient() val transports = listOf(WebSocketTransport(simpleWebSocketClient)) diff --git a/src/main/kotlin/net/leanix/githubagent/controllers/GitHubWebhookController.kt b/src/main/kotlin/net/leanix/githubagent/controllers/GitHubWebhookController.kt index 18915e3..35c4ee5 100644 --- a/src/main/kotlin/net/leanix/githubagent/controllers/GitHubWebhookController.kt +++ b/src/main/kotlin/net/leanix/githubagent/controllers/GitHubWebhookController.kt @@ -19,7 +19,7 @@ class GitHubWebhookController(private val gitHubWebhookService: GitHubWebhookSer @RequestHeader("X-Github-Event") eventType: String, @RequestHeader("X-GitHub-Enterprise-Host") host: String, @RequestHeader("X-Hub-Signature-256", required = false) signature256: String?, - @RequestBody payload: String + @RequestBody payload: String, ) { gitHubWebhookService.handleWebhookEvent(eventType, host, signature256, payload) } diff --git a/src/main/kotlin/net/leanix/githubagent/controllers/advice/GlobalExceptionHandler.kt b/src/main/kotlin/net/leanix/githubagent/controllers/advice/GlobalExceptionHandler.kt index c207b10..d836e4d 100644 --- a/src/main/kotlin/net/leanix/githubagent/controllers/advice/GlobalExceptionHandler.kt +++ b/src/main/kotlin/net/leanix/githubagent/controllers/advice/GlobalExceptionHandler.kt @@ -11,9 +11,7 @@ import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @ControllerAdvice -class GlobalExceptionHandler( - private val syncLogService: SyncLogService -) { +class GlobalExceptionHandler(private val syncLogService: SyncLogService) { val exceptionLogger: Logger = LoggerFactory.getLogger(GlobalExceptionHandler::class.java) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/ArtifactDTO.kt b/src/main/kotlin/net/leanix/githubagent/dto/ArtifactDTO.kt index 51fd13e..beff459 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/ArtifactDTO.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/ArtifactDTO.kt @@ -1,7 +1,3 @@ package net.leanix.githubagent.dto -data class ArtifactDTO( - val repositoryFullName: String, - val artifactFileName: String, - val artifactFileContent: String, -) +data class ArtifactDTO(val repositoryFullName: String, val artifactFileName: String, val artifactFileContent: String) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/ArtifactsDto.kt b/src/main/kotlin/net/leanix/githubagent/dto/ArtifactsDto.kt index 98092d1..9af0724 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/ArtifactsDto.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/ArtifactsDto.kt @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonProperty data class ArtifactsListResponse( @JsonProperty("total_count") val totalCount: Int, - val artifacts: List + val artifacts: List, ) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/GenericWebhookEvent.kt b/src/main/kotlin/net/leanix/githubagent/dto/GenericWebhookEvent.kt index 09fb789..e3a351c 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/GenericWebhookEvent.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/GenericWebhookEvent.kt @@ -3,6 +3,4 @@ package net.leanix.githubagent.dto import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) -class GenericWebhookEvent( - val action: String? = null -) +class GenericWebhookEvent(val action: String? = null) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/GitHubAppResponse.kt b/src/main/kotlin/net/leanix/githubagent/dto/GitHubAppResponse.kt index ecb8426..b392463 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/GitHubAppResponse.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/GitHubAppResponse.kt @@ -7,5 +7,5 @@ import com.fasterxml.jackson.annotation.JsonProperty data class GitHubAppResponse( @JsonProperty("slug") val slug: String, @JsonProperty("permissions") val permissions: Map, - @JsonProperty("events") val events: List + @JsonProperty("events") val events: List, ) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/GitHubResponsesDto.kt b/src/main/kotlin/net/leanix/githubagent/dto/GitHubResponsesDto.kt index 2dabda5..298e807 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/GitHubResponsesDto.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/GitHubResponsesDto.kt @@ -8,7 +8,7 @@ data class InstallationTokenResponse( @JsonProperty("token") val token: String, @JsonProperty("expires_at") val expiresAt: String, @JsonProperty("permissions") val permissions: Map, - @JsonProperty("repository_selection") val repositorySelection: String + @JsonProperty("repository_selection") val repositorySelection: String, ) @JsonIgnoreProperties(ignoreUnknown = true) @@ -16,19 +16,14 @@ data class Installation( @JsonProperty("id") val id: Long, @JsonProperty("account") val account: Account, @JsonProperty("permissions") val permissions: Map, - @JsonProperty("events") val events: List + @JsonProperty("events") val events: List, ) @JsonIgnoreProperties(ignoreUnknown = true) -data class Account( - @JsonProperty("login") val login: String -) +data class Account(@JsonProperty("login") val login: String) @JsonIgnoreProperties(ignoreUnknown = true) -data class Organization( - @JsonProperty("login") val login: String, - @JsonProperty("id") val id: Int, -) +data class Organization(@JsonProperty("login") val login: String, @JsonProperty("id") val id: Int) @JsonIgnoreProperties(ignoreUnknown = true) data class Repository( @@ -36,5 +31,5 @@ data class Repository( @JsonProperty("name") val name: String, @JsonProperty("full_name") val fullName: Boolean, @JsonProperty("owner") val owner: Organization, - @JsonProperty("topics") val topics: List + @JsonProperty("topics") val topics: List, ) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/GitHubSearchResponse.kt b/src/main/kotlin/net/leanix/githubagent/dto/GitHubSearchResponse.kt index 585541f..35390c8 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/GitHubSearchResponse.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/GitHubSearchResponse.kt @@ -7,16 +7,11 @@ import com.fasterxml.jackson.annotation.JsonProperty data class GitHubSearchResponse( @JsonProperty("total_count") val totalCount: Int, - val items: List + val items: List, ) @JsonIgnoreProperties(ignoreUnknown = true) -data class ItemResponse( - val name: String, - val path: String, - val repository: RepositoryItemResponse, - val url: String, -) +data class ItemResponse(val name: String, val path: String, val repository: RepositoryItemResponse, val url: String) @JsonIgnoreProperties(ignoreUnknown = true) data class RepositoryItemResponse( diff --git a/src/main/kotlin/net/leanix/githubagent/dto/InstallationRequestDTO.kt b/src/main/kotlin/net/leanix/githubagent/dto/InstallationRequestDTO.kt index 67af01b..1f7a2e0 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/InstallationRequestDTO.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/InstallationRequestDTO.kt @@ -1,6 +1,3 @@ package net.leanix.githubagent.dto -data class InstallationRequestDTO( - val id: Long, - val account: Account, -) +data class InstallationRequestDTO(val id: Long, val account: Account) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/JwtDto.kt b/src/main/kotlin/net/leanix/githubagent/dto/JwtDto.kt index 7c7e2a6..4d97cb7 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/JwtDto.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/JwtDto.kt @@ -9,6 +9,6 @@ data class JwtDto( val accessToken: String, @JsonProperty("token_type") val tokenType: String, - @JsonProperty("expired_in") + @JsonProperty("expires_in") val expiredIn: Int, ) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/ManifestFileUpdateDto.kt b/src/main/kotlin/net/leanix/githubagent/dto/ManifestFileUpdateDto.kt index db0374f..abdcd84 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/ManifestFileUpdateDto.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/ManifestFileUpdateDto.kt @@ -4,11 +4,11 @@ data class ManifestFileUpdateDto( val repositoryFullName: String, val action: ManifestFileAction, val manifestFileContent: String?, - val manifestFilePath: String? + val manifestFilePath: String?, ) enum class ManifestFileAction { ADDED, MODIFIED, - REMOVED + REMOVED, } diff --git a/src/main/kotlin/net/leanix/githubagent/dto/ManifestFilesDTO.kt b/src/main/kotlin/net/leanix/githubagent/dto/ManifestFilesDTO.kt index f052c8d..4bf5677 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/ManifestFilesDTO.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/ManifestFilesDTO.kt @@ -3,10 +3,7 @@ package net.leanix.githubagent.dto data class ManifestFilesDTO( val repositoryId: String, val repositoryFullName: String, - val manifestFiles: List + val manifestFiles: List, ) -data class ManifestFileDTO( - val path: String, - val content: String, -) +data class ManifestFileDTO(val path: String, val content: String) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/OrganizationDto.kt b/src/main/kotlin/net/leanix/githubagent/dto/OrganizationDto.kt index 4702a06..febed45 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/OrganizationDto.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/OrganizationDto.kt @@ -1,7 +1,3 @@ package net.leanix.githubagent.dto -class OrganizationDto( - val id: Int, - val name: String, - val installed: Boolean -) +class OrganizationDto(val id: Int, val name: String, val installed: Boolean) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/PagedRepositories.kt b/src/main/kotlin/net/leanix/githubagent/dto/PagedRepositories.kt index 002b5ad..fdbcc68 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/PagedRepositories.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/PagedRepositories.kt @@ -3,5 +3,5 @@ package net.leanix.githubagent.dto data class PagedRepositories( val repositories: List, val hasNextPage: Boolean, - val cursor: String? = null + val cursor: String? = null, ) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/PushEventPayload.kt b/src/main/kotlin/net/leanix/githubagent/dto/PushEventPayload.kt index 0d51731..a3262cb 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/PushEventPayload.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/PushEventPayload.kt @@ -9,7 +9,7 @@ data class PushEventPayload( val repository: PushEventRepository, val installation: PushEventInstallation, @JsonProperty("head_commit") - val headCommit: PushEventCommit? + val headCommit: PushEventCommit?, ) @JsonIgnoreProperties(ignoreUnknown = true) @@ -20,22 +20,14 @@ data class PushEventRepository( val fullName: String, @JsonProperty("default_branch") val defaultBranch: String, - val owner: PushEventOwner + val owner: PushEventOwner, ) @JsonIgnoreProperties(ignoreUnknown = true) -data class PushEventInstallation( - val id: Int -) +data class PushEventInstallation(val id: Int) @JsonIgnoreProperties(ignoreUnknown = true) -data class PushEventCommit( - val added: List, - val removed: List, - val modified: List -) +data class PushEventCommit(val added: List, val removed: List, val modified: List) @JsonIgnoreProperties(ignoreUnknown = true) -data class PushEventOwner( - val name: String -) +data class PushEventOwner(val name: String) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/RateLimitType.kt b/src/main/kotlin/net/leanix/githubagent/dto/RateLimitType.kt index 2a9662c..9993cc4 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/RateLimitType.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/RateLimitType.kt @@ -3,5 +3,5 @@ package net.leanix.githubagent.dto enum class RateLimitType { GRAPHQL, REST, - SEARCH + SEARCH, } diff --git a/src/main/kotlin/net/leanix/githubagent/dto/RepositoryRequestDTO.kt b/src/main/kotlin/net/leanix/githubagent/dto/RepositoryRequestDTO.kt index b7ebf62..3487688 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/RepositoryRequestDTO.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/RepositoryRequestDTO.kt @@ -6,7 +6,4 @@ data class RepositoryRequestDTO( val repositoryFullName: String, ) -data class RepositoryRequestInstallationDTO( - val id: Long, - val account: Account -) +data class RepositoryRequestInstallationDTO(val id: Long, val account: Account) diff --git a/src/main/kotlin/net/leanix/githubagent/dto/SyncLogDto.kt b/src/main/kotlin/net/leanix/githubagent/dto/SyncLogDto.kt index dde1641..7a6a5e6 100644 --- a/src/main/kotlin/net/leanix/githubagent/dto/SyncLogDto.kt +++ b/src/main/kotlin/net/leanix/githubagent/dto/SyncLogDto.kt @@ -7,19 +7,19 @@ data class SyncLogDto( val trigger: Trigger, val logLevel: LogLevel, val synchronizationProgress: SynchronizationProgress, - val message: String + val message: String, ) enum class Trigger { FULL_SCAN, - WEB_HOOK + WEB_HOOK, } enum class LogLevel { OK, WARNING, INFO, - ERROR + ERROR, } enum class SynchronizationProgress { @@ -27,5 +27,5 @@ enum class SynchronizationProgress { RUNNING, ABORTION_PENDING, ABORTED, - FINISHED + FINISHED, } diff --git a/src/main/kotlin/net/leanix/githubagent/exceptions/Exceptions.kt b/src/main/kotlin/net/leanix/githubagent/exceptions/Exceptions.kt index 6b3bf4b..031af74 100644 --- a/src/main/kotlin/net/leanix/githubagent/exceptions/Exceptions.kt +++ b/src/main/kotlin/net/leanix/githubagent/exceptions/Exceptions.kt @@ -2,9 +2,10 @@ package net.leanix.githubagent.exceptions import com.expediagroup.graphql.client.types.GraphQLClientError -class GitHubEnterpriseConfigurationMissingException(properties: String) : RuntimeException( - "Github Enterprise properties '$properties' are not set" -) +class GitHubEnterpriseConfigurationMissingException(properties: String) : + RuntimeException( + "Github Enterprise properties '$properties' are not set", + ) class GitHubAppInsufficientPermissionsException(message: String) : RuntimeException(message) class FailedToCreateJWTException(message: String) : RuntimeException(message) class UnableToConnectToGitHubEnterpriseException(message: String) : RuntimeException(message) @@ -17,5 +18,5 @@ class ManifestFileNotFoundException : RuntimeException("Manifest File Not Found" class UnableToSendMessageException(exception: Exception) : RuntimeException( "Unable to send message to the backend", - exception + exception, ) diff --git a/src/main/kotlin/net/leanix/githubagent/handler/ArtifactDownloadHandler.kt b/src/main/kotlin/net/leanix/githubagent/handler/ArtifactDownloadHandler.kt index 55af70b..197844e 100644 --- a/src/main/kotlin/net/leanix/githubagent/handler/ArtifactDownloadHandler.kt +++ b/src/main/kotlin/net/leanix/githubagent/handler/ArtifactDownloadHandler.kt @@ -22,14 +22,12 @@ class ArtifactDownloadHandler( @Lazy @Autowired private val webSocketService: WebSocketService, @Lazy @Autowired - private val gitHubAuthenticationService: GitHubAuthenticationService + private val gitHubAuthenticationService: GitHubAuthenticationService, ) : StompFrameHandler { private val logger = LoggerFactory.getLogger(ArtifactDownloadHandler::class.java) - override fun getPayloadType(headers: StompHeaders): Type { - return ArtifactDownloadDTO::class.java - } + override fun getPayloadType(headers: StompHeaders): Type = ArtifactDownloadDTO::class.java override fun handleFrame(headers: StompHeaders, payload: Any?) { payload?.let { @@ -48,8 +46,8 @@ class ArtifactDownloadHandler( } } } - private fun getValidArtifacts(dto: ArtifactDownloadDTO, token: String): List { - return gitHubClient.getRunArtifacts(dto.repositoryOwner, dto.repositoryName, dto.runId, token) + private fun getValidArtifacts(dto: ArtifactDownloadDTO, token: String): List = + gitHubClient.getRunArtifacts(dto.repositoryOwner, dto.repositoryName, dto.runId, token) .artifacts .filter { if (dto.artifactName != null) { @@ -58,12 +56,11 @@ class ArtifactDownloadHandler( true } } - } private fun fetchAndProcessArtifacts( artifacts: List, dto: ArtifactDownloadDTO, - installationToken: String + installationToken: String, ) { artifacts.forEach { artifact -> logger.info("Processing artifact: ${artifact.name}") @@ -95,7 +92,7 @@ class ArtifactDownloadHandler( repositoryFullName = "${dto.repositoryOwner}/${dto.repositoryName}", artifactFileName = artifactName, artifactFileContent = artifactContent, - ) + ), ) } } diff --git a/src/main/kotlin/net/leanix/githubagent/handler/BrokerStompSessionHandler.kt b/src/main/kotlin/net/leanix/githubagent/handler/BrokerStompSessionHandler.kt index facd613..ccd5780 100644 --- a/src/main/kotlin/net/leanix/githubagent/handler/BrokerStompSessionHandler.kt +++ b/src/main/kotlin/net/leanix/githubagent/handler/BrokerStompSessionHandler.kt @@ -19,7 +19,7 @@ class BrokerStompSessionHandler( private val installationGetHandler: InstallationGetHandler, private val fullScanHandler: FullScanHandler, private val configurationSetHandler: ConfigurationSetHandler, - private val eventPublisher: ApplicationEventPublisher + private val eventPublisher: ApplicationEventPublisher, ) : StompSessionHandlerAdapter() { @Lazy @Autowired @@ -60,7 +60,5 @@ class BrokerStompSessionHandler( } } - fun isConnected(): Boolean { - return isConnected - } + fun isConnected(): Boolean = isConnected } diff --git a/src/main/kotlin/net/leanix/githubagent/handler/ConfigurationSetHandler.kt b/src/main/kotlin/net/leanix/githubagent/handler/ConfigurationSetHandler.kt index ead0f02..f6bfdef 100644 --- a/src/main/kotlin/net/leanix/githubagent/handler/ConfigurationSetHandler.kt +++ b/src/main/kotlin/net/leanix/githubagent/handler/ConfigurationSetHandler.kt @@ -12,9 +12,7 @@ class ConfigurationSetHandler : StompFrameHandler { private val logger = LoggerFactory.getLogger(ConfigurationSetHandler::class.java) - override fun getPayloadType(headers: StompHeaders): Type { - return AgentConfigurationRequest::class.java - } + override fun getPayloadType(headers: StompHeaders): Type = AgentConfigurationRequest::class.java override fun handleFrame(headers: StompHeaders, payload: Any?) { payload?.let { @@ -24,7 +22,7 @@ class ConfigurationSetHandler : StompFrameHandler { config.supportedWebhookEvents?.let { supportedEvents -> GitHubWebhookService.updateSupportedWebhookEvents(supportedEvents) logger.info( - "Supported webhook events updated: ${GitHubWebhookService.getSupportedWebhookEvents()}" + "Supported webhook events updated: ${GitHubWebhookService.getSupportedWebhookEvents()}", ) } } diff --git a/src/main/kotlin/net/leanix/githubagent/handler/FullScanHandler.kt b/src/main/kotlin/net/leanix/githubagent/handler/FullScanHandler.kt index b475c2a..0a814e2 100644 --- a/src/main/kotlin/net/leanix/githubagent/handler/FullScanHandler.kt +++ b/src/main/kotlin/net/leanix/githubagent/handler/FullScanHandler.kt @@ -22,9 +22,7 @@ class FullScanHandler( private val logger = LoggerFactory.getLogger(FullScanHandler::class.java) - override fun getPayloadType(headers: StompHeaders): Type { - return MessagePayload::class.java - } + override fun getPayloadType(headers: StompHeaders): Type = MessagePayload::class.java override fun handleFrame(headers: StompHeaders, payload: Any?) { logger.info("Received full scan request") diff --git a/src/main/kotlin/net/leanix/githubagent/handler/InstallationGetHandler.kt b/src/main/kotlin/net/leanix/githubagent/handler/InstallationGetHandler.kt index 9f90eb5..b7ae518 100644 --- a/src/main/kotlin/net/leanix/githubagent/handler/InstallationGetHandler.kt +++ b/src/main/kotlin/net/leanix/githubagent/handler/InstallationGetHandler.kt @@ -37,9 +37,7 @@ class InstallationGetHandler( private val logger = LoggerFactory.getLogger(InstallationGetHandler::class.java) - override fun getPayloadType(headers: StompHeaders): Type { - return InstallationRequestDTO::class.java - } + override fun getPayloadType(headers: StompHeaders): Type = InstallationRequestDTO::class.java override fun handleFrame(headers: StompHeaders, payload: Any?) { payload?.let { @@ -61,12 +59,12 @@ class InstallationGetHandler( val jwtToken = cachingService.get("jwtToken") ?: throw JwtTokenNotFound() val installation = gitHubClient.getInstallation( installationRequestDTO.id, - "Bearer $jwtToken" + "Bearer $jwtToken", ) gitHubEnterpriseService.validateEnabledPermissionsAndEvents( INSTALLATION_LABEL, installation.permissions, - installation.events + installation.events, ) gitHubAuthenticationService.refreshTokens() gitHubScanningService.fetchAndSendOrganisationsData(listOf(installation)) diff --git a/src/main/kotlin/net/leanix/githubagent/handler/RateLimitHandler.kt b/src/main/kotlin/net/leanix/githubagent/handler/RateLimitHandler.kt index bf05eba..69f2598 100644 --- a/src/main/kotlin/net/leanix/githubagent/handler/RateLimitHandler.kt +++ b/src/main/kotlin/net/leanix/githubagent/handler/RateLimitHandler.kt @@ -6,9 +6,7 @@ import net.leanix.githubagent.shared.RateLimitMonitor import org.springframework.stereotype.Component @Component -class RateLimitHandler( - private val syncLogService: SyncLogService, -) { +class RateLimitHandler(private val syncLogService: SyncLogService) { fun executeWithRateLimitHandler(rateLimitType: RateLimitType, block: () -> T): T { while (true) { @@ -16,7 +14,7 @@ class RateLimitHandler( if (waitTimeSeconds > 0) { syncLogService.sendInfoLog( "Approaching rate limit for $rateLimitType calls. " + - "Waiting for $waitTimeSeconds seconds." + "Waiting for $waitTimeSeconds seconds.", ) Thread.sleep(waitTimeSeconds * 1000) } diff --git a/src/main/kotlin/net/leanix/githubagent/handler/RepositoryGetHandler.kt b/src/main/kotlin/net/leanix/githubagent/handler/RepositoryGetHandler.kt index 0189a65..ff928f7 100644 --- a/src/main/kotlin/net/leanix/githubagent/handler/RepositoryGetHandler.kt +++ b/src/main/kotlin/net/leanix/githubagent/handler/RepositoryGetHandler.kt @@ -17,14 +17,12 @@ class RepositoryGetHandler( @Lazy @Autowired private val gitHubAuthenticationService: GitHubAuthenticationService, @Lazy @Autowired - private val repositoryGetService: GitHubRepositoryService + private val repositoryGetService: GitHubRepositoryService, ) : StompFrameHandler { private val logger = LoggerFactory.getLogger(RepositoryGetHandler::class.java) - override fun getPayloadType(headers: StompHeaders): Type { - return RepositoryRequestDTO::class.java - } + override fun getPayloadType(headers: StompHeaders): Type = RepositoryRequestDTO::class.java override fun handleFrame(headers: StompHeaders, payload: Any?) { payload?.let { @@ -41,7 +39,7 @@ class RepositoryGetHandler( ), dto.repositoryName, dto.repositoryFullName, - installationToken + installationToken, ) } } diff --git a/src/main/kotlin/net/leanix/githubagent/interceptor/RateLimitInterceptor.kt b/src/main/kotlin/net/leanix/githubagent/interceptor/RateLimitInterceptor.kt index c14a1df..145ebf2 100644 --- a/src/main/kotlin/net/leanix/githubagent/interceptor/RateLimitInterceptor.kt +++ b/src/main/kotlin/net/leanix/githubagent/interceptor/RateLimitInterceptor.kt @@ -10,8 +10,8 @@ import reactor.core.publisher.Mono class RateLimitInterceptor : ExchangeFilterFunction { - override fun filter(request: ClientRequest, next: ExchangeFunction): Mono { - return next.exchange(request).flatMap { response -> + override fun filter(request: ClientRequest, next: ExchangeFunction): Mono = + next.exchange(request).flatMap { response -> val headers = response.headers().asHttpHeaders() val rateLimitRemaining = headers["X-RateLimit-Remaining"]?.firstOrNull()?.toIntOrNull() val rateLimitReset = headers["X-RateLimit-Reset"]?.firstOrNull()?.toLongOrNull() @@ -22,5 +22,4 @@ class RateLimitInterceptor : ExchangeFilterFunction { } Mono.just(response) } - } } diff --git a/src/main/kotlin/net/leanix/githubagent/interceptor/RateLimitResponseInterceptor.kt b/src/main/kotlin/net/leanix/githubagent/interceptor/RateLimitResponseInterceptor.kt index 5cd5bcb..0a2b369 100644 --- a/src/main/kotlin/net/leanix/githubagent/interceptor/RateLimitResponseInterceptor.kt +++ b/src/main/kotlin/net/leanix/githubagent/interceptor/RateLimitResponseInterceptor.kt @@ -7,10 +7,7 @@ import net.leanix.githubagent.shared.determineRateLimitType class RateLimitResponseInterceptor : ResponseInterceptor { - override fun intercept( - invocationContext: InvocationContext, - chain: ResponseInterceptor.Chain - ): Any { + override fun intercept(invocationContext: InvocationContext, chain: ResponseInterceptor.Chain): Any { val result = chain.next(invocationContext) val response = invocationContext.response() diff --git a/src/main/kotlin/net/leanix/githubagent/listener/ApplicationReadyListener.kt b/src/main/kotlin/net/leanix/githubagent/listener/ApplicationReadyListener.kt index 1433489..324f377 100644 --- a/src/main/kotlin/net/leanix/githubagent/listener/ApplicationReadyListener.kt +++ b/src/main/kotlin/net/leanix/githubagent/listener/ApplicationReadyListener.kt @@ -9,9 +9,8 @@ import org.springframework.stereotype.Component @Component @Profile("!test") -class ApplicationReadyListener( - private val webSocketService: WebSocketService, -) : ApplicationListener { +class ApplicationReadyListener(private val webSocketService: WebSocketService) : + ApplicationListener { private val logger = LoggerFactory.getLogger(this::class.java) diff --git a/src/main/kotlin/net/leanix/githubagent/scheduler/AgentConnectionScheduler.kt b/src/main/kotlin/net/leanix/githubagent/scheduler/AgentConnectionScheduler.kt index f32f29a..08e5d83 100644 --- a/src/main/kotlin/net/leanix/githubagent/scheduler/AgentConnectionScheduler.kt +++ b/src/main/kotlin/net/leanix/githubagent/scheduler/AgentConnectionScheduler.kt @@ -9,7 +9,7 @@ import org.springframework.stereotype.Component @Component class AgentConnectionScheduler( private val brokerStompSessionHandler: BrokerStompSessionHandler, - private val webSocketService: WebSocketService + private val webSocketService: WebSocketService, ) { private val logger = LoggerFactory.getLogger(AgentConnectionScheduler::class.java) diff --git a/src/main/kotlin/net/leanix/githubagent/services/CachingService.kt b/src/main/kotlin/net/leanix/githubagent/services/CachingService.kt index 427be69..67c1c80 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/CachingService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/CachingService.kt @@ -9,40 +9,29 @@ import org.springframework.stereotype.Service import java.util.concurrent.TimeUnit @Service -class CachingService( - private val gitHubEnterpriseProperties: GitHubEnterpriseProperties -) { +class CachingService(private val gitHubEnterpriseProperties: GitHubEnterpriseProperties) { data class CacheValue(val value: Any, val expiry: Long?) private val cache: Cache = Caffeine.newBuilder() .maximumSize(100) .expireAfter(object : Expiry { - override fun expireAfterCreate( - key: String, - value: CacheValue, - currentTime: Long - ): Long { - return TimeUnit.SECONDS.toNanos(value.expiry ?: Long.MAX_VALUE) - } + override fun expireAfterCreate(key: String, value: CacheValue, currentTime: Long): Long = + TimeUnit.SECONDS.toNanos(value.expiry ?: Long.MAX_VALUE) override fun expireAfterUpdate( key: String, value: CacheValue, currentTime: Long, - currentDuration: Long - ): Long { - return TimeUnit.SECONDS.toNanos(value.expiry ?: Long.MAX_VALUE) - } + currentDuration: Long, + ): Long = TimeUnit.SECONDS.toNanos(value.expiry ?: Long.MAX_VALUE) override fun expireAfterRead( key: String, value: CacheValue, currentTime: Long, - currentDuration: Long - ): Long { - return currentDuration - } + currentDuration: Long, + ): Long = currentDuration }) .build() @@ -50,9 +39,7 @@ class CachingService( cache.put(key, CacheValue(value, expiry)) } - fun get(key: String): Any? { - return cache.getIfPresent(key)?.value - } + fun get(key: String): Any? = cache.getIfPresent(key)?.value fun remove(key: String) { cache.invalidate(key) diff --git a/src/main/kotlin/net/leanix/githubagent/services/FullScanService.kt b/src/main/kotlin/net/leanix/githubagent/services/FullScanService.kt index f6d5ab2..1fe2ead 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/FullScanService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/FullScanService.kt @@ -8,7 +8,7 @@ import org.springframework.stereotype.Service class FullScanService( private val gitHubScanningService: GitHubScanningService, private val syncLogService: SyncLogService, - private val gitHubAuthenticationService: GitHubAuthenticationService + private val gitHubAuthenticationService: GitHubAuthenticationService, ) { companion object { diff --git a/src/main/kotlin/net/leanix/githubagent/services/GitHubAPIService.kt b/src/main/kotlin/net/leanix/githubagent/services/GitHubAPIService.kt index 3e57035..82f7f97 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/GitHubAPIService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/GitHubAPIService.kt @@ -6,9 +6,7 @@ import net.leanix.githubagent.dto.Organization import org.springframework.stereotype.Service @Service -class GitHubAPIService( - private val gitHubClient: GitHubClient, -) { +class GitHubAPIService(private val gitHubClient: GitHubClient) { companion object { private const val PAGE_SIZE = 30 // Maximum allowed by GitHub API is 100 diff --git a/src/main/kotlin/net/leanix/githubagent/services/GitHubAuthenticationService.kt b/src/main/kotlin/net/leanix/githubagent/services/GitHubAuthenticationService.kt index 892f30b..b269f32 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/GitHubAuthenticationService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/GitHubAuthenticationService.kt @@ -34,8 +34,8 @@ class GitHubAuthenticationService( companion object { private const val JWT_EXPIRATION_DURATION_IN_SECONDS = 600L private const val INSTALLATION_JWT_EXPIRATION_DURATION_IN_SECONDS = 3600L - private const val pemPrefix = "-----BEGIN RSA PRIVATE KEY-----" - private const val pemSuffix = "-----END RSA PRIVATE KEY-----" + private const val PEM_PREFIX = "-----BEGIN RSA PRIVATE KEY-----" + private const val PEM_SUFFIX = "-----END RSA PRIVATE KEY-----" private val logger = LoggerFactory.getLogger(GitHubAuthenticationService::class.java) } @@ -58,33 +58,29 @@ class GitHubAuthenticationService( } } - private fun loadPrivateKey(): PrivateKey { - return runCatching { - Security.addProvider(BouncyCastleProvider()) - val rsaPrivateKey: String = readPrivateKey() - val keySpec = PKCS8EncodedKeySpec(Base64.getDecoder().decode(rsaPrivateKey)) - KeyFactory.getInstance("RSA").generatePrivate(keySpec) - }.getOrElse { - logger.error("Failed to load private key", it) - throw IllegalArgumentException( - "Failed to load private key, " + - "the provided private key is not a valid PKCS8 key." - ) - } + private fun loadPrivateKey(): PrivateKey = runCatching { + Security.addProvider(BouncyCastleProvider()) + val rsaPrivateKey: String = readPrivateKey() + val keySpec = PKCS8EncodedKeySpec(Base64.getDecoder().decode(rsaPrivateKey)) + KeyFactory.getInstance("RSA").generatePrivate(keySpec) + }.getOrElse { + logger.error("Failed to load private key", it) + throw IllegalArgumentException( + "Failed to load private key, " + + "the provided private key is not a valid PKCS8 key.", + ) } - private fun createJwtToken(privateKey: PrivateKey): String { - return runCatching { - Jwts.builder() - .setIssuedAt(Date()) - .setExpiration(Date(System.currentTimeMillis() + (JWT_EXPIRATION_DURATION_IN_SECONDS * 1000))) - .setIssuer(cachingService.get("githubAppId").toString()) - .signWith(privateKey, SignatureAlgorithm.RS256) - .compact() - }.getOrElse { - logger.error("Failed to generate a JWT token", it) - throw FailedToCreateJWTException("Failed to generate a JWT token") - } + private fun createJwtToken(privateKey: PrivateKey): String = runCatching { + Jwts.builder() + .setIssuedAt(Date()) + .setExpiration(Date(System.currentTimeMillis() + (JWT_EXPIRATION_DURATION_IN_SECONDS * 1000))) + .setIssuer(cachingService.get("githubAppId").toString()) + .signWith(privateKey, SignatureAlgorithm.RS256) + .compact() + }.getOrElse { + logger.error("Failed to generate a JWT token", it) + throw FailedToCreateJWTException("Failed to generate a JWT token") } private fun verifyAndCacheJwtToken(jwt: String) { @@ -98,16 +94,13 @@ class GitHubAuthenticationService( } } - fun generateAndCacheInstallationTokens( - installations: List, - jwtToken: String - ) { + fun generateAndCacheInstallationTokens(installations: List, jwtToken: String) { installations.forEach { installation -> val installationToken = gitHubClient.createInstallationToken(installation.id, "Bearer $jwtToken").token cachingService.set( "installationToken:${installation.id}", installationToken, - INSTALLATION_JWT_EXPIRATION_DURATION_IN_SECONDS + INSTALLATION_JWT_EXPIRATION_DURATION_IN_SECONDS, ) } } @@ -117,14 +110,14 @@ class GitHubAuthenticationService( val pemFile = File(resourceLoader.getResource("file:${githubEnterpriseProperties.pemFile}").uri) val fileContent = String(Files.readAllBytes(pemFile.toPath()), Charset.defaultCharset()).trim() - require(fileContent.startsWith(pemPrefix) && fileContent.endsWith(pemSuffix)) { + require(fileContent.startsWith(PEM_PREFIX) && fileContent.endsWith(PEM_SUFFIX)) { "The provided file is not a valid PEM file." } return fileContent - .replace(pemPrefix, "") + .replace(PEM_PREFIX, "") .replace(System.lineSeparator().toRegex(), "") - .replace(pemSuffix, "") + .replace(PEM_SUFFIX, "") } fun getInstallationToken(installationId: Int): String { diff --git a/src/main/kotlin/net/leanix/githubagent/services/GitHubEnterpriseService.kt b/src/main/kotlin/net/leanix/githubagent/services/GitHubEnterpriseService.kt index 236ab8c..e3f4225 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/GitHubEnterpriseService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/GitHubEnterpriseService.kt @@ -8,10 +8,7 @@ import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service -class GitHubEnterpriseService( - private val githubClient: GitHubClient, - private val syncLogService: SyncLogService, -) { +class GitHubEnterpriseService(private val githubClient: GitHubClient, private val syncLogService: SyncLogService) { companion object { val expectedPermissions = listOf("administration", "contents", "metadata") @@ -30,6 +27,7 @@ class GitHubEnterpriseService( logger.error(it.message) syncLogService.sendErrorLog(it.message!!) } + else -> { logger.error("Failed to verify JWT token", it) throw UnableToConnectToGitHubEnterpriseException("Failed to verify JWT token") diff --git a/src/main/kotlin/net/leanix/githubagent/services/GitHubGraphQLService.kt b/src/main/kotlin/net/leanix/githubagent/services/GitHubGraphQLService.kt index 6b0b5a2..42246e2 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/GitHubGraphQLService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/GitHubGraphQLService.kt @@ -17,26 +17,21 @@ import java.time.Duration import io.github.resilience4j.retry.annotation.Retry as ResilienceRetry @Component -class GitHubGraphQLService( - private val cachingService: CachingService, -) { +class GitHubGraphQLService(private val cachingService: CachingService) { companion object { private val logger = LoggerFactory.getLogger(GitHubGraphQLService::class.java) private const val PAGE_COUNT = 20 } @ResilienceRetry(name = "secondary_rate_limit") - fun getRepositories( - token: String, - cursor: String? = null - ): PagedRepositories { + fun getRepositories(token: String, cursor: String? = null): PagedRepositories { val client = buildGitHubGraphQLClient(token) val query = GetRepositories( GetRepositories.Variables( pageCount = PAGE_COUNT, cursor = cursor, - ) + ), ) val result = runBlocking { @@ -64,26 +59,21 @@ class GitHubGraphQLService( languages = it.languages!!.nodes!!.map { language -> language!!.name }, topics = it.repositoryTopics.nodes!!.map { topic -> topic!!.topic.name }, ) - } + }, ) } } @ResilienceRetry(name = "secondary_rate_limit") - fun getManifestFileContent( - owner: String, - repositoryName: String, - filePath: String, - token: String - ): String? { + fun getManifestFileContent(owner: String, repositoryName: String, filePath: String, token: String): String? { val client = buildGitHubGraphQLClient(token) val query = GetRepositoryManifestContent( GetRepositoryManifestContent.Variables( owner = owner, repositoryName = repositoryName, - manifestFilePath = "HEAD:$filePath" - ) + manifestFilePath = "HEAD:$filePath", + ), ) val result = runBlocking { @@ -99,18 +89,14 @@ class GitHubGraphQLService( } @ResilienceRetry(name = "secondary_rate_limit") - fun getRepository( - owner: String, - repositoryName: String, - token: String - ): RepositoryDto? { + fun getRepository(owner: String, repositoryName: String, token: String): RepositoryDto? { val client = buildGitHubGraphQLClient(token) val query = GetRepository( GetRepository.Variables( owner = owner, - repositoryName = repositoryName - ) + repositoryName = repositoryName, + ), ) val result = runBlocking { @@ -139,18 +125,15 @@ class GitHubGraphQLService( ) } - private fun buildGitHubGraphQLClient( - token: String - ) = - GraphQLWebClient( - url = "${cachingService.get("baseUrl")}/api/graphql", - builder = WebClient.builder().defaultHeaders { it.setBearerAuth(token) } - .filter(RateLimitInterceptor()) - .filter { request, next -> - next.exchange(request) - .retryWhen(Retry.backoff(3, Duration.ofSeconds(2))) - } - ) + private fun buildGitHubGraphQLClient(token: String) = GraphQLWebClient( + url = "${cachingService.get("baseUrl")}/api/graphql", + builder = WebClient.builder().defaultHeaders { it.setBearerAuth(token) } + .filter(RateLimitInterceptor()) + .filter { request, next -> + next.exchange(request) + .retryWhen(Retry.backoff(3, Duration.ofSeconds(2))) + }, + ) } typealias RepositoryManifestBlob = net.leanix.githubagent.graphql.`data`.getrepositorymanifestcontent.Blob diff --git a/src/main/kotlin/net/leanix/githubagent/services/GitHubRepositoryService.kt b/src/main/kotlin/net/leanix/githubagent/services/GitHubRepositoryService.kt index fc9da1d..c474cc0 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/GitHubRepositoryService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/GitHubRepositoryService.kt @@ -29,7 +29,7 @@ class GitHubRepositoryService( installation: Installation, repositoryName: String, repositoryFullName: String, - installationToken: String + installationToken: String, ) { kotlin.runCatching { logger.info("Fetching repository details for: $repositoryFullName") @@ -37,7 +37,7 @@ class GitHubRepositoryService( gitHubGraphQLService.getRepository( installation.account.login, repositoryName, - installationToken + installationToken, ) } if (repository == null) { @@ -63,7 +63,7 @@ class GitHubRepositoryService( installation, manifestFiles, repositoryAdded.name, - repositoryAdded.defaultBranch + repositoryAdded.defaultBranch, ).getOrThrow() if (manifestContents.isEmpty()) { @@ -78,8 +78,8 @@ class GitHubRepositoryService( repositoryAdded.fullName, ManifestFileAction.ADDED, it.content, - generateFullPath(repositoryAdded.defaultBranch, fileNameMatchRegex.replace(it.path, "")) - ) + generateFullPath(repositoryAdded.defaultBranch, fileNameMatchRegex.replace(it.path, "")), + ), ) } } diff --git a/src/main/kotlin/net/leanix/githubagent/services/GitHubScanningService.kt b/src/main/kotlin/net/leanix/githubagent/services/GitHubScanningService.kt index 7aacdf3..0ffd9d3 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/GitHubScanningService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/GitHubScanningService.kt @@ -44,7 +44,7 @@ class GitHubScanningService( gitHubEnterpriseService.validateEnabledPermissionsAndEvents( INSTALLATION_LABEL, installation.permissions, - installation.events + installation.events, ) fetchAndSendRepositoriesData(installation) .forEach { repository -> @@ -58,6 +58,7 @@ class GitHubScanningService( syncLogService.sendErrorLog("$message ${it.message}") logger.error("$message ${it.message}") } + else -> { syncLogService.sendErrorLog(message) logger.error(message, it) @@ -74,9 +75,7 @@ class GitHubScanningService( return installations } - fun fetchAndSendOrganisationsData( - installations: List - ) { + fun fetchAndSendOrganisationsData(installations: List) { if (installations.isEmpty()) { logger.warn("No installations found, please install the GitHub App on an organization") webSocketService.sendMessage("${cachingService.get("runId")}/organizations", emptyList()) @@ -96,7 +95,7 @@ class GitHubScanningService( logger.info("Sending organizations data") syncLogService.sendInfoLog( "The connector found ${organizations.filter { it.installed }.size} " + - "organizations with GitHub application installed, out of possible ${organizations.size}." + "organizations with GitHub application installed, out of possible ${organizations.size}.", ) webSocketService.sendMessage("${cachingService.get("runId")}/organizations", organizations) } @@ -111,12 +110,12 @@ class GitHubScanningService( val repositoriesPage = rateLimitHandler.executeWithRateLimitHandler(RateLimitType.GRAPHQL) { gitHubGraphQLService.getRepositories( token = installationToken, - cursor = cursor + cursor = cursor, ) } webSocketService.sendMessage( "${cachingService.get("runId")}/repositories", - repositoriesPage.repositories.filter { !it.archived } + repositoriesPage.repositories.filter { !it.archived }, ) repositories.addAll(repositoriesPage.repositories) cursor = repositoriesPage.cursor @@ -134,7 +133,7 @@ class GitHubScanningService( installation, manifestFiles, repository.name, - repository.defaultBranch + repository.defaultBranch, ).getOrThrow() webSocketService.sendMessage( @@ -143,7 +142,7 @@ class GitHubScanningService( repositoryId = repository.id, repositoryFullName = repository.fullName, manifestFiles = manifestFilesContents, - ) + ), ) } @@ -153,7 +152,7 @@ class GitHubScanningService( gitHubClient.searchManifestFiles( "Bearer $installationToken", "" + - "repo:${installation.account.login}/$repositoryName filename:$MANIFEST_FILE_NAME" + "repo:${installation.account.login}/$repositoryName filename:$MANIFEST_FILE_NAME", ) } manifestFiles.items.filter { it.name.lowercase() == MANIFEST_FILE_NAME } @@ -162,7 +161,7 @@ class GitHubScanningService( installation: Installation, items: List, repositoryName: String, - defaultBranch: String? + defaultBranch: String?, ) = runCatching { val installationToken = cachingService.get("installationToken:${installation.id}").toString() syncLogService.sendInfoLog("Scanning repository $repositoryName for manifest files.") @@ -172,16 +171,16 @@ class GitHubScanningService( owner = installation.account.login, repositoryName = repositoryName, filePath = manifestFile.path, - token = installationToken + token = installationToken, ) if (content != null) { numOfManifestFilesFound++ syncLogService.sendInfoLog( - "Fetched manifest file '${manifestFile.path}' from repository '$repositoryName'." + "Fetched manifest file '${manifestFile.path}' from repository '$repositoryName'.", ) ManifestFileDTO( path = generateFullPath(defaultBranch, fileNameMatchRegex.replace(manifestFile.path, "")), - content = content + content = content, ) } else { throw ManifestFileNotFoundException() diff --git a/src/main/kotlin/net/leanix/githubagent/services/GitHubStartService.kt b/src/main/kotlin/net/leanix/githubagent/services/GitHubStartService.kt index 422b3b1..6a53f16 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/GitHubStartService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/GitHubStartService.kt @@ -26,7 +26,7 @@ class GitHubStartService( val jwt = cachingService.get("jwtToken") as String webSocketService.sendMessage( APP_NAME_TOPIC, - gitHubEnterpriseService.getGitHubApp(jwt).slug + gitHubEnterpriseService.getGitHubApp(jwt).slug, ) } } diff --git a/src/main/kotlin/net/leanix/githubagent/services/GitHubWebhookService.kt b/src/main/kotlin/net/leanix/githubagent/services/GitHubWebhookService.kt index e74dd5b..05eafcb 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/GitHubWebhookService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/GitHubWebhookService.kt @@ -1,6 +1,5 @@ package net.leanix.githubagent.services -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import net.leanix.githubagent.config.GitHubEnterpriseProperties import net.leanix.githubagent.dto.GenericWebhookEvent import net.leanix.githubagent.exceptions.InvalidEventSignatureException @@ -11,6 +10,7 @@ import net.leanix.githubagent.shared.timingSafeEqual import org.slf4j.LoggerFactory import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Service +import tools.jackson.module.kotlin.jacksonObjectMapper @Service class GitHubWebhookService( @@ -51,7 +51,7 @@ class GitHubWebhookService( logger.error( "Event signature is present but webhook secret is not set, " + "please restart the agent with a valid secret, " + - "or remove the secret from the GitHub App settings." + "or remove the secret from the GitHub App settings.", ) throw WebhookSecretNotSetException() } @@ -80,15 +80,14 @@ class GitHubWebhookService( } } - private fun findSupportedWebhookEvent(eventType: String): SupportedWebhookEvent? { - return getSupportedWebhookEvents().find { it.eventType.equals(eventType, ignoreCase = true) } - } + private fun findSupportedWebhookEvent(eventType: String): SupportedWebhookEvent? = + getSupportedWebhookEvents().find { + it.eventType.equals(eventType, ignoreCase = true) + } - private fun extractEventAction(payload: String): String? { - return objectMapper.readValue(payload, GenericWebhookEvent::class.java).action - } + private fun extractEventAction(payload: String): String? = + objectMapper.readValue(payload, GenericWebhookEvent::class.java).action - private fun isEventSupported(event: SupportedWebhookEvent?, action: String?): Boolean { - return event != null && (event.actions.isEmpty() || (action != null && action in event.actions)) - } + private fun isEventSupported(event: SupportedWebhookEvent?, action: String?): Boolean = + event != null && (event.actions.isEmpty() || (action != null && action in event.actions)) } diff --git a/src/main/kotlin/net/leanix/githubagent/services/LeanIXAuthService.kt b/src/main/kotlin/net/leanix/githubagent/services/LeanIXAuthService.kt index bfbab6f..afde6f4 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/LeanIXAuthService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/LeanIXAuthService.kt @@ -8,18 +8,15 @@ import java.util.* @Service class LeanIXAuthService( private val leanIXAuthClient: LeanIXAuthClient, - private val leanIXProperties: LeanIXProperties + private val leanIXProperties: LeanIXProperties, ) { - fun getBearerToken(): String { - return leanIXAuthClient.getToken( - authorization = getBasicAuthHeader(), - body = "grant_type=client_credentials", - ).accessToken - } + fun getBearerToken(): String = leanIXAuthClient.getToken( + authorization = getBasicAuthHeader(), + body = "grant_type=client_credentials", + ).accessToken - private fun getBasicAuthHeader(): String = - "Basic " + Base64.getEncoder().encodeToString( - "apitoken:${leanIXProperties.auth.technicalUserToken}".toByteArray(), - ) + private fun getBasicAuthHeader(): String = "Basic " + Base64.getEncoder().encodeToString( + "apitoken:${leanIXProperties.auth.technicalUserToken}".toByteArray(), + ) } diff --git a/src/main/kotlin/net/leanix/githubagent/services/SyncLogService.kt b/src/main/kotlin/net/leanix/githubagent/services/SyncLogService.kt index 1897729..4634235 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/SyncLogService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/SyncLogService.kt @@ -10,10 +10,7 @@ import org.springframework.stereotype.Service import java.util.UUID @Service -class SyncLogService( - private val webSocketService: WebSocketService, - private val cachingService: CachingService -) { +class SyncLogService(private val webSocketService: WebSocketService, private val cachingService: CachingService) { private val logger = LoggerFactory.getLogger(SyncLogService::class.java) fun sendFullScanStart(orgName: String?) { @@ -27,7 +24,7 @@ class SyncLogService( sendSyncLog( logLevel = LogLevel.INFO, synchronizationProgress = SynchronizationProgress.PENDING, - message = message + message = message, ) } @@ -35,7 +32,7 @@ class SyncLogService( sendSyncLog( logLevel = LogLevel.INFO, synchronizationProgress = SynchronizationProgress.FINISHED, - message = "Synchronization finished." + message = "Synchronization finished.", ) cachingService.remove("runId") logger.info("Full sync finished") @@ -47,7 +44,7 @@ class SyncLogService( sendSyncLog( logLevel = LogLevel.ERROR, synchronizationProgress = SynchronizationProgress.ABORTED, - message = message + message = message, ) cachingService.remove("runId") logger.error(message) @@ -65,7 +62,7 @@ class SyncLogService( message: String, topic: String = LOGS_TOPIC, logLevel: LogLevel, - synchronizationProgress: SynchronizationProgress + synchronizationProgress: SynchronizationProgress, ) { val runId = cachingService.get("runId")?.let { it as UUID } val syncLogDto = SyncLogDto( @@ -73,12 +70,10 @@ class SyncLogService( trigger = if (runId != null) Trigger.FULL_SCAN else Trigger.WEB_HOOK, logLevel = logLevel, synchronizationProgress = synchronizationProgress, - message = message + message = message, ) webSocketService.sendMessage(constructTopic(topic), syncLogDto) } - private fun constructTopic(topic: String): String { - return topic - } + private fun constructTopic(topic: String): String = topic } diff --git a/src/main/kotlin/net/leanix/githubagent/services/WebhookEventService.kt b/src/main/kotlin/net/leanix/githubagent/services/WebhookEventService.kt index 4764123..3226e1e 100644 --- a/src/main/kotlin/net/leanix/githubagent/services/WebhookEventService.kt +++ b/src/main/kotlin/net/leanix/githubagent/services/WebhookEventService.kt @@ -1,7 +1,5 @@ package net.leanix.githubagent.services -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import com.fasterxml.jackson.module.kotlin.readValue import net.leanix.githubagent.dto.ManifestFileAction import net.leanix.githubagent.dto.ManifestFileUpdateDto import net.leanix.githubagent.dto.PushEventCommit @@ -11,6 +9,8 @@ import net.leanix.githubagent.shared.fileNameMatchRegex import net.leanix.githubagent.shared.generateFullPath import org.slf4j.LoggerFactory import org.springframework.stereotype.Service +import tools.jackson.module.kotlin.jacksonObjectMapper +import tools.jackson.module.kotlin.readValue @SuppressWarnings("TooManyFunctions") @Service @@ -26,6 +26,7 @@ class WebhookEventService( fun consumeWebhookEvent(eventType: String, payload: String) { when (eventType.uppercase()) { "PUSH" -> handlePushEvent(payload) + else -> { logger.debug("Sending event of type: $eventType") webSocketService.sendMessage("/events/other/$eventType", payload) @@ -50,7 +51,7 @@ class WebhookEventService( repositoryFullName, owner, repositoryName, - installationToken + installationToken, ) } } @@ -61,7 +62,7 @@ class WebhookEventService( repositoryFullName: String, owner: String, repositoryName: String, - installationToken: String + installationToken: String, ) { val addedManifestFiles = headCommit.added.filter { isLeanixManifestFile(it.lowercase()) } val modifiedManifestFiles = headCommit.modified.filter { isLeanixManifestFile(it.lowercase()) } @@ -75,7 +76,7 @@ class WebhookEventService( installationToken, filePath, ManifestFileAction.ADDED, - defaultBranch + defaultBranch, ) } @@ -87,7 +88,7 @@ class WebhookEventService( installationToken, filePath, ManifestFileAction.MODIFIED, - defaultBranch + defaultBranch, ) } @@ -106,7 +107,7 @@ class WebhookEventService( installationToken: String, manifestFilePath: String, action: ManifestFileAction, - defaultBranch: String? + defaultBranch: String?, ) { val location = getManifestFileLocation(manifestFilePath) @@ -116,7 +117,7 @@ class WebhookEventService( owner, repositoryName, manifestFilePath, - installationToken + installationToken, ) webSocketService.sendMessage( "/events/manifestFile", @@ -124,19 +125,19 @@ class WebhookEventService( repositoryFullName, action, fileContent, - generateFullPath(defaultBranch, fileNameMatchRegex.replace(manifestFilePath, "")) - ) + generateFullPath(defaultBranch, fileNameMatchRegex.replace(manifestFilePath, "")), + ), ) } private fun handleRemovedManifestFile( repositoryFullName: String, manifestFilePath: String, - defaultBranch: String? + defaultBranch: String?, ) { val location = getManifestFileLocation(manifestFilePath) logger.info( - " Manifest file ${ManifestFileAction.REMOVED} from repository $repositoryFullName under $location" + " Manifest file ${ManifestFileAction.REMOVED} from repository $repositoryFullName under $location", ) webSocketService.sendMessage( "/events/manifestFile", @@ -144,16 +145,14 @@ class WebhookEventService( repositoryFullName, ManifestFileAction.REMOVED, null, - generateFullPath(defaultBranch, fileNameMatchRegex.replace(manifestFilePath, "")) - ) + generateFullPath(defaultBranch, fileNameMatchRegex.replace(manifestFilePath, "")), + ), ) } - private fun getManifestFileLocation(manifestFilePath: String): String { - return if (manifestFilePath.contains('/')) { - "directory '/${manifestFilePath.substringBeforeLast('/')}'" - } else { - "root folder" - } + private fun getManifestFileLocation(manifestFilePath: String): String = if (manifestFilePath.contains('/')) { + "directory '/${manifestFilePath.substringBeforeLast('/')}'" + } else { + "root folder" } } diff --git a/src/main/kotlin/net/leanix/githubagent/shared/GitHubAgentProperties.kt b/src/main/kotlin/net/leanix/githubagent/shared/GitHubAgentProperties.kt index fb4c0c8..4be2cae 100644 --- a/src/main/kotlin/net/leanix/githubagent/shared/GitHubAgentProperties.kt +++ b/src/main/kotlin/net/leanix/githubagent/shared/GitHubAgentProperties.kt @@ -1,5 +1,5 @@ package net.leanix.githubagent.shared object GitHubAgentProperties { - lateinit var GITHUB_AGENT_VERSION: String + lateinit var githubAgentVersion: String } diff --git a/src/main/kotlin/net/leanix/githubagent/shared/GradlePropertiesConfiguration.kt b/src/main/kotlin/net/leanix/githubagent/shared/GradlePropertiesConfiguration.kt index 8ec67ab..729d314 100644 --- a/src/main/kotlin/net/leanix/githubagent/shared/GradlePropertiesConfiguration.kt +++ b/src/main/kotlin/net/leanix/githubagent/shared/GradlePropertiesConfiguration.kt @@ -1,7 +1,7 @@ package net.leanix.githubagent.shared import jakarta.annotation.PostConstruct -import net.leanix.githubagent.shared.GitHubAgentProperties.GITHUB_AGENT_VERSION +import net.leanix.githubagent.shared.GitHubAgentProperties.githubAgentVersion import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.context.annotation.Configuration @@ -17,10 +17,10 @@ class GradlePropertiesConfiguration { try { val gradleProperties = Properties() gradleProperties.load(this::class.java.getResourceAsStream("/gradle.properties")) - GITHUB_AGENT_VERSION = gradleProperties.getProperty("version") - logger.info("Running GitHub agent on version: $GITHUB_AGENT_VERSION") + githubAgentVersion = gradleProperties.getProperty("version") + logger.info("Running GitHub agent on version: $githubAgentVersion") } catch (e: RuntimeException) { - GITHUB_AGENT_VERSION = "unknown" + githubAgentVersion = "unknown" logger.error("Unable to load GitHub agent version") } } diff --git a/src/main/kotlin/net/leanix/githubagent/shared/RateLimitHelper.kt b/src/main/kotlin/net/leanix/githubagent/shared/RateLimitHelper.kt index e9663c9..208a079 100644 --- a/src/main/kotlin/net/leanix/githubagent/shared/RateLimitHelper.kt +++ b/src/main/kotlin/net/leanix/githubagent/shared/RateLimitHelper.kt @@ -2,12 +2,10 @@ package net.leanix.githubagent.shared import net.leanix.githubagent.dto.RateLimitType -fun determineRateLimitType(requestUrl: String): RateLimitType { - return if (requestUrl.contains("/graphql")) { - RateLimitType.GRAPHQL - } else if (requestUrl.contains("/search")) { - RateLimitType.SEARCH - } else { - RateLimitType.REST - } +fun determineRateLimitType(requestUrl: String): RateLimitType = if (requestUrl.contains("/graphql")) { + RateLimitType.GRAPHQL +} else if (requestUrl.contains("/search")) { + RateLimitType.SEARCH +} else { + RateLimitType.REST } diff --git a/src/main/kotlin/net/leanix/githubagent/shared/RateLimitMonitor.kt b/src/main/kotlin/net/leanix/githubagent/shared/RateLimitMonitor.kt index 278e4bb..d42bb1c 100644 --- a/src/main/kotlin/net/leanix/githubagent/shared/RateLimitMonitor.kt +++ b/src/main/kotlin/net/leanix/githubagent/shared/RateLimitMonitor.kt @@ -34,10 +34,12 @@ object RateLimitMonitor { graphqlRateLimitRemaining = remaining graphqlRateLimitResetTime = resetTimeEpochSeconds } + RateLimitType.REST -> { restRateLimitRemaining = remaining restRateLimitResetTime = resetTimeEpochSeconds } + RateLimitType.SEARCH -> { searchRateLimitRemaining = remaining searchRateLimitResetTime = resetTimeEpochSeconds @@ -61,13 +63,13 @@ object RateLimitMonitor { val adjustedWaitTime = if (waitTimeSeconds > 0) waitTimeSeconds else 0 logger.warn( "Rate limit remaining ($rateLimitRemaining) for $rateLimitType calls, is at or below " + - "threshold ($THRESHOLD). Throttling for $adjustedWaitTime seconds." + "threshold ($THRESHOLD). Throttling for $adjustedWaitTime seconds.", ) return adjustedWaitTime } else { logger.debug( "Rate limit remaining ($rateLimitRemaining) for $rateLimitType calls, is above threshold" + - " ($THRESHOLD). No need to throttle." + " ($THRESHOLD). No need to throttle.", ) } return 0 diff --git a/src/main/resources/application-saas.yaml b/src/main/resources/application-saas.yaml new file mode 100644 index 0000000..960e55b --- /dev/null +++ b/src/main/resources/application-saas.yaml @@ -0,0 +1,30 @@ +github-enterprise: + baseUrl: https://api.github.com/ + graphUrl: https://api.github.com/graphql + githubAppId: ${GITHUB_APP_ID:} + pemFile: ${PEM_FILE:} + manifestFileDirectory: ${MANIFEST_FILE_DIRECTORY:} + webhookSecret: ${WEBHOOK_SECRET:} +leanix: + base-url: https://${LEANIX_DOMAIN}/services + ws-base-url: wss://${LEANIX_DOMAIN}/services/git-integrations/v1/git-ws +# ws-base-url: ws://localhost:8080/git-ws + auth: + access-token-uri: ${leanix.base-url}/mtm/v1 + technical-user-token: ${LEANIX_TECHNICAL_USER_TOKEN} +webhookEventService: + waitingTime: 10000 + +resilience4j.retry: + configs: + default: + maxAttempts: 5 + enable-exponential-backoff: true + exponential-backoff-multiplier: 2 + waitDuration: 20s +logging: + level: + org.springframework.web.socket.handler: DEBUG + sun.net.www.protocol.http.HttpURLConnection: OFF +server: + port: 0 diff --git a/src/test/kotlin/net/leanix/githubagent/config/WebSocketClientConfigTests.kt b/src/test/kotlin/net/leanix/githubagent/config/WebSocketClientConfigTests.kt index 62c596f..79cc35a 100644 --- a/src/test/kotlin/net/leanix/githubagent/config/WebSocketClientConfigTests.kt +++ b/src/test/kotlin/net/leanix/githubagent/config/WebSocketClientConfigTests.kt @@ -1,6 +1,5 @@ package net.leanix.githubagent.config -import com.fasterxml.jackson.databind.ObjectMapper import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.runBlocking @@ -27,7 +26,6 @@ class WebSocketClientConfigTests { @BeforeEach fun setUp() { val brokerStompSessionHandler = mockk() - val objectMapper = mockk() leanIXProperties = mockk() gitHubEnterpriseProperties = mockk() stompClient = mockk() @@ -36,13 +34,12 @@ class WebSocketClientConfigTests { leanIXAuthService = mockk() webSocketClientConfig = WebSocketClientConfig( brokerStompSessionHandler, - objectMapper, leanIXAuthService, leanIXProperties, - gitHubEnterpriseProperties + gitHubEnterpriseProperties, ) - GitHubAgentProperties.GITHUB_AGENT_VERSION = "test-version" + GitHubAgentProperties.githubAgentVersion = "test-version" } @Test @@ -54,8 +51,10 @@ class WebSocketClientConfigTests { coEvery { leanIXAuthService.getBearerToken() } returns "bearer token" coEvery { stompClient.connectAsync( - any(), any(), - any(), any() + any(), + any(), + any(), + any(), ) } throws RuntimeException("Connection failed") diff --git a/src/test/kotlin/net/leanix/githubagent/controllers/GitHubWebhookControllerTest.kt b/src/test/kotlin/net/leanix/githubagent/controllers/GitHubWebhookControllerTest.kt index 04144b6..f54fce9 100644 --- a/src/test/kotlin/net/leanix/githubagent/controllers/GitHubWebhookControllerTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/controllers/GitHubWebhookControllerTest.kt @@ -13,7 +13,7 @@ import net.leanix.githubagent.services.WebhookEventService import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders import org.springframework.test.web.servlet.result.MockMvcResultMatchers @@ -57,7 +57,7 @@ class GitHubWebhookControllerTest { MockMvcRequestBuilders.post("/github/webhook") .header("X-GitHub-Event", eventType) .header("X-GitHub-Enterprise-Host", host) - .content(payload) + .content(payload), ) .andExpect(MockMvcResultMatchers.status().isAccepted) } @@ -71,7 +71,10 @@ class GitHubWebhookControllerTest { every { gitHubWebhookService.handleWebhookEvent( - eventType, host, signature256, payload + eventType, + host, + signature256, + payload, ) } throws WebhookSecretNotSetException() @@ -80,7 +83,7 @@ class GitHubWebhookControllerTest { .header("X-GitHub-Event", eventType) .header("X-GitHub-Enterprise-Host", host) .header("X-Hub-Signature-256", signature256) - .content(payload) + .content(payload), ) .andExpect(MockMvcResultMatchers.status().isBadRequest) } @@ -106,7 +109,7 @@ class GitHubWebhookControllerTest { MockMvcRequestBuilders.post("/github/webhook") .header("X-GitHub-Event", eventType) .header("X-GitHub-Enterprise-Host", host) - .content(payload) + .content(payload), ) .andExpect(MockMvcResultMatchers.status().isAccepted) diff --git a/src/test/kotlin/net/leanix/githubagent/handler/ArtifactDownloadHandlerTest.kt b/src/test/kotlin/net/leanix/githubagent/handler/ArtifactDownloadHandlerTest.kt index cfd24a6..54d5750 100644 --- a/src/test/kotlin/net/leanix/githubagent/handler/ArtifactDownloadHandlerTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/handler/ArtifactDownloadHandlerTest.kt @@ -26,7 +26,7 @@ class ArtifactDownloadHandlerTest { private val artifactDownloadHandler = ArtifactDownloadHandler( gitHubClient, webSocketService, - gitHubAuthenticationService + gitHubAuthenticationService, ) @BeforeEach @@ -45,15 +45,15 @@ class ArtifactDownloadHandlerTest { id = 1, name = "leanix-sbom-test-sbom", url = "http://download.url", - archiveDownloadUrl = "http://download.url" + archiveDownloadUrl = "http://download.url", ), Artifact( id = 2, name = "invalid-name", url = "http://download.url", - archiveDownloadUrl = "http://download.url" - ) - ) + archiveDownloadUrl = "http://download.url", + ), + ), ) val request = mockk() every { gitHubClient.downloadArtifact(any(), any(), any(), any()) } returns Response @@ -70,8 +70,8 @@ class ArtifactDownloadHandlerTest { repositoryOwner = "leanix", runId = 1, installationId = 1, - artifactName = "-sbom" - ) + artifactName = "-sbom", + ), ) // then @@ -91,15 +91,15 @@ class ArtifactDownloadHandlerTest { id = 1, name = "leanix-sbom-test-sbom", url = "http://download.url", - archiveDownloadUrl = "http://download.url" + archiveDownloadUrl = "http://download.url", ), Artifact( id = 2, name = "invalid-name", url = "http://download.url", - archiveDownloadUrl = "http://download.url" - ) - ) + archiveDownloadUrl = "http://download.url", + ), + ), ) val request = mockk() every { gitHubClient.downloadArtifact(any(), any(), any(), any()) } returns Response @@ -117,7 +117,7 @@ class ArtifactDownloadHandlerTest { repositoryOwner = "leanix", runId = 1, installationId = 1, - ) + ), ) // then @@ -137,15 +137,15 @@ class ArtifactDownloadHandlerTest { id = 1, name = "leanix-sbom-test-sbom", url = "http://download.url", - archiveDownloadUrl = "http://download.url" + archiveDownloadUrl = "http://download.url", ), Artifact( id = 2, name = "invalid-name", url = "http://download.url", - archiveDownloadUrl = "http://download.url" - ) - ) + archiveDownloadUrl = "http://download.url", + ), + ), ) val request = mockk() every { gitHubClient.downloadArtifact(any(), any(), any(), any()) } returns Response @@ -162,7 +162,7 @@ class ArtifactDownloadHandlerTest { repositoryOwner = "leanix", runId = 1, installationId = 1, - ) + ), ) // then diff --git a/src/test/kotlin/net/leanix/githubagent/handler/ConfigurationSetHandlerTest.kt b/src/test/kotlin/net/leanix/githubagent/handler/ConfigurationSetHandlerTest.kt index 218f5ae..f90e8bd 100644 --- a/src/test/kotlin/net/leanix/githubagent/handler/ConfigurationSetHandlerTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/handler/ConfigurationSetHandlerTest.kt @@ -22,7 +22,7 @@ class ConfigurationSetHandlerTest { val headers = StompHeaders() val supportedEvents = listOf( SupportedWebhookEvent("PUSH", listOf("created", "updated")), - SupportedWebhookEvent("PULL_REQUEST", listOf("opened", "closed")) + SupportedWebhookEvent("PULL_REQUEST", listOf("opened", "closed")), ) val payload = AgentConfigurationRequest(supportedWebhookEvents = supportedEvents) diff --git a/src/test/kotlin/net/leanix/githubagent/handler/RepositoryGetHandlerTest.kt b/src/test/kotlin/net/leanix/githubagent/handler/RepositoryGetHandlerTest.kt index 5e47738..c42d78b 100644 --- a/src/test/kotlin/net/leanix/githubagent/handler/RepositoryGetHandlerTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/handler/RepositoryGetHandlerTest.kt @@ -22,7 +22,7 @@ class RepositoryGetHandlerTest { private val repositoryGetHandler = RepositoryGetHandler( gitHubAuthenticationService, - gitHubRepositoryService + gitHubRepositoryService, ) @BeforeEach @@ -41,8 +41,8 @@ class RepositoryGetHandlerTest { RepositoryRequestDTO( installation = RepositoryRequestInstallationDTO(1, Account("account")), repositoryName = "repoName", - repositoryFullName = "repoFullName" - ) + repositoryFullName = "repoFullName", + ), ) // then @@ -51,7 +51,7 @@ class RepositoryGetHandlerTest { installation = Installation(1, Account("account"), mapOf(), listOf()), repositoryName = "repoName", repositoryFullName = "repoFullName", - installationToken = "token" + installationToken = "token", ) } } diff --git a/src/test/kotlin/net/leanix/githubagent/helper/TestDataBuilder.kt b/src/test/kotlin/net/leanix/githubagent/helper/TestDataBuilder.kt index f426618..87ea35b 100644 --- a/src/test/kotlin/net/leanix/githubagent/helper/TestDataBuilder.kt +++ b/src/test/kotlin/net/leanix/githubagent/helper/TestDataBuilder.kt @@ -2,12 +2,11 @@ package net.leanix.githubagent.helper import net.leanix.githubagent.handler.SupportedWebhookEvent -fun defaultSupportedWebhookEvents() = - listOf( - SupportedWebhookEvent("WORKFLOW_RUN", listOf("completed")), - SupportedWebhookEvent("REPOSITORY", listOf("archived", "unarchived", "renamed", "edited")), - SupportedWebhookEvent("INSTALLATION_REPOSITORIES", listOf("removed", "added")), - SupportedWebhookEvent("PUSH", emptyList()), - SupportedWebhookEvent("INSTALLATION", listOf("created")), - SupportedWebhookEvent("ORGANIZATION", listOf("created")) - ) +fun defaultSupportedWebhookEvents() = listOf( + SupportedWebhookEvent("WORKFLOW_RUN", listOf("completed")), + SupportedWebhookEvent("REPOSITORY", listOf("archived", "unarchived", "renamed", "edited")), + SupportedWebhookEvent("INSTALLATION_REPOSITORIES", listOf("removed", "added")), + SupportedWebhookEvent("PUSH", emptyList()), + SupportedWebhookEvent("INSTALLATION", listOf("created")), + SupportedWebhookEvent("ORGANIZATION", listOf("created")), +) diff --git a/src/test/kotlin/net/leanix/githubagent/listener/ApplicationReadyListenerTest.kt b/src/test/kotlin/net/leanix/githubagent/listener/ApplicationReadyListenerTest.kt index cba7012..8e41b1e 100644 --- a/src/test/kotlin/net/leanix/githubagent/listener/ApplicationReadyListenerTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/listener/ApplicationReadyListenerTest.kt @@ -15,7 +15,7 @@ class ApplicationReadyListenerTest { @BeforeEach fun setUp() { applicationListener = ApplicationReadyListener( - webSocketService + webSocketService, ) every { webSocketService.initSession() } returns Unit diff --git a/src/test/kotlin/net/leanix/githubagent/services/GitHubAPIServiceTest.kt b/src/test/kotlin/net/leanix/githubagent/services/GitHubAPIServiceTest.kt index d9bda62..a94b32a 100644 --- a/src/test/kotlin/net/leanix/githubagent/services/GitHubAPIServiceTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/services/GitHubAPIServiceTest.kt @@ -22,7 +22,7 @@ class GitHubAPIServiceTest { val jwtToken = "test-jwt-token" val installationsPage1 = listOf( Installation(1, Account("test-account"), permissions, events), - Installation(2, Account("test-account"), permissions, events) + Installation(2, Account("test-account"), permissions, events), ) every { gitHubClient.getInstallations(any(), any(), any()) } returns installationsPage1 @@ -54,7 +54,7 @@ class GitHubAPIServiceTest { val installationToken = "test-installation-token" val organizationsPage1 = listOf( Organization("org-1", 1), - Organization("org-2", 2) + Organization("org-2", 2), ) every { gitHubClient.getOrganizations(any(), any(), any()) } returns organizationsPage1 diff --git a/src/test/kotlin/net/leanix/githubagent/services/GitHubAuthenticationServiceTest.kt b/src/test/kotlin/net/leanix/githubagent/services/GitHubAuthenticationServiceTest.kt index 0471c36..0d6a108 100644 --- a/src/test/kotlin/net/leanix/githubagent/services/GitHubAuthenticationServiceTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/services/GitHubAuthenticationServiceTest.kt @@ -28,7 +28,7 @@ class GitHubAuthenticationServiceTest { resourceLoader, gitHubEnterpriseService, gitHubClient, - gitHubAPIService + gitHubAPIService, ) @BeforeEach diff --git a/src/test/kotlin/net/leanix/githubagent/services/GitHubEnterpriseServiceTest.kt b/src/test/kotlin/net/leanix/githubagent/services/GitHubEnterpriseServiceTest.kt index 35092d1..264a81b 100644 --- a/src/test/kotlin/net/leanix/githubagent/services/GitHubEnterpriseServiceTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/services/GitHubEnterpriseServiceTest.kt @@ -29,7 +29,7 @@ class GitHubEnterpriseServiceTest { val githubApp = GitHubAppResponse( slug = "validApp", permissions = mapOf("administration" to "read", "contents" to "read", "metadata" to "read"), - events = listOf("label", "public", "repository", "push", "installation") + events = listOf("label", "public", "repository", "push", "installation"), ) every { githubClient.getApp(any()) } returns githubApp @@ -49,7 +49,7 @@ class GitHubEnterpriseServiceTest { val response = GitHubAppResponse( slug = "validApp", permissions = mapOf("administration" to "read", "contents" to "read", "metadata" to "read"), - events = listOf("label", "public", "repository", "push", "installation") + events = listOf("label", "public", "repository", "push", "installation"), ) assertDoesNotThrow { @@ -62,11 +62,11 @@ class GitHubEnterpriseServiceTest { val response = GitHubAppResponse( slug = "validApp", permissions = mapOf("administration" to "read", "contents" to "read"), - events = listOf("label", "public", "repository") + events = listOf("label", "public", "repository"), ) assertThrows( - GitHubAppInsufficientPermissionsException::class.java + GitHubAppInsufficientPermissionsException::class.java, ) { service.validateEnabledPermissionsAndEvents(GITHUB_APP_LABEL, response.permissions, response.events) } } @@ -75,11 +75,11 @@ class GitHubEnterpriseServiceTest { val response = GitHubAppResponse( slug = "validApp", permissions = mapOf("administration" to "read", "contents" to "read", "metadata" to "read"), - events = listOf("label", "public") + events = listOf("label", "public"), ) assertThrows( - GitHubAppInsufficientPermissionsException::class.java + GitHubAppInsufficientPermissionsException::class.java, ) { service.validateEnabledPermissionsAndEvents(GITHUB_APP_LABEL, response.permissions, response.events) } } } diff --git a/src/test/kotlin/net/leanix/githubagent/services/GitHubScanningServiceTest.kt b/src/test/kotlin/net/leanix/githubagent/services/GitHubScanningServiceTest.kt index 39927c2..ac1d020 100644 --- a/src/test/kotlin/net/leanix/githubagent/services/GitHubScanningServiceTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/services/GitHubScanningServiceTest.kt @@ -46,7 +46,7 @@ class GitHubScanningServiceTest { syncLogService, rateLimitHandler, gitHubEnterpriseService, - gitHubAPIService + gitHubAPIService, ) private val runId = UUID.randomUUID() @@ -57,7 +57,7 @@ class GitHubScanningServiceTest { fun setup() { every { cachingService.get(any()) } returns "value" every { gitHubAPIService.getPaginatedInstallations(any()) } returns listOf( - Installation(1, Account("testInstallation"), permissions, events) + Installation(1, Account("testInstallation"), permissions, events), ) every { gitHubClient.createInstallationToken(1, any()) } returns InstallationTokenResponse("testToken", "2024-01-01T00:00:00Z", mapOf(), "all") @@ -66,7 +66,7 @@ class GitHubScanningServiceTest { every { gitHubGraphQLService.getRepositories(any(), any()) } returns PagedRepositories( repositories = emptyList(), hasNextPage = false, - cursor = null + cursor = null, ) every { cachingService.remove(any()) } returns Unit every { gitHubAuthenticationService.generateAndCacheInstallationTokens(any(), any()) } returns Unit @@ -84,7 +84,7 @@ class GitHubScanningServiceTest { verify { webSocketService.sendMessage(eq("$runId/organizations"), any()) } verify { syncLogService.sendInfoLog( - "The connector found 0 organizations with GitHub application installed, out of possible 1." + "The connector found 0 organizations with GitHub application installed, out of possible 1.", ) } } @@ -126,10 +126,10 @@ class GitHubScanningServiceTest { updatedAt = "2024-01-01T00:00:00Z", languages = listOf("Kotlin", "Java"), topics = listOf("test", "example"), - ) + ), ), hasNextPage = false, - cursor = null + cursor = null, ) every { gitHubClient.searchManifestFiles(any(), any()) } returns GitHubSearchResponse(0, emptyList()) gitHubScanningService.scanGitHubResources() @@ -154,10 +154,10 @@ class GitHubScanningServiceTest { updatedAt = "2024-01-01T00:00:00Z", languages = listOf("Kotlin", "Java"), topics = listOf("test", "example"), - ) + ), ), hasNextPage = false, - cursor = null + cursor = null, ) every { gitHubClient.searchManifestFiles(any(), any()) } returns GitHubSearchResponse( 1, @@ -167,11 +167,11 @@ class GitHubScanningServiceTest { path = "dir/leanix.yaml", repository = RepositoryItemResponse( name = "TestRepo", - fullName = "testOrg/TestRepo" + fullName = "testOrg/TestRepo", ), - url = "http://url" - ) - ) + url = "http://url", + ), + ), ) every { gitHubGraphQLService.getManifestFileContent(any(), any(), "dir/leanix.yaml", any()) } returns "content" @@ -205,10 +205,10 @@ class GitHubScanningServiceTest { updatedAt = "2024-01-01T00:00:00Z", languages = listOf("Kotlin", "Java"), topics = listOf("test", "example"), - ) + ), ), hasNextPage = false, - cursor = null + cursor = null, ) every { gitHubClient.searchManifestFiles(any(), any()) } returns GitHubSearchResponse( 1, @@ -218,11 +218,11 @@ class GitHubScanningServiceTest { path = "dir/leanix.yaml", repository = RepositoryItemResponse( name = "TestRepo", - fullName = "testOrg/TestRepo" + fullName = "testOrg/TestRepo", ), - url = "http://url" - ) - ) + url = "http://url", + ), + ), ) every { gitHubGraphQLService.getManifestFileContent(any(), any(), "dir/leanix.yaml", any()) } returns "content" @@ -233,7 +233,7 @@ class GitHubScanningServiceTest { verify(exactly = 0) { webSocketService.sendMessage(eq("$runId/manifestFiles"), any()) } verify(exactly = 0) { syncLogService.sendInfoLog("Scanning repository TestRepo for manifest files.") } verify( - exactly = 0 + exactly = 0, ) { syncLogService.sendInfoLog("Fetched manifest file 'dir/leanix.yaml' from repository 'TestRepo'.") } verify(exactly = 0) { syncLogService.sendInfoLog("Found 1 manifest files in repository TestRepo.") } verify { syncLogService.sendInfoLog("Finished initial full scan for organization testInstallation.") } @@ -258,10 +258,10 @@ class GitHubScanningServiceTest { updatedAt = "2024-01-01T00:00:00Z", languages = listOf("Kotlin", "Java"), topics = listOf("test", "example"), - ) + ), ), hasNextPage = false, - cursor = null + cursor = null, ) every { gitHubClient.searchManifestFiles(any(), any()) } returns GitHubSearchResponse( 1, @@ -271,11 +271,11 @@ class GitHubScanningServiceTest { path = MANIFEST_FILE_NAME, repository = RepositoryItemResponse( name = "TestRepo", - fullName = "testOrg/TestRepo" + fullName = "testOrg/TestRepo", ), - url = "http://url" - ) - ) + url = "http://url", + ), + ), ) every { gitHubGraphQLService.getManifestFileContent(any(), any(), MANIFEST_FILE_NAME, any()) } returns "content" val fileSlot = slot() @@ -306,10 +306,10 @@ class GitHubScanningServiceTest { updatedAt = "2024-01-01T00:00:00Z", languages = listOf("Kotlin", "Java"), topics = listOf("test", "example"), - ) + ), ), hasNextPage = false, - cursor = null + cursor = null, ) every { gitHubClient.searchManifestFiles(any(), any()) } returns GitHubSearchResponse( 1, @@ -319,29 +319,29 @@ class GitHubScanningServiceTest { path = MANIFEST_FILE_NAME, repository = RepositoryItemResponse( name = "TestRepo", - fullName = "testOrg/TestRepo" + fullName = "testOrg/TestRepo", ), - url = "http://url" + url = "http://url", ), ItemResponse( name = MANIFEST_FILE_NAME, path = "a/$MANIFEST_FILE_NAME", repository = RepositoryItemResponse( name = "TestRepo", - fullName = "testOrg/TestRepo" + fullName = "testOrg/TestRepo", ), - url = "http://url" + url = "http://url", ), ItemResponse( name = "a-$MANIFEST_FILE_NAME", path = "a/a-$MANIFEST_FILE_NAME", repository = RepositoryItemResponse( name = "TestRepo", - fullName = "testOrg/TestRepo" + fullName = "testOrg/TestRepo", ), - url = "http://url" - ) - ) + url = "http://url", + ), + ), ) every { gitHubGraphQLService.getManifestFileContent(any(), any(), MANIFEST_FILE_NAME, any()) } returns "content" every { @@ -375,10 +375,10 @@ class GitHubScanningServiceTest { updatedAt = "2024-01-01T00:00:00Z", languages = listOf("Kotlin", "Java"), topics = listOf("test", "example"), - ) + ), ), hasNextPage = false, - cursor = null + cursor = null, ) every { gitHubClient.searchManifestFiles(any(), any()) } returns GitHubSearchResponse( 1, @@ -388,29 +388,29 @@ class GitHubScanningServiceTest { path = "leanIX.yaml", repository = RepositoryItemResponse( name = "TestRepo", - fullName = "testOrg/TestRepo" + fullName = "testOrg/TestRepo", ), - url = "http://url" + url = "http://url", ), ItemResponse( name = "lEAnIX.yaml", path = "a/lEAnIX.yaml", repository = RepositoryItemResponse( name = "TestRepo", - fullName = "testOrg/TestRepo" + fullName = "testOrg/TestRepo", ), - url = "http://url" + url = "http://url", ), ItemResponse( name = MANIFEST_FILE_NAME, path = "b/$MANIFEST_FILE_NAME", repository = RepositoryItemResponse( name = "TestRepo", - fullName = "testOrg/TestRepo" + fullName = "testOrg/TestRepo", ), - url = "http://url" - ) - ) + url = "http://url", + ), + ), ) every { gitHubGraphQLService.getManifestFileContent(any(), any(), "b/leanix.yaml", any()) @@ -435,7 +435,7 @@ class GitHubScanningServiceTest { every { gitHubAPIService.getPaginatedInstallations(any()) } returns listOf( Installation(1, Account("testInstallation1"), mapOf(), listOf()), Installation(2, Account("testInstallation2"), permissions, events), - Installation(3, Account("testInstallation3"), permissions, events) + Installation(3, Account("testInstallation3"), permissions, events), ) gitHubScanningService.scanGitHubResources() verify { webSocketService.sendMessage(eq("$runId/organizations"), any()) } @@ -443,7 +443,7 @@ class GitHubScanningServiceTest { syncLogService.sendErrorLog( "Failed to scan organization testInstallation1. Installation missing " + "the following permissions: [administration, contents, metadata], " + - "and the following events: [label, public, repository, push]" + "and the following events: [label, public, repository, push]", ) } verify { syncLogService.sendInfoLog("Finished initial full scan for organization testInstallation2.") } diff --git a/src/test/kotlin/net/leanix/githubagent/services/GitHubStartServiceTest.kt b/src/test/kotlin/net/leanix/githubagent/services/GitHubStartServiceTest.kt index acd9eb1..d359ff3 100644 --- a/src/test/kotlin/net/leanix/githubagent/services/GitHubStartServiceTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/services/GitHubStartServiceTest.kt @@ -56,7 +56,9 @@ class GitHubStartServiceTest { val gitHubAppName = "appName" every { gitHubEnterpriseService.getGitHubApp("jwt") } returns GitHubAppResponse( - gitHubAppName, mapOf(), listOf() + gitHubAppName, + mapOf(), + listOf(), ) gitHubStartService.startAgent(ConnectionEstablishedEvent()) diff --git a/src/test/kotlin/net/leanix/githubagent/services/InstallationGetHandlerTest.kt b/src/test/kotlin/net/leanix/githubagent/services/InstallationGetHandlerTest.kt index ad73879..3296325 100644 --- a/src/test/kotlin/net/leanix/githubagent/services/InstallationGetHandlerTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/services/InstallationGetHandlerTest.kt @@ -35,7 +35,7 @@ class InstallationGetHandlerTest { val installationRequestDTO = InstallationRequestDTO( 30, - Account("test-org") + Account("test-org"), ) installationGetHandler.fetchAndSendOrganisationData(installationRequestDTO) diff --git a/src/test/kotlin/net/leanix/githubagent/services/LeanIXAuthServiceTest.kt b/src/test/kotlin/net/leanix/githubagent/services/LeanIXAuthServiceTest.kt index 5495461..64dc4d1 100644 --- a/src/test/kotlin/net/leanix/githubagent/services/LeanIXAuthServiceTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/services/LeanIXAuthServiceTest.kt @@ -25,7 +25,7 @@ class LeanIXAuthServiceTest { false, "valid_access_token", "access_token", - 3600 + 3600, ) } diff --git a/src/test/kotlin/net/leanix/githubagent/services/WebhookEventServiceTest.kt b/src/test/kotlin/net/leanix/githubagent/services/WebhookEventServiceTest.kt index 1b66172..6df0b60 100644 --- a/src/test/kotlin/net/leanix/githubagent/services/WebhookEventServiceTest.kt +++ b/src/test/kotlin/net/leanix/githubagent/services/WebhookEventServiceTest.kt @@ -86,8 +86,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.MODIFIED, "content", - "" - ) + "", + ), ) } } @@ -119,8 +119,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.MODIFIED, "content", - "" - ) + "", + ), ) } @@ -131,8 +131,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.MODIFIED, "content", - "tree/main/a" - ) + "tree/main/a", + ), ) } } @@ -164,8 +164,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.MODIFIED, "content", - "tree/main/b" - ) + "tree/main/b", + ), ) } @@ -176,8 +176,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.MODIFIED, "content", - "tree/main/a" - ) + "tree/main/a", + ), ) } @@ -188,8 +188,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.MODIFIED, "content", - "" - ) + "", + ), ) } } @@ -274,8 +274,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.REMOVED, null, - "tree/main/a/b/c" - ) + "tree/main/a/b/c", + ), ) } } @@ -307,8 +307,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.ADDED, "content", - "tree/main/a/b/c" - ) + "tree/main/a/b/c", + ), ) } } @@ -340,8 +340,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.ADDED, "content", - "tree/main/custom/path/added1" - ) + "tree/main/custom/path/added1", + ), ) webSocketService.sendMessage( "/events/manifestFile", @@ -349,8 +349,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.ADDED, "content", - "tree/main/custom/path/added2" - ) + "tree/main/custom/path/added2", + ), ) webSocketService.sendMessage( "/events/manifestFile", @@ -358,8 +358,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.MODIFIED, "content", - "tree/main/custom/path/modified" - ) + "tree/main/custom/path/modified", + ), ) } } @@ -391,8 +391,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.ADDED, "content", - "tree/main/custom/path/added2" - ) + "tree/main/custom/path/added2", + ), ) } @@ -403,8 +403,8 @@ class WebhookEventServiceTest { "owner/repo", ManifestFileAction.ADDED, "content", - "tree/main/custom/path/added1/$UNSUPPORTED_MANIFEST_EXTENSION" - ) + "tree/main/custom/path/added1/$UNSUPPORTED_MANIFEST_EXTENSION", + ), ) } } @@ -429,12 +429,10 @@ class WebhookEventServiceTest { } } - fun createItemResponse(repoName: String, organization: String): ItemResponse { - return ItemResponse( - MANIFEST_FILE_NAME, - "$organization/$repoName/$MANIFEST_FILE_NAME", - RepositoryItemResponse(repoName, repoName), - "url" - ) - } + fun createItemResponse(repoName: String, organization: String): ItemResponse = ItemResponse( + MANIFEST_FILE_NAME, + "$organization/$repoName/$MANIFEST_FILE_NAME", + RepositoryItemResponse(repoName, repoName), + "url", + ) }