264 lines
11 KiB
Python
264 lines
11 KiB
Python
# #region Test.ScenarioEditor.Routes [C:3] [TYPE Module] [SEMANTICS test,scenario,editor,api,rbac,agent-propose]
|
|
# @defgroup ScenarioEditor Agent-propose + proposal-save route tests with RBAC scenario:edit enforcement (T016).
|
|
# @LAYER Test
|
|
# @RELATION VERIFIES -> [Api.DashboardTesting.Scenarios.EditorAgentPropose]
|
|
# @RELATION VERIFIES -> [Api.DashboardTesting.Scenarios.EditorProposalSave]
|
|
# @TEST_EDGE: edit_denied->403; run_only->403; admin_save->201/200; digest_conflict->409
|
|
# @TEST_INVARIANT: No_arbitrary_agent_save_bypass -> verified by digest + stale-base route tests
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
import json
|
|
from pathlib import Path
|
|
import pytest
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.pool import StaticPool
|
|
|
|
from src.api.routes.dashboard_testing.scenarios import router
|
|
from src.core.database import get_db
|
|
from src.dependencies import get_current_user
|
|
from src.models.auth import Permission, Role, User
|
|
from src.models.scenario_registry import ScenarioRegistryEntry, ScenarioRevision
|
|
from tests.admitted_metric_fixture import literal_graph
|
|
from tests.services.dashboard_testing.registry.editor_canonical_base import canonicalize_base_graph
|
|
|
|
_FIXTURE_PATH = (
|
|
Path(__file__).resolve().parents[1] / "fixtures" / "scenario_registry" / "registry.json"
|
|
)
|
|
|
|
_SCENARIO_ID = "11111111-1111-4111-8111-111111111111"
|
|
_BASE_REVISION_ID = "22222222-2222-4222-8222-222222222222"
|
|
# Structural graph for editor/RBAC tests only, not a publication or execution grant.
|
|
_CURRENT_GRAPH = literal_graph()
|
|
|
|
|
|
def _parse_ts(value: str | None) -> datetime | None:
|
|
if not value:
|
|
return None
|
|
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
|
|
|
|
def _seed_registry(session) -> None:
|
|
data = json.loads(_FIXTURE_PATH.read_text(encoding="utf-8"))
|
|
for row in data["entries"]:
|
|
session.add(ScenarioRegistryEntry(
|
|
scenario_id=row["scenario_id"],
|
|
scenario_key=row["scenario_key"],
|
|
name=row["name"],
|
|
description=row.get("description"),
|
|
dashboard_id=row["dashboard_id"],
|
|
environment_ids=row.get("environment_ids", []),
|
|
owner_id=row["owner_id"],
|
|
owner_username=row["owner_username"],
|
|
tags=row.get("tags", []),
|
|
metadata_version=row["metadata_version"],
|
|
current_revision_id=row.get("current_revision_id"),
|
|
lifecycle_status=row["lifecycle_status"],
|
|
validation_status=row["validation_status"],
|
|
last_run_id=row.get("last_run_id"),
|
|
last_successful_run_id=row.get("last_successful_run_id"),
|
|
health=row.get("health", "none"),
|
|
baseline_compatibility=row.get("baseline_compatibility"),
|
|
last_modified_at=_parse_ts(row["last_modified_at"]),
|
|
created_at=_parse_ts(row["created_at"]),
|
|
))
|
|
for row in data["revisions"]:
|
|
session.add(ScenarioRevision(
|
|
revision_id=row["revision_id"],
|
|
scenario_id=row["scenario_id"],
|
|
content_hash=row["content_hash"],
|
|
parent_revision_id=row.get("parent_revision_id"),
|
|
graph_snapshot=row.get("graph_snapshot", {}),
|
|
execution_template_hash=row.get("execution_template_hash", ""),
|
|
template_version=row.get("template_version", "v1"),
|
|
schema_version=row.get("schema_version", 1),
|
|
compatibility_family=row.get("compatibility_family", "default"),
|
|
change_summary=row.get("change_summary", {}),
|
|
created_by=row["created_by"],
|
|
created_at=_parse_ts(row["created_at"]),
|
|
activation_status=row["activation_status"],
|
|
activated_by=row.get("activated_by"),
|
|
activated_at=_parse_ts(row.get("activated_at")),
|
|
activation_agent_action_id=row.get("activation_agent_action_id"),
|
|
))
|
|
canonicalize_base_graph(session, current_graph=_CURRENT_GRAPH.scenario)
|
|
session.commit()
|
|
|
|
|
|
# #region Test.ScenarioEditor.Routes.EditorRouteEnv [C:2] [TYPE Class]
|
|
# @BRIEF Isolated in-memory SQLite app with permission-scoped current-user overrides.
|
|
class EditorRouteEnv:
|
|
def __init__(self):
|
|
self.engine = create_engine(
|
|
"sqlite:///:memory:",
|
|
poolclass=StaticPool,
|
|
connect_args={"check_same_thread": False},
|
|
)
|
|
event.listen(self.engine, "connect", lambda c, _: c.execute("PRAGMA foreign_keys=ON"))
|
|
from src.models.mapping import Base
|
|
|
|
Base.metadata.create_all(self.engine)
|
|
self.session_factory = sessionmaker(bind=self.engine)
|
|
|
|
def seed(self) -> None:
|
|
session = self.session_factory()
|
|
try:
|
|
_seed_registry(session)
|
|
finally:
|
|
session.close()
|
|
|
|
def client(self, permissions: list[tuple[str, str]] | None = None, *, admin: bool = False) -> TestClient:
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
|
|
def _override_db():
|
|
session = self.session_factory()
|
|
try:
|
|
yield session
|
|
finally:
|
|
session.close()
|
|
|
|
if admin:
|
|
role = Role(id="admin-role-editor-routes", name="Admin", is_admin=True)
|
|
user = User(id="admin-user-editor-routes", username="admin", email="admin@test.com")
|
|
else:
|
|
role = Role(id=f"role-{len(permissions or [])}", name="Scoped", is_admin=False)
|
|
role.permissions = [
|
|
Permission(id=f"perm-{resource}-{action}", resource=resource, action=action)
|
|
for resource, action in (permissions or [])
|
|
]
|
|
user = User(id="scoped-user-editor-routes", username="scoped", email="scoped@test.com")
|
|
user.roles = [role]
|
|
app.dependency_overrides[get_current_user] = lambda: user
|
|
app.dependency_overrides[get_db] = _override_db
|
|
return TestClient(app)
|
|
|
|
def close(self) -> None:
|
|
self.engine.dispose()
|
|
# #endregion Test.ScenarioEditor.Routes.EditorRouteEnv
|
|
|
|
|
|
@pytest.fixture
|
|
def editor_route_env():
|
|
env = EditorRouteEnv()
|
|
yield env
|
|
env.close()
|
|
|
|
|
|
def _propose_payload():
|
|
return {
|
|
"base_revision_id": _BASE_REVISION_ID,
|
|
"request_text": "add XLSX comparison",
|
|
"ops": [{
|
|
"op": "set_assertion",
|
|
"logical_step_id": _CURRENT_GRAPH.binding.comparison_step_id,
|
|
"comparison": "chart_response",
|
|
"baseline_ref": f"baseline:{_CURRENT_GRAPH.selection.baseline_id}",
|
|
}],
|
|
"agent_action_id": "agent-action-1",
|
|
}
|
|
|
|
|
|
# #region Test.ScenarioEditor.Routes.TestAgentProposeRoutes [C:2] [TYPE Class]
|
|
class TestAgentProposeRoutes:
|
|
"""POST /api/dashboard-testing/scenarios/{id}/edits/agent-propose — RBAC + validation."""
|
|
|
|
def test_agent_propose_happy_path(self, editor_route_env):
|
|
editor_route_env.seed()
|
|
resp = editor_route_env.client(permissions=[("scenario", "EDIT")]).post(
|
|
f"/api/dashboard-testing/scenarios/{_SCENARIO_ID}/edits/agent-propose",
|
|
json=_propose_payload(),
|
|
)
|
|
assert resp.status_code == 200, resp.text
|
|
body = resp.json()
|
|
assert body["proposal_id"]
|
|
assert body["digest"] and len(body["digest"]) == 64
|
|
assert body["status"] == "open"
|
|
|
|
def test_agent_propose_denied_without_scenario_edit(self, editor_route_env):
|
|
editor_route_env.seed()
|
|
resp = editor_route_env.client(permissions=[]).post(
|
|
f"/api/dashboard-testing/scenarios/{_SCENARIO_ID}/edits/agent-propose",
|
|
json=_propose_payload(),
|
|
)
|
|
assert resp.status_code == 403
|
|
|
|
def test_agent_propose_denied_for_run_only_user(self, editor_route_env):
|
|
editor_route_env.seed()
|
|
resp = editor_route_env.client(permissions=[("scenario", "RUN")]).post(
|
|
f"/api/dashboard-testing/scenarios/{_SCENARIO_ID}/edits/agent-propose",
|
|
json=_propose_payload(),
|
|
)
|
|
assert resp.status_code == 403
|
|
|
|
def test_agent_propose_rejects_unsafe_ops(self, editor_route_env):
|
|
editor_route_env.seed()
|
|
payload = _propose_payload()
|
|
payload["ops"] = [{
|
|
"op": "set_assertion",
|
|
"logical_step_id": "step-1",
|
|
"comparison": "chart_response",
|
|
"baseline_ref": "baseline:SELECT * FROM users",
|
|
}]
|
|
resp = editor_route_env.client(permissions=[("scenario", "EDIT")]).post(
|
|
f"/api/dashboard-testing/scenarios/{_SCENARIO_ID}/edits/agent-propose",
|
|
json=payload,
|
|
)
|
|
assert resp.status_code == 422
|
|
assert resp.json()["detail"]["code"] == "INVALID_EDIT"
|
|
# #endregion Test.ScenarioEditor.Routes.TestAgentProposeRoutes
|
|
|
|
|
|
# #region Test.ScenarioEditor.Routes.TestProposalSaveRoutes [C:2] [TYPE Class]
|
|
class TestProposalSaveRoutes:
|
|
"""POST /api/dashboard-testing/scenarios/{id}/edits/proposals/{proposal_id}/save — guarded save."""
|
|
|
|
def _create_proposal(self, client):
|
|
resp = client.post(
|
|
f"/api/dashboard-testing/scenarios/{_SCENARIO_ID}/edits/agent-propose",
|
|
json=_propose_payload(),
|
|
)
|
|
assert resp.status_code == 200
|
|
return resp.json()
|
|
|
|
def test_proposal_save_creates_attributed_revision(self, editor_route_env):
|
|
editor_route_env.seed()
|
|
client = editor_route_env.client(permissions=[("scenario", "EDIT")])
|
|
proposal = self._create_proposal(client)
|
|
resp = client.post(
|
|
f"/api/dashboard-testing/scenarios/{_SCENARIO_ID}/edits/proposals/{proposal['proposal_id']}/save",
|
|
json={"digest": proposal["digest"], "agent_action_id": "agent-action-1"},
|
|
)
|
|
assert resp.status_code == 200, resp.text
|
|
body = resp.json()
|
|
assert body["activation_status"] == "candidate"
|
|
assert body["parent_revision_id"] == _BASE_REVISION_ID
|
|
|
|
def test_proposal_save_denied_without_scenario_edit(self, editor_route_env):
|
|
editor_route_env.seed()
|
|
client = editor_route_env.client(permissions=[("scenario", "EDIT")])
|
|
proposal = self._create_proposal(client)
|
|
denied = editor_route_env.client(permissions=[])
|
|
resp = denied.post(
|
|
f"/api/dashboard-testing/scenarios/{_SCENARIO_ID}/edits/proposals/{proposal['proposal_id']}/save",
|
|
json={"digest": proposal["digest"]},
|
|
)
|
|
assert resp.status_code == 403
|
|
|
|
def test_proposal_save_digest_mismatch_conflicts(self, editor_route_env):
|
|
editor_route_env.seed()
|
|
client = editor_route_env.client(permissions=[("scenario", "EDIT")])
|
|
proposal = self._create_proposal(client)
|
|
resp = client.post(
|
|
f"/api/dashboard-testing/scenarios/{_SCENARIO_ID}/edits/proposals/{proposal['proposal_id']}/save",
|
|
json={"digest": "0" * 64},
|
|
)
|
|
assert resp.status_code == 409
|
|
assert resp.json()["detail"]["code"] == "EDITOR_SAVE_CONFLICT"
|
|
# #endregion Test.ScenarioEditor.Routes.TestProposalSaveRoutes
|
|
# #endregion Test.ScenarioEditor.Routes
|