mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-11-09 05:24:49 +09:00
Introduce programmatic API features and observability: add API Key management, API usage analytics, webhook event subscriptions, and OpenAPI docs. New models (ApiKey, ApiUsageLog, ApiUsageSummary, EventSubscription, EventDelivery), services (api_analytics, api_key, event, openapi), and blueprints (/api-keys, /api-analytics, /event-subscriptions, /docs) were added and registered in create_app. Middleware for API key authentication, buffered analytics logging (with a flush thread), and enhanced rate limiting (custom key function and response headers) were implemented; RBAC was updated to accept API key auth via an auth_required decorator. Background threads for hourly aggregation and event retry were added; security CSP updated to allow resources for Swagger UI. Frontend settings UI and styles were added/updated for API keys and webhooks, and requirements were updated.
43 lines
1.5 KiB
Python
43 lines
1.5 KiB
Python
"""Security middleware for adding security headers to responses."""
|
|
|
|
from flask import Flask
|
|
|
|
|
|
def register_security_headers(app: Flask):
|
|
"""Register security headers as an after_request handler."""
|
|
|
|
@app.after_request
|
|
def add_security_headers(response):
|
|
# Prevent clickjacking
|
|
response.headers['X-Frame-Options'] = 'DENY'
|
|
|
|
# Prevent MIME type sniffing
|
|
response.headers['X-Content-Type-Options'] = 'nosniff'
|
|
|
|
# XSS Protection (legacy but still useful for older browsers)
|
|
response.headers['X-XSS-Protection'] = '1; mode=block'
|
|
|
|
# Referrer Policy
|
|
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
|
|
|
|
# Content Security Policy
|
|
csp_directives = [
|
|
"default-src 'self'",
|
|
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://unpkg.com",
|
|
"style-src 'self' 'unsafe-inline' https://unpkg.com",
|
|
"img-src 'self' data: https:",
|
|
"font-src 'self'",
|
|
"connect-src 'self' ws: wss:",
|
|
"frame-ancestors 'none'",
|
|
]
|
|
response.headers['Content-Security-Policy'] = '; '.join(csp_directives)
|
|
|
|
# Permissions Policy (formerly Feature-Policy)
|
|
response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=()'
|
|
|
|
# HSTS - only in production and on HTTPS
|
|
if not app.debug:
|
|
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
|
|
|
|
return response
|