diff --git a/src/main/kotlin/net/trueog/staffauth/security/CurrentRoleRule.kt b/src/main/kotlin/net/trueog/staffauth/security/CurrentRoleRule.kt new file mode 100644 index 0000000..d11a3b3 --- /dev/null +++ b/src/main/kotlin/net/trueog/staffauth/security/CurrentRoleRule.kt @@ -0,0 +1,43 @@ +package net.trueog.staffauth.security + +import io.micronaut.http.HttpRequest +import io.micronaut.security.annotation.Secured +import io.micronaut.security.authentication.Authentication +import io.micronaut.security.rules.SecuredAnnotationRule +import io.micronaut.security.rules.SecurityRule +import io.micronaut.security.rules.SecurityRuleResult +import io.micronaut.web.router.RouteAttributes +import jakarta.inject.Singleton +import kotlinx.coroutines.reactor.mono +import net.trueog.staffauth.repository.UserRepository +import org.reactivestreams.Publisher +import java.util.* + +// Re-checks the database on every request to a role-protected route so demotions take effect at once +// The panel session is Hydra's ID token in a cookie, whose roles stay frozen until it expires +@Singleton +class CurrentRoleRule(private val userRepository: UserRepository) : SecurityRule> { + // Run just before Micronaut's @Secured rule, which still checks the roles in the token afterwards + override fun getOrder(): Int = SecuredAnnotationRule.ORDER - 1 + + override fun check(request: HttpRequest<*>?, authentication: Authentication?): Publisher = mono { + // Roles the matched route requires, from its @Secured annotation + val roles = Optional.ofNullable(request).flatMap { RouteAttributes.getRouteMatch(it) } + .map { it.annotationMetadata.stringValues(Secured::class.java).toList() }.orElse(emptyList()) + .filter { it !in NOT_ROLES } + // Not role-protected, or nobody signed in: leave the decision to the other rules + if (roles.isEmpty() || authentication == null) return@mono SecurityRuleResult.UNKNOWN + // The token's subject is the user's Staff-Auth UUID + val uuid = runCatching { UUID.fromString(authentication.attributes["sub"] as? String) }.getOrNull() + // Load the user fresh instead of trusting the token + val user = uuid?.let { userRepository.findByUuid(it) } + // Deleted, deactivated or no longer holding a required role: reject, otherwise let @Secured decide + if (user == null || user.deactivated || user.role.name !in roles) SecurityRuleResult.REJECTED + else SecurityRuleResult.UNKNOWN + } + + companion object { + // Values @Secured accepts that are not roles + private val NOT_ROLES = setOf(SecurityRule.IS_ANONYMOUS, SecurityRule.IS_AUTHENTICATED, SecurityRule.DENY_ALL) + } +} diff --git a/src/main/kotlin/net/trueog/staffauth/service/UserService.kt b/src/main/kotlin/net/trueog/staffauth/service/UserService.kt index 61a8024..6a9e31d 100644 --- a/src/main/kotlin/net/trueog/staffauth/service/UserService.kt +++ b/src/main/kotlin/net/trueog/staffauth/service/UserService.kt @@ -7,6 +7,7 @@ import net.trueog.staffauth.client.MinecraftClient import net.trueog.staffauth.dto.admin.CreateUserDto import net.trueog.staffauth.dto.admin.UpdateUserDto import net.trueog.staffauth.dto.admin.UserDto +import net.trueog.staffauth.entity.User import net.trueog.staffauth.exception.user.DeactivateSelfException import net.trueog.staffauth.exception.user.DeleteSelfException import net.trueog.staffauth.exception.user.DuplicateMinecraftUuidException @@ -58,11 +59,10 @@ class UserService(private val userRepository: UserRepository, private val minecr val roleChanged = user.role != updatedUser.role val deactivate = !user.deactivated && updatedUser.deactivated - if (roleChanged || deactivate) { - if (deactivate) oAuth2Api.revokeOAuth2LoginSessions(updatedUser.uuid.toString(), null) - oAuth2Api.revokeOAuth2ConsentSessions(updatedUser.uuid.toString(), null, null, true) - } + // Revoke before the write so a Hydra failure aborts it, and after so nothing accepted in between survives + if (roleChanged || deactivate) revokeSessions(updatedUser) updatedUser = userRepository.update(updatedUser) + if (roleChanged || deactivate) revokeSessions(updatedUser) val username = minecraftClient.getByUuid(updatedUser.minecraftUuid)?.name return UserDto.fromEntity(updatedUser, username) } @@ -72,6 +72,14 @@ class UserService(private val userRepository: UserRepository, private val minecr if (user.uuid.toString() == auth.attributes["sub"]) { throw DeleteSelfException() } - return userRepository.deleteById(id) + revokeSessions(user) + val deleted = userRepository.deleteById(id) + revokeSessions(user) + return deleted + } + + private fun revokeSessions(user: User) { + oAuth2Api.revokeOAuth2LoginSessions(user.uuid.toString(), null) + oAuth2Api.revokeOAuth2ConsentSessions(user.uuid.toString(), null, null, true) } } \ No newline at end of file diff --git a/src/main/kotlin/net/trueog/staffauth/service/oauth/ConsentService.kt b/src/main/kotlin/net/trueog/staffauth/service/oauth/ConsentService.kt index 3218461..1631fe6 100644 --- a/src/main/kotlin/net/trueog/staffauth/service/oauth/ConsentService.kt +++ b/src/main/kotlin/net/trueog/staffauth/service/oauth/ConsentService.kt @@ -3,6 +3,7 @@ package net.trueog.staffauth.service.oauth import io.micronaut.context.annotation.Value import jakarta.inject.Singleton import net.trueog.staffauth.client.MinecraftClient +import net.trueog.staffauth.model.Role import net.trueog.staffauth.repository.UserRepository import sh.ory.hydra.api.OAuth2Api import sh.ory.hydra.model.AcceptOAuth2ConsentRequest @@ -36,6 +37,7 @@ class ConsentService( val claims = buildMap { if (consentRequest.requestedScope?.contains("email") == true) put("email", user.email) if (consentRequest.requestedScope?.contains("roles") == true) put("roles", arrayOf(user.role)) + if (consentRequest.requestedScope?.contains("roles") == true && user.role in GITEA_ROLES) put("gitea_role", user.role) if (consentRequest.requestedScope?.contains("profile") == true) { val name = minecraftClient.getByUuid(user.minecraftUuid)?.name ?: "Unknown username" put("name", name) @@ -55,4 +57,9 @@ class ConsentService( val response = oAuth2Api.rejectOAuth2ConsentRequest(consentRequest.challenge, RejectOAuth2Request()) return URI.create(response.redirectTo) } + + companion object { + // Only these roles get the gitea_role claim that Gitea requires, so everyone else is refused at login + private val GITEA_ROLES = setOf(Role.ADMIN, Role.DEVELOPER) + } } \ No newline at end of file diff --git a/src/main/kotlin/net/trueog/staffauth/service/oauth/LoginService.kt b/src/main/kotlin/net/trueog/staffauth/service/oauth/LoginService.kt index b32215b..470adb6 100644 --- a/src/main/kotlin/net/trueog/staffauth/service/oauth/LoginService.kt +++ b/src/main/kotlin/net/trueog/staffauth/service/oauth/LoginService.kt @@ -38,6 +38,9 @@ class LoginService( val totpRegex = "^\\d{6}$".toRegex() + // How long a login without "remember me" stays valid for single sign-on + private val shortRememberDuration: Duration = Duration.ofMinutes(15) + @Value($$"${hydra.remember-duration}") lateinit var rememberDuration: Duration @@ -146,9 +149,9 @@ class LoginService( val response = oAuth2Api.acceptOAuth2LoginRequest( loginRequest.challenge, - AcceptOAuth2LoginRequest().subject(user.uuid.toString()).remember(rememberMe).apply { - if (rememberMe) rememberFor(rememberDuration.seconds) - } + // Always remember the login for single sign-on, briefly when unticked, never 0 (Hydra's default lifespan) + AcceptOAuth2LoginRequest().subject(user.uuid.toString()).remember(true) + .rememberFor(if (rememberMe) rememberDuration.seconds else shortRememberDuration.seconds) ) loginStageMap.invalidate(loginChallenge) return response.redirectTo