"""
Lab 14.2.5 + 14.4 target: a small Flask app with deliberate security issues.

This file is a TEACHING SPECIMEN - it intentionally demonstrates:
  - A missing @require_role decorator (lab 14.2.5 SAST target)
  - A string-formatted SQL query (lab 14.2.5 taint-tracking target)
  - A hardcoded placeholder secret (lab 14.5.6 secrets-sweep target)

Run ONLY in the disposable lab container - never against real infrastructure.
"""

from flask import Flask, request, jsonify
import sqlite3

app = Flask(__name__)

# Authorisation decorator (simplified stub for lab purposes)
def require_role(role):
    def decorator(fn):
        def wrapper(*args, **kwargs):
            # Real implementation would check session/JWT
            return fn(*args, **kwargs)
        wrapper.__name__ = fn.__name__
        return wrapper
    return decorator


# ---- Correctly decorated route (SAST rule should NOT flag this) ----
@require_role("admin")
@app.route("/admin")
def admin_panel():
    return jsonify({"status": "ok", "message": "admin panel"})


# ---- Missing decorator (SAST rule SHOULD flag this) ----
@app.route("/reports")
def reports():
    """
    This route is intentionally missing @require_role.
    The custom Semgrep rule from lab 14.2.5 should report a finding here.
    """
    return jsonify({"status": "ok", "reports": []})


# ---- SQL injection demonstration (taint tracking target) ----
@app.route("/search")
def search():
    """
    Intentionally vulnerable: user-supplied 'q' parameter is interpolated
    directly into the SQL query. A SAST taint-analysis rule should flag this.
    Do NOT use in production.
    """
    q = request.args.get("q", "")
    conn = sqlite3.connect(":memory:")
    cursor = conn.cursor()
    # BAD: string formatting - taint source (request.args) reaches sink (execute)
    cursor.execute("SELECT * FROM items WHERE name = '%s'" % q)
    rows = cursor.fetchall()
    conn.close()
    return jsonify({"results": rows})


# ---- Hardcoded placeholder credential (secrets-sweep target) ----
# This is a SYNTHETIC / NON-FUNCTIONAL placeholder, not a real credential.
# gitleaks and trufflehog should flag this pattern.
DB_PASSWORD = "PLACEHOLDER_SECRET_abc123xyz"  # noqa: S106 - intentional for lab


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=False)
