Philips656 commited on
Commit
d4cd2e4
·
verified ·
1 Parent(s): 2255c27

Update shield.py

Browse files
Files changed (1) hide show
  1. shield.py +48 -36
shield.py CHANGED
@@ -1,10 +1,11 @@
1
- import os, requests, mysql.connector
2
  from flask import Flask, request, Response
3
 
4
  app = Flask(__name__)
5
 
6
  # --- CONFIGURATION ---
7
- OPENAI_KEY = "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"
 
8
 
9
  TIDB_CONFIG = {
10
  "host": "gateway01.eu-central-1.prod.aws.tidbcloud.com",
@@ -14,63 +15,74 @@ TIDB_CONFIG = {
14
  "database": "test",
15
  "autocommit": True,
16
  "use_pure": True,
17
- "ssl_verify_cert": False
 
18
  }
19
 
20
- def log_to_tidb(user_id, prompt):
21
  try:
22
  conn = mysql.connector.connect(**TIDB_CONFIG)
23
  cursor = conn.cursor()
24
- query = "INSERT INTO safety_violations (user_id, prompt_content) VALUES (%s, %s)"
25
- cursor.execute(query, (str(user_id), str(prompt)[:1000]))
26
  conn.commit()
27
- print(f"✅ LOGGED TO TiDB: {user_id}")
28
- cursor.close()
29
  conn.close()
30
  except Exception as e:
31
- print(f"❌ TiDB ERROR: {e}")
32
 
33
- # --- SERVE THE UI ---
34
  @app.route('/')
35
  def home():
36
- # Reads the index.html file we created
37
  with open('index.html', 'r') as f:
38
  return f.read()
39
 
40
- # --- API ENDPOINT ---
 
 
 
 
 
 
 
 
 
41
  @app.route('/v1/chat/completions', methods=['POST'])
42
- def handle_request():
43
  data = request.json
44
- messages = data.get('messages', [])
45
- user_input = " ".join([m.get('content', '') for m in messages])
46
- auth_header = request.headers.get('Authorization', 'Anonymous')
47
-
48
- # 1. SAFETY CHECK
49
  try:
50
- mod_res = requests.post(
51
- "https://api.openai.com/v1/moderations",
52
- headers={"Authorization": f"Bearer {OPENAI_KEY}"},
53
- json={"input": user_input}
54
- ).json()
55
-
56
- if mod_res.get('results', [{}])[0].get('categories', {}).get('sexual/minors'):
57
- print(f"!!! BLOCKING CSAM REQUEST FROM {auth_header} !!!")
58
- log_to_tidb(auth_header, user_input)
59
- return {"error": {"message": "Policy Violation: Content blocked by Shield.", "type": "safety_error"}}, 403
60
  except Exception as e:
61
- print(f"Moderation Error: {e}")
 
 
 
62
 
63
- # 2. FORWARD TO OPENAI (Using your key)
64
- # This powers the chat response in the UI
65
  try:
66
- resp = requests.post(
67
- "https://api.openai.com/v1/chat/completions",
68
- headers={"Authorization": f"Bearer {OPENAI_KEY}"},
69
- json=data
 
 
70
  )
71
  return Response(resp.content, resp.status_code, resp.headers.items())
72
  except Exception as e:
73
- return {"error": {"message": str(e)}}, 500
74
 
75
  if __name__ == '__main__':
 
76
  app.run(host='0.0.0.0', port=7860)
 
1
+ import requests, mysql.connector
2
  from flask import Flask, request, Response
3
 
4
  app = Flask(__name__)
5
 
6
  # --- CONFIGURATION ---
7
+ NEWAPI_INTERNAL = "http://127.0.0.1:3000"
8
+ OPENAI_MOD_KEY = "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"
9
 
10
  TIDB_CONFIG = {
11
  "host": "gateway01.eu-central-1.prod.aws.tidbcloud.com",
 
15
  "database": "test",
16
  "autocommit": True,
17
  "use_pure": True,
18
+ "ssl_ca": "/etc/ssl/certs/ca-certificates.crt",
19
+ "ssl_verify_cert": True
20
  }
21
 
22
+ def log_violation(user_id, prompt):
23
  try:
24
  conn = mysql.connector.connect(**TIDB_CONFIG)
25
  cursor = conn.cursor()
26
+ cursor.execute("INSERT INTO safety_violations (user_id, prompt_content) VALUES (%s, %s)",
27
+ (str(user_id), str(prompt)[:1000]))
28
  conn.commit()
29
+ print(f"✅ LOGGED VIOLATION: {user_id}")
 
30
  conn.close()
31
  except Exception as e:
32
+ print(f"❌ DATABASE ERROR: {e}")
33
 
34
+ # 1. SERVE UI
35
  @app.route('/')
36
  def home():
 
37
  with open('index.html', 'r') as f:
38
  return f.read()
39
 
40
+ # 2. PROXY AUTH & MODEL LISTS DIRECTLY (Don't Block These)
41
+ @app.route('/api/<path:subpath>', methods=['GET', 'POST', 'PUT', 'DELETE'])
42
+ def proxy_api(subpath):
43
+ return forward_request(f"{NEWAPI_INTERNAL}/api/{subpath}")
44
+
45
+ @app.route('/v1/models', methods=['GET'])
46
+ def proxy_models():
47
+ return forward_request(f"{NEWAPI_INTERNAL}/v1/models")
48
+
49
+ # 3. INTERCEPT & PROTECT CHAT
50
  @app.route('/v1/chat/completions', methods=['POST'])
51
+ def protect_chat():
52
  data = request.json
53
+ # Extract text from latest message
54
+ msgs = data.get('messages', [])
55
+ last_msg = msgs[-1].get('content', '') if msgs else ""
56
+
57
+ # Check Safety (using your OpenAI Key for moderation)
58
  try:
59
+ mod = requests.post("https://api.openai.com/v1/moderations",
60
+ headers={"Authorization": f"Bearer {OPENAI_MOD_KEY}"},
61
+ json={"input": last_msg}, timeout=3).json()
62
+
63
+ if mod.get('results', [{}])[0].get('categories', {}).get('sexual/minors'):
64
+ user_token = request.headers.get('Authorization', 'Anon')
65
+ log_violation(user_token, last_msg)
66
+ return {"error": {"message": "Policy Violation: Blocked by Shield.", "type": "safety_error"}}, 403
 
 
67
  except Exception as e:
68
+ print(f"Moderation Warning: {e}")
69
+
70
+ # If Safe -> Forward to NewAPI (using the USER'S token from the UI)
71
+ return forward_request(f"{NEWAPI_INTERNAL}/v1/chat/completions")
72
 
73
+ def forward_request(url):
 
74
  try:
75
+ resp = requests.request(
76
+ method=request.method,
77
+ url=url,
78
+ headers={k: v for k, v in request.headers if k.lower() != 'host'},
79
+ data=request.get_data(),
80
+ allow_redirects=False
81
  )
82
  return Response(resp.content, resp.status_code, resp.headers.items())
83
  except Exception as e:
84
+ return {"error": str(e)}, 502
85
 
86
  if __name__ == '__main__':
87
+ # Start Shield on 7860
88
  app.run(host='0.0.0.0', port=7860)