Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException
|
| 2 |
from pydantic import BaseModel
|
| 3 |
from typing import Optional
|
| 4 |
import random
|
| 5 |
import time
|
|
|
|
| 6 |
|
| 7 |
app = FastAPI(
|
| 8 |
title="ARF Sandbox API",
|
|
@@ -12,6 +13,24 @@ app = FastAPI(
|
|
| 12 |
redoc_url="/redoc",
|
| 13 |
)
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
# ---------- Request/Response Models ----------
|
| 16 |
class Metrics(BaseModel):
|
| 17 |
latency_ms: Optional[float] = None
|
|
@@ -43,7 +62,6 @@ def generate_mock_response(request: EvaluateRequest) -> EvaluateResponse:
|
|
| 43 |
# Simulate risk score based on severity
|
| 44 |
severity_map = {"low": 0.2, "medium": 0.4, "high": 0.7, "critical": 0.9}
|
| 45 |
base_risk = severity_map.get(request.severity, 0.5)
|
| 46 |
-
# Add small random noise
|
| 47 |
risk = min(0.99, max(0.01, base_risk + random.uniform(-0.1, 0.1)))
|
| 48 |
|
| 49 |
# Decision logic (mock)
|
|
@@ -54,11 +72,9 @@ def generate_mock_response(request: EvaluateRequest) -> EvaluateResponse:
|
|
| 54 |
else:
|
| 55 |
rec = "ESCALATE"
|
| 56 |
|
| 57 |
-
# Confidence inversely related to uncertainty (simulated)
|
| 58 |
confidence = 1.0 - (risk * 0.3) + random.uniform(-0.05, 0.05)
|
| 59 |
confidence = min(0.99, max(0.5, confidence))
|
| 60 |
|
| 61 |
-
# Justification template
|
| 62 |
justification = (
|
| 63 |
f"Simulated evaluation for {request.service_name}: {request.event_type} severity={request.severity}. "
|
| 64 |
f"Risk score {risk:.2f} → {rec}. (Mock response, not real inference.)"
|
|
@@ -79,17 +95,19 @@ async def health():
|
|
| 79 |
return {"status": "ok", "timestamp": time.time()}
|
| 80 |
|
| 81 |
@app.post("/v1/evaluate", response_model=EvaluateResponse, tags=["evaluation"])
|
| 82 |
-
async def evaluate(request: EvaluateRequest):
|
| 83 |
-
#
|
|
|
|
|
|
|
|
|
|
| 84 |
if not request.service_name or not request.event_type:
|
| 85 |
raise HTTPException(status_code=400, detail="Missing service_name or event_type")
|
| 86 |
return generate_mock_response(request)
|
| 87 |
|
| 88 |
-
# ---------- Root redirect to docs ----------
|
| 89 |
@app.get("/", include_in_schema=False)
|
| 90 |
async def root():
|
| 91 |
-
return {"message": "ARF Sandbox API. See /docs for interactive documentation."}
|
| 92 |
|
| 93 |
if __name__ == "__main__":
|
| 94 |
import uvicorn
|
| 95 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 2 |
from pydantic import BaseModel
|
| 3 |
from typing import Optional
|
| 4 |
import random
|
| 5 |
import time
|
| 6 |
+
from collections import defaultdict
|
| 7 |
|
| 8 |
app = FastAPI(
|
| 9 |
title="ARF Sandbox API",
|
|
|
|
| 13 |
redoc_url="/redoc",
|
| 14 |
)
|
| 15 |
|
| 16 |
+
# ---------- Rate Limiting Configuration ----------
|
| 17 |
+
RATE_LIMIT = 10 # max requests per time window
|
| 18 |
+
RATE_LIMIT_WINDOW = 60 # seconds
|
| 19 |
+
|
| 20 |
+
# In-memory store: {ip: [(timestamp,), ...]} or use a deque
|
| 21 |
+
request_log = defaultdict(list)
|
| 22 |
+
|
| 23 |
+
def rate_limit_middleware(ip: str):
|
| 24 |
+
now = time.time()
|
| 25 |
+
# Remove timestamps older than the window
|
| 26 |
+
request_log[ip] = [ts for ts in request_log[ip] if now - ts < RATE_LIMIT_WINDOW]
|
| 27 |
+
if len(request_log[ip]) >= RATE_LIMIT:
|
| 28 |
+
raise HTTPException(
|
| 29 |
+
status_code=429,
|
| 30 |
+
detail=f"Rate limit exceeded. Max {RATE_LIMIT} requests per {RATE_LIMIT_WINDOW} seconds."
|
| 31 |
+
)
|
| 32 |
+
request_log[ip].append(now)
|
| 33 |
+
|
| 34 |
# ---------- Request/Response Models ----------
|
| 35 |
class Metrics(BaseModel):
|
| 36 |
latency_ms: Optional[float] = None
|
|
|
|
| 62 |
# Simulate risk score based on severity
|
| 63 |
severity_map = {"low": 0.2, "medium": 0.4, "high": 0.7, "critical": 0.9}
|
| 64 |
base_risk = severity_map.get(request.severity, 0.5)
|
|
|
|
| 65 |
risk = min(0.99, max(0.01, base_risk + random.uniform(-0.1, 0.1)))
|
| 66 |
|
| 67 |
# Decision logic (mock)
|
|
|
|
| 72 |
else:
|
| 73 |
rec = "ESCALATE"
|
| 74 |
|
|
|
|
| 75 |
confidence = 1.0 - (risk * 0.3) + random.uniform(-0.05, 0.05)
|
| 76 |
confidence = min(0.99, max(0.5, confidence))
|
| 77 |
|
|
|
|
| 78 |
justification = (
|
| 79 |
f"Simulated evaluation for {request.service_name}: {request.event_type} severity={request.severity}. "
|
| 80 |
f"Risk score {risk:.2f} → {rec}. (Mock response, not real inference.)"
|
|
|
|
| 95 |
return {"status": "ok", "timestamp": time.time()}
|
| 96 |
|
| 97 |
@app.post("/v1/evaluate", response_model=EvaluateResponse, tags=["evaluation"])
|
| 98 |
+
async def evaluate(request: EvaluateRequest, req: Request):
|
| 99 |
+
# Apply rate limit based on client IP
|
| 100 |
+
client_ip = req.client.host if req.client else "unknown"
|
| 101 |
+
rate_limit_middleware(client_ip)
|
| 102 |
+
|
| 103 |
if not request.service_name or not request.event_type:
|
| 104 |
raise HTTPException(status_code=400, detail="Missing service_name or event_type")
|
| 105 |
return generate_mock_response(request)
|
| 106 |
|
|
|
|
| 107 |
@app.get("/", include_in_schema=False)
|
| 108 |
async def root():
|
| 109 |
+
return {"message": "ARF Sandbox API. See /docs for interactive documentation. Rate limit: 10 requests per minute per IP."}
|
| 110 |
|
| 111 |
if __name__ == "__main__":
|
| 112 |
import uvicorn
|
| 113 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|