Files
HangmanLab.Backend/app.py
hzhang 58f23ddcb8 Security hardening: fix RCE, auth and SSRF issues
Critical:
- backup: prevent Zip Slip path traversal and zip bombs in restore/convert
  via safe_extract(); serialize get_backup() with backup_lock and always
  restore CWD so concurrent requests can't corrupt the os.chdir state
- app: only enable the Werkzeug debugger/reloader when ENVIRONMENT=dev;
  always init rate limits (also under WSGI), not just under __main__
- apikey: fix create_key never committing (session.commit -> commit()),
  validate roles against an allowlist, and fix revoke_key/update_last_used
  operating on detached instances so revocation actually persists
- env_provider: redact DB_PASSWORD and SESSION_SECRET_KEY in summerize()

High:
- markdown: filter private/protected docs for non-admins in the listing,
  get_home, get_index and search endpoints (was an anonymous data leak);
  escape LIKE metacharacters and cap search results
- webhooks: validate target URL to block SSRF (loopback/private/link-local/
  metadata IPs), disable redirects, safely parse additional_header
- auth: validate JWT issuer and require exp/iat; add timeout to JWKS fetch;
  harden Authorization header parsing against malformed values
- log: require admin for GET /api/log and auth for POST; bound entry size

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:12:43 +01:00

65 lines
1.7 KiB
Python

from pprint import pprint
from events.WebhookEventHandlers import register_all_webhook_event_handlers
from logging_handlers.DatabaseLogHandler import DatabaseLogHandler
from api import limiter
from flask import Flask, request
from flask_cors import CORS
import api
import env_provider
import db
import logging
logger = logging.getLogger(__name__)
db_handler = DatabaseLogHandler(application="backend")
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
db_handler.setFormatter(formatter)
logger.addHandler(db_handler)
logger.setLevel(logging.INFO)
try:
db.setup_db()
except Exception as e:
print(f"db not ready")
print(e)
app = Flask(__name__)
app.secret_key = env_provider.SESSION_SECRET_KEY
CORS(app, resources={
r"/api/*": {
"origins": [
env_provider.KC_HOST,
env_provider.FRONTEND_HOST,
r"https?://localhost:\d+",
r"https?://127\.0\.0\.1:\d+",
r"https?://localhost"
],
"supports_credentials": True
}
},
expose_headers=['Content-Disposition']
)
limiter.init_app(app)
api.register_blueprints(app)
register_all_webhook_event_handlers()
@app.before_request
def log_request():
if request.path.startswith("/api/log"):
return
logger.info(f"Request received: {request.method} {request.path} from {request.remote_addr}")
api.init_rate_limits(app)
if __name__ == '__main__':
print("env")
pprint(env_provider.summerize())
# The Werkzeug debugger allows remote code execution. Only enable it in
# an explicit dev environment, never in the published production image.
is_dev = env_provider.ENVIRONMENT == "dev"
app.run(host='0.0.0.0', port=5000, debug=is_dev, use_reloader=is_dev)