From 1cd72fbec44278eb397b3341a31da22cde0ddbf9 Mon Sep 17 00:00:00 2001 From: SlimusMinus Date: Tue, 27 Oct 2026 22:49:16 +0300 Subject: [PATCH] fixed show phone number --- .env.example | 5 + docs/phone-protection.md | 66 +++++++ .../krylov/refound/ReFoundApplication.java | 3 +- .../controller/PhoneRevealController.java | 61 ++++++ .../refound/controller/PostController.java | 6 +- .../refound/dto/PhoneRevealRequest.java | 5 + .../refound/dto/PhoneRevealResponse.java | 5 + .../com/krylov/refound/dto/PostRequest.java | 2 + .../com/krylov/refound/dto/PostResponse.java | 7 + .../refound/dto/admin/AdminPostResponse.java | 2 + .../java/com/krylov/refound/entity/Post.java | 8 + .../refound/exception/ApiException.java | 7 + .../exception/GlobalExceptionHandler.java | 9 +- .../com/krylov/refound/mapper/PostMapper.java | 7 + .../refound/security/SecurityConfig.java | 2 + .../krylov/refound/service/PostService.java | 65 ++++++- .../service/admin/AdminPostService.java | 8 +- .../service/phone/PhoneRevealProperties.java | 59 ++++++ .../service/phone/PhoneRevealService.java | 151 +++++++++++++++ .../service/phone/ProofOfWorkService.java | 148 +++++++++++++++ .../krylov/refound/util/PostFieldLimits.java | 14 ++ src/main/resources/application.yaml | 30 +++ .../add/023-add-phone-visible-posts.yaml | 25 +++ .../db/changelog/db.changelog-master.yaml | 1 + .../refound/service/PostPhoneConsentTest.java | 66 +++++++ .../service/phone/PhoneRevealServiceTest.java | 176 ++++++++++++++++++ .../service/phone/ProofOfWorkServiceTest.java | 131 +++++++++++++ 27 files changed, 1054 insertions(+), 15 deletions(-) create mode 100644 docs/phone-protection.md create mode 100644 src/main/java/com/krylov/refound/controller/PhoneRevealController.java create mode 100644 src/main/java/com/krylov/refound/dto/PhoneRevealRequest.java create mode 100644 src/main/java/com/krylov/refound/dto/PhoneRevealResponse.java create mode 100644 src/main/java/com/krylov/refound/service/phone/PhoneRevealProperties.java create mode 100644 src/main/java/com/krylov/refound/service/phone/PhoneRevealService.java create mode 100644 src/main/java/com/krylov/refound/service/phone/ProofOfWorkService.java create mode 100644 src/main/resources/db/changelog/add/023-add-phone-visible-posts.yaml create mode 100644 src/test/java/com/krylov/refound/service/PostPhoneConsentTest.java create mode 100644 src/test/java/com/krylov/refound/service/phone/PhoneRevealServiceTest.java create mode 100644 src/test/java/com/krylov/refound/service/phone/ProofOfWorkServiceTest.java diff --git a/.env.example b/.env.example index 21017c4..eb9849c 100644 --- a/.env.example +++ b/.env.example @@ -53,3 +53,8 @@ JWT_SECRET= # JWT_REFRESH_EXPIRATION=604800000 # JPA_DDL_AUTO=validate # JPA_SHOW_SQL=false + +# Защита номеров от сбора (docs/phone-protection.md) +# PHONE_REVEAL_SECRET= +# id объявлений-ловушек через запятую +# PHONE_TRAP_POST_IDS= diff --git a/docs/phone-protection.md b/docs/phone-protection.md new file mode 100644 index 0000000..7a02e6e --- /dev/null +++ b/docs/phone-protection.md @@ -0,0 +1,66 @@ +# Номера телефонов: согласие и защита от сбора + +## Согласие (152-ФЗ) + +- По умолчанию объявление в режиме «только чат»: `posts.phone_visible = false`, номер не хранится. +- Номер сохраняется только с явной галочкой «Показывать мой номер…» в форме (`phoneVisible=true`). + Время согласия — `posts.phone_consent_at`. Без галочки или после её снятия номер стирается. +- У объявлений, созданных до миграции 023, явного согласия не было: их номера скрыты, + пока автор не отредактирует объявление и не поставит галочку. +- Админ может поправить или убрать номер, но не включить показ за автора. + +## Как отдаётся номер + +В ленте, на карте, в избранном и в кэше Redis номера нет: `PostResponse.phone` заполняется +только для автора (свои объявления, ответы на создание и правку). Остальные видят +`phoneVisible: true` и кнопку «Показать номер»: + +1. `GET /api/v1/posts/{id}/phone/challenge` → задача proof-of-work (формат ALTCHA: + `algorithm, challenge, salt, maxNumber, signature`). +2. Браузер перебирает `n` до `SHA-256(salt + n) == challenge` (`src/utils/proofOfWork.js`). +3. `POST /api/v1/posts/{id}/phone` `{salt, number, signature}` → `{phone}`. + +Задача подписана HMAC, привязана к объявлению, живёт 2 минуты и принимается один раз. +Номер отдаётся только у активных объявлений с согласием. Оба эндпоинта публичные, +регистрация не нужна. + +Время решения (JS, худший случай, десктоп; телефон в 3–5 раз медленнее, в среднем — вдвое быстрее): + +| maxNumber | когда | время | +|---|---|---| +| 100 000 | первые 5 номеров за час с IP | ~0,15 с | +| 400 000 | 5–9 | ~0,5 с | +| 1 600 000 | 10–14 | ~1,6 с | +| 5 000 000 | 15+ (предел) | ~4,5 с | + +## Лимиты и ловушки (`phone-reveal.*`) + +- С IP: 30 номеров в час, 100 в сутки; с аккаунта — 50 в сутки. Сверх — 429 с `Retry-After`. +- Всплески: `rate-limit.rules` — 20 задач и 10 открытий в минуту с IP. +- Подозрительные запросы — те, что интерфейс не делает: номер объявления без номера, + закрытого или несуществующего; неверное решение. 5 таких за час → бан IP на 24 часа + (ответ — тот же 429, причину не раскрываем). +- Объявления-ловушки: `PHONE_TRAP_POST_IDS=900001,900002` — запрос номера по ним сразу банит IP. + Берите id удалённых объявлений или далеко за текущим максимумом. +- Каждый показ пишется в лог: `Показан номер: postId=…, ip=…, userId=…`. + +## nginx перед API (если есть) + +Бесплатный первый рубеж до Spring; IP клиента в Spring приходит через `X-Forwarded-For`. + +```nginx +limit_req_zone $binary_remote_addr zone=phone:10m rate=10r/m; + +location ~ ^/api/v1/posts/\d+/phone { + limit_req zone=phone burst=5 nodelay; + limit_req_status 429; + proxy_pass http://backend; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; +} +``` + +## Ограничения + +Абсолютной защиты нет: сборщик на резидентных прокси с настоящим браузером обойдёт всё. +Цель — сделать массовый сбор дорогим. Id объявлений остаются последовательными: +лента и так отдаёт их все, поэтому UUID тут почти ничего не добавляют. diff --git a/src/main/java/com/krylov/refound/ReFoundApplication.java b/src/main/java/com/krylov/refound/ReFoundApplication.java index a5a3b10..e968d31 100644 --- a/src/main/java/com/krylov/refound/ReFoundApplication.java +++ b/src/main/java/com/krylov/refound/ReFoundApplication.java @@ -6,6 +6,7 @@ import com.krylov.refound.config.MinioProperties; import com.krylov.refound.ratelimit.RateLimitProperties; import com.krylov.refound.search.SearchProperties; import com.krylov.refound.service.advertising.AdsProperties; +import com.krylov.refound.service.phone.PhoneRevealProperties; import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -19,7 +20,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class } )@EnableScheduling @EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class, - SearchProperties.class, RateLimitProperties.class, AdsProperties.class}) + SearchProperties.class, RateLimitProperties.class, AdsProperties.class, PhoneRevealProperties.class}) @EnableRetry public class ReFoundApplication { diff --git a/src/main/java/com/krylov/refound/controller/PhoneRevealController.java b/src/main/java/com/krylov/refound/controller/PhoneRevealController.java new file mode 100644 index 0000000..bff7d11 --- /dev/null +++ b/src/main/java/com/krylov/refound/controller/PhoneRevealController.java @@ -0,0 +1,61 @@ +package com.krylov.refound.controller; + +import com.krylov.refound.dto.PhoneRevealRequest; +import com.krylov.refound.dto.PhoneRevealResponse; +import com.krylov.refound.entity.User; +import com.krylov.refound.exception.ApiException; +import com.krylov.refound.service.UserService; +import com.krylov.refound.service.phone.PhoneRevealService; +import com.krylov.refound.service.phone.ProofOfWorkService; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.http.CacheControl; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Показ номера автора: сначала задача proof-of-work, затем номер в обмен на + * решение. Оба эндпоинта публичные — позвонить можно без регистрации. + * IP — {@code request.getRemoteAddr()}, за прокси восстанавливается из + * X-Forwarded-For (server.forward-headers-strategy). + */ +@RestController +@RequestMapping("/api/v1/posts/{id:\\d+}/phone") +@RequiredArgsConstructor +public class PhoneRevealController { + + private final PhoneRevealService phoneRevealService; + private final UserService userService; + + @GetMapping("/challenge") + public ResponseEntity challenge(@PathVariable Long id, HttpServletRequest request) { + return ResponseEntity.ok() + .cacheControl(CacheControl.noStore()) + .body(phoneRevealService.challenge(id, request.getRemoteAddr())); + } + + @PostMapping + public ResponseEntity reveal(@PathVariable Long id, @RequestBody PhoneRevealRequest body, + HttpServletRequest request) { + String phone = phoneRevealService.reveal(id, body.salt(), body.number(), body.signature(), + request.getRemoteAddr(), currentUserId()); + return ResponseEntity.ok() + .cacheControl(CacheControl.noStore()) + .body(new PhoneRevealResponse(phone)); + } + + /** id пользователя с токеном или null для анонимного запроса. */ + private Long currentUserId() { + try { + User user = userService.getCurrentUser(); + return user == null ? null : user.getId(); + } catch (ApiException e) { + return null; + } + } +} diff --git a/src/main/java/com/krylov/refound/controller/PostController.java b/src/main/java/com/krylov/refound/controller/PostController.java index 58f2eca..d51e69b 100644 --- a/src/main/java/com/krylov/refound/controller/PostController.java +++ b/src/main/java/com/krylov/refound/controller/PostController.java @@ -90,11 +90,13 @@ public class PostController { @PutMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public PostResponse update(@PathVariable Long id, @RequestParam String type, @RequestParam String title, @RequestParam(required = false) String address, @RequestParam(required = false) Double latitude, @RequestParam(required = false) Double longitude, @RequestParam(required = false) String description, - @RequestParam(required = false) String category, @RequestParam(required = false) String phone, @RequestParam(required = false) Boolean reward, + @RequestParam(required = false) String category, @RequestParam(required = false) String phone, + @RequestParam(required = false) Boolean phoneVisible, @RequestParam(required = false) Boolean reward, @RequestParam(required = false) String rewardText, @RequestParam(value = "images", required = false) List images, @RequestParam(value = "existingImages", required = false) String existingImagesJson) { log.info("update post {}", id); - return service.update(id, type, title, address, latitude, longitude, description, category, phone, reward, rewardText, images, existingImagesJson); + return service.update(id, type, title, address, latitude, longitude, description, category, phone, phoneVisible, reward, rewardText, images, + existingImagesJson); } @DeleteMapping("/{id}") diff --git a/src/main/java/com/krylov/refound/dto/PhoneRevealRequest.java b/src/main/java/com/krylov/refound/dto/PhoneRevealRequest.java new file mode 100644 index 0000000..9332b18 --- /dev/null +++ b/src/main/java/com/krylov/refound/dto/PhoneRevealRequest.java @@ -0,0 +1,5 @@ +package com.krylov.refound.dto; + +/** Решение proof-of-work задачи из GET /api/v1/posts/{id}/phone/challenge. */ +public record PhoneRevealRequest(String salt, Long number, String signature) { +} diff --git a/src/main/java/com/krylov/refound/dto/PhoneRevealResponse.java b/src/main/java/com/krylov/refound/dto/PhoneRevealResponse.java new file mode 100644 index 0000000..df708f1 --- /dev/null +++ b/src/main/java/com/krylov/refound/dto/PhoneRevealResponse.java @@ -0,0 +1,5 @@ +package com.krylov.refound.dto; + +/** Номер автора объявления (POST /api/v1/posts/{id}/phone). */ +public record PhoneRevealResponse(String phone) { +} diff --git a/src/main/java/com/krylov/refound/dto/PostRequest.java b/src/main/java/com/krylov/refound/dto/PostRequest.java index 8fc61cc..2556fd2 100644 --- a/src/main/java/com/krylov/refound/dto/PostRequest.java +++ b/src/main/java/com/krylov/refound/dto/PostRequest.java @@ -14,6 +14,8 @@ public class PostRequest { private String description; private String category; private String phone; + /** Явное согласие на показ номера другим пользователям; без него номер не сохраняется. */ + private Boolean phoneVisible; private String imageUrl; private Double latitude; private Double longitude; diff --git a/src/main/java/com/krylov/refound/dto/PostResponse.java b/src/main/java/com/krylov/refound/dto/PostResponse.java index fcfb654..a457df2 100644 --- a/src/main/java/com/krylov/refound/dto/PostResponse.java +++ b/src/main/java/com/krylov/refound/dto/PostResponse.java @@ -29,7 +29,14 @@ public class PostResponse { private LocalDateTime closedAt; /** Логин автора. */ private String userLogin; + /** + * Номер автора — только в ответах самому автору (свои объявления, правка). + * Остальные получают номер через POST /api/v1/posts/{id}/phone с решённой + * proof-of-work задачей, чтобы его нельзя было собрать из ленты. + */ private String phone; + /** Автор разрешил показ номера: фронт показывает кнопку «Показать номер». */ + private boolean phoneVisible; private List images; private Long userId; private Role userRole; diff --git a/src/main/java/com/krylov/refound/dto/admin/AdminPostResponse.java b/src/main/java/com/krylov/refound/dto/admin/AdminPostResponse.java index eff7d3b..2203f47 100644 --- a/src/main/java/com/krylov/refound/dto/admin/AdminPostResponse.java +++ b/src/main/java/com/krylov/refound/dto/admin/AdminPostResponse.java @@ -31,6 +31,8 @@ public class AdminPostResponse { private Double latitude; private Double longitude; private String phone; + /** Автор согласился на показ номера; без согласия phone = null. */ + private boolean phoneVisible; private Boolean reward; private String rewardText; private LocalDateTime createdAt; diff --git a/src/main/java/com/krylov/refound/entity/Post.java b/src/main/java/com/krylov/refound/entity/Post.java index 972df45..13b27b9 100644 --- a/src/main/java/com/krylov/refound/entity/Post.java +++ b/src/main/java/com/krylov/refound/entity/Post.java @@ -44,7 +44,15 @@ public class Post { private Double latitude; private Double longitude; private LocalDateTime createdAt; + // Хранится только при согласии на показ (phoneVisible); без него — null private String phone; + // Согласие автора на показ номера другим пользователям (152-ФЗ). + // false — режим «только чат», по умолчанию. Ведётся в PostService.applyPhone + @Column(name = "phone_visible", nullable = false) + private boolean phoneVisible = false; + // Когда дано согласие на показ номера; сбрасывается при отзыве + @Column(name = "phone_consent_at") + private LocalDateTime phoneConsentAt; // В БД колонка boolean NOT NULL (changelog 013). Строка была рассинхронизирована // со схемой и ломала ddl-auto: validate. @Column(name = "rules_accepted", nullable = false) diff --git a/src/main/java/com/krylov/refound/exception/ApiException.java b/src/main/java/com/krylov/refound/exception/ApiException.java index 518fc3d..9d5127f 100644 --- a/src/main/java/com/krylov/refound/exception/ApiException.java +++ b/src/main/java/com/krylov/refound/exception/ApiException.java @@ -9,10 +9,17 @@ public class ApiException extends RuntimeException { private final ErrorCode errorCode; private final HttpStatus status; + /** Для 429: через сколько секунд повторить (заголовок Retry-After); null — не указывать. */ + private final Long retryAfterSeconds; public ApiException(ErrorCode errorCode, String message, HttpStatus status) { + this(errorCode, message, status, null); + } + + public ApiException(ErrorCode errorCode, String message, HttpStatus status, Long retryAfterSeconds) { super(message); this.errorCode = errorCode; this.status = status; + this.retryAfterSeconds = retryAfterSeconds; } } diff --git a/src/main/java/com/krylov/refound/exception/GlobalExceptionHandler.java b/src/main/java/com/krylov/refound/exception/GlobalExceptionHandler.java index 3e88cad..0e40f02 100644 --- a/src/main/java/com/krylov/refound/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/krylov/refound/exception/GlobalExceptionHandler.java @@ -9,6 +9,7 @@ import java.time.LocalDateTime; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.security.access.AccessDeniedException; @@ -37,7 +38,13 @@ public class GlobalExceptionHandler { @ExceptionHandler(ApiException.class) public ResponseEntity handleApiException(ApiException ex, HttpServletRequest request) { - return buildResponse(ex.getStatus(), ex.getErrorCode(), ex.getMessage(), request); + ResponseEntity response = buildResponse(ex.getStatus(), ex.getErrorCode(), ex.getMessage(), request); + if (ex.getRetryAfterSeconds() == null) { + return response; + } + return ResponseEntity.status(response.getStatusCode()) + .header(HttpHeaders.RETRY_AFTER, Long.toString(ex.getRetryAfterSeconds())) + .body(response.getBody()); } @ExceptionHandler(MethodArgumentNotValidException.class) diff --git a/src/main/java/com/krylov/refound/mapper/PostMapper.java b/src/main/java/com/krylov/refound/mapper/PostMapper.java index 9323f8c..20dc287 100644 --- a/src/main/java/com/krylov/refound/mapper/PostMapper.java +++ b/src/main/java/com/krylov/refound/mapper/PostMapper.java @@ -16,6 +16,10 @@ public interface PostMapper { @Mapping(source = "category", target = "category", qualifiedByName = "stringToPostCategory") @Mapping(source = "rewardText", target = "reward") @Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "stringToBoolean") + // Номер и согласие на его показ ставит PostService.applyPhone + @Mapping(target = "phone", ignore = true) + @Mapping(target = "phoneVisible", ignore = true) + @Mapping(target = "phoneConsentAt", ignore = true) Post toEntity(PostRequest request); @Mapping(source = "user.id", target = "userId") @@ -26,6 +30,9 @@ public interface PostMapper { @Mapping(source = "isReward", target = "reward") @Mapping(source = "reward", target = "rewardText") @Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "booleanToString") + // Номер в публичном ответе (лента, кэш ленты, избранное) не отдаётся: + // владельцу его добавляет PostService.toOwnerResponse + @Mapping(target = "phone", ignore = true) PostResponse toResponse(Post post); /** Фронт присылает правила как строку ("true"), в БД колонка boolean. */ diff --git a/src/main/java/com/krylov/refound/security/SecurityConfig.java b/src/main/java/com/krylov/refound/security/SecurityConfig.java index d5ca915..1a2ab95 100644 --- a/src/main/java/com/krylov/refound/security/SecurityConfig.java +++ b/src/main/java/com/krylov/refound/security/SecurityConfig.java @@ -64,6 +64,8 @@ public class SecurityConfig { .requestMatchers(HttpMethod.POST, "/api/v1/reviews/**").authenticated() .requestMatchers(HttpMethod.PUT, "/api/v1/reviews/**").authenticated() .requestMatchers(HttpMethod.DELETE, "/api/v1/reviews/**").authenticated() + // показ номера — без регистрации, защищён proof-of-work и лимитами (PhoneRevealService) + .requestMatchers(HttpMethod.POST, "/api/v1/posts/*/phone").permitAll() .requestMatchers(HttpMethod.POST, "/api/v1/posts/**").authenticated() .requestMatchers(HttpMethod.PUT, "/api/v1/posts/**").authenticated() .requestMatchers(HttpMethod.DELETE, "/api/v1/posts/**").authenticated() diff --git a/src/main/java/com/krylov/refound/service/PostService.java b/src/main/java/com/krylov/refound/service/PostService.java index c067cf1..e403402 100644 --- a/src/main/java/com/krylov/refound/service/PostService.java +++ b/src/main/java/com/krylov/refound/service/PostService.java @@ -82,6 +82,10 @@ public class PostService { public PostResponse create(PostRequest request, List images) { User currentUser = userService.getCurrentUser(); PostFieldLimits.validate(request.getTitle(), request.getAddress(), request.getPhone(), request.getRewardText()); + boolean phoneVisible = Boolean.TRUE.equals(request.getPhoneVisible()); + if (phoneVisible) { + PostFieldLimits.requirePhone(request.getPhone()); + } AddressInfo location = geocode(request.getLatitude(), request.getLongitude()); List imageKeys = uploadImages(images); @@ -94,6 +98,7 @@ public class PostService { post.setStatus(PostStatus.MODERATION); post.setUser(currentUser); post.setIsReward(request.getReward()); + applyPhone(post, request.getPhone(), phoneVisible); // Адрес из формы сохраняем как есть; геокодер заполняет только city/district post.setAddress(normalizeAddress(request.getAddress())); applyLocation(post, location, request.getAddress()); @@ -106,7 +111,7 @@ public class PostService { statisticsService.incrementCreated(); postCacheService.invalidatePosts(); // Ответ собираем в транзакции: картинки и автор — ленивые связи - return toResponse(post, true); + return toOwnerResponse(post, true); }); } catch (RuntimeException e) { postDeletionService.deleteFilesAfterCommit(imageKeys); @@ -196,10 +201,11 @@ public class PostService { */ @Transactional(readOnly = true) public Page getPostsByUser(Long userId, Pageable pageable) { - Page posts = isCurrentUser(userId) + boolean owner = isCurrentUser(userId); + Page posts = owner ? postRepository.findByUserId(userId, pageable) : postRepository.findByUserIdAndStatusIn(userId, FEED_VISIBLE_STATUSES, pageable); - return posts.map(post -> toResponse(post, false)); + return posts.map(post -> owner ? toOwnerResponse(post, false) : toResponse(post, false)); } /** @@ -207,8 +213,8 @@ public class PostService { * Как и при создании, геокодер и загрузка фото выполняются до транзакции. */ public PostResponse update(Long id, String type, String title, String address, Double latitude, - Double longitude, String description, String category, String phone, Boolean reward, - String rewardText, List images, String existingImagesJson) { + Double longitude, String description, String category, String phone, Boolean phoneVisible, + Boolean reward, String rewardText, List images, String existingImagesJson) { PostRequest request = new PostRequest(); request.setType(PostType.from(type)); @@ -216,12 +222,16 @@ public class PostService { request.setDescription(description); request.setCategory(category); request.setPhone(phone); + request.setPhoneVisible(phoneVisible); request.setLatitude(latitude); request.setLongitude(longitude); request.setAddress(address); request.setReward(reward); request.setRewardText(rewardText); PostFieldLimits.validate(title, address, phone, rewardText); + if (Boolean.TRUE.equals(phoneVisible)) { + PostFieldLimits.requirePhone(phone); + } List existingUrls = parseExistingImages(existingImagesJson); @@ -248,7 +258,9 @@ public class PostService { if (request.getCategory() != null) { post.setCategory(PostCategory.fromDisplayName(request.getCategory())); } - post.setPhone(request.getPhone()); + // Старый клиент не присылает phoneVisible — тогда согласие не меняется + boolean phoneVisible = request.getPhoneVisible() != null ? request.getPhoneVisible() : post.isPhoneVisible(); + applyPhone(post, request.getPhone(), phoneVisible); post.setType(request.getType()); post.setIsReward(request.getReward()); post.setReward(request.getRewardText()); @@ -273,7 +285,7 @@ public class PostService { Post updated = postRepository.save(post); log.info("Обновлён пост id={}: удалено изображений={}, добавлено={}, статус={}", id, toRemove.size(), uploaded, updated.getStatus()); postCacheService.invalidatePosts(); - return mapper.toResponse(updated); + return withOwnerPhone(mapper.toResponse(updated), updated); } @Transactional @@ -306,7 +318,7 @@ public class PostService { Post updated = postRepository.save(post); log.info("Статус поста id={} изменён: {} -> {}", id, previousStatus, newStatus); postCacheService.invalidatePosts(); - return mapper.toResponse(updated); + return withOwnerPhone(mapper.toResponse(updated), updated); } public List getCities() { @@ -422,6 +434,7 @@ public class PostService { post.setCity(PostFieldLimits.cityFromAddress(address)); } + /** Публичное представление: без номера телефона (см. PostResponse.phone). */ public PostResponse toResponse(Post post, boolean includeUserRole) { PostResponse response = mapper.toResponse(post); response.setReward(post.getIsReward()); @@ -431,6 +444,37 @@ public class PostService { return response; } + /** Представление для автора: с номером, чтобы форма правки его показала. */ + private PostResponse toOwnerResponse(Post post, boolean includeUserRole) { + return withOwnerPhone(toResponse(post, includeUserRole), post); + } + + private static PostResponse withOwnerPhone(PostResponse response, Post post) { + if (response != null) { + response.setPhone(post.getPhone()); + } + return response; + } + + /** + * Номер хранится, только пока автор согласен на его показ: при отзыве + * согласия номер стирается (152-ФЗ — не храним данные без цели). + * Время согласия ставится при включении и не сдвигается при правках. + */ + public static void applyPhone(Post post, String phone, boolean phoneVisible) { + if (!phoneVisible || !StringUtils.hasText(phone)) { + post.setPhoneVisible(false); + post.setPhone(null); + post.setPhoneConsentAt(null); + return; + } + if (!post.isPhoneVisible() || post.getPhoneConsentAt() == null) { + post.setPhoneConsentAt(TimeZoneContext.now()); + } + post.setPhoneVisible(true); + post.setPhone(phone.trim()); + } + private List parseExistingImages(String existingImagesJson) { if (existingImagesJson == null) { return List.of(); @@ -450,11 +494,12 @@ public class PostService { // Неопубликованный пост (MODERATION, REJECTED) виден только владельцу. // Остальным отвечаем 404, чтобы не раскрывать, что такой id существует - if (!FEED_VISIBLE_STATUSES.contains(post.getStatus()) && !isCurrentUser(post.getUser().getId())) { + boolean owner = isCurrentUser(post.getUser().getId()); + if (!FEED_VISIBLE_STATUSES.contains(post.getStatus()) && !owner) { throw new ApiException(ErrorCode.NOT_FOUND, "Post not found", HttpStatus.NOT_FOUND); } - return toResponse(post, true); + return owner ? toOwnerResponse(post, true) : toResponse(post, true); } private static String normalizeAddress(String address) { diff --git a/src/main/java/com/krylov/refound/service/admin/AdminPostService.java b/src/main/java/com/krylov/refound/service/admin/AdminPostService.java index 5e7147c..2de5b7d 100644 --- a/src/main/java/com/krylov/refound/service/admin/AdminPostService.java +++ b/src/main/java/com/krylov/refound/service/admin/AdminPostService.java @@ -17,6 +17,7 @@ import com.krylov.refound.repository.PostRepository; import com.krylov.refound.service.FileStorageService; import com.krylov.refound.service.GeocodingService; import com.krylov.refound.service.PostDeletionService; +import com.krylov.refound.service.PostService; import com.krylov.refound.service.StatisticsService; import com.krylov.refound.service.redis.PostCacheService; import com.krylov.refound.util.PostFieldLimits; @@ -130,7 +131,11 @@ public class AdminPostService { post.setType(parseTypeOrThrow(type)); post.setTitle(title); post.setDescription(description); - post.setPhone(phone); + // Согласие на показ номера даёт только автор: админ может поправить или + // убрать номер, но не включить показ там, где автор выбрал «только чат» + if (post.isPhoneVisible()) { + PostService.applyPhone(post, phone, true); + } post.setIsReward(Boolean.TRUE.equals(reward)); post.setReward(rewardText); @@ -288,6 +293,7 @@ public class AdminPostService { .latitude(post.getLatitude()) .longitude(post.getLongitude()) .phone(post.getPhone()) + .phoneVisible(post.isPhoneVisible()) .reward(Boolean.TRUE.equals(post.getIsReward())) .rewardText(post.getReward()) .createdAt(post.getCreatedAt()) diff --git a/src/main/java/com/krylov/refound/service/phone/PhoneRevealProperties.java b/src/main/java/com/krylov/refound/service/phone/PhoneRevealProperties.java new file mode 100644 index 0000000..c1425ff --- /dev/null +++ b/src/main/java/com/krylov/refound/service/phone/PhoneRevealProperties.java @@ -0,0 +1,59 @@ +package com.krylov.refound.service.phone; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Защита номеров от массового сбора ({@code phone-reveal.*} в application.yaml). + * Номер отдаётся только с решённой proof-of-work задачей; сложность растёт с + * числом открытых с одного IP номеров. Счётчики и баны — в Redis. + */ +@Getter +@Setter +@ConfigurationProperties(prefix = "phone-reveal") +public class PhoneRevealProperties { + + /** HMAC-ключ подписи задач; пусто — используется jwt.secret. */ + private String secret; + + /** Сколько живёт выданная задача. */ + private Duration challengeTtl = Duration.ofMinutes(2); + + /** + * Верхняя граница перебора для первых открытий: браузер решает в среднем + * за maxNumber/2 хешей SHA-256 (100 000 — доли секунды на телефоне). + */ + private long baseMaxNumber = 100_000; + + /** Каждые столько номеров за час с IP сложность умножается на escalationFactor. */ + private int escalationStep = 5; + private int escalationFactor = 4; + /** Предел сложности (~десяток секунд на слабом телефоне). */ + private long maxMaxNumber = 5_000_000; + + /** Сколько номеров можно открыть с одного IP за час и за сутки. */ + private int ipHourlyLimit = 30; + private int ipDailyLimit = 100; + /** Сколько номеров может открыть один аккаунт за сутки. */ + private int userDailyLimit = 50; + + /** + * Подозрительные запросы (номер объявления, где его нет или которого нет, + * неверное решение задачи) — интерфейс таких не делает. После strikeLimit + * за час IP банится на banDuration. + */ + private int strikeLimit = 5; + private Duration strikeWindow = Duration.ofHours(1); + private Duration banDuration = Duration.ofHours(24); + + /** + * Объявления-ловушки: id, которых нет в интерфейсе. Запрос номера по ним — + * сразу бан. Подходят id удалённых объявлений или id далеко за текущим + * максимумом — на них натыкается только перебор. + */ + private List trapPostIds = new ArrayList<>(); +} diff --git a/src/main/java/com/krylov/refound/service/phone/PhoneRevealService.java b/src/main/java/com/krylov/refound/service/phone/PhoneRevealService.java new file mode 100644 index 0000000..0f634c8 --- /dev/null +++ b/src/main/java/com/krylov/refound/service/phone/PhoneRevealService.java @@ -0,0 +1,151 @@ +package com.krylov.refound.service.phone; + +import com.krylov.refound.entity.Post; +import com.krylov.refound.enums.ErrorCode; +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.Optional; +import java.util.concurrent.TimeUnit; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +/** + * Показ номера автора объявления. Цель — сделать массовый сбор номеров дорогим, + * а разовый звонок оставить бесплатным и без регистрации: + *
    + *
  • номер отдаётся только с решённой proof-of-work задачей (ProofOfWorkService), + * сложность растёт с числом открытых с IP номеров;
  • + *
  • лимиты на IP (час, сутки) и на аккаунт (сутки);
  • + *
  • ловушки: запросы, которые интерфейс не делает (номер объявления без + * номера или несуществующего, неверное решение, id-ловушки), — это + * перебор; после нескольких таких IP банится на сутки.
  • + *
+ * Номер показывается только у активных объявлений с согласием автора. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class PhoneRevealService { + + static final String RULE_HOUR = "phone-reveal-hour"; + static final String RULE_DAY = "phone-reveal-day"; + static final String RULE_USER_DAY = "phone-reveal-user-day"; + static final String RULE_STRIKE = "phone-strike"; + private static final String BAN_KEY_PREFIX = "phone-ban:"; + private static final Duration HOUR = Duration.ofHours(1); + private static final Duration DAY = Duration.ofDays(1); + + private final PostRepository postRepository; + private final ProofOfWorkService proofOfWork; + private final RedisRateLimiter rateLimiter; + private final StringRedisTemplate redisTemplate; + private final PhoneRevealProperties properties; + + /** Задача для открытия номера; сложность зависит от того, сколько номеров IP уже открыл за час. */ + @Transactional(readOnly = true) + public ProofOfWorkService.Challenge challenge(long postId, String ip) { + checkNotBanned(ip); + requireRevealablePost(postId, ip); + long revealsThisHour = rateLimiter.current(RULE_HOUR, ip, HOUR); + return proofOfWork.create(postId, proofOfWork.maxNumberFor(revealsThisHour)); + } + + /** Номер автора, если решение задачи верно и лимиты не исчерпаны. */ + @Transactional(readOnly = true) + public String reveal(long postId, String salt, Long number, String signature, String ip, Long userId) { + checkNotBanned(ip); + Optional solvedFor = proofOfWork.verify(salt, number, signature); + if (solvedFor.isEmpty() || solvedFor.get() != postId) { + strike(ip, "неверное решение задачи для поста " + postId); + throw new ApiException(ErrorCode.VALIDATION_ERROR, "Проверка не пройдена, попробуйте ещё раз", + HttpStatus.BAD_REQUEST); + } + Post post = requireRevealablePost(postId, ip); + if (userId != null && post.getUser() != null && userId.equals(post.getUser().getId())) { + // Автор смотрит свой номер в ленте — это не сбор, лимиты не тратим + return post.getPhone(); + } + + // Лимиты считаем после проверки решения: каждая попытка сборщика стоит ему CPU + checkLimit(RULE_HOUR, ip, properties.getIpHourlyLimit(), HOUR); + checkLimit(RULE_DAY, ip, properties.getIpDailyLimit(), DAY); + if (userId != null) { + checkLimit(RULE_USER_DAY, "u" + userId, properties.getUserDailyLimit(), DAY); + } + + log.info("Показан номер: postId={}, ip={}, userId={}", postId, ip, userId); + return post.getPhone(); + } + + private Post requireRevealablePost(long postId, String ip) { + if (properties.getTrapPostIds().contains(postId)) { + ban(ip, "запрос номера объявления-ловушки " + postId); + throw notFound(); + } + Post post = postRepository.findById(postId).orElse(null); + if (post == null || post.getStatus() != PostStatus.ACTIVE || !post.isPhoneVisible() + || !StringUtils.hasText(post.getPhone())) { + strike(ip, "запрос номера поста без номера " + postId); + throw notFound(); + } + return post; + } + + private void checkLimit(String rule, String subject, int limit, Duration window) { + RedisRateLimiter.Decision decision = rateLimiter.hit(rule, subject, limit, window); + if (!decision.allowed()) { + log.warn("Лимит показа номеров '{}' превышен: {}", rule, subject); + throw tooManyRequests(decision.retryAfterSeconds()); + } + } + + private void strike(String ip, String reason) { + RedisRateLimiter.Decision decision = rateLimiter.hit(RULE_STRIKE, ip, properties.getStrikeLimit(), + properties.getStrikeWindow()); + log.warn("Подозрительный запрос номера ({}): ip={}, {}/{}", reason, ip, decision.count(), + properties.getStrikeLimit()); + if (decision.count() >= properties.getStrikeLimit()) { + ban(ip, "превышен порог подозрительных запросов"); + } + } + + private void ban(String ip, String reason) { + try { + redisTemplate.opsForValue().set(BAN_KEY_PREFIX + ip, "1", properties.getBanDuration()); + log.warn("IP {} заблокирован для показа номеров на {}: {}", ip, properties.getBanDuration(), reason); + } catch (RuntimeException e) { + log.warn("Бан IP {} не записан, Redis недоступен: {}", ip, e.getMessage()); + } + } + + /** Забаненному отвечаем тем же 429, что и при лимите: причину бана сборщику не раскрываем. */ + private void checkNotBanned(String ip) { + Long ttl; + try { + ttl = redisTemplate.getExpire(BAN_KEY_PREFIX + ip, TimeUnit.SECONDS); + } catch (RuntimeException e) { + return; + } + if (ttl != null && ttl > 0) { + throw tooManyRequests(ttl); + } + } + + private static ApiException tooManyRequests(long retryAfterSeconds) { + return new ApiException(ErrorCode.TOO_MANY_REQUESTS, + "Слишком много запросов номера, повторите позже или напишите в чат", HttpStatus.TOO_MANY_REQUESTS, + retryAfterSeconds); + } + + private static ApiException notFound() { + return new ApiException(ErrorCode.NOT_FOUND, "Номер недоступен", HttpStatus.NOT_FOUND); + } +} diff --git a/src/main/java/com/krylov/refound/service/phone/ProofOfWorkService.java b/src/main/java/com/krylov/refound/service/phone/ProofOfWorkService.java new file mode 100644 index 0000000..56bde55 --- /dev/null +++ b/src/main/java/com/krylov/refound/service/phone/ProofOfWorkService.java @@ -0,0 +1,148 @@ +package com.krylov.refound.service.phone; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.util.HexFormat; +import java.util.Optional; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; + +/** + * Proof-of-work по схеме ALTCHA, без внешних сервисов. Сервер берёт случайное + * число {@code n ≤ maxNumber} и отдаёт {@code challenge = SHA-256(salt + n)}; + * браузер перебирает n, пока хеш не совпадёт. Человек тратит доли секунды, + * сборщику на 10 000 номеров нужны часы CPU. + * + *

Задача не хранится на сервере: {@code signature = HMAC(challenge)}, а id + * объявления и срок годности лежат в salt ({@code ..}), + * поэтому решение нельзя перенести на другое объявление или использовать + * после срока. Повторное использование решения отсекается ключом в Redis. + */ +@Slf4j +@Service +public class ProofOfWorkService { + + public static final String ALGORITHM = "SHA-256"; + private static final String USED_KEY_PREFIX = "pow:used:"; + private static final HexFormat HEX = HexFormat.of(); + + private final byte[] secret; + private final PhoneRevealProperties properties; + private final StringRedisTemplate redisTemplate; + private final Clock clock; + private final SecureRandom random = new SecureRandom(); + + /** Задача для клиента; поля совпадают с форматом ALTCHA. */ + public record Challenge(String algorithm, String challenge, String salt, long maxNumber, String signature) { + } + + @Autowired + public ProofOfWorkService(PhoneRevealProperties properties, StringRedisTemplate redisTemplate, + @Value("${jwt.secret}") String jwtSecret) { + this(properties, redisTemplate, jwtSecret, Clock.systemUTC()); + } + + ProofOfWorkService(PhoneRevealProperties properties, StringRedisTemplate redisTemplate, String jwtSecret, + Clock clock) { + String configured = properties.getSecret(); + this.secret = (configured == null || configured.isBlank() ? jwtSecret : configured) + .getBytes(StandardCharsets.UTF_8); + this.properties = properties; + this.redisTemplate = redisTemplate; + this.clock = clock; + } + + public Challenge create(long postId, long maxNumber) { + byte[] nonce = new byte[12]; + random.nextBytes(nonce); + long expiresAt = clock.instant().plus(properties.getChallengeTtl()).getEpochSecond(); + String salt = HEX.formatHex(nonce) + "." + postId + "." + expiresAt; + long number = random.nextLong(maxNumber + 1); + String challenge = sha256Hex(salt + number); + return new Challenge(ALGORITHM, challenge, salt, maxNumber, HEX.formatHex(hmac(challenge))); + } + + /** + * Проверяет решение и «гасит» его. Возвращает id объявления, для которого + * выдана задача, или пусто, если решение неверно, просрочено или уже использовано. + */ + public Optional verify(String salt, Long number, String signature) { + if (salt == null || number == null || number < 0 || signature == null) { + return Optional.empty(); + } + String[] parts = salt.split("\\.", -1); + if (parts.length != 3) { + return Optional.empty(); + } + long postId; + long expiresAt; + byte[] actual; + try { + postId = Long.parseLong(parts[1]); + expiresAt = Long.parseLong(parts[2]); + actual = HEX.parseHex(signature); + } catch (IllegalArgumentException e) { + return Optional.empty(); + } + long now = clock.instant().getEpochSecond(); + if (now > expiresAt) { + return Optional.empty(); + } + String challenge = sha256Hex(salt + number); + if (!MessageDigest.isEqual(hmac(challenge), actual)) { + return Optional.empty(); + } + if (!markUsed(challenge, Duration.ofSeconds(expiresAt - now + 1))) { + return Optional.empty(); + } + return Optional.of(postId); + } + + /** Сложность по числу уже открытых с IP номеров за час. */ + public long maxNumberFor(long revealsThisHour) { + long maxNumber = properties.getBaseMaxNumber(); + long steps = properties.getEscalationStep() <= 0 ? 0 : revealsThisHour / properties.getEscalationStep(); + for (long i = 0; i < steps && maxNumber < properties.getMaxMaxNumber(); i++) { + maxNumber *= properties.getEscalationFactor(); + } + return Math.min(maxNumber, properties.getMaxMaxNumber()); + } + + /** false — решение уже использовано. При недоступном Redis пропускаем: подпись и срок проверены. */ + private boolean markUsed(String challenge, Duration ttl) { + try { + Boolean fresh = redisTemplate.opsForValue().setIfAbsent(USED_KEY_PREFIX + challenge, "1", ttl); + return !Boolean.FALSE.equals(fresh); + } catch (RuntimeException e) { + log.warn("PoW: повторное использование не проверено, Redis недоступен: {}", e.getMessage()); + return true; + } + } + + static String sha256Hex(String value) { + try { + return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("SHA-256 недоступен", e); + } + } + + private byte[] hmac(String value) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(secret, "HmacSHA256")); + return mac.doFinal(value.getBytes(StandardCharsets.UTF_8)); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("HmacSHA256 недоступен", e); + } + } +} diff --git a/src/main/java/com/krylov/refound/util/PostFieldLimits.java b/src/main/java/com/krylov/refound/util/PostFieldLimits.java index 450abdb..e82b35f 100644 --- a/src/main/java/com/krylov/refound/util/PostFieldLimits.java +++ b/src/main/java/com/krylov/refound/util/PostFieldLimits.java @@ -16,6 +16,8 @@ public final class PostFieldLimits { public static final int REWARD_TEXT = 255; public static final int ADDRESS = 500; public static final int CITY = 100; + private static final int MIN_PHONE_DIGITS = 10; + private static final int MAX_PHONE_DIGITS = 15; private PostFieldLimits() { } @@ -31,6 +33,18 @@ public final class PostFieldLimits { checkLength("Текст вознаграждения", rewardText, REWARD_TEXT); } + /** + * Номер для показа другим пользователям: 10–15 цифр (E.164), остальное — + * форматирование. 400 VALIDATION_ERROR, если номера нет или он некорректен. + */ + public static void requirePhone(String phone) { + int digits = phone == null ? 0 : (int) phone.chars().filter(Character::isDigit).count(); + if (digits < MIN_PHONE_DIGITS || digits > MAX_PHONE_DIGITS) { + throw new ApiException(ErrorCode.VALIDATION_ERROR, + "Укажите корректный номер телефона или отключите его показ", HttpStatus.BAD_REQUEST); + } + } + /** * Город, когда геокодер его не дал: берётся адрес из формы, обрезанный под * колонку city (адрес допускает 500 символов, город — 100). diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index d992ba5..8c4d973 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -181,6 +181,18 @@ rate-limit: paths: [/api/v1/chats/with/**] limit: 30 window: PT1M + # Первый рубеж против сборщиков номеров — короткие всплески; часовые и + # суточные лимиты, PoW и баны — в PhoneRevealService (phone-reveal.*) + - name: phone-challenge + method: GET + paths: [/api/v1/posts/*/phone/challenge] + limit: 20 + window: PT1M + - name: phone-reveal + method: POST + paths: [/api/v1/posts/*/phone] + limit: 10 + window: PT1M - name: ads-next method: GET paths: [/api/ads/next, /api/fullscreen-ad] @@ -192,6 +204,24 @@ rate-limit: limit: 120 window: PT1M +# Защита номеров от сбора (PhoneRevealService, docs/phone-protection.md) +phone-reveal: + # HMAC-ключ задач proof-of-work; пусто — используется jwt.secret + secret: ${PHONE_REVEAL_SECRET:} + challenge-ttl: PT2M + base-max-number: 100000 # ~0,1–0,5 с на телефоне + escalation-step: 5 # каждые 5 номеров за час с IP — + escalation-factor: 4 # задача в 4 раза тяжелее + max-max-number: 5000000 + ip-hourly-limit: 30 + ip-daily-limit: 100 + user-daily-limit: 50 + strike-limit: 5 # подозрительных запросов за strike-window до бана + strike-window: PT1H + ban-duration: PT24H + # id объявлений-ловушек через запятую (см. docs/phone-protection.md) + trap-post-ids: ${PHONE_TRAP_POST_IDS:} + # Реклама (docs/advertising.md) ads: # Пояс дат кампаний и календарных суток дневного лимита diff --git a/src/main/resources/db/changelog/add/023-add-phone-visible-posts.yaml b/src/main/resources/db/changelog/add/023-add-phone-visible-posts.yaml new file mode 100644 index 0000000..de0ef2d --- /dev/null +++ b/src/main/resources/db/changelog/add/023-add-phone-visible-posts.yaml @@ -0,0 +1,25 @@ +databaseChangeLog: + - changeSet: + id: 023-add-phone-visible-posts + author: krylov + comment: > + Согласие автора на показ номера (152-ФЗ). phone_visible = false — режим + «только чат»: номер не хранится и не показывается. phone_consent_at — + когда дано согласие. У старых объявлений явного согласия не было, + поэтому их номера скрываются до правки объявления автором. + preConditions: + onFail: MARK_RAN + not: + columnExists: + tableName: posts + columnName: phone_visible + changes: + - addColumn: + tableName: posts + columns: + - column: + name: phone_visible + type: BOOLEAN + defaultValueBoolean: false + constraints: { nullable: false } + - column: { name: phone_consent_at, type: TIMESTAMP } diff --git a/src/main/resources/db/changelog/db.changelog-master.yaml b/src/main/resources/db/changelog/db.changelog-master.yaml index 72ba0c6..f59f0d3 100644 --- a/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/src/main/resources/db/changelog/db.changelog-master.yaml @@ -35,3 +35,4 @@ databaseChangeLog: - include: { file: db/changelog/search/020-search-words.yaml } - include: { file: db/changelog/add/021-ad-stats-indexes.yaml } - include: { file: db/changelog/add/022-add-closed-at-posts.yaml } + - include: { file: db/changelog/add/023-add-phone-visible-posts.yaml } diff --git a/src/test/java/com/krylov/refound/service/PostPhoneConsentTest.java b/src/test/java/com/krylov/refound/service/PostPhoneConsentTest.java new file mode 100644 index 0000000..949485a --- /dev/null +++ b/src/test/java/com/krylov/refound/service/PostPhoneConsentTest.java @@ -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"); + } +} diff --git a/src/test/java/com/krylov/refound/service/phone/PhoneRevealServiceTest.java b/src/test/java/com/krylov/refound/service/phone/PhoneRevealServiceTest.java new file mode 100644 index 0000000..39618cc --- /dev/null +++ b/src/test/java/com/krylov/refound/service/phone/PhoneRevealServiceTest.java @@ -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 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); + }); + } +} diff --git a/src/test/java/com/krylov/refound/service/phone/ProofOfWorkServiceTest.java b/src/test/java/com/krylov/refound/service/phone/ProofOfWorkServiceTest.java new file mode 100644 index 0000000..5ca03b0 --- /dev/null +++ b/src/test/java/com/krylov/refound/service/phone/ProofOfWorkServiceTest.java @@ -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 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); + } +}