filament_scope.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. """Which filaments a caller may print with (#3522).
  2. Permissions answer *what* a caller may do and a printer scope *on which
  3. printers* (#1727); a filament scope answers *with which filaments*. It is
  4. checked when a job is queued (the file's filaments) and again by the scheduler
  5. before dispatch (the file's filaments and the AMS trays it maps them to), so a
  6. job created any other way -- webhook, pipeline, batch, virtual printer -- is
  7. held to it too.
  8. How a scope is derived, as for printers:
  9. * Auth disabled, no user, or an admin: every filament.
  10. * A user: each of their groups with ``restrict_filaments`` set is a policy, and
  11. a filament any of those policies allows is allowed. A user in no such group
  12. may use every filament, so installs that never configure this are unchanged.
  13. * A deleted or deactivated user: no policies, so nothing identifiable.
  14. A policy is an allow list or a block list (``filament_rule_mode``). A rule
  15. matches a material type ("PETG", case-insensitive, by name: "PETG" is not
  16. "PETG-CF", but the materials the tray matcher treats as one, such as PA-CF,
  17. PA12-CF and PAHT-CF, count as one here too) or a slicer filament id ("GFG03":
  18. the ``tray_info_idx`` an AMS tray reports and a 3MF records). A
  19. filament with neither a type nor an id can't be judged and is allowed: the
  20. scheduler only blocks dispatch on a positive finding.
  21. """
  22. from __future__ import annotations
  23. from collections.abc import Iterable, Mapping
  24. from dataclasses import dataclass
  25. from typing import Literal
  26. from fastapi import HTTPException, status
  27. from sqlalchemy import select
  28. from sqlalchemy.ext.asyncio import AsyncSession
  29. from backend.app.schemas.auth import FilamentPolicyBrief
  30. from backend.app.schemas.group import FilamentRuleSchema
  31. from backend.app.utils.filament_types import canonical_filament_type
  32. RuleMatch = Literal["material", "filament_id"]
  33. RuleMode = Literal["allow", "block"]
  34. RULE_MATCHES: tuple[str, ...] = ("material", "filament_id")
  35. RULE_MODES: tuple[str, ...] = ("allow", "block")
  36. def _norm(value: object) -> str:
  37. return str(value or "").strip().upper()
  38. @dataclass(frozen=True)
  39. class FilamentRule:
  40. match: RuleMatch
  41. value: str
  42. def matches(self, filament_type: str | None, filament_id: str | None) -> bool:
  43. wanted = _norm(self.value)
  44. if not wanted:
  45. return False
  46. if self.match == "material":
  47. # The tray matcher treats some materials as one (PA-CF, PA12-CF
  48. # and PAHT-CF, ``canonical_filament_type``); a rule naming one of
  49. # them names them all, or the matcher would map a job onto a
  50. # spool the rule meant to keep it from, or hold it off one the
  51. # rule allows.
  52. return canonical_filament_type(_norm(filament_type)) == canonical_filament_type(wanted)
  53. return _norm(filament_id) == wanted
  54. @dataclass(frozen=True)
  55. class GroupFilamentPolicy:
  56. group_name: str
  57. mode: RuleMode
  58. rules: tuple[FilamentRule, ...]
  59. def allows(self, filament_type: str | None, filament_id: str | None) -> bool:
  60. hit = any(rule.matches(filament_type, filament_id) for rule in self.rules)
  61. return hit if self.mode == "allow" else not hit
  62. @dataclass(frozen=True)
  63. class FilamentScope:
  64. """The filaments a caller may use. ``policies=None`` means all of them."""
  65. policies: tuple[GroupFilamentPolicy, ...] | None = None
  66. @property
  67. def is_unrestricted(self) -> bool:
  68. return self.policies is None
  69. def allows(self, filament_type: str | None, filament_id: str | None) -> bool:
  70. if self.policies is None:
  71. return True
  72. if not _norm(filament_type) and not _norm(filament_id):
  73. return True
  74. return any(policy.allows(filament_type, filament_id) for policy in self.policies)
  75. def blocked_requirements(self, requirements: Iterable[Mapping]) -> list[Mapping]:
  76. """The file's filament slots (``extract_filament_requirements`` entries) not allowed."""
  77. return [r for r in requirements if not self.allows(r.get("type"), r.get("tray_info_idx"))]
  78. def blocked_tray_ids(self, loaded: Iterable[Mapping]) -> set[int]:
  79. """Global tray ids (``_build_loaded_filaments`` entries) holding a filament not allowed."""
  80. return {
  81. int(tray["global_tray_id"])
  82. for tray in loaded
  83. if not self.allows(tray.get("type"), tray.get("tray_info_idx"))
  84. }
  85. ALL_FILAMENTS = FilamentScope()
  86. NO_FILAMENTS = FilamentScope(())
  87. def clean_rules(raw: Iterable[Mapping | object] | None) -> list[dict]:
  88. """Rules as stored: known kinds only, values stripped, materials upper-cased, no repeats."""
  89. cleaned: list[dict] = []
  90. seen: set[tuple[str, str]] = set()
  91. for entry in raw or ():
  92. if isinstance(entry, Mapping):
  93. match, value = entry.get("match"), entry.get("value")
  94. else:
  95. match, value = getattr(entry, "match", None), getattr(entry, "value", None)
  96. if match not in RULE_MATCHES or not isinstance(value, str) or not value.strip():
  97. continue
  98. value = value.strip().upper() if match == "material" else value.strip()
  99. key = (match, _norm(value))
  100. if key in seen:
  101. continue
  102. seen.add(key)
  103. cleaned.append({"match": match, "value": value})
  104. return cleaned
  105. def policy_for_group(group) -> GroupFilamentPolicy:
  106. mode = group.filament_rule_mode if group.filament_rule_mode in RULE_MODES else "block"
  107. rules = tuple(FilamentRule(r["match"], r["value"]) for r in clean_rules(group.filament_rules))
  108. return GroupFilamentPolicy(group.name, mode, rules)
  109. def resolve_user_filament_scope(user) -> FilamentScope:
  110. """Scope of a loaded ``User`` (``groups`` must already be loaded)."""
  111. if user.is_admin:
  112. return ALL_FILAMENTS
  113. restricted = [g for g in user.groups if g.restrict_filaments]
  114. if not restricted:
  115. return ALL_FILAMENTS
  116. return FilamentScope(tuple(policy_for_group(g) for g in restricted))
  117. def filament_policies_for(user) -> list[FilamentPolicyBrief] | None:
  118. """The user's filament rules for the print dialog; None when unrestricted.
  119. Every ``UserResponse`` builder fills ``filament_policies`` from this:
  120. None there means "may print with every filament", so leaving it out for a
  121. restricted user would say the wrong thing. ``user.groups`` must be loaded.
  122. """
  123. scope = resolve_user_filament_scope(user)
  124. if scope.policies is None:
  125. return None
  126. return [
  127. FilamentPolicyBrief(
  128. group=policy.group_name,
  129. mode=policy.mode,
  130. rules=[FilamentRuleSchema(match=rule.match, value=rule.value) for rule in policy.rules],
  131. )
  132. for policy in scope.policies
  133. ]
  134. async def resolve_user_id_filament_scope(db: AsyncSession, user_id: int | None) -> FilamentScope:
  135. """Scope of the user with ``user_id``, as the scheduler and the queue routes read it."""
  136. from sqlalchemy.orm import selectinload
  137. from backend.app.core.auth import is_auth_enabled
  138. from backend.app.models.user import User
  139. if user_id is None or not await is_auth_enabled(db):
  140. return ALL_FILAMENTS
  141. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  142. user = result.scalar_one_or_none()
  143. if user is None or not user.is_active:
  144. return NO_FILAMENTS
  145. return resolve_user_filament_scope(user)
  146. def describe_filament(entry: Mapping) -> str:
  147. """Name a filament for messages: "PETG (GFG03)", "PETG" or "GFG03"."""
  148. kind = str(entry.get("type") or "").strip()
  149. ident = str(entry.get("tray_info_idx") or "").strip()
  150. if kind and ident:
  151. return f"{kind} ({ident})"
  152. return kind or ident
  153. def describe_filaments(entries: Iterable[Mapping]) -> str:
  154. """Each filament in ``entries`` named once, sorted: "PETG (GFG03), PLA"."""
  155. return ", ".join(sorted({describe_filament(e) for e in entries}))
  156. def blocked_message(entries: Iterable[Mapping]) -> str:
  157. """What the queue route's 403 tells the caller about filaments their groups don't allow."""
  158. return f"Your group can't print with: {describe_filaments(entries)}"
  159. # The scheduler's holds are read on the queue row, by an admin as well as by
  160. # the job's creator, so they name the creator's group in the third person. A
  161. # file finding and a spool finding are worded apart: the first waits for a
  162. # rule change or another file, the second also ends when the spool is swapped.
  163. _CREATOR_CANT = "the job creator's group can't print with"
  164. def file_hold_message(entries: Iterable[Mapping]) -> str:
  165. """The scheduler's hold for a file that needs filaments its creator's groups don't allow."""
  166. return f"This file needs a filament {_CREATOR_CANT}: {describe_filaments(entries)}"
  167. def spool_hold_message(entries: Iterable[Mapping]) -> str:
  168. """The scheduler's hold for a job that would print from loaded spools its creator's groups don't allow."""
  169. return f"It would print from a loaded spool {_CREATOR_CANT}: {describe_filaments(entries)}"
  170. def unlisted_file_hold_message(blocked: Iterable[Mapping]) -> str:
  171. """The scheduler's hold for a file that lists no filaments, on a printer that could feed it a blocked spool."""
  172. return (
  173. f"This file doesn't list its filaments, and the printer has a loaded spool {_CREATOR_CANT}: "
  174. f"{describe_filaments(blocked)}"
  175. )
  176. def print_anyway_hold_message(unresolved: Iterable[Mapping], blocked: Iterable[Mapping]) -> str:
  177. """The scheduler's hold for "Print anyway" leaving slots for the printer to fill, next to blocked spools.
  178. The unmatched filament is named apart: it isn't the one the group blocks,
  179. and may well be allowed.
  180. """
  181. return (
  182. f"Print anyway leaves {describe_filaments(unresolved)} without a slot, and the printer could pick "
  183. f"a loaded spool {_CREATOR_CANT}: {describe_filaments(blocked)}"
  184. )
  185. def judged_requirements(requirements: Iterable[Mapping], overrides: Iterable[object] | None) -> list[Mapping]:
  186. """The file's filament slots as a scope judges them once the job's overrides apply (#3522).
  187. One rule wherever a file is judged: ``POST /queue/``, the scheduler and
  188. the print dialog (``judgedFilaments`` in ``filamentScope.ts``). An
  189. overridden slot is judged as its override names it: the override's type,
  190. and its filament id only for a forced colour, since a swap clears the id
  191. (``PrintScheduler._apply_filament_overrides``). A slot left naming no
  192. filament id isn't judged here at all: the tray matcher never maps it onto
  193. a spool the creator may not use, so the tray it prints from is what is
  194. judged. Judged by its type alone, a group that allows only filament ids
  195. would refuse a colour swap onto one of its own spools.
  196. """
  197. by_slot: dict[int, Mapping] = {}
  198. for override in overrides or ():
  199. if isinstance(override, Mapping):
  200. slot_id = override.get("slot_id")
  201. if isinstance(slot_id, int) and not isinstance(slot_id, bool):
  202. by_slot[slot_id] = override
  203. judged: list[Mapping] = []
  204. for req in requirements:
  205. slot_id = req.get("slot_id")
  206. override = by_slot.get(slot_id) if isinstance(slot_id, int) else None
  207. if override is None:
  208. judged.append(req)
  209. continue
  210. filament_id = str(override.get("tray_info_idx") or "").strip() if override.get("force_color_match") else ""
  211. if filament_id:
  212. judged.append({**req, "type": override.get("type", ""), "tray_info_idx": filament_id})
  213. return judged
  214. def ensure_requirements_allowed(scope: FilamentScope, requirements: Iterable[Mapping]) -> None:
  215. """403 naming each filament of the file the caller's groups don't allow."""
  216. if scope.is_unrestricted:
  217. return
  218. blocked = scope.blocked_requirements(requirements)
  219. if blocked:
  220. raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=blocked_message(blocked))