"""HTTPS ACL, Argon migration, shared rate limit and session revocation.""" import base64,hashlib,json,os,ssl,time,uuid from pipeline_helpers import * def basic(u,p):return {'Authorization':'Basic '+base64.b64encode((u+':'+p).encode()).decode()} def main(): c=Client();actor,_,outsider,chat=c.bootstrap();raw=(ROOT/'tests/fixtures/sample.png').read_bytes() item=upload(c,actor,chat);wait_state(c,actor,item) c.call('GET','/api/v1/attachments/'+item['id'],404,actor=outsider) c.call('GET','/api/v1/attachments/'+item['id']+'/content',404,actor=outsider) c.call('GET','/api/v1/users/me',actor=outsider,headers={'X-User-Id':actor['id']},schema='User') own=c.call('GET','/api/v1/users/me',actor=outsider,headers={'X-User-Id':actor['id']},schema='User')['json'] check(own['id']==outsider['id'],'spoofed identity accepted') c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=forbidden.png',404,actor=outsider,raw=raw,headers={'Content-Type':'image/png'}) stored=psql("SELECT password_hash FROM users WHERE id='"+actor['id']+"';") check(stored.startswith('$argon2id$v=19$m=19456,t=2,p=1$'),'Argon2id parameters missing') # Actual legacy scrypt row, followed by real Basic login and persisted rehash. reg=actor['registration'];salt=os.urandom(16) digest=hashlib.scrypt(reg['password'].encode(),salt=salt,n=32768,r=8,p=1,dklen=32,maxmem=64*1024*1024) enc=lambda b:base64.b64encode(b).decode().rstrip('=') legacy='scrypt$32768$8$1$'+enc(salt)+'$'+enc(digest) psql("UPDATE users SET password_hash='"+legacy+"' WHERE id='"+actor['id']+"';") began=time.monotonic();c.call('POST','/api/v1/auth/sessions',201,headers=basic(reg['username'],reg['password'])) rehash_ms=(time.monotonic()-began)*1000 check(psql("SELECT password_hash LIKE '$argon2id$%' FROM users WHERE id='"+actor['id']+"';")=='t','successful login did not rehash legacy') # Only a hash of the bearer token is a session key. expected='session:'+hashlib.sha256(actor['token'].encode()).hexdigest() check(actor['token'] not in stored,'password storage leaked bearer') c.call('DELETE','/api/v1/auth/sessions/current',204,actor=actor) c.call('GET','/api/v1/users/me',401,actor=actor) # Actual Redis expiry on the existing session; operator shortens only this synthetic key. key='session:'+hashlib.sha256(outsider['token'].encode()).hexdigest() compose('exec','-T','redis','sh','-ec','redis-cli -p 16379 --user operator --no-auth-warning -a "$(cat /run/secrets/redis_operator)" EXPIRE "$1" 1','sh',key) time.sleep(2) c.call('GET','/api/v1/users/me',401,actor=outsider) # A repeated username shares its budget across both LB backends. identity='limit_'+uuid.uuid4().hex[:12];seen=set();throttled=[] for i in range(16): r=c.call('POST','/api/v1/auth/sessions',[401,429],headers=basic(identity,'wrong')) seen.add(r['headers']['X-Instance-Id']) if r['status']==429: check(int(r['headers']['Retry-After'])>0,'Retry-After missing');throttled.append(i) check(len(seen)==2 and throttled and throttled[0]==10,'rate budget is not shared across replicas') # The CA is trusted, but this hostname must still be rejected. try: import socket with socket.create_connection(('localhost',8443),timeout=3) as sock: ssl.create_default_context(cafile=str(ROOT/'secrets/public/ca.crt')).wrap_socket(sock,server_hostname='wrong.invalid') raise Failure('wrong hostname accepted') except ssl.SSLCertVerificationError:pass result={'status':'PASS','argon2id':'m=19456KiB,t=2,p=1','legacy_rehash_ms':round(rehash_ms,3),'outsider_metadata_content_upload':'denied','spoofed_header':'ignored','logout':'401','session_expiry':'401','shared_rate_limit_first_429_attempt':throttled[0]+1,'api_instances':sorted(seen),'hostname_mismatch':'rejected'} dump_evidence('security-grade4.json',result);print('PASS: HTTPS ACL, real legacy rehash, logout and shared rate limit') if __name__=='__main__':run(main)