|
| 1 | +/* |
| 2 | + * Copyright 2014-2023 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.session.data.redis; |
| 18 | + |
| 19 | +import java.time.Duration; |
| 20 | +import java.time.Instant; |
| 21 | +import java.time.temporal.ChronoUnit; |
| 22 | +import java.util.Comparator; |
| 23 | +import java.util.UUID; |
| 24 | + |
| 25 | +import org.junit.jupiter.api.BeforeEach; |
| 26 | +import org.junit.jupiter.api.Test; |
| 27 | +import org.junit.jupiter.api.extension.ExtendWith; |
| 28 | + |
| 29 | +import org.springframework.context.annotation.Bean; |
| 30 | +import org.springframework.context.annotation.Configuration; |
| 31 | +import org.springframework.context.annotation.Import; |
| 32 | +import org.springframework.data.redis.core.ReactiveRedisOperations; |
| 33 | +import org.springframework.data.redis.serializer.RedisSerializer; |
| 34 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 35 | +import org.springframework.security.core.authority.AuthorityUtils; |
| 36 | +import org.springframework.security.core.context.SecurityContext; |
| 37 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 38 | +import org.springframework.session.ReactiveFindByIndexNameSessionRepository; |
| 39 | +import org.springframework.session.Session; |
| 40 | +import org.springframework.session.config.ReactiveSessionRepositoryCustomizer; |
| 41 | +import org.springframework.session.data.SessionEventRegistry; |
| 42 | +import org.springframework.session.data.redis.ReactiveRedisIndexedSessionRepository.RedisSession; |
| 43 | +import org.springframework.session.data.redis.config.ConfigureReactiveRedisAction; |
| 44 | +import org.springframework.session.data.redis.config.annotation.web.server.EnableRedisIndexedWebSession; |
| 45 | +import org.springframework.session.events.SessionCreatedEvent; |
| 46 | +import org.springframework.test.context.junit.jupiter.SpringExtension; |
| 47 | +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; |
| 48 | + |
| 49 | +import static org.assertj.core.api.Assertions.assertThat; |
| 50 | +import static org.awaitility.Awaitility.await; |
| 51 | + |
| 52 | +@ExtendWith(SpringExtension.class) |
| 53 | +class ReactiveRedisIndexedSessionRepositoryConfigurationITests { |
| 54 | + |
| 55 | + ReactiveRedisIndexedSessionRepository repository; |
| 56 | + |
| 57 | + ReactiveRedisOperations<String, Object> sessionRedisOperations; |
| 58 | + |
| 59 | + AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); |
| 60 | + |
| 61 | + SecurityContext securityContext; |
| 62 | + |
| 63 | + @BeforeEach |
| 64 | + void setup() { |
| 65 | + this.securityContext = SecurityContextHolder.createEmptyContext(); |
| 66 | + this.securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("username-" + UUID.randomUUID(), |
| 67 | + "na", AuthorityUtils.createAuthorityList("ROLE_USER"))); |
| 68 | + } |
| 69 | + |
| 70 | + @Test |
| 71 | + void cleanUpTaskWhenSessionIsExpiredThenAllRelatedKeysAreDeleted() { |
| 72 | + registerConfig(OneSecCleanUpIntervalConfig.class); |
| 73 | + RedisSession session = this.repository.createSession().block(); |
| 74 | + session.setAttribute("SPRING_SECURITY_CONTEXT", this.securityContext); |
| 75 | + this.repository.save(session).block(); |
| 76 | + await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> { |
| 77 | + assertThat(this.repository.findById(session.getId()).block()).isNull(); |
| 78 | + Boolean hasSessionKey = this.sessionRedisOperations.hasKey("spring:session:sessions:" + session.getId()) |
| 79 | + .block(); |
| 80 | + Boolean hasSessionIndexesKey = this.sessionRedisOperations |
| 81 | + .hasKey("spring:session:sessions:" + session.getId() + ":idx") |
| 82 | + .block(); |
| 83 | + Boolean hasPrincipalIndexKey = this.sessionRedisOperations |
| 84 | + .hasKey("spring:session:sessions:index:" |
| 85 | + + ReactiveFindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME + ":" |
| 86 | + + this.securityContext.getAuthentication().getName()) |
| 87 | + .block(); |
| 88 | + Long expirationsSize = this.sessionRedisOperations.opsForZSet() |
| 89 | + .size("spring:session:sessions:expirations") |
| 90 | + .block(); |
| 91 | + assertThat(hasSessionKey).isFalse(); |
| 92 | + assertThat(hasSessionIndexesKey).isFalse(); |
| 93 | + assertThat(hasPrincipalIndexKey).isFalse(); |
| 94 | + assertThat(expirationsSize).isZero(); |
| 95 | + }); |
| 96 | + } |
| 97 | + |
| 98 | + @Test |
| 99 | + void onSessionCreatedWhenUsingJsonSerializerThenEventDeserializedCorrectly() throws InterruptedException { |
| 100 | + registerConfig(SessionEventRegistryJsonSerializerConfig.class); |
| 101 | + RedisSession session = this.repository.createSession().block(); |
| 102 | + this.repository.save(session).block(); |
| 103 | + SessionEventRegistry registry = this.context.getBean(SessionEventRegistry.class); |
| 104 | + SessionCreatedEvent event = registry.getEvent(session.getId()); |
| 105 | + Session eventSession = event.getSession(); |
| 106 | + assertThat(eventSession).usingRecursiveComparison() |
| 107 | + .withComparatorForFields(new InstantComparator(), "cached.creationTime", "cached.lastAccessedTime") |
| 108 | + .isEqualTo(session); |
| 109 | + } |
| 110 | + |
| 111 | + @Test |
| 112 | + void sessionExpiredWhenNoCleanUpTaskAndNoKeyspaceEventsThenNoCleanup() { |
| 113 | + registerConfig(DisableCleanupTaskAndNoKeyspaceEventsConfig.class); |
| 114 | + RedisSession session = this.repository.createSession().block(); |
| 115 | + this.repository.save(session).block(); |
| 116 | + await().during(Duration.ofSeconds(3)).untilAsserted(() -> { |
| 117 | + Boolean exists = this.sessionRedisOperations.hasKey("spring:session:sessions:" + session.getId()).block(); |
| 118 | + assertThat(exists).isTrue(); |
| 119 | + }); |
| 120 | + } |
| 121 | + |
| 122 | + private void registerConfig(Class<?> clazz) { |
| 123 | + this.context.register(clazz); |
| 124 | + this.context.refresh(); |
| 125 | + this.repository = this.context.getBean(ReactiveRedisIndexedSessionRepository.class); |
| 126 | + this.sessionRedisOperations = this.repository.getSessionRedisOperations(); |
| 127 | + } |
| 128 | + |
| 129 | + static class InstantComparator implements Comparator<Instant> { |
| 130 | + |
| 131 | + @Override |
| 132 | + public int compare(Instant o1, Instant o2) { |
| 133 | + return o1.truncatedTo(ChronoUnit.SECONDS).compareTo(o2.truncatedTo(ChronoUnit.SECONDS)); |
| 134 | + } |
| 135 | + |
| 136 | + } |
| 137 | + |
| 138 | + @Configuration(proxyBeanMethods = false) |
| 139 | + @EnableRedisIndexedWebSession(maxInactiveIntervalInSeconds = 1) |
| 140 | + @Import(AbstractRedisITests.BaseConfig.class) |
| 141 | + static class OneSecCleanUpIntervalConfig { |
| 142 | + |
| 143 | + @Bean |
| 144 | + ReactiveSessionRepositoryCustomizer<ReactiveRedisIndexedSessionRepository> customizer() { |
| 145 | + return (sessionRepository) -> sessionRepository.setCleanupInterval(Duration.ofSeconds(1)); |
| 146 | + } |
| 147 | + |
| 148 | + } |
| 149 | + |
| 150 | + @Configuration(proxyBeanMethods = false) |
| 151 | + @EnableRedisIndexedWebSession |
| 152 | + @Import(AbstractRedisITests.BaseConfig.class) |
| 153 | + static class SessionEventRegistryJsonSerializerConfig { |
| 154 | + |
| 155 | + @Bean |
| 156 | + SessionEventRegistry sessionEventRegistry() { |
| 157 | + return new SessionEventRegistry(); |
| 158 | + } |
| 159 | + |
| 160 | + @Bean |
| 161 | + RedisSerializer<Object> springSessionDefaultRedisSerializer() { |
| 162 | + return RedisSerializer.json(); |
| 163 | + } |
| 164 | + |
| 165 | + } |
| 166 | + |
| 167 | + @Configuration(proxyBeanMethods = false) |
| 168 | + @EnableRedisIndexedWebSession(maxInactiveIntervalInSeconds = 1) |
| 169 | + @Import(AbstractRedisITests.BaseConfig.class) |
| 170 | + static class DisableCleanupTaskAndNoKeyspaceEventsConfig { |
| 171 | + |
| 172 | + @Bean |
| 173 | + ReactiveSessionRepositoryCustomizer<ReactiveRedisIndexedSessionRepository> customizer() { |
| 174 | + return ReactiveRedisIndexedSessionRepository::disableCleanupTask; |
| 175 | + } |
| 176 | + |
| 177 | + @Bean |
| 178 | + ConfigureReactiveRedisAction configureReactiveRedisAction() { |
| 179 | + return (connection) -> connection.serverCommands().setConfig("notify-keyspace-events", "").then(); |
| 180 | + } |
| 181 | + |
| 182 | + } |
| 183 | + |
| 184 | +} |
0 commit comments