diff --git a/Dockerfile b/Dockerfile index adc03d7..0fba698 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,6 +16,7 @@ RUN cd WebApi && uv sync --no-dev ENV CACU_DATABASE_URL=sqlite:////data/cacu.db ENV CAMA_DATABASE_URL=sqlite:////data/cama.db ENV TEA_DATABASE_URL=sqlite:////data/tea.db +ENV AUTH_DATABASE_URL=sqlite:////data/auth.db RUN chmod +x /app/WebApi/docker-entrypoint.sh diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 4ba638d..177080d 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -1,6 +1,24 @@ #!/bin/sh set -e +case "${AUTH_LITE_ENABLED-false}" in + true|false) + ;; + *) + echo "AUTH_LITE_ENABLED must be exactly 'true' or 'false'" >&2 + exit 1 + ;; +esac + +case "${AUTH_LITE_SEED_DEMO_USERS-false}" in + true|false) + ;; + *) + echo "AUTH_LITE_SEED_DEMO_USERS must be exactly 'true' or 'false'" >&2 + exit 1 + ;; +esac + mkdir -p /data cd /app/Persistance @@ -8,5 +26,12 @@ uv run alembic -c persistance/cacu/alembic.ini upgrade head uv run alembic -c persistance/cama/alembic.ini upgrade head uv run alembic -c persistance/tea/alembic.ini upgrade head +if [ "${AUTH_LITE_ENABLED-false}" = "true" ]; then + uv run alembic -c persistance/auth/alembic.ini upgrade head +fi + cd /app/WebApi +if [ "${AUTH_LITE_ENABLED-false}" = "true" ] && [ "${AUTH_LITE_SEED_DEMO_USERS-false}" = "true" ]; then + uv run python -m webapi.auth_demo_seed --ensure +fi exec uv run python main.py diff --git a/tests/test_app.py b/tests/test_app.py index 0f6696d..da78306 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -7,29 +7,38 @@ import pytest @pytest.fixture(scope="module") def client(): db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name - os.environ["CACU_DATABASE_URL"] = f"sqlite:///{db_path}" + isolation = pytest.MonkeyPatch() + isolation.setenv("CACU_DATABASE_URL", f"sqlite:///{db_path}") + isolation.setenv("AUTH_LITE_ENABLED", "false") from core.cacu.base import CaCuModel from core.cacu.models import Paciente from persistance.db import get_cacu_engine + from persistance.settings import settings + isolation.setattr(settings, "cacu_database_url", f"sqlite:///{db_path}") + get_cacu_engine.cache_clear() engine = get_cacu_engine() - CaCuModel.metadata.create_all(engine) + try: + CaCuModel.metadata.create_all(engine) - from sqlmodel import Session + from sqlmodel import Session - with Session(engine) as session: - session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino")) - session.commit() + with Session(engine) as session: + session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino")) + session.commit() - from webapi import create_app + from webapi import create_app - app = create_app() - app.config.update(TESTING=True) - with app.test_client() as client: - yield client - - os.unlink(db_path) + app = create_app() + app.config.update(TESTING=True) + with app.test_client() as client: + yield client + finally: + engine.dispose() + get_cacu_engine.cache_clear() + os.unlink(db_path) + isolation.undo() def test_health(client): diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..f02b1bf --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,500 @@ +import json +from contextlib import closing +from pathlib import Path + +import pytest +from alembic import command +from alembic.config import Config +from sqlalchemy import text +from werkzeug.security import check_password_hash, generate_password_hash + +from persistance.db import get_auth_engine +from persistance.settings import settings +from webapi import create_app, parse_auth_lite_enabled +from webapi.auth_bootstrap import bootstrap, main +from webapi.auth_token import TOKEN_MAX_AGE, issue_token, serializer + +ALEMBIC_INI = Path(__file__).resolve().parents[2] / "Persistance/persistance/auth/alembic.ini" +TEST_SECRET = "fictitious-test-secret-only" +TEST_PASSWORD = "fictitious-password-only" + + +@pytest.fixture +def storage(tmp_path, monkeypatch): + path = tmp_path / "auth.sqlite" + monkeypatch.setattr(settings, "auth_database_url", f"sqlite:///{path.as_posix()}") + monkeypatch.setenv("AUTH_LITE_ENABLED", "true") + monkeypatch.setenv("AUTH_LITE_SECRET_KEY", TEST_SECRET) + get_auth_engine.cache_clear() + try: + command.upgrade(Config(str(ALEMBIC_INI)), "head") + yield path + finally: + if get_auth_engine.cache_info().currsize: + get_auth_engine().dispose() + get_auth_engine.cache_clear() + path.unlink(missing_ok=True) + assert not path.exists() + + +@pytest.fixture +def client(storage): + with get_auth_engine().begin() as connection: + connection.execute(text("INSERT INTO user(username,password_hash) VALUES (:name,:hash)"), + {"name": "sample.user", "hash": generate_password_hash(TEST_PASSWORD, method="scrypt")}) + connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (1,'TEA'),(1,'CAMA')")) + app = create_app() + app.config["TESTING"] = True + with app.test_client() as client: + yield client + + +def login(client, **changes): + return client.post("/auth/login", json={"username": "sample.user", "password": TEST_PASSWORD, **changes}) + + +def bearer(token): + return {"Authorization": f"Bearer {token}"} + + +@pytest.mark.parametrize("value,expected", [(None, False), ("false", False), ("true", True)]) +def test_flag(value, expected): + assert parse_auth_lite_enabled(value) is expected + + +@pytest.mark.parametrize("value", ["1", "0", "yes", "no", "on", "off", "TRUE", "False", "", " true "]) +def test_invalid_flag(value, monkeypatch): + with pytest.raises(ValueError, match="AUTH_LITE_ENABLED"): + parse_auth_lite_enabled(value) + monkeypatch.setenv("AUTH_LITE_ENABLED", value) + with pytest.raises(ValueError, match="AUTH_LITE_ENABLED"): + create_app() + + +@pytest.mark.parametrize("flag", [None, "false"]) +@pytest.mark.parametrize("isolated_config", ["none", "secret", "url"]) +def test_disabled_never_touches_storage(flag, isolated_config, monkeypatch, tmp_path): + import persistance.db as db + import persistance.auth.repository as repository + from webapi import auth_token + + def forbidden(*args, **kwargs): + pytest.fail("Auth storage was touched while disabled") + + monkeypatch.delenv("AUTH_LITE_ENABLED", raising=False) + if flag is not None: + monkeypatch.setenv("AUTH_LITE_ENABLED", flag) + monkeypatch.delenv("AUTH_LITE_SECRET_KEY", raising=False) + monkeypatch.delenv("AUTH_DATABASE_URL", raising=False) + if isolated_config == "secret": + monkeypatch.setenv("AUTH_LITE_SECRET_KEY", TEST_SECRET) + if isolated_config == "url": + monkeypatch.setenv("AUTH_DATABASE_URL", "invalid://unusable") + path = tmp_path / "never-created.sqlite" + monkeypatch.setattr(settings, "auth_database_url", f"sqlite:///{path.as_posix()}") + for name in ("get_auth_engine", "get_auth_session"): + monkeypatch.setattr(db, name, forbidden) + for name in ("get_user_by_username", "get_user_with_roles_by_id", "get_auth_session"): + monkeypatch.setattr(repository, name, forbidden) + monkeypatch.setattr(auth_token, "validate_auth_storage", forbidden) + from persistance.cacu import paciente_repository as cacu + from persistance.cama import paciente_repository as cama + from persistance.tea import pacientes_repository as tea + for repo in (cacu, cama, tea): + monkeypatch.setattr(repo, "get", lambda key: None) + app = create_app() + assert "auth" not in app.blueprints + assert {"cacu", "cama", "tea"} <= set(app.blueprints) + with app.test_client() as client: + assert client.get("/health").status_code == 200 + assert client.post("/auth/login", json={}).status_code == 404 + assert client.get("/auth/me").status_code == 404 + for domain in ("cacu", "cama", "tea"): + response = client.get(f"/{domain}/pacientes/999") + assert response.status_code == 404 + assert response.json == {"error": "not found"} + assert client.post(f"/{domain}/predict").status_code == 501 + assert not path.exists() + + +@pytest.mark.parametrize("secret", [None, "", " "]) +def test_enabled_requires_secret(storage, monkeypatch, secret): + monkeypatch.delenv("AUTH_LITE_SECRET_KEY", raising=False) + if secret is not None: + monkeypatch.setenv("AUTH_LITE_SECRET_KEY", secret) + with pytest.raises(ValueError, match="AUTH_LITE_SECRET_KEY"): + create_app() + + +@pytest.mark.parametrize("kind", ["missing", "unmigrated", "corrupt", "invalid_url", "inaccessible"]) +def test_enabled_requires_migrated_storage(tmp_path, monkeypatch, kind): + import sqlite3 + monkeypatch.setenv("AUTH_LITE_ENABLED", "true") + monkeypatch.setenv("AUTH_LITE_SECRET_KEY", TEST_SECRET) + path = tmp_path / "unusable.sqlite" + if kind == "unmigrated": + with closing(sqlite3.connect(path)) as connection: + connection.execute("CREATE TABLE unrelated(id INTEGER)") + connection.commit() + elif kind == "corrupt": + path.write_text("not a database", encoding="utf-8") + elif kind == "inaccessible": + path = tmp_path / "missing-parent" / "unusable.sqlite" + url = "invalid://unusable" if kind == "invalid_url" else f"sqlite:///{path.as_posix()}" + monkeypatch.setattr(settings, "auth_database_url", url) + get_auth_engine.cache_clear() + try: + with pytest.raises(ValueError, match="accessible migrated SQLite"): + create_app() + if kind in ("missing", "inaccessible"): + assert not path.exists() + if kind == "unmigrated": + with closing(sqlite3.connect(path)) as connection: + assert connection.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall() == [("unrelated",)] + finally: + if get_auth_engine.cache_info().currsize: + get_auth_engine().dispose() + get_auth_engine.cache_clear() + path.unlink(missing_ok=True) + + +def test_login_and_me(client): + response = login(client, username=" SAMPLE.User ") + assert response.status_code == 200 + body = response.json + assert set(body) == {"token", "expires_in", "user"} + assert body["expires_in"] == TOKEN_MAX_AGE + expected = {"id": 1, "username": "sample.user", "roles": ["CAMA", "TEA"]} + assert body["user"] == expected + assert serializer(TEST_SECRET).loads(body["token"]) == {"user_id": 1, "v": 1} + assert "password" not in json.dumps(body) and "hash" not in json.dumps(body) + assert response.headers["Cache-Control"] == "no-store" + me = client.get("/auth/me", headers=bearer(body["token"])) + assert me.status_code == 200 and me.json == {"user": expected} + assert me.headers["Cache-Control"] == "no-store" + + +@pytest.mark.parametrize("condition", ["missing", "wrong_password", "inactive"]) +def test_generic_credentials(client, condition): + changes = {} + if condition == "missing": + changes["username"] = "absent.user" + elif condition == "wrong_password": + changes["password"] = "incorrect" + else: + with get_auth_engine().begin() as connection: + connection.execute(text("UPDATE user SET activo=0 WHERE id=1")) + response = login(client, **changes) + assert response.status_code == 401 and response.json == {"error": "invalid_credentials"} + assert response.headers["Cache-Control"] == "no-store" + + +@pytest.mark.parametrize("body", [None, [], "text", 1, {}, {"username": "sample.user"}, + {"password": TEST_PASSWORD}, {"username": 1, "password": TEST_PASSWORD}, + {"username": "sample.user", "password": []}, + *[{"username": name, "password": TEST_PASSWORD} for name in ("", "ab", "bad!", "ábc", "x" * 65)], + {"username": "sample.user", "password": ""}, {"username": "sample.user", "password": "x" * 129}]) +def test_invalid_login_body(client, body): + response = client.post("/auth/login", data=json.dumps(body), content_type="application/json") + assert response.status_code == 400 and response.json == {"error": "invalid_request"} + assert response.headers["Cache-Control"] == "no-store" + + +def test_no_json_and_malformed_json(client): + for kwargs in ({"data": "plain"}, {"data": "{", "content_type": "application/json"}): + response = client.post("/auth/login", **kwargs) + assert response.status_code == 400 + assert response.headers["Cache-Control"] == "no-store" + + +@pytest.mark.parametrize("header", [None, "Basic abc", "Bearer", "Bearer ", "Bearer garbage", "Bearer a b"]) +def test_bad_authorization(client, header): + response = client.get("/auth/me", headers={} if header is None else {"Authorization": header}) + assert response.status_code == 401 and response.json == {"error": "unauthorized"} + assert response.headers["Cache-Control"] == "no-store" + + +@pytest.mark.parametrize("payload", [None, [], 1, {}, {"user_id": 1}, {"user_id": 1, "v": 2}, + {"user_id": 1, "v": True}, {"user_id": 1, "v": 1, "roles": []}, + *[{"user_id": value, "v": 1} for value in (None, "1", True, 0, -1, 1.0, 2**63)]]) +def test_bad_signed_payload(client, payload): + response = client.get("/auth/me", headers=bearer(serializer(TEST_SECRET).dumps(payload))) + assert response.status_code == 401 and response.json == {"error": "unauthorized"} + + +def test_altered_and_wrong_secret(client): + token = issue_token(TEST_SECRET, 1) + pieces = token.split(".") + pieces[-1] = ("A" if pieces[-1][0] != "A" else "B") + pieces[-1][1:] + for invalid in (".".join(pieces), issue_token("different-fictitious-secret", 1)): + assert client.get("/auth/me", headers=bearer(invalid)).status_code == 401 + + +def test_expired_deterministically(client, monkeypatch): + from itsdangerous import TimestampSigner + monkeypatch.setattr(TimestampSigner, "get_timestamp", lambda self: 100000) + token = issue_token(TEST_SECRET, 1) + monkeypatch.setattr(TimestampSigner, "get_timestamp", lambda self: 100000 + TOKEN_MAX_AGE) + assert client.get("/auth/me", headers=bearer(token)).status_code == 200 + monkeypatch.setattr(TimestampSigner, "get_timestamp", lambda self: 100001 + TOKEN_MAX_AGE) + response = client.get("/auth/me", headers=bearer(token)) + assert response.status_code == 401 and response.json == {"error": "unauthorized"} + + +@pytest.mark.parametrize("change", ["inactive", "deleted", "roles"]) +def test_me_revalidates(client, change): + token = login(client).json["token"] + with get_auth_engine().begin() as connection: + if change == "inactive": + connection.execute(text("UPDATE user SET activo=0 WHERE id=1")) + elif change == "deleted": + connection.execute(text("DELETE FROM user WHERE id=1")) + else: + connection.execute(text("DELETE FROM user_role WHERE user_id=1")) + connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (1,'CACU')")) + response = client.get("/auth/me", headers=bearer(token)) + if change == "roles": + assert response.status_code == 200 and response.json["user"]["roles"] == ["CACU"] + else: + assert response.status_code == 401 and response.json == {"error": "unauthorized"} + + +def test_enabled_clinical_routes_are_independent(client, monkeypatch): + from persistance.cacu import paciente_repository as cacu + from persistance.cama import paciente_repository as cama + from persistance.tea import pacientes_repository as tea + for domain, repo in (("cacu", cacu), ("cama", cama), ("tea", tea)): + monkeypatch.setattr(repo, "get", lambda key: None) + assert client.get(f"/{domain}/pacientes/999").status_code == 404 + assert client.post(f"/{domain}/predict").status_code == 501 + assert client.get("/health").status_code == 200 + assert client.get("/auth/login").headers["Cache-Control"] == "no-store" + assert client.get("/auth/missing").headers["Cache-Control"] == "no-store" + + +def test_bootstrap_creation_repeat_and_update(storage, monkeypatch, capsys): + from webapi import auth_bootstrap + monkeypatch.setattr(auth_bootstrap, "getpass", lambda prompt: TEST_PASSWORD) + assert main(["--username", " NEW.User ", "--roles", "TEA", "CAMA", "CAMA"]) == 0 + from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id + user = get_user_by_username("new.user") + assert user.password_hash.startswith("scrypt:") and check_password_hash(user.password_hash, TEST_PASSWORD) + assert get_user_with_roles_by_id(user.id)[1] == ["CAMA", "TEA"] + old_hash = user.password_hash + assert main(["--username", "new.user", "--roles", "ADMIN"]) == 1 + assert get_user_by_username("new.user").password_hash == old_hash + with get_auth_engine().begin() as connection: + connection.execute(text("UPDATE user SET activo=0 WHERE id=:id"), {"id": user.id}) + new_password = "another-fictitious-password" + monkeypatch.setattr(auth_bootstrap, "getpass", lambda prompt: new_password) + assert main(["--username", "new.user", "--roles", "ADMIN", "--update"]) == 0 + updated = get_user_by_username("new.user") + assert updated.id == user.id and not updated.activo + assert check_password_hash(updated.password_hash, new_password) + assert get_user_with_roles_by_id(user.id)[1] == ["ADMIN"] + output = capsys.readouterr() + assert all(value not in output.out + output.err for value in (TEST_PASSWORD, new_password, old_hash, updated.password_hash)) + + +@pytest.mark.parametrize("username,roles,password", [ + ("bad!", ["CAMA"], TEST_PASSWORD), (None, ["CAMA"], TEST_PASSWORD), + ("good.user", [], TEST_PASSWORD), ("good.user", ["OTHER"], TEST_PASSWORD), + *[("good.user", ["CAMA"], value) for value in (None, "", "short", "x" * 129)]]) +def test_bootstrap_invalid(storage, username, roles, password): + with pytest.raises(ValueError): + bootstrap(username, roles, password) + with get_auth_engine().connect() as connection: + assert connection.execute(text("SELECT count(*) FROM user")).scalar_one() == 0 + + +def test_bootstrap_atomic_rollback(storage): + from sqlalchemy.exc import IntegrityError + from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id + user_id = bootstrap("atomic.user", ["CAMA"], TEST_PASSWORD) + original_hash = get_user_by_username("atomic.user").password_hash + with get_auth_engine().begin() as connection: + connection.execute(text("DELETE FROM role WHERE code='TEA'")) + for name, update in (("new.user", False), ("atomic.user", True)): + with pytest.raises(IntegrityError): + bootstrap(name, ["ADMIN", "TEA"], "different-fictitious-password", update=update) + assert get_user_by_username("new.user") is None + assert get_user_by_username("atomic.user").password_hash == original_hash + assert get_user_with_roles_by_id(user_id)[1] == ["CAMA"] + + +def test_bootstrap_cli_rejects_role_and_password_argument(storage): + for args in (["--username", "sample.user", "--roles", "OTHER"], + ["--username", "sample.user", "--roles", "CAMA", "--password", "dummy"]): + with pytest.raises(SystemExit) as error: + main(args) + assert error.value.code == 2 + + +def test_bootstrap_cli_invalid_password(storage, monkeypatch, capsys): + from webapi import auth_bootstrap + monkeypatch.setattr(auth_bootstrap, "getpass", lambda prompt: "short") + assert main(["--username", "sample.user", "--roles", "CAMA"]) == 1 + assert "short" not in capsys.readouterr().out + + +# Fase J: all demo credentials are consumed from the single seed definition. +from webapi import auth_demo_seed as demo + + +def demo_snapshot(): + with get_auth_engine().connect() as connection: + return (connection.execute(text("SELECT * FROM user ORDER BY id")).fetchall(), + connection.execute(text("SELECT * FROM user_role ORDER BY user_id,role_code")).fetchall()) + + +def test_demo_definition(): + accounts = demo.validate_demo_users() + assert [(a["username"], a["roles"]) for a in accounts] == [ + ("admin", ("ADMIN",)), ("cacu", ("CACU",)), ("cama", ("CAMA",)), ("tea", ("TEA",))] + + +def test_demo_ensure_hashes_roles_http_and_idempotence(storage, capsys): + assert demo.main(["--ensure"]) == 0 + original = demo_snapshot() + assert len(original[0]) == 4 + from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id + app = create_app() + with app.test_client() as client: + for account in demo.DEMO_USERS: + user = get_user_by_username(account["username"]) + assert user.password_hash != account["password"] + assert user.password_hash.startswith("scrypt:") + assert check_password_hash(user.password_hash, account["password"]) + assert get_user_with_roles_by_id(user.id)[1] == list(account["roles"]) + response = client.post("/auth/login", json={"username": account["username"], "password": account["password"]}) + assert response.status_code == 200 + assert response.json["user"]["roles"] == list(account["roles"]) + assert demo.main(["--ensure"]) == 0 + assert demo_snapshot() == original + output = capsys.readouterr().out + assert output.count("-> created") == 4 and output.count("-> skipped") == 4 + assert all(a["password"] not in output for a in demo.DEMO_USERS) + assert all(row.password_hash not in output for row in original[0]) + + +@pytest.mark.parametrize("roles,active", [(["TEA"], True), (["CAMA", "TEA"], False), (["ADMIN"], False)]) +def test_demo_partial_preserves_every_existing_field(storage, roles, active): + bootstrap(" ADMIN ", roles, TEST_PASSWORD) + with get_auth_engine().begin() as connection: + connection.execute(text("UPDATE user SET activo=:active WHERE username='admin'"), {"active": active}) + original = demo_snapshot() + result = demo.seed_demo_users() + assert [r[2] for r in result] == ["skipped", "created", "created", "created"] + after = demo_snapshot() + assert after[0][0] == original[0][0] + assert [r for r in after[1] if r.user_id == original[0][0].id] == original[1] + assert check_password_hash(after[0][0].password_hash, TEST_PASSWORD) + + +def test_demo_normalizes_before_lookup(storage, monkeypatch): + bootstrap("admin", ["TEA"], TEST_PASSWORD) + monkeypatch.setattr(demo, "DEMO_USERS", tuple({**a, "username": f" {a['username'].upper()} "} for a in demo.DEMO_USERS)) + result = demo.seed_demo_users() + assert result[0] == ("admin", ("ADMIN",), "skipped") + assert len(demo_snapshot()[0]) == 4 + + +@pytest.mark.parametrize("invalid", [ + {"username": "bad!"}, {"password": ""}, {"password": "short"}, + {"roles": ()}, {"roles": ("OTHER",)}, {"roles": ("ADMIN", "ADMIN")}, + {"roles": "ADMIN"}, {"roles": (None,)}, {"username": None}, +]) +@pytest.mark.parametrize("replace", [False, True]) +def test_demo_invalid_configuration_never_changes_db(storage, monkeypatch, invalid, replace): + bootstrap("existing.user", ["TEA"], TEST_PASSWORD) + original = demo_snapshot() + monkeypatch.setattr(demo, "DEMO_USERS", (*demo.DEMO_USERS[:-1], {**demo.DEMO_USERS[-1], **invalid})) + with pytest.raises(ValueError): + demo.seed_demo_users(replace_all=replace) + assert demo_snapshot() == original + + +def test_demo_duplicate_normalized_username(storage, monkeypatch): + monkeypatch.setattr(demo, "DEMO_USERS", (*demo.DEMO_USERS, {**demo.DEMO_USERS[0], "username": " ADMIN "})) + with pytest.raises(ValueError, match="duplicate"): + demo.seed_demo_users() + assert demo_snapshot() == ([], []) + + +@pytest.mark.parametrize("replace", [False, True]) +def test_demo_missing_roles_before_mutation(storage, replace): + bootstrap("existing.user", ["ADMIN"], TEST_PASSWORD) + with get_auth_engine().begin() as connection: + connection.execute(text("DELETE FROM role WHERE code='TEA'")) + original = demo_snapshot() + with pytest.raises(ValueError, match="roles are missing"): + demo.seed_demo_users(replace_all=replace) + assert demo_snapshot() == original + + +def test_demo_replace_confirmed_cascade_schema_and_output(storage, monkeypatch, capsys): + bootstrap("foreign.user", ["CAMA", "TEA"], TEST_PASSWORD) + monkeypatch.setattr("builtins.input", lambda prompt: "REPLACE") + with get_auth_engine().connect() as connection: + schema = connection.execute(text("SELECT name,sql FROM sqlite_master ORDER BY name")).fetchall() + version = connection.execute(text("SELECT * FROM alembic_version")).fetchall() + assert demo.main(["--replace-all"]) == 0 + users, associations = demo_snapshot() + assert {r.username for r in users} == {a["username"] for a in demo.DEMO_USERS} + assert len(associations) == 4 + with get_auth_engine().connect() as connection: + assert connection.execute(text("PRAGMA foreign_keys")).scalar_one() == 1 + assert connection.execute(text("PRAGMA foreign_key_check")).fetchall() == [] + assert connection.execute(text("SELECT name,sql FROM sqlite_master ORDER BY name")).fetchall() == schema + assert connection.execute(text("SELECT * FROM alembic_version")).fetchall() == version + assert connection.execute(text("SELECT count(*) FROM role")).scalar_one() == 4 + assert storage.is_file() + output = capsys.readouterr().out + assert "WARNING" in output and "replaced" in output + assert all(a["password"] not in output for a in demo.DEMO_USERS) + + +@pytest.mark.parametrize("answer", ["", "replace", " REPLACE", "REPLACE ", "NO", None]) +def test_demo_cancelled_before_storage(storage, monkeypatch, answer, capsys): + bootstrap("foreign.user", ["TEA"], TEST_PASSWORD) + original = demo_snapshot() + def confirm(prompt): + if answer is None: + raise EOFError + return answer + monkeypatch.setattr("builtins.input", confirm) + monkeypatch.setattr(demo, "validate_auth_storage", lambda: pytest.fail("cancel touched storage")) + assert demo.main(["--replace-all"]) == 0 + assert demo_snapshot() == original + assert "cancelled" in capsys.readouterr().out + + +@pytest.mark.parametrize("replace", [False, True]) +def test_demo_insert_failure_rolls_back_everything(storage, monkeypatch, replace): + from sqlmodel import Session + bootstrap("foreign.user", ["TEA", "CAMA"], TEST_PASSWORD) + original = demo_snapshot() + original_flush = Session.flush + calls = 0 + def failing_flush(self, *args, **kwargs): + nonlocal calls + calls += 1 + result = original_flush(self, *args, **kwargs) + if calls == 5: + raise RuntimeError("injected after mutation") + return result + monkeypatch.setattr(Session, "flush", failing_flush) + with pytest.raises(RuntimeError): + demo.seed_demo_users(replace_all=replace) + assert calls >= 5 + assert demo_snapshot() == original + + +@pytest.mark.parametrize("mode", ["--ensure", "--replace-all"]) +def test_demo_disabled_never_touches_storage(monkeypatch, mode, capsys): + monkeypatch.setenv("AUTH_LITE_ENABLED", "false") + monkeypatch.setenv("AUTH_LITE_SEED_DEMO_USERS", "true") + monkeypatch.setattr(demo, "validate_auth_storage", lambda: pytest.fail("disabled touched storage")) + monkeypatch.setattr("builtins.input", lambda prompt: pytest.fail("disabled requested confirmation")) + assert demo.main([mode]) == 0 + assert "disabled" in capsys.readouterr().out diff --git a/webapi/__init__.py b/webapi/__init__.py index 26266fc..71ddfdc 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -1,10 +1,20 @@ -from flask import Flask +import os + +from flask import Flask, request from webapi.blueprints.cacu import cacu_bp from webapi.blueprints.cama import cama_bp from webapi.blueprints.tea import tea_bp +def parse_auth_lite_enabled(value: str | None) -> bool: + if value is None or value == "false": + return False + if value == "true": + return True + raise ValueError("AUTH_LITE_ENABLED must be exactly 'true' or 'false'") + + def create_app() -> Flask: app = Flask(__name__) @@ -16,4 +26,21 @@ def create_app() -> Flask: app.register_blueprint(cama_bp, url_prefix="/cama") app.register_blueprint(tea_bp, url_prefix="/tea") + if parse_auth_lite_enabled(os.environ.get("AUTH_LITE_ENABLED")): + from webapi.auth_token import validate_auth_storage + from webapi.blueprints.auth import auth_bp + + secret = os.environ.get("AUTH_LITE_SECRET_KEY") + if not secret or not secret.strip(): + raise ValueError("AUTH_LITE_SECRET_KEY is required when Auth-Lite is enabled") + validate_auth_storage() + app.config["AUTH_LITE_SECRET_KEY"] = secret + app.register_blueprint(auth_bp, url_prefix="/auth") + + @app.after_request + def auth_no_store(response): + if request.path == "/auth" or request.path.startswith("/auth/"): + response.headers["Cache-Control"] = "no-store" + return response + return app diff --git a/webapi/auth_bootstrap.py b/webapi/auth_bootstrap.py new file mode 100644 index 0000000..2e844d7 --- /dev/null +++ b/webapi/auth_bootstrap.py @@ -0,0 +1,67 @@ +"""Explicit interactive account bootstrap; never accepts a password argument.""" +import argparse +from getpass import getpass + +from sqlalchemy import delete +from sqlmodel import select +from werkzeug.security import generate_password_hash + +from core.auth.models import User, UserRole +from persistance.db import get_auth_engine, get_auth_session +from webapi.auth_token import normalize_username, validate_auth_storage, validate_password + +ALLOWED_ROLES = {"ADMIN", "CACU", "CAMA", "TEA"} + + +def bootstrap(username: str, roles: list[str], password: str, update: bool = False) -> int: + username = normalize_username(username) + validate_password(password, minimum=8) + if not roles or any(role not in ALLOWED_ROLES for role in roles): + raise ValueError("at least one role from ADMIN/CACU/CAMA/TEA is required") + validate_auth_storage() + with get_auth_session() as session: + with session.begin(): + user = session.exec(select(User).where(User.username == username)).first() + if user is not None and not update: + raise ValueError("user already exists; use --update explicitly") + password_hash = generate_password_hash(password, method="scrypt") + if user is None: + user = User(username=username, password_hash=password_hash) + session.add(user) + session.flush() + else: + user.password_hash = password_hash + session.add(user) + session.exec(delete(UserRole).where(UserRole.user_id == user.id)) + for role in sorted(set(roles)): + session.add(UserRole(user_id=user.id, role_code=role)) + user_id = user.id + return user_id + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Bootstrap an Auth-Lite account interactively") + parser.add_argument("--username", required=True) + parser.add_argument("--roles", nargs="+", required=True, choices=sorted(ALLOWED_ROLES)) + parser.add_argument("--update", action="store_true") + args = parser.parse_args(argv) + try: + username = normalize_username(args.username) + validate_auth_storage() + bootstrap(username, args.roles, getpass("Password: "), update=args.update) + print("Auth-Lite account saved.") + return 0 + except ValueError as error: + print(str(error)) + return 1 + except Exception: + print("Auth-Lite bootstrap failed; transaction rolled back.") + return 1 + finally: + if get_auth_engine.cache_info().currsize: + get_auth_engine().dispose() + get_auth_engine.cache_clear() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/webapi/auth_demo_seed.py b/webapi/auth_demo_seed.py new file mode 100644 index 0000000..ed1b356 --- /dev/null +++ b/webapi/auth_demo_seed.py @@ -0,0 +1,117 @@ +"""Explicit, transactional demo account provisioning; never suitable for production.""" +import argparse +import os + +from sqlalchemy import delete +from sqlmodel import select +from werkzeug.security import generate_password_hash + +from core.auth.models import Role, User, UserRole +from persistance.db import get_auth_engine, get_auth_session +from webapi import parse_auth_lite_enabled +from webapi.auth_bootstrap import ALLOWED_ROLES +from webapi.auth_token import normalize_username, validate_auth_storage, validate_password + +# DEMO-ONLY credentials. These credentials are intentionally simple and public +# for demonstrations. Do not enable the demo seed in production. +DEMO_USERS = ( + {"username": "admin", "password": "Admin1234", "roles": ("ADMIN",)}, + {"username": "cacu", "password": "Cacu1234", "roles": ("CACU",)}, + {"username": "cama", "password": "Cama1234", "roles": ("CAMA",)}, + {"username": "tea", "password": "Tea12345", "roles": ("TEA",)}, +) + + +def validate_demo_users(): + """Validate the entire editable definition, including skipped accounts.""" + validated = [] + usernames = set() + if not DEMO_USERS: + raise ValueError("demo configuration must contain accounts") + for entry in DEMO_USERS: + if not isinstance(entry, dict) or set(entry) != {"username", "password", "roles"}: + raise ValueError("invalid demo account definition") + username = normalize_username(entry["username"]) + password = validate_password(entry["password"], minimum=8) + roles = entry["roles"] + if (not isinstance(roles, (tuple, list)) or not roles + or any(not isinstance(role, str) or role not in ALLOWED_ROLES for role in roles) + or len(set(roles)) != len(roles)): + raise ValueError("demo roles must be unique and from ADMIN/CACU/CAMA/TEA") + if username in usernames: + raise ValueError("duplicate normalized demo username") + usernames.add(username) + validated.append({"username": username, "password": password, "roles": tuple(roles)}) + return validated + + +def seed_demo_users(*, replace_all: bool = False): + """Complete missing accounts, or replace all, in one transaction. + + The explicit CLI requires Auth enabled. The internal function is also usable + with migrated temporary storage in tests; it never creates/migrates storage. + """ + accounts = validate_demo_users() + validate_auth_storage() + results = [] + with get_auth_session() as session: + with session.begin(): + required = {role for account in accounts for role in account["roles"]} + if not required <= set(session.exec(select(Role.code))): + raise ValueError("required demo roles are missing; apply Auth migration first") + existing = set(session.exec(select(User.username))) + missing = accounts if replace_all else [a for a in accounts if a["username"] not in existing] + # Hash every new password before any delete/insert. No plaintext enters DB. + hashes = {a["username"]: generate_password_hash(a["password"], method="scrypt") for a in missing} + if replace_all: + session.exec(delete(User)) # FK ON DELETE CASCADE clears user_role. + for account in accounts: + username, roles = account["username"], account["roles"] + if username not in hashes: + results.append((username, roles, "skipped")) + continue + user = User(username=username, password_hash=hashes[username]) + session.add(user) + session.flush() + for role in roles: + session.add(UserRole(user_id=user.id, role_code=role)) + results.append((username, roles, "created")) + return results + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="DEMO ONLY: provision public Auth-Lite accounts") + modes = parser.add_mutually_exclusive_group(required=True) + modes.add_argument("--ensure", action="store_true", help="create only missing usernames") + modes.add_argument("--replace-all", action="store_true", help="delete EVERY Auth user; requires REPLACE") + args = parser.parse_args(argv) + try: + if not parse_auth_lite_enabled(os.environ.get("AUTH_LITE_ENABLED")): + print("Auth-Lite is disabled; demo seed skipped.") + return 0 + if args.replace_all: + print("WARNING: this will delete every Auth-Lite user.") + try: + confirmation = input("Type REPLACE to continue: ") + except EOFError: + confirmation = "" + if confirmation != "REPLACE": + print("Auth-Lite demo replacement cancelled; no changes.") + return 0 + results = seed_demo_users(replace_all=args.replace_all) + print("Auth-Lite demo users replaced." if args.replace_all else "Auth-Lite demo seed:") + for username, roles, status in results: + print(f"{username} [{','.join(roles)}] -> {status}") + return 0 + except Exception: + # Editable configuration and DB exceptions may include sensitive values. + print("Auth-Lite demo seed failed; transaction rolled back. Check configuration and migrated storage.") + return 1 + finally: + if get_auth_engine.cache_info().currsize: + get_auth_engine().dispose() + get_auth_engine.cache_clear() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/webapi/auth_token.py b/webapi/auth_token.py new file mode 100644 index 0000000..4d3dbb8 --- /dev/null +++ b/webapi/auth_token.py @@ -0,0 +1,76 @@ +"""Auth-Lite token, input and explicit storage validation helpers.""" +from pathlib import Path +import re + +from itsdangerous import BadData, URLSafeTimedSerializer +from sqlalchemy import inspect +from sqlalchemy.engine import make_url + +TOKEN_MAX_AGE = 28800 +TOKEN_SALT = "auth-lite-session-v1" + + +def normalize_username(value: str) -> str: + if not isinstance(value, str): + raise ValueError("username must be a string") + value = value.strip().lower() + if not re.fullmatch(r"[a-z0-9._-]{3,64}", value): + raise ValueError("username must contain 3-64 characters from [a-z0-9._-]") + return value + + +def validate_password(value: str, minimum: int = 1) -> str: + if not isinstance(value, str) or not minimum <= len(value) <= 128: + raise ValueError(f"password must contain {minimum}-128 characters") + return value + + +def validate_auth_storage() -> None: + from persistance.db import get_auth_engine + from persistance.settings import settings + + try: + url = make_url(settings.auth_database_url) + if url.get_backend_name() != "sqlite": + raise ValueError("SQLite required") + if not url.database or url.database == ":memory:" or not Path(url.database).is_file(): + raise ValueError("existing SQLite required") + engine = get_auth_engine() + if not {"user", "role", "user_role", "alembic_version"} <= set(inspect(engine).get_table_names()): + raise ValueError("migration required") + # Validate the columns needed by login/bootstrap, without creating schema. + from sqlalchemy import text + with engine.connect() as connection: + connection.execute(text("SELECT id, username, password_hash, activo FROM user LIMIT 0")) + connection.execute(text("SELECT code FROM role LIMIT 0")) + connection.execute(text("SELECT user_id, role_code FROM user_role LIMIT 0")) + except Exception: + if get_auth_engine.cache_info().currsize: + get_auth_engine().dispose() + get_auth_engine.cache_clear() + raise ValueError("Auth-Lite storage must be an accessible migrated SQLite database") from None + + +def serializer(secret: str) -> URLSafeTimedSerializer: + return URLSafeTimedSerializer(secret, salt=TOKEN_SALT) + + +def issue_token(secret: str, user_id: int) -> str: + return serializer(secret).dumps({"user_id": user_id, "v": 1}) + + +def read_token(secret: str, token: str) -> int | None: + try: + payload = serializer(secret).loads(token, max_age=TOKEN_MAX_AGE) + except BadData: + return None + if not isinstance(payload, dict) or set(payload) != {"user_id", "v"}: + return None + if type(payload["v"]) is not int or payload["v"] != 1: + return None + user_id = payload["user_id"] + return user_id if type(user_id) is int and 0 < user_id <= 9223372036854775807 else None + + +def user_dto(user, roles: list[str]) -> dict: + return {"id": user.id, "username": user.username, "roles": sorted(roles)} diff --git a/webapi/blueprints/auth.py b/webapi/blueprints/auth.py new file mode 100644 index 0000000..53ddb02 --- /dev/null +++ b/webapi/blueprints/auth.py @@ -0,0 +1,44 @@ +from flask import Blueprint, current_app, request +from werkzeug.security import check_password_hash + +from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id +from webapi.auth_token import ( + TOKEN_MAX_AGE, issue_token, normalize_username, read_token, user_dto, validate_password, +) + +auth_bp = Blueprint("auth", __name__) + + +@auth_bp.post("/login") +def login(): + body = request.get_json(silent=True) + try: + if not isinstance(body, dict): + raise ValueError("JSON object required") + username = normalize_username(body.get("username")) + password = validate_password(body.get("password")) + except ValueError: + return {"error": "invalid_request"}, 400 + user = get_user_by_username(username) + if user is None or not user.activo or not check_password_hash(user.password_hash, password): + return {"error": "invalid_credentials"}, 401 + identity = get_user_with_roles_by_id(user.id) + if identity is None or not identity[0].activo: + return {"error": "invalid_credentials"}, 401 + return { + "token": issue_token(current_app.config["AUTH_LITE_SECRET_KEY"], user.id), + "expires_in": TOKEN_MAX_AGE, + "user": user_dto(*identity), + } + + +@auth_bp.get("/me") +def me(): + parts = request.headers.get("Authorization", "").split() + if len(parts) != 2 or parts[0].lower() != "bearer": + return {"error": "unauthorized"}, 401 + user_id = read_token(current_app.config["AUTH_LITE_SECRET_KEY"], parts[1]) + identity = get_user_with_roles_by_id(user_id) if user_id is not None else None + if identity is None or not identity[0].activo: + return {"error": "unauthorized"}, 401 + return {"user": user_dto(*identity)}