Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,23 @@ public interface OneTimeCodeRepository extends JpaRepository<OneTimeCodeEntity,
void deleteByRevoked();

/**
* Mark a one-time code as revoked (consumed).
*
* @param code the OTC UUID to revoke
* Atomically mark a one-time code as revoked (consumed), but only if it is
* still unrevoked and unexpired. The conditions live in the UPDATE itself so
* that concurrent redemptions of the same code cannot both succeed.
*
* @param code the OTC UUID to consume
* @param now current instant for expiration comparison
* @return number of rows updated: 1 if this call consumed the code, 0 otherwise
*/
@Modifying
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("""
update OneTimeCode otc
set otc.revoked = true
where otc.code = :code
and otc.revoked = false
and otc.expiresAt >= :now
""")
void revokeByCode(@Param("code") UUID code);
int consumeByCode(@Param("code") UUID code, @Param("now") Instant now);

/**
* Delete all codes for a specific login (used when user is deleted/disabled).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,32 +83,17 @@ public UUID generateCode(String login, UserOrigin origin, String jwtToken) {
* @return Optional containing the OTC entity if valid, empty if invalid/expired/already revoked
*/
public Optional<OneTimeCodeEntity> validateAndConsume(UUID code) {
Optional<OneTimeCodeEntity> otcOpt = repo.findById(code);

if (otcOpt.isEmpty()) {
log.debug("OTC: {} not found", code);
return Optional.empty();
}

OneTimeCodeEntity otc = otcOpt.get();

// Check expiration
if (otc.getExpiresAt().isBefore(Instant.now())) {
log.debug("OTC: {} expired", code);
// Consume first with a single conditional UPDATE. Checking the revoked/expired
// flags in Java and then updating would let two concurrent requests both read
// revoked=false and both receive the JWT, breaking the single-use guarantee.
if (repo.consumeByCode(code, Instant.now()) != 1) {
log.debug("OTC: {} not found, expired, or already consumed", code);
return Optional.empty();
}

// Check revocation (already used)
if (otc.isRevoked()) {
log.debug("OTC: {} already revoked (single-use)", code);
return Optional.empty();
}

// Mark as revoked (consumed) - single use
repo.revokeByCode(code);
log.debug("OTC: {} consumed for user: {}", code, otc.getLogin());

return Optional.of(otc);
Optional<OneTimeCodeEntity> otcOpt = repo.findById(code);
otcOpt.ifPresent(otc -> log.debug("OTC: {} consumed for user: {}", code, otc.getLogin()));
return otcOpt;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package org.ohdsi.webapi.security.authc;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Optional;
import java.util.UUID;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class OneTimeCodeServiceTest {

private OneTimeCodeRepository repo;
private OneTimeCodeService service;

@BeforeEach
void setUp() {
repo = mock(OneTimeCodeRepository.class);
service = new OneTimeCodeService(repo, new OneTimeCodeProperties());
}

@Test
void returnsCodeWhenThisCallConsumedIt() {
UUID code = UUID.randomUUID();
OneTimeCodeEntity otc = new OneTimeCodeEntity();
otc.setCode(code);
otc.setLogin("alice");
otc.setJwtToken("jwt");
when(repo.consumeByCode(eq(code), any())).thenReturn(1);
when(repo.findById(code)).thenReturn(Optional.of(otc));

Optional<OneTimeCodeEntity> result = service.validateAndConsume(code);

assertTrue(result.isPresent());
assertEquals("jwt", result.get().getJwtToken());
}

@Test
void rejectsCodeAlreadyConsumedByConcurrentRequest() {
UUID code = UUID.randomUUID();
// The conditional UPDATE matched no row: another request consumed it first,
// or it is expired or unknown. The JWT must not be read or returned.
when(repo.consumeByCode(eq(code), any())).thenReturn(0);

Optional<OneTimeCodeEntity> result = service.validateAndConsume(code);

assertTrue(result.isEmpty());
verify(repo, never()).findById(code);
}
}
Loading