forked from mtusi2026/mtusi2026lab7
72 lines
1.7 KiB
Python
72 lines
1.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Verify that an expired session is rejected through HTTPS."""
|
|
|
|
import hashlib
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
|
|
from client import Client, Failure, arguments, run
|
|
|
|
|
|
def database_query(sql):
|
|
result = subprocess.run(
|
|
[
|
|
"docker", "compose", "exec", "-T",
|
|
"-e", "SQL=" + sql,
|
|
"postgres",
|
|
"sh", "-lc",
|
|
'psql -X -A -t -v ON_ERROR_STOP=1 '
|
|
'-U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "$SQL"',
|
|
],
|
|
cwd=ROOT,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
|
|
if result.returncode != 0:
|
|
raise Failure("PostgreSQL operation failed")
|
|
|
|
return result.stdout.strip()
|
|
|
|
|
|
def main():
|
|
args = arguments("Expired session security test")
|
|
client = Client(args.base_url, args.ca_file)
|
|
|
|
actor = client.user("expiry")
|
|
token = actor["token"]
|
|
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
|
|
|
try:
|
|
updated = database_query(
|
|
"UPDATE sessions "
|
|
"SET expires_at = NOW() - INTERVAL '1 second' "
|
|
f"WHERE token_hash = '{token_hash}' "
|
|
"RETURNING id;"
|
|
)
|
|
|
|
if not updated:
|
|
raise Failure("Test session was not found in PostgreSQL")
|
|
|
|
client.call(
|
|
"GET",
|
|
"/api/v1/users/me",
|
|
401,
|
|
actor=actor,
|
|
)
|
|
|
|
print("PASS: expired session rejected with HTTP 401")
|
|
|
|
finally:
|
|
database_query(
|
|
f"DELETE FROM sessions WHERE token_hash = '{token_hash}';"
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|