aa-desktop-bridge 0.2.0__py3-none-any.whl
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.
- aa_desktop_bridge/__init__.py +8 -0
- aa_desktop_bridge/account.py +151 -0
- aa_desktop_bridge/adapters.py +51 -0
- aa_desktop_bridge/api.py +220 -0
- aa_desktop_bridge/apps.py +8 -0
- aa_desktop_bridge/auth.py +71 -0
- aa_desktop_bridge/discovery.py +62 -0
- aa_desktop_bridge/launcher.py +165 -0
- aa_desktop_bridge/management/__init__.py +0 -0
- aa_desktop_bridge/management/commands/__init__.py +0 -0
- aa_desktop_bridge/management/commands/desktop_modules.py +50 -0
- aa_desktop_bridge/modules.py +273 -0
- aa_desktop_bridge/scopes.py +45 -0
- aa_desktop_bridge/urls.py +7 -0
- aa_desktop_bridge-0.2.0.dist-info/METADATA +51 -0
- aa_desktop_bridge-0.2.0.dist-info/RECORD +18 -0
- aa_desktop_bridge-0.2.0.dist-info/WHEEL +5 -0
- aa_desktop_bridge-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -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 []
|
aa_desktop_bridge/api.py
ADDED
|
@@ -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,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
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Tier-0 launcher.
|
|
2
|
+
|
|
3
|
+
Lists Alliance Auth menu hooks the current user can see, using the same
|
|
4
|
+
signal the side menu uses: ``render(request)`` returns empty when the app
|
|
5
|
+
hides the item. The response is structured data, never the rendered HTML.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Iterable, Sequence
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from django.http import HttpRequest
|
|
16
|
+
from django.urls import NoReverseMatch, reverse
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
_ID_RE = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$")
|
|
21
|
+
_LABEL_MAX = 150
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class LauncherLink:
|
|
26
|
+
id: str
|
|
27
|
+
kind: str
|
|
28
|
+
label: str
|
|
29
|
+
url_name: str
|
|
30
|
+
path: str
|
|
31
|
+
order: int
|
|
32
|
+
count: int | None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def visible_links(request: HttpRequest, hooks: Sequence[object] | None = None) -> list[LauncherLink]:
|
|
36
|
+
"""Return launcher links for ``request.user``.
|
|
37
|
+
|
|
38
|
+
``hooks`` overrides the Alliance Auth registry. Tests pass fakes.
|
|
39
|
+
Production loads ``menu_item_hook``. A hook that throws, renders an
|
|
40
|
+
empty string, or has a URL name that does not reverse to a single-slash
|
|
41
|
+
path is omitted.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
items = list(hooks) if hooks is not None else _load_menu_hooks()
|
|
45
|
+
links: list[LauncherLink] = []
|
|
46
|
+
for item in items:
|
|
47
|
+
link = _link_from_item(request, item)
|
|
48
|
+
if link is not None:
|
|
49
|
+
links.append(link)
|
|
50
|
+
links.sort(key=lambda link: (link.order, link.label.lower(), link.id))
|
|
51
|
+
return links
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _load_menu_hooks() -> list[object]:
|
|
55
|
+
try:
|
|
56
|
+
from allianceauth.hooks import get_hooks
|
|
57
|
+
except ImportError:
|
|
58
|
+
logger.info("allianceauth is not installed; launcher list is empty")
|
|
59
|
+
return []
|
|
60
|
+
try:
|
|
61
|
+
producers = get_hooks("menu_item_hook")
|
|
62
|
+
except Exception:
|
|
63
|
+
logger.warning("menu_item_hook registry failed; launcher list is empty")
|
|
64
|
+
return []
|
|
65
|
+
|
|
66
|
+
items: list[object] = []
|
|
67
|
+
for produce in producers:
|
|
68
|
+
try:
|
|
69
|
+
produced = produce()
|
|
70
|
+
except Exception:
|
|
71
|
+
logger.warning("a menu hook failed to construct; omitting it")
|
|
72
|
+
continue
|
|
73
|
+
if isinstance(produced, (list, tuple)):
|
|
74
|
+
items.extend(produced)
|
|
75
|
+
elif produced is not None:
|
|
76
|
+
items.append(produced)
|
|
77
|
+
return items
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _link_from_item(request: HttpRequest, item: object) -> LauncherLink | None:
|
|
81
|
+
render = getattr(item, "render", None)
|
|
82
|
+
url_name = getattr(item, "url_name", None)
|
|
83
|
+
if not callable(render) or not isinstance(url_name, str):
|
|
84
|
+
return None
|
|
85
|
+
if not _ID_RE.fullmatch(url_name):
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
rendered = render(request)
|
|
90
|
+
except Exception:
|
|
91
|
+
logger.warning("menu hook %s failed while rendering; omitting it", url_name)
|
|
92
|
+
return None
|
|
93
|
+
if not isinstance(rendered, str) or not rendered.strip():
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
path = _safe_path(url_name)
|
|
97
|
+
if path is None:
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
label = _label(getattr(item, "text", url_name))
|
|
101
|
+
order = _order(getattr(item, "order", None))
|
|
102
|
+
count = _count(getattr(item, "count", None))
|
|
103
|
+
return LauncherLink(
|
|
104
|
+
id=url_name,
|
|
105
|
+
kind="link",
|
|
106
|
+
label=label,
|
|
107
|
+
url_name=url_name,
|
|
108
|
+
path=path,
|
|
109
|
+
order=order,
|
|
110
|
+
count=count,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _safe_path(url_name: str) -> str | None:
|
|
115
|
+
try:
|
|
116
|
+
path = reverse(url_name)
|
|
117
|
+
except NoReverseMatch:
|
|
118
|
+
return None
|
|
119
|
+
except Exception:
|
|
120
|
+
return None
|
|
121
|
+
if not isinstance(path, str):
|
|
122
|
+
return None
|
|
123
|
+
if not path.startswith("/") or path.startswith("//"):
|
|
124
|
+
return None
|
|
125
|
+
if "\\" in path or "://" in path or "\x00" in path:
|
|
126
|
+
return None
|
|
127
|
+
return path
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _label(value: object) -> str:
|
|
131
|
+
text = str(value).replace("\r", " ").replace("\n", " ").strip()
|
|
132
|
+
if not text or "<" in text or ">" in text:
|
|
133
|
+
return "App"
|
|
134
|
+
if len(text) > _LABEL_MAX:
|
|
135
|
+
return text[:_LABEL_MAX]
|
|
136
|
+
return text
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _order(value: object) -> int:
|
|
140
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
141
|
+
return 9999
|
|
142
|
+
return value
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _count(value: object) -> int | None:
|
|
146
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
147
|
+
return None
|
|
148
|
+
if value < 0:
|
|
149
|
+
return None
|
|
150
|
+
return value
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def links_as_dicts(links: Iterable[LauncherLink]) -> list[dict]:
|
|
154
|
+
return [
|
|
155
|
+
{
|
|
156
|
+
"id": link.id,
|
|
157
|
+
"kind": link.kind,
|
|
158
|
+
"label": link.label,
|
|
159
|
+
"url_name": link.url_name,
|
|
160
|
+
"path": link.path,
|
|
161
|
+
"order": link.order,
|
|
162
|
+
"count": link.count,
|
|
163
|
+
}
|
|
164
|
+
for link in links
|
|
165
|
+
]
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""``manage.py desktop_modules``: which desktop modules are mounted, and why not.
|
|
2
|
+
|
|
3
|
+
Exits 1 when a module was skipped or a module scope is not registered in
|
|
4
|
+
``OAUTH2_PROVIDER["SCOPES"]``, so an image build can stop on it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from django.core.management.base import BaseCommand, CommandError
|
|
10
|
+
from oauth2_provider.scopes import get_scopes_backend
|
|
11
|
+
|
|
12
|
+
from aa_desktop_bridge.api import get_registry
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Command(BaseCommand):
|
|
16
|
+
help = "List AA Desktop modules from desktop_module_hook: mounted, skipped, and unregistered scopes."
|
|
17
|
+
|
|
18
|
+
def handle(self, *args, **options):
|
|
19
|
+
registry = get_registry()
|
|
20
|
+
registered = set(get_scopes_backend().get_all_scopes())
|
|
21
|
+
problems = 0
|
|
22
|
+
|
|
23
|
+
if not registry.mounted and not registry.skipped:
|
|
24
|
+
self.stdout.write("No desktop modules are registered.")
|
|
25
|
+
|
|
26
|
+
for module in registry.mounted:
|
|
27
|
+
if module.required_permissions:
|
|
28
|
+
requires = ", ".join(module.required_permissions)
|
|
29
|
+
else:
|
|
30
|
+
requires = "any signed-in user"
|
|
31
|
+
self.stdout.write(
|
|
32
|
+
f"mounted {module.id} {module.version} at modules/{module.id}/ "
|
|
33
|
+
f"(requires {requires})"
|
|
34
|
+
)
|
|
35
|
+
for scope in sorted(module.scopes):
|
|
36
|
+
if scope in registered:
|
|
37
|
+
self.stdout.write(f" scope {scope}")
|
|
38
|
+
else:
|
|
39
|
+
problems += 1
|
|
40
|
+
self.stdout.write(
|
|
41
|
+
f" scope {scope}: not in OAUTH2_PROVIDER['SCOPES'], "
|
|
42
|
+
"so it cannot be granted"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
for skipped in registry.skipped:
|
|
46
|
+
problems += 1
|
|
47
|
+
self.stdout.write(f"skipped {skipped.source}: {skipped.reason}")
|
|
48
|
+
|
|
49
|
+
if problems:
|
|
50
|
+
raise CommandError(f"{problems} problem(s) with desktop modules")
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Module-owned API routes, registered through ``desktop_module_hook``.
|
|
2
|
+
|
|
3
|
+
An Alliance Auth app that wants routes for the desktop client registers a
|
|
4
|
+
hook that returns a :class:`DesktopModule`::
|
|
5
|
+
|
|
6
|
+
from allianceauth import hooks
|
|
7
|
+
from ninja import Router
|
|
8
|
+
from aa_desktop_bridge.auth import DesktopBearer
|
|
9
|
+
from aa_desktop_bridge.modules import DesktopModule
|
|
10
|
+
|
|
11
|
+
SCOPE = "desktop.example.read"
|
|
12
|
+
PERMISSIONS = ("example.basic_access",)
|
|
13
|
+
router = Router()
|
|
14
|
+
|
|
15
|
+
@router.get("items", auth=DesktopBearer([SCOPE], permissions=PERMISSIONS))
|
|
16
|
+
def items(request):
|
|
17
|
+
...
|
|
18
|
+
|
|
19
|
+
@hooks.register("desktop_module_hook")
|
|
20
|
+
def register_desktop_module():
|
|
21
|
+
return DesktopModule(
|
|
22
|
+
id="example",
|
|
23
|
+
name="Example",
|
|
24
|
+
version="1.0.0",
|
|
25
|
+
scopes={SCOPE: "See your example items."},
|
|
26
|
+
required_permissions=PERMISSIONS,
|
|
27
|
+
router=router,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
The bridge mounts the router at ``/api/desktop/v1/modules/<id>/``. It checks
|
|
31
|
+
each descriptor before mounting and skips (and logs) any that fails; a module
|
|
32
|
+
is mounted whole or not at all. The rules:
|
|
33
|
+
|
|
34
|
+
* ``id`` matches ``[a-z][a-z0-9-]{1,31}`` and is not reserved. Two hooks that
|
|
35
|
+
claim the same id are both skipped.
|
|
36
|
+
* Every scope is ``desktop.<id>`` or ``desktop.<id>.<name>``, so a module can
|
|
37
|
+
neither claim ``desktop.core`` nor another module's scopes.
|
|
38
|
+
* ``required_permissions`` is the floor for the whole module. It may be empty.
|
|
39
|
+
An empty floor means any active signed-in user is offered the module and may
|
|
40
|
+
call routes that do not add permissions of their own. A non-empty floor is
|
|
41
|
+
still required on every route, and a user without all of those permissions
|
|
42
|
+
is not offered the module.
|
|
43
|
+
* Every route authenticates with :class:`DesktopBearer` only (no session or
|
|
44
|
+
other auth beside it) and names only the module's own scopes. A route must
|
|
45
|
+
require every permission in the floor and may require more (an upload or
|
|
46
|
+
admin route, for example). The extra names are enforced on that route only.
|
|
47
|
+
* The router is flat (no nested routers), and route paths do not start with
|
|
48
|
+
the names the bridge keeps for itself under a module (``package``,
|
|
49
|
+
``openapi.json``).
|
|
50
|
+
|
|
51
|
+
These checks catch mistakes. A module is still server code the admin chose to
|
|
52
|
+
install; it is not a sandbox.
|
|
53
|
+
|
|
54
|
+
The admin registers each module scope in ``OAUTH2_PROVIDER["SCOPES"]``, like
|
|
55
|
+
``desktop.core``. A scope that is not registered cannot be granted, so its
|
|
56
|
+
routes answer 403 until it is. ``manage.py desktop_modules`` lists mounted and
|
|
57
|
+
skipped modules and unregistered scopes.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
from __future__ import annotations
|
|
61
|
+
|
|
62
|
+
import logging
|
|
63
|
+
import re
|
|
64
|
+
from collections.abc import Iterable, Mapping
|
|
65
|
+
from dataclasses import dataclass, field
|
|
66
|
+
|
|
67
|
+
from ninja import Router
|
|
68
|
+
from ninja.constants import NOT_SET
|
|
69
|
+
|
|
70
|
+
from .auth import DesktopBearer
|
|
71
|
+
|
|
72
|
+
logger = logging.getLogger(__name__)
|
|
73
|
+
|
|
74
|
+
MODULE_ID_RE = re.compile(r"^[a-z][a-z0-9-]{1,31}$")
|
|
75
|
+
RESERVED_IDS = frozenset({"bridge", "core", "desktop", "generic"})
|
|
76
|
+
RESERVED_FIRST_SEGMENTS = frozenset({"package", "openapi.json"})
|
|
77
|
+
|
|
78
|
+
_SCOPE_SUFFIX_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
|
|
79
|
+
_PERMISSION_RE = re.compile(r"^[A-Za-z0-9_]+\.[A-Za-z0-9_]+$")
|
|
80
|
+
_VERSION_RE = re.compile(r"^[0-9A-Za-z][0-9A-Za-z.+-]{0,31}$")
|
|
81
|
+
_NAME_MAX = 64
|
|
82
|
+
_DESCRIPTION_MAX = 200
|
|
83
|
+
_MAX_SCOPES = 16
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class DesktopModule:
|
|
88
|
+
"""What a ``desktop_module_hook`` returns."""
|
|
89
|
+
|
|
90
|
+
id: str
|
|
91
|
+
name: str
|
|
92
|
+
version: str
|
|
93
|
+
scopes: Mapping[str, str]
|
|
94
|
+
router: Router
|
|
95
|
+
required_permissions: tuple[str, ...] = ()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class SkippedModule:
|
|
100
|
+
source: str
|
|
101
|
+
reason: str
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass
|
|
105
|
+
class ModuleRegistry:
|
|
106
|
+
mounted: list[DesktopModule] = field(default_factory=list)
|
|
107
|
+
skipped: list[SkippedModule] = field(default_factory=list)
|
|
108
|
+
|
|
109
|
+
def scope_descriptions(self) -> dict[str, str]:
|
|
110
|
+
return {
|
|
111
|
+
name: description
|
|
112
|
+
for module in self.mounted
|
|
113
|
+
for name, description in module.scopes.items()
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
def skip(self, source: str, reason: str) -> None:
|
|
117
|
+
logger.warning("desktop module from %s was not mounted: %s", source, reason)
|
|
118
|
+
self.skipped.append(SkippedModule(source=source, reason=reason))
|
|
119
|
+
|
|
120
|
+
def available_to(self, user) -> list[DesktopModule]:
|
|
121
|
+
return [
|
|
122
|
+
module
|
|
123
|
+
for module in self.mounted
|
|
124
|
+
if user.is_active and user.has_perms(module.required_permissions)
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class ModuleRefused(Exception):
|
|
129
|
+
"""A descriptor that breaks a rule. The message says which."""
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def check_module(module: object) -> DesktopModule:
|
|
133
|
+
"""Return ``module`` if it may be mounted; raise :class:`ModuleRefused` otherwise."""
|
|
134
|
+
|
|
135
|
+
if not isinstance(module, DesktopModule):
|
|
136
|
+
raise ModuleRefused("the hook did not return a DesktopModule")
|
|
137
|
+
|
|
138
|
+
if not isinstance(module.id, str) or not MODULE_ID_RE.fullmatch(module.id):
|
|
139
|
+
raise ModuleRefused("id must match [a-z][a-z0-9-]{1,31}")
|
|
140
|
+
if module.id in RESERVED_IDS:
|
|
141
|
+
raise ModuleRefused(f"id {module.id!r} is reserved")
|
|
142
|
+
|
|
143
|
+
if not _plain_text(module.name, _NAME_MAX):
|
|
144
|
+
raise ModuleRefused("name must be 1 to 64 characters of plain text")
|
|
145
|
+
if not isinstance(module.version, str) or not _VERSION_RE.fullmatch(module.version):
|
|
146
|
+
raise ModuleRefused("version must be a short version string")
|
|
147
|
+
|
|
148
|
+
scopes = _check_scopes(module)
|
|
149
|
+
permissions = _check_permissions(module)
|
|
150
|
+
_check_router(module, scopes, permissions)
|
|
151
|
+
return module
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _check_scopes(module: DesktopModule) -> set[str]:
|
|
155
|
+
if not isinstance(module.scopes, Mapping) or not module.scopes:
|
|
156
|
+
raise ModuleRefused("a module must declare at least one scope")
|
|
157
|
+
if len(module.scopes) > _MAX_SCOPES:
|
|
158
|
+
raise ModuleRefused(f"a module may declare at most {_MAX_SCOPES} scopes")
|
|
159
|
+
own = f"desktop.{module.id}"
|
|
160
|
+
for name, description in module.scopes.items():
|
|
161
|
+
if not isinstance(name, str):
|
|
162
|
+
raise ModuleRefused("scope names must be strings")
|
|
163
|
+
if name != own:
|
|
164
|
+
prefix = own + "."
|
|
165
|
+
if not name.startswith(prefix) or not _SCOPE_SUFFIX_RE.fullmatch(name[len(prefix):]):
|
|
166
|
+
raise ModuleRefused(f"scope {name!r} must be {own} or {own}.<name>")
|
|
167
|
+
if not _plain_text(description, _DESCRIPTION_MAX):
|
|
168
|
+
raise ModuleRefused(f"scope {name!r} needs a plain-text description up to 200 characters")
|
|
169
|
+
return set(module.scopes)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _check_permissions(module: DesktopModule) -> set[str]:
|
|
173
|
+
permissions = module.required_permissions
|
|
174
|
+
if isinstance(permissions, str) or not isinstance(permissions, (tuple, list)):
|
|
175
|
+
raise ModuleRefused("required_permissions must be a tuple of permission names")
|
|
176
|
+
# An empty tuple is the open floor: any active signed-in user. Routes may
|
|
177
|
+
# still name extra permissions of their own.
|
|
178
|
+
for permission in permissions:
|
|
179
|
+
if not isinstance(permission, str) or not _PERMISSION_RE.fullmatch(permission):
|
|
180
|
+
raise ModuleRefused(f"permission {permission!r} must look like app_label.codename")
|
|
181
|
+
return set(permissions)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _check_router(module: DesktopModule, scopes: set[str], permissions: set[str]) -> None:
|
|
185
|
+
router = module.router
|
|
186
|
+
if not isinstance(router, Router):
|
|
187
|
+
raise ModuleRefused("router must be a ninja Router")
|
|
188
|
+
if getattr(router, "_routers", None):
|
|
189
|
+
raise ModuleRefused("nested routers are not supported; use one flat router")
|
|
190
|
+
|
|
191
|
+
operations = 0
|
|
192
|
+
for path, path_view in router.path_operations.items():
|
|
193
|
+
first = path.strip("/").split("/", 1)[0]
|
|
194
|
+
if first in RESERVED_FIRST_SEGMENTS:
|
|
195
|
+
raise ModuleRefused(f"route {path!r} uses a path the bridge keeps for itself")
|
|
196
|
+
for operation in path_view.operations:
|
|
197
|
+
operations += 1
|
|
198
|
+
auth = operation.auth_param
|
|
199
|
+
if auth is NOT_SET:
|
|
200
|
+
auth = router.auth
|
|
201
|
+
_check_auth(path, auth, scopes, permissions)
|
|
202
|
+
if operations == 0:
|
|
203
|
+
raise ModuleRefused("the router has no routes")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _check_auth(path: str, auth: object, scopes: set[str], permissions: set[str]) -> None:
|
|
207
|
+
if auth is NOT_SET or auth is None:
|
|
208
|
+
raise ModuleRefused(f"route {path!r} has no authentication")
|
|
209
|
+
callbacks = list(auth) if isinstance(auth, (list, tuple)) else [auth]
|
|
210
|
+
if not callbacks:
|
|
211
|
+
raise ModuleRefused(f"route {path!r} has no authentication")
|
|
212
|
+
for callback in callbacks:
|
|
213
|
+
# Ninja tries auth callbacks in turn and accepts the first that
|
|
214
|
+
# passes, so a second, weaker one would be a way around the bearer.
|
|
215
|
+
if not isinstance(callback, DesktopBearer):
|
|
216
|
+
raise ModuleRefused(f"route {path!r} must authenticate with DesktopBearer only")
|
|
217
|
+
if not set(callback.scopes) <= scopes:
|
|
218
|
+
raise ModuleRefused(f"route {path!r} names a scope the module did not declare")
|
|
219
|
+
route_permissions = set(callback.permissions)
|
|
220
|
+
if not permissions <= route_permissions:
|
|
221
|
+
raise ModuleRefused(
|
|
222
|
+
f"route {path!r} must require all of the module's required_permissions"
|
|
223
|
+
)
|
|
224
|
+
for extra in route_permissions - permissions:
|
|
225
|
+
if not _PERMISSION_RE.fullmatch(extra):
|
|
226
|
+
raise ModuleRefused(
|
|
227
|
+
f"route {path!r} permission {extra!r} must look like app_label.codename"
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _plain_text(value: object, limit: int) -> bool:
|
|
232
|
+
if not isinstance(value, str):
|
|
233
|
+
return False
|
|
234
|
+
text = value.strip()
|
|
235
|
+
if not text or len(text) > limit:
|
|
236
|
+
return False
|
|
237
|
+
if "<" in text or ">" in text:
|
|
238
|
+
return False
|
|
239
|
+
return not any(ord(ch) < 32 or ord(ch) == 127 for ch in text)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def load_modules(hooks: Iterable[object]) -> ModuleRegistry:
|
|
243
|
+
"""Call each hook and keep the descriptors that pass :func:`check_module`."""
|
|
244
|
+
|
|
245
|
+
registry = ModuleRegistry()
|
|
246
|
+
candidates: list[tuple[str, DesktopModule]] = []
|
|
247
|
+
for hook in hooks:
|
|
248
|
+
source = _source(hook)
|
|
249
|
+
try:
|
|
250
|
+
produced = hook() if callable(hook) else hook
|
|
251
|
+
candidates.append((source, check_module(produced)))
|
|
252
|
+
except ModuleRefused as refusal:
|
|
253
|
+
registry.skip(source, str(refusal))
|
|
254
|
+
except Exception:
|
|
255
|
+
logger.exception("desktop module hook %s failed", source)
|
|
256
|
+
registry.skip(source, "the hook raised an exception")
|
|
257
|
+
|
|
258
|
+
counts: dict[str, int] = {}
|
|
259
|
+
for _, module in candidates:
|
|
260
|
+
counts[module.id] = counts.get(module.id, 0) + 1
|
|
261
|
+
for source, module in candidates:
|
|
262
|
+
if counts[module.id] > 1:
|
|
263
|
+
registry.skip(source, f"more than one hook claims the id {module.id!r}")
|
|
264
|
+
else:
|
|
265
|
+
registry.mounted.append(module)
|
|
266
|
+
registry.mounted.sort(key=lambda module: module.id)
|
|
267
|
+
return registry
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _source(hook: object) -> str:
|
|
271
|
+
module = getattr(hook, "__module__", None) or type(hook).__module__
|
|
272
|
+
name = getattr(hook, "__qualname__", None) or type(hook).__qualname__
|
|
273
|
+
return f"{module}.{name}"
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""OAuth scopes the bridge understands.
|
|
2
|
+
|
|
3
|
+
Register these descriptions on the Alliance Auth instance
|
|
4
|
+
(``OAUTH2_PROVIDER['SCOPES']``). The desktop client requests the union of
|
|
5
|
+
scopes for features the user has turned on. This phase only requests
|
|
6
|
+
``desktop.core``. Later phases add the names below; they are not granted
|
|
7
|
+
by any route here.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
DESKTOP_CORE = "desktop.core"
|
|
11
|
+
|
|
12
|
+
# Reserved for later phases. No route accepts these yet.
|
|
13
|
+
RESERVED_SCOPES = (
|
|
14
|
+
"desktop.notifications",
|
|
15
|
+
"desktop.groups.read",
|
|
16
|
+
"desktop.groups.write",
|
|
17
|
+
"desktop.services.read",
|
|
18
|
+
"desktop.timers.read",
|
|
19
|
+
"desktop.timers.write",
|
|
20
|
+
"desktop.fleet.read",
|
|
21
|
+
"desktop.fleet.write",
|
|
22
|
+
"desktop.buyback.read",
|
|
23
|
+
"desktop.buyback.quote",
|
|
24
|
+
"desktop.wormhole",
|
|
25
|
+
"desktop.generic.read",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
SCOPE_DESCRIPTIONS = {
|
|
29
|
+
DESKTOP_CORE: "See your Alliance Auth account and open apps you can already access.",
|
|
30
|
+
"desktop.notifications": "Read and acknowledge Alliance Auth notifications.",
|
|
31
|
+
"desktop.groups.read": "See groups and your membership.",
|
|
32
|
+
"desktop.groups.write": "Request to join or leave groups.",
|
|
33
|
+
"desktop.services.read": "See service link status.",
|
|
34
|
+
"desktop.timers.read": "See upcoming timers.",
|
|
35
|
+
"desktop.timers.write": "Create or edit timers you are allowed to change.",
|
|
36
|
+
"desktop.fleet.read": "See fleets you can see on the site.",
|
|
37
|
+
"desktop.fleet.write": "Record fleet participation.",
|
|
38
|
+
"desktop.buyback.read": "See buyback programs and your contracts.",
|
|
39
|
+
"desktop.buyback.quote": "Price an item list.",
|
|
40
|
+
"desktop.wormhole": "Use the wormhole map service advertised by this server.",
|
|
41
|
+
"desktop.generic.read": "Read admin-approved declarative app data.",
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
# Requested by the desktop client during phase-1 login.
|
|
45
|
+
PHASE1_LOGIN_SCOPES = ("openid", "profile", "offline_access", DESKTOP_CORE)
|
|
@@ -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,18 @@
|
|
|
1
|
+
aa_desktop_bridge/__init__.py,sha256=-45varLTfR88_5pFJz3XYzTMi7EbtKrUZkzzrdcNNW0,266
|
|
2
|
+
aa_desktop_bridge/account.py,sha256=L6pqKU6rTJ-5T-IzEUEWCTPXfSRb7iPSTNgaQPAylGc,4711
|
|
3
|
+
aa_desktop_bridge/adapters.py,sha256=oT1Bn5jUnTJ-bq7VPgV_7mGxaxkhE5njQ1xGDnrXmpE,1662
|
|
4
|
+
aa_desktop_bridge/api.py,sha256=P8IIJStw3shLUDHJVo-biglUXFTXn8e9A205iqwQiTA,5831
|
|
5
|
+
aa_desktop_bridge/apps.py,sha256=I684268L5Ldt9QClDHLMgGtTQWQMreIhywq8GYP-r3s,235
|
|
6
|
+
aa_desktop_bridge/auth.py,sha256=tNTjQHRl2iU5N8AHWEoNCAYxoNJcusUIJOo-vCzIzOE,2793
|
|
7
|
+
aa_desktop_bridge/discovery.py,sha256=_41f9bYiIuC__gZofsd2rTV-rM-Bhvw9lSK2vO0E46Q,2072
|
|
8
|
+
aa_desktop_bridge/launcher.py,sha256=a2VEGSoDM3QXsgPcPtOIunzRSmy2eCE4OfA0sGIm7ME,4560
|
|
9
|
+
aa_desktop_bridge/modules.py,sha256=l8CFNvah5RuX3ES_p6Ra5BZJi0JDHFJuZFlSeKQ7Ttg,10883
|
|
10
|
+
aa_desktop_bridge/scopes.py,sha256=k8tRqO7iiuw84k_PszMVJMZwD_DAix1r3iLemN_n4x8,1827
|
|
11
|
+
aa_desktop_bridge/urls.py,sha256=1aL6UHjU7yD4uWNLAqSMXhppSUOYe3x-vGG0XgAC1N0,119
|
|
12
|
+
aa_desktop_bridge/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
13
|
+
aa_desktop_bridge/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
14
|
+
aa_desktop_bridge/management/commands/desktop_modules.py,sha256=R3YGRQn1xj8agma3rtojT-NrJjmr1zp5Chu1JpcgNs4,1890
|
|
15
|
+
aa_desktop_bridge-0.2.0.dist-info/METADATA,sha256=cSaUuSSbScM7FldYqmSqTzbGlo7LqfiOlFOOpqC1JG0,2755
|
|
16
|
+
aa_desktop_bridge-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
17
|
+
aa_desktop_bridge-0.2.0.dist-info/top_level.txt,sha256=1rf0kP7ioXmE_UKZMZtBvpvGZ_rqro9awwHx6KFp70U,18
|
|
18
|
+
aa_desktop_bridge-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
aa_desktop_bridge
|