Spaces:
Running
Running
Commit
·
c89d79e
1
Parent(s):
3dc5183
Fix middleware order and session access issues
Browse files- Reorder middleware stack: Session -> UsageTracking -> Auth -> CORS
- Fix session access in authentication middleware with try-catch
- Add proper error handling for session not available scenarios
- Ensure SessionMiddleware runs before ConditionalAuthMiddleware
- backend/app.py +14 -14
- backend/middleware/auth.py +10 -2
- backend/routers/auth.py +12 -2
backend/app.py
CHANGED
|
@@ -44,27 +44,27 @@ logger = logging.getLogger("agent_monitoring_server")
|
|
| 44 |
# Create FastAPI app
|
| 45 |
app = FastAPI(title="Agent Monitoring System", version="1.0.0")
|
| 46 |
|
| 47 |
-
# Add
|
| 48 |
-
session_secret = os.getenv("SESSION_SECRET_KEY") or secrets.token_urlsafe(32)
|
| 49 |
app.add_middleware(
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
| 53 |
)
|
| 54 |
|
| 55 |
-
# Add usage tracking middleware (before auth, to track all requests)
|
| 56 |
-
app.add_middleware(UsageTrackingMiddleware)
|
| 57 |
-
|
| 58 |
# Add conditional authentication middleware
|
| 59 |
app.add_middleware(ConditionalAuthMiddleware)
|
| 60 |
|
| 61 |
-
# Add
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
app.add_middleware(
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
allow_methods=["*"],
|
| 67 |
-
allow_headers=["*"],
|
| 68 |
)
|
| 69 |
|
| 70 |
# Mount datasets directory for accessing json files
|
|
|
|
| 44 |
# Create FastAPI app
|
| 45 |
app = FastAPI(title="Agent Monitoring System", version="1.0.0")
|
| 46 |
|
| 47 |
+
# Add CORS middleware (first, so it's outermost)
|
|
|
|
| 48 |
app.add_middleware(
|
| 49 |
+
CORSMiddleware,
|
| 50 |
+
allow_origins=["*"],
|
| 51 |
+
allow_credentials=True,
|
| 52 |
+
allow_methods=["*"],
|
| 53 |
+
allow_headers=["*"],
|
| 54 |
)
|
| 55 |
|
|
|
|
|
|
|
|
|
|
| 56 |
# Add conditional authentication middleware
|
| 57 |
app.add_middleware(ConditionalAuthMiddleware)
|
| 58 |
|
| 59 |
+
# Add usage tracking middleware (after auth, to track authenticated requests)
|
| 60 |
+
app.add_middleware(UsageTrackingMiddleware)
|
| 61 |
+
|
| 62 |
+
# Add session middleware (last, so it's innermost and processes requests first)
|
| 63 |
+
session_secret = os.getenv("SESSION_SECRET_KEY") or secrets.token_urlsafe(32)
|
| 64 |
app.add_middleware(
|
| 65 |
+
SessionMiddleware,
|
| 66 |
+
secret_key=session_secret,
|
| 67 |
+
max_age=86400, # 24 hours
|
|
|
|
|
|
|
| 68 |
)
|
| 69 |
|
| 70 |
# Mount datasets directory for accessing json files
|
backend/middleware/auth.py
CHANGED
|
@@ -122,7 +122,13 @@ class ConditionalAuthMiddleware(BaseHTTPMiddleware):
|
|
| 122 |
3. Authorization header
|
| 123 |
"""
|
| 124 |
# Check if user info is in session (our own auth)
|
| 125 |
-
user =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
# In HF Spaces, check for __sign parameter which indicates HF has pre-authenticated the user
|
| 128 |
if not user and is_huggingface_space():
|
|
@@ -139,8 +145,10 @@ class ConditionalAuthMiddleware(BaseHTTPMiddleware):
|
|
| 139 |
"auth_method": "hf_sign"
|
| 140 |
}
|
| 141 |
# Store in session for future requests
|
| 142 |
-
|
| 143 |
request.session["user"] = user
|
|
|
|
|
|
|
| 144 |
logger.info("User authenticated via HF __sign parameter")
|
| 145 |
|
| 146 |
# Check Authorization header as fallback
|
|
|
|
| 122 |
3. Authorization header
|
| 123 |
"""
|
| 124 |
# Check if user info is in session (our own auth)
|
| 125 |
+
user = None
|
| 126 |
+
try:
|
| 127 |
+
user = request.session.get("user")
|
| 128 |
+
except (AttributeError, AssertionError):
|
| 129 |
+
# Session middleware not available or not configured
|
| 130 |
+
logger.debug("Session not available for authentication check")
|
| 131 |
+
user = None
|
| 132 |
|
| 133 |
# In HF Spaces, check for __sign parameter which indicates HF has pre-authenticated the user
|
| 134 |
if not user and is_huggingface_space():
|
|
|
|
| 145 |
"auth_method": "hf_sign"
|
| 146 |
}
|
| 147 |
# Store in session for future requests
|
| 148 |
+
try:
|
| 149 |
request.session["user"] = user
|
| 150 |
+
except (AttributeError, AssertionError):
|
| 151 |
+
logger.debug("Cannot store user in session - session middleware not available")
|
| 152 |
logger.info("User authenticated via HF __sign parameter")
|
| 153 |
|
| 154 |
# Check Authorization header as fallback
|
backend/routers/auth.py
CHANGED
|
@@ -22,7 +22,12 @@ router = APIRouter(prefix="/auth", tags=["authentication"])
|
|
| 22 |
async def auth_status(request: Request):
|
| 23 |
"""Get authentication status and configuration."""
|
| 24 |
config = get_oauth_config()
|
| 25 |
-
user = getattr(request.state, "user", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
return {
|
| 28 |
"auth_enabled": should_enable_auth(),
|
|
@@ -170,7 +175,12 @@ async def get_current_user(request: Request):
|
|
| 170 |
if not should_enable_auth():
|
| 171 |
return {"message": "Authentication disabled in local development"}
|
| 172 |
|
| 173 |
-
user = getattr(request.state, "user", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
if not user:
|
| 175 |
raise HTTPException(status_code=401, detail="Not authenticated")
|
| 176 |
|
|
|
|
| 22 |
async def auth_status(request: Request):
|
| 23 |
"""Get authentication status and configuration."""
|
| 24 |
config = get_oauth_config()
|
| 25 |
+
user = getattr(request.state, "user", None)
|
| 26 |
+
if not user:
|
| 27 |
+
try:
|
| 28 |
+
user = request.session.get("user")
|
| 29 |
+
except (AttributeError, AssertionError):
|
| 30 |
+
user = None
|
| 31 |
|
| 32 |
return {
|
| 33 |
"auth_enabled": should_enable_auth(),
|
|
|
|
| 175 |
if not should_enable_auth():
|
| 176 |
return {"message": "Authentication disabled in local development"}
|
| 177 |
|
| 178 |
+
user = getattr(request.state, "user", None)
|
| 179 |
+
if not user:
|
| 180 |
+
try:
|
| 181 |
+
user = request.session.get("user")
|
| 182 |
+
except (AttributeError, AssertionError):
|
| 183 |
+
user = None
|
| 184 |
if not user:
|
| 185 |
raise HTTPException(status_code=401, detail="Not authenticated")
|
| 186 |
|