qodalis-cli-server-plugin-users 1.0.0b28__tar.gz → 1.0.0b29__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/.gitignore +3 -0
  2. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/PKG-INFO +1 -1
  3. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/pyproject.toml +1 -1
  4. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/__init__.py +16 -1
  5. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/cli_users_builder.py +159 -21
  6. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/controllers/__init__.py +2 -0
  7. qodalis_cli_server_plugin_users-1.0.0b29/qodalis_cli_users/controllers/permissions_controller.py +37 -0
  8. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/controllers/tokens_controller.py +102 -35
  9. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/errors.py +26 -0
  10. qodalis_cli_server_plugin_users-1.0.0b29/qodalis_cli_users/middleware/auth_middleware.py +195 -0
  11. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/models.py +50 -3
  12. qodalis_cli_server_plugin_users-1.0.0b29/qodalis_cli_users/permissions.py +145 -0
  13. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/server_protection.py +142 -9
  14. qodalis_cli_server_plugin_users-1.0.0b29/qodalis_cli_users/services/api_token_manager.py +165 -0
  15. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/services/auth_service.py +71 -10
  16. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/services/link_service.py +4 -3
  17. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/shell_access.py +3 -2
  18. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/stores/interfaces.py +2 -1
  19. qodalis_cli_server_plugin_users-1.0.0b28/qodalis_cli_users/middleware/auth_middleware.py +0 -77
  20. qodalis_cli_server_plugin_users-1.0.0b28/qodalis_cli_users/permissions.py +0 -60
  21. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/LICENSE +0 -0
  22. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/_http.py +0 -0
  23. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/controllers/_routing.py +0 -0
  24. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/controllers/groups_controller.py +0 -0
  25. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/controllers/link_controller.py +0 -0
  26. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/controllers/sessions_controller.py +0 -0
  27. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/controllers/users_controller.py +0 -0
  28. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/external_request.py +0 -0
  29. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/middleware/__init__.py +0 -0
  30. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/services/__init__.py +0 -0
  31. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/services/password_hasher.py +0 -0
  32. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/services/users_service.py +0 -0
  33. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/stores/__init__.py +0 -0
  34. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/stores/in_memory_api_token_store.py +0 -0
  35. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/stores/in_memory_audit_store.py +0 -0
  36. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/stores/in_memory_credential_store.py +0 -0
  37. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/stores/in_memory_group_store.py +0 -0
  38. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/stores/in_memory_session_store.py +0 -0
  39. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/stores/in_memory_user_store.py +0 -0
  40. {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b29}/qodalis_cli_users/validation.py +0 -0
@@ -42,3 +42,6 @@ TestResults/
42
42
  .DS_Store
43
43
  Thumbs.db
44
44
  node_modules/
45
+
46
+ # Portal site copied into the package at build time (scripts/copy_portal.py)
47
+ plugins/portal/qodalis_cli_portal/site/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: qodalis-cli-server-plugin-users
3
- Version: 1.0.0b28
3
+ Version: 1.0.0b29
4
4
  Summary: User management plugin for Qodalis CLI servers — authentication, sessions, groups and API tokens, recorded in the audit plugin's log
5
5
  Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
6
6
  Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "qodalis-cli-server-plugin-users"
7
- version = "1.0.0b28"
7
+ version = "1.0.0b29"
8
8
  description = "User management plugin for Qodalis CLI servers — authentication, sessions, groups and API tokens, recorded in the audit plugin's log"
9
9
  readme = { text = "", content-type = "text/plain" }
10
10
  license = "MIT"
@@ -9,7 +9,7 @@ from __future__ import annotations
9
9
  __plugin_icon__ = "👥"
10
10
 
11
11
  from .cli_users_builder import CliUsersBuilder, CliUsersPlugin
12
- from .errors import UsersApiError
12
+ from .errors import QcliGuardError, UsersApiError
13
13
  from .models import (
14
14
  ApiToken,
15
15
  AuditEntry,
@@ -18,17 +18,25 @@ from .models import (
18
18
  ExternalAuthAdapter,
19
19
  ExternalAuthResult,
20
20
  Group,
21
+ QcliCaller,
21
22
  Session,
22
23
  SessionMetadata,
24
+ TokenUsageProvider,
23
25
  User,
24
26
  )
25
27
  from .permissions import has_permission, merge_permissions, permission_matches
26
28
  from .services.auth_service import (
27
29
  DEFAULT_SESSION_TIMEOUT_MS,
30
+ HOST_TOKEN_REQUIRED,
28
31
  AuthContext,
29
32
  AuthService,
30
33
  AuthServiceOptions,
31
34
  )
35
+ from .services.api_token_manager import (
36
+ ApiTokenCreateOptions,
37
+ ApiTokenManager,
38
+ CreatedApiToken,
39
+ )
32
40
  from .services.users_service import UsersService
33
41
  from .server_protection import ServerProtectionMiddleware
34
42
  from .shell_access import UsersShellAccess
@@ -49,6 +57,8 @@ from .stores.interfaces import (
49
57
 
50
58
  __all__ = [
51
59
  "ApiToken",
60
+ "ApiTokenCreateOptions",
61
+ "ApiTokenManager",
52
62
  "AuditEntry",
53
63
  "AuditQueryOptions",
54
64
  "AuthContext",
@@ -56,6 +66,8 @@ __all__ = [
56
66
  "AuthServiceOptions",
57
67
  "CliUsersBuilder",
58
68
  "CliUsersPlugin",
69
+ "CreatedApiToken",
70
+ "HOST_TOKEN_REQUIRED",
59
71
  "Credentials",
60
72
  "ExternalAuthAdapter",
61
73
  "ExternalAuthResult",
@@ -72,9 +84,12 @@ __all__ = [
72
84
  "InMemoryGroupStore",
73
85
  "InMemorySessionStore",
74
86
  "InMemoryUserStore",
87
+ "QcliCaller",
88
+ "QcliGuardError",
75
89
  "Session",
76
90
  "ServerProtectionMiddleware",
77
91
  "SessionMetadata",
92
+ "TokenUsageProvider",
78
93
  "User",
79
94
  "UsersApiError",
80
95
  "UsersService",
@@ -32,12 +32,19 @@ from qodalis_cli_server_abstractions.events import ICliEventBus
32
32
 
33
33
  from .controllers.groups_controller import create_groups_router
34
34
  from .controllers.link_controller import create_link_router
35
+ from .controllers.permissions_controller import create_permissions_router
35
36
  from .controllers.sessions_controller import create_sessions_router
36
37
  from .controllers.tokens_controller import create_tokens_router
37
38
  from .controllers.users_controller import create_users_router
38
- from .middleware.auth_middleware import create_auth_dependencies
39
- from .errors import UsersApiError
40
- from .models import ExternalAuthAdapter
39
+ from .middleware.auth_middleware import (
40
+ cli_only,
41
+ create_auth_dependencies,
42
+ host_token_dependency,
43
+ permission_dependency,
44
+ )
45
+ from .errors import QcliGuardError, UsersApiError, install_guard_error_handler
46
+ from .models import ExternalAuthAdapter, TokenUsageProvider
47
+ from .permissions import USERS_PERMISSION_ENTRIES
41
48
  from .server_protection import ServerProtectionMiddleware, _normalize_base
42
49
  from .shell_access import UsersShellAccess
43
50
  from .services.auth_service import (
@@ -58,6 +65,7 @@ from .services.link_service import (
58
65
  LinkService,
59
66
  validate_link_approval_url,
60
67
  )
68
+ from .services.api_token_manager import ApiTokenManager
61
69
  from .services.users_service import UsersService
62
70
  from .stores.in_memory_api_token_store import InMemoryApiTokenStore
63
71
  from .stores.in_memory_credential_store import InMemoryCredentialStore
@@ -83,6 +91,15 @@ DEFAULT_CLEANUP_INTERVAL_MS = 5 * 60 * 1000
83
91
  DEFAULT_SESSION_CHECK_INTERVAL = 30.0
84
92
  MAX_SESSION_CHECK_INTERVAL = 60.0
85
93
  LOGS_READ = "logs:read"
94
+ GUARD_ONLY_NEEDS_NO_CLI_ROUTES = "guard-only needs cli_routes=False"
95
+
96
+
97
+ def _is_own_entry(existing: Any, entry: dict[str, str]) -> bool:
98
+ return (
99
+ existing is not None
100
+ and getattr(existing, "surface", None) == "cli"
101
+ and getattr(existing, "description", None) == entry["description"]
102
+ )
86
103
 
87
104
 
88
105
  @dataclass
@@ -113,8 +130,30 @@ class CliUsersPlugin:
113
130
  require_auth: Any = None
114
131
  #: ``require_permission("perm")`` → FastAPI dependency (403 if missing).
115
132
  require_permission: Any = None
133
+ #: FastAPI dependency for CLI routes of other plugins (e.g. the admin
134
+ #: API): ``require_auth`` that also refuses ``host`` API tokens (403
135
+ #: ``forbidden: host tokens cannot use CLI routes``).
136
+ require_cli_auth: Any = None
137
+ #: ``require_host_token("perm")`` → FastAPI dependency accepting only
138
+ #: ``host`` API tokens (403 ``forbidden: a host token is required``),
139
+ #: then checking the permission when given.
140
+ require_host_token: Any = None
141
+ #: ``require_auth`` without setting ``request.state.qcli_caller``: for
142
+ #: guards that set it themselves once they fully passed (public-api).
143
+ authenticate: Any = None
144
+ #: Guard-only mode (``set_guard_only()``): no routes, no seeding, no
145
+ #: server protection; the guards validate tokens of shared stores.
146
+ guard_only: bool = False
147
+ #: API tokens the host creates, lists and revokes for its users,
148
+ #: including ``host`` tokens (accepted only by ``require_auth`` /
149
+ #: ``require_permission``).
150
+ api_tokens: Optional[ApiTokenManager] = None
116
151
  _extra_public: list = field(default_factory=list, repr=False)
117
152
  _base_paths: list = field(default_factory=list, repr=False)
153
+ #: The server's ``cli_route_prefixes`` (live list), set when mounted.
154
+ _server_cli_prefixes: Optional[list] = field(default=None, repr=False)
155
+ #: The server's ``public_paths`` (live list), set when mounted.
156
+ _server_public_paths: Optional[list] = field(default=None, repr=False)
118
157
  _protected_apps: list = field(default_factory=list, repr=False)
119
158
  _cleanup_task: Optional[asyncio.Task] = field(default=None, repr=False)
120
159
  #: ``(socket manager, permission)`` of the server's events/logs sockets.
@@ -128,10 +167,19 @@ class CliUsersPlugin:
128
167
  link_service: Optional[LinkService] = None
129
168
  _link_limiter: Optional[LinkRateLimiter] = field(default=None, repr=False)
130
169
  _seeded: bool = field(default=False, repr=False)
170
+ #: Guard-only: mounted on a server without CLI routes (the guards work).
171
+ _guard_only_mounted: bool = field(default=False, repr=False)
131
172
  _seed_lock: Optional[asyncio.Lock] = field(default=None, repr=False)
132
173
 
133
174
  async def ensure_seeded(self) -> None:
134
- """Seed built-in groups and the root user once (idempotent)."""
175
+ """Seed built-in groups and the root user once (idempotent). In
176
+ guard-only mode nothing is seeded, and until the plugin is mounted on
177
+ a server without CLI routes the guards answer 500 (fail closed)."""
178
+ if self.guard_only:
179
+ if not self._guard_only_mounted:
180
+ logger.error(GUARD_ONLY_NEEDS_NO_CLI_ROUTES)
181
+ raise QcliGuardError(500, "internal server error")
182
+ return
135
183
  if self._seeded:
136
184
  return
137
185
  if self._seed_lock is None:
@@ -146,6 +194,15 @@ class CliUsersPlugin:
146
194
  def auth(self) -> AuthService:
147
195
  return self.auth_service
148
196
 
197
+ def set_token_usage_provider(self, provider: TokenUsageProvider | None) -> None:
198
+ """Add ``usage`` to the token views (``GET /tokens`` and
199
+ :meth:`ApiTokenManager.list`): ``await provider(token_ids)`` returns
200
+ ``{token_id: {"today", "last30Days", "days"}}``. ``None`` removes
201
+ it. The public-api plugin sets one."""
202
+ if provider is not None and not callable(provider):
203
+ raise TypeError("token usage provider must be callable")
204
+ self.auth_service.token_usage_provider = provider
205
+
149
206
  def allow_anonymous(self, path: str, methods: list[str] | None = None) -> None:
150
207
  """Exempt an exact path from server protection (e.g. another plugin's
151
208
  login endpoint)."""
@@ -153,9 +210,12 @@ class CliUsersPlugin:
153
210
  (path, frozenset(m.upper() for m in methods) if methods else None),
154
211
  )
155
212
 
156
- def protect(self, app: Any) -> None:
213
+ def protect(self, app: Any, *, enforce: bool = True) -> None:
157
214
  """Install the server-protection middleware on ``app`` (innermost,
158
- so CORS stays outermost). Must be called before the app starts."""
215
+ so CORS stays outermost). Must be called before the app starts.
216
+ ``enforce=False`` (``set_protect_server(False)``) authenticates
217
+ nothing and only refuses ``host`` API tokens on the CLI's routes and
218
+ sockets."""
159
219
  if any(a is app for a in self._protected_apps):
160
220
  return
161
221
  from starlette.middleware import Middleware
@@ -166,6 +226,9 @@ class CliUsersPlugin:
166
226
  ensure_ready=self.ensure_seeded,
167
227
  extra_public=self._extra_public,
168
228
  base_paths=self._base_paths,
229
+ cli_prefixes=lambda: self._server_cli_prefixes,
230
+ enforce=enforce,
231
+ public_paths=lambda: self._server_public_paths,
169
232
  ))
170
233
  app.middleware_stack = None
171
234
  self._protected_apps.append(app)
@@ -176,6 +239,13 @@ class CliUsersPlugin:
176
239
  ended, adopts the server's allowed origins (CSRF), protects the whole
177
240
  server unless disabled and owns access to the remote shell (``users``
178
241
  shell mode)."""
242
+ options = getattr(server, "options", None)
243
+ # Fail closed: guard-only installs no protection, so the CLI's routes
244
+ # must not be served at all.
245
+ if self.guard_only and getattr(options, "cli_routes", True) is not False:
246
+ raise ValueError(GUARD_ONLY_NEEDS_NO_CLI_ROUTES)
247
+ if self.guard_only:
248
+ self._guard_only_mounted = True
179
249
  manager = getattr(server, "event_socket_manager", None)
180
250
  if manager is not None and hasattr(manager, "send_to_user"):
181
251
  self.auth_service.user_event_sender = manager.send_to_user
@@ -187,7 +257,6 @@ class CliUsersPlugin:
187
257
  # sockets without a user (read on every event).
188
258
  if manager is not None and hasattr(manager, "set_authentication_required"):
189
259
  manager.set_authentication_required(lambda: True)
190
- options = getattr(server, "options", None)
191
260
  # The host application signs users in (read by the admin dashboard).
192
261
  if self.auth_service.external_auth and hasattr(options, "external_authentication"):
193
262
  options.external_authentication = True
@@ -200,8 +269,17 @@ class CliUsersPlugin:
200
269
  base = _normalize_base(base_path)
201
270
  if base not in self._base_paths:
202
271
  self._base_paths.append(base)
203
- if self.protect_server:
204
- self.protect(server.app)
272
+ prefixes = getattr(server, "cli_route_prefixes", None)
273
+ if isinstance(prefixes, list):
274
+ self._server_cli_prefixes = prefixes
275
+ public = getattr(server, "public_paths", None)
276
+ if isinstance(public, list):
277
+ self._server_public_paths = public
278
+ # Without protection the middleware still refuses host tokens on the
279
+ # CLI's routes (they authenticate nothing else then). A guard-only
280
+ # plugin (on a server without CLI routes) has nothing to protect.
281
+ if not self.guard_only:
282
+ self.protect(server.app, enforce=self.protect_server)
205
283
  # Events/logs sockets are bound to their session: closed (4401
206
284
  # "session ended") on logout, revoke, disable/delete and expiry.
207
285
  # Those of adapter identities are re-checked through the adapter
@@ -223,7 +301,24 @@ class CliUsersPlugin:
223
301
  set_shell_provider = getattr(server, "set_shell_access_provider", None)
224
302
  if callable(set_shell_provider):
225
303
  set_shell_provider(UsersShellAccess(self.auth_service))
226
- self._mount_audit(server)
304
+ self._adopt_permission_catalog(server)
305
+ # The host-token-only guards answer {"error": ...} on host routes.
306
+ install_guard_error_handler(server.app)
307
+ if not self.guard_only:
308
+ self._mount_audit(server)
309
+
310
+ def _adopt_permission_catalog(self, server: Any) -> None:
311
+ """Use the server's permission catalog (``server.builder.permissions``,
312
+ core 1.0.0b29 and later) and add the plugin's entries to it, once. On
313
+ an older core the plugin keeps its own catalog."""
314
+ catalog = getattr(getattr(server, "builder", None), "permissions", None)
315
+ if catalog is None or not all(callable(getattr(catalog, m, None)) for m in ("add", "all", "find")):
316
+ return
317
+ # Skipped only on a remount (all twelve entries are the plugin's own);
318
+ # a host or plugin that registered any of them itself fails startup.
319
+ if not all(_is_own_entry(catalog.find(e["name"]), e) for e in USERS_PERMISSION_ENTRIES):
320
+ catalog.add(USERS_PERMISSION_ENTRIES, "cli")
321
+ self.auth_service.permission_catalog = catalog
227
322
 
228
323
  def _mount_audit(self, server: Any) -> None:
229
324
  """Mount the audit plugin with the users plugin, so a host that only
@@ -243,7 +338,7 @@ class CliUsersPlugin:
243
338
  async def authorize_audit(self, request: Request, permission: str) -> Any:
244
339
  """The users plugin's guard of the audit API (a session or token with
245
340
  ``permission``), used when it does not protect the whole server."""
246
- ctx = await self.require_auth(request)
341
+ ctx = await self.require_cli_auth(request)
247
342
  if not ctx.can(permission):
248
343
  raise UsersApiError(403, f"missing permission: {permission}")
249
344
  return ctx
@@ -261,7 +356,11 @@ class CliUsersPlugin:
261
356
  async def startup(self) -> None:
262
357
  """Seed and start the background tasks on the running loop: the
263
358
  session sweep and, with an external auth adapter, the re-check of
264
- the events/logs sockets opened through it."""
359
+ the events/logs sockets opened through it. Nothing in guard-only
360
+ mode."""
361
+ # Guard-only: the stores are the token-issuing service's to sweep.
362
+ if self.guard_only:
363
+ return
265
364
  await self.ensure_seeded()
266
365
  loop = asyncio.get_running_loop()
267
366
  if self._cleanup_task is None or self._cleanup_task.done():
@@ -370,6 +469,7 @@ class CliUsersBuilder:
370
469
  self._lockout_ms = DEFAULT_LOCKOUT_MS
371
470
  self._cleanup_interval_ms = DEFAULT_CLEANUP_INTERVAL_MS
372
471
  self._link_approval_url = DEFAULT_LINK_APPROVAL_URL
472
+ self._guard_only = False
373
473
 
374
474
  def set_user_store(self, store: IUserStore) -> CliUsersBuilder:
375
475
  self._user_store = store
@@ -496,6 +596,25 @@ class CliUsersBuilder:
496
596
  self._protect_server = protect
497
597
  return self
498
598
 
599
+ def set_guard_only(self, on: bool = True) -> CliUsersBuilder:
600
+ """Guard-only mode, for a service that only validates tokens (e.g. a
601
+ public API next to the service that runs the CLI): no users routes
602
+ (sign-in, users, groups, sessions, tokens, permissions, link, audit),
603
+ no seeding (no ``root``, no built-in groups) and no server
604
+ protection (``host`` tokens are still refused on CLI routes). The
605
+ guards (``require_auth``, ``require_permission``,
606
+ ``require_host_token``, the public-api guard) authenticate
607
+ ``qcli_pat_`` tokens against the stores set here, shared with the
608
+ service that creates them. Create and revoke tokens from one service
609
+ only: the name and 20-token checks run in the creating process.
610
+
611
+ Mount it on a server without CLI routes
612
+ (``CliServerOptions(cli_routes=False)``): on any other server
613
+ ``mount_plugin`` raises ``ValueError("guard-only needs
614
+ cli_routes=False")``, so the CLI routes are never left open."""
615
+ self._guard_only = on
616
+ return self
617
+
499
618
  def set_session_timeout(self, timeout_ms: int) -> CliUsersBuilder:
500
619
  """Idle session timeout in milliseconds (default 30 minutes)."""
501
620
  self._session_timeout_ms = timeout_ms
@@ -576,8 +695,10 @@ class CliUsersBuilder:
576
695
  api_token_store=auth_service.api_token_store,
577
696
  default_admin_password=self._default_admin_password,
578
697
  cleanup_interval_ms=self._cleanup_interval_ms,
579
- protect_server=self._protect_server,
698
+ protect_server=self._protect_server and not self._guard_only,
580
699
  audit_plugin=audit_plugin,
700
+ api_tokens=ApiTokenManager(auth_service),
701
+ guard_only=self._guard_only,
581
702
  )
582
703
 
583
704
  # The users plugin records its events in the audit plugin's store,
@@ -590,26 +711,43 @@ class CliUsersBuilder:
590
711
 
591
712
  # Requests made before startup() (e.g. apps without a lifespan) still
592
713
  # see the seeded built-ins.
593
- get_auth, require_permission, get_auth_pending = create_auth_dependencies(
714
+ get_auth, require_permission, get_auth_pending, get_cli_auth = create_auth_dependencies(
594
715
  auth_service, ensure_ready=plugin.ensure_seeded,
595
716
  )
717
+ # Host routes (require_auth / require_permission) accept host tokens;
718
+ # the plugin's own routes refuse them.
596
719
  plugin.require_auth = get_auth
597
720
  plugin.require_permission = require_permission
721
+ plugin.require_cli_auth = get_cli_auth
722
+ plugin.authenticate = get_auth.authenticate
723
+
724
+ def require_host_token(permission: str | None = None) -> Any:
725
+ return host_token_dependency(get_auth.authenticate, permission)
726
+
727
+ plugin.require_host_token = require_host_token
728
+ if self._guard_only:
729
+ return plugin
730
+ get_cli_auth_pending = cli_only(get_auth_pending)
731
+
732
+ def require_cli_permission(permission: str) -> Any:
733
+ return permission_dependency(get_cli_auth, permission)
734
+
598
735
  router.include_router(create_sessions_router(
599
- auth_service, get_auth, require_permission,
600
- ensure_ready=plugin.ensure_seeded, get_auth_pending=get_auth_pending,
736
+ auth_service, get_cli_auth, require_cli_permission,
737
+ ensure_ready=plugin.ensure_seeded, get_auth_pending=get_cli_auth_pending,
601
738
  ))
602
739
  router.include_router(create_users_router(
603
- auth_service, users_service, get_auth, require_permission,
604
- get_auth_pending=get_auth_pending,
740
+ auth_service, users_service, get_cli_auth, require_cli_permission,
741
+ get_auth_pending=get_cli_auth_pending,
605
742
  ))
606
743
  router.include_router(create_groups_router(
607
- auth_service, users_service, get_auth, require_permission,
744
+ auth_service, users_service, get_cli_auth, require_cli_permission,
608
745
  ))
609
- router.include_router(create_tokens_router(auth_service, get_auth))
746
+ router.include_router(create_tokens_router(auth_service, get_cli_auth))
747
+ router.include_router(create_permissions_router(auth_service, get_cli_auth))
610
748
  plugin.link_service = LinkService(auth_service, self._link_approval_url)
611
749
  plugin._link_limiter = LinkRateLimiter()
612
750
  router.include_router(create_link_router(
613
- auth_service, plugin.link_service, get_auth, plugin._link_limiter,
751
+ auth_service, plugin.link_service, get_cli_auth, plugin._link_limiter,
614
752
  ))
615
753
  return plugin
@@ -1,12 +1,14 @@
1
1
  """Users plugin controllers."""
2
2
 
3
3
  from .groups_controller import create_groups_router
4
+ from .permissions_controller import create_permissions_router
4
5
  from .sessions_controller import create_sessions_router
5
6
  from .tokens_controller import create_tokens_router
6
7
  from .users_controller import create_users_router
7
8
 
8
9
  __all__ = [
9
10
  "create_groups_router",
11
+ "create_permissions_router",
10
12
  "create_sessions_router",
11
13
  "create_tokens_router",
12
14
  "create_users_router",
@@ -0,0 +1,37 @@
1
+ """Permission catalog controller — ``/permissions``.
2
+
3
+ - ``GET /permissions`` the catalog entries the caller holds
4
+ - ``GET /permissions?all=true`` every catalog entry (``users:read``)
5
+
6
+ The dashboard's and console's token pickers are built from it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Callable
12
+
13
+ from fastapi import APIRouter, Depends
14
+
15
+ from ..errors import bad_request, forbidden
16
+ from ..permissions import USERS_READ
17
+ from ..services.auth_service import AuthContext, AuthService
18
+ from ._routing import collection, new_router
19
+
20
+
21
+ def create_permissions_router(auth_service: AuthService, get_auth: Callable) -> APIRouter:
22
+ router = new_router("/permissions", "permissions")
23
+
24
+ @collection(router, "GET")
25
+ async def list_permissions(all: str | None = None, ctx: AuthContext = Depends(get_auth)): # noqa: A002
26
+ if all not in (None, "true", "false"):
27
+ raise bad_request("all must be true or false")
28
+ entries = auth_service.permission_catalog.all()
29
+ if all == "true":
30
+ if not ctx.can(USERS_READ):
31
+ raise forbidden(f"permission denied: {USERS_READ}")
32
+ else:
33
+ # Wildcards in the caller's (scope-narrowed) permissions match.
34
+ entries = [p for p in entries if ctx.can(p.name)]
35
+ return [p.to_dict() for p in entries]
36
+
37
+ return router