|
| 1 | +package com.digitalsanctuary.spring.user.service; |
| 2 | + |
| 3 | +import static org.assertj.core.api.Assertions.assertThat; |
| 4 | +import com.digitalsanctuary.spring.user.persistence.model.PasswordResetToken; |
| 5 | +import com.digitalsanctuary.spring.user.persistence.model.User; |
| 6 | +import com.digitalsanctuary.spring.user.persistence.model.VerificationToken; |
| 7 | +import com.digitalsanctuary.spring.user.persistence.repository.PasswordResetTokenRepository; |
| 8 | +import com.digitalsanctuary.spring.user.persistence.repository.UserRepository; |
| 9 | +import com.digitalsanctuary.spring.user.persistence.repository.VerificationTokenRepository; |
| 10 | +import com.digitalsanctuary.spring.user.test.app.TestApplication; |
| 11 | +import com.digitalsanctuary.spring.user.test.builders.UserTestDataBuilder; |
| 12 | +import java.util.ArrayList; |
| 13 | +import java.util.List; |
| 14 | +import java.util.concurrent.Callable; |
| 15 | +import java.util.concurrent.CountDownLatch; |
| 16 | +import java.util.concurrent.ExecutionException; |
| 17 | +import java.util.concurrent.ExecutorService; |
| 18 | +import java.util.concurrent.Executors; |
| 19 | +import java.util.concurrent.Future; |
| 20 | +import java.util.concurrent.TimeUnit; |
| 21 | +import java.util.concurrent.atomic.AtomicInteger; |
| 22 | +import org.junit.jupiter.api.AfterEach; |
| 23 | +import org.junit.jupiter.api.DisplayName; |
| 24 | +import org.junit.jupiter.api.RepeatedTest; |
| 25 | +import org.springframework.beans.factory.annotation.Autowired; |
| 26 | +import org.springframework.boot.test.context.SpringBootTest; |
| 27 | +import org.springframework.test.context.ActiveProfiles; |
| 28 | + |
| 29 | +/** |
| 30 | + * Validates that single-use token consumption is truly atomic under concurrency on a real, production-grade database |
| 31 | + * (not just H2). The fix makes the conditional {@code DELETE} (which returns the affected row count) the atomicity |
| 32 | + * guard: the row lock serializes concurrent deletes, so exactly one caller observes a count of {@code 1} (and applies |
| 33 | + * the effect) while the rest observe {@code 0} (and are rejected). A plain read-check-delete would let two requests |
| 34 | + * both read the token under READ_COMMITTED and both succeed — the replay this test guards against. |
| 35 | + * |
| 36 | + * <p> |
| 37 | + * Two threads race to consume the SAME token at the same instant (released together via a {@link CountDownLatch}). |
| 38 | + * Exactly one must win. This is asserted for both the password-reset consume path |
| 39 | + * ({@link UserService#validateAndConsumePasswordResetToken(String)}) and the email-verification consume path |
| 40 | + * ({@link UserVerificationService#validateVerificationToken(String)}). |
| 41 | + * </p> |
| 42 | + * |
| 43 | + * <p> |
| 44 | + * Subclasses provide a real database via Testcontainers. The class is deliberately NOT {@code @Transactional}: each |
| 45 | + * consume must run in its own service-managed transaction on its own thread, and a test-managed transaction would |
| 46 | + * defeat the race. |
| 47 | + * </p> |
| 48 | + */ |
| 49 | +@SpringBootTest(classes = TestApplication.class) |
| 50 | +@ActiveProfiles("test") |
| 51 | +abstract class AbstractConcurrentTokenConsumeTest { |
| 52 | + |
| 53 | + @Autowired |
| 54 | + private UserService userService; |
| 55 | + |
| 56 | + @Autowired |
| 57 | + private UserVerificationService userVerificationService; |
| 58 | + |
| 59 | + @Autowired |
| 60 | + private UserRepository userRepository; |
| 61 | + |
| 62 | + @Autowired |
| 63 | + private PasswordResetTokenRepository passwordResetTokenRepository; |
| 64 | + |
| 65 | + @Autowired |
| 66 | + private VerificationTokenRepository verificationTokenRepository; |
| 67 | + |
| 68 | + @Autowired |
| 69 | + private TokenHasher tokenHasher; |
| 70 | + |
| 71 | + @AfterEach |
| 72 | + void cleanUp() { |
| 73 | + // The threads commit their own transactions, so clean up explicitly. |
| 74 | + passwordResetTokenRepository.deleteAll(); |
| 75 | + verificationTokenRepository.deleteAll(); |
| 76 | + userRepository.deleteAll(); |
| 77 | + } |
| 78 | + |
| 79 | + @RepeatedTest(value = 3, name = "{displayName} [run {currentRepetition}/{totalRepetitions}]") |
| 80 | + @DisplayName("password-reset token is consumed by exactly one of two racing threads") |
| 81 | + void shouldConsumePasswordResetTokenExactlyOnceUnderConcurrency() throws InterruptedException { |
| 82 | + final User user = userRepository.save(UserTestDataBuilder.aUser() |
| 83 | + .withId(null) // let the DB assign the id so save() performs an INSERT, not a merge |
| 84 | + .withEmail("pwd-race-" + System.nanoTime() + "@test.com") |
| 85 | + .withFirstName("Pwd").withLastName("Race").enabled().build()); |
| 86 | + final String rawToken = "pwd-reset-" + System.nanoTime(); |
| 87 | + passwordResetTokenRepository.save(new PasswordResetToken(tokenHasher.hash(rawToken), user, 60)); |
| 88 | + |
| 89 | + final List<Object> outcomes = raceTwoThreads(() -> userService.validateAndConsumePasswordResetToken(rawToken)); |
| 90 | + |
| 91 | + final long wins = outcomes.stream().filter(o -> o instanceof User).count(); |
| 92 | + assertThat(wins).as("exactly one thread may consume the password-reset token").isEqualTo(1); |
| 93 | + assertThat(passwordResetTokenRepository.findByToken(tokenHasher.hash(rawToken))) |
| 94 | + .as("the token must be gone after consumption").isNull(); |
| 95 | + } |
| 96 | + |
| 97 | + @RepeatedTest(value = 3, name = "{displayName} [run {currentRepetition}/{totalRepetitions}]") |
| 98 | + @DisplayName("verification token is consumed by exactly one of two racing threads") |
| 99 | + void shouldConsumeVerificationTokenExactlyOnceUnderConcurrency() throws InterruptedException { |
| 100 | + final User user = userRepository.save(UserTestDataBuilder.aUser() |
| 101 | + .withId(null) // let the DB assign the id so save() performs an INSERT, not a merge |
| 102 | + .withEmail("verify-race-" + System.nanoTime() + "@test.com") |
| 103 | + .withFirstName("Verify").withLastName("Race").unverified().build()); |
| 104 | + final String rawToken = "verify-" + System.nanoTime(); |
| 105 | + verificationTokenRepository.save(new VerificationToken(tokenHasher.hash(rawToken), user, 60)); |
| 106 | + |
| 107 | + final List<Object> outcomes = |
| 108 | + raceTwoThreads(() -> userVerificationService.validateVerificationToken(rawToken)); |
| 109 | + |
| 110 | + final long valid = outcomes.stream() |
| 111 | + .filter(o -> o == UserService.TokenValidationResult.VALID).count(); |
| 112 | + assertThat(valid).as("exactly one thread may validate (consume) the verification token").isEqualTo(1); |
| 113 | + assertThat(verificationTokenRepository.findByToken(tokenHasher.hash(rawToken))) |
| 114 | + .as("the token must be gone after consumption").isNull(); |
| 115 | + assertThat(userRepository.findById(user.getId())) |
| 116 | + .get().extracting(User::isEnabled).as("the user is enabled exactly once").isEqualTo(true); |
| 117 | + } |
| 118 | + |
| 119 | + /** |
| 120 | + * Runs the given consume action on two threads released simultaneously and returns both outcomes. |
| 121 | + * |
| 122 | + * @param consume the consume action under test |
| 123 | + * @return the two outcomes (a result object, or {@code null} for the losing/rejected call) |
| 124 | + */ |
| 125 | + private List<Object> raceTwoThreads(final Callable<Object> consume) throws InterruptedException { |
| 126 | + final int threadCount = 2; |
| 127 | + final CountDownLatch readyLatch = new CountDownLatch(threadCount); |
| 128 | + final CountDownLatch startLatch = new CountDownLatch(1); |
| 129 | + final ExecutorService executor = Executors.newFixedThreadPool(threadCount); |
| 130 | + try { |
| 131 | + final List<Future<Object>> futures = new ArrayList<>(); |
| 132 | + for (int i = 0; i < threadCount; i++) { |
| 133 | + futures.add(executor.submit(() -> { |
| 134 | + readyLatch.countDown(); |
| 135 | + if (!startLatch.await(30, TimeUnit.SECONDS)) { |
| 136 | + throw new IllegalStateException("start gate was never opened"); |
| 137 | + } |
| 138 | + return consume.call(); |
| 139 | + })); |
| 140 | + } |
| 141 | + |
| 142 | + assertThat(readyLatch.await(30, TimeUnit.SECONDS)) |
| 143 | + .as("both consume threads should reach the start gate").isTrue(); |
| 144 | + startLatch.countDown(); |
| 145 | + |
| 146 | + final AtomicInteger unexpected = new AtomicInteger(); |
| 147 | + final List<Object> outcomes = new ArrayList<>(); |
| 148 | + for (Future<Object> future : futures) { |
| 149 | + try { |
| 150 | + outcomes.add(future.get(60, TimeUnit.SECONDS)); |
| 151 | + } catch (ExecutionException e) { |
| 152 | + unexpected.incrementAndGet(); |
| 153 | + } catch (Exception e) { |
| 154 | + unexpected.incrementAndGet(); |
| 155 | + } |
| 156 | + } |
| 157 | + assertThat(unexpected.get()).as("neither consume call should throw").isZero(); |
| 158 | + return outcomes; |
| 159 | + } finally { |
| 160 | + executor.shutdownNow(); |
| 161 | + } |
| 162 | + } |
| 163 | +} |
0 commit comments