fixed show phone number

This commit is contained in:
SlimusMinus
2026-10-27 22:49:16 +03:00
parent aa7c9f25f0
commit 1cd72fbec4
27 changed files with 1054 additions and 15 deletions

View File

@@ -0,0 +1,66 @@
package com.krylov.refound.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.krylov.refound.entity.Post;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.util.PostFieldLimits;
import java.time.LocalDateTime;
import org.junit.jupiter.api.Test;
/** Номер в объявлении хранится только с согласием автора на показ (152-ФЗ). */
class PostPhoneConsentTest {
@Test
void withoutConsentPhoneIsNotStored() {
Post post = new Post();
PostService.applyPhone(post, "+7 (999) 111-22-33", false);
assertThat(post.isPhoneVisible()).isFalse();
assertThat(post.getPhone()).isNull();
assertThat(post.getPhoneConsentAt()).isNull();
}
@Test
void consentStoresPhoneAndTime() {
Post post = new Post();
PostService.applyPhone(post, " +7 (999) 111-22-33 ", true);
assertThat(post.isPhoneVisible()).isTrue();
assertThat(post.getPhone()).isEqualTo("+7 (999) 111-22-33");
assertThat(post.getPhoneConsentAt()).isNotNull();
}
@Test
void editKeepsOriginalConsentTime() {
Post post = new Post();
LocalDateTime consentAt = LocalDateTime.of(2026, 1, 1, 10, 0);
post.setPhoneVisible(true);
post.setPhoneConsentAt(consentAt);
PostService.applyPhone(post, "+79990000000", true);
assertThat(post.getPhoneConsentAt()).isEqualTo(consentAt);
}
@Test
void withdrawingConsentErasesPhone() {
Post post = new Post();
PostService.applyPhone(post, "+79991112233", true);
PostService.applyPhone(post, "+79991112233", false);
assertThat(post.getPhone()).isNull();
assertThat(post.isPhoneVisible()).isFalse();
}
@Test
void phoneForDisplayMustHaveEnoughDigits() {
assertThatThrownBy(() -> PostFieldLimits.requirePhone("+7")).isInstanceOf(ApiException.class);
assertThatThrownBy(() -> PostFieldLimits.requirePhone(null)).isInstanceOf(ApiException.class);
PostFieldLimits.requirePhone("+7 (999) 111-22-33");
}
}

View File

@@ -0,0 +1,176 @@
package com.krylov.refound.service.phone;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.krylov.refound.entity.Post;
import com.krylov.refound.entity.User;
import com.krylov.refound.enums.PostStatus;
import com.krylov.refound.exception.ApiException;
import com.krylov.refound.ratelimit.RedisRateLimiter;
import com.krylov.refound.repository.PostRepository;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
@ExtendWith(MockitoExtension.class)
class PhoneRevealServiceTest {
private static final String IP = "10.0.0.7";
private static final RedisRateLimiter.Decision ALLOWED = new RedisRateLimiter.Decision(true, 1, 1);
@Mock
private PostRepository postRepository;
@Mock
private ProofOfWorkService proofOfWork;
@Mock
private RedisRateLimiter rateLimiter;
@Mock
private StringRedisTemplate redis;
@Mock
private ValueOperations<String, String> values;
private final PhoneRevealProperties properties = new PhoneRevealProperties();
private PhoneRevealService service;
@BeforeEach
void setUp() {
service = new PhoneRevealService(postRepository, proofOfWork, rateLimiter, redis, properties);
lenient().when(redis.getExpire(anyString(), eq(TimeUnit.SECONDS))).thenReturn(-2L);
lenient().when(redis.opsForValue()).thenReturn(values);
lenient().when(rateLimiter.hit(anyString(), anyString(), anyInt(), any())).thenReturn(ALLOWED);
}
private static Post post(PostStatus status, boolean phoneVisible, String phone) {
Post post = new Post();
post.setId(1L);
post.setStatus(status);
post.setPhoneVisible(phoneVisible);
post.setPhone(phone);
return post;
}
@Test
void challengeDifficultyDependsOnRevealsFromIp() {
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.ACTIVE, true, "+79991112233")));
when(rateLimiter.current(eq(PhoneRevealService.RULE_HOUR), eq(IP), any())).thenReturn(7L);
when(proofOfWork.maxNumberFor(7)).thenReturn(400_000L);
ProofOfWorkService.Challenge challenge = new ProofOfWorkService.Challenge("SHA-256", "c", "s", 400_000, "sig");
when(proofOfWork.create(1L, 400_000L)).thenReturn(challenge);
assertThat(service.challenge(1L, IP)).isSameAs(challenge);
}
@Test
void validSolutionRevealsPhone() {
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(1L));
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.ACTIVE, true, "+79991112233")));
assertThat(service.reveal(1L, "s", 5L, "sig", IP, 9L)).isEqualTo("+79991112233");
verify(rateLimiter).hit(eq(PhoneRevealService.RULE_USER_DAY), eq("u9"), anyInt(), any());
}
@Test
void ownerSeesOwnPhoneWithoutSpendingLimits() {
Post own = post(PostStatus.ACTIVE, true, "+79991112233");
User author = new User();
author.setId(9L);
own.setUser(author);
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(1L));
when(postRepository.findById(1L)).thenReturn(Optional.of(own));
assertThat(service.reveal(1L, "s", 5L, "sig", IP, 9L)).isEqualTo("+79991112233");
verify(rateLimiter, never()).hit(anyString(), anyString(), anyInt(), any());
}
@Test
void solutionForAnotherPostIsRejectedAsStrike() {
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(2L));
assertThatThrownBy(() -> service.reveal(1L, "s", 5L, "sig", IP, null))
.isInstanceOf(ApiException.class)
.extracting(e -> ((ApiException) e).getStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
verify(rateLimiter).hit(eq(PhoneRevealService.RULE_STRIKE), eq(IP), anyInt(), any());
verify(postRepository, never()).findById(anyLong());
}
@Test
void postWithoutConsentIsNotFoundAndCountsAsStrike() {
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.ACTIVE, false, null)));
assertThatThrownBy(() -> service.challenge(1L, IP))
.isInstanceOf(ApiException.class)
.extracting(e -> ((ApiException) e).getStatus()).isEqualTo(HttpStatus.NOT_FOUND);
verify(rateLimiter).hit(eq(PhoneRevealService.RULE_STRIKE), eq(IP), anyInt(), any());
}
@Test
void closedPostDoesNotShowPhone() {
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.CLOSED, true, "+79991112233")));
assertThatThrownBy(() -> service.challenge(1L, IP)).isInstanceOf(ApiException.class);
}
@Test
void tooManyStrikesBanIp() {
when(postRepository.findById(anyLong())).thenReturn(Optional.empty());
when(rateLimiter.hit(eq(PhoneRevealService.RULE_STRIKE), eq(IP), anyInt(), any()))
.thenReturn(new RedisRateLimiter.Decision(false, properties.getStrikeLimit(), 60));
assertThatThrownBy(() -> service.challenge(99L, IP)).isInstanceOf(ApiException.class);
verify(values).set(eq("phone-ban:" + IP), eq("1"), eq(properties.getBanDuration()));
}
@Test
void trapPostBansImmediately() {
properties.setTrapPostIds(List.of(777L));
assertThatThrownBy(() -> service.challenge(777L, IP)).isInstanceOf(ApiException.class);
verify(values).set(eq("phone-ban:" + IP), eq("1"), any(Duration.class));
verify(postRepository, never()).findById(anyLong());
}
@Test
void bannedIpGets429WithRetryAfter() {
when(redis.getExpire("phone-ban:" + IP, TimeUnit.SECONDS)).thenReturn(3600L);
assertThatThrownBy(() -> service.challenge(1L, IP))
.isInstanceOfSatisfying(ApiException.class, e -> {
assertThat(e.getStatus()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
assertThat(e.getRetryAfterSeconds()).isEqualTo(3600L);
});
verify(postRepository, never()).findById(anyLong());
}
@Test
void hourlyLimitGives429() {
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(1L));
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.ACTIVE, true, "+79991112233")));
when(rateLimiter.hit(eq(PhoneRevealService.RULE_HOUR), eq(IP), anyInt(), any()))
.thenReturn(new RedisRateLimiter.Decision(false, 31, 120));
assertThatThrownBy(() -> service.reveal(1L, "s", 5L, "sig", IP, null))
.isInstanceOfSatisfying(ApiException.class, e -> {
assertThat(e.getStatus()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
assertThat(e.getRetryAfterSeconds()).isEqualTo(120L);
});
}
}

View File

@@ -0,0 +1,131 @@
package com.krylov.refound.service.phone;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
class ProofOfWorkServiceTest {
private static final Instant NOW = Instant.parse("2026-10-27T12:00:00Z");
private PhoneRevealProperties properties;
private ValueOperations<String, String> values;
private StringRedisTemplate redis;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
properties = new PhoneRevealProperties();
redis = mock(StringRedisTemplate.class);
values = mock(ValueOperations.class);
when(redis.opsForValue()).thenReturn(values);
when(values.setIfAbsent(anyString(), eq("1"), any(Duration.class))).thenReturn(true);
}
private ProofOfWorkService service(Instant now) {
return new ProofOfWorkService(properties, redis, "test-secret", Clock.fixed(now, ZoneOffset.UTC));
}
/** Перебор, как в браузере. */
private static long solve(ProofOfWorkService.Challenge challenge) {
for (long n = 0; n <= challenge.maxNumber(); n++) {
if (ProofOfWorkService.sha256Hex(challenge.salt() + n).equals(challenge.challenge())) {
return n;
}
}
throw new AssertionError("задача не решается");
}
@Test
void solvedChallengeIsAcceptedForItsPost() {
ProofOfWorkService pow = service(NOW);
ProofOfWorkService.Challenge challenge = pow.create(42, 1000);
assertThat(challenge.algorithm()).isEqualTo("SHA-256");
assertThat(challenge.maxNumber()).isEqualTo(1000);
assertThat(pow.verify(challenge.salt(), solve(challenge), challenge.signature())).contains(42L);
}
@Test
void wrongNumberIsRejected() {
ProofOfWorkService pow = service(NOW);
ProofOfWorkService.Challenge challenge = pow.create(42, 1000);
long wrong = solve(challenge) + 1;
assertThat(pow.verify(challenge.salt(), wrong, challenge.signature())).isEmpty();
}
@Test
void saltForAnotherPostDoesNotMatchSignature() {
ProofOfWorkService pow = service(NOW);
ProofOfWorkService.Challenge challenge = pow.create(42, 1000);
String forged = challenge.salt().replace(".42.", ".43.");
assertThat(pow.verify(forged, solve(challenge), challenge.signature())).isEmpty();
}
@Test
void expiredChallengeIsRejected() {
ProofOfWorkService.Challenge challenge = service(NOW).create(42, 1000);
long number = solve(challenge);
ProofOfWorkService later = service(NOW.plus(properties.getChallengeTtl()).plusSeconds(1));
assertThat(later.verify(challenge.salt(), number, challenge.signature())).isEmpty();
}
@Test
void solutionCannotBeUsedTwice() {
ProofOfWorkService pow = service(NOW);
ProofOfWorkService.Challenge challenge = pow.create(42, 1000);
long number = solve(challenge);
when(values.setIfAbsent(anyString(), eq("1"), any(Duration.class))).thenReturn(true, false);
assertThat(pow.verify(challenge.salt(), number, challenge.signature())).isPresent();
assertThat(pow.verify(challenge.salt(), number, challenge.signature())).isEmpty();
}
@Test
void redisOutageDoesNotBlockValidSolution() {
ProofOfWorkService pow = service(NOW);
ProofOfWorkService.Challenge challenge = pow.create(42, 1000);
when(values.setIfAbsent(anyString(), eq("1"), any(Duration.class)))
.thenThrow(new RedisConnectionFailureException("down"));
assertThat(pow.verify(challenge.salt(), solve(challenge), challenge.signature())).contains(42L);
}
@Test
void garbageInputIsRejectedWithoutExceptions() {
ProofOfWorkService pow = service(NOW);
assertThat(pow.verify(null, 1L, "ab")).isEmpty();
assertThat(pow.verify("a.b.c", 1L, "ab")).isEmpty();
assertThat(pow.verify("aa.1." + NOW.getEpochSecond(), 1L, "not-hex")).isEmpty();
assertThat(pow.verify("aa.1." + NOW.getEpochSecond(), -1L, "ab")).isEqualTo(Optional.empty());
}
@Test
void difficultyGrowsWithRevealsAndIsCapped() {
ProofOfWorkService pow = service(NOW);
assertThat(pow.maxNumberFor(0)).isEqualTo(100_000);
assertThat(pow.maxNumberFor(4)).isEqualTo(100_000);
assertThat(pow.maxNumberFor(5)).isEqualTo(400_000);
assertThat(pow.maxNumberFor(10)).isEqualTo(1_600_000);
assertThat(pow.maxNumberFor(1_000)).isEqualTo(5_000_000);
}
}