Block chat injection

This commit is contained in:
2026-04-14 20:02:06 -06:00
parent 7db8e966fc
commit c00afd2256
3 changed files with 35 additions and 0 deletions

View File

@@ -8,6 +8,7 @@ import com.petshop.backend.repository.PetRepository;
import com.petshop.backend.repository.UserRepository;
import com.petshop.backend.service.OpenRouterService;
import com.petshop.backend.util.AuthenticationHelper;
import com.petshop.backend.util.ContentFilter;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -49,6 +50,7 @@ public class AiChatController {
if (request.getMessage() == null || request.getMessage().isBlank()) {
return ResponseEntity.badRequest().body(AiChatResponse.fail("Message cannot be empty"));
}
ContentFilter.validate(request.getMessage());
User user = getCurrentUser();

View File

@@ -9,6 +9,7 @@ import com.petshop.backend.entity.Conversation;
import com.petshop.backend.entity.Message;
import com.petshop.backend.entity.User;
import com.petshop.backend.exception.ResourceNotFoundException;
import com.petshop.backend.util.ContentFilter;
import com.petshop.backend.repository.ConversationRepository;
import com.petshop.backend.repository.MessageRepository;
import com.petshop.backend.repository.UserRepository;
@@ -138,6 +139,8 @@ public class ChatService {
}
}
ContentFilter.validate(request.getContent());
Message message = new Message();
message.setConversationId(conversationId);
message.setSenderId(userId);

View File

@@ -0,0 +1,30 @@
package com.petshop.backend.util;
import com.petshop.backend.exception.BusinessException;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
public class ContentFilter {
private static final Pattern SCRIPT_PATTERN = Pattern.compile(
"<script|javascript:|on\\w+\\s*=", Pattern.CASE_INSENSITIVE);
private static final Set<String> PROFANITY = Set.of(
"profanityOne", "profanityTwo", "profanityThree"
);
public static void validate(String input) {
if (input == null || input.isBlank()) return;
if (SCRIPT_PATTERN.matcher(input).find()) {
throw new BusinessException("Message contains prohibited content");
}
String lower = input.toLowerCase(Locale.ROOT);
for (String word : PROFANITY) {
if (lower.contains(word)) {
throw new BusinessException("Message contains prohibited language");
}
}
}
}