import pytest import aiosqlite from app.db import MIGRATIONS_DIR from app.rbac import user_has_role, user_has_role_for_host async def _fresh_db() -> aiosqlite.Connection: conn = await aiosqlite.connect(":memory:") for migration_file in sorted(MIGRATIONS_DIR.glob("*.sql")): await conn.executescript(migration_file.read_text(encoding="utf-8")) return conn @pytest.mark.asyncio async def test_rbac_grants_and_expiry(): conn = await _fresh_db() await conn.execute("INSERT INTO users (id, username, password_hash) VALUES (1, 'alice', 'x')") await conn.execute("INSERT INTO host_groups (id, name) VALUES (1, 'linux-prod')") await conn.execute( "INSERT INTO hosts (id, host_group_id, hostname, address, protocol, port, os_type) " "VALUES (1, 1, 'db01', '10.0.0.1', 'ssh', 22, 'linux')" ) assert not await user_has_role(conn, user_id=1, host_group_id=1, role_name="ssh_connect") await conn.execute( "INSERT INTO user_hostgroup_roles (user_id, host_group_id, role_id) VALUES (1, 1, 1)" ) await conn.commit() assert await user_has_role(conn, user_id=1, host_group_id=1, role_name="ssh_connect") assert await user_has_role_for_host(conn, user_id=1, host_id=1, role_name="ssh_connect") assert not await user_has_role_for_host(conn, user_id=1, host_id=1, role_name="rdp_connect") # Abgelaufene Freigabe darf nicht mehr gelten. await conn.execute( "UPDATE user_hostgroup_roles SET expires_at = '2000-01-01T00:00:00.000000Z' " "WHERE user_id = 1 AND host_group_id = 1 AND role_id = 1" ) await conn.commit() assert not await user_has_role(conn, user_id=1, host_group_id=1, role_name="ssh_connect") await conn.close()