qodalis-cli-server-plugin-users 1.0.0b24__tar.gz → 1.0.0b26__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.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/PKG-INFO +1 -1
  2. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/pyproject.toml +1 -1
  3. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/cli_users_builder.py +36 -0
  4. qodalis_cli_server_plugin_users-1.0.0b26/qodalis_cli_users/controllers/link_controller.py +80 -0
  5. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/controllers/tokens_controller.py +82 -47
  6. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/server_protection.py +1 -1
  7. qodalis_cli_server_plugin_users-1.0.0b26/qodalis_cli_users/services/link_service.py +322 -0
  8. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/.gitignore +0 -0
  9. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/LICENSE +0 -0
  10. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/__init__.py +0 -0
  11. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/_http.py +0 -0
  12. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/controllers/__init__.py +0 -0
  13. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/controllers/_routing.py +0 -0
  14. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/controllers/groups_controller.py +0 -0
  15. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/controllers/sessions_controller.py +0 -0
  16. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/controllers/users_controller.py +0 -0
  17. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/errors.py +0 -0
  18. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/external_request.py +0 -0
  19. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/middleware/__init__.py +0 -0
  20. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/middleware/auth_middleware.py +0 -0
  21. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/models.py +0 -0
  22. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/permissions.py +0 -0
  23. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/services/__init__.py +0 -0
  24. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/services/auth_service.py +0 -0
  25. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/services/password_hasher.py +0 -0
  26. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/services/users_service.py +0 -0
  27. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/shell_access.py +0 -0
  28. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/stores/__init__.py +0 -0
  29. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/stores/in_memory_api_token_store.py +0 -0
  30. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/stores/in_memory_audit_store.py +0 -0
  31. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/stores/in_memory_credential_store.py +0 -0
  32. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/stores/in_memory_group_store.py +0 -0
  33. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/stores/in_memory_session_store.py +0 -0
  34. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/stores/in_memory_user_store.py +0 -0
  35. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/qodalis_cli_users/stores/interfaces.py +0 -0
  36. {qodalis_cli_server_plugin_users-1.0.0b24 → qodalis_cli_server_plugin_users-1.0.0b26}/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.0b24
3
+ Version: 1.0.0b26
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.0b24"
7
+ version = "1.0.0b26"
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"
@@ -31,6 +31,7 @@ from qodalis_cli_audit import CliAuditBuilder, CliAuditPlugin
31
31
  from qodalis_cli_server_abstractions.events import ICliEventBus
32
32
 
33
33
  from .controllers.groups_controller import create_groups_router
34
+ from .controllers.link_controller import create_link_router
34
35
  from .controllers.sessions_controller import create_sessions_router
35
36
  from .controllers.tokens_controller import create_tokens_router
36
37
  from .controllers.users_controller import create_users_router
@@ -51,6 +52,12 @@ from .services.auth_service import (
51
52
  AuthServiceOptions,
52
53
  BroadcastFn,
53
54
  )
55
+ from .services.link_service import (
56
+ DEFAULT_LINK_APPROVAL_URL,
57
+ LinkRateLimiter,
58
+ LinkService,
59
+ validate_link_approval_url,
60
+ )
54
61
  from .services.users_service import UsersService
55
62
  from .stores.in_memory_api_token_store import InMemoryApiTokenStore
56
63
  from .stores.in_memory_credential_store import InMemoryCredentialStore
@@ -117,6 +124,9 @@ class CliUsersPlugin:
117
124
  #: The audit plugin the users plugin records its events in, mounted with
118
125
  #: it (or joining the audit plugin the host mounted, see :meth:`on_mount`).
119
126
  audit_plugin: Optional[CliAuditPlugin] = None
127
+ #: Link requests (``/link``): terminals linked through the browser.
128
+ link_service: Optional[LinkService] = None
129
+ _link_limiter: Optional[LinkRateLimiter] = field(default=None, repr=False)
120
130
  _seeded: bool = field(default=False, repr=False)
121
131
  _seed_lock: Optional[asyncio.Lock] = field(default=None, repr=False)
122
132
 
@@ -311,10 +321,21 @@ class CliUsersPlugin:
311
321
  except Exception:
312
322
  logger.exception("External-auth socket check error")
313
323
 
324
+ def sweep_links(self) -> None:
325
+ """Drop expired link requests and stale rate-limit windows."""
326
+ try:
327
+ if self.link_service is not None:
328
+ self.link_service.sweep()
329
+ if self._link_limiter is not None:
330
+ self._link_limiter.sweep()
331
+ except Exception:
332
+ logger.exception("Link request cleanup error")
333
+
314
334
  async def _cleanup_loop(self) -> None:
315
335
  interval = max(self.cleanup_interval_ms, 1) / 1000
316
336
  while True:
317
337
  await asyncio.sleep(interval)
338
+ self.sweep_links()
318
339
  try:
319
340
  await self.auth_service.cleanup_sessions()
320
341
  except Exception:
@@ -347,6 +368,7 @@ class CliUsersBuilder:
347
368
  self._max_login_attempts = DEFAULT_MAX_LOGIN_ATTEMPTS
348
369
  self._lockout_ms = DEFAULT_LOCKOUT_MS
349
370
  self._cleanup_interval_ms = DEFAULT_CLEANUP_INTERVAL_MS
371
+ self._link_approval_url = DEFAULT_LINK_APPROVAL_URL
350
372
 
351
373
  def set_user_store(self, store: IUserStore) -> CliUsersBuilder:
352
374
  self._user_store = store
@@ -398,6 +420,15 @@ class CliUsersBuilder:
398
420
  self._read_only_groups = read_only
399
421
  return self
400
422
 
423
+ def set_link_approval_url(self, url: str) -> CliUsersBuilder:
424
+ """The page where users approve a terminal's link request
425
+ (``server add`` in the web CLI): an http(s) URL or a root-relative
426
+ path, ``{code}`` replaced by the code (otherwise ``?code=`` is
427
+ appended). Defaults to the admin dashboard's ``/qcli/admin/link``.
428
+ Raises ``ValueError`` for anything else (e.g. ``//host``)."""
429
+ self._link_approval_url = validate_link_approval_url(url)
430
+ return self
431
+
401
432
  def set_auth_adapter(self, adapter: ExternalAuthAdapter | None) -> CliUsersBuilder:
402
433
  """Delegate authentication to the host app (see README).
403
434
 
@@ -561,4 +592,9 @@ class CliUsersBuilder:
561
592
  auth_service, users_service, get_auth, require_permission,
562
593
  ))
563
594
  router.include_router(create_tokens_router(auth_service, get_auth))
595
+ plugin.link_service = LinkService(auth_service, self._link_approval_url)
596
+ plugin._link_limiter = LinkRateLimiter()
597
+ router.include_router(create_link_router(
598
+ auth_service, plugin.link_service, get_auth, plugin._link_limiter,
599
+ ))
564
600
  return plugin
@@ -0,0 +1,80 @@
1
+ """Link requests controller — ``/link`` (``server add`` in the web CLI,
2
+ through the browser).
3
+
4
+ - ``POST /link`` a terminal asks to be linked (public, rate limited)
5
+ → ``201 {linkId, userCode, verificationUrl, expiresIn, interval}``
6
+ - ``GET /link/{linkId}`` the terminal polls (public) → ``{status}``, the token
7
+ once approved; 404 ``{"status": "expired"}``
8
+ - ``GET /link/code/{userCode}`` the approval page reads the request (signed in)
9
+ - ``POST /link/code/{userCode}/approve`` creates the approver's API token (session only)
10
+ - ``POST /link/code/{userCode}/deny`` → 204
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from typing import Callable
17
+
18
+ from fastapi import APIRouter, Depends, Request, Response
19
+ from fastapi.responses import JSONResponse
20
+
21
+ from ..errors import UsersApiError, bad_request
22
+ from ..services.auth_service import AuthContext, AuthService
23
+ from ..services.link_service import LinkRateLimiter, LinkService
24
+ from ._routing import collection, new_router
25
+
26
+ TOO_MANY_LINK_REQUESTS = "too many link requests, try again later"
27
+
28
+
29
+ async def _json_body(request: Request) -> dict:
30
+ raw = await request.body()
31
+ if not raw:
32
+ return {}
33
+ try:
34
+ body = json.loads(raw)
35
+ except ValueError as exc:
36
+ raise bad_request("invalid request body") from exc
37
+ if not isinstance(body, dict):
38
+ raise bad_request("invalid request body")
39
+ return body
40
+
41
+
42
+ def create_link_router(
43
+ auth_service: AuthService,
44
+ links: LinkService,
45
+ get_auth: Callable,
46
+ limiter: LinkRateLimiter,
47
+ ) -> APIRouter:
48
+ router = new_router("/link", "link")
49
+
50
+ @collection(router, "POST", status_code=201)
51
+ async def create_link(request: Request):
52
+ ip = auth_service.client_ip(request)
53
+ if not limiter.try_acquire(ip):
54
+ raise UsersApiError(429, TOO_MANY_LINK_REQUESTS)
55
+ body = await _json_body(request)
56
+ origin = request.headers.get("origin") or None
57
+ return links.create(body, origin, ip)
58
+
59
+ # /code/... before /{linkId}
60
+ @router.get("/code/{code}")
61
+ async def view_link(code: str, ctx: AuthContext = Depends(get_auth)):
62
+ return links.view(code)
63
+
64
+ @router.post("/code/{code}/approve")
65
+ async def approve_link(code: str, ctx: AuthContext = Depends(get_auth)):
66
+ return await links.approve(ctx, code)
67
+
68
+ @router.post("/code/{code}/deny", status_code=204)
69
+ async def deny_link(code: str, ctx: AuthContext = Depends(get_auth)):
70
+ await links.deny(ctx, code)
71
+ return Response(status_code=204)
72
+
73
+ @router.get("/{link_id}")
74
+ async def poll_link(link_id: str):
75
+ result = links.poll(link_id)
76
+ if result is None:
77
+ return JSONResponse(status_code=404, content={"status": "expired"})
78
+ return JSONResponse(content=result, headers={"Cache-Control": "no-store"})
79
+
80
+ return router
@@ -53,7 +53,7 @@ def _expires_at(body: CreateApiTokenRequest, allow_never: bool, now: int) -> int
53
53
  return now + days * DAY_MS
54
54
 
55
55
 
56
- def _scope(ctx: AuthContext, raw: Any) -> list[str] | None:
56
+ def scope_permissions(ctx: AuthContext, raw: Any) -> list[str] | None:
57
57
  """``None`` (omitted/null) = unscoped; ``[]`` = an empty scope. Field
58
58
  errors (400) are raised before the coverage check (403)."""
59
59
  if raw is None:
@@ -67,6 +67,82 @@ def _scope(ctx: AuthContext, raw: Any) -> list[str] | None:
67
67
  return perms
68
68
 
69
69
 
70
+ def ensure_can_create_tokens(ctx: AuthContext) -> None:
71
+ """Only a signed-in session creates tokens: 403 for API tokens (a leaked
72
+ token must not mint more), 501 for external auth (no sessions)."""
73
+ if ctx.api_token is not None:
74
+ raise forbidden(API_TOKENS_CANNOT_CREATE)
75
+ if ctx.session is None or ctx.external:
76
+ raise UsersApiError(501, MANAGED_BY_HOST)
77
+
78
+
79
+ async def revoke_api_token(auth_service: AuthService, ctx: AuthContext, record: ApiToken) -> None:
80
+ """Delete an API token as ``ctx`` (``DELETE /tokens/{id}`` and link
81
+ approvals the terminal can no longer collect); audited
82
+ (``token_revoked``) and published (``token:revoked``)."""
83
+ await auth_service.api_token_store.delete_token(record.id)
84
+ owner = await auth_service.user_store.get_user(record.user_id)
85
+ # The audit also notifies change listeners: sockets opened with this
86
+ # token are re-checked and closed (4401 "session ended").
87
+ await auth_service.audit(
88
+ "token_revoked", owner.name if owner else record.user_id,
89
+ details=f"{record.name} ({record.id})",
90
+ actor=ctx.user.name, actor_id=ctx.user.id, user_id=record.user_id,
91
+ metadata={"tokenId": record.id, "tokenName": record.name},
92
+ )
93
+ await auth_service.publish("token:revoked", {
94
+ "tokenId": record.id, "name": record.name, "userId": record.user_id, "actor": ctx.user.name,
95
+ }, permission=TOKENS_READ, user_id=record.user_id)
96
+
97
+
98
+ def default_token_expiry(now: int | None = None) -> int:
99
+ """Expiry of a token created without ``expiresInDays`` (90 days)."""
100
+ return (now if now is not None else now_ms()) + DEFAULT_EXPIRES_IN_DAYS * DAY_MS
101
+
102
+
103
+ async def create_api_token(
104
+ auth_service: AuthService,
105
+ ctx: AuthContext,
106
+ name: str,
107
+ permissions: list[str] | None,
108
+ expires_at: int | None,
109
+ ) -> tuple[str, ApiToken]:
110
+ """Create an API token for the caller (``POST /tokens`` and link
111
+ approvals): the name is unique per user (409), at most
112
+ ``MAX_TOKENS_PER_USER`` unexpired tokens (400); audited
113
+ (``token_created``) and published (``token:created``). The caller
114
+ validated the session, the name, the expiry and the scope. Returns the
115
+ raw token (shown once) and the stored record."""
116
+ store = auth_service.api_token_store
117
+ now = now_ms()
118
+ existing = await store.get_tokens(ctx.user.id)
119
+ if any(t.name.lower() == name.lower() for t in existing):
120
+ raise conflict(f"token '{name}' already exists")
121
+ # Expired tokens stay listed but do not count toward the limit.
122
+ if sum(1 for t in existing if not t.is_expired(now)) >= MAX_TOKENS_PER_USER:
123
+ raise bad_request(f"a user may have at most {MAX_TOKENS_PER_USER} tokens")
124
+ token = auth_service.generate_api_token()
125
+ record = await store.create_token(ApiToken(
126
+ id=uuid.uuid4().hex,
127
+ user_id=ctx.user.id,
128
+ name=name,
129
+ token_hash=hash_token(token),
130
+ created_at=now,
131
+ expires_at=expires_at,
132
+ permissions=permissions,
133
+ ))
134
+ await auth_service.audit(
135
+ "token_created", ctx.user.name,
136
+ details=f"{record.name} ({record.id})",
137
+ actor=ctx.user.name, actor_id=ctx.user.id, user_id=ctx.user.id,
138
+ metadata={"tokenId": record.id, "tokenName": record.name},
139
+ )
140
+ await auth_service.publish("token:created", {
141
+ "tokenId": record.id, "name": record.name, "userId": record.user_id, "actor": ctx.user.name,
142
+ }, permission=TOKENS_READ, user_id=record.user_id)
143
+ return token, record
144
+
145
+
70
146
  def create_tokens_router(
71
147
  auth_service: AuthService,
72
148
  get_auth: Callable,
@@ -87,40 +163,11 @@ def create_tokens_router(
87
163
 
88
164
  @collection(router, "POST", status_code=201)
89
165
  async def create_token(body: CreateApiTokenRequest, ctx: AuthContext = Depends(get_auth)):
90
- # A leaked token must not be able to mint more tokens.
91
- if ctx.api_token is not None:
92
- raise forbidden(API_TOKENS_CANNOT_CREATE)
93
- if ctx.session is None or ctx.external:
94
- raise UsersApiError(501, MANAGED_BY_HOST)
166
+ ensure_can_create_tokens(ctx)
95
167
  name = _validate_name(body.name)
96
- now = now_ms()
97
- expires_at = _expires_at(body, auth_service.options.allow_non_expiring_tokens, now)
98
- permissions = _scope(ctx, body.permissions)
99
- existing = await store.get_tokens(ctx.user.id)
100
- if any(t.name.lower() == name.lower() for t in existing):
101
- raise conflict(f"token '{name}' already exists")
102
- # Expired tokens stay listed but do not count toward the limit.
103
- if sum(1 for t in existing if not t.is_expired(now)) >= MAX_TOKENS_PER_USER:
104
- raise bad_request(f"a user may have at most {MAX_TOKENS_PER_USER} tokens")
105
- token = auth_service.generate_api_token()
106
- record = await store.create_token(ApiToken(
107
- id=uuid.uuid4().hex,
108
- user_id=ctx.user.id,
109
- name=name,
110
- token_hash=hash_token(token),
111
- created_at=now,
112
- expires_at=expires_at,
113
- permissions=permissions,
114
- ))
115
- await auth_service.audit(
116
- "token_created", ctx.user.name,
117
- details=f"{record.name} ({record.id})",
118
- actor=ctx.user.name, actor_id=ctx.user.id, user_id=ctx.user.id,
119
- metadata={"tokenId": record.id, "tokenName": record.name},
120
- )
121
- await auth_service.publish("token:created", {
122
- "tokenId": record.id, "name": record.name, "userId": record.user_id, "actor": ctx.user.name,
123
- }, permission=TOKENS_READ, user_id=record.user_id)
168
+ expires_at = _expires_at(body, auth_service.options.allow_non_expiring_tokens, now_ms())
169
+ permissions = scope_permissions(ctx, body.permissions)
170
+ token, record = await create_api_token(auth_service, ctx, name, permissions, expires_at)
124
171
  return {"token": token, "apiToken": record.to_view(ctx.user.name)}
125
172
 
126
173
  @router.delete("/{token_id}", status_code=204)
@@ -128,19 +175,7 @@ def create_tokens_router(
128
175
  record = await store.get_token(token_id)
129
176
  if record is None or (record.user_id != ctx.user.id and not ctx.can(TOKENS_REVOKE)):
130
177
  raise not_found("token not found")
131
- await store.delete_token(record.id)
132
- owner = await auth_service.user_store.get_user(record.user_id)
133
- # The audit also notifies change listeners: sockets opened with this
134
- # token are re-checked and closed (4401 "session ended").
135
- await auth_service.audit(
136
- "token_revoked", owner.name if owner else record.user_id,
137
- details=f"{record.name} ({record.id})",
138
- actor=ctx.user.name, actor_id=ctx.user.id, user_id=record.user_id,
139
- metadata={"tokenId": record.id, "tokenName": record.name},
140
- )
141
- await auth_service.publish("token:revoked", {
142
- "tokenId": record.id, "name": record.name, "userId": record.user_id, "actor": ctx.user.name,
143
- }, permission=TOKENS_READ, user_id=record.user_id)
178
+ await revoke_api_token(auth_service, ctx, record)
144
179
  return Response(status_code=204)
145
180
 
146
181
  return router
@@ -40,7 +40,7 @@ PUBLIC_PATHS: list[tuple[re.Pattern[str], frozenset[str] | None]] = [
40
40
 
41
41
  #: Routes of the users plugin itself — they authenticate in their own
42
42
  #: dependencies (with CSRF and password-change gating).
43
- SELF_PROTECTED = re.compile(r"^/api/v1/qcli/(sessions|users|groups|tokens)(/.*)?$")
43
+ SELF_PROTECTED = re.compile(r"^/api/v1/qcli/(sessions|users|groups|tokens|link)(/.*)?$")
44
44
 
45
45
  #: HTTP permission rules, first match wins: (path, methods or None, permission).
46
46
  HTTP_RULES: list[Rule] = [
@@ -0,0 +1,322 @@
1
+ """Link requests: a terminal (``server add`` in the web CLI) asks to be linked
2
+ and a signed-in user approves it in a browser, like the OAuth device flow
3
+ (spec: web-cli ``docs/superpowers/specs/2026-11-12-server-linking-design.md``).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import hashlib
10
+ import hmac
11
+ import re
12
+ import secrets
13
+ from collections import OrderedDict, deque
14
+ from dataclasses import dataclass
15
+ from typing import Any, Callable, Optional
16
+ from urllib.parse import quote
17
+
18
+ from ..errors import UsersApiError, bad_request, not_found
19
+ from ..models import now_ms
20
+ from ..validation import validate_permissions
21
+ from .auth_service import AuthContext, AuthService
22
+
23
+ #: Seconds a link request waits for its approval.
24
+ LINK_EXPIRES_IN_SECONDS = 600
25
+ #: Seconds between two polls of the terminal.
26
+ LINK_POLL_INTERVAL_SECONDS = 2
27
+ #: Pending requests kept at most; the oldest is dropped when full.
28
+ MAX_PENDING_LINKS = 100
29
+ #: The approval page of the admin dashboard.
30
+ DEFAULT_LINK_APPROVAL_URL = "/qcli/admin/link"
31
+ #: Link requests created per client address and minute at most.
32
+ LINK_CREATE_RATE_LIMIT = 10
33
+ LINK_CREATE_RATE_WINDOW_MS = 60_000
34
+
35
+ CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
36
+ CODE_LENGTH = 8
37
+ MAX_CLIENT_LENGTH = 100
38
+ TOKEN_NAME_MAX = 64
39
+ #: Numbered names tried when ``link <client>`` is taken.
40
+ MAX_NAME_SUFFIX = 20
41
+ NOT_FOUND = "link request not found or expired"
42
+
43
+ _APPROVAL_URL_RE = re.compile(r"^(https?://\S+|/(?![/\\])\S*)$")
44
+ _CONTROL_RE = re.compile(r"[\u0000-\u001f\u007f]")
45
+ _TOKEN_NAME_INVALID = re.compile(r"[^A-Za-z0-9._ -]")
46
+ _CODE_SEPARATORS = re.compile(r"[\s-]")
47
+
48
+
49
+ def validate_link_approval_url(url: Any) -> str:
50
+ """An http(s) URL or a root-relative path (not ``//host``)."""
51
+ if not isinstance(url, str) or not _APPROVAL_URL_RE.match(url):
52
+ raise ValueError("[users] link_approval_url must be an http(s) URL or a root-relative path")
53
+ return url
54
+
55
+
56
+ def normalize_user_code(code: str) -> str:
57
+ """Upper case without dashes and spaces (``abcd-2345`` → ``ABCD2345``)."""
58
+ return _CODE_SEPARATORS.sub("", code).upper()
59
+
60
+
61
+ def _hash_code(code: str) -> bytes:
62
+ return hashlib.sha256(normalize_user_code(code).encode("utf-8")).digest()
63
+
64
+
65
+ def _format_code(code: str) -> str:
66
+ return f"{code[:4]}-{code[4:]}"
67
+
68
+
69
+ def link_token_name(client: str, suffix: int = 0) -> str:
70
+ """A token name from a client name: ``link <client>``, ``[A-Za-z0-9._ -]``
71
+ only, at most 64 characters; ``suffix`` n > 0 appends `` n+1``."""
72
+ tail = f" {suffix + 1}" if suffix > 0 else ""
73
+ base = _TOKEN_NAME_INVALID.sub("-", f"link {client}").strip()
74
+ return base[: TOKEN_NAME_MAX - len(tail)].rstrip() + tail
75
+
76
+
77
+ def link_verification_url(approval_url: str, user_code: str) -> str:
78
+ """Where the approval page is: ``{code}`` replaced, otherwise ``?code=``
79
+ (or ``&code=``) appended."""
80
+ code = quote(user_code, safe="")
81
+ if "{code}" in approval_url:
82
+ return approval_url.replace("{code}", code)
83
+ return f"{approval_url}{'&' if '?' in approval_url else '?'}code={code}"
84
+
85
+
86
+ @dataclass
87
+ class LinkRequest:
88
+ link_id: str
89
+ #: sha256 of the normalised user code.
90
+ code_hash: bytes
91
+ user_code: str
92
+ client: str
93
+ permissions: Optional[list[str]]
94
+ origin: Optional[str]
95
+ remote_address: Optional[str]
96
+ created_at: int
97
+ expires_at: int
98
+ status: str = "pending" # pending | approving | approved | denied
99
+ token: Optional[str] = None
100
+ user_name: Optional[str] = None
101
+ token_expires_at: Optional[int] = None
102
+
103
+
104
+ class LinkRateLimiter:
105
+ """At most ``limit`` link requests per client address and window."""
106
+
107
+ def __init__(self, limit: int = LINK_CREATE_RATE_LIMIT, window_ms: int = LINK_CREATE_RATE_WINDOW_MS,
108
+ now: Callable[[], int] = now_ms, max_keys: int = 10_000) -> None:
109
+ self.limit = limit
110
+ self.window_ms = window_ms
111
+ self._now = now
112
+ self._max_keys = max_keys
113
+ self._hits: OrderedDict[str, deque[int]] = OrderedDict()
114
+
115
+ def try_acquire(self, key: str) -> bool:
116
+ now = self._now()
117
+ window = self._hits.get(key)
118
+ if window is None:
119
+ window = deque()
120
+ self._hits[key] = window
121
+ while len(self._hits) > self._max_keys:
122
+ self._hits.popitem(last=False)
123
+ while window and window[0] <= now - self.window_ms:
124
+ window.popleft()
125
+ if len(window) >= self.limit:
126
+ return False
127
+ window.append(now)
128
+ return True
129
+
130
+ def sweep(self) -> None:
131
+ cutoff = self._now() - self.window_ms
132
+ for key in [k for k, w in self._hits.items() if not w or w[-1] <= cutoff]:
133
+ del self._hits[key]
134
+
135
+
136
+ class LinkService:
137
+ """Link requests in memory: created by terminals, approved or denied by
138
+ signed-in users. A restart drops them."""
139
+
140
+ def __init__(
141
+ self,
142
+ auth_service: AuthService,
143
+ approval_url: str = DEFAULT_LINK_APPROVAL_URL,
144
+ now: Callable[[], int] = now_ms,
145
+ ) -> None:
146
+ self.auth_service = auth_service
147
+ self.approval_url = approval_url
148
+ self._now = now
149
+ self._links: OrderedDict[str, LinkRequest] = OrderedDict()
150
+
151
+ # ``POST /link``
152
+ def create(self, body: Any, origin: str | None = None, remote_address: str | None = None) -> dict[str, Any]:
153
+ body = body if isinstance(body, dict) else {}
154
+ raw_client = body.get("client")
155
+ client = raw_client.strip() if isinstance(raw_client, str) else ""
156
+ if not 1 <= len(client) <= MAX_CLIENT_LENGTH or _CONTROL_RE.search(client):
157
+ raise bad_request(f"client must be 1-{MAX_CLIENT_LENGTH} characters")
158
+ permissions: list[str] | None = None
159
+ value = body.get("permissions")
160
+ if value is not None:
161
+ if (
162
+ not isinstance(value, list) or not value
163
+ or any(not isinstance(p, str) or not p for p in value)
164
+ ):
165
+ raise bad_request("permissions must be a non-empty array of strings")
166
+ permissions = validate_permissions(value)
167
+
168
+ self.sweep()
169
+ while len(self._links) >= MAX_PENDING_LINKS:
170
+ self._links.popitem(last=False)
171
+
172
+ code = "".join(secrets.choice(CODE_ALPHABET) for _ in range(CODE_LENGTH))
173
+ user_code = _format_code(code)
174
+ link_id = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode("ascii")
175
+ now = self._now()
176
+ self._links[link_id] = LinkRequest(
177
+ link_id=link_id,
178
+ code_hash=_hash_code(code),
179
+ user_code=user_code,
180
+ client=client,
181
+ permissions=permissions,
182
+ origin=origin[:200] if origin else None,
183
+ remote_address=remote_address or None,
184
+ created_at=now,
185
+ expires_at=now + LINK_EXPIRES_IN_SECONDS * 1000,
186
+ )
187
+ return {
188
+ "linkId": link_id,
189
+ "userCode": user_code,
190
+ "verificationUrl": link_verification_url(self.approval_url, user_code),
191
+ "expiresIn": LINK_EXPIRES_IN_SECONDS,
192
+ "interval": LINK_POLL_INTERVAL_SECONDS,
193
+ }
194
+
195
+ # ``GET /link/{linkId}``: the token is handed out once, then the request is gone.
196
+ def poll(self, link_id: str) -> dict[str, Any] | None:
197
+ self.sweep()
198
+ link = self._links.get(link_id)
199
+ if link is None:
200
+ return None
201
+ if link.status == "approved":
202
+ del self._links[link_id]
203
+ return {
204
+ "status": "approved",
205
+ "token": link.token,
206
+ "userName": link.user_name,
207
+ "expiresAt": link.token_expires_at,
208
+ }
209
+ if link.status == "denied":
210
+ del self._links[link_id]
211
+ return {"status": "denied"}
212
+ return {"status": "pending"}
213
+
214
+ def _find_pending(self, user_code: str) -> LinkRequest | None:
215
+ """The pending request with this user code (constant-time compare)."""
216
+ self.sweep()
217
+ code_hash = _hash_code(user_code)
218
+ found: LinkRequest | None = None
219
+ for link in self._links.values():
220
+ if hmac.compare_digest(link.code_hash, code_hash) and link.status == "pending":
221
+ found = link
222
+ return found
223
+
224
+ # ``GET /link/code/{userCode}``
225
+ def view(self, user_code: str) -> dict[str, Any]:
226
+ link = self._find_pending(user_code)
227
+ if link is None:
228
+ raise not_found(NOT_FOUND)
229
+ return {
230
+ "userCode": link.user_code,
231
+ "client": link.client,
232
+ "origin": link.origin,
233
+ "remoteAddress": link.remote_address,
234
+ "permissions": link.permissions,
235
+ "createdAt": link.created_at,
236
+ "expiresAt": link.expires_at,
237
+ }
238
+
239
+ # ``POST /link/code/{userCode}/approve``
240
+ async def approve(self, ctx: AuthContext, user_code: str) -> dict[str, str]:
241
+ """Create the approver's API token for the terminal, through the same
242
+ path as ``POST /tokens`` (session only, permissions the approver's,
243
+ token limit, default expiry, ``token_created`` audit)."""
244
+ # Imported here: the tokens controller imports the services package.
245
+ from ..controllers.tokens_controller import (
246
+ create_api_token,
247
+ default_token_expiry,
248
+ ensure_can_create_tokens,
249
+ revoke_api_token,
250
+ scope_permissions,
251
+ )
252
+
253
+ link = self._find_pending(user_code)
254
+ if link is None:
255
+ raise not_found(NOT_FOUND)
256
+ ensure_can_create_tokens(ctx)
257
+ permissions = scope_permissions(ctx, link.permissions)
258
+ # Claimed before the token exists, so a parallel approval or deny gets 404
259
+ # instead of leaving a second token behind.
260
+ link.status = "approving"
261
+ created = None
262
+ suffix = 0
263
+ try:
264
+ while created is None:
265
+ try:
266
+ created = await create_api_token(
267
+ self.auth_service, ctx, link_token_name(link.client, suffix),
268
+ permissions, default_token_expiry(),
269
+ )
270
+ except UsersApiError as exc:
271
+ if exc.status_code != 409 or suffix >= MAX_NAME_SUFFIX:
272
+ raise
273
+ suffix += 1
274
+ except BaseException:
275
+ # Another approver (with the permissions, or a free token slot) can still approve it.
276
+ link.status = "pending"
277
+ raise
278
+ token, record = created
279
+ # Expired (swept or not) or dropped while the token was created: the
280
+ # terminal can no longer collect it, so the token goes too.
281
+ self.sweep()
282
+ if self._links.get(link.link_id) is not link:
283
+ await revoke_api_token(self.auth_service, ctx, record)
284
+ raise not_found(NOT_FOUND)
285
+ link.status = "approved"
286
+ link.token = token
287
+ link.user_name = ctx.user.name
288
+ link.token_expires_at = record.expires_at
289
+ metadata: dict[str, Any] = {"client": link.client}
290
+ if link.origin:
291
+ metadata["origin"] = link.origin
292
+ metadata["tokenId"] = record.id
293
+ await self.auth_service.audit(
294
+ "link_approved", ctx.user.name,
295
+ details=f"{link.client} ({record.name})",
296
+ actor=ctx.user.name, actor_id=ctx.user.id, user_id=ctx.user.id,
297
+ metadata=metadata,
298
+ )
299
+ return {"tokenId": record.id, "tokenName": record.name}
300
+
301
+ # ``POST /link/code/{userCode}/deny``
302
+ async def deny(self, ctx: AuthContext, user_code: str) -> None:
303
+ link = self._find_pending(user_code)
304
+ if link is None:
305
+ raise not_found(NOT_FOUND)
306
+ link.status = "denied"
307
+ metadata: dict[str, Any] = {"client": link.client}
308
+ if link.origin:
309
+ metadata["origin"] = link.origin
310
+ await self.auth_service.audit(
311
+ "link_denied", ctx.user.name,
312
+ details=link.client,
313
+ actor=ctx.user.name, actor_id=ctx.user.id, user_id=ctx.user.id,
314
+ metadata=metadata,
315
+ )
316
+
317
+ def sweep(self) -> None:
318
+ """Drop expired requests (an approved token not collected in time
319
+ stays listed with the user's tokens)."""
320
+ now = self._now()
321
+ for link_id in [i for i, link in self._links.items() if link.expires_at <= now]:
322
+ del self._links[link_id]