package com.linkerbot.vibemake.api; import static org.assertj.core.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.linkerbot.vibemake.bean.entity.User; import com.linkerbot.vibemake.common.SecurityHashes; import com.linkerbot.vibemake.common.state.TransientStateStore; import com.linkerbot.vibemake.security.CaptchaService; import com.linkerbot.vibemake.security.TokenService; import com.linkerbot.vibemake.service.UserService; import com.linkerbot.vibemake.service.config.VibemakeProperties; import com.linkerbot.vibemake.service.config.RedisStateProperties; import com.linkerbot.vibemake.service.state.RedisStateStore; import org.junit.jupiter.api.*; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.*; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import java.time.Duration; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; @SpringBootTest( properties = { "vibemake.redis.real-test=true", "vibemake.limits.enabled=false", "vibemake.admin.worker-enabled=false", "spring.datasource.url=jdbc:h2:mem:redis-live;MODE=MySQL;DB_CLOSE_DELAY=-1", "spring.datasource.username=sa", "spring.datasource.password=", "spring.datasource.driver-class-name=org.h2.Driver", "spring.data.redis.host=${REDIS_TEST_HOST}", "spring.data.redis.port=${REDIS_TEST_PORT:6379}", "spring.data.redis.username=${REDIS_TEST_USERNAME:}", "spring.data.redis.password=${REDIS_TEST_PASSWORD:}", "spring.data.redis.database=${REDIS_TEST_DATABASE:0}", "spring.data.redis.ssl.enabled=${REDIS_TEST_SSL_ENABLED:false}", "vibemake.redis.key-prefix=vibemake:test:redis-live-${random.uuid}", "logging.level.org.springframework=WARN" }) @ActiveProfiles("test") @AutoConfigureMockMvc(print = MockMvcPrint.NONE) @Import(WorkflowTest.Config.class) @EnabledIfEnvironmentVariable(named = "REDIS_TEST_HOST", matches = ".+") class RedisLiveTest { @Autowired TransientStateStore state; @Autowired StringRedisTemplate redis; @Autowired RedisStateProperties namespace; @Autowired VibemakeProperties properties; @Autowired ObjectMapper json; @Autowired TokenService tokens; @Autowired CaptchaService captcha; @Autowired UserService users; @Autowired JdbcTemplate jdbc; @Autowired MockMvc mvc; @BeforeEach void schema() throws Exception { SchemaSupport.reset(jdbc); } @AfterEach void cleanOnlyThisTestNamespace() { assertThat(namespace.getKeyPrefix()).startsWith("vibemake:test:redis-live-"); try (Cursor cursor = redis.scan( ScanOptions.scanOptions() .match(namespace.prefix() + "*") .count(100) .build())) { while (cursor.hasNext()) redis.delete(cursor.next()); } } @Test void ttlAtomicConsumptionIsolationAndReconnection() throws Exception { assertThat(state).isInstanceOf(RedisStateStore.class); state.verify(); assertThat(state.putIfAbsent("ttl", "once", Duration.ofMillis(80))).isTrue(); assertThat(state.putIfAbsent("ttl", "other", Duration.ofMinutes(1))).isFalse(); Thread.sleep(120); assertThat(state.get("ttl")).isNull(); state.putIfAbsent("consume", "only", Duration.ofMinutes(1)); AtomicInteger accepted = new AtomicInteger(); try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 30; i++) pool.submit( () -> { if ("only".equals(state.consume("consume"))) accepted.incrementAndGet(); }); } assertThat(accepted.get()).isEqualTo(1); AtomicInteger maximum = new AtomicInteger(); try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 40; i++) pool.submit( () -> maximum.accumulateAndGet( (int) state.increment( "counter", Duration.ofSeconds(30), false) .count(), Math::max)); } assertThat(maximum.get()).isEqualTo(40); RedisStateProperties other = new RedisStateProperties(); other.setKeyPrefix(namespace.getKeyPrefix()); other.setApplication("admin"); assertThat(new RedisStateStore(redis, other).get("counter")).isNull(); RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration( System.getenv("REDIS_TEST_HOST"), Integer.parseInt(System.getenv().getOrDefault("REDIS_TEST_PORT", "6379"))); configuration.setUsername(System.getenv("REDIS_TEST_USERNAME")); configuration.setPassword(System.getenv().getOrDefault("REDIS_TEST_PASSWORD", "")); configuration.setDatabase( Integer.parseInt(System.getenv().getOrDefault("REDIS_TEST_DATABASE", "0"))); org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration .LettuceClientConfigurationBuilder client = org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration .builder() .commandTimeout(Duration.ofSeconds(1)); if (Boolean.parseBoolean(System.getenv("REDIS_TEST_SSL_ENABLED"))) client.useSsl(); LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration, client.build()); try { factory.afterPropertiesSet(); factory.start(); StringRedisTemplate replacement = new StringRedisTemplate(factory); assertThat(new RedisStateStore(replacement, namespace).get("counter")).isEqualTo("40"); } finally { factory.destroy(); } } @Test void sessionsCaptchaRevocationAndDisabledUsersUseRealRedis() throws Exception { User user = users.login("redis-test@example.invalid"); String token = tokens.issue(user.getId(), user.getSessionVersion()); assertThat(redis.hasKey(namespace.prefix() + "session:" + token)).isFalse(); assertThat(redis.hasKey(namespace.prefix() + "session:" + SecurityHashes.sha256(token))) .isTrue(); TokenService replacement = new TokenService(properties, new RedisStateStore(redis, namespace), json); assertThat(replacement.resolve(token)).isEqualTo(user.getId()); mvc.perform(get("/api/users/me").header("Authorization", "Bearer " + token)) .andExpect(status().isOk()); String code = captcha.issue().captchaCode(); captcha.verify(code, "ABCDE"); assertThatThrownBy(() -> captcha.verify(code, "ABCDE")) .isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class); jdbc.update( "UPDATE sys_user SET status='DISABLED', session_version=session_version+1 WHERE" + " id=?", user.getId()); mvc.perform(get("/api/users/me").header("Authorization", "Bearer " + token)) .andExpect(status().isUnauthorized()); jdbc.update("UPDATE sys_user SET status='ACTIVE' WHERE id=?", user.getId()); mvc.perform(get("/api/users/me").header("Authorization", "Bearer " + token)) .andExpect(status().isUnauthorized()); replacement.revoke(token); assertThat(tokens.resolve(token)).isNull(); } }