qodalis-cli-server-plugin-users 1.0.0b8__tar.gz → 1.0.0b13__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 (36) hide show
  1. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/PKG-INFO +1 -1
  2. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/pyproject.toml +1 -1
  3. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/cli_users_builder.py +116 -18
  4. qodalis_cli_server_plugin_users-1.0.0b13/qodalis_cli_users/controllers/_routing.py +47 -0
  5. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/controllers/groups_controller.py +9 -6
  6. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/controllers/users_controller.py +6 -5
  7. qodalis_cli_server_plugin_users-1.0.0b13/qodalis_cli_users/external_request.py +60 -0
  8. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/models.py +17 -4
  9. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/server_protection.py +2 -0
  10. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/services/auth_service.py +93 -14
  11. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/services/users_service.py +3 -1
  12. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/shell_access.py +12 -16
  13. qodalis_cli_server_plugin_users-1.0.0b8/qodalis_cli_users/controllers/_routing.py +0 -25
  14. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/.gitignore +0 -0
  15. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/LICENSE +0 -0
  16. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/__init__.py +0 -0
  17. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/_http.py +0 -0
  18. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/controllers/__init__.py +0 -0
  19. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/controllers/audit_controller.py +0 -0
  20. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/controllers/sessions_controller.py +0 -0
  21. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/controllers/tokens_controller.py +0 -0
  22. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/errors.py +0 -0
  23. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/middleware/__init__.py +0 -0
  24. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/middleware/auth_middleware.py +0 -0
  25. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/permissions.py +0 -0
  26. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/services/__init__.py +0 -0
  27. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/services/password_hasher.py +0 -0
  28. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/stores/__init__.py +0 -0
  29. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/stores/in_memory_api_token_store.py +0 -0
  30. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/stores/in_memory_audit_store.py +0 -0
  31. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/stores/in_memory_credential_store.py +0 -0
  32. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/stores/in_memory_group_store.py +0 -0
  33. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/stores/in_memory_session_store.py +0 -0
  34. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/stores/in_memory_user_store.py +0 -0
  35. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/stores/interfaces.py +0 -0
  36. {qodalis_cli_server_plugin_users-1.0.0b8 → qodalis_cli_server_plugin_users-1.0.0b13}/qodalis_cli_users/validation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: qodalis-cli-server-plugin-users
3
- Version: 1.0.0b8
3
+ Version: 1.0.0b13
4
4
  Summary: User management plugin for Qodalis CLI servers — authentication, sessions, groups, and audit 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.0b8"
7
+ version = "1.0.0b13"
8
8
  description = "User management plugin for Qodalis CLI servers — authentication, sessions, groups, and audit log"
9
9
  readme = { text = "", content-type = "text/plain" }
10
10
  license = "MIT"
@@ -68,6 +68,12 @@ logger = logging.getLogger(__name__)
68
68
 
69
69
  PREFIX = "/api/v1/qcli"
70
70
  DEFAULT_CLEANUP_INTERVAL_MS = 5 * 60 * 1000
71
+ #: Re-check interval (seconds) of events/logs sockets opened through the
72
+ #: external auth adapter: the server's ``shell.session_check_interval``
73
+ #: (default 30), at most 60, as for shells.
74
+ DEFAULT_SESSION_CHECK_INTERVAL = 30.0
75
+ MAX_SESSION_CHECK_INTERVAL = 60.0
76
+ LOGS_READ = "logs:read"
71
77
 
72
78
 
73
79
  @dataclass
@@ -102,6 +108,10 @@ class CliUsersPlugin:
102
108
  _base_paths: list = field(default_factory=list, repr=False)
103
109
  _protected_apps: list = field(default_factory=list, repr=False)
104
110
  _cleanup_task: Optional[asyncio.Task] = field(default=None, repr=False)
111
+ #: ``(socket manager, permission)`` of the server's events/logs sockets.
112
+ _session_sockets: list = field(default_factory=list, repr=False)
113
+ _session_check_interval: Optional[float] = field(default=None, repr=False)
114
+ _external_check_task: Optional[asyncio.Task] = field(default=None, repr=False)
105
115
  _seeded: bool = field(default=False, repr=False)
106
116
  _seed_lock: Optional[asyncio.Lock] = field(default=None, repr=False)
107
117
 
@@ -155,6 +165,9 @@ class CliUsersPlugin:
155
165
  if manager is not None and hasattr(manager, "send_to_user"):
156
166
  self.auth_service.user_event_sender = manager.send_to_user
157
167
  options = getattr(server, "options", None)
168
+ # The host application signs users in (read by the admin dashboard).
169
+ if self.auth_service.external_auth and hasattr(options, "external_authentication"):
170
+ options.external_authentication = True
158
171
  origins = getattr(options, "allowed_origins", None)
159
172
  if origins and self.auth_service.options.allowed_origins is None:
160
173
  self.auth_service.options.allowed_origins = list(origins)
@@ -168,41 +181,98 @@ class CliUsersPlugin:
168
181
  self.protect(server.app)
169
182
  # Events/logs sockets are bound to their session: closed (4401
170
183
  # "session ended") on logout, revoke, disable/delete and expiry.
171
- for name in ("event_socket_manager", "log_socket_manager"):
184
+ # Those of adapter identities are re-checked through the adapter
185
+ # (see startup()).
186
+ for name, permission in (("event_socket_manager", None), ("log_socket_manager", LOGS_READ)):
172
187
  sockets = getattr(server, name, None)
173
188
  if sockets is not None and hasattr(sockets, "set_session_check"):
174
189
  sockets.set_session_check(self.auth_service.is_context_active)
175
190
  self.auth_service.add_change_listener(sockets.request_recheck)
191
+ if hasattr(sockets, "close_ended_sessions") and not any(
192
+ s is sockets for s, _ in self._session_sockets
193
+ ):
194
+ self._session_sockets.append((sockets, permission))
195
+ shell_options = getattr(options, "shell", None)
196
+ interval = getattr(shell_options, "session_check_interval", None)
197
+ if isinstance(interval, (int, float)):
198
+ self._session_check_interval = float(interval)
176
199
  # Remote shell: users mode (ticket + shell:execute, session-bound).
177
200
  set_shell_provider = getattr(server, "set_shell_access_provider", None)
178
201
  if callable(set_shell_provider):
179
202
  set_shell_provider(UsersShellAccess(self.auth_service))
180
203
 
204
+ @property
205
+ def external_socket_check_interval(self) -> float:
206
+ """Seconds between re-checks of events/logs sockets opened through the
207
+ external auth adapter: the server's ``shell.session_check_interval``
208
+ (default 30), capped at 60 like the shell re-check."""
209
+ value = self._session_check_interval
210
+ if not value or value <= 0:
211
+ return DEFAULT_SESSION_CHECK_INTERVAL
212
+ return min(value, MAX_SESSION_CHECK_INTERVAL)
213
+
181
214
  async def startup(self) -> None:
182
- """Seed and start the background session sweep on the running loop."""
215
+ """Seed and start the background tasks on the running loop: the
216
+ session sweep and, with an external auth adapter, the re-check of
217
+ the events/logs sockets opened through it."""
183
218
  await self.ensure_seeded()
219
+ loop = asyncio.get_running_loop()
184
220
  if self._cleanup_task is None or self._cleanup_task.done():
185
- self._cleanup_task = asyncio.get_running_loop().create_task(self._cleanup_loop())
221
+ self._cleanup_task = loop.create_task(self._cleanup_loop())
222
+ if self.auth_service.external_auth and (
223
+ self._external_check_task is None or self._external_check_task.done()
224
+ ):
225
+ self._external_check_task = loop.create_task(self._external_socket_loop())
186
226
 
187
227
  async def shutdown(self) -> None:
188
- """Stop the background session sweep."""
189
- task, self._cleanup_task = self._cleanup_task, None
190
- if task is None:
191
- return
192
- task.cancel()
193
- try:
194
- await task
195
- except (asyncio.CancelledError, RuntimeError):
196
- pass
228
+ """Stop the background tasks."""
229
+ tasks = [self._cleanup_task, self._external_check_task]
230
+ self._cleanup_task = self._external_check_task = None
231
+ for task in tasks:
232
+ if task is None:
233
+ continue
234
+ task.cancel()
235
+ try:
236
+ await task
237
+ except (asyncio.CancelledError, RuntimeError):
238
+ pass
197
239
 
198
240
  def dispose(self) -> None:
199
241
  """Synchronous best-effort stop (prefer :meth:`shutdown`)."""
200
- task, self._cleanup_task = self._cleanup_task, None
201
- if task is not None:
242
+ tasks = [self._cleanup_task, self._external_check_task]
243
+ self._cleanup_task = self._external_check_task = None
244
+ for task in tasks:
245
+ if task is not None:
246
+ try:
247
+ task.cancel()
248
+ except RuntimeError:
249
+ pass # loop already closed
250
+
251
+ async def recheck_external_sockets(self) -> None:
252
+ """Run the external auth adapter again for every events/logs socket
253
+ opened through it (on the snapshot of the request it accepted) and
254
+ close with 4401 ``session ended`` those whose user is gone, another
255
+ user, disabled, or no longer holds the socket's permission
256
+ (``logs:read`` for logs), or when the adapter raises. Sockets with a
257
+ stored session or API token are left alone."""
258
+ checks = []
259
+ for sockets, permission in self._session_sockets:
260
+ async def check(ctx: Any, permission: str | None = permission) -> bool:
261
+ return await self.auth_service.is_external_socket_active(ctx, permission)
262
+
263
+ checks.append(sockets.close_ended_sessions(check))
264
+ if checks:
265
+ await asyncio.gather(*checks)
266
+
267
+ async def _external_socket_loop(self) -> None:
268
+ # One check at a time: the next sleep starts after the previous check
269
+ # finished, so a slow adapter never stacks checks.
270
+ while True:
271
+ await asyncio.sleep(self.external_socket_check_interval)
202
272
  try:
203
- task.cancel()
204
- except RuntimeError:
205
- pass # loop already closed
273
+ await self.recheck_external_sockets()
274
+ except Exception:
275
+ logger.exception("External-auth socket check error")
206
276
 
207
277
  async def _cleanup_loop(self) -> None:
208
278
  interval = max(self.cleanup_interval_ms, 1) / 1000
@@ -225,6 +295,8 @@ class CliUsersBuilder:
225
295
  self._group_store: IGroupStore | None = None
226
296
  self._api_token_store: IApiTokenStore | None = None
227
297
  self._allow_non_expiring_tokens = False
298
+ self._read_only_users = False
299
+ self._read_only_groups = False
228
300
  self._auth_adapter: ExternalAuthAdapter | None = None
229
301
  self._default_admin_password: str | None = None
230
302
  self._session_timeout_ms = DEFAULT_SESSION_TIMEOUT_MS
@@ -270,8 +342,32 @@ class CliUsersBuilder:
270
342
  self._allow_non_expiring_tokens = allow
271
343
  return self
272
344
 
345
+ def set_read_only_users(self, read_only: bool = True) -> CliUsersBuilder:
346
+ """The host application owns the users (e.g. a read-only
347
+ ``IUserStore`` over its own accounts): creating, updating and deleting
348
+ users, password changes and group membership changes answer ``501``
349
+ without calling the stores, no ``root`` user is seeded, and the
350
+ current session reports ``usersReadOnly: true``."""
351
+ self._read_only_users = read_only
352
+ return self
353
+
354
+ def set_read_only_groups(self, read_only: bool = True) -> CliUsersBuilder:
355
+ """The host application owns the groups: creating, updating and
356
+ deleting groups answer ``501`` without calling the store, the built-in
357
+ groups are not seeded, and the current session reports
358
+ ``groupsReadOnly: true``."""
359
+ self._read_only_groups = read_only
360
+ return self
361
+
273
362
  def set_auth_adapter(self, adapter: ExternalAuthAdapter | None) -> CliUsersBuilder:
274
- """Delegate authentication to the host app (see README)."""
363
+ """Delegate authentication to the host app (see README).
364
+
365
+ ``adapter(request)`` returns an :class:`ExternalAuthResult` or
366
+ ``None``, either directly or as an awaitable: plain functions,
367
+ ``async def`` functions and objects with a sync or async ``__call__``
368
+ are all accepted. ``None`` turns external auth off again."""
369
+ if adapter is not None and not callable(adapter):
370
+ raise TypeError("auth adapter must be callable (sync or async)")
275
371
  self._auth_adapter = adapter
276
372
  return self
277
373
 
@@ -359,6 +455,8 @@ class CliUsersBuilder:
359
455
  trust_proxy=self._trust_proxy,
360
456
  allowed_origins=self._allowed_origins,
361
457
  allow_non_expiring_tokens=self._allow_non_expiring_tokens,
458
+ read_only_users=self._read_only_users,
459
+ read_only_groups=self._read_only_groups,
362
460
  ),
363
461
  broadcast_fn=broadcast_fn,
364
462
  auth_adapter=self._auth_adapter,
@@ -0,0 +1,47 @@
1
+ """Routing helpers shared by the users controllers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Callable
6
+
7
+ from fastapi import APIRouter, Depends
8
+
9
+ from ..errors import UsersApiError, UsersApiRoute
10
+
11
+ if TYPE_CHECKING:
12
+ from ..services.auth_service import AuthService
13
+
14
+ USERS_READ_ONLY = "Users are managed by the host application"
15
+ GROUPS_READ_ONLY = "Groups are managed by the host application"
16
+
17
+
18
+ def new_router(prefix: str, tag: str) -> APIRouter:
19
+ return APIRouter(prefix=prefix, tags=[tag], route_class=UsersApiRoute)
20
+
21
+
22
+ def collection(router: APIRouter, method: str, **kwargs: Any) -> Callable[[Callable], Callable]:
23
+ """Register a collection endpoint at both ``<prefix>`` and ``<prefix>/``
24
+ so neither form redirects."""
25
+
26
+ def decorator(func: Callable) -> Callable:
27
+ router.add_api_route("", func, methods=[method], **kwargs)
28
+ router.add_api_route("/", func, methods=[method], include_in_schema=False, **kwargs)
29
+ return func
30
+
31
+ return decorator
32
+
33
+
34
+ def store_write(auth_service: AuthService, *, users: bool = False, groups: bool = False) -> list:
35
+ """Route ``dependencies`` for an endpoint writing to the user and/or group
36
+ store: 501 when that store is read-only (``read_only_users`` /
37
+ ``read_only_groups``, read on every request), before authentication,
38
+ body validation and any store call."""
39
+
40
+ async def guard() -> None:
41
+ options = auth_service.options
42
+ if users and options.read_only_users:
43
+ raise UsersApiError(501, USERS_READ_ONLY)
44
+ if groups and options.read_only_groups:
45
+ raise UsersApiError(501, GROUPS_READ_ONLY)
46
+
47
+ return [Depends(guard)]
@@ -11,7 +11,7 @@ from ..models import CreateGroupRequest, Group, UpdateGroupRequest
11
11
  from ..permissions import GROUPS_CREATE, GROUPS_DELETE, GROUPS_READ, GROUPS_UPDATE
12
12
  from ..services.auth_service import AuthContext, AuthService
13
13
  from ..services.users_service import UsersService
14
- from ._routing import collection, new_router
14
+ from ._routing import collection, new_router, store_write
15
15
 
16
16
 
17
17
  def create_groups_router(
@@ -23,6 +23,9 @@ def create_groups_router(
23
23
  router = new_router("/groups", "groups")
24
24
  group_store = auth_service.group_store
25
25
  user_store = auth_service.user_store
26
+ group_write = store_write(auth_service, groups=True)
27
+ # Membership lives on the users (their ``groups``).
28
+ member_write = store_write(auth_service, users=True)
26
29
 
27
30
  async def load_group(name: str) -> Group:
28
31
  group = await group_store.get_group(name)
@@ -40,7 +43,7 @@ def create_groups_router(
40
43
  async def list_groups(ctx: AuthContext = Depends(get_auth)):
41
44
  return [g.to_dict() for g in await group_store.get_groups()]
42
45
 
43
- @collection(router, "POST", status_code=201)
46
+ @collection(router, "POST", status_code=201, dependencies=group_write)
44
47
  async def create_group(
45
48
  body: CreateGroupRequest,
46
49
  ctx: AuthContext = Depends(require_permission(GROUPS_CREATE)),
@@ -61,7 +64,7 @@ def create_groups_router(
61
64
  raise forbidden(f"missing permission: {GROUPS_READ}")
62
65
  return [u.to_dict() for u in await users_service.group_members(group)]
63
66
 
64
- @router.put("/{name}")
67
+ @router.put("/{name}", dependencies=group_write)
65
68
  async def update_group(
66
69
  name: str,
67
70
  body: UpdateGroupRequest,
@@ -73,7 +76,7 @@ def create_groups_router(
73
76
  )
74
77
  return updated.to_dict()
75
78
 
76
- @router.delete("/{name}", status_code=204)
79
+ @router.delete("/{name}", status_code=204, dependencies=group_write)
77
80
  async def delete_group(
78
81
  name: str,
79
82
  ctx: AuthContext = Depends(require_permission(GROUPS_DELETE)),
@@ -81,7 +84,7 @@ def create_groups_router(
81
84
  await users_service.delete_group(ctx, await load_group(name))
82
85
  return Response(status_code=204)
83
86
 
84
- @router.post("/{name}/members/{id_or_name}", status_code=204)
87
+ @router.post("/{name}/members/{id_or_name}", status_code=204, dependencies=member_write)
85
88
  async def add_member(
86
89
  name: str,
87
90
  id_or_name: str,
@@ -95,7 +98,7 @@ def create_groups_router(
95
98
  await users_service.add_member(ctx, group, user)
96
99
  return Response(status_code=204)
97
100
 
98
- @router.delete("/{name}/members/{id_or_name}", status_code=204)
101
+ @router.delete("/{name}/members/{id_or_name}", status_code=204, dependencies=member_write)
99
102
  async def remove_member(
100
103
  name: str,
101
104
  id_or_name: str,
@@ -17,7 +17,7 @@ from ..models import (
17
17
  from ..permissions import USERS_CREATE, USERS_DELETE, USERS_READ, USERS_UPDATE
18
18
  from ..services.auth_service import AuthContext, AuthService
19
19
  from ..services.users_service import UsersService
20
- from ._routing import collection, new_router
20
+ from ._routing import collection, new_router, store_write
21
21
 
22
22
  MANAGED_BY_HOST = "Authentication is managed by the host application"
23
23
  API_TOKENS_CANNOT_CHANGE_PASSWORDS = "forbidden: API tokens cannot change passwords"
@@ -34,6 +34,7 @@ def create_users_router(
34
34
  router = new_router("/users", "users")
35
35
  user_store = auth_service.user_store
36
36
  external = auth_service.external_auth
37
+ user_write = store_write(auth_service, users=True)
37
38
 
38
39
  async def load_target(id_or_name: str, ctx: AuthContext, permission: str, *, allow_self: bool) -> User:
39
40
  """Resolve the target user, enforcing ``permission`` (or self).
@@ -59,7 +60,7 @@ def create_users_router(
59
60
  users = await users_service.list_users(query, skip, take)
60
61
  return [u.to_dict() for u in users]
61
62
 
62
- @collection(router, "POST", status_code=201)
63
+ @collection(router, "POST", status_code=201, dependencies=user_write)
63
64
  async def create_user(
64
65
  body: CreateUserRequest,
65
66
  ctx: AuthContext = Depends(require_permission(USERS_CREATE)),
@@ -91,7 +92,7 @@ def create_users_router(
91
92
  "permissions": await auth_service.effective_permissions(groups),
92
93
  }
93
94
 
94
- @router.put("/{id_or_name}")
95
+ @router.put("/{id_or_name}", dependencies=user_write)
95
96
  async def update_user(
96
97
  id_or_name: str,
97
98
  body: UpdateUserRequest,
@@ -122,7 +123,7 @@ def create_users_router(
122
123
  )
123
124
  return user.to_dict()
124
125
 
125
- @router.delete("/{id_or_name}", status_code=204)
126
+ @router.delete("/{id_or_name}", status_code=204, dependencies=user_write)
126
127
  async def delete_user(
127
128
  id_or_name: str,
128
129
  ctx: AuthContext = Depends(require_permission(USERS_DELETE)),
@@ -142,7 +143,7 @@ def create_users_router(
142
143
 
143
144
  return router
144
145
 
145
- @router.put("/{id_or_name}/password", status_code=204)
146
+ @router.put("/{id_or_name}/password", status_code=204, dependencies=user_write)
146
147
  async def change_password(
147
148
  id_or_name: str,
148
149
  body: PasswordChangeRequest,
@@ -0,0 +1,60 @@
1
+ """Snapshot of the request an external auth adapter accepted.
2
+
3
+ Sockets opened by adapter identities have no stored session; they are
4
+ re-checked by running the adapter again on a fresh request rebuilt from this
5
+ snapshot: the request that authenticated them (the ``POST
6
+ /sessions/ws-ticket`` request when a ticket was used). Only the request line,
7
+ headers (cookies included), client/server addresses and the app are kept;
8
+ state set by middleware is not.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+
15
+ from starlette.requests import Request
16
+
17
+ #: ASGI scope keys copied into the snapshot.
18
+ _SCOPE_KEYS = (
19
+ "type",
20
+ "asgi",
21
+ "http_version",
22
+ "method",
23
+ "scheme",
24
+ "server",
25
+ "client",
26
+ "root_path",
27
+ "path",
28
+ "raw_path",
29
+ "query_string",
30
+ "app",
31
+ )
32
+
33
+
34
+ class ExternalRequestSnapshot:
35
+ """An immutable copy of an HTTP (or WebSocket) request's scope."""
36
+
37
+ __slots__ = ("_scope",)
38
+
39
+ def __init__(self, scope: dict[str, Any]) -> None:
40
+ self._scope = scope
41
+
42
+ @classmethod
43
+ def capture(cls, request: Any) -> ExternalRequestSnapshot | None:
44
+ """Snapshot ``request`` (anything with an ASGI ``scope``), or ``None``."""
45
+ scope = getattr(request, "scope", None)
46
+ if not isinstance(scope, dict) or scope.get("type") not in ("http", "websocket"):
47
+ return None
48
+ copied = {key: scope[key] for key in _SCOPE_KEYS if key in scope}
49
+ copied["headers"] = [(bytes(k), bytes(v)) for k, v in scope.get("headers") or []]
50
+ return cls(copied)
51
+
52
+ def to_request(self) -> Request:
53
+ """A new request from the snapshot (empty ``state``, no body)."""
54
+ scope = dict(self._scope)
55
+ scope["headers"] = list(self._scope["headers"])
56
+ scope["state"] = {}
57
+ return Request(scope)
58
+
59
+
60
+ __all__ = ["ExternalRequestSnapshot"]
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
  import time
11
11
  import uuid
12
12
  from dataclasses import dataclass, field
13
- from typing import TYPE_CHECKING, Any, Callable, Optional
13
+ from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional, Union
14
14
 
15
15
  if TYPE_CHECKING:
16
16
  from starlette.requests import Request
@@ -319,12 +319,25 @@ class ExternalAuthResult:
319
319
  """Result returned by an external auth adapter.
320
320
 
321
321
  ``is_admin`` adds the built-in ``admin`` group to the user's effective
322
- groups (the adapter's ``user`` object is never mutated).
322
+ groups (the adapter's ``user`` object is never mutated). ``permissions``
323
+ are granted directly by the host (e.g. ``logs:read``), added to those of
324
+ the user's groups, so hosts with their own roles need no group per
325
+ permission. Group names missing from the group store grant nothing.
323
326
  """
324
327
 
325
328
  user: User
326
329
  is_admin: bool = False
330
+ permissions: list[str] | None = None
331
+
327
332
 
333
+ ExternalAuthAdapter = Callable[
334
+ ["Request"],
335
+ Union[Optional[ExternalAuthResult], Awaitable[Optional[ExternalAuthResult]]],
336
+ ]
337
+ """``(request) -> ExternalAuthResult | None``, or an awaitable of it.
328
338
 
329
- # (Request) -> ExternalAuthResult | None (may also be async)
330
- ExternalAuthAdapter = Callable[["Request"], Optional[ExternalAuthResult]]
339
+ Any callable works: a function, an ``async def`` function (to load the user,
340
+ their roles or their disabled state from a database), or an object with a
341
+ sync or async ``__call__``. The plugin awaits the result whenever it is
342
+ awaitable: for requests, ticket issuance and every re-check of open sockets.
343
+ """
@@ -34,6 +34,8 @@ PUBLIC_PATHS: list[tuple[re.Pattern[str], frozenset[str] | None]] = [
34
34
  (re.compile(r"^/api/(qcli|cli|v1/qcli|v1/cli)/versions?/?$"), frozenset({"GET", "HEAD"})),
35
35
  (re.compile(r"^/api/(qcli|cli|v1/qcli|v1/cli)/capabilities/?$"), frozenset({"GET", "HEAD"})),
36
36
  (re.compile(r"^/(api/)?(qcli/)?health(z|/.*)?$"), None),
37
+ # Admin dashboard: which sign-in to show (password form or the host's).
38
+ (re.compile(r"^/api/v1/qcli/auth/mode/?$"), frozenset({"GET", "HEAD"})),
37
39
  ]
38
40
 
39
41
  #: Routes of the users plugin itself — they authenticate in their own
@@ -16,6 +16,7 @@ from dataclasses import dataclass, replace
16
16
  from typing import Any, Awaitable, Callable, Optional, Union
17
17
 
18
18
  from .._http import forwarded_client_ip
19
+ from ..external_request import ExternalRequestSnapshot
19
20
  from ..errors import UsersApiError, forbidden, unauthorized
20
21
  from ..models import (
21
22
  ApiToken,
@@ -102,6 +103,9 @@ class AuthContext:
102
103
  external: bool = False
103
104
  #: Set when authenticated by an API token (then ``session`` is ``None``).
104
105
  api_token: ApiToken | None = None
106
+ #: External adapter identities: the request the adapter accepted (the
107
+ #: ``ws-ticket`` request for sockets), re-run to re-check open sockets.
108
+ external_request: ExternalRequestSnapshot | None = None
105
109
 
106
110
  @property
107
111
  def api_token_id(self) -> str | None:
@@ -164,6 +168,12 @@ class AuthServiceOptions:
164
168
  ticket_ttl_ms: int = TICKET_TTL_MS
165
169
  #: Allow API tokens that never expire (``expiresInDays: null``).
166
170
  allow_non_expiring_tokens: bool = False
171
+ #: The host owns the users: user writes (create, update, delete, password,
172
+ #: group membership) answer 501 and no ``root`` user is seeded.
173
+ read_only_users: bool = False
174
+ #: The host owns the groups: group writes answer 501 and the built-in
175
+ #: groups are not seeded.
176
+ read_only_groups: bool = False
167
177
 
168
178
 
169
179
  class AuthService:
@@ -535,7 +545,8 @@ class AuthService:
535
545
  """Whether the session behind an authenticated WebSocket is still
536
546
  alive (not logged out, revoked, expired; user neither disabled nor
537
547
  deleted). Never extends the session. Adapter identities have no
538
- stored session and stay valid."""
548
+ stored session and stay valid here: they are re-checked through the
549
+ adapter (:meth:`is_external_socket_active`)."""
539
550
  if not isinstance(ctx, AuthContext):
540
551
  return True
541
552
  if ctx.external:
@@ -561,6 +572,8 @@ class AuthService:
561
572
  "loginTime": session.created_at,
562
573
  "lastActivity": session.last_activity,
563
574
  "expiresAt": self.expires_at(session),
575
+ "usersReadOnly": bool(self.options.read_only_users),
576
+ "groupsReadOnly": bool(self.options.read_only_groups),
564
577
  }
565
578
 
566
579
  # ------------------------------------------------------------------
@@ -646,13 +659,31 @@ class AuthService:
646
659
  user = await self.user_store.get_user(record.user_id)
647
660
  return record.to_view(user.name if user else "")
648
661
 
649
- async def authenticate_external(self, request: Any) -> AuthContext:
662
+ async def run_auth_adapter(self, request: Any) -> ExternalAuthResult | None:
663
+ """Call the external auth adapter on ``request``, awaiting its result
664
+ when the adapter is async (or returns an awaitable)."""
650
665
  assert self.auth_adapter is not None
651
666
  result = self.auth_adapter(request)
652
667
  if inspect.isawaitable(result):
653
668
  result = await result
669
+ return result
670
+
671
+ async def authenticate_external(self, request: Any) -> AuthContext:
672
+ """Authenticate ``request`` through the external auth adapter.
673
+
674
+ 401 when the adapter returns no user, 401 ``account disabled`` for a
675
+ disabled user. The context keeps a snapshot of ``request`` so open
676
+ sockets can be re-checked against it (:meth:`revalidate_external`)."""
677
+ result = await self.run_auth_adapter(request)
654
678
  if not isinstance(result, ExternalAuthResult) or result.user is None:
655
679
  raise unauthorized()
680
+ return await self._external_context(result, ExternalRequestSnapshot.capture(request))
681
+
682
+ async def _external_context(
683
+ self, result: ExternalAuthResult, request: ExternalRequestSnapshot | None,
684
+ ) -> AuthContext:
685
+ if result.user.disabled:
686
+ raise unauthorized(ACCOUNT_DISABLED)
656
687
  groups = list(result.user.groups or [])
657
688
  if result.is_admin and not any(g.lower() == ADMIN_GROUP for g in groups):
658
689
  groups.append(ADMIN_GROUP)
@@ -666,14 +697,60 @@ class AuthService:
666
697
  created_at=now,
667
698
  last_activity=now,
668
699
  )
700
+ permissions = await self.effective_permissions(groups)
701
+ if result.permissions:
702
+ permissions = merge_permissions(permissions, result.permissions)
669
703
  return AuthContext(
670
704
  user=user,
671
705
  groups=groups,
672
- permissions=await self.effective_permissions(groups),
706
+ permissions=permissions,
673
707
  session=session,
674
708
  external=True,
709
+ external_request=request,
675
710
  )
676
711
 
712
+ async def revalidate_external(self, ctx: AuthContext, connection: Any = None) -> AuthContext | None:
713
+ """Re-run the external auth adapter for an adapter identity on a request
714
+ rebuilt from the snapshot of the request it was authenticated with
715
+ (``connection`` when there is no snapshot).
716
+
717
+ ``None`` when there is nothing to re-run it on, or the adapter returns
718
+ no user, another user or a disabled user, or raises."""
719
+ if not ctx.external or self.auth_adapter is None:
720
+ return None
721
+ if ctx.external_request is not None:
722
+ request = ctx.external_request.to_request()
723
+ snapshot = ctx.external_request
724
+ elif connection is not None:
725
+ request = connection
726
+ snapshot = ExternalRequestSnapshot.capture(connection)
727
+ else:
728
+ return None
729
+ try:
730
+ result = await self.run_auth_adapter(request)
731
+ except Exception:
732
+ logger.warning("External auth adapter failed while re-validating user %s",
733
+ ctx.user.id, exc_info=True)
734
+ return None
735
+ if (
736
+ not isinstance(result, ExternalAuthResult)
737
+ or result.user is None
738
+ or result.user.id != ctx.user.id
739
+ or result.user.disabled
740
+ ):
741
+ return None
742
+ return await self._external_context(result, snapshot)
743
+
744
+ async def is_external_socket_active(self, ctx: Any, permission: str | None = None) -> bool:
745
+ """Whether an adapter identity behind an events/logs socket is still
746
+ authenticated by the adapter (same user, enabled) and holds
747
+ ``permission``. ``True`` for every other identity: those are checked
748
+ against their stored session or token (:meth:`is_context_active`)."""
749
+ if not isinstance(ctx, AuthContext) or not ctx.external:
750
+ return True
751
+ current = await self.revalidate_external(ctx)
752
+ return current is not None and (permission is None or current.can(permission))
753
+
677
754
  @staticmethod
678
755
  def ensure_password_changed(ctx: AuthContext) -> None:
679
756
  if ctx.must_change_password:
@@ -829,17 +906,19 @@ class AuthService:
829
906
  """Seed the built-in groups and (unless external auth) the root user.
830
907
 
831
908
  Without a configured password a random one is generated, logged once
832
- and the root account must change it at first login."""
833
- if not await self.group_store.get_group(ADMIN_GROUP):
834
- await self.group_store.create_group(
835
- ADMIN_GROUP, "Administrators", ["*"], built_in=True,
836
- )
837
- if not await self.group_store.get_group(USERS_GROUP):
838
- await self.group_store.create_group(
839
- USERS_GROUP, "Default group for new accounts",
840
- list(DEFAULT_USERS_GROUP_PERMISSIONS), built_in=True,
841
- )
842
- if self.external_auth:
909
+ and the root account must change it at first login. Read-only stores
910
+ belong to the host application: nothing is seeded into them."""
911
+ if not self.options.read_only_groups:
912
+ if not await self.group_store.get_group(ADMIN_GROUP):
913
+ await self.group_store.create_group(
914
+ ADMIN_GROUP, "Administrators", ["*"], built_in=True,
915
+ )
916
+ if not await self.group_store.get_group(USERS_GROUP):
917
+ await self.group_store.create_group(
918
+ USERS_GROUP, "Default group for new accounts",
919
+ list(DEFAULT_USERS_GROUP_PERMISSIONS), built_in=True,
920
+ )
921
+ if self.external_auth or self.options.read_only_users:
843
922
  return
844
923
  if len(await self.user_store.get_users()) != 0:
845
924
  return
@@ -300,7 +300,9 @@ class UsersService:
300
300
  async def delete_group(self, ctx: AuthContext | None, group: Group) -> None:
301
301
  if self._is_built_in(group):
302
302
  raise conflict(f"cannot delete built-in group: {group.name}")
303
- for user in await self.group_members(group):
303
+ # A read-only user store keeps its memberships (the host owns them).
304
+ members = [] if self.auth.options.read_only_users else await self.group_members(group)
305
+ for user in members:
304
306
  await self.users.update_user(
305
307
  user.id,
306
308
  groups=[g for g in user.groups if g.lower() != group.name.lower()],
@@ -4,9 +4,9 @@ Registered on the CLI server when the plugin is mounted. An open shell is
4
4
  bound to the session that opened it: the server re-checks it periodically and
5
5
  on every session/user/group change, and closes it (4401 ``session ended``)
6
6
  after logout, expiry, revoke, disable/delete or loss of ``shell:execute``.
7
- Identities from an external auth adapter are re-validated by calling the
8
- adapter again with the shell's WebSocket request, so the adapter must be able
9
- to authenticate it from its headers/cookies.
7
+ Identities from an external auth adapter are re-validated by running the
8
+ adapter again on a snapshot of the request it accepted (the ``ws-ticket``
9
+ request), with the same headers and cookies.
10
10
  """
11
11
 
12
12
  from __future__ import annotations
@@ -32,8 +32,8 @@ class UsersShellPrincipal:
32
32
  user_name: str
33
33
  session_id: str | None
34
34
  context: AuthContext
35
- #: The shell's WebSocket: adapter identities are re-validated by calling
36
- #: the external auth adapter again with it.
35
+ #: The shell's WebSocket: adapter identities without a request snapshot
36
+ #: are re-validated by calling the external auth adapter again with it.
37
37
  connection: Any = None
38
38
 
39
39
 
@@ -104,17 +104,13 @@ class UsersShellAccess:
104
104
  return True
105
105
 
106
106
  async def _adapter_active(self, principal: UsersShellPrincipal) -> bool | str:
107
- """Adapter identities have no stored session: ask the external auth
108
- adapter again with the shell's WebSocket (its headers and cookies).
109
- ``None`` or an exception ends the shell; a different user or one
110
- without ``shell:execute`` too."""
111
- if principal.connection is None or not self.auth.external_auth:
112
- return False
113
- try:
114
- fresh = await self.auth.authenticate_external(principal.connection)
115
- except Exception:
116
- return False
117
- if fresh.user.id != principal.user_id or fresh.must_change_password:
107
+ """Adapter identities have no stored session: run the external auth
108
+ adapter again on the snapshot of the request it accepted (the
109
+ ``ws-ticket`` request; the shell's WebSocket when there is none).
110
+ ``None``, an exception, a different or disabled user end the shell;
111
+ a user without ``shell:execute`` too (``permission removed``)."""
112
+ fresh = await self.auth.revalidate_external(principal.context, principal.connection)
113
+ if fresh is None or fresh.must_change_password:
118
114
  return False
119
115
  if not fresh.can(SHELL_PERMISSION):
120
116
  return PERMISSION_REMOVED
@@ -1,25 +0,0 @@
1
- """Routing helpers shared by the users controllers."""
2
-
3
- from __future__ import annotations
4
-
5
- from typing import Any, Callable
6
-
7
- from fastapi import APIRouter
8
-
9
- from ..errors import UsersApiRoute
10
-
11
-
12
- def new_router(prefix: str, tag: str) -> APIRouter:
13
- return APIRouter(prefix=prefix, tags=[tag], route_class=UsersApiRoute)
14
-
15
-
16
- def collection(router: APIRouter, method: str, **kwargs: Any) -> Callable[[Callable], Callable]:
17
- """Register a collection endpoint at both ``<prefix>`` and ``<prefix>/``
18
- so neither form redirects."""
19
-
20
- def decorator(func: Callable) -> Callable:
21
- router.add_api_route("", func, methods=[method], **kwargs)
22
- router.add_api_route("/", func, methods=[method], include_in_schema=False, **kwargs)
23
- return func
24
-
25
- return decorator