# [CRUCIBLE-SEED]
# category: ssrf
# severity: high
# language: python
# expected: SSRF via urllib.request.urlopen with unvalidated user URL

import urllib.request
import urllib.parse
from django.http import JsonResponse


def fetch_remote_resource(request):
    """Fetch an external resource on behalf of the client."""
    url = request.GET.get("url", "")

    # No validation — internal URLs, file://, gopher:// etc. all accepted
    try:
        with urllib.request.urlopen(url, timeout=10) as response:
            content = response.read(4096).decode("utf-8", errors="replace")
            content_type = response.headers.get("Content-Type", "")
        return JsonResponse({"content": content, "content_type": content_type})
    except Exception as e:
        return JsonResponse({"error": str(e)}, status=400)


def check_url_status(request):
    target = request.POST.get("target", "")
    try:
        req = urllib.request.Request(target, headers={"User-Agent": "StatusChecker/1.0"})
        with urllib.request.urlopen(req, timeout=8) as resp:
            return JsonResponse({"status": resp.status, "url": target})
    except urllib.error.HTTPError as e:
        return JsonResponse({"status": e.code})
