# [CRUCIBLE-SEED]
# category: deserialization
# severity: high
# language: python
# expected: marshal.loads and jsonpickle.decode used with untrusted data

import marshal
import jsonpickle
from flask import Flask, request, jsonify

app = Flask(__name__)


@app.post("/code/load")
def load_code():
    """Load a compiled Python code object from client."""
    data = request.get_data()
    # marshal.loads with user data can reconstruct code objects — arbitrary execution
    code_obj = marshal.loads(data)
    result = eval(code_obj)
    return jsonify({"result": str(result)})


@app.post("/object/restore")
def restore_object():
    payload = request.get_json()
    serialized = payload.get("object", "")
    # jsonpickle can deserialize arbitrary Python objects including those with __reduce__
    obj = jsonpickle.decode(serialized)
    return jsonify({"type": type(obj).__name__, "repr": repr(obj)})


@app.post("/state/import")
def import_state():
    body = request.get_json()
    state_json = body.get("state", "null")
    # jsonpickle.decode with py/object tags allows instantiation of arbitrary classes
    state = jsonpickle.decode(state_json, classes=None)
    return jsonify({"imported": True, "keys": list(state.keys()) if isinstance(state, dict) else []})
