Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/cid 2744/get list of organisations #7

Merged
merged 5 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/main/kotlin/net/leanix/githubagent/client/GitHubClient.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
package net.leanix.githubagent.client

import net.leanix.githubagent.dto.GitHubAppResponse
import net.leanix.githubagent.dto.Installation
import net.leanix.githubagent.dto.InstallationTokenResponse
import net.leanix.githubagent.dto.Organization
import net.leanix.githubagent.dto.Repository
import org.springframework.cloud.openfeign.FeignClient
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestHeader

@FeignClient(name = "githubClient", url = "\${github-enterprise.baseUrl}")
Expand All @@ -13,4 +19,22 @@ interface GitHubClient {
@RequestHeader("Authorization") jwt: String,
@RequestHeader("Accept") accept: String = "application/vnd.github.v3+json"
): GitHubAppResponse

@GetMapping("/api/v3/app/installations")
fun getInstallations(@RequestHeader("Authorization") jwt: String): List<Installation>

@PostMapping("/api/v3/app/installations/{installationId}/access_tokens")
fun createInstallationToken(
@PathVariable("installationId") installationId: Long,
@RequestHeader("Authorization") jwt: String
): InstallationTokenResponse

@GetMapping("/api/v3/organizations")
fun getOrganizations(@RequestHeader("Authorization") token: String): List<Organization>

@GetMapping("/api/v3/orgs/{org}/repos")
fun getRepositories(
@PathVariable("org") org: String,
@RequestHeader("Authorization") token: String
): List<Repository>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package net.leanix.githubagent.dto

import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty

@JsonIgnoreProperties(ignoreUnknown = true)
data class InstallationTokenResponse(
@JsonProperty("token") val token: String,
@JsonProperty("expires_at") val expiresAt: String,
@JsonProperty("permissions") val permissions: Map<String, String>,
@JsonProperty("repository_selection") val repositorySelection: String
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class Installation(
@JsonProperty("id") val id: Long,
@JsonProperty("account") val account: Account
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class Account(
@JsonProperty("login") val login: String
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class Organization(
@JsonProperty("login") val login: String,
@JsonProperty("id") val id: Int,
)

@JsonIgnoreProperties(ignoreUnknown = true)
data class Repository(
@JsonProperty("id") val id: String,
@JsonProperty("name") val name: String,
@JsonProperty("full_name") val fullName: Boolean,
@JsonProperty("owner") val owner: Organization,
@JsonProperty("topics") val topics: List<String>
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package net.leanix.githubagent.dto

class OrganizationDto(
val id: Int,
val name: String,
val installed: Boolean
)
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ class GitHubEnterpriseConfigurationMissingException(properties: String) : Runtim
class GitHubAppInsufficientPermissionsException(message: String) : RuntimeException(message)
class FailedToCreateJWTException(message: String) : RuntimeException(message)
class UnableToConnectToGitHubEnterpriseException(message: String) : RuntimeException(message)
class JwtTokenNotFound : RuntimeException("JWT token not found")
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package net.leanix.githubagent.runners

import net.leanix.githubagent.services.GitHubAuthenticationService
import net.leanix.githubagent.services.GitHubScanningService
import net.leanix.githubagent.services.WebSocketService
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
Expand All @@ -11,11 +12,13 @@ import org.springframework.stereotype.Component
@Profile("!test")
class PostStartupRunner(
private val githubAuthenticationService: GitHubAuthenticationService,
private val webSocketService: WebSocketService
private val webSocketService: WebSocketService,
private val gitHubScanningService: GitHubScanningService
) : ApplicationRunner {

override fun run(args: ApplicationArguments?) {
githubAuthenticationService.generateJwtToken()
webSocketService.initSession()
gitHubScanningService.scanGitHubResources()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package net.leanix.githubagent.services

import net.leanix.githubagent.client.GitHubClient
import net.leanix.githubagent.dto.Installation
import net.leanix.githubagent.dto.OrganizationDto
import net.leanix.githubagent.exceptions.JwtTokenNotFound
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service

@Service
class GitHubScanningService(
private val gitHubClient: GitHubClient,
private val cachingService: CachingService,
private val webSocketService: WebSocketService
) {
private val logger = LoggerFactory.getLogger(GitHubScanningService::class.java)

fun scanGitHubResources() {
runCatching {
val jwtToken = cachingService.get("jwtToken") ?: throw JwtTokenNotFound()
val installations = getInstallations(jwtToken.toString())
val organizations = generateOrganizations(installations)
webSocketService.sendMessage("/app/ghe/organizations", organizations)
}.onFailure {
logger.error("Error while scanning GitHub resources")
throw it
}
}

private fun getInstallations(jwtToken: String): List<Installation> {
val installations = gitHubClient.getInstallations("Bearer $jwtToken")
generateAndCacheInstallationTokens(installations, jwtToken)
return installations
}

private fun generateAndCacheInstallationTokens(
installations: List<Installation>,
jwtToken: String
) {
installations.forEach { installation ->
val installationToken = gitHubClient.createInstallationToken(installation.id, "Bearer $jwtToken").token
cachingService.set("installationToken:${installation.id}", installationToken, 3600L)
}
}

private fun generateOrganizations(
installations: List<Installation>
): List<OrganizationDto> {
val installationToken = cachingService.get("installationToken:${installations.first().id}")
val organizations = gitHubClient.getOrganizations("Bearer $installationToken")
return organizations.map { organization ->
if (installations.find { it.account.login == organization.login } != null) {
OrganizationDto(organization.id, organization.login, true)
} else {
OrganizationDto(organization.id, organization.login, false)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,8 @@ class WebSocketService(
logger.info("init session")
stompSession = webSocketClientConfig.initSession()
}

fun sendMessage(topic: String, data: Any) {
stompSession!!.send(topic, data)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package net.leanix.githubagent.services

import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import net.leanix.githubagent.client.GitHubClient
import net.leanix.githubagent.dto.Account
import net.leanix.githubagent.dto.Installation
import net.leanix.githubagent.dto.InstallationTokenResponse
import net.leanix.githubagent.dto.Organization
import net.leanix.githubagent.exceptions.JwtTokenNotFound
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

class GitHubScanningServiceTest {

private val gitHubClient = mockk<GitHubClient>()
private val cachingService = mockk<CachingService>()
private val webSocketService = mockk<WebSocketService>(relaxUnitFun = true)
private val gitHubScanningService = GitHubScanningService(gitHubClient, cachingService, webSocketService)

@BeforeEach
fun setup() {
every { cachingService.get(any()) } returns "value"
every { gitHubClient.getInstallations(any()) } returns listOf(
Installation(1, Account("testInstallation"))
)
every { gitHubClient.createInstallationToken(1, any()) } returns
InstallationTokenResponse("testToken", "2024-01-01T00:00:00Z", mapOf(), "all")
every { cachingService.set(any(), any(), any()) } returns Unit
every { gitHubClient.getOrganizations(any()) } returns listOf(Organization("testOrganization", 1))
}

@Test
fun `scanGitHubResources should send organizations over WebSocket`() {
gitHubScanningService.scanGitHubResources()
verify { webSocketService.sendMessage("/app/ghe/organizations", any()) }
}

@Test
fun `scanGitHubResources should throw JwtTokenNotFound when jwtToken is expired`() {
every { cachingService.get("jwtToken") } returns null
assertThrows<JwtTokenNotFound> {
gitHubScanningService.scanGitHubResources()
}
}
}
Loading