test(maintenance): preserve union permission denial and no effects

This commit is contained in:
2026-10-11 22:34:54 +03:00
parent 84a4a62e6f
commit f343bcbc3b
4 changed files with 51 additions and 15 deletions

View File

@@ -1,10 +1,10 @@
# #region Test.Maintenance.Routes.Rbac [C:3] [TYPE Module] [SEMANTICS test,maintenance,rbac,routes]
# @BRIEF RBAC denied-path tests for every Maintenance Banner endpoint: the real has_permission()
# and require_api_key_or_jwt() closures (never mocked) must return 403 for an authenticated user
# @BRIEF RBAC denied-path tests for every Maintenance Banner endpoint: the real has_permission(),
# has_any_permission() and require_api_key_or_jwt() closures (never mocked) return 403 for an authenticated user
# lacking the FR-015 permission and 401 when no credentials are presented. Closes the QA-found
# gap that all existing maintenance route tests run only under permission-bypassing fixtures.
# @RELATION BINDS_TO -> [Api.Routes.MaintenanceRoutesModule]
# @TEST_CONTRACT: authenticated user without FR-015 permission -> 403 "Permission denied for <resource>:<action>"
# @TEST_CONTRACT: missing single grants -> named 403; missing both settings WRITE grants -> generic 403 plus exact any_of audit
# @TEST_CONTRACT: request without JWT/API-key credentials -> 401
# @TEST_EDGE: rbac_denied -> every maintenance endpoint returns 403 for a user lacking the FR-015 permission (and 401 unauthenticated where applicable)
# @TEST_FIXTURE: _PREVIEW_BODY -> INLINE_JSON
@@ -23,6 +23,7 @@ from fastapi.testclient import TestClient
from src.api.routes.maintenance._router import router as _maintenance_router
from src.core.auth.jwt import create_access_token
from src.core.auth.logger import log_security_event
from src.dependencies import (
get_auth_db,
get_config_manager,
@@ -60,7 +61,6 @@ _CONTROL_TASK_ID = "task-rbac-control"
# src/api/routes/maintenance/_routes_*.py handler modules (denial origin must be identifiable).
_DETAIL_MAINT_READ = "Permission denied for maintenance:READ"
_DETAIL_MAINT_WRITE = "Permission denied for maintenance:WRITE"
_DETAIL_ADMIN_SETTINGS_WRITE = "Permission denied for admin:settings:WRITE"
# #region Test.Maintenance.Routes.Rbac.ConstOverride [C:1] [TYPE Function]
@@ -245,13 +245,21 @@ class TestSessionUserRbac:
# #endregion Test.Maintenance.Routes.Rbac.SettingsReadDenied
# #region Test.Maintenance.Routes.Rbac.SettingsWriteDenied [C:2] [TYPE Function]
# @BRIEF PUT /api/maintenance/settings denies without the SEPARATE admin:settings:WRITE
# permission -> 403 (FR-015: admin only, distinct from maintenance:READ).
# @BRIEF Settings WRITE requires maintenance:settings WRITE OR admin:settings WRITE;
# lacking both returns the union guard's generic 403 before settings I/O.
def test_put_settings_denied_403(self) -> None:
client = _session_user_client(scenario_routes_no_perm_user())
resp = client.put("/api/maintenance/settings", json=_SETTINGS_BODY)
user = scenario_routes_no_perm_user()
assert user.roles == []
db = MagicMock()
client = _session_user_client(user, db=db)
with patch("src.core.auth.logger.log_security_event", wraps=log_security_event) as audit:
resp = client.put("/api/maintenance/settings", json=_SETTINGS_BODY)
assert resp.status_code == 403
assert resp.json()["detail"] == _DETAIL_ADMIN_SETTINGS_WRITE
assert resp.json()["detail"] == "Permission denied"
audit.assert_called_once_with("PERMISSION_DENIED", "u1", {
"any_of": ["admin:settings:WRITE", "maintenance:settings:WRITE"],
})
assert db.mock_calls == []
# #endregion Test.Maintenance.Routes.Rbac.SettingsWriteDenied
# #region Test.Maintenance.Routes.Rbac.ControlAdminRead [C:2] [TYPE Function]

View File

@@ -1,14 +1,16 @@
# #region Test.Maintenance.TemplatesRoutes [C:3] [TYPE Module] [SEMANTICS test,maintenance,template,routes,rbac]
# @BRIEF Contract tests for the maintenance template library endpoints: RBAC gates
# (maintenance:template READ/WRITE, admin:settings for default) and the CRUD/soft-archive
# (maintenance:template READ/WRITE, maintenance:settings OR admin:settings WRITE for default) and the CRUD/soft-archive
# lifecycle with the single-default invariant.
# @RELATION BINDS_TO -> [Api.Routes.MaintenanceTemplatesModule]
# @TEST_CONTRACT: template read requires maintenance:template READ -> 403 without it
# @TEST_CONTRACT: template write requires maintenance:template WRITE -> 403 without it
# @TEST_CONTRACT: setting a default requires admin:settings WRITE -> 403 for a template-only role
# @TEST_CONTRACT: default requires maintenance:settings OR admin:settings WRITE -> 403 for a template-only role
# @TEST_CONTRACT: archiving the default template is rejected -> 409
# @TEST_INVARIANT Api.Routes.MaintenanceTemplatesModule."default is never set by a template-only role" -> VERIFIED_BY: [test_set_default_requires_admin]
from types import SimpleNamespace
from copy import deepcopy
from unittest.mock import patch
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@@ -19,7 +21,9 @@ from fastapi.testclient import TestClient
from src.api.routes.maintenance._router import router as _maintenance_router
from src.dependencies import get_current_user, get_db
from src.core.auth.logger import log_security_event
from src.models.mapping import Base
from src.models.maintenance import MaintenanceTemplate
def _user(*pairs: tuple[str, str], is_admin: bool = False) -> SimpleNamespace:
@@ -75,7 +79,14 @@ def test_create_template_requires_template_write():
def test_set_default_requires_admin():
client = _client(_user(_TPL_READ, _TPL_WRITE))
from src.api.routes.maintenance import _routes_templates
user = _user(_TPL_READ, _TPL_WRITE)
assert {(p.resource, p.action) for role in user.roles for p in role.permissions}.isdisjoint({
("maintenance:settings", "WRITE"), _ADMIN_SETTINGS,
})
assert all(not role.is_admin for role in user.roles)
client = _client(user)
created = client.post(
"/api/maintenance/templates",
json={"name": "T1", "html": "<div>{message}</div>"},
@@ -83,9 +94,22 @@ def test_set_default_requires_admin():
assert created.status_code == 201
template_id = created.json()["id"]
denied = client.put(f"/api/maintenance/templates/{template_id}/default")
db = client.app.state.db
before = deepcopy(db.query(*MaintenanceTemplate.__table__.columns).all())
with (
patch("src.core.auth.logger.log_security_event", wraps=log_security_event) as audit,
patch.object(_routes_templates, "set_default_template", wraps=_routes_templates.set_default_template) as operation,
patch.object(db, "commit", wraps=db.commit) as commit,
):
denied = client.put(f"/api/maintenance/templates/{template_id}/default")
assert denied.status_code == 403
assert "admin:settings:WRITE" in denied.json()["detail"]
assert denied.json()["detail"] == "Permission denied"
audit.assert_called_once_with("PERMISSION_DENIED", "tpl-user", {
"any_of": ["admin:settings:WRITE", "maintenance:settings:WRITE"],
})
operation.assert_not_called()
commit.assert_not_called()
assert db.query(*MaintenanceTemplate.__table__.columns).all() == before
allowed = _client(_user(_TPL_READ, _TPL_WRITE, _ADMIN_SETTINGS))
created2 = allowed.post(

View File

@@ -1379,3 +1379,7 @@ The six test owners retain all fourteen original identities. SDK probes delegate
ONE bounded run of exact14 + six live provenance controls + pure DSL unknown-op control passed21 nodes/all63 phases/private0, source/dependency hashes unchanged. Eight same-trace/same-operation terminal commit confirmations precede SDK refusal; six actual transform refusal events precede synthetic admission, and all six provenance controls reach their intended typed branches. Matching-session watcher closed normally and RR/RO full0039 pre/post health retained identical rows digest, one quota and zero leases/active/charged. Curate independently reviewed the retained source and actual receipts. Packet: artifacts/evidence-curation-20261011/sdk-transform-positive-current/causal-receipt.json. This is component SQL/savepoint/refusal/admission proof, not SDK execution, independent durability, fullbackend or347 acceptance.
Current owner26 property matrix is complete across the reviewed bounded cuts: SDK58/59/60/61/62/63/64/65/66/70/71/72/73/76/77/78 preserve explicit unsupported, terminal receipts and live identity/duplicate protections; transforms79/80/94/95/96/124/125/132/133 preserve unsupported plus pure DSL/current provenance/admission guards; mixed preview120 preserves metadata inspection/capture-required with no SDK numeric result. Existing live74/75 and126–131 remain separate, already targeted. No double credit for owner26 or rechecked controls: targeted130 + owner26 still leaves68 original cases/53 classes; N120 and mandatory final fullbackend/Ruff/347/chart8 proof remain open.
### 2026-10-11 — C14 keeps current union permission denial observable and without effects
The two old admin-only copy operands now assert the current generic403 from real has_any_permission: maintenance:settings WRITE OR admin:settings WRITE, as required by031. Exact real PERMISSION_DENIED audit asserts both sorted grants; settings DB receives no calls and the owned SQLite template rows/service/commit stay unchanged. Existing allowed admin201/200/default=True controls remain. ONE actual run of original27/28 passed all6 phases/private0 with source hashes unchanged; Curate verified both source files and all six artifacts in fixture-ports-20261011/maintenance-union-c14. Both audit records join exact HealthFixture traces. The matching-session watcher closed normally; existing PG import/RR/RO health retained full0039/same rows digest/one quota/zero leases-active-charged. This is real HTTP permission + Mock settings/SQLite business component evidence; PostgreSQL health is separate, with no durability/fullsuite claim. Targeted132 + owner26 leaves66 original cases/52 classes; N120/347 unchanged.

View File

@@ -34,7 +34,7 @@
Готовы PostgreSQL-каталог и миграции, целевые исправления и очистка evidence. Для всех 26 выведенных владельцем SDK/transform случаев активные проверки перенесены на текущий явный отказ; живые admission/receipt/ownership свойства сохранены отдельно. Проверки миграций повторять не нужно. Очистка и защита SOURCE-публикации проверены в границах отчёта ниже; это не продуктовый GO.
Последний полный backend на `94921069`: 14 690 узлов, 14 137 PASS, 210 call FAIL, 14 setup FAIL, 329 skips, exit 1; teardown прошёл. После 130 целевых успешных проверок и 26 решений владельца о границах мержа остаются 68 исходных случаев из 224 в 53 группах. Крупнейшая группа: C56 — 5. Эти результаты не заменяют свежий полный green.
Последний полный backend на `94921069`: 14 690 узлов, 14 137 PASS, 210 call FAIL, 14 setup FAIL, 329 skips, exit 1; teardown прошёл. После 132 целевых успешных проверок и 26 решений владельца о границах мержа остаются 66 исходных случаев из 224 в 52 группах. Крупнейшая группа: C56 — 5. Эти результаты не заменяют свежий полный green.
Открыты: оставшиеся причины; итоговые full backend и Ruff; автоматическое доказательство 347; API-цикл чарта 8 с тем же pin. C56 — живой блокер верификации: нет actual evidence/явного selector. PROD теперь отказывает до deployment plugin; это исправление порядка не даёт недостающих данных проверки и не относится к отложенному SDK. Причина исторических зависаний не установлена; текущие ограниченные повторения завершились нормально.