"""Minimal canonical service shape for CVE-2024-4340.

A remote, unauthenticated endpoint that passes the untrusted request body
straight to sqlparse. The same source file is used by both the vulnerable
(sqlparse==0.4.4) and patched (sqlparse==0.5.0) stacks; only the installed
sqlparse version differs between the two images.

The endpoint does NOT impose a size cap on the parsed body and does NOT
catch RecursionError, so on the vulnerable stack the worker process dies
with an uncaught RecursionError originating in sqlparse grouping code.
"""

import sqlparse
from flask import Flask, request

app = Flask(__name__)


@app.get("/health")
def health():
    return {"status": "ok", "sqlparse": sqlparse.__version__}, 200


@app.post("/format")
def format_sql():
    # Untrusted request body handed directly to sqlparse, exactly the
    # canonical vulnerable shape. No depth/size guard, no try/except:
    # an uncaught RecursionError must be free to kill the worker.
    body = request.get_data(as_text=True)
    formatted = sqlparse.format(body, reindent=True, keyword_case="upper")
    return {"formatted": formatted}, 200


if __name__ == "__main__":
    # Dev fallback only; production entrypoint is gunicorn (see Dockerfile).
    app.run(host="0.0.0.0", port=8000)
