Coverage for app / services / rules / references.py: 93%
42 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Resources a rule's actions name by id — checked when the rule is written.
4An action parameter declares the kind of resource it names
5(``ActionParam.resource``), and this is where each kind resolves: one entry
6per kind, not a branch per action. The check is the one a pinned scope gets
7(``rules.router._verify_scope``): an id that resolves to nothing, or to
8something the author may not read, would make a rule that looks active and
9never does what it says — so it is refused before the row exists, and a
10generated rule naming one is dropped whole.
11"""
13from __future__ import annotations
15from typing import Any
16from uuid import UUID
18from fastapi import HTTPException
19from sqlalchemy.orm import Session
21from app.db.postgres.enums import RuleEnum
22from app.db.postgres.models import TestSuite
23from app.dependency.resource_access import verify_resource_read
24from app.services.rules import actions as action_registry
26#: Resource kind → its model. Readability is ``verify_resource_read``: a
27#: gold dataset is platform-managed and every user may name it.
28RESOURCE_MODELS: dict[str, type] = {"dataset": TestSuite}
31def _readable(db: Session, user: Any, model: type, raw: Any) -> bool:
32 try:
33 row = db.get(model, UUID(str(raw)))
34 except (TypeError, ValueError):
35 return False
36 if row is None:
37 return False
38 try:
39 verify_resource_read(row, user, db)
40 except HTTPException:
41 return False
42 return True
45def unresolved(
46 db: Session,
47 user: Any,
48 layer: RuleEnum.Layer | str,
49 blocks: list[dict] | None,
50) -> list[str]:
51 """Why each resource id the action blocks name cannot be used — empty
52 when every one resolves to something the author may read."""
53 try:
54 kind = RuleEnum.Layer(layer)
55 except ValueError:
56 return []
57 problems: list[str] = []
58 for block in blocks or []:
59 if not isinstance(block, dict):
60 continue
61 action = action_registry.get_action(kind, str(block.get("type", "")))
62 if action is None:
63 continue
64 for param in action.params:
65 raw = block.get(param.key)
66 if not param.resource or raw in (None, ""):
67 continue
68 model = RESOURCE_MODELS.get(param.resource)
69 if model is None or not _readable(db, user, model, raw):
70 problems.append(
71 f"No {param.resource} found for “{action.label}” → {param.label}"
72 )
73 return problems