Skip to content

Commit

Permalink
Merge pull request #500 from navikt/update_gradle
Browse files Browse the repository at this point in the history
Update dependencies
  • Loading branch information
ybelMekk authored Jul 3, 2023
2 parents de683dd + 5cdab51 commit ac59f47
Show file tree
Hide file tree
Showing 75 changed files with 430 additions and 429 deletions.
15 changes: 8 additions & 7 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask
val assertjVersion = "3.24.2"
val kotlinLoggingVersion = "3.0.5"
val logbackVersion = "1.4.8"
val nimbusSdkVersion = "10.9.2"
val nimbusSdkVersion = "10.10.1"
val mockWebServerVersion = "4.11.0"
val jacksonVersion = "2.15.2"
val nettyVersion = "4.1.94.Final"
Expand All @@ -15,7 +15,7 @@ val kotestVersion = "5.6.2"
val bouncyCastleVersion = "1.70"
val springBootVersion = "2.7.5"
val reactorTestVersion = "3.4.24"
val ktorVersion = "2.3.1"
val ktorVersion = "2.3.2"

val mavenRepoBaseUrl = "https://oss.sonatype.org"
val mainClassKt = "no.nav.security.mock.oauth2.StandaloneMockOAuth2ServerKt"
Expand All @@ -26,8 +26,8 @@ plugins {
id("se.patrikerdes.use-latest-versions") version "0.2.18"
id("com.github.ben-manes.versions") version "0.47.0"
id("org.jmailen.kotlinter") version "3.15.0"
id("com.google.cloud.tools.jib") version "3.3.1"
id("com.github.johnrengelman.shadow") version "7.1.2"
id("com.google.cloud.tools.jib") version "3.3.2"
id("com.github.johnrengelman.shadow") version "8.1.1"
id("net.researchgate.release") version "3.0.2"
id("io.github.gradle-nexus.publish-plugin") version "1.3.0"
id("org.jetbrains.dokka") version "1.8.20"
Expand All @@ -37,7 +37,7 @@ plugins {
}

application {
mainClassName = mainClassKt
mainClass.set(mainClassKt)
}

java {
Expand Down Expand Up @@ -200,7 +200,7 @@ jib {
}

fun isNonStable(version: String): Boolean {
val stableKeyword = listOf("RELEASE", "FINAL", "GA").any { version.toUpperCase().contains(it) }
val stableKeyword = listOf("RELEASE", "FINAL", "GA").any { version.uppercase().contains(it) }
val regex = "^[0-9,.v-]+(-r)?$".toRegex()
val isStable = stableKeyword || regex.matches(version)
return isStable.not()
Expand Down Expand Up @@ -259,6 +259,7 @@ tasks {
}

withType<Test> {
jvmArgs("--add-opens=java.base/java.util=ALL-UNNAMED")
useJUnitPlatform()
}

Expand All @@ -273,6 +274,6 @@ tasks {
}

withType<Wrapper> {
gradleVersion = "7.4.2"
gradleVersion = "8.2"
}
}
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
18 changes: 9 additions & 9 deletions src/main/kotlin/no/nav/security/mock/oauth2/MockOAuth2Server.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ private val log = KotlinLogging.logger { }
@Suppress("unused", "MemberVisibilityCanBePrivate")
open class MockOAuth2Server(
val config: OAuth2Config = OAuth2Config(),
vararg additionalRoutes: Route
vararg additionalRoutes: Route,
) {
constructor(vararg additionalRoutes: Route) : this(config = OAuth2Config(), additionalRoutes = additionalRoutes)
constructor(config: OAuth2Config) : this(config = config, additionalRoutes = emptyArray())
Expand All @@ -51,7 +51,7 @@ open class MockOAuth2Server(
private val defaultRequestHandler: OAuth2HttpRequestHandler = OAuth2HttpRequestHandler(config)
private val router: RequestHandler = routes(
*additionalRoutes,
defaultRequestHandler.authorizationServer
defaultRequestHandler.authorizationServer,
)

/**
Expand Down Expand Up @@ -221,7 +221,7 @@ open class MockOAuth2Server(
val tokenRequest = TokenRequest(
uri.toUri(),
ClientSecretBasic(ClientID(clientId), Secret("secret")),
AuthorizationCodeGrant(AuthorizationCode("123"), URI.create("http://localhost"))
AuthorizationCodeGrant(AuthorizationCode("123"), URI.create("http://localhost")),
)
return config.tokenProvider.accessToken(tokenRequest, issuerUrl, tokenCallback, null)
}
Expand All @@ -237,7 +237,7 @@ open class MockOAuth2Server(
subject: String = UUID.randomUUID().toString(),
audience: String? = "default",
claims: Map<String, Any> = emptyMap(),
expiry: Long = 3600
expiry: Long = 3600,
): SignedJWT = issueToken(
issuerId,
"default",
Expand All @@ -247,8 +247,8 @@ open class MockOAuth2Server(
JOSEObjectType.JWT.type,
audience?.let { listOf(it) },
claims,
expiry
)
expiry,
),
)

/**
Expand All @@ -267,8 +267,8 @@ open class MockOAuth2Server(
jwtClaimsSet,
DefaultOAuth2TokenCallback(
audience = jwtClaimsSet.audience,
expiry = expiry.toMillis()
)
expiry = expiry.toMillis(),
),
)
}

Expand Down Expand Up @@ -306,7 +306,7 @@ internal fun Map<String, Any>.toJwtClaimsSet(): JWTClaimsSet =

fun <R> withMockOAuth2Server(
config: OAuth2Config = OAuth2Config(),
test: MockOAuth2Server.() -> R
test: MockOAuth2Server.() -> R,
): R {
val server = MockOAuth2Server(config)
server.start()
Expand Down
16 changes: 8 additions & 8 deletions src/main/kotlin/no/nav/security/mock/oauth2/OAuth2Config.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,18 @@ data class OAuth2Config @JvmOverloads constructor(
@JsonDeserialize(contentAs = RequestMappingTokenCallback::class)
val tokenCallbacks: Set<OAuth2TokenCallback> = emptySet(),
@JsonDeserialize(using = OAuth2HttpServerDeserializer::class)
val httpServer: OAuth2HttpServer = MockWebServerWrapper()
val httpServer: OAuth2HttpServer = MockWebServerWrapper(),
) {

class OAuth2TokenProviderDeserializer : JsonDeserializer<OAuth2TokenProvider>() {

data class ProviderConfig(
val keyProvider: KeyProviderConfig?
val keyProvider: KeyProviderConfig?,
)

data class KeyProviderConfig(
val initialKeys: String?,
val algorithm: String
val algorithm: String,
)

override fun deserialize(p: JsonParser, ctxt: DeserializationContext?): OAuth2TokenProvider {
Expand All @@ -56,28 +56,28 @@ data class OAuth2Config @JvmOverloads constructor(
return OAuth2TokenProvider(
KeyProvider(
jwks,
config.keyProvider?.algorithm ?: JWSAlgorithm.RS256.name
)
config.keyProvider?.algorithm ?: JWSAlgorithm.RS256.name,
),
)
}
}

class OAuth2HttpServerDeserializer : JsonDeserializer<OAuth2HttpServer>() {
enum class ServerType {
MockWebServerWrapper,
NettyWrapper
NettyWrapper,
}

data class ServerConfig(
val type: ServerType,
val ssl: SslConfig? = null
val ssl: SslConfig? = null,
)

data class SslConfig(
val keyPassword: String = "",
val keystoreFile: File? = null,
val keystoreType: SslKeystore.KeyStoreType = SslKeystore.KeyStoreType.PKCS12,
val keystorePassword: String = ""
val keystorePassword: String = "",
) {
fun ssl() = Ssl(sslKeyStore())

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ object StandaloneConfig {
} else {
OAuth2Config(
interactiveLogin = true,
httpServer = NettyWrapper()
httpServer = NettyWrapper(),
)
}
}
Expand All @@ -49,7 +49,7 @@ fun main() {
oauth2Config(),
route("/isalive") {
OAuth2HttpResponse(status = 200, body = "alive and well")
}
},
).apply {
start(hostname(), port())
}
Expand Down
12 changes: 6 additions & 6 deletions src/main/kotlin/no/nav/security/mock/oauth2/debugger/Client.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package no.nav.security.mock.oauth2.debugger

import com.nimbusds.oauth2.sdk.OAuth2Error
import no.nav.security.mock.oauth2.OAuth2Exception
import no.nav.security.mock.oauth2.http.Ssl
import okhttp3.Credentials
import okhttp3.Headers
import okhttp3.HttpUrl
Expand All @@ -15,12 +16,11 @@ import java.nio.charset.StandardCharsets
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
import no.nav.security.mock.oauth2.http.Ssl

internal class TokenRequest(
val url: HttpUrl,
clientAuthentication: ClientAuthentication,
parameters: Map<String, String>
parameters: Map<String, String>,
) {
val headers = when (clientAuthentication.clientAuthMethod) {
ClientAuthentication.Method.CLIENT_SECRET_BASIC -> Headers.headersOf("Authorization", clientAuthentication.basic())
Expand Down Expand Up @@ -49,7 +49,7 @@ internal class TokenRequest(
internal data class ClientAuthentication(
val clientId: String,
val clientSecret: String,
val clientAuthMethod: Method
val clientAuthMethod: Method,
) {
fun form(): String = "client_id=${clientId.urlEncode()}&client_secret=${clientSecret.urlEncode()}"
fun basic(): String = Credentials.basic(clientId, clientSecret, StandardCharsets.UTF_8)
Expand All @@ -59,7 +59,7 @@ internal data class ClientAuthentication(
ClientAuthentication(
map.require("client_id"),
map.require("client_secret"),
Method.valueOf(map.require("client_auth_method"))
Method.valueOf(map.require("client_auth_method")),
)

private fun Map<String, String>.require(key: String): String =
Expand All @@ -68,7 +68,7 @@ internal data class ClientAuthentication(

enum class Method {
CLIENT_SECRET_POST,
CLIENT_SECRET_BASIC
CLIENT_SECRET_BASIC,
}
}

Expand All @@ -80,7 +80,7 @@ internal fun OkHttpClient.post(tokenRequest: TokenRequest): String =
.headers(tokenRequest.headers)
.url(tokenRequest.url)
.post(tokenRequest.body.toRequestBody("application/x-www-form-urlencoded".toMediaType()))
.build()
.build(),
).execute().body?.string() ?: throw RuntimeException("could not get response body from url=${tokenRequest.url}")

fun OkHttpClient.withSsl(ssl: Ssl, followRedirects: Boolean = false): OkHttpClient =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ class DebuggerRequestHandler(
exceptionHandler(handle(sessionManager))
debuggerForm(sessionManager)
debuggerCallback(sessionManager, ssl)
}
},
) : Route by route

private fun handle(sessionManager: SessionManager): ExceptionHandler = { request, error ->
OAuth2HttpResponse(
status = 500,
headers = Headers.headersOf("Content-Type", "text/html", "Set-Cookie", sessionManager.session(request).asCookie()),
body = templateMapper.debuggerErrorHtml(request.url.toDebuggerUrl(), error.stackTraceToString())
body = templateMapper.debuggerErrorHtml(request.url.toDebuggerUrl(), error.stackTraceToString()),
).also {
log.error("received exception when handling url=${request.url}", error)
}
Expand All @@ -55,7 +55,7 @@ private fun Route.Builder.debuggerForm(sessionManager: SessionManager) = apply {
"&response_mode=query" +
"&scope=openid+somescope" +
"&state=1234" +
"&nonce=5678"
"&nonce=5678",
).build()
html(templateMapper.debuggerFormHtml(url, "CLIENT_SECRET_BASIC"))
}
Expand Down Expand Up @@ -90,8 +90,8 @@ private fun Route.Builder.debuggerCallback(sessionManager: SessionManager, ssl:
"grant_type" to "authorization_code",
"code" to code,
"scope" to session["scope"].urlEncode(),
"redirect_uri" to session["redirect_uri"].urlEncode()
)
"redirect_uri" to session["redirect_uri"].urlEncode(),
),
)
val response = if (ssl != null) {
client.withSsl(ssl).post(request)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class SessionManager {

class Session(
private val encryptionKey: SecretKey,
val request: OAuth2HttpRequest
val request: OAuth2HttpRequest,
) {
val parameters: MutableMap<String, String> = getSessionCookie() ?.let { objectMapper.readValue(it) } ?: mutableMapOf()

Expand All @@ -41,7 +41,7 @@ class SessionManager {
private fun String.encrypt(key: SecretKey): String =
JWEObject(
JWEHeader(JWEAlgorithm.DIR, EncryptionMethod.A128GCM),
Payload(this)
Payload(this),
).also {
it.encrypt(DirectEncrypter(key))
}.serialize()
Expand All @@ -59,7 +59,7 @@ class SessionManager {
onFailure = { error ->
log.error("received exception when decrypting cookie", error)
null
}
},
)
companion object {
const val DEBUGGER_SESSION_COOKIE = "debugger-session"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ object OAuth2Endpoints {
USER_INFO,
INTROSPECT,
DEBUGGER,
DEBUGGER_CALLBACK
DEBUGGER_CALLBACK,
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ fun SignedJWT.verifySignatureAndIssuer(issuer: Issuer, jwkSet: JWKSet, jwsAlgori
jwtProcessor.jwsTypeVerifier = DefaultJOSEObjectTypeVerifier(JOSEObjectType("JWT"))
val keySelector: JWSKeySelector<SecurityContext?> = JWSVerificationKeySelector(
jwsAlgorithm,
ImmutableJWKSet(jwkSet)
ImmutableJWKSet(jwkSet),
)
jwtProcessor.jwsKeySelector = keySelector
jwtProcessor.jwtClaimsSetVerifier = DefaultJWTClaimsVerifier(
JWTClaimsSet.Builder().issuer(issuer.toString()).build(),
HashSet(listOf("sub", "iat", "exp"))
HashSet(listOf("sub", "iat", "exp")),
)
return jwtProcessor.process(this, null)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ private val jsonMapper: ObjectMapper = jacksonObjectMapper()

internal class AuthorizationCodeHandler(
private val tokenProvider: OAuth2TokenProvider,
private val refreshTokenManager: RefreshTokenManager
private val refreshTokenManager: RefreshTokenManager,
) : GrantHandler {

private val codeToAuthRequestCache: MutableMap<AuthorizationCode, AuthenticationRequest> = HashMap()
Expand All @@ -51,20 +51,20 @@ internal class AuthorizationCodeHandler(
null,
authenticationRequest.state,
null,
authenticationRequest.responseMode
authenticationRequest.responseMode,
)
}
else -> throw OAuth2Exception(
OAuth2Error.INVALID_GRANT,
"hybrid og implicit flow not supported (yet)."
"hybrid og implicit flow not supported (yet).",
)
}
}

override fun tokenResponse(
request: OAuth2HttpRequest,
issuerUrl: HttpUrl,
oAuth2TokenCallback: OAuth2TokenCallback
oAuth2TokenCallback: OAuth2TokenCallback,
): OAuth2TokenResponse {
val tokenRequest = request.asNimbusTokenRequest()
val code = tokenRequest.authorizationCode()
Expand All @@ -84,7 +84,7 @@ internal class AuthorizationCodeHandler(
accessToken = accessToken.serialize(),
refreshToken = refreshToken,
expiresIn = idToken.expiresIn(),
scope = scope
scope = scope,
)
}

Expand Down
Loading

0 comments on commit ac59f47

Please sign in to comment.