File size: 1,183 Bytes
c03f547
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import re
from typing import List

class SecurityValidator:
    @staticmethod
    def validate_input(text: str, max_length: int = 1000) -> bool:
        """Validate input text for security"""
        if len(text) > max_length:
            raise ValueError(f"Input too long. Max {max_length} characters.")
        
        # Check for potential prompt injection
        injection_patterns = [
            r"ignore previous",
            r"system prompt",
            r"forget your instructions"
        ]
        
        for pattern in injection_patterns:
            if re.search(pattern, text, re.IGNORECASE):
                raise SecurityError("Potential prompt injection detected")
        
        return True
    
    @staticmethod
    def sanitize_output(text: str) -> str:
        """Sanitize model output"""
        # Remove any potentially harmful content
        harmful_patterns = [
            r"<script.*?>.*?</script>",
            r"<iframe.*?>.*?</iframe>"
        ]
        
        for pattern in harmful_patterns:
            text = re.sub(pattern, "", text, flags=re.IGNORECASE | re.DOTALL)
        
        return text

class SecurityError(Exception):
    pass