Add anti-fraud verification questions and scam warnings
- posts can carry up to 3 verification questions (post_verification_questions,
changelog 026); to contact the author one answers them first
- POST /api/v1/posts/{id}/claim creates a PENDING chat with the answers as a
CLAIM message; the claimant cannot write or see the phone until the author
approves via POST /api/v1/chats/{chatId}/verification
- plain first message to such a post and phone reveal return 403
VERIFICATION_REQUIRED; GET /api/v1/chats/{chatId} exposes the status
- FraudSignals flags prepayment, card data (Luhn) and SMS-code requests in
messages (MessageDto.fraudSignal); ChatDto.otherUserCreatedAt for new accounts
- claim limits: 5 per day per account, 2 per post per 30 days, 10/h per IP
- docs/anti-fraud.md, tests
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,245 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
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.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
import com.krylov.refound.dto.ChatDto;
|
||||
import com.krylov.refound.dto.ClaimAnswerDto;
|
||||
import com.krylov.refound.dto.MessageDto;
|
||||
import com.krylov.refound.entity.Chat;
|
||||
import com.krylov.refound.entity.Message;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.enums.FraudSignal;
|
||||
import com.krylov.refound.enums.MessageKind;
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import com.krylov.refound.enums.PostType;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
import com.krylov.refound.repository.MessageAttachmentRepository;
|
||||
import com.krylov.refound.repository.MessageRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import com.krylov.refound.service.antifraud.AntiFraudProperties;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
class ChatClaimServiceTest {
|
||||
|
||||
private static final long OWNER = 19L;
|
||||
private static final long CLAIMANT = 14L;
|
||||
private static final long POST = 41L;
|
||||
|
||||
private ChatRepository chatRepository;
|
||||
private PostRepository postRepository;
|
||||
private MessageRepository messageRepository;
|
||||
private RedisRateLimiter rateLimiter;
|
||||
private ChatService chatService;
|
||||
private ChatClaimService claimService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
chatRepository = mock(ChatRepository.class);
|
||||
postRepository = mock(PostRepository.class);
|
||||
messageRepository = mock(MessageRepository.class);
|
||||
rateLimiter = mock(RedisRateLimiter.class);
|
||||
UserRepository userRepository = mock(UserRepository.class);
|
||||
chatService = new ChatService(chatRepository, messageRepository, mock(ClusterMessaging.class),
|
||||
userRepository, postRepository, mock(MessageAttachmentRepository.class), mock(ChatAttachmentService.class),
|
||||
mock(TransactionTemplate.class), mock(ChatVideoUploadService.class), mock(ApplicationEventPublisher.class));
|
||||
claimService = new ChatClaimService(postRepository, chatRepository, chatService, rateLimiter,
|
||||
new AntiFraudProperties());
|
||||
|
||||
when(userRepository.existsById(anyLong())).thenReturn(true);
|
||||
when(chatRepository.findByUsersAndPost(any(), any(), any())).thenReturn(List.of());
|
||||
when(chatRepository.save(any(Chat.class))).thenAnswer(inv -> {
|
||||
Chat chat = inv.getArgument(0);
|
||||
chat.setId(100L);
|
||||
return chat;
|
||||
});
|
||||
when(messageRepository.save(any(Message.class))).thenAnswer(inv -> {
|
||||
Message message = inv.getArgument(0);
|
||||
message.setId(500L);
|
||||
return message;
|
||||
});
|
||||
when(rateLimiter.hit(anyString(), anyString(), anyInt(), any()))
|
||||
.thenReturn(new RedisRateLimiter.Decision(true, 1, 1));
|
||||
}
|
||||
|
||||
private Post foundWithQuestions(String... questions) {
|
||||
User owner = new User();
|
||||
owner.setId(OWNER);
|
||||
Post post = new Post();
|
||||
post.setId(POST);
|
||||
post.setUser(owner);
|
||||
post.setType(PostType.FOUND);
|
||||
post.setStatus(PostStatus.ACTIVE);
|
||||
post.setVerificationQuestions(new ArrayList<>(List.of(questions)));
|
||||
when(postRepository.findById(POST)).thenReturn(Optional.of(post));
|
||||
return post;
|
||||
}
|
||||
|
||||
private Chat pendingChat() {
|
||||
Chat chat = new Chat();
|
||||
chat.setId(100L);
|
||||
chat.setUserOneId(CLAIMANT);
|
||||
chat.setUserTwoId(OWNER);
|
||||
chat.setPostId(POST);
|
||||
chat.setVerificationStatus(ChatVerificationStatus.PENDING);
|
||||
chat.setClaimantId(CLAIMANT);
|
||||
when(chatRepository.findById(100L)).thenReturn(Optional.of(chat));
|
||||
return chat;
|
||||
}
|
||||
|
||||
@Test
|
||||
void claimCreatesPendingChatWithAnswersAsFirstMessage() {
|
||||
foundWithQuestions("Что на брелке?", "Какого цвета чехол?");
|
||||
|
||||
ChatDto chat = claimService.claim(CLAIMANT, POST, List.of(" Сова ", "Синий"));
|
||||
|
||||
assertThat(chat.getVerificationStatus()).isEqualTo(ChatVerificationStatus.PENDING);
|
||||
assertThat(chat.getClaimantId()).isEqualTo(CLAIMANT);
|
||||
ArgumentCaptor<Message> saved = ArgumentCaptor.forClass(Message.class);
|
||||
verify(messageRepository).save(saved.capture());
|
||||
Message message = saved.getValue();
|
||||
assertThat(message.getKind()).isEqualTo(MessageKind.CLAIM);
|
||||
assertThat(message.getContent()).contains("Что на брелке?").contains("— Сова");
|
||||
assertThat(ClaimPayload.readAnswers(message.getPayload())).containsExactly(
|
||||
new ClaimAnswerDto("Что на брелке?", "Сова"), new ClaimAnswerDto("Какого цвета чехол?", "Синий"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lossOwnerQuestionsStopFakeFinderBeforeChat() {
|
||||
// Главная схема: «нашёл вашу вещь, оплатите доставку» — к потере только через ответы
|
||||
foundWithQuestions("Что выгравировано на обороте?").setType(PostType.LOSS);
|
||||
|
||||
assertThatThrownBy(() -> chatService.startChat(CLAIMANT, OWNER, POST, "Нашёл, оплатите доставку"))
|
||||
.isInstanceOfSatisfying(ApiException.class,
|
||||
e -> assertThat(e.getErrorCode()).isEqualTo(ErrorCode.VERIFICATION_REQUIRED));
|
||||
ChatDto chat = claimService.claim(CLAIMANT, POST, List.of("Инициалы А.К."));
|
||||
|
||||
assertThat(chat.getVerificationStatus()).isEqualTo(ChatVerificationStatus.PENDING);
|
||||
}
|
||||
|
||||
@Test
|
||||
void claimRequiresAnswerToEveryQuestion() {
|
||||
foundWithQuestions("Что на брелке?", "Какого цвета чехол?");
|
||||
|
||||
assertThatThrownBy(() -> claimService.claim(CLAIMANT, POST, List.of("Сова", " ")))
|
||||
.isInstanceOf(ApiException.class);
|
||||
assertThatThrownBy(() -> claimService.claim(CLAIMANT, POST, List.of("Сова")))
|
||||
.isInstanceOf(ApiException.class);
|
||||
verify(chatRepository, never()).save(any());
|
||||
verify(rateLimiter, never()).hit(anyString(), anyString(), anyInt(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void claimOverDailyLimitIsRejected() {
|
||||
foundWithQuestions("Что на брелке?");
|
||||
when(rateLimiter.hit(eq(ChatClaimService.RULE_CLAIM_DAY), anyString(), anyInt(), any()))
|
||||
.thenReturn(new RedisRateLimiter.Decision(false, 6, 600));
|
||||
|
||||
assertThatThrownBy(() -> claimService.claim(CLAIMANT, POST, List.of("Сова")))
|
||||
.isInstanceOfSatisfying(ApiException.class,
|
||||
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS));
|
||||
verify(chatRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainFirstMessageToFoundWithQuestionsIsRefused() {
|
||||
foundWithQuestions("Что на брелке?");
|
||||
|
||||
assertThatThrownBy(() -> chatService.startChat(CLAIMANT, OWNER, POST, "Это моё, вышлите доставкой"))
|
||||
.isInstanceOfSatisfying(ApiException.class,
|
||||
e -> assertThat(e.getErrorCode()).isEqualTo(ErrorCode.VERIFICATION_REQUIRED));
|
||||
verify(chatRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownerCanStillWriteFirstToClaimantOfOwnFound() {
|
||||
foundWithQuestions("Что на брелке?");
|
||||
|
||||
ChatDto chat = chatService.startChat(OWNER, CLAIMANT, POST, "Здравствуйте");
|
||||
|
||||
assertThat(chat.getVerificationStatus()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void claimantCannotWriteUntilApprovedButOwnerCan() {
|
||||
pendingChat();
|
||||
|
||||
assertThatThrownBy(() -> chatService.sendMessage(CLAIMANT, 100L, "Ну что?"))
|
||||
.isInstanceOfSatisfying(ApiException.class,
|
||||
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||
chatService.sendMessage(OWNER, 100L, "Какая наклейка на обороте?");
|
||||
verify(messageRepository).save(any(Message.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void approvalUnlocksChatAndIsBroadcastAsVerificationMessage() {
|
||||
Chat chat = pendingChat();
|
||||
|
||||
MessageDto decision = claimService.decide(OWNER, 100L, true);
|
||||
|
||||
assertThat(chat.getVerificationStatus()).isEqualTo(ChatVerificationStatus.APPROVED);
|
||||
assertThat(chat.getVerifiedAt()).isNotNull();
|
||||
assertThat(decision.getKind()).isEqualTo(MessageKind.VERIFICATION);
|
||||
assertThat(decision.getVerificationStatus()).isEqualTo(ChatVerificationStatus.APPROVED);
|
||||
chatService.sendMessage(CLAIMANT, 100L, "Спасибо!");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyOwnerDecidesAndApprovalIsFinal() {
|
||||
Chat chat = pendingChat();
|
||||
|
||||
assertThatThrownBy(() -> claimService.decide(CLAIMANT, 100L, true))
|
||||
.isInstanceOfSatisfying(ApiException.class,
|
||||
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||
|
||||
claimService.decide(OWNER, 100L, false);
|
||||
assertThat(chat.getVerificationStatus()).isEqualTo(ChatVerificationStatus.REJECTED);
|
||||
// Отклонение можно исправить на подтверждение, но не наоборот
|
||||
claimService.decide(OWNER, 100L, true);
|
||||
assertThatThrownBy(() -> claimService.decide(OWNER, 100L, false))
|
||||
.isInstanceOfSatisfying(ApiException.class,
|
||||
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.CONFLICT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void messagesWithPrepaymentRequestCarryFraudSignal() {
|
||||
Chat chat = pendingChat();
|
||||
chat.setVerificationStatus(null);
|
||||
Message message = new Message();
|
||||
message.setId(1L);
|
||||
message.setChatId(100L);
|
||||
message.setSenderId(OWNER);
|
||||
message.setContent("Нашёл ваш кошелёк, переведите 500 ₽ за доставку курьером");
|
||||
when(messageRepository.findByChatIdOrderByCreatedAtDesc(eq(100L), any()))
|
||||
.thenReturn(new org.springframework.data.domain.PageImpl<>(List.of(message)));
|
||||
|
||||
MessageDto dto = chatService.getMessages(100L, CLAIMANT, org.springframework.data.domain.Pageable.unpaged())
|
||||
.getContent().get(0);
|
||||
|
||||
assertThat(dto.getFraudSignal()).isEqualTo(FraudSignal.PREPAYMENT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.krylov.refound.service.antifraud;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.krylov.refound.enums.FraudSignal;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FraudSignalsTest {
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"Нужна предоплата 50%, потом отправлю",
|
||||
"Переведите 300 рублей, и я отправлю СДЭКом",
|
||||
"оплатите доставку курьером, он привезёт",
|
||||
"Скиньте на карту за пересылку",
|
||||
"Доставка платная, 450 руб",
|
||||
"Скинь по СБП, номер тот же",
|
||||
"Нужен залог, чтобы я не ездил зря"})
|
||||
void detectsPrepaymentRequests(String text) {
|
||||
assertThat(FraudSignals.detect(text)).isEqualTo(FraudSignal.PREPAYMENT);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"Вам придёт код из СМС, продиктуйте его",
|
||||
"Назовите код, который пришёл",
|
||||
"Скажите смс-код для подтверждения",
|
||||
"Зайдите в Госуслуги и подтвердите"})
|
||||
void detectsSmsCodeRequests(String text) {
|
||||
assertThat(FraudSignals.detect(text)).isEqualTo(FraudSignal.SMS_CODE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void detectsValidCardNumberAndCvv() {
|
||||
assertThat(FraudSignals.detect("Моя карта 4276 3800 1234 5679")).isEqualTo(FraudSignal.CARD_DATA);
|
||||
assertThat(FraudSignals.detect("и ещё CVV с обратной стороны")).isEqualTo(FraudSignal.CARD_DATA);
|
||||
}
|
||||
|
||||
@Test
|
||||
void smsCodeOutranksPrepayment() {
|
||||
assertThat(FraudSignals.detect("Переведите предоплату и продиктуйте код из смс"))
|
||||
.isEqualTo(FraudSignal.SMS_CODE);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"Здравствуйте! Это мой кот, на ошейнике бирка с именем Барсик",
|
||||
"Могу подъехать завтра к метро в 18:00",
|
||||
"Мой номер +7 999 123-45-67",
|
||||
"Трек-номер посылки 1234567890123",
|
||||
"Спасибо огромное, что нашли!"})
|
||||
void ordinaryMessagesAreClean(String text) {
|
||||
assertThat(FraudSignals.detect(text)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void luhnRejectsRandomLongNumbers() {
|
||||
assertThat(FraudSignals.luhnValid("4276380012345679")).isTrue();
|
||||
assertThat(FraudSignals.luhnValid("4276380012345678")).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,12 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.ChatVerificationStatus;
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import com.krylov.refound.enums.PostType;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
@@ -47,13 +50,15 @@ class PhoneRevealServiceTest {
|
||||
private StringRedisTemplate redis;
|
||||
@Mock
|
||||
private ValueOperations<String, String> values;
|
||||
@Mock
|
||||
private ChatRepository chatRepository;
|
||||
|
||||
private final PhoneRevealProperties properties = new PhoneRevealProperties();
|
||||
private PhoneRevealService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new PhoneRevealService(postRepository, proofOfWork, rateLimiter, redis, properties);
|
||||
service = new PhoneRevealService(postRepository, proofOfWork, rateLimiter, redis, properties, chatRepository);
|
||||
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);
|
||||
@@ -76,7 +81,7 @@ class PhoneRevealServiceTest {
|
||||
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);
|
||||
assertThat(service.challenge(1L, IP, null)).isSameAs(challenge);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -101,6 +106,50 @@ class PhoneRevealServiceTest {
|
||||
verify(rateLimiter, never()).hit(anyString(), anyString(), anyInt(), any());
|
||||
}
|
||||
|
||||
private static Post foundWithQuestions() {
|
||||
Post post = post(PostStatus.ACTIVE, true, "+79991112233");
|
||||
post.setType(PostType.FOUND);
|
||||
post.setVerificationQuestions(new java.util.ArrayList<>(List.of("Что на брелке?")));
|
||||
User author = new User();
|
||||
author.setId(9L);
|
||||
post.setUser(author);
|
||||
return post;
|
||||
}
|
||||
|
||||
@Test
|
||||
void foundWithQuestionsHidesPhoneUntilAnswersApproved() {
|
||||
when(postRepository.findById(1L)).thenReturn(Optional.of(foundWithQuestions()));
|
||||
when(chatRepository.existsByClaimantIdAndPostIdAndVerificationStatus(5L, 1L, ChatVerificationStatus.APPROVED))
|
||||
.thenReturn(false);
|
||||
|
||||
assertThatThrownBy(() -> service.challenge(1L, IP, 5L))
|
||||
.isInstanceOfSatisfying(ApiException.class,
|
||||
e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.FORBIDDEN));
|
||||
assertThatThrownBy(() -> service.challenge(1L, IP, null)).isInstanceOf(ApiException.class);
|
||||
// Кнопку видят все — это не перебор, IP не штрафуем
|
||||
verify(rateLimiter, never()).hit(eq(PhoneRevealService.RULE_STRIKE), anyString(), anyInt(), any());
|
||||
verify(proofOfWork, never()).create(anyLong(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void approvedClaimantSeesPhoneOfFoundWithQuestions() {
|
||||
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(1L));
|
||||
when(postRepository.findById(1L)).thenReturn(Optional.of(foundWithQuestions()));
|
||||
when(chatRepository.existsByClaimantIdAndPostIdAndVerificationStatus(5L, 1L, ChatVerificationStatus.APPROVED))
|
||||
.thenReturn(true);
|
||||
|
||||
assertThat(service.reveal(1L, "s", 5L, "sig", IP, 5L)).isEqualTo("+79991112233");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownerOfFoundWithQuestionsSeesOwnPhone() {
|
||||
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(1L));
|
||||
when(postRepository.findById(1L)).thenReturn(Optional.of(foundWithQuestions()));
|
||||
|
||||
assertThat(service.reveal(1L, "s", 5L, "sig", IP, 9L)).isEqualTo("+79991112233");
|
||||
verify(chatRepository, never()).existsByClaimantIdAndPostIdAndVerificationStatus(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void solutionForAnotherPostIsRejectedAsStrike() {
|
||||
when(proofOfWork.verify("s", 5L, "sig")).thenReturn(Optional.of(2L));
|
||||
@@ -116,7 +165,7 @@ class PhoneRevealServiceTest {
|
||||
void postWithoutConsentIsNotFoundAndCountsAsStrike() {
|
||||
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.ACTIVE, false, null)));
|
||||
|
||||
assertThatThrownBy(() -> service.challenge(1L, IP))
|
||||
assertThatThrownBy(() -> service.challenge(1L, IP, null))
|
||||
.isInstanceOf(ApiException.class)
|
||||
.extracting(e -> ((ApiException) e).getStatus()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
verify(rateLimiter).hit(eq(PhoneRevealService.RULE_STRIKE), eq(IP), anyInt(), any());
|
||||
@@ -126,7 +175,7 @@ class PhoneRevealServiceTest {
|
||||
void closedPostDoesNotShowPhone() {
|
||||
when(postRepository.findById(1L)).thenReturn(Optional.of(post(PostStatus.CLOSED, true, "+79991112233")));
|
||||
|
||||
assertThatThrownBy(() -> service.challenge(1L, IP)).isInstanceOf(ApiException.class);
|
||||
assertThatThrownBy(() -> service.challenge(1L, IP, null)).isInstanceOf(ApiException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -135,7 +184,7 @@ class PhoneRevealServiceTest {
|
||||
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);
|
||||
assertThatThrownBy(() -> service.challenge(99L, IP, null)).isInstanceOf(ApiException.class);
|
||||
verify(values).set(eq("phone-ban:" + IP), eq("1"), eq(properties.getBanDuration()));
|
||||
}
|
||||
|
||||
@@ -143,7 +192,7 @@ class PhoneRevealServiceTest {
|
||||
void trapPostBansImmediately() {
|
||||
properties.setTrapPostIds(List.of(777L));
|
||||
|
||||
assertThatThrownBy(() -> service.challenge(777L, IP)).isInstanceOf(ApiException.class);
|
||||
assertThatThrownBy(() -> service.challenge(777L, IP, null)).isInstanceOf(ApiException.class);
|
||||
verify(values).set(eq("phone-ban:" + IP), eq("1"), any(Duration.class));
|
||||
verify(postRepository, never()).findById(anyLong());
|
||||
}
|
||||
@@ -152,7 +201,7 @@ class PhoneRevealServiceTest {
|
||||
void bannedIpGets429WithRetryAfter() {
|
||||
when(redis.getExpire("phone-ban:" + IP, TimeUnit.SECONDS)).thenReturn(3600L);
|
||||
|
||||
assertThatThrownBy(() -> service.challenge(1L, IP))
|
||||
assertThatThrownBy(() -> service.challenge(1L, IP, null))
|
||||
.isInstanceOfSatisfying(ApiException.class, e -> {
|
||||
assertThat(e.getStatus()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
|
||||
assertThat(e.getRetryAfterSeconds()).isEqualTo(3600L);
|
||||
|
||||
Reference in New Issue
Block a user