Задачи 032-033: ролевая модель с привязкой к организации, исправления по ревью
Пентест (docs/reviews/2026-09-27-pentest.md) и план 031 (Swagger, TLS) — план, не реализован.
032 Роль superadmin (без организации) и привязка admin/viewer к одной организации:
users.organization_id + CHECK, audit_log.organization_id (миграции 0010-0012);
require_org/scope_org во всех чтениях и записях, журнал и «Обзор» в границах
организации; пользователи, организации, типы устройств, настройки журнала — только superadmin.
033 Исправление находок ревью 032 (docs/reviews/2026-09-27-changes-032-review.md,
docs/reviews/2026-09-27-codebase-review.md):
- FK audit_log.organization_id ON DELETE SET NULL (миграция 0013) — удаление организаций;
- проверка организации в предпросмотре подсети;
- инвариант «роль — организация» по итоговому состоянию (повышение снимает организацию,
понижение требует её), 422/404 вместо обезличенных 409;
- одинаковый 404 для чужих и несуществующих объектов (VRF, устройство, parent_id, оператор);
- отказы удаления в журнале организации, счётчики типов в пределах организации;
- UI: живое поле «Организация» в диалоге пользователя, бейдж superadmin; род в текстах 404.
README актуализирован под ролевую модель.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5210ba3333
commit
744a025960
28 files changed
+1283
-164
No files matched your search
@@ -1,4 +1,6 @@
|
||||
import ipaddress
|
||||
import uuid
|
||||
|
||||
import httpx
|
||||
|
||||
from tests.conftest import BASE, ENV
|
||||
@@ -45,6 +47,22 @@ def test_in_use_objects_cannot_be_deleted(client, org):
|
||||
client.post("/devices", json={"name": "t-1.internal", "device_type_id": t["id"], "organization_id": org["id"]})
|
||||
assert client.delete(f"/device-types/{t['id']}").status_code == 409
|
||||
|
||||
# изменение 033, находка №4: отказ в удалении VRF попадает в журнал с organization_id и виден админу этой организации
|
||||
name, uid, admin = f"qa-{uuid.uuid4().hex[:8]}", None, None
|
||||
try:
|
||||
created = client.post("/users", json={"username": name, "password": "start-pass-123", "role": "admin", "organization_id": org["id"]})
|
||||
assert created.status_code == 201, created.text
|
||||
uid = created.json()["id"]
|
||||
admin = httpx.Client(base_url=BASE, timeout=30)
|
||||
r = admin.post("/auth/login", json={"username": name, "password": "start-pass-123"})
|
||||
admin.headers["Authorization"] = "Bearer " + r.json()["access_token"]
|
||||
assert admin.get("/audit", params={"event_type": "vrf.delete_blocked"}).json()["total"] >= 1
|
||||
finally:
|
||||
if admin is not None:
|
||||
admin.close()
|
||||
if uid is not None:
|
||||
client.delete(f"/users/{uid}")
|
||||
|
||||
|
||||
def test_delete_organization(client, org):
|
||||
_prefix(client, org, "10.206.0.0/24")
|
||||
@@ -77,6 +95,41 @@ def test_allocate_next_subnet(client, org):
|
||||
assert next_free_subnet("fd00::/64", 66, [(v6, v6 + 5)]) == "fd00::4000:0:0:0/66" # IPv6: первый блок занят, берётся второй
|
||||
|
||||
|
||||
def test_prefix_isolation_between_organizations(client, org):
|
||||
"""Изменение 033, находка №9: чужой организации не должен быть виден чужой префикс ни через GET, ни через предпросмотр подсети.
|
||||
Находка №11: admin чужой организации получает тот же 404 при попытке создать префикс в VRF организации A."""
|
||||
other = client.post("/organizations", json={"name": f"other-{org['name']}", "inn": "".join(reversed(org["inn"]))}).json()
|
||||
pid = _prefix(client, org, "10.208.0.0/24").json()["id"]
|
||||
name, uid, admin_b = f"qa-{uuid.uuid4().hex[:8]}", None, None
|
||||
try:
|
||||
created = client.post("/users", json={"username": name, "password": "start-pass-123", "role": "admin", "organization_id": other["id"]})
|
||||
assert created.status_code == 201, created.text
|
||||
uid = created.json()["id"]
|
||||
|
||||
admin_b = httpx.Client(base_url=BASE, timeout=30)
|
||||
r = admin_b.post("/auth/login", json={"username": name, "password": "start-pass-123"})
|
||||
assert r.status_code == 200
|
||||
admin_b.headers["Authorization"] = "Bearer " + r.json()["access_token"]
|
||||
|
||||
assert admin_b.get(f"/prefixes/{pid}").status_code == 404
|
||||
assert admin_b.get(f"/prefixes/{pid}/subnets/next", params={"length": 24}).status_code == 404
|
||||
# изменение 033, находка №11: чужой VRF в create_prefix — 404 (раньше было 422)
|
||||
cross = admin_b.post("/prefixes", json={"organization_id": other["id"], "vrf_id": org["vrf_id"], "prefix": "10.209.0.0/24"})
|
||||
assert cross.status_code == 404
|
||||
# изменение 033, находка №11: чужой parent_id в create_prefix — тоже 404 (раньше было 422)
|
||||
other_vrf_id = client.get("/vrfs", params={"organization_id": other["id"]}).json()["items"][0]["id"]
|
||||
cross_parent = admin_b.post("/prefixes", json={"organization_id": other["id"], "vrf_id": other_vrf_id, "prefix": "10.208.0.0/25", "parent_id": pid})
|
||||
assert cross_parent.status_code == 404
|
||||
finally:
|
||||
if admin_b is not None:
|
||||
admin_b.close()
|
||||
if uid is not None:
|
||||
client.delete(f"/users/{uid}")
|
||||
for v in client.get("/vrfs", params={"organization_id": other["id"]}).json()["items"]:
|
||||
client.delete(f"/vrfs/{v['id']}")
|
||||
client.delete(f"/organizations/{other['id']}")
|
||||
|
||||
|
||||
def test_vrf_name_unique_per_organization(client, org):
|
||||
other = client.post("/organizations", json={"name": f"other-{org['name']}", "inn": "".join(reversed(org["inn"]))}).json()
|
||||
try:
|
||||
|
||||
@@ -40,7 +40,7 @@ def test_rotation_by_age_and_count(client, db):
|
||||
|
||||
def test_clear_requires_password_and_locks_out(db):
|
||||
name, pw = f"tmp-{uuid.uuid4().hex[:6]}", "tmp-pass-123"
|
||||
db.execute("INSERT INTO users (username, password_hash, role, is_active) VALUES (%s, %s, 'admin', true)", (name, hash_password(pw)))
|
||||
db.execute("INSERT INTO users (username, password_hash, role, is_active) VALUES (%s, %s, 'superadmin', true)", (name, hash_password(pw))) # изменение 033: очистка журнала — только superadmin
|
||||
try:
|
||||
c = httpx.Client(base_url=BASE)
|
||||
c.headers["Authorization"] = "Bearer " + c.post("/auth/login", json={"username": name, "password": pw}).json()["access_token"]
|
||||
|
||||
+14
-4
@@ -17,23 +17,25 @@ def _client(username: str, password: str):
|
||||
return c
|
||||
|
||||
|
||||
def test_users_management(client):
|
||||
def test_users_management(client, org):
|
||||
name, uid, other = f"qa-{uuid.uuid4().hex[:8]}", None, None
|
||||
try:
|
||||
created = client.post("/users", json={"username": name, "password": "start-pass-123", "role": "viewer"})
|
||||
created = client.post("/users", json={"username": name, "password": "start-pass-123", "role": "viewer", "organization_id": org["id"]}) # изменение 033
|
||||
assert created.status_code == 201, created.text
|
||||
uid = created.json()["id"]
|
||||
assert created.json()["role"] == "viewer" and created.json()["is_active"] is True
|
||||
assert created.json()["organization_id"] == org["id"] # изменение 033
|
||||
|
||||
assert client.post("/users", json={"username": name.upper(), "password": "start-pass-123"}).status_code == 409 # логин занят без учёта регистра
|
||||
assert client.post("/users", json={"username": name.upper(), "password": "start-pass-123", "organization_id": org["id"]}).status_code == 409 # логин занят без учёта регистра
|
||||
assert client.post("/users", json={"username": "system", "password": "start-pass-123"}).status_code == 422 # служебный логин журнала
|
||||
assert client.post("/users", json={"username": "ab", "password": "start-pass-123"}).status_code == 422 # короткий логин
|
||||
assert client.post("/users", json={"username": "short-pw", "password": "123"}).status_code == 422 # короткий пароль
|
||||
assert client.post("/users", json={"username": f"qa-{uuid.uuid4().hex[:8]}", "password": "start-pass-123", "role": "admin"}).status_code == 422 # админ без организации (изменение 033, находка №2)
|
||||
|
||||
other = _client(name, "start-pass-123")
|
||||
assert other is not None
|
||||
assert other.get("/auth/me").json()["role"] == "viewer"
|
||||
assert other.get("/users").status_code == 403 # список пользователей только для админа
|
||||
assert other.get("/users").status_code == 403 # список пользователей только для суперадминистратора (изменение 032)
|
||||
assert other.post("/organizations", json={"name": "qa", "inn": "1234567890"}).status_code == 403 # роль «просмотр» — только чтение
|
||||
|
||||
# отключение действует немедленно, включая ранее выданный токен
|
||||
@@ -62,6 +64,14 @@ def test_users_management(client):
|
||||
assert client.delete(f"/users/{me['id']}").status_code == 409
|
||||
assert client.patch(f"/users/{me['id']}", json={"is_active": False}).status_code == 409
|
||||
assert client.patch(f"/users/{uid}", json={"role": "admin"}).json()["role"] == "admin"
|
||||
|
||||
# реконсиляция «роль — организация» по итоговому состоянию (изменение 033, находка №3)
|
||||
promoted = client.patch(f"/users/{uid}", json={"role": "superadmin"})
|
||||
assert promoted.status_code == 200 and promoted.json()["organization_id"] is None # повышение снимает организацию само
|
||||
assert client.patch(f"/users/{uid}", json={"role": "viewer"}).status_code == 422 # понижение без организации
|
||||
demoted = client.patch(f"/users/{uid}", json={"role": "viewer", "organization_id": org["id"]})
|
||||
assert demoted.status_code == 200 and demoted.json()["role"] == "viewer"
|
||||
|
||||
assert client.delete(f"/users/{uid}").status_code == 204
|
||||
uid = None
|
||||
assert client.get("/audit", params={"event_type": "user.created"}).json()["total"] >= 1
|
||||
|
||||
Reference in new issue
Block a user