|
| 1 | +package com.swisscom.health.des.cdr.client.config |
| 2 | + |
| 3 | +import com.nimbusds.oauth2.sdk.AccessTokenResponse |
| 4 | +import com.nimbusds.oauth2.sdk.AuthorizationGrant |
| 5 | +import com.nimbusds.oauth2.sdk.ClientCredentialsGrant |
| 6 | +import com.nimbusds.oauth2.sdk.Scope |
| 7 | +import com.nimbusds.oauth2.sdk.TokenRequest |
| 8 | +import com.nimbusds.oauth2.sdk.TokenResponse |
| 9 | +import com.nimbusds.oauth2.sdk.auth.ClientAuthentication |
| 10 | +import com.nimbusds.oauth2.sdk.auth.ClientSecretPost |
| 11 | +import com.nimbusds.oauth2.sdk.auth.Secret |
| 12 | +import com.nimbusds.oauth2.sdk.http.HTTPResponse |
| 13 | +import com.nimbusds.oauth2.sdk.id.ClientID |
| 14 | +import com.swisscom.health.des.cdr.client.config.OAuth2AuthNService.AuthNState.AUTHENTICATED |
| 15 | +import com.swisscom.health.des.cdr.client.config.OAuth2AuthNService.AuthNState.DENIED |
| 16 | +import com.swisscom.health.des.cdr.client.config.OAuth2AuthNService.AuthNState.RETRYABLE_FAILURE |
| 17 | +import com.swisscom.health.des.cdr.client.config.OAuth2AuthNService.AuthNState.UNAUTHENTICATED |
| 18 | +import org.springframework.retry.support.RetryTemplate |
| 19 | +import org.springframework.stereotype.Service |
| 20 | +import java.io.IOException |
| 21 | +import java.net.URI |
| 22 | +import java.net.URL |
| 23 | +import kotlin.time.Clock |
| 24 | +import kotlin.time.ExperimentalTime |
| 25 | + |
| 26 | +@Service |
| 27 | +internal class OAuth2AuthNService @OptIn(ExperimentalTime::class) constructor( |
| 28 | + private val config: CdrClientConfig, |
| 29 | + private val retryIoErrors: RetryTemplate, |
| 30 | + private val clock: Clock = Clock.System, |
| 31 | +) { |
| 32 | + |
| 33 | + private var accessTokenAuthNResponse: AuthNResponse = AuthNResponse.NotAuthenticated |
| 34 | + |
| 35 | + internal enum class AuthNState { |
| 36 | + AUTHENTICATED, |
| 37 | + UNAUTHENTICATED, |
| 38 | + RETRYABLE_FAILURE, |
| 39 | + FAILED, |
| 40 | + DENIED; |
| 41 | + } |
| 42 | + |
| 43 | + internal sealed interface AuthNResponse { |
| 44 | + data class Success(val response: AccessTokenResponse) : AuthNResponse |
| 45 | + data class Deny(val error: WrongCredentialsException) : AuthNResponse |
| 46 | + data class RetryableFailure(val error: IOException) : AuthNResponse |
| 47 | + data class Failed(val error: IllegalStateException) : AuthNResponse |
| 48 | + object NotAuthenticated : AuthNResponse |
| 49 | + } |
| 50 | + |
| 51 | + @Synchronized |
| 52 | + internal fun currentAuthNState(): AuthNState = |
| 53 | + when (accessTokenAuthNResponse) { |
| 54 | + is AuthNResponse.Success -> AUTHENTICATED |
| 55 | + is AuthNResponse.RetryableFailure -> RETRYABLE_FAILURE |
| 56 | + is AuthNResponse.Failed -> AuthNState.FAILED |
| 57 | + is AuthNResponse.Deny -> DENIED |
| 58 | + is AuthNResponse.NotAuthenticated -> UNAUTHENTICATED |
| 59 | + } |
| 60 | + |
| 61 | + @OptIn(ExperimentalTime::class) |
| 62 | + // could be improved with more fine-grained locking to avoid blocking all threads while a valid token is available and no renewal is required; |
| 63 | + // but we have only five threads for uploads, one for downloads (all of which are mostly waiting for IO), and one for the service status check, |
| 64 | + // so lock contention should be minimal |
| 65 | + @Synchronized |
| 66 | + internal fun getAccessToken(): AuthNResponse = |
| 67 | + when (val currentTokenResponse = accessTokenAuthNResponse) { |
| 68 | + is AuthNResponse.NotAuthenticated, is AuthNResponse.RetryableFailure -> { |
| 69 | + getNewAccessToken(config.idpCredentials, config.idpEndpoint) |
| 70 | + } |
| 71 | + |
| 72 | + is AuthNResponse.Deny, is AuthNResponse.Failed -> { |
| 73 | + currentTokenResponse |
| 74 | + } |
| 75 | + |
| 76 | + is AuthNResponse.Success -> { |
| 77 | + val expiresOn = currentTokenResponse.response.customParameters["expires_on"] as Long? |
| 78 | + if (expiresOn == null || clock.now().epochSeconds > expiresOn) { |
| 79 | + getNewAccessToken(config.idpCredentials, config.idpEndpoint) |
| 80 | + } else { |
| 81 | + currentTokenResponse |
| 82 | + } |
| 83 | + } |
| 84 | + }.also { |
| 85 | + accessTokenAuthNResponse = it |
| 86 | + } |
| 87 | + |
| 88 | + private fun getNewAccessToken(idpCredentials: IdpCredentials, idpEndpoint: URL): AuthNResponse { |
| 89 | + val clientGrant: AuthorizationGrant = ClientCredentialsGrant() |
| 90 | + val clientID = ClientID(idpCredentials.clientId.id) |
| 91 | + val clientSecret = Secret(idpCredentials.clientSecret.value) |
| 92 | + // `ClientSecretBasic` is another option; it works in production, but our mock IdP is not set up to get the client id from the Basic Auth header, |
| 93 | + // instead we use the form parameter `client_id` |
| 94 | + val clientAuth: ClientAuthentication = ClientSecretPost(clientID, clientSecret) |
| 95 | + val scope = Scope(idpCredentials.scope.scope) |
| 96 | + val tokenEndpoint: URI = idpEndpoint.toURI() |
| 97 | + val request = TokenRequest(tokenEndpoint, clientAuth, clientGrant, scope) |
| 98 | + |
| 99 | + val authNResponse: AuthNResponse = |
| 100 | + runCatching { |
| 101 | + retryIoErrors.execute<HTTPResponse, Throwable> { _ -> |
| 102 | + request.toHTTPRequest().send() |
| 103 | + }.run { TokenResponse.parse(this) } |
| 104 | + }.fold( |
| 105 | + onSuccess = { httpResponse: TokenResponse -> |
| 106 | + if (httpResponse.indicatesSuccess()) { |
| 107 | + AuthNResponse.Success(httpResponse.toSuccessResponse()) |
| 108 | + } else { |
| 109 | + AuthNResponse.Deny( |
| 110 | + WrongCredentialsException( |
| 111 | + "Failed to login; client id: '${idpCredentials.clientId}'; IdP endpoint: '$idpEndpoint'; message: '${ |
| 112 | + httpResponse.toErrorResponse().toJSONObject() |
| 113 | + }'" |
| 114 | + ) |
| 115 | + ) |
| 116 | + } |
| 117 | + }, |
| 118 | + onFailure = { t -> |
| 119 | + when (t) { |
| 120 | + is IOException -> AuthNResponse.RetryableFailure(t) |
| 121 | + else -> AuthNResponse.Failed( |
| 122 | + IllegalStateException( |
| 123 | + "Failed to login; client id: '${idpCredentials.clientId}'; IdP endpoint: '$idpEndpoint'; root cause: '$t'", |
| 124 | + t, |
| 125 | + ) |
| 126 | + ) |
| 127 | + } |
| 128 | + } |
| 129 | + ) |
| 130 | + |
| 131 | + return authNResponse |
| 132 | + } |
| 133 | +} |
0 commit comments