Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4ac3026bb1 |
@@ -0,0 +1,4 @@
|
||||
from core.auth.base import AuthModel
|
||||
from core.auth.models import Role, User, UserRole
|
||||
|
||||
__all__ = ["AuthModel", "User", "Role", "UserRole"]
|
||||
@@ -0,0 +1,8 @@
|
||||
import sqlalchemy.orm as orm
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
registry = orm.registry()
|
||||
|
||||
|
||||
class AuthModel(SQLModel, registry=registry):
|
||||
"""Base class for Auth tables, isolated from clinical metadata."""
|
||||
@@ -0,0 +1,60 @@
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
|
||||
from core.auth.base import AuthModel
|
||||
|
||||
|
||||
class User(AuthModel, table=True):
|
||||
__tablename__ = "user"
|
||||
__table_args__ = (
|
||||
sa.CheckConstraint(
|
||||
"length(username) BETWEEN 3 AND 64 "
|
||||
"AND username NOT GLOB '*[^a-z0-9._-]*'",
|
||||
name="ck_user_username_format",
|
||||
),
|
||||
)
|
||||
|
||||
id: int | None = Field(
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
username: str = Field(
|
||||
sa_column=sa.Column(sa.String(64), nullable=False, unique=True),
|
||||
)
|
||||
password_hash: str = Field(
|
||||
sa_column=sa.Column(sa.Text, nullable=False),
|
||||
)
|
||||
activo: bool = Field(
|
||||
default=True,
|
||||
sa_column=sa.Column(sa.Boolean, nullable=False, default=True, server_default=sa.true()),
|
||||
)
|
||||
|
||||
|
||||
class Role(AuthModel, table=True):
|
||||
__tablename__ = "role"
|
||||
__table_args__ = (
|
||||
sa.CheckConstraint("code IN ('ADMIN', 'CACU', 'CAMA', 'TEA')", name="ck_role_code_allowed"),
|
||||
)
|
||||
|
||||
code: str = Field(sa_column=sa.Column(sa.String(8), primary_key=True))
|
||||
|
||||
|
||||
class UserRole(AuthModel, table=True):
|
||||
__tablename__ = "user_role"
|
||||
|
||||
user_id: int = Field(
|
||||
sa_column=sa.Column(
|
||||
sa.Integer,
|
||||
sa.ForeignKey("user.id", ondelete="CASCADE"),
|
||||
primary_key=True,
|
||||
nullable=False,
|
||||
),
|
||||
)
|
||||
role_code: str = Field(
|
||||
sa_column=sa.Column(
|
||||
sa.String(8),
|
||||
sa.ForeignKey("role.code"),
|
||||
primary_key=True,
|
||||
nullable=False,
|
||||
),
|
||||
)
|
||||
@@ -1,8 +1,11 @@
|
||||
"""Smoke tests: each domain's models import cleanly and register on their
|
||||
own isolated metadata (no cross-domain table-name collisions)."""
|
||||
import sqlalchemy as sa
|
||||
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.cama.base import CaMaModel
|
||||
from core.tea.base import TeaModel
|
||||
from core.auth.base import AuthModel
|
||||
from core.cacu import models as cacu_models
|
||||
from core.cama import models as cama_models
|
||||
from core.tea import models as tea_models
|
||||
@@ -36,3 +39,50 @@ def test_domains_do_not_share_metadata():
|
||||
assert CaCuModel.metadata is not CaMaModel.metadata
|
||||
assert CaCuModel.metadata is not TeaModel.metadata
|
||||
assert CaMaModel.metadata is not TeaModel.metadata
|
||||
assert AuthModel.metadata is not CaCuModel.metadata
|
||||
assert AuthModel.metadata is not CaMaModel.metadata
|
||||
assert AuthModel.metadata is not TeaModel.metadata
|
||||
|
||||
|
||||
def test_auth_tables_registered():
|
||||
assert set(AuthModel.metadata.tables) == {"user", "role", "user_role"}
|
||||
|
||||
|
||||
def test_auth_primary_keys_and_foreign_keys():
|
||||
users = AuthModel.metadata.tables["user"]
|
||||
roles = AuthModel.metadata.tables["role"]
|
||||
user_roles = AuthModel.metadata.tables["user_role"]
|
||||
|
||||
assert [column.name for column in users.primary_key.columns] == ["id"]
|
||||
assert [column.name for column in roles.primary_key.columns] == ["code"]
|
||||
assert {column.name for column in user_roles.primary_key.columns} == {"user_id", "role_code"}
|
||||
assert {foreign_key.target_fullname for foreign_key in user_roles.foreign_keys} == {
|
||||
"user.id",
|
||||
"role.code",
|
||||
}
|
||||
ondelete_by_column = {
|
||||
next(iter(user_roles.c[column_name].foreign_keys)).parent.name:
|
||||
next(iter(user_roles.c[column_name].foreign_keys)).ondelete
|
||||
for column_name in ("user_id", "role_code")
|
||||
}
|
||||
assert ondelete_by_column == {"user_id": "CASCADE", "role_code": None}
|
||||
|
||||
|
||||
def test_auth_essential_constraints():
|
||||
users = AuthModel.metadata.tables["user"]
|
||||
roles = AuthModel.metadata.tables["role"]
|
||||
|
||||
assert any(
|
||||
list(constraint.columns.keys()) == ["username"]
|
||||
for constraint in users.constraints
|
||||
if isinstance(constraint, sa.UniqueConstraint)
|
||||
)
|
||||
username_check = next(
|
||||
constraint
|
||||
for constraint in users.constraints
|
||||
if isinstance(constraint, sa.CheckConstraint)
|
||||
and constraint.name == "ck_user_username_format"
|
||||
)
|
||||
assert "length(username) BETWEEN 3 AND 64" in str(username_check.sqltext)
|
||||
assert "username NOT GLOB '*[^a-z0-9._-]*'" in str(username_check.sqltext)
|
||||
assert any(constraint.name == "ck_role_code_allowed" for constraint in roles.constraints)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Read access and migration environment for the independent Auth database."""
|
||||
@@ -0,0 +1,38 @@
|
||||
[alembic]
|
||||
script_location = %(here)s/alembic
|
||||
prepend_sys_path = .
|
||||
path_separator = os
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,49 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from core.auth import models # noqa: F401 -- registers Auth tables
|
||||
from core.auth.base import AuthModel
|
||||
from persistance.settings import settings
|
||||
|
||||
config = context.config
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
config.set_main_option("sqlalchemy.url", settings.auth_database_url)
|
||||
target_metadata = AuthModel.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(
|
||||
url=config.get_main_option("sqlalchemy.url"),
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
render_as_batch=connection.dialect.name == "sqlite",
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,26 @@
|
||||
<%!
|
||||
import re
|
||||
%>"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
import sqlmodel
|
||||
${imports if imports else ""}
|
||||
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Create Auth tables and fixed role codes.
|
||||
|
||||
Revision ID: a1b2c3d4e5f6
|
||||
Revises:
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "a1b2c3d4e5f6"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"user",
|
||||
sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
|
||||
sa.Column("username", sa.String(64), nullable=False, unique=True),
|
||||
sa.Column("password_hash", sa.Text(), nullable=False),
|
||||
sa.Column("activo", sa.Boolean(), nullable=False, server_default=sa.true()),
|
||||
sa.CheckConstraint(
|
||||
"length(username) BETWEEN 3 AND 64 "
|
||||
"AND username NOT GLOB '*[^a-z0-9._-]*'",
|
||||
name="ck_user_username_format",
|
||||
),
|
||||
)
|
||||
op.create_table(
|
||||
"role",
|
||||
sa.Column("code", sa.String(8), primary_key=True),
|
||||
sa.CheckConstraint("code IN ('ADMIN', 'CACU', 'CAMA', 'TEA')", name="ck_role_code_allowed"),
|
||||
)
|
||||
op.create_table(
|
||||
"user_role",
|
||||
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||
sa.Column("role_code", sa.String(8), nullable=False),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["user.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["role_code"], ["role.code"]),
|
||||
sa.PrimaryKeyConstraint("user_id", "role_code"),
|
||||
)
|
||||
op.bulk_insert(
|
||||
sa.table("role", sa.column("code", sa.String(8))),
|
||||
[{"code": code} for code in ("ADMIN", "CACU", "CAMA", "TEA")],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("user_role")
|
||||
op.drop_table("role")
|
||||
op.drop_table("user")
|
||||
@@ -0,0 +1,22 @@
|
||||
from sqlmodel import select
|
||||
|
||||
from core.auth.models import User, UserRole
|
||||
from persistance.db import get_auth_session
|
||||
|
||||
|
||||
def get_user_by_username(username: str) -> User | None:
|
||||
with get_auth_session() as session:
|
||||
return session.exec(select(User).where(User.username == username)).first()
|
||||
|
||||
|
||||
def get_user_with_roles_by_id(user_id: int) -> tuple[User, list[str]] | None:
|
||||
with get_auth_session() as session:
|
||||
user = session.get(User, user_id)
|
||||
if user is None:
|
||||
return None
|
||||
roles = list(session.exec(
|
||||
select(UserRole.role_code)
|
||||
.where(UserRole.user_id == user_id)
|
||||
.order_by(UserRole.role_code)
|
||||
))
|
||||
return user, roles
|
||||
@@ -1,6 +1,6 @@
|
||||
from functools import lru_cache
|
||||
|
||||
from sqlalchemy import Engine, create_engine
|
||||
from sqlalchemy import Engine, create_engine, event
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.settings import settings
|
||||
@@ -21,6 +21,20 @@ def get_tea_engine() -> Engine:
|
||||
return create_engine(settings.tea_database_url)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_auth_engine() -> Engine:
|
||||
engine = create_engine(settings.auth_database_url)
|
||||
if engine.dialect.name == "sqlite":
|
||||
@event.listens_for(engine, "connect")
|
||||
def enable_foreign_keys(dbapi_connection, connection_record) -> None:
|
||||
cursor = dbapi_connection.cursor()
|
||||
try:
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
finally:
|
||||
cursor.close()
|
||||
return engine
|
||||
|
||||
|
||||
def get_cacu_session() -> Session:
|
||||
return Session(get_cacu_engine())
|
||||
|
||||
@@ -31,3 +45,7 @@ def get_cama_session() -> Session:
|
||||
|
||||
def get_tea_session() -> Session:
|
||||
return Session(get_tea_engine())
|
||||
|
||||
|
||||
def get_auth_session() -> Session:
|
||||
return Session(get_auth_engine())
|
||||
|
||||
@@ -12,6 +12,7 @@ class PersistanceSettings(BaseSettings):
|
||||
cacu_database_url: str = "sqlite:///cacu.db"
|
||||
cama_database_url: str = "sqlite:///cama.db"
|
||||
tea_database_url: str = "sqlite:///tea.db"
|
||||
auth_database_url: str = "sqlite:///auth.db"
|
||||
|
||||
|
||||
settings = PersistanceSettings()
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from sqlalchemy import inspect, text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from persistance.db import get_auth_engine
|
||||
from persistance.settings import PersistanceSettings, settings
|
||||
|
||||
|
||||
ALEMBIC_INI = Path(__file__).resolve().parents[1] / "persistance/auth/alembic.ini"
|
||||
ROLES = ["ADMIN", "CACU", "CAMA", "TEA"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_db(tmp_path, monkeypatch):
|
||||
path = tmp_path / "auth.sqlite"
|
||||
monkeypatch.setattr(settings, "auth_database_url", f"sqlite:///{path.as_posix()}")
|
||||
get_auth_engine.cache_clear()
|
||||
yield path
|
||||
if get_auth_engine.cache_info().currsize:
|
||||
get_auth_engine().dispose()
|
||||
get_auth_engine.cache_clear()
|
||||
|
||||
|
||||
def migrate(revision: str) -> None:
|
||||
command.upgrade(Config(str(ALEMBIC_INI)), revision)
|
||||
|
||||
|
||||
def roles(connection):
|
||||
return connection.execute(text("SELECT code FROM role ORDER BY code")).scalars().all()
|
||||
|
||||
|
||||
def test_config_is_inert(tmp_path, monkeypatch):
|
||||
path = tmp_path / "unopened.sqlite"
|
||||
monkeypatch.setenv("AUTH_DATABASE_URL", f"sqlite:///{path.as_posix()}")
|
||||
configured = PersistanceSettings(_env_file=None)
|
||||
assert configured.auth_database_url.endswith("unopened.sqlite")
|
||||
assert not path.exists()
|
||||
assert PersistanceSettings.model_fields["auth_database_url"].default == "sqlite:///auth.db"
|
||||
|
||||
|
||||
def test_migration_schema_seed_and_constraints(auth_db):
|
||||
migrate("head")
|
||||
engine = get_auth_engine()
|
||||
inspector = inspect(engine)
|
||||
assert set(inspector.get_table_names()) == {"user", "role", "user_role", "alembic_version"}
|
||||
assert inspector.get_pk_constraint("user_role")["constrained_columns"] == ["user_id", "role_code"]
|
||||
fks = {fk["constrained_columns"][0]: fk for fk in inspector.get_foreign_keys("user_role")}
|
||||
assert fks["user_id"]["referred_table"] == "user"
|
||||
assert fks["user_id"]["options"]["ondelete"] == "CASCADE"
|
||||
assert fks["role_code"]["referred_table"] == "role"
|
||||
assert fks["role_code"]["options"].get("ondelete") != "CASCADE"
|
||||
assert inspector.get_unique_constraints("user")
|
||||
with engine.connect() as connection:
|
||||
assert roles(connection) == ROLES
|
||||
assert connection.execute(text("PRAGMA foreign_keys")).scalar_one() == 1
|
||||
with pytest.raises(IntegrityError):
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("INSERT INTO role(code) VALUES ('OTHER')"))
|
||||
|
||||
|
||||
def test_constraints_and_real_cascade(auth_db):
|
||||
migrate("head")
|
||||
engine = get_auth_engine()
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("INSERT INTO user(username,password_hash) VALUES ('test.user','fictitious')"))
|
||||
user_id = connection.execute(text("SELECT id FROM user WHERE username='test.user'")).scalar_one()
|
||||
connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (:id,'CAMA')"), {"id": user_id})
|
||||
with pytest.raises(IntegrityError):
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("INSERT INTO user(username,password_hash) VALUES ('test.user','fictitious')"))
|
||||
for bad_name in ("AB", "Bad", "bad!", "x" * 65):
|
||||
with pytest.raises(IntegrityError):
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("INSERT INTO user(username,password_hash) VALUES (:name,'fictitious')"), {"name": bad_name})
|
||||
with pytest.raises(IntegrityError):
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (:id,'CAMA')"), {"id": user_id})
|
||||
with pytest.raises(IntegrityError):
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (999999,'CAMA')"))
|
||||
with pytest.raises(IntegrityError):
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (:id,'MISSING')"), {"id": user_id})
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("DELETE FROM user WHERE id=:id"), {"id": user_id})
|
||||
assert connection.execute(text("SELECT count(*) FROM user_role WHERE user_id=:id"), {"id": user_id}).scalar_one() == 0
|
||||
|
||||
|
||||
def test_repository_reads_users_and_ordered_roles(auth_db):
|
||||
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
|
||||
|
||||
migrate("head")
|
||||
with get_auth_engine().begin() as connection:
|
||||
connection.execute(text("INSERT INTO user(username,password_hash) VALUES ('sample.user','fictitious')"))
|
||||
user_id = connection.execute(text("SELECT id FROM user WHERE username='sample.user'")).scalar_one()
|
||||
connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (:id,'TEA'),(:id,'CACU')"), {"id": user_id})
|
||||
assert get_user_by_username("sample.user").id == user_id
|
||||
assert get_user_by_username("absent") is None
|
||||
assert get_user_with_roles_by_id(user_id)[1] == ["CACU", "TEA"]
|
||||
assert get_user_with_roles_by_id(999999) is None
|
||||
with get_auth_engine().begin() as connection:
|
||||
connection.execute(text("DELETE FROM user_role WHERE user_id=:id AND role_code='TEA'"), {"id": user_id})
|
||||
assert get_user_with_roles_by_id(user_id)[1] == ["CACU"]
|
||||
|
||||
|
||||
def test_upgrade_downgrade_upgrade(auth_db):
|
||||
migrate("head")
|
||||
assert set(inspect(get_auth_engine()).get_table_names()) == {"user", "role", "user_role", "alembic_version"}
|
||||
command.downgrade(Config(str(ALEMBIC_INI)), "base")
|
||||
assert not {"user", "role", "user_role"} & set(inspect(get_auth_engine()).get_table_names())
|
||||
migrate("head")
|
||||
with get_auth_engine().connect() as connection:
|
||||
assert roles(connection) == ROLES
|
||||
+1
-1
Submodule WebApi updated: c1444e2b8d...f56265fdd7
+1
-1
Submodule WebApp updated: 3605d23fc0...a370f307b5
@@ -7,6 +7,11 @@ services:
|
||||
- "5000:5000"
|
||||
volumes:
|
||||
- webapi_data:/data
|
||||
environment:
|
||||
# Default only when absent; an explicit empty flag must be rejected.
|
||||
AUTH_LITE_ENABLED: ${AUTH_LITE_ENABLED-false}
|
||||
AUTH_LITE_SEED_DEMO_USERS: ${AUTH_LITE_SEED_DEMO_USERS-false}
|
||||
AUTH_LITE_SECRET_KEY: ${AUTH_LITE_SECRET_KEY:-}
|
||||
|
||||
webapp:
|
||||
build:
|
||||
|
||||
Reference in New Issue
Block a user