eheguy commited on
Commit
0ce8fd1
·
1 Parent(s): 70a15ea

Add input sanitization against prompt injection

Browse files
Files changed (1) hide show
  1. main.py +29 -1
main.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import traceback
3
  from fastapi import FastAPI, HTTPException
4
  from pydantic import BaseModel
@@ -11,6 +12,25 @@ from humanizer import humanize_text
11
 
12
  from fastapi.middleware.cors import CORSMiddleware
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  app = FastAPI(title="AI Humanizer API")
15
 
16
  app.add_middleware(
@@ -43,9 +63,17 @@ async def humanize(request: HumanizeRequest):
43
  status_code=400,
44
  detail="mode must be one of: simple, standard, enhanced"
45
  )
 
 
 
 
 
 
 
 
46
  try:
47
  humanized_text = await humanize_text(
48
- request.text,
49
  mode=request.mode,
50
  readability=request.readability,
51
  purpose=request.purpose,
 
1
  import os
2
+ import re
3
  import traceback
4
  from fastapi import FastAPI, HTTPException
5
  from pydantic import BaseModel
 
12
 
13
  from fastapi.middleware.cors import CORSMiddleware
14
 
15
+ def sanitize_input(text: str) -> str:
16
+ """
17
+ Strip prompt injection patterns from user input before
18
+ passing to the Groq API.
19
+ """
20
+ patterns = [
21
+ r'\[SYSTEM OVERRIDE.*?\]',
22
+ r'\[INST.*?\]',
23
+ r'ignore (all |your |previous |the )?instructions',
24
+ r'do not (rewrite|change|edit|humanize)',
25
+ r'bypass (rewriting|humanization|the system)',
26
+ r'output (the text|this text) (exactly|verbatim|as.is)',
27
+ r'disregard (all |your |previous |the )?instructions',
28
+ r'forget (all |your |previous |the )?instructions',
29
+ ]
30
+ for pattern in patterns:
31
+ text = re.sub(pattern, '', text, flags=re.IGNORECASE | re.DOTALL)
32
+ return text.strip()
33
+
34
  app = FastAPI(title="AI Humanizer API")
35
 
36
  app.add_middleware(
 
63
  status_code=400,
64
  detail="mode must be one of: simple, standard, enhanced"
65
  )
66
+ clean_text = sanitize_input(request.text)
67
+
68
+ if not clean_text:
69
+ raise HTTPException(
70
+ status_code=400,
71
+ detail="Input text is empty or invalid after sanitization."
72
+ )
73
+
74
  try:
75
  humanized_text = await humanize_text(
76
+ clean_text,
77
  mode=request.mode,
78
  readability=request.readability,
79
  purpose=request.purpose,