runtime_bootstrap.py 4.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """Private local bootstrap grants; never put these credentials in discovery."""
  2. from __future__ import annotations
  3. import hashlib
  4. import secrets
  5. import threading
  6. import time
  7. _PURPOSE_CAPABILITIES = {
  8. 'interactive': frozenset({'session:create', 'session:read', 'session:submit',
  9. 'session:control', 'session:approve', 'session:respond'}),
  10. 'native-http': frozenset({'http:owner'}),
  11. # Same-user host operation, not permission to read or mutate another profile.
  12. 'native-profile-create': frozenset({'profiles:create'}),
  13. # Rename/delete of the ONE profile it is minted for (#140345): a registry write on that home,
  14. # never a read of it or any other route.
  15. 'native-profile-registry': frozenset({'profiles:registry'}),
  16. 'exposure': frozenset({'transport:delegate'}),
  17. 'worker-adoption': frozenset({'worker:adopt'}),
  18. }
  19. # A grant's profile reach: its own home, or (interactive only) every served sibling.
  20. _SCOPES = frozenset({'profile', 'host'})
  21. class TicketStore:
  22. TTL_SECONDS = 30
  23. MAX_ENTRIES = 1024
  24. def __init__(self, instance_id: str, profile_ids: frozenset[str]):
  25. if not instance_id or not profile_ids:
  26. raise ValueError('bootstrap requires instance and served profiles')
  27. self.instance_id = instance_id
  28. self.profile_ids = frozenset(profile_ids)
  29. self._entries: dict[str, tuple[float, dict]] = {}
  30. self._lock = threading.Lock()
  31. def mint(self, *, profile_id, subject, purpose, scope='profile', refuse_restart_wait=False) -> str:
  32. """``scope='host'`` lets an interactive connection select every profile this process
  33. serves (the Desktop's one shared socket); the default binds exactly ``profile_id``.
  34. ``refuse_restart_wait``: the socket redeeming it is refused while a restart's after-turn
  35. wait is open, however long after the mint that wait began (a machine poller, never a human)."""
  36. if (profile_id not in self.profile_ids or purpose not in _PURPOSE_CAPABILITIES or not subject
  37. or scope not in _SCOPES or (scope == 'host' and purpose != 'interactive')):
  38. raise PermissionError('bootstrap binding rejected')
  39. with self._lock:
  40. now = time.monotonic()
  41. self._entries = {k: v for k, v in self._entries.items() if v[0] > now}
  42. if len(self._entries) >= self.MAX_ENTRIES:
  43. raise PermissionError('bootstrap capacity exhausted')
  44. ticket = secrets.token_urlsafe(32)
  45. self._entries[hashlib.sha256(ticket.encode()).hexdigest()] = (
  46. now + self.TTL_SECONDS,
  47. {'instance_id': self.instance_id, 'profile_id': profile_id, 'subject': subject,
  48. 'purpose': purpose, 'capabilities': _PURPOSE_CAPABILITIES[purpose], 'scope': scope,
  49. 'refuse_restart_wait': bool(refuse_restart_wait)})
  50. return ticket
  51. def redeem(self, ticket, *, profile_id, purpose) -> dict:
  52. """``profile_id=None`` accepts a ticket minted for ANY served profile; the returned grant's
  53. ``profile_id`` then selects the authority. A named profile must match exactly."""
  54. if not isinstance(ticket, str) or len(ticket) > 256:
  55. raise PermissionError('invalid bootstrap ticket')
  56. key = hashlib.sha256(ticket.encode()).hexdigest()
  57. with self._lock:
  58. entry = self._entries.get(key)
  59. if entry is None:
  60. raise PermissionError('invalid bootstrap ticket')
  61. expires, grant = entry
  62. if expires <= time.monotonic():
  63. del self._entries[key]
  64. raise PermissionError('expired bootstrap ticket')
  65. served = grant['profile_id'] in self.profile_ids if profile_id is None else grant['profile_id'] == profile_id
  66. if not served or grant['purpose'] != purpose:
  67. raise PermissionError('bootstrap binding rejected')
  68. del self._entries[key]
  69. return dict(grant)
  70. def outstanding(self) -> bool:
  71. """An unexpired ticket was minted and not yet redeemed: a client is attaching right now."""
  72. with self._lock:
  73. now = time.monotonic()
  74. return any(expires > now for expires, _grant in self._entries.values())
  75. def revoke(self) -> None:
  76. with self._lock:
  77. self._entries.clear()