Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,7 @@ from fastapi import FastAPI, Request, HTTPException, Depends, status
|
|
| 6 |
from fastapi.exceptions import RequestValidationError
|
| 7 |
from fastapi.responses import JSONResponse
|
| 8 |
from fastapi.security import APIKeyHeader
|
| 9 |
-
from typing import Dict, Any, Optional
|
| 10 |
from datetime import datetime
|
| 11 |
|
| 12 |
# LangGraph and Model Imports
|
|
@@ -22,6 +22,24 @@ from models import (
|
|
| 22 |
logging.basicConfig(level=logging.INFO)
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
# --- Configuration ---
|
| 26 |
API_KEY_NAME = "x-api-key"
|
| 27 |
API_KEY = os.environ.get("HONEYPOT_API_KEY", "sk_test_123456789")
|
|
@@ -29,40 +47,64 @@ api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
|
|
| 29 |
|
| 30 |
# --- Initialization ---
|
| 31 |
app = FastAPI(
|
| 32 |
-
title="Agentic Honey-Pot API",
|
| 33 |
-
description="REST API for Scam Detection
|
| 34 |
-
version="1.
|
| 35 |
)
|
| 36 |
|
| 37 |
# Initialize LangGraph Checkpointer
|
| 38 |
checkpointer: BaseCheckpointSaver = MemorySaver()
|
| 39 |
honeypot_app = create_honeypot_graph(checkpointer)
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
# --- Exception Handler for Diagnostic Logging ---
|
| 42 |
@app.exception_handler(RequestValidationError)
|
| 43 |
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
| 44 |
-
"""
|
| 45 |
-
Captures and logs the exact payload that caused a 422 Unprocessable Entity error.
|
| 46 |
-
This is crucial for diagnosing why the tester is failing.
|
| 47 |
-
"""
|
| 48 |
body = await request.body()
|
| 49 |
try:
|
| 50 |
payload = json.loads(body)
|
| 51 |
except:
|
| 52 |
payload = body.decode()
|
| 53 |
|
| 54 |
-
|
| 55 |
-
logger.error(f"
|
| 56 |
-
logger.error(f"Validation errors: {exc.errors()}")
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
)
|
| 66 |
|
| 67 |
# --- Dependency for API Key Validation ---
|
| 68 |
async def get_api_key(api_key_header: str = Depends(api_key_header)):
|
|
@@ -75,15 +117,19 @@ async def get_api_key(api_key_header: str = Depends(api_key_header)):
|
|
| 75 |
|
| 76 |
# --- API Endpoints ---
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
@app.post("/api/honeypot-detection", response_model=HoneypotResponse)
|
| 79 |
async def honeypot_detection(
|
| 80 |
request_data: HoneypotRequest,
|
| 81 |
api_key: str = Depends(get_api_key)
|
| 82 |
) -> Dict[str, Any]:
|
| 83 |
-
"""
|
| 84 |
-
Accepts an incoming message event, runs the LangGraph agent, and returns the response.
|
| 85 |
-
Strictly follows Problem Statement 2 schema.
|
| 86 |
-
"""
|
| 87 |
session_id = request_data.sessionId
|
| 88 |
config = {"configurable": {"thread_id": session_id}}
|
| 89 |
|
|
@@ -104,7 +150,6 @@ async def honeypot_detection(
|
|
| 104 |
current_state["totalMessagesExchanged"] += 1
|
| 105 |
input_state = current_state
|
| 106 |
else:
|
| 107 |
-
# New session
|
| 108 |
initial_history = request_data.conversationHistory + [request_data.message]
|
| 109 |
input_state = AgentState(
|
| 110 |
sessionId=session_id,
|
|
@@ -121,11 +166,9 @@ async def honeypot_detection(
|
|
| 121 |
try:
|
| 122 |
final_state_dict = honeypot_app.invoke(input_state, config=config)
|
| 123 |
final_state = AgentState(**final_state_dict)
|
| 124 |
-
|
| 125 |
engagement_duration = int(time.time() - start_time)
|
| 126 |
|
| 127 |
-
|
| 128 |
-
return {
|
| 129 |
"status": "success",
|
| 130 |
"scamDetected": final_state["scamDetected"],
|
| 131 |
"engagementMetrics": {
|
|
@@ -135,14 +178,24 @@ async def honeypot_detection(
|
|
| 135 |
"extractedIntelligence": final_state["extractedIntelligence"].model_dump(),
|
| 136 |
"agentNotes": final_state["agentNotes"]
|
| 137 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
except Exception as e:
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
)
|
| 145 |
|
| 146 |
@app.get("/")
|
| 147 |
async def root():
|
| 148 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from fastapi.exceptions import RequestValidationError
|
| 7 |
from fastapi.responses import JSONResponse
|
| 8 |
from fastapi.security import APIKeyHeader
|
| 9 |
+
from typing import Dict, Any, Optional, List
|
| 10 |
from datetime import datetime
|
| 11 |
|
| 12 |
# LangGraph and Model Imports
|
|
|
|
| 22 |
logging.basicConfig(level=logging.INFO)
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
| 25 |
+
# --- Global Debug Store ---
|
| 26 |
+
# This will store the last 50 requests and responses in memory for easy debugging
|
| 27 |
+
DEBUG_LOGS: List[Dict[str, Any]] = []
|
| 28 |
+
MAX_DEBUG_LOGS = 50
|
| 29 |
+
|
| 30 |
+
def add_debug_log(direction: str, path: str, method: str, headers: Dict[str, str], body: Any):
|
| 31 |
+
log_entry = {
|
| 32 |
+
"timestamp": datetime.now().isoformat(),
|
| 33 |
+
"direction": direction,
|
| 34 |
+
"path": path,
|
| 35 |
+
"method": method,
|
| 36 |
+
"headers": {k: v for k, v in headers.items() if k.lower() != "x-api-key"}, # Hide key for safety
|
| 37 |
+
"body": body
|
| 38 |
+
}
|
| 39 |
+
DEBUG_LOGS.insert(0, log_entry)
|
| 40 |
+
if len(DEBUG_LOGS) > MAX_DEBUG_LOGS:
|
| 41 |
+
DEBUG_LOGS.pop()
|
| 42 |
+
|
| 43 |
# --- Configuration ---
|
| 44 |
API_KEY_NAME = "x-api-key"
|
| 45 |
API_KEY = os.environ.get("HONEYPOT_API_KEY", "sk_test_123456789")
|
|
|
|
| 47 |
|
| 48 |
# --- Initialization ---
|
| 49 |
app = FastAPI(
|
| 50 |
+
title="Agentic Honey-Pot API - Super Debug Mode",
|
| 51 |
+
description="REST API for Scam Detection with enhanced logging.",
|
| 52 |
+
version="1.3.0"
|
| 53 |
)
|
| 54 |
|
| 55 |
# Initialize LangGraph Checkpointer
|
| 56 |
checkpointer: BaseCheckpointSaver = MemorySaver()
|
| 57 |
honeypot_app = create_honeypot_graph(checkpointer)
|
| 58 |
|
| 59 |
+
# --- Middleware for Global Logging ---
|
| 60 |
+
@app.middleware("http")
|
| 61 |
+
async def log_requests(request: Request, call_next):
|
| 62 |
+
path = request.url.path
|
| 63 |
+
method = request.method
|
| 64 |
+
headers = dict(request.headers)
|
| 65 |
+
|
| 66 |
+
# Capture request body
|
| 67 |
+
body = None
|
| 68 |
+
if method == "POST":
|
| 69 |
+
try:
|
| 70 |
+
raw_body = await request.body()
|
| 71 |
+
body = json.loads(raw_body)
|
| 72 |
+
except:
|
| 73 |
+
body = "Could not parse body as JSON"
|
| 74 |
+
|
| 75 |
+
add_debug_log("INCOMING", path, method, headers, body)
|
| 76 |
+
logger.info(f"INCOMING {method} {path} | Body: {body}")
|
| 77 |
+
|
| 78 |
+
start_time = time.time()
|
| 79 |
+
response = await call_next(request)
|
| 80 |
+
process_time = time.time() - start_time
|
| 81 |
+
|
| 82 |
+
# Capture response body (this is a bit tricky in FastAPI middleware)
|
| 83 |
+
# For simplicity, we'll log the status code here and log the actual body in the endpoint
|
| 84 |
+
logger.info(f"OUTGOING {method} {path} | Status: {response.status_code} | Time: {process_time:.4f}s")
|
| 85 |
+
|
| 86 |
+
return response
|
| 87 |
+
|
| 88 |
# --- Exception Handler for Diagnostic Logging ---
|
| 89 |
@app.exception_handler(RequestValidationError)
|
| 90 |
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
body = await request.body()
|
| 92 |
try:
|
| 93 |
payload = json.loads(body)
|
| 94 |
except:
|
| 95 |
payload = body.decode()
|
| 96 |
|
| 97 |
+
error_detail = exc.errors()
|
| 98 |
+
logger.error(f"422 Unprocessable Entity Error! Payload: {payload} | Errors: {error_detail}")
|
|
|
|
| 99 |
|
| 100 |
+
response_body = {
|
| 101 |
+
"detail": error_detail,
|
| 102 |
+
"received_body": payload,
|
| 103 |
+
"message": "Validation failed. Check /debug/logs for details."
|
| 104 |
+
}
|
| 105 |
+
add_debug_log("OUTGOING_ERROR", request.url.path, request.method, {}, response_body)
|
| 106 |
+
|
| 107 |
+
return JSONResponse(status_code=422, content=response_body)
|
| 108 |
|
| 109 |
# --- Dependency for API Key Validation ---
|
| 110 |
async def get_api_key(api_key_header: str = Depends(api_key_header)):
|
|
|
|
| 117 |
|
| 118 |
# --- API Endpoints ---
|
| 119 |
|
| 120 |
+
@app.get("/debug/logs")
|
| 121 |
+
async def get_debug_logs():
|
| 122 |
+
"""Endpoint to view the last 50 requests and responses."""
|
| 123 |
+
return {
|
| 124 |
+
"count": len(DEBUG_LOGS),
|
| 125 |
+
"logs": DEBUG_LOGS
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
@app.post("/api/honeypot-detection", response_model=HoneypotResponse)
|
| 129 |
async def honeypot_detection(
|
| 130 |
request_data: HoneypotRequest,
|
| 131 |
api_key: str = Depends(get_api_key)
|
| 132 |
) -> Dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
session_id = request_data.sessionId
|
| 134 |
config = {"configurable": {"thread_id": session_id}}
|
| 135 |
|
|
|
|
| 150 |
current_state["totalMessagesExchanged"] += 1
|
| 151 |
input_state = current_state
|
| 152 |
else:
|
|
|
|
| 153 |
initial_history = request_data.conversationHistory + [request_data.message]
|
| 154 |
input_state = AgentState(
|
| 155 |
sessionId=session_id,
|
|
|
|
| 166 |
try:
|
| 167 |
final_state_dict = honeypot_app.invoke(input_state, config=config)
|
| 168 |
final_state = AgentState(**final_state_dict)
|
|
|
|
| 169 |
engagement_duration = int(time.time() - start_time)
|
| 170 |
|
| 171 |
+
response_content = {
|
|
|
|
| 172 |
"status": "success",
|
| 173 |
"scamDetected": final_state["scamDetected"],
|
| 174 |
"engagementMetrics": {
|
|
|
|
| 178 |
"extractedIntelligence": final_state["extractedIntelligence"].model_dump(),
|
| 179 |
"agentNotes": final_state["agentNotes"]
|
| 180 |
}
|
| 181 |
+
|
| 182 |
+
# Log the successful response body
|
| 183 |
+
add_debug_log("OUTGOING_SUCCESS", "/api/honeypot-detection", "POST", {}, response_content)
|
| 184 |
+
|
| 185 |
+
return response_content
|
| 186 |
|
| 187 |
except Exception as e:
|
| 188 |
+
error_msg = f"Internal Error: {str(e)}"
|
| 189 |
+
logger.error(error_msg)
|
| 190 |
+
add_debug_log("OUTGOING_ERROR", "/api/honeypot-detection", "POST", {}, {"error": error_msg})
|
| 191 |
+
raise HTTPException(status_code=500, detail=error_msg)
|
|
|
|
| 192 |
|
| 193 |
@app.get("/")
|
| 194 |
async def root():
|
| 195 |
+
return {
|
| 196 |
+
"message": "Agentic Honey-Pot API is running.",
|
| 197 |
+
"endpoints": {
|
| 198 |
+
"detection": "/api/honeypot-detection",
|
| 199 |
+
"debug_logs": "/debug/logs"
|
| 200 |
+
}
|
| 201 |
+
}
|