aa-desktop-bridge 0.2.0__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 (29) hide show
  1. aa_desktop_bridge-0.2.0/PKG-INFO +51 -0
  2. aa_desktop_bridge-0.2.0/README.md +38 -0
  3. aa_desktop_bridge-0.2.0/aa_desktop_bridge/__init__.py +8 -0
  4. aa_desktop_bridge-0.2.0/aa_desktop_bridge/account.py +151 -0
  5. aa_desktop_bridge-0.2.0/aa_desktop_bridge/adapters.py +51 -0
  6. aa_desktop_bridge-0.2.0/aa_desktop_bridge/api.py +220 -0
  7. aa_desktop_bridge-0.2.0/aa_desktop_bridge/apps.py +8 -0
  8. aa_desktop_bridge-0.2.0/aa_desktop_bridge/auth.py +71 -0
  9. aa_desktop_bridge-0.2.0/aa_desktop_bridge/discovery.py +62 -0
  10. aa_desktop_bridge-0.2.0/aa_desktop_bridge/launcher.py +165 -0
  11. aa_desktop_bridge-0.2.0/aa_desktop_bridge/management/__init__.py +0 -0
  12. aa_desktop_bridge-0.2.0/aa_desktop_bridge/management/commands/__init__.py +0 -0
  13. aa_desktop_bridge-0.2.0/aa_desktop_bridge/management/commands/desktop_modules.py +50 -0
  14. aa_desktop_bridge-0.2.0/aa_desktop_bridge/modules.py +273 -0
  15. aa_desktop_bridge-0.2.0/aa_desktop_bridge/scopes.py +45 -0
  16. aa_desktop_bridge-0.2.0/aa_desktop_bridge/urls.py +7 -0
  17. aa_desktop_bridge-0.2.0/aa_desktop_bridge.egg-info/PKG-INFO +51 -0
  18. aa_desktop_bridge-0.2.0/aa_desktop_bridge.egg-info/SOURCES.txt +27 -0
  19. aa_desktop_bridge-0.2.0/aa_desktop_bridge.egg-info/dependency_links.txt +1 -0
  20. aa_desktop_bridge-0.2.0/aa_desktop_bridge.egg-info/requires.txt +7 -0
  21. aa_desktop_bridge-0.2.0/aa_desktop_bridge.egg-info/top_level.txt +1 -0
  22. aa_desktop_bridge-0.2.0/pyproject.toml +29 -0
  23. aa_desktop_bridge-0.2.0/setup.cfg +4 -0
  24. aa_desktop_bridge-0.2.0/tests/test_account.py +62 -0
  25. aa_desktop_bridge-0.2.0/tests/test_auth.py +95 -0
  26. aa_desktop_bridge-0.2.0/tests/test_discovery.py +42 -0
  27. aa_desktop_bridge-0.2.0/tests/test_launcher.py +86 -0
  28. aa_desktop_bridge-0.2.0/tests/test_modules.py +397 -0
  29. aa_desktop_bridge-0.2.0/tests/test_scopes.py +50 -0
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: aa-desktop-bridge
3
+ Version: 0.2.0
4
+ Summary: Alliance Auth plugin that exposes the AA Desktop bridge API.
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: django<6,>=5.2
8
+ Requires-Dist: django-ninja<2,>=1.3
9
+ Requires-Dist: django-oauth-toolkit<4,>=3.2
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=8; extra == "dev"
12
+ Requires-Dist: pytest-django>=4.8; extra == "dev"
13
+
14
+ # aa-desktop-bridge
15
+
16
+ Alliance Auth plugin for [AA Desktop](../README.md). It mounts a django-ninja API at `/api/desktop/v1/`.
17
+
18
+ | Method | Path | Auth |
19
+ | --- | --- | --- |
20
+ | `GET` | `/api/desktop/v1/discovery` | none |
21
+ | `GET` | `/api/desktop/v1/me` | Bearer access token, scope `desktop.core` |
22
+ | `GET` | `/api/desktop/v1/modules` | Bearer access token, scope `desktop.core` |
23
+ | any | `/api/desktop/v1/modules/<id>/...` | Bearer access token, a scope of that module, and the module's Alliance Auth permissions |
24
+
25
+ Session cookies are not a credential. See the repository README for installing it on Alliance Auth 5.5 and for the OIDC client the desktop app expects.
26
+
27
+ ## Module routes
28
+
29
+ Another Alliance Auth app can give the desktop client its own routes. It registers a `desktop_module_hook` that returns a `DesktopModule` (id, name, version, scopes, required permissions, and a django-ninja `Router`). The bridge mounts the router at `/api/desktop/v1/modules/<id>/`. The full example and rules are in [`aa_desktop_bridge/modules.py`](aa_desktop_bridge/modules.py). In short:
30
+
31
+ - Scopes are named `desktop.<id>` or `desktop.<id>.<name>`.
32
+ - At least one Alliance Auth permission is required.
33
+ - Every route uses `DesktopBearer([...], permissions=...)` with the module's own scopes and all of its required permissions, and nothing else.
34
+
35
+ A module that breaks a rule, or whose hook raises, is not mounted at all, and the reason is logged. The rest of the API keeps working.
36
+
37
+ The admin registers each module scope in `OAUTH2_PROVIDER["SCOPES"]`, the same way as `desktop.core`. Until then the scope cannot be granted, and the module's routes answer 403.
38
+
39
+ `discovery` lists mounted modules and their scopes. `/modules` lists the ones the signed-in user has the permissions for, and which of their scopes the token already holds. `/me` gives their ids in `modules_available`.
40
+
41
+ Check what is mounted:
42
+
43
+ ```bash
44
+ python manage.py desktop_modules
45
+ ```
46
+
47
+ It prints each mounted module and its scopes, each skipped module with the reason, and any module scope that is missing from `OAUTH2_PROVIDER["SCOPES"]`. It exits 1 if anything is wrong, so an image build can stop on it.
48
+
49
+ ## Publishing
50
+
51
+ The package is published to PyPI from a `bridge-v<version>` tag. The workflow and the one-time Trusted Publisher settings are in [docs/pypi.md](../docs/pypi.md).
@@ -0,0 +1,38 @@
1
+ # aa-desktop-bridge
2
+
3
+ Alliance Auth plugin for [AA Desktop](../README.md). It mounts a django-ninja API at `/api/desktop/v1/`.
4
+
5
+ | Method | Path | Auth |
6
+ | --- | --- | --- |
7
+ | `GET` | `/api/desktop/v1/discovery` | none |
8
+ | `GET` | `/api/desktop/v1/me` | Bearer access token, scope `desktop.core` |
9
+ | `GET` | `/api/desktop/v1/modules` | Bearer access token, scope `desktop.core` |
10
+ | any | `/api/desktop/v1/modules/<id>/...` | Bearer access token, a scope of that module, and the module's Alliance Auth permissions |
11
+
12
+ Session cookies are not a credential. See the repository README for installing it on Alliance Auth 5.5 and for the OIDC client the desktop app expects.
13
+
14
+ ## Module routes
15
+
16
+ Another Alliance Auth app can give the desktop client its own routes. It registers a `desktop_module_hook` that returns a `DesktopModule` (id, name, version, scopes, required permissions, and a django-ninja `Router`). The bridge mounts the router at `/api/desktop/v1/modules/<id>/`. The full example and rules are in [`aa_desktop_bridge/modules.py`](aa_desktop_bridge/modules.py). In short:
17
+
18
+ - Scopes are named `desktop.<id>` or `desktop.<id>.<name>`.
19
+ - At least one Alliance Auth permission is required.
20
+ - Every route uses `DesktopBearer([...], permissions=...)` with the module's own scopes and all of its required permissions, and nothing else.
21
+
22
+ A module that breaks a rule, or whose hook raises, is not mounted at all, and the reason is logged. The rest of the API keeps working.
23
+
24
+ The admin registers each module scope in `OAUTH2_PROVIDER["SCOPES"]`, the same way as `desktop.core`. Until then the scope cannot be granted, and the module's routes answer 403.
25
+
26
+ `discovery` lists mounted modules and their scopes. `/modules` lists the ones the signed-in user has the permissions for, and which of their scopes the token already holds. `/me` gives their ids in `modules_available`.
27
+
28
+ Check what is mounted:
29
+
30
+ ```bash
31
+ python manage.py desktop_modules
32
+ ```
33
+
34
+ It prints each mounted module and its scopes, each skipped module with the reason, and any module scope that is missing from `OAUTH2_PROVIDER["SCOPES"]`. It exits 1 if anything is wrong, so an image build can stop on it.
35
+
36
+ ## Publishing
37
+
38
+ The package is published to PyPI from a `bridge-v<version>` tag. The workflow and the one-time Trusted Publisher settings are in [docs/pypi.md](../docs/pypi.md).
@@ -0,0 +1,8 @@
1
+ """AA Desktop bridge.
2
+
3
+ Exposes discovery, the signed-in account, the tier-0 launcher, and routes
4
+ that other Alliance Auth apps mount through ``desktop_module_hook``. Signed
5
+ packages, tier-1 manifests, and tier-2 adapters are later phases.
6
+ """
7
+
8
+ __version__ = "0.2.0"
@@ -0,0 +1,151 @@
1
+ """Account summary for ``GET /me``.
2
+
3
+ Alliance Auth's profile (main character, state) is read when the attribute
4
+ exists. A stock Django user, which is what the bridge's own tests use,
5
+ simply reports no character and no state.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ def account_summary(user) -> dict:
12
+ profile = _profile(user)
13
+ return {
14
+ "user_id": user.pk,
15
+ "username": user.get_username(),
16
+ "main_character": _character(profile),
17
+ "characters": linked_characters(user, profile),
18
+ "state": _state_name(profile),
19
+ "groups": sorted(user.groups.values_list("name", flat=True)),
20
+ "permissions": sorted(user.get_all_permissions()),
21
+ }
22
+
23
+
24
+ def linked_characters(user, profile=None) -> list[dict]:
25
+ """Characters linked to the account, when Alliance Auth provides them.
26
+
27
+ Each entry is the character id and name, corporation and alliance id,
28
+ name and ticker, and whether it is the main. Ownership hashes and other
29
+ credential-like fields are not copied. A user with no such relation
30
+ (the bridge's own tests, for example) gets an empty list.
31
+ """
32
+
33
+ if profile is None:
34
+ profile = _profile(user)
35
+ main_id = _main_character_id(profile)
36
+ rows = _ownerships(user)
37
+ characters = []
38
+ seen = set()
39
+ for ownership in rows:
40
+ record = _linked(getattr(ownership, "character", None), main_id)
41
+ if record is None or record["character_id"] in seen:
42
+ continue
43
+ seen.add(record["character_id"])
44
+ characters.append(record)
45
+ characters.sort(key=lambda item: (not item["is_main"], item["character_name"].lower()))
46
+ return characters
47
+
48
+
49
+ def _profile(user):
50
+ try:
51
+ return user.profile
52
+ except Exception:
53
+ return None
54
+
55
+
56
+ def _character(profile) -> dict | None:
57
+ if profile is None:
58
+ return None
59
+ try:
60
+ character = profile.main_character
61
+ except Exception:
62
+ return None
63
+ if character is None:
64
+ return None
65
+ character_id = getattr(character, "character_id", None)
66
+ if character_id is not None:
67
+ try:
68
+ character_id = int(character_id)
69
+ except (TypeError, ValueError):
70
+ character_id = None
71
+ return {
72
+ "character_id": character_id,
73
+ "character_name": _text(getattr(character, "character_name", None)),
74
+ "corporation_name": _text(getattr(character, "corporation_name", None)),
75
+ "alliance_name": _text(getattr(character, "alliance_name", None)),
76
+ }
77
+
78
+
79
+ def _state_name(profile) -> str | None:
80
+ if profile is None:
81
+ return None
82
+ try:
83
+ state = profile.state
84
+ except Exception:
85
+ return None
86
+ if state is None:
87
+ return None
88
+ return _text(getattr(state, "name", None))
89
+
90
+
91
+ def _ownerships(user):
92
+ relation = getattr(user, "character_ownerships", None)
93
+ if relation is None:
94
+ return []
95
+ try:
96
+ queryset = relation.select_related("character")
97
+ except Exception:
98
+ queryset = relation
99
+ try:
100
+ return list(queryset.all() if hasattr(queryset, "all") else queryset)
101
+ except Exception:
102
+ return []
103
+
104
+
105
+ def _linked(character, main_id: int | None) -> dict | None:
106
+ character_id = _character_id(character)
107
+ name = _text(getattr(character, "character_name", None)) if character is not None else None
108
+ if character_id is None or not name:
109
+ return None
110
+ return {
111
+ "character_id": character_id,
112
+ "character_name": name,
113
+ "corporation_id": _optional_int(getattr(character, "corporation_id", None)),
114
+ "corporation_name": _text(getattr(character, "corporation_name", None)),
115
+ "corporation_ticker": _text(getattr(character, "corporation_ticker", None)),
116
+ "alliance_id": _optional_int(getattr(character, "alliance_id", None)),
117
+ "alliance_name": _text(getattr(character, "alliance_name", None)),
118
+ "alliance_ticker": _text(getattr(character, "alliance_ticker", None)),
119
+ "is_main": main_id is not None and character_id == main_id,
120
+ }
121
+
122
+
123
+ def _main_character_id(profile) -> int | None:
124
+ if profile is None:
125
+ return None
126
+ try:
127
+ return _character_id(profile.main_character)
128
+ except Exception:
129
+ return None
130
+
131
+
132
+ def _character_id(character) -> int | None:
133
+ if character is None:
134
+ return None
135
+ return _optional_int(getattr(character, "character_id", None))
136
+
137
+
138
+ def _optional_int(value) -> int | None:
139
+ if value is None or isinstance(value, bool):
140
+ return None
141
+ try:
142
+ return int(value)
143
+ except (TypeError, ValueError):
144
+ return None
145
+
146
+
147
+ def _text(value) -> str | None:
148
+ if value is None:
149
+ return None
150
+ text = str(value).strip()
151
+ return text or None
@@ -0,0 +1,51 @@
1
+ """Seams for later phases.
2
+
3
+ Tier 0 is the launcher: menu hooks become links opened in the system
4
+ browser. Nothing in this module loads a manifest or imports another AA app.
5
+
6
+ * ``desktop_module_hook`` is the registry for module-owned routes. Its
7
+ descriptors and the checks on them are in :mod:`aa_desktop_bridge.modules`.
8
+ * ``registered_packages`` stays empty until signed ``.aamod`` packages exist.
9
+ * Tier 1 (declarative manifests) and tier 2 (Python adapters) plug in here
10
+ and stay fail-closed: an adapter that cannot prove its version range
11
+ disables itself instead of exposing models.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ DESKTOP_MODULE_HOOK = "desktop_module_hook"
21
+
22
+
23
+ def registered_packages() -> list[dict]:
24
+ """Signed package descriptors advertised to the desktop client.
25
+
26
+ Always empty in this phase. A later phase returns descriptors whose
27
+ bytes were signature-checked before they were stored.
28
+ """
29
+
30
+ return []
31
+
32
+
33
+ def registered_module_hooks() -> list:
34
+ """Hook callables registered under ``desktop_module_hook``.
35
+
36
+ Each returns a :class:`aa_desktop_bridge.modules.DesktopModule`.
37
+
38
+ Importing Alliance Auth is deferred so the bridge still imports in a
39
+ test settings module that does not install it. Failures yield an empty
40
+ list (nothing extra is exposed).
41
+ """
42
+
43
+ try:
44
+ from allianceauth.hooks import get_hooks
45
+ except ImportError:
46
+ return []
47
+ try:
48
+ return list(get_hooks(DESKTOP_MODULE_HOOK))
49
+ except Exception:
50
+ logger.warning("desktop_module_hook registry failed; no desktop modules are mounted")
51
+ return []
@@ -0,0 +1,220 @@
1
+ """django-ninja API mounted at ``/api/desktop/v1/``.
2
+
3
+ OpenAPI and the interactive docs are off. This API is not a browser origin,
4
+ so there is no CORS configuration.
5
+
6
+ The API is built once, when the URLconf is first loaded: the bridge's own
7
+ routes, then each module from ``desktop_module_hook`` that passes the checks
8
+ in :mod:`aa_desktop_bridge.modules`, mounted at ``modules/<id>/``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import threading
14
+ from collections.abc import Iterable
15
+
16
+ from django.http import HttpRequest, HttpResponse
17
+ from ninja import NinjaAPI, Schema
18
+
19
+ from .account import account_summary
20
+ from .adapters import registered_module_hooks, registered_packages
21
+ from .auth import DesktopBearer
22
+ from .discovery import discovery_document
23
+ from .launcher import links_as_dicts, visible_links
24
+ from .modules import ModuleRegistry, load_modules
25
+ from .scopes import DESKTOP_CORE
26
+
27
+ _core = DesktopBearer([DESKTOP_CORE])
28
+
29
+
30
+ class ScopeOut(Schema):
31
+ name: str
32
+ description: str
33
+
34
+
35
+ class DiscoveryModuleOut(Schema):
36
+ id: str
37
+ name: str
38
+ version: str
39
+ scopes: list[str]
40
+
41
+
42
+ class DiscoveryOut(Schema):
43
+ api: str
44
+ api_version: int
45
+ api_versions: list[int]
46
+ client_id: str | None
47
+ issuer_path: str
48
+ authorization_endpoint_path: str
49
+ token_endpoint_path: str
50
+ jwks_uri_path: str
51
+ scopes: list[ScopeOut]
52
+ modules: list[DiscoveryModuleOut]
53
+ services: dict[str, str]
54
+ signature: str | None
55
+ signature_scheme: str
56
+ signature_enforced: bool
57
+
58
+
59
+ class CharacterOut(Schema):
60
+ character_id: int | None
61
+ character_name: str | None
62
+ corporation_name: str | None
63
+ alliance_name: str | None
64
+
65
+
66
+ class LinkedCharacterOut(Schema):
67
+ character_id: int
68
+ character_name: str
69
+ corporation_id: int | None
70
+ corporation_name: str | None
71
+ corporation_ticker: str | None
72
+ alliance_id: int | None
73
+ alliance_name: str | None
74
+ alliance_ticker: str | None
75
+ is_main: bool
76
+
77
+
78
+ class MeOut(Schema):
79
+ user_id: int
80
+ username: str
81
+ main_character: CharacterOut | None
82
+ characters: list[LinkedCharacterOut]
83
+ state: str | None
84
+ groups: list[str]
85
+ permissions: list[str]
86
+ scopes: list[str]
87
+ modules_available: list[str]
88
+
89
+
90
+ class LauncherLinkOut(Schema):
91
+ id: str
92
+ kind: str
93
+ label: str
94
+ url_name: str
95
+ path: str
96
+ order: int
97
+ count: int | None
98
+
99
+
100
+ class PackageOut(Schema):
101
+ """Reserved. This phase returns an empty list."""
102
+
103
+ id: str
104
+ version: str
105
+
106
+
107
+ class ModuleScopeOut(Schema):
108
+ name: str
109
+ description: str
110
+ granted: bool
111
+
112
+
113
+ class ModuleOut(Schema):
114
+ id: str
115
+ name: str
116
+ version: str
117
+ path: str
118
+ scopes: list[ModuleScopeOut]
119
+
120
+
121
+ class ModulesOut(Schema):
122
+ links: list[LauncherLinkOut]
123
+ modules: list[ModuleOut]
124
+ packages: list[PackageOut]
125
+
126
+
127
+ def _no_store(response: HttpResponse) -> None:
128
+ response["Cache-Control"] = "no-store"
129
+ response["X-Content-Type-Options"] = "nosniff"
130
+ response["Referrer-Policy"] = "no-referrer"
131
+
132
+
133
+ def _token_scopes(token) -> set[str]:
134
+ return set(token.scope.split()) if token is not None and token.scope else set()
135
+
136
+
137
+ def build_api(
138
+ hooks: Iterable[object] | None = None,
139
+ *,
140
+ urls_namespace: str = "aa_desktop_bridge",
141
+ ) -> tuple[NinjaAPI, ModuleRegistry]:
142
+ """Build the API and mount the modules that pass the checks.
143
+
144
+ ``hooks`` overrides the Alliance Auth registry; tests pass fakes.
145
+ """
146
+
147
+ registry = load_modules(registered_module_hooks() if hooks is None else hooks)
148
+ api = NinjaAPI(
149
+ title="AA Desktop Bridge",
150
+ urls_namespace=urls_namespace,
151
+ auth=None,
152
+ docs_url=None,
153
+ openapi_url=None,
154
+ )
155
+
156
+ @api.get("/discovery", response=DiscoveryOut, auth=None)
157
+ def discovery(request: HttpRequest, response: HttpResponse):
158
+ _no_store(response)
159
+ return discovery_document(registry)
160
+
161
+ @api.get("/me", response=MeOut, auth=_core)
162
+ def me(request: HttpRequest, response: HttpResponse):
163
+ _no_store(response)
164
+ summary = account_summary(request.user)
165
+ summary["scopes"] = sorted(_token_scopes(request.auth))
166
+ summary["modules_available"] = [
167
+ module.id for module in registry.available_to(request.user)
168
+ ]
169
+ return summary
170
+
171
+ @api.get("/modules", response=ModulesOut, auth=_core)
172
+ def modules(request: HttpRequest, response: HttpResponse):
173
+ _no_store(response)
174
+ granted = _token_scopes(request.auth)
175
+ return {
176
+ "links": links_as_dicts(visible_links(request)),
177
+ "modules": [
178
+ {
179
+ "id": module.id,
180
+ "name": module.name,
181
+ "version": module.version,
182
+ "path": f"modules/{module.id}/",
183
+ "scopes": [
184
+ {"name": name, "description": description, "granted": name in granted}
185
+ for name, description in sorted(module.scopes.items())
186
+ ],
187
+ }
188
+ for module in registry.available_to(request.user)
189
+ ],
190
+ "packages": registered_packages(),
191
+ }
192
+
193
+ for module in list(registry.mounted):
194
+ try:
195
+ api.add_router(f"/modules/{module.id}/", module.router)
196
+ except Exception as error: # e.g. a router already attached elsewhere
197
+ registry.mounted.remove(module)
198
+ registry.skip(module.id, f"the router could not be mounted ({type(error).__name__})")
199
+
200
+ return api, registry
201
+
202
+
203
+ _built: tuple[NinjaAPI, ModuleRegistry] | None = None
204
+ _lock = threading.Lock()
205
+
206
+
207
+ def get_api() -> NinjaAPI:
208
+ return _get()[0]
209
+
210
+
211
+ def get_registry() -> ModuleRegistry:
212
+ return _get()[1]
213
+
214
+
215
+ def _get() -> tuple[NinjaAPI, ModuleRegistry]:
216
+ global _built
217
+ with _lock:
218
+ if _built is None:
219
+ _built = build_api()
220
+ return _built
@@ -0,0 +1,8 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class AaDesktopBridgeConfig(AppConfig):
5
+ default_auto_field = "django.db.models.BigAutoField"
6
+ name = "aa_desktop_bridge"
7
+ label = "aa_desktop_bridge"
8
+ verbose_name = "AA Desktop Bridge"
@@ -0,0 +1,71 @@
1
+ """Bearer-only authentication for the bridge API.
2
+
3
+ Tokens are django-oauth-toolkit access tokens, looked up by their stored
4
+ checksum. Session cookies are never consulted. An expired or unknown token
5
+ is a 401. A live token that lacks the route's scopes is a 403
6
+ ``insufficient_scope``. A user who lacks the route's Alliance Auth
7
+ permissions is a 403 ``permission_denied``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+
14
+ from django.http import HttpRequest
15
+ from ninja.errors import HttpError
16
+ from ninja.security import HttpBearer
17
+ from oauth2_provider.models import get_access_token_model
18
+
19
+
20
+ class DesktopBearer(HttpBearer):
21
+ """Validate a DOT access token and require every listed scope.
22
+
23
+ ``permissions`` are Alliance Auth permission names (``app.codename``)
24
+ the token's user must also hold. Module routes always pass them: a
25
+ scope limits what the client may do, a permission limits what the user
26
+ may do, and a request needs both.
27
+ """
28
+
29
+ def __init__(self, scopes: list[str], *, permissions: list[str] | tuple[str, ...] = ()) -> None:
30
+ if not scopes:
31
+ raise ValueError("a bridge route must name at least one scope")
32
+ if isinstance(permissions, str):
33
+ raise TypeError("permissions must be a list of permission names, not a string")
34
+ self.scopes = list(scopes)
35
+ self.permissions = tuple(permissions)
36
+ super().__init__()
37
+
38
+ def authenticate(self, request: HttpRequest, token: str):
39
+ # Query-string tokens are ignored because this class only receives the
40
+ # Authorization header value. Reject anything that is not a single
41
+ # token (no spaces) so a pasted header cannot smuggle a second scheme.
42
+ if not token or any(ch.isspace() for ch in token):
43
+ return None
44
+
45
+ access_token_model = get_access_token_model()
46
+ checksum = hashlib.sha256(token.encode("utf-8")).hexdigest()
47
+ try:
48
+ access = access_token_model.objects.select_related("user").get(
49
+ token_checksum=checksum
50
+ )
51
+ except access_token_model.DoesNotExist:
52
+ return None
53
+
54
+ if access.is_expired():
55
+ return None
56
+
57
+ user = access.user
58
+ if user is None or not user.is_active:
59
+ return None
60
+
61
+ if not access.allow_scopes(self.scopes):
62
+ raise HttpError(403, "insufficient_scope")
63
+
64
+ if self.permissions and not user.has_perms(self.permissions):
65
+ raise HttpError(403, "permission_denied")
66
+
67
+ # The view reads request.user. Ninja does not set it from the token,
68
+ # and AuthenticationMiddleware may already have set it from a session
69
+ # cookie. The token user wins; the cookie is not a credential here.
70
+ request.user = user
71
+ return access
@@ -0,0 +1,62 @@
1
+ """Public discovery document.
2
+
3
+ The desktop client joins these paths onto the server origin the user
4
+ confirmed. This view must not echo the request Host, and it must not claim
5
+ that a publisher-key signature was checked. Mounted modules and their
6
+ scopes are listed so the client can tell which ones this server has; which
7
+ of them a user may use is in the authenticated ``/modules``.
8
+ ``signature_enforced`` stays false until a later phase verifies an Ed25519 signature. A client that sees
9
+ ``true`` from a newer bridge and cannot verify the signature is required to
10
+ refuse the document.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from django.conf import settings
16
+
17
+ from .modules import ModuleRegistry
18
+ from .scopes import SCOPE_DESCRIPTIONS
19
+
20
+
21
+ def discovery_document(registry: ModuleRegistry | None = None) -> dict:
22
+ client_id = _client_id()
23
+ module_scopes = registry.scope_descriptions() if registry is not None else {}
24
+ scopes = [
25
+ {"name": name, "description": description}
26
+ for name, description in {**SCOPE_DESCRIPTIONS, **module_scopes}.items()
27
+ ]
28
+ modules = [
29
+ {
30
+ "id": module.id,
31
+ "name": module.name,
32
+ "version": module.version,
33
+ "scopes": sorted(module.scopes),
34
+ }
35
+ for module in (registry.mounted if registry is not None else [])
36
+ ]
37
+ return {
38
+ "api": "aa-desktop-bridge",
39
+ "api_version": 1,
40
+ "api_versions": [1],
41
+ "client_id": client_id,
42
+ "issuer_path": "/o",
43
+ "authorization_endpoint_path": "/o/authorize/",
44
+ "token_endpoint_path": "/o/token/",
45
+ "jwks_uri_path": "/o/.well-known/jwks.json",
46
+ "scopes": scopes,
47
+ "modules": modules,
48
+ "services": {},
49
+ "signature": None,
50
+ "signature_scheme": "ed25519",
51
+ "signature_enforced": False,
52
+ }
53
+
54
+
55
+ def _client_id() -> str | None:
56
+ value = getattr(settings, "AA_DESKTOP_OIDC_CLIENT_ID", None)
57
+ if not isinstance(value, str):
58
+ return None
59
+ value = value.strip()
60
+ if not value:
61
+ return None
62
+ return value