Block chat injection
This commit is contained in:
@@ -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();
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user