This commit is contained in:
1 parent
8f3fd04618
commit
2d3ff21222
17 files changed
+1566
-136
No files matched your search
@@ -0,0 +1,9 @@
|
||||
import assert from "node:assert/strict";
|
||||
import authHelpers from "../auth.js";
|
||||
|
||||
const { getLoginUrlForPath, shouldShowAdminEntry } = authHelpers;
|
||||
|
||||
assert.equal(getLoginUrlForPath("/study.html?video=2"), "./login.html?next=%2Fstudy.html%3Fvideo%3D2");
|
||||
assert.equal(shouldShowAdminEntry({ role: "admin" }), true);
|
||||
assert.equal(shouldShowAdminEntry({ role: "user" }), false);
|
||||
assert.equal(shouldShowAdminEntry(null), false);
|
||||
@@ -0,0 +1,73 @@
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from backend import db
|
||||
from backend.auth import create_auth_token, hash_password, verify_auth_token, verify_password
|
||||
|
||||
|
||||
class TempDatabase:
|
||||
def __enter__(self):
|
||||
self.temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
|
||||
self.original = db.DATABASE_PATH
|
||||
db.DATABASE_PATH = Path(self.temp_dir.name) / "test.sqlite"
|
||||
db.initialize_database()
|
||||
return db.DATABASE_PATH
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
db.DATABASE_PATH = self.original
|
||||
self.temp_dir.cleanup()
|
||||
|
||||
|
||||
def test_password_hash_roundtrip():
|
||||
stored = hash_password("secret123")
|
||||
|
||||
assert stored != "secret123"
|
||||
assert verify_password("secret123", stored) is True
|
||||
assert verify_password("wrong", stored) is False
|
||||
|
||||
|
||||
def test_auth_token_roundtrip_and_tamper_rejection():
|
||||
token = create_auth_token({"username": "student", "role": "user", "userId": 1}, "secret")
|
||||
|
||||
payload = verify_auth_token(token, "secret")
|
||||
assert payload["username"] == "student"
|
||||
assert payload["role"] == "user"
|
||||
assert verify_auth_token(token + "x", "secret") is None
|
||||
|
||||
|
||||
def test_activation_code_registers_user_once():
|
||||
with TempDatabase():
|
||||
created = db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
|
||||
assert created[0]["status"] == "unused"
|
||||
|
||||
user = db.register_user_with_activation(
|
||||
username="student",
|
||||
password_hash=hash_password("secret123"),
|
||||
activation_code="SL-ABC123-DEF456-GHI789",
|
||||
)
|
||||
|
||||
assert user["username"] == "student"
|
||||
codes = db.list_activation_codes()
|
||||
assert codes[0]["status"] == "used"
|
||||
assert codes[0]["usedByUsername"] == "student"
|
||||
|
||||
try:
|
||||
db.register_user_with_activation(
|
||||
username="student2",
|
||||
password_hash=hash_password("secret123"),
|
||||
activation_code="SL-ABC123-DEF456-GHI789",
|
||||
)
|
||||
except ValueError as error:
|
||||
assert str(error) == "activation_code_unavailable"
|
||||
else:
|
||||
raise AssertionError("used activation code should not register another user")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_password_hash_roundtrip()
|
||||
test_auth_token_roundtrip_and_tamper_rejection()
|
||||
test_activation_code_registers_user_once()
|
||||
@@ -0,0 +1,141 @@
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from backend import db, main
|
||||
|
||||
|
||||
class EnvPatch:
|
||||
def __init__(self):
|
||||
self.attributes = []
|
||||
|
||||
def setattr(self, target, name, value):
|
||||
self.attributes.append((target, name, getattr(target, name)))
|
||||
setattr(target, name, value)
|
||||
|
||||
def restore(self):
|
||||
while self.attributes:
|
||||
target, name, original = self.attributes.pop()
|
||||
setattr(target, name, original)
|
||||
|
||||
|
||||
class TempDatabase:
|
||||
def __enter__(self):
|
||||
self.temp_dir = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
|
||||
self.original = db.DATABASE_PATH
|
||||
db.DATABASE_PATH = Path(self.temp_dir.name) / "test.sqlite"
|
||||
db.initialize_database()
|
||||
return db.DATABASE_PATH
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
db.DATABASE_PATH = self.original
|
||||
self.temp_dir.cleanup()
|
||||
|
||||
|
||||
def configure_admin(monkeypatch):
|
||||
monkeypatch.setattr(main, "get_config_value", lambda key, default="": {
|
||||
"ADMIN_USERNAME": "admin",
|
||||
"ADMIN_PASSWORD": "admin123",
|
||||
"AUTH_SECRET": "test-secret",
|
||||
}.get(key, default))
|
||||
|
||||
|
||||
def test_admin_login_can_generate_activation_code(monkeypatch):
|
||||
configure_admin(monkeypatch)
|
||||
|
||||
with TempDatabase():
|
||||
login = main.api_auth_login(main.LoginRequest(username="admin", password="admin123"))
|
||||
assert login["user"]["role"] == "admin"
|
||||
|
||||
bearer = HTTPAuthorizationCredentials(scheme="Bearer", credentials=login["token"])
|
||||
admin = main.require_admin(credentials=None, bearer=bearer)
|
||||
created = main.api_admin_create_activation_codes(
|
||||
main.GenerateActivationCodesRequest(quantity=2),
|
||||
admin=admin,
|
||||
)
|
||||
|
||||
assert len(created["codes"]) == 2
|
||||
assert created["codes"][0]["code"].startswith("SL-")
|
||||
|
||||
|
||||
def test_activation_registration_login_and_reuse_rejection(monkeypatch):
|
||||
configure_admin(monkeypatch)
|
||||
|
||||
with TempDatabase():
|
||||
admin_login = main.api_auth_login(main.LoginRequest(username="admin", password="admin123"))
|
||||
admin = main.require_admin(
|
||||
credentials=None,
|
||||
bearer=HTTPAuthorizationCredentials(scheme="Bearer", credentials=admin_login["token"]),
|
||||
)
|
||||
created = main.api_admin_create_activation_codes(
|
||||
main.GenerateActivationCodesRequest(quantity=1),
|
||||
admin=admin,
|
||||
)
|
||||
code = created["codes"][0]["code"]
|
||||
|
||||
registered = main.api_auth_register(main.RegisterRequest(
|
||||
activationCode=code,
|
||||
username="student",
|
||||
password="secret123",
|
||||
))
|
||||
assert registered["user"]["username"] == "student"
|
||||
assert registered["user"]["role"] == "user"
|
||||
|
||||
login = main.api_auth_login(main.LoginRequest(username="student", password="secret123"))
|
||||
session = main.api_auth_session(main.require_session(
|
||||
HTTPAuthorizationCredentials(scheme="Bearer", credentials=login["token"])
|
||||
))
|
||||
assert session["user"]["username"] == "student"
|
||||
|
||||
try:
|
||||
main.api_auth_register(main.RegisterRequest(
|
||||
activationCode=code,
|
||||
username="student2",
|
||||
password="secret123",
|
||||
))
|
||||
except HTTPException as error:
|
||||
assert error.status_code == 400
|
||||
else:
|
||||
raise AssertionError("used activation code should be rejected")
|
||||
|
||||
|
||||
def test_normal_user_cannot_use_admin_dependency(monkeypatch):
|
||||
configure_admin(monkeypatch)
|
||||
|
||||
with TempDatabase():
|
||||
db.create_activation_codes(["SL-ABC123-DEF456-GHI789"], "admin")
|
||||
registered = main.api_auth_register(main.RegisterRequest(
|
||||
activationCode="SL-ABC123-DEF456-GHI789",
|
||||
username="student",
|
||||
password="secret123",
|
||||
))
|
||||
|
||||
try:
|
||||
main.require_admin(
|
||||
credentials=None,
|
||||
bearer=HTTPAuthorizationCredentials(scheme="Bearer", credentials=registered["token"]),
|
||||
)
|
||||
except HTTPException as error:
|
||||
assert error.status_code == 401
|
||||
else:
|
||||
raise AssertionError("normal user token should not pass admin dependency")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
patch = EnvPatch()
|
||||
try:
|
||||
configure_admin(patch)
|
||||
test_admin_login_can_generate_activation_code(patch)
|
||||
patch.restore()
|
||||
configure_admin(patch)
|
||||
test_activation_registration_login_and_reuse_rejection(patch)
|
||||
patch.restore()
|
||||
configure_admin(patch)
|
||||
test_normal_user_cannot_use_admin_dependency(patch)
|
||||
finally:
|
||||
patch.restore()
|
||||
Reference in new issue
Block a user