forked from mtusi2026/mtusi2026lab2
Implement lab2 PostgreSQL authentication and Redis sessions
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade-4 Redis/Postgres failure injection for isolated local Compose environment.
|
||||
Requires Docker permissions; never uses 'down -v'. Never prints tokens.
|
||||
"""
|
||||
import subprocess
|
||||
import time
|
||||
from client import Client, Failure, check, run
|
||||
|
||||
|
||||
def compose(*args):
|
||||
outcome = subprocess.run(['docker','compose','--env-file','.env',*args],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
check(outcome.returncode==0, 'docker compose action failed; inspect locally')
|
||||
|
||||
|
||||
def wait_ready(c, status):
|
||||
until = time.monotonic()+60
|
||||
while time.monotonic()<until:
|
||||
try:
|
||||
c.call('GET','/health/ready',status)
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(0.5)
|
||||
raise Failure('readiness did not reach '+str(status))
|
||||
|
||||
|
||||
def main():
|
||||
c=Client(timeout=10)
|
||||
alice = c.user('dependency')
|
||||
for service in ('redis','postgres'):
|
||||
try:
|
||||
compose('stop',service)
|
||||
wait_ready(c,503)
|
||||
c.call('GET','/api/v1/users/me',503,actor=alice)
|
||||
finally:
|
||||
compose('start',service)
|
||||
wait_ready(c,200)
|
||||
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
print('PASS:', service, 'outage returned 503; recovered without losing session')
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Requires a separate short-TTL run (SESSION_TTL_SECONDS=2); checks expiry automatically."""
|
||||
import time
|
||||
from client import Client, run
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice = c.user('expiry')
|
||||
time.sleep(3.1)
|
||||
c.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
print('PASS: short-lived Bearer session expires and is rejected')
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional grade-4 tests: validation, authentication and username race.
|
||||
Run against an isolated running lab2 stack. Uses unique test usernames.
|
||||
"""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import time
|
||||
import uuid
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic NOT-BASE64'})
|
||||
incorrect = base64.b64encode((alice['registration']['username'] + ':wrong-password').encode()).decode()
|
||||
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic ' + incorrect})
|
||||
c.call('POST','/api/v1/users',400,body={**alice['registration'],'admin':True})
|
||||
c.call('POST','/api/v1/users',400,body={'username':'xy','display_name':'Valid','password':'long-password-123'})
|
||||
c.call('POST','/api/v1/users',400,body={'username':'anothername','display_name':'Valid','password':'short'})
|
||||
c.call('POST','/api/v1/users',400,body={'username':'blankpass_' + uuid.uuid4().hex[:8], 'display_name':'Valid','password':' '*12})
|
||||
credentials = base64.b64encode((alice['registration']['username']+':'+alice['registration']['password']).encode('utf-8')).decode('ascii')
|
||||
c.call('POST','/api/v1/auth/sessions',400,headers={'Authorization':'Basic '+credentials},body={'unexpected':True})
|
||||
c.call('POST','/api/v1/auth/sessions',400,headers={'Authorization':'Basic '+credentials},body={})
|
||||
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'Too many members', 'member_ids':[alice['id']]+[str(uuid.uuid4()) for _ in range(100)]})
|
||||
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'bad','member_ids':[alice['id'],alice['id']]})
|
||||
c.call('POST','/api/v1/chats',400,actor=alice,body={'title':'bad','member_ids':[alice['id'],str(uuid.uuid4())]})
|
||||
c.call('POST',path+'/messages',400,actor=alice,body={'text':' '})
|
||||
# PostgreSQL text/varchar reject NUL. Public API does not: verify exact
|
||||
# round-trip through bytea storage for all three user-controlled fields.
|
||||
special = 'A\x00Б'
|
||||
nul_user = c.call('POST','/api/v1/users',201,body={'username':'nul_' + uuid.uuid4().hex[:12], 'display_name':special, 'password':'Strong-password-123'},schema='User')['json']
|
||||
check(nul_user['display_name']==special,'display_name U+0000 round-trip failed')
|
||||
nul_chat = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':special,'member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
|
||||
check(nul_chat['title']==special,'chat title U+0000 round-trip failed')
|
||||
fetched_chat = c.call('GET','/api/v1/chats/'+nul_chat['id'],actor=bob,schema='Chat')['json']
|
||||
check(fetched_chat['title']==special,'chat GET title U+0000 round-trip failed')
|
||||
special_message = c.call('POST',path+'/messages',201,actor=alice,body={'text':special},schema='Message')['json']
|
||||
check(special_message['text']==special,'message U+0000 write lost data')
|
||||
items = c.call('GET',path+'/messages',actor=bob,schema='MessagePage')['json']['items']
|
||||
check(any(m['id']==special_message['id'] and m['text']==special for m in items),'message GET lost U+0000')
|
||||
max_message = 'Ж'*3999 + '\x00'
|
||||
posted_max = c.call('POST',path+'/messages',201,actor=alice,body={'text':max_message},schema='Message')['json']
|
||||
check(posted_max['text']==max_message,'max-length UTF8/NUL failed')
|
||||
c.call('POST',path+'/messages',404,actor=eve,body={'text':'bad outsider'})
|
||||
c.call('GET',path+'/messages?limit=0',400,actor=alice)
|
||||
c.call('GET',path+'/messages?limit=101',400,actor=alice)
|
||||
c.call('GET',path+'/messages?cursor=notvalid',400,actor=alice)
|
||||
c.call('POST','/api/v1/users',415,raw=b'{}',headers={'Content-Type':'text/plain'})
|
||||
c.call('POST','/api/v1/users',400,raw=b'{"bad json":',headers={'Content-Type':'application/json'})
|
||||
token_alice = alice['token']
|
||||
c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||
c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Bearer '+token_alice})
|
||||
|
||||
username = 'race_' + uuid.uuid4().hex[:12]
|
||||
payload = {'username':username,'display_name':'Race','password':'Race-password-123456'}
|
||||
def worker(_):
|
||||
return Client().call('POST','/api/v1/users',[201,409],body=payload)['status']
|
||||
with ThreadPoolExecutor(max_workers=10) as executor:
|
||||
statuses = list(executor.map(worker, range(10)))
|
||||
check(statuses.count(201)==1 and statuses.count(409)==9,'concurrent username race was not serialized by UNIQUE')
|
||||
print('PASS: grade4 API negatives, login body, Unicode NUL round-trip, max members and username race')
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Optional operator test for Redis session corruption on an isolated lab stack.
|
||||
No other users' keys are modified. Run only against own Docker Compose setup.
|
||||
"""
|
||||
import hashlib
|
||||
import subprocess
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
user = c.user('cachecorrupt')
|
||||
digest = hashlib.sha256(user['token'].encode('ascii')).hexdigest()
|
||||
key = 'session:' + digest
|
||||
cmd = ['docker','compose','--env-file','.env','exec','-T','redis','redis-cli']
|
||||
proc = subprocess.run(cmd + ['SET',key,'null','EX','30'], text=True, capture_output=True)
|
||||
check(proc.returncode == 0 and 'OK' in proc.stdout, 'could not inject synthetic corrupt Redis session')
|
||||
c.call('GET','/api/v1/users/me',401,actor=user)
|
||||
proc = subprocess.run(cmd + ['EXISTS', key], text=True, capture_output=True)
|
||||
check(proc.returncode == 0 and proc.stdout.strip()=='0', 'corrupt session key was not removed')
|
||||
print('PASS: malformed Redis session value fails closed with 401 and is removed')
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user