OAuthProviders.kt

package fr.codetics.ev_server.security

import fr.codetics.ev_server.core.ensure
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.env.Environment
import org.springframework.security.oauth2.client.registration.ClientRegistration
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository
import org.springframework.security.oauth2.core.AuthorizationGrantType
import org.springframework.security.oauth2.core.ClientAuthenticationMethod

/**
 * The configured sign-in providers. A provider whose client secret changes over time (Sign in with Apple)
 * is given as a supplier, so every sign-in reads the current secret.
 */
class ProviderRegistry(private val suppliers: List<() -> ClientRegistration>) :
    ClientRegistrationRepository, Iterable<ClientRegistration> {
    val registrations: List<ClientRegistration>
        get() = suppliers.map { it() }

    override fun findByRegistrationId(registrationId: String): ClientRegistration? {
        return registrations.find { registration -> registration.registrationId == registrationId }
    }

    override fun iterator(): Iterator<ClientRegistration> {
        return registrations.iterator()
    }
}

private data class ProviderEndpoints(
    val issuer: String,
    val authorization: String,
    val token: String,
    val keys: String,
)

@Configuration(proxyBeanMethods = false)
class OAuthProviders {
    @Bean
    fun providers(environment: Environment): ProviderRegistry {
        val publicUrl = requireNotNull(environment.getProperty("app.public-url")).trimEnd('/')
        val registrations =
            listOfNotNull<() -> ClientRegistration>(
                buildProvider(
                    environment,
                    "google",
                    publicUrl,
                    listOf("openid", "email", "profile"),
                    ProviderEndpoints(
                        issuer = "https://accounts.google.com",
                        authorization = "https://accounts.google.com/o/oauth2/v2/auth",
                        token = "https://oauth2.googleapis.com/token",
                        keys = "https://www.googleapis.com/oauth2/v3/certs",
                    ),
                )?.let { registration -> { registration } },
                microsoft(environment, publicUrl)?.let { registration -> { registration } },
                apple(environment, publicUrl),
            )

        return ProviderRegistry(registrations)
    }

    /**
     * Sign in with Apple. With APPLE_TEAM_ID, APPLE_KEY_ID and APPLE_PRIVATE_KEY the server signs its own
     * client secret and renews it; a fixed APPLE_CLIENT_SECRET still works but expires after six months at most.
     */
    private fun apple(environment: Environment, publicUrl: String): (() -> ClientRegistration)? {
        val clientId = environment.getProperty("APPLE_CLIENT_ID")
        if (clientId.isNullOrBlank()) return null
        val endpoints =
            ProviderEndpoints(
                issuer = "https://appleid.apple.com",
                authorization = "https://appleid.apple.com/auth/authorize",
                token = "https://appleid.apple.com/auth/token",
                keys = "https://appleid.apple.com/auth/keys",
            )
        val scopes = listOf("openid", "email", "name")
        val privateKey = environment.getProperty("APPLE_PRIVATE_KEY")
        if (privateKey.isNullOrBlank()) {
            val registration = requireNotNull(buildProvider(environment, "apple", publicUrl, scopes, endpoints))
            return { registration }
        }
        val signer =
            AppleClientSecret(
                teamId = requireNotNull(environment.getProperty("APPLE_TEAM_ID")) { "APPLE_TEAM_ID est requis avec APPLE_PRIVATE_KEY." },
                keyId = requireNotNull(environment.getProperty("APPLE_KEY_ID")) { "APPLE_KEY_ID est requis avec APPLE_PRIVATE_KEY." },
                clientId = clientId,
                privateKey = privateKey,
            )
        var cached: Pair<String, ClientRegistration>? = null
        return {
            val secret = signer.current()
            cached?.takeIf { it.first == secret }?.second
                ?: requireNotNull(buildProvider(environment, "apple", publicUrl, scopes, endpoints, secret)).also {
                    cached = secret to it
                }
        }
    }

    private fun microsoft(environment: Environment, publicUrl: String): ClientRegistration? {
        val client = environment.getProperty("MICROSOFT_CLIENT_ID")

        if (client.isNullOrBlank()) {
            return null
        }

        val tenant =
            requireNotNull(environment.getProperty("MICROSOFT_TENANT_ID")) {
                "Renseignez l’identifiant UUID de votre annuaire Entra dans MICROSOFT_TENANT_ID."
            }
        ensure(tenant.matches(Regex("[0-9a-fA-F-]{36}"))) {
            "Un annuaire Microsoft précis est requis."
        }

        return buildProvider(
            environment,
            "microsoft",
            publicUrl,
            listOf("openid", "email", "profile"),
            ProviderEndpoints(
                issuer = "https://login.microsoftonline.com/$tenant/v2.0",
                authorization = "https://login.microsoftonline.com/$tenant/oauth2/v2.0/authorize",
                token = "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token",
                keys = "https://login.microsoftonline.com/$tenant/discovery/v2.0/keys",
            ),
        )
    }

    private fun buildProvider(
        environment: Environment,
        id: String,
        publicUrl: String,
        scopes: List<String>,
        endpoints: ProviderEndpoints,
        signedSecret: String? = null,
    ): ClientRegistration? {
        val clientId = environment.getProperty("${id.uppercase()}_CLIENT_ID")

        if (clientId.isNullOrBlank()) {
            return null
        }

        val secret =
            signedSecret
                ?: requireNotNull(environment.getProperty("${id.uppercase()}_CLIENT_SECRET")) {
                    "Le secret client du fournisseur $id est manquant."
                }
        require(secret.isNotBlank())
        val authentication =
            if (id == "apple") {
                ClientAuthenticationMethod.CLIENT_SECRET_POST
            } else {
                ClientAuthenticationMethod.CLIENT_SECRET_BASIC
            }

        return ClientRegistration.withRegistrationId(id)
            .clientId(clientId)
            .clientSecret(secret)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .clientAuthenticationMethod(authentication)
            .redirectUri("$publicUrl/login/oauth2/code/$id")
            .scope(scopes)
            .authorizationUri(endpoints.authorization)
            .tokenUri(endpoints.token)
            .jwkSetUri(endpoints.keys)
            .issuerUri(endpoints.issuer)
            .userNameAttributeName("sub")
            .clientName(id.replaceFirstChar(Char::uppercase))
            .build()
    }
}