printer_scope.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """Which printers a caller may see and control (#1727).
  2. Permissions answer *what* a caller may do; a printer scope answers *on which
  3. printers*. The two are checked separately: a route first passes its
  4. permission gate, then refuses any printer outside the caller's scope.
  5. How a scope is derived:
  6. * Auth disabled, or an admin user: every printer.
  7. * A user: the union of the printers of each of their groups that has
  8. ``restrict_printers`` set. A user in no such group sees every printer, so
  9. installs that never configure this behave exactly as before. A group
  10. without the flag doesn't contribute, so permission groups (Operators,
  11. Viewers) combine with team groups without widening them.
  12. * An API key: its own ``printer_ids`` (None = all), narrowed to its owner's
  13. scope, so a key can never reach a printer its owner can't.
  14. A printer outside the scope is reported as missing (404), never as forbidden,
  15. so its id isn't confirmed to a caller who can't see it.
  16. """
  17. from __future__ import annotations
  18. from collections.abc import Iterable
  19. from dataclasses import dataclass
  20. from fastapi import HTTPException, status
  21. from sqlalchemy import select
  22. from sqlalchemy.ext.asyncio import AsyncSession
  23. from backend.app.models.group import Group, group_printers
  24. @dataclass(frozen=True)
  25. class PrinterScope:
  26. """The printers a caller may use. ``printer_ids=None`` means all of them."""
  27. printer_ids: frozenset[int] | None = None
  28. @property
  29. def is_unrestricted(self) -> bool:
  30. return self.printer_ids is None
  31. def allows(self, printer_id: int | None) -> bool:
  32. """Whether ``printer_id`` is in scope. ``None`` (no printer) always is."""
  33. if printer_id is None or self.printer_ids is None:
  34. return True
  35. return printer_id in self.printer_ids
  36. def ensure(self, printer_id: int | None) -> None:
  37. """Raise the same 404 a missing printer gets when ``printer_id`` is out of scope."""
  38. if not self.allows(printer_id):
  39. raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Printer not found")
  40. def intersect(self, other: PrinterScope) -> PrinterScope:
  41. if self.printer_ids is None:
  42. return other
  43. if other.printer_ids is None:
  44. return self
  45. return PrinterScope(self.printer_ids & other.printer_ids)
  46. def filter_ids(self, printer_ids: Iterable[int]) -> list[int]:
  47. """``printer_ids`` minus the ones out of scope, order kept."""
  48. return [pid for pid in printer_ids if self.allows(pid)]
  49. def where(self, column):
  50. """A WHERE clause limiting ``column`` (a printer id column) to the scope.
  51. Returns None when unrestricted so callers can skip the filter. Rows
  52. whose printer is NULL stay visible: they aren't bound to any printer
  53. (orphaned archives, queue items waiting for a model match).
  54. """
  55. if self.printer_ids is None:
  56. return None
  57. return column.is_(None) | column.in_(self.printer_ids)
  58. def where_strict(self, column):
  59. """Like ``where`` but also drops rows with no printer."""
  60. if self.printer_ids is None:
  61. return None
  62. return column.in_(self.printer_ids)
  63. ALL_PRINTERS = PrinterScope()
  64. def ensure_model_target_allowed(user, scope: PrinterScope) -> None:
  65. """Refuse an "any printer of a model" job from a limited caller with no user.
  66. The scheduler keeps such a job within its *creator's* scope, but a job
  67. queued through an API key records no creator, so a key limited to certain
  68. printers could otherwise reach the rest of the fleet through it. Users are
  69. unaffected: their jobs carry their id.
  70. """
  71. if user is None and not scope.is_unrestricted:
  72. raise HTTPException(
  73. status_code=status.HTTP_400_BAD_REQUEST,
  74. detail="A caller limited to certain printers must queue to a specific printer, not to any printer of a model",
  75. )
  76. async def group_printer_ids(db: AsyncSession, group_id: int) -> list[int]:
  77. result = await db.execute(
  78. select(group_printers.c.printer_id)
  79. .where(group_printers.c.group_id == group_id)
  80. .order_by(group_printers.c.printer_id)
  81. )
  82. return list(result.scalars().all())
  83. async def resolve_user_printer_scope(db: AsyncSession, user) -> PrinterScope:
  84. """Scope of a loaded ``User`` (``groups`` must already be loaded)."""
  85. if user.is_admin:
  86. return ALL_PRINTERS
  87. restricted = [g.id for g in user.groups if g.restrict_printers]
  88. if not restricted:
  89. return ALL_PRINTERS
  90. result = await db.execute(select(group_printers.c.printer_id).where(group_printers.c.group_id.in_(restricted)))
  91. return PrinterScope(frozenset(result.scalars().all()))
  92. async def resolve_user_id_printer_scope(db: AsyncSession, user_id: int | None) -> PrinterScope:
  93. """Scope of the user with ``user_id``; no user (VP, auth off) means every printer.
  94. For background work acting on a user's behalf, such as the scheduler
  95. choosing a printer for a queued job. A deleted or deactivated user gets an
  96. empty scope rather than everything, so their leftover jobs don't spread
  97. onto printers they were never allowed to use.
  98. """
  99. from sqlalchemy.orm import selectinload
  100. from backend.app.models.user import User
  101. if user_id is None:
  102. return ALL_PRINTERS
  103. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  104. user = result.scalar_one_or_none()
  105. if user is None or not user.is_active:
  106. return PrinterScope(frozenset())
  107. return await resolve_user_printer_scope(db, user)
  108. def api_key_own_scope(api_key) -> PrinterScope:
  109. """The key's own ``printer_ids`` allowlist, without its owner's narrowing."""
  110. if api_key.printer_ids is None:
  111. return ALL_PRINTERS
  112. return PrinterScope(frozenset(int(pid) for pid in api_key.printer_ids))
  113. async def group_restricts_printers(db: AsyncSession, group_ids: Iterable[int]) -> bool:
  114. ids = list(group_ids)
  115. if not ids:
  116. return False
  117. result = await db.execute(select(Group.id).where(Group.id.in_(ids), Group.restrict_printers.is_(True)).limit(1))
  118. return result.first() is not None