#!/usr/bin/env python3
"""
Airlock IAM target-flow probe for this engagement.

Usage:
  python work/scratch/airlock-flow-probe.py HOST --location /group/ao
  python work/scratch/airlock-flow-probe.py HOST --application-id portal_ao

Prerequisites: curl_cffi; exact host must be in scope. Sends two low-rate requests,
keeps the HTTP client's normal User-Agent, and identifies as X-Bug-Bounty: dwbzn.
It does not submit credentials or follow off-host redirects.
"""
import argparse, json, sys, time
from urllib.parse import urljoin
from curl_cffi import requests

IDENTITY = {"X-Bug-Bounty": "dwbzn"}

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("host")
    g = ap.add_mutually_exclusive_group(required=True)
    g.add_argument("--location", help="Target path or absolute same-host URL")
    g.add_argument("--application-id")
    ap.add_argument("--timeout", type=float, default=25)
    args = ap.parse_args()
    base = f"https://{args.host}"
    session = requests.Session()
    init = session.get(base + "/auth/ui/app", headers=IDENTITY, allow_redirects=False, timeout=args.timeout)
    if init.status_code != 200:
        print(json.dumps({"stage":"init","status":init.status_code,"location":init.headers.get("location"),"body":init.text[:500]}, indent=2))
        return 2
    csrf = session.cookies.get("CSRFT759-S")
    headers = {**IDENTITY, "Accept":"application/json", "Content-Type":"application/json", "X-Same-Domain":"1"}
    if csrf:
        headers["X-CSRFT759"] = csrf
    time.sleep(1)
    if args.application_id:
        endpoint = base + f"/auth/rest/public/authentication/applications/{args.application_id}/access"
        body = None
    else:
        location = args.location if args.location.startswith(("http://","https://")) else urljoin(base + "/", args.location.lstrip("/"))
        if not location.startswith(base + "/"):
            print("location must remain on the exact target host", file=sys.stderr)
            return 2
        endpoint = base + "/auth/rest/public/authentication/location/access"
        body = json.dumps({"location": location})
    response = session.post(endpoint, headers=headers, data=body, allow_redirects=False, timeout=args.timeout)
    out = {"status":response.status_code,"headers":{k:v for k,v in response.headers.items() if k.lower() in {"content-type","location","x-forward-url","www-authenticate"}}}
    try:
        out["json"] = response.json()
    except Exception:
        out["body"] = response.text[:2000]
    print(json.dumps(out, ensure_ascii=False, indent=2))
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
