qodalis-cli-server-plugin-users 1.0.0b28__tar.gz → 1.0.0b30__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.
- qodalis_cli_server_plugin_users-1.0.0b30/.gitignore +3 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/PKG-INFO +1 -1
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/pyproject.toml +4 -1
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/__init__.py +16 -1
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/cli_users_builder.py +248 -21
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/controllers/__init__.py +2 -0
- qodalis_cli_server_plugin_users-1.0.0b30/qodalis_cli_users/controllers/permissions_controller.py +37 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/controllers/tokens_controller.py +102 -35
- qodalis_cli_server_plugin_users-1.0.0b30/qodalis_cli_users/dashboard/extension.css +1 -0
- qodalis_cli_server_plugin_users-1.0.0b30/qodalis_cli_users/dashboard/extension.js +40 -0
- qodalis_cli_server_plugin_users-1.0.0b30/qodalis_cli_users/dashboard_users/extension.css +1 -0
- qodalis_cli_server_plugin_users-1.0.0b30/qodalis_cli_users/dashboard_users/extension.js +42 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/errors.py +26 -0
- qodalis_cli_server_plugin_users-1.0.0b30/qodalis_cli_users/middleware/auth_middleware.py +195 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/models.py +50 -3
- qodalis_cli_server_plugin_users-1.0.0b30/qodalis_cli_users/permissions.py +145 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/server_protection.py +166 -9
- qodalis_cli_server_plugin_users-1.0.0b30/qodalis_cli_users/services/api_token_manager.py +165 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/services/auth_service.py +71 -10
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/services/link_service.py +4 -3
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/shell_access.py +3 -2
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/stores/interfaces.py +2 -1
- qodalis_cli_server_plugin_users-1.0.0b28/.gitignore +0 -44
- qodalis_cli_server_plugin_users-1.0.0b28/qodalis_cli_users/middleware/auth_middleware.py +0 -77
- qodalis_cli_server_plugin_users-1.0.0b28/qodalis_cli_users/permissions.py +0 -60
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/LICENSE +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/_http.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/controllers/_routing.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/controllers/groups_controller.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/controllers/link_controller.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/controllers/sessions_controller.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/controllers/users_controller.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/external_request.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/middleware/__init__.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/services/__init__.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/services/password_hasher.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/services/users_service.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/stores/__init__.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/stores/in_memory_api_token_store.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/stores/in_memory_audit_store.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/stores/in_memory_credential_store.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/stores/in_memory_group_store.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/stores/in_memory_session_store.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/stores/in_memory_user_store.py +0 -0
- {qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/qodalis_cli_users/validation.py +0 -0
{qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: qodalis-cli-server-plugin-users
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.0b30
|
|
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
|
{qodalis_cli_server_plugin_users-1.0.0b28 → qodalis_cli_server_plugin_users-1.0.0b30}/pyproject.toml
RENAMED
|
@@ -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.
|
|
7
|
+
version = "1.0.0b30"
|
|
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"
|
|
@@ -38,3 +38,6 @@ packages = ["qodalis_cli_users"]
|
|
|
38
38
|
|
|
39
39
|
[tool.hatch.build.targets.sdist]
|
|
40
40
|
include = ["qodalis_cli_users/**"]
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build]
|
|
43
|
+
artifacts = ["qodalis_cli_users/dashboard/**", "qodalis_cli_users/dashboard_users/**"]
|
|
@@ -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",
|
|
@@ -22,22 +22,35 @@ from __future__ import annotations
|
|
|
22
22
|
|
|
23
23
|
import asyncio
|
|
24
24
|
import logging
|
|
25
|
+
import os
|
|
25
26
|
from dataclasses import dataclass, field
|
|
26
27
|
from typing import Any, Optional
|
|
27
28
|
|
|
28
29
|
from fastapi import APIRouter, Request
|
|
29
30
|
|
|
30
31
|
from qodalis_cli_audit import CliAuditBuilder, CliAuditPlugin
|
|
32
|
+
from qodalis_cli_server_abstractions.dashboard_modules import (
|
|
33
|
+
DASHBOARD_MODULES_PREFIX,
|
|
34
|
+
dashboard_module_page,
|
|
35
|
+
module_page_of,
|
|
36
|
+
)
|
|
31
37
|
from qodalis_cli_server_abstractions.events import ICliEventBus
|
|
32
38
|
|
|
33
39
|
from .controllers.groups_controller import create_groups_router
|
|
34
40
|
from .controllers.link_controller import create_link_router
|
|
41
|
+
from .controllers.permissions_controller import create_permissions_router
|
|
35
42
|
from .controllers.sessions_controller import create_sessions_router
|
|
36
43
|
from .controllers.tokens_controller import create_tokens_router
|
|
37
44
|
from .controllers.users_controller import create_users_router
|
|
38
|
-
from .middleware.auth_middleware import
|
|
39
|
-
|
|
40
|
-
|
|
45
|
+
from .middleware.auth_middleware import (
|
|
46
|
+
cli_only,
|
|
47
|
+
create_auth_dependencies,
|
|
48
|
+
host_token_dependency,
|
|
49
|
+
permission_dependency,
|
|
50
|
+
)
|
|
51
|
+
from .errors import QcliGuardError, UsersApiError, install_guard_error_handler
|
|
52
|
+
from .models import ExternalAuthAdapter, TokenUsageProvider
|
|
53
|
+
from .permissions import USERS_PERMISSION_ENTRIES
|
|
41
54
|
from .server_protection import ServerProtectionMiddleware, _normalize_base
|
|
42
55
|
from .shell_access import UsersShellAccess
|
|
43
56
|
from .services.auth_service import (
|
|
@@ -58,6 +71,7 @@ from .services.link_service import (
|
|
|
58
71
|
LinkService,
|
|
59
72
|
validate_link_approval_url,
|
|
60
73
|
)
|
|
74
|
+
from .services.api_token_manager import ApiTokenManager
|
|
61
75
|
from .services.users_service import UsersService
|
|
62
76
|
from .stores.in_memory_api_token_store import InMemoryApiTokenStore
|
|
63
77
|
from .stores.in_memory_credential_store import InMemoryCredentialStore
|
|
@@ -76,6 +90,50 @@ from .stores.interfaces import (
|
|
|
76
90
|
logger = logging.getLogger(__name__)
|
|
77
91
|
|
|
78
92
|
PREFIX = "/api/v1/qcli"
|
|
93
|
+
|
|
94
|
+
#: The dashboard's API tokens page (``@qodalis/cli-dashboard-module-tokens``): its registration, served at
|
|
95
|
+
#: ``/qcli/modules/tokens``. No permission: every user sees their own tokens.
|
|
96
|
+
TOKENS_DASHBOARD_PAGE = {
|
|
97
|
+
"id": "tokens",
|
|
98
|
+
"title": "API tokens",
|
|
99
|
+
"titles": {
|
|
100
|
+
"es": "Tokens de API", "fr": "Jetons d’API", "de": "API-Tokens", "pt": "Tokens de API", "it": "Token API",
|
|
101
|
+
"ja": "API トークン", "ko": "API 토큰", "zh": "API 令牌", "ru": "API-токены", "ro": "Tokenuri API",
|
|
102
|
+
},
|
|
103
|
+
"icon": "🔑",
|
|
104
|
+
"group": "access",
|
|
105
|
+
"order": 10,
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
#: The dashboard's Users page (users, groups, sessions; ``@qodalis/cli-dashboard-module-users``), served at
|
|
109
|
+
#: ``/qcli/modules/users``.
|
|
110
|
+
USERS_DASHBOARD_PAGE = {
|
|
111
|
+
"id": "users",
|
|
112
|
+
"title": "Users",
|
|
113
|
+
"titles": {
|
|
114
|
+
"de": "Benutzer", "es": "Usuarios", "fr": "Utilisateurs", "it": "Utenti", "ja": "ユーザー",
|
|
115
|
+
"ko": "사용자", "pt": "Usuários", "ro": "Utilizatori", "ru": "Пользователи", "zh": "用户",
|
|
116
|
+
},
|
|
117
|
+
"icon": "👥",
|
|
118
|
+
"group": "access",
|
|
119
|
+
"order": 5,
|
|
120
|
+
"permission": "users:read",
|
|
121
|
+
"search": "/?q=",
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
#: The signed-in user's Account page (profile, password change): the Users build, which renders it for this id,
|
|
125
|
+
#: served again at ``/qcli/modules/account`` and listed in the dashboard's account menu. No permission: every user.
|
|
126
|
+
ACCOUNT_DASHBOARD_PAGE = {
|
|
127
|
+
"id": "account",
|
|
128
|
+
"title": "Account",
|
|
129
|
+
"titles": {
|
|
130
|
+
"de": "Konto", "es": "Cuenta", "fr": "Compte", "it": "Account", "ja": "アカウント",
|
|
131
|
+
"ko": "계정", "pt": "Conta", "ro": "Cont", "ru": "Учётная запись", "zh": "账户",
|
|
132
|
+
},
|
|
133
|
+
"icon": "👤",
|
|
134
|
+
"group": "account",
|
|
135
|
+
"order": 0,
|
|
136
|
+
}
|
|
79
137
|
DEFAULT_CLEANUP_INTERVAL_MS = 5 * 60 * 1000
|
|
80
138
|
#: Re-check interval (seconds) of events/logs sockets opened through the
|
|
81
139
|
#: external auth adapter: the server's ``shell.session_check_interval``
|
|
@@ -83,6 +141,15 @@ DEFAULT_CLEANUP_INTERVAL_MS = 5 * 60 * 1000
|
|
|
83
141
|
DEFAULT_SESSION_CHECK_INTERVAL = 30.0
|
|
84
142
|
MAX_SESSION_CHECK_INTERVAL = 60.0
|
|
85
143
|
LOGS_READ = "logs:read"
|
|
144
|
+
GUARD_ONLY_NEEDS_NO_CLI_ROUTES = "guard-only needs cli_routes=False"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _is_own_entry(existing: Any, entry: dict[str, str]) -> bool:
|
|
148
|
+
return (
|
|
149
|
+
existing is not None
|
|
150
|
+
and getattr(existing, "surface", None) == "cli"
|
|
151
|
+
and getattr(existing, "description", None) == entry["description"]
|
|
152
|
+
)
|
|
86
153
|
|
|
87
154
|
|
|
88
155
|
@dataclass
|
|
@@ -113,8 +180,32 @@ class CliUsersPlugin:
|
|
|
113
180
|
require_auth: Any = None
|
|
114
181
|
#: ``require_permission("perm")`` → FastAPI dependency (403 if missing).
|
|
115
182
|
require_permission: Any = None
|
|
183
|
+
#: FastAPI dependency for CLI routes of other plugins (e.g. the admin
|
|
184
|
+
#: API): ``require_auth`` that also refuses ``host`` API tokens (403
|
|
185
|
+
#: ``forbidden: host tokens cannot use CLI routes``).
|
|
186
|
+
require_cli_auth: Any = None
|
|
187
|
+
#: ``require_host_token("perm")`` → FastAPI dependency accepting only
|
|
188
|
+
#: ``host`` API tokens (403 ``forbidden: a host token is required``),
|
|
189
|
+
#: then checking the permission when given.
|
|
190
|
+
require_host_token: Any = None
|
|
191
|
+
#: ``require_auth`` without setting ``request.state.qcli_caller``: for
|
|
192
|
+
#: guards that set it themselves once they fully passed (public-api).
|
|
193
|
+
authenticate: Any = None
|
|
194
|
+
#: Guard-only mode (``set_guard_only()``): no routes, no seeding, no
|
|
195
|
+
#: server protection; the guards validate tokens of shared stores.
|
|
196
|
+
guard_only: bool = False
|
|
197
|
+
#: API tokens the host creates, lists and revokes for its users,
|
|
198
|
+
#: including ``host`` tokens (accepted only by ``require_auth`` /
|
|
199
|
+
#: ``require_permission``).
|
|
200
|
+
api_tokens: Optional[ApiTokenManager] = None
|
|
116
201
|
_extra_public: list = field(default_factory=list, repr=False)
|
|
117
202
|
_base_paths: list = field(default_factory=list, repr=False)
|
|
203
|
+
#: The server's ``cli_route_prefixes`` (live list), set when mounted.
|
|
204
|
+
_server_cli_prefixes: Optional[list] = field(default=None, repr=False)
|
|
205
|
+
#: The server's ``public_paths`` (live list), set when mounted.
|
|
206
|
+
_server_public_paths: Optional[list] = field(default=None, repr=False)
|
|
207
|
+
#: The server's ``route_permissions`` (live list), set when mounted.
|
|
208
|
+
_server_route_permissions: Optional[list] = field(default=None, repr=False)
|
|
118
209
|
_protected_apps: list = field(default_factory=list, repr=False)
|
|
119
210
|
_cleanup_task: Optional[asyncio.Task] = field(default=None, repr=False)
|
|
120
211
|
#: ``(socket manager, permission)`` of the server's events/logs sockets.
|
|
@@ -126,12 +217,24 @@ class CliUsersPlugin:
|
|
|
126
217
|
audit_plugin: Optional[CliAuditPlugin] = None
|
|
127
218
|
#: Link requests (``/link``): terminals linked through the browser.
|
|
128
219
|
link_service: Optional[LinkService] = None
|
|
220
|
+
#: The dashboard's Users, Account and API tokens pages, when the package carries their builds (not in
|
|
221
|
+
#: guard-only mode).
|
|
222
|
+
dashboard_pages: list = field(default_factory=list)
|
|
129
223
|
_link_limiter: Optional[LinkRateLimiter] = field(default=None, repr=False)
|
|
130
224
|
_seeded: bool = field(default=False, repr=False)
|
|
225
|
+
#: Guard-only: mounted on a server without CLI routes (the guards work).
|
|
226
|
+
_guard_only_mounted: bool = field(default=False, repr=False)
|
|
131
227
|
_seed_lock: Optional[asyncio.Lock] = field(default=None, repr=False)
|
|
132
228
|
|
|
133
229
|
async def ensure_seeded(self) -> None:
|
|
134
|
-
"""Seed built-in groups and the root user once (idempotent).
|
|
230
|
+
"""Seed built-in groups and the root user once (idempotent). In
|
|
231
|
+
guard-only mode nothing is seeded, and until the plugin is mounted on
|
|
232
|
+
a server without CLI routes the guards answer 500 (fail closed)."""
|
|
233
|
+
if self.guard_only:
|
|
234
|
+
if not self._guard_only_mounted:
|
|
235
|
+
logger.error(GUARD_ONLY_NEEDS_NO_CLI_ROUTES)
|
|
236
|
+
raise QcliGuardError(500, "internal server error")
|
|
237
|
+
return
|
|
135
238
|
if self._seeded:
|
|
136
239
|
return
|
|
137
240
|
if self._seed_lock is None:
|
|
@@ -146,6 +249,15 @@ class CliUsersPlugin:
|
|
|
146
249
|
def auth(self) -> AuthService:
|
|
147
250
|
return self.auth_service
|
|
148
251
|
|
|
252
|
+
def set_token_usage_provider(self, provider: TokenUsageProvider | None) -> None:
|
|
253
|
+
"""Add ``usage`` to the token views (``GET /tokens`` and
|
|
254
|
+
:meth:`ApiTokenManager.list`): ``await provider(token_ids)`` returns
|
|
255
|
+
``{token_id: {"today", "last30Days", "days"}}``. ``None`` removes
|
|
256
|
+
it. The public-api plugin sets one."""
|
|
257
|
+
if provider is not None and not callable(provider):
|
|
258
|
+
raise TypeError("token usage provider must be callable")
|
|
259
|
+
self.auth_service.token_usage_provider = provider
|
|
260
|
+
|
|
149
261
|
def allow_anonymous(self, path: str, methods: list[str] | None = None) -> None:
|
|
150
262
|
"""Exempt an exact path from server protection (e.g. another plugin's
|
|
151
263
|
login endpoint)."""
|
|
@@ -153,9 +265,12 @@ class CliUsersPlugin:
|
|
|
153
265
|
(path, frozenset(m.upper() for m in methods) if methods else None),
|
|
154
266
|
)
|
|
155
267
|
|
|
156
|
-
def protect(self, app: Any) -> None:
|
|
268
|
+
def protect(self, app: Any, *, enforce: bool = True) -> None:
|
|
157
269
|
"""Install the server-protection middleware on ``app`` (innermost,
|
|
158
|
-
so CORS stays outermost). Must be called before the app starts.
|
|
270
|
+
so CORS stays outermost). Must be called before the app starts.
|
|
271
|
+
``enforce=False`` (``set_protect_server(False)``) authenticates
|
|
272
|
+
nothing and only refuses ``host`` API tokens on the CLI's routes and
|
|
273
|
+
sockets."""
|
|
159
274
|
if any(a is app for a in self._protected_apps):
|
|
160
275
|
return
|
|
161
276
|
from starlette.middleware import Middleware
|
|
@@ -166,6 +281,10 @@ class CliUsersPlugin:
|
|
|
166
281
|
ensure_ready=self.ensure_seeded,
|
|
167
282
|
extra_public=self._extra_public,
|
|
168
283
|
base_paths=self._base_paths,
|
|
284
|
+
cli_prefixes=lambda: self._server_cli_prefixes,
|
|
285
|
+
enforce=enforce,
|
|
286
|
+
public_paths=lambda: self._server_public_paths,
|
|
287
|
+
route_permissions=lambda: self._server_route_permissions,
|
|
169
288
|
))
|
|
170
289
|
app.middleware_stack = None
|
|
171
290
|
self._protected_apps.append(app)
|
|
@@ -176,6 +295,13 @@ class CliUsersPlugin:
|
|
|
176
295
|
ended, adopts the server's allowed origins (CSRF), protects the whole
|
|
177
296
|
server unless disabled and owns access to the remote shell (``users``
|
|
178
297
|
shell mode)."""
|
|
298
|
+
options = getattr(server, "options", None)
|
|
299
|
+
# Fail closed: guard-only installs no protection, so the CLI's routes
|
|
300
|
+
# must not be served at all.
|
|
301
|
+
if self.guard_only and getattr(options, "cli_routes", True) is not False:
|
|
302
|
+
raise ValueError(GUARD_ONLY_NEEDS_NO_CLI_ROUTES)
|
|
303
|
+
if self.guard_only:
|
|
304
|
+
self._guard_only_mounted = True
|
|
179
305
|
manager = getattr(server, "event_socket_manager", None)
|
|
180
306
|
if manager is not None and hasattr(manager, "send_to_user"):
|
|
181
307
|
self.auth_service.user_event_sender = manager.send_to_user
|
|
@@ -187,7 +313,6 @@ class CliUsersPlugin:
|
|
|
187
313
|
# sockets without a user (read on every event).
|
|
188
314
|
if manager is not None and hasattr(manager, "set_authentication_required"):
|
|
189
315
|
manager.set_authentication_required(lambda: True)
|
|
190
|
-
options = getattr(server, "options", None)
|
|
191
316
|
# The host application signs users in (read by the admin dashboard).
|
|
192
317
|
if self.auth_service.external_auth and hasattr(options, "external_authentication"):
|
|
193
318
|
options.external_authentication = True
|
|
@@ -200,8 +325,20 @@ class CliUsersPlugin:
|
|
|
200
325
|
base = _normalize_base(base_path)
|
|
201
326
|
if base not in self._base_paths:
|
|
202
327
|
self._base_paths.append(base)
|
|
203
|
-
|
|
204
|
-
|
|
328
|
+
prefixes = getattr(server, "cli_route_prefixes", None)
|
|
329
|
+
if isinstance(prefixes, list):
|
|
330
|
+
self._server_cli_prefixes = prefixes
|
|
331
|
+
public = getattr(server, "public_paths", None)
|
|
332
|
+
if isinstance(public, list):
|
|
333
|
+
self._server_public_paths = public
|
|
334
|
+
declared = getattr(server, "route_permissions", None)
|
|
335
|
+
if isinstance(declared, list):
|
|
336
|
+
self._server_route_permissions = declared
|
|
337
|
+
# Without protection the middleware still refuses host tokens on the
|
|
338
|
+
# CLI's routes (they authenticate nothing else then). A guard-only
|
|
339
|
+
# plugin (on a server without CLI routes) has nothing to protect.
|
|
340
|
+
if not self.guard_only:
|
|
341
|
+
self.protect(server.app, enforce=self.protect_server)
|
|
205
342
|
# Events/logs sockets are bound to their session: closed (4401
|
|
206
343
|
# "session ended") on logout, revoke, disable/delete and expiry.
|
|
207
344
|
# Those of adapter identities are re-checked through the adapter
|
|
@@ -223,7 +360,24 @@ class CliUsersPlugin:
|
|
|
223
360
|
set_shell_provider = getattr(server, "set_shell_access_provider", None)
|
|
224
361
|
if callable(set_shell_provider):
|
|
225
362
|
set_shell_provider(UsersShellAccess(self.auth_service))
|
|
226
|
-
self.
|
|
363
|
+
self._adopt_permission_catalog(server)
|
|
364
|
+
# The host-token-only guards answer {"error": ...} on host routes.
|
|
365
|
+
install_guard_error_handler(server.app)
|
|
366
|
+
if not self.guard_only:
|
|
367
|
+
self._mount_audit(server)
|
|
368
|
+
|
|
369
|
+
def _adopt_permission_catalog(self, server: Any) -> None:
|
|
370
|
+
"""Use the server's permission catalog (``server.builder.permissions``,
|
|
371
|
+
core 1.0.0b29 and later) and add the plugin's entries to it, once. On
|
|
372
|
+
an older core the plugin keeps its own catalog."""
|
|
373
|
+
catalog = getattr(getattr(server, "builder", None), "permissions", None)
|
|
374
|
+
if catalog is None or not all(callable(getattr(catalog, m, None)) for m in ("add", "all", "find")):
|
|
375
|
+
return
|
|
376
|
+
# Skipped only on a remount (all twelve entries are the plugin's own);
|
|
377
|
+
# a host or plugin that registered any of them itself fails startup.
|
|
378
|
+
if not all(_is_own_entry(catalog.find(e["name"]), e) for e in USERS_PERMISSION_ENTRIES):
|
|
379
|
+
catalog.add(USERS_PERMISSION_ENTRIES, "cli")
|
|
380
|
+
self.auth_service.permission_catalog = catalog
|
|
227
381
|
|
|
228
382
|
def _mount_audit(self, server: Any) -> None:
|
|
229
383
|
"""Mount the audit plugin with the users plugin, so a host that only
|
|
@@ -243,7 +397,7 @@ class CliUsersPlugin:
|
|
|
243
397
|
async def authorize_audit(self, request: Request, permission: str) -> Any:
|
|
244
398
|
"""The users plugin's guard of the audit API (a session or token with
|
|
245
399
|
``permission``), used when it does not protect the whole server."""
|
|
246
|
-
ctx = await self.
|
|
400
|
+
ctx = await self.require_cli_auth(request)
|
|
247
401
|
if not ctx.can(permission):
|
|
248
402
|
raise UsersApiError(403, f"missing permission: {permission}")
|
|
249
403
|
return ctx
|
|
@@ -261,7 +415,11 @@ class CliUsersPlugin:
|
|
|
261
415
|
async def startup(self) -> None:
|
|
262
416
|
"""Seed and start the background tasks on the running loop: the
|
|
263
417
|
session sweep and, with an external auth adapter, the re-check of
|
|
264
|
-
the events/logs sockets opened through it.
|
|
418
|
+
the events/logs sockets opened through it. Nothing in guard-only
|
|
419
|
+
mode."""
|
|
420
|
+
# Guard-only: the stores are the token-issuing service's to sweep.
|
|
421
|
+
if self.guard_only:
|
|
422
|
+
return
|
|
265
423
|
await self.ensure_seeded()
|
|
266
424
|
loop = asyncio.get_running_loop()
|
|
267
425
|
if self._cleanup_task is None or self._cleanup_task.done():
|
|
@@ -370,6 +528,9 @@ class CliUsersBuilder:
|
|
|
370
528
|
self._lockout_ms = DEFAULT_LOCKOUT_MS
|
|
371
529
|
self._cleanup_interval_ms = DEFAULT_CLEANUP_INTERVAL_MS
|
|
372
530
|
self._link_approval_url = DEFAULT_LINK_APPROVAL_URL
|
|
531
|
+
self._guard_only = False
|
|
532
|
+
self._dashboard_dir: str | bool | None = None
|
|
533
|
+
self._users_dashboard_dir: str | bool | None = None
|
|
373
534
|
|
|
374
535
|
def set_user_store(self, store: IUserStore) -> CliUsersBuilder:
|
|
375
536
|
self._user_store = store
|
|
@@ -496,6 +657,38 @@ class CliUsersBuilder:
|
|
|
496
657
|
self._protect_server = protect
|
|
497
658
|
return self
|
|
498
659
|
|
|
660
|
+
def set_dashboard_dir(self, directory: str | bool) -> CliUsersBuilder:
|
|
661
|
+
"""Where the dashboard's API tokens page is (``@qodalis/cli-dashboard-module-tokens``'s build); by
|
|
662
|
+
default the copy in this package (``scripts/copy_dashboard.py``). ``False`` leaves the page out."""
|
|
663
|
+
self._dashboard_dir = directory
|
|
664
|
+
return self
|
|
665
|
+
|
|
666
|
+
def set_users_dashboard_dir(self, directory: str | bool) -> CliUsersBuilder:
|
|
667
|
+
"""Where the dashboard's Users and Account pages are (``@qodalis/cli-dashboard-module-users``'s build, served
|
|
668
|
+
at ``/qcli/modules/users`` and ``/qcli/modules/account``); by default the copy in this package
|
|
669
|
+
(``dashboard_users``, ``scripts/copy_dashboard.py``). ``False`` leaves both pages out."""
|
|
670
|
+
self._users_dashboard_dir = directory
|
|
671
|
+
return self
|
|
672
|
+
|
|
673
|
+
def set_guard_only(self, on: bool = True) -> CliUsersBuilder:
|
|
674
|
+
"""Guard-only mode, for a service that only validates tokens (e.g. a
|
|
675
|
+
public API next to the service that runs the CLI): no users routes
|
|
676
|
+
(sign-in, users, groups, sessions, tokens, permissions, link, audit),
|
|
677
|
+
no seeding (no ``root``, no built-in groups) and no server
|
|
678
|
+
protection (``host`` tokens are still refused on CLI routes). The
|
|
679
|
+
guards (``require_auth``, ``require_permission``,
|
|
680
|
+
``require_host_token``, the public-api guard) authenticate
|
|
681
|
+
``qcli_pat_`` tokens against the stores set here, shared with the
|
|
682
|
+
service that creates them. Create and revoke tokens from one service
|
|
683
|
+
only: the name and 20-token checks run in the creating process.
|
|
684
|
+
|
|
685
|
+
Mount it on a server without CLI routes
|
|
686
|
+
(``CliServerOptions(cli_routes=False)``): on any other server
|
|
687
|
+
``mount_plugin`` raises ``ValueError("guard-only needs
|
|
688
|
+
cli_routes=False")``, so the CLI routes are never left open."""
|
|
689
|
+
self._guard_only = on
|
|
690
|
+
return self
|
|
691
|
+
|
|
499
692
|
def set_session_timeout(self, timeout_ms: int) -> CliUsersBuilder:
|
|
500
693
|
"""Idle session timeout in milliseconds (default 30 minutes)."""
|
|
501
694
|
self._session_timeout_ms = timeout_ms
|
|
@@ -576,9 +769,26 @@ class CliUsersBuilder:
|
|
|
576
769
|
api_token_store=auth_service.api_token_store,
|
|
577
770
|
default_admin_password=self._default_admin_password,
|
|
578
771
|
cleanup_interval_ms=self._cleanup_interval_ms,
|
|
579
|
-
protect_server=self._protect_server,
|
|
772
|
+
protect_server=self._protect_server and not self._guard_only,
|
|
580
773
|
audit_plugin=audit_plugin,
|
|
774
|
+
api_tokens=ApiTokenManager(auth_service),
|
|
775
|
+
guard_only=self._guard_only,
|
|
581
776
|
)
|
|
777
|
+
if not self._guard_only:
|
|
778
|
+
package_dir = os.path.dirname(os.path.abspath(__file__))
|
|
779
|
+
pages = []
|
|
780
|
+
if self._users_dashboard_dir is not False:
|
|
781
|
+
users_dir = self._users_dashboard_dir if isinstance(self._users_dashboard_dir, str) \
|
|
782
|
+
else os.path.join(package_dir, "dashboard_users")
|
|
783
|
+
users_page = module_page_of(package_dir, users_dir, f"{DASHBOARD_MODULES_PREFIX}/users", USERS_DASHBOARD_PAGE)
|
|
784
|
+
if users_page:
|
|
785
|
+
# The same build, at the Account page's own prefix
|
|
786
|
+
account_page = dashboard_module_page(users_dir, f"{DASHBOARD_MODULES_PREFIX}/account", ACCOUNT_DASHBOARD_PAGE)
|
|
787
|
+
pages += [users_page, account_page]
|
|
788
|
+
tokens_page = module_page_of(
|
|
789
|
+
package_dir, self._dashboard_dir, f"{DASHBOARD_MODULES_PREFIX}/tokens", TOKENS_DASHBOARD_PAGE,
|
|
790
|
+
)
|
|
791
|
+
plugin.dashboard_pages = pages + ([tokens_page] if tokens_page else [])
|
|
582
792
|
|
|
583
793
|
# The users plugin records its events in the audit plugin's store,
|
|
584
794
|
# also after it joined the host's audit plugin (another store).
|
|
@@ -590,26 +800,43 @@ class CliUsersBuilder:
|
|
|
590
800
|
|
|
591
801
|
# Requests made before startup() (e.g. apps without a lifespan) still
|
|
592
802
|
# see the seeded built-ins.
|
|
593
|
-
get_auth, require_permission, get_auth_pending = create_auth_dependencies(
|
|
803
|
+
get_auth, require_permission, get_auth_pending, get_cli_auth = create_auth_dependencies(
|
|
594
804
|
auth_service, ensure_ready=plugin.ensure_seeded,
|
|
595
805
|
)
|
|
806
|
+
# Host routes (require_auth / require_permission) accept host tokens;
|
|
807
|
+
# the plugin's own routes refuse them.
|
|
596
808
|
plugin.require_auth = get_auth
|
|
597
809
|
plugin.require_permission = require_permission
|
|
810
|
+
plugin.require_cli_auth = get_cli_auth
|
|
811
|
+
plugin.authenticate = get_auth.authenticate
|
|
812
|
+
|
|
813
|
+
def require_host_token(permission: str | None = None) -> Any:
|
|
814
|
+
return host_token_dependency(get_auth.authenticate, permission)
|
|
815
|
+
|
|
816
|
+
plugin.require_host_token = require_host_token
|
|
817
|
+
if self._guard_only:
|
|
818
|
+
return plugin
|
|
819
|
+
get_cli_auth_pending = cli_only(get_auth_pending)
|
|
820
|
+
|
|
821
|
+
def require_cli_permission(permission: str) -> Any:
|
|
822
|
+
return permission_dependency(get_cli_auth, permission)
|
|
823
|
+
|
|
598
824
|
router.include_router(create_sessions_router(
|
|
599
|
-
auth_service,
|
|
600
|
-
ensure_ready=plugin.ensure_seeded, get_auth_pending=
|
|
825
|
+
auth_service, get_cli_auth, require_cli_permission,
|
|
826
|
+
ensure_ready=plugin.ensure_seeded, get_auth_pending=get_cli_auth_pending,
|
|
601
827
|
))
|
|
602
828
|
router.include_router(create_users_router(
|
|
603
|
-
auth_service, users_service,
|
|
604
|
-
get_auth_pending=
|
|
829
|
+
auth_service, users_service, get_cli_auth, require_cli_permission,
|
|
830
|
+
get_auth_pending=get_cli_auth_pending,
|
|
605
831
|
))
|
|
606
832
|
router.include_router(create_groups_router(
|
|
607
|
-
auth_service, users_service,
|
|
833
|
+
auth_service, users_service, get_cli_auth, require_cli_permission,
|
|
608
834
|
))
|
|
609
|
-
router.include_router(create_tokens_router(auth_service,
|
|
835
|
+
router.include_router(create_tokens_router(auth_service, get_cli_auth))
|
|
836
|
+
router.include_router(create_permissions_router(auth_service, get_cli_auth))
|
|
610
837
|
plugin.link_service = LinkService(auth_service, self._link_approval_url)
|
|
611
838
|
plugin._link_limiter = LinkRateLimiter()
|
|
612
839
|
router.include_router(create_link_router(
|
|
613
|
-
auth_service, plugin.link_service,
|
|
840
|
+
auth_service, plugin.link_service, get_cli_auth, plugin._link_limiter,
|
|
614
841
|
))
|
|
615
842
|
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",
|
qodalis_cli_server_plugin_users-1.0.0b30/qodalis_cli_users/controllers/permissions_controller.py
ADDED
|
@@ -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
|