fleetmesh-auth 0.1.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.
- fleetmesh_auth/__init__.py +71 -0
- fleetmesh_auth/__main__.py +5 -0
- fleetmesh_auth/directory.py +60 -0
- fleetmesh_auth/engine.py +404 -0
- fleetmesh_auth/http_routes.py +129 -0
- fleetmesh_auth/nip46_bunker.py +162 -0
- fleetmesh_auth/principal.py +214 -0
- fleetmesh_auth/providers/__init__.py +12 -0
- fleetmesh_auth/providers/base.py +34 -0
- fleetmesh_auth/providers/key_did.py +238 -0
- fleetmesh_auth/providers/local_operator.py +92 -0
- fleetmesh_auth/providers/meshtube.py +266 -0
- fleetmesh_auth/schema_probe.py +23 -0
- fleetmesh_auth/server.py +144 -0
- fleetmesh_auth/settings.py +76 -0
- fleetmesh_auth/studio_directory.py +344 -0
- fleetmesh_auth/ui_widget.py +1076 -0
- fleetmesh_auth-0.1.0.dist-info/METADATA +66 -0
- fleetmesh_auth-0.1.0.dist-info/RECORD +23 -0
- fleetmesh_auth-0.1.0.dist-info/WHEEL +5 -0
- fleetmesh_auth-0.1.0.dist-info/entry_points.txt +2 -0
- fleetmesh_auth-0.1.0.dist-info/licenses/LICENSE +121 -0
- fleetmesh_auth-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""FleetMesh Auth (`fleetmesh_auth`) — Unified Pluggable Identity & SSO."""
|
|
2
|
+
import os as _os
|
|
3
|
+
import sys as _sys
|
|
4
|
+
|
|
5
|
+
_CORE_DIR = _os.path.abspath(_os.path.join(_os.path.dirname(__file__), "..", "..", "core"))
|
|
6
|
+
if _os.path.isdir(_CORE_DIR) and _CORE_DIR not in _sys.path:
|
|
7
|
+
_sys.path.insert(0, _CORE_DIR)
|
|
8
|
+
|
|
9
|
+
from fleetmesh_auth.engine import FleetmeshAuthEngine
|
|
10
|
+
from fleetmesh_auth.http_routes import (
|
|
11
|
+
extract_request_token,
|
|
12
|
+
handle_fauth_get,
|
|
13
|
+
handle_fauth_post,
|
|
14
|
+
)
|
|
15
|
+
from fleetmesh_auth.nip46_bunker import (
|
|
16
|
+
BunkerDescriptor,
|
|
17
|
+
decode_bech32_hex,
|
|
18
|
+
normalize_pubkey_or_did,
|
|
19
|
+
normalize_secret_key,
|
|
20
|
+
parse_bunker_uri,
|
|
21
|
+
sign_challenge_with_secret_key,
|
|
22
|
+
)
|
|
23
|
+
from fleetmesh_auth.principal import (
|
|
24
|
+
PRESET_WIDGET_CONFIGS,
|
|
25
|
+
AuthPrincipal,
|
|
26
|
+
AuthWidgetConfig,
|
|
27
|
+
expand_roles,
|
|
28
|
+
has_required_role,
|
|
29
|
+
resolve_widget_config,
|
|
30
|
+
)
|
|
31
|
+
from fleetmesh_auth.providers import (
|
|
32
|
+
AuthProviderPlugin,
|
|
33
|
+
LocalOperatorProvider,
|
|
34
|
+
MeshTubeAuthProvider,
|
|
35
|
+
SovereignKeyBunkerProvider,
|
|
36
|
+
)
|
|
37
|
+
from fleetmesh_auth.server import create_auth_http_server
|
|
38
|
+
from fleetmesh_auth.ui_widget import (
|
|
39
|
+
render_auth_bundle_html,
|
|
40
|
+
render_auth_widget_css,
|
|
41
|
+
render_auth_widget_html,
|
|
42
|
+
render_auth_widget_js,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"AuthPrincipal",
|
|
47
|
+
"AuthProviderPlugin",
|
|
48
|
+
"AuthWidgetConfig",
|
|
49
|
+
"BunkerDescriptor",
|
|
50
|
+
"FleetmeshAuthEngine",
|
|
51
|
+
"LocalOperatorProvider",
|
|
52
|
+
"MeshTubeAuthProvider",
|
|
53
|
+
"PRESET_WIDGET_CONFIGS",
|
|
54
|
+
"SovereignKeyBunkerProvider",
|
|
55
|
+
"create_auth_http_server",
|
|
56
|
+
"decode_bech32_hex",
|
|
57
|
+
"expand_roles",
|
|
58
|
+
"extract_request_token",
|
|
59
|
+
"handle_fauth_get",
|
|
60
|
+
"handle_fauth_post",
|
|
61
|
+
"has_required_role",
|
|
62
|
+
"normalize_pubkey_or_did",
|
|
63
|
+
"normalize_secret_key",
|
|
64
|
+
"parse_bunker_uri",
|
|
65
|
+
"render_auth_bundle_html",
|
|
66
|
+
"render_auth_widget_css",
|
|
67
|
+
"render_auth_widget_html",
|
|
68
|
+
"render_auth_widget_js",
|
|
69
|
+
"resolve_widget_config",
|
|
70
|
+
"sign_challenge_with_secret_key",
|
|
71
|
+
]
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Where an app keeps its users: the one surface fleetmesh_auth needs from it.
|
|
2
|
+
|
|
3
|
+
fleetmesh_auth proves who someone is; the app hosting it decides who its users
|
|
4
|
+
are. A `UserDirectory` finds or creates the app's record for a proven pubkey,
|
|
5
|
+
names the keys the app itself runs as, and carries sessions into the app's own
|
|
6
|
+
session tables when it has any. `StudioDirectory` (studio_directory.py) adapts
|
|
7
|
+
a co-hosted StudioEngine; an app without users of its own passes none.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import TYPE_CHECKING, FrozenSet, List, Optional, Protocol, TypedDict
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from fleetmesh_auth.principal import AuthPrincipal
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class UserRecord(TypedDict):
|
|
18
|
+
user_id: str
|
|
19
|
+
handle: str
|
|
20
|
+
display_name: str
|
|
21
|
+
roles: List[str]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class UserDirectory(Protocol):
|
|
25
|
+
def own_pubkeys(self) -> FrozenSet[str]:
|
|
26
|
+
"""Pubkeys the app runs as (operator, node): they sign in as operators."""
|
|
27
|
+
...
|
|
28
|
+
|
|
29
|
+
def find_user(self, pubkey_hex: str) -> Optional[UserRecord]:
|
|
30
|
+
"""The app's user for this pubkey, if it has one."""
|
|
31
|
+
...
|
|
32
|
+
|
|
33
|
+
def create_user(self, pubkey_hex: str, handle_hint: Optional[str]) -> Optional[UserRecord]:
|
|
34
|
+
"""Make a user for a pubkey seen for the first time; None if the app declines."""
|
|
35
|
+
...
|
|
36
|
+
|
|
37
|
+
def link_session(
|
|
38
|
+
self,
|
|
39
|
+
token: str,
|
|
40
|
+
principal: "AuthPrincipal",
|
|
41
|
+
issued_at: int,
|
|
42
|
+
expires_at: int,
|
|
43
|
+
operator_pubkeys: FrozenSet[str],
|
|
44
|
+
) -> None:
|
|
45
|
+
"""Make `token` a session in the app's own tables too (no-op if it keeps none)."""
|
|
46
|
+
...
|
|
47
|
+
|
|
48
|
+
def has_session(self, token: str) -> bool:
|
|
49
|
+
...
|
|
50
|
+
|
|
51
|
+
def resolve_session(self, token: str, now: int, ttl_sec: int) -> Optional["AuthPrincipal"]:
|
|
52
|
+
"""A session (or API key) the app issued itself, as a principal."""
|
|
53
|
+
...
|
|
54
|
+
|
|
55
|
+
def revoke_session(self, token: str) -> None:
|
|
56
|
+
...
|
|
57
|
+
|
|
58
|
+
def default_db_path(self) -> Optional[str]:
|
|
59
|
+
"""Where fleetmesh_auth's own database should live beside the app's, if anywhere."""
|
|
60
|
+
...
|
fleetmesh_auth/engine.py
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
"""Core authentication engine for FleetMesh Auth (`fleetmesh_auth.engine`)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import secrets
|
|
6
|
+
import sqlite3
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
from typing import Any, Dict, List, Optional
|
|
10
|
+
|
|
11
|
+
from fleetmesh_core.identity.web_auth import FederatedWebAuth
|
|
12
|
+
|
|
13
|
+
from fleetmesh_auth.directory import UserDirectory
|
|
14
|
+
from fleetmesh_auth.principal import (
|
|
15
|
+
AuthPrincipal,
|
|
16
|
+
AuthWidgetConfig,
|
|
17
|
+
resolve_widget_config,
|
|
18
|
+
)
|
|
19
|
+
from fleetmesh_auth.providers.base import AuthProviderPlugin
|
|
20
|
+
from fleetmesh_auth.providers.key_did import SovereignKeyBunkerProvider
|
|
21
|
+
from fleetmesh_auth.providers.local_operator import LocalOperatorProvider
|
|
22
|
+
from fleetmesh_auth.providers.meshtube import MeshTubeAuthProvider
|
|
23
|
+
from fleetmesh_auth.studio_directory import StudioDirectory
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class FleetmeshAuthEngine:
|
|
27
|
+
"""Pluggable multi-provider authentication engine for FleetMesh applications.
|
|
28
|
+
|
|
29
|
+
Coordinates:
|
|
30
|
+
- Sovereign Key / DID / NIP-46 Bunker / NIP-07 Browser Extension auth
|
|
31
|
+
- Service Provider auth (e.g. 'Sign in with MeshTube')
|
|
32
|
+
- Standalone Node Operator Token auth (`LocalOperatorProvider`)
|
|
33
|
+
- Unified session storage (`fleetmesh_auth_sessions`) + automatic session bridging
|
|
34
|
+
with attached `StudioEngine` (`sessions` and `admin_sessions`) when co-hosted.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
*,
|
|
40
|
+
db_path: Optional[str] = None,
|
|
41
|
+
studio: Any = None,
|
|
42
|
+
directory: Optional[UserDirectory] = None,
|
|
43
|
+
domain: str = "fleetmesh.local",
|
|
44
|
+
session_ttl_sec: int = 86400 * 7,
|
|
45
|
+
allow_any_sovereign_key: bool = False,
|
|
46
|
+
) -> None:
|
|
47
|
+
# The app's users: an explicit directory, else a co-hosted StudioEngine's.
|
|
48
|
+
# `studio` itself stays for the MeshTube provider, which is that app's login.
|
|
49
|
+
self._explicit_directory = directory
|
|
50
|
+
self.directory: Optional[UserDirectory] = directory
|
|
51
|
+
self.studio = studio
|
|
52
|
+
self.domain = domain
|
|
53
|
+
self.session_ttl_sec = int(session_ttl_sec)
|
|
54
|
+
self.allow_any_sovereign_key = bool(allow_any_sovereign_key)
|
|
55
|
+
self._db_lock = threading.RLock()
|
|
56
|
+
|
|
57
|
+
if db_path is None and self.directory is not None:
|
|
58
|
+
db_path = self.directory.default_db_path()
|
|
59
|
+
self.db_path = db_path or ":memory:"
|
|
60
|
+
|
|
61
|
+
self._conn = sqlite3.connect(self.db_path, check_same_thread=False)
|
|
62
|
+
self._conn.row_factory = sqlite3.Row
|
|
63
|
+
if self.db_path != ":memory:":
|
|
64
|
+
with self._db_lock:
|
|
65
|
+
self._conn.execute("PRAGMA journal_mode=WAL")
|
|
66
|
+
self._init_schema()
|
|
67
|
+
|
|
68
|
+
origin_url = domain if domain.startswith(("http://", "https://")) else f"https://{domain}"
|
|
69
|
+
# web_auth shares this connection, so it takes the same lock and
|
|
70
|
+
# holds it only around its own statements.
|
|
71
|
+
self.web_auth = FederatedWebAuth(
|
|
72
|
+
conn=self._conn,
|
|
73
|
+
origin_url=origin_url,
|
|
74
|
+
challenge_ttl_sec=600,
|
|
75
|
+
lock=self._db_lock,
|
|
76
|
+
)
|
|
77
|
+
self.providers: Dict[str, AuthProviderPlugin] = {}
|
|
78
|
+
|
|
79
|
+
# Register built-in providers
|
|
80
|
+
self._key_provider = SovereignKeyBunkerProvider()
|
|
81
|
+
self.register_provider(MeshTubeAuthProvider())
|
|
82
|
+
self.register_provider(self._key_provider)
|
|
83
|
+
self.register_provider(LocalOperatorProvider())
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def studio(self) -> Any:
|
|
87
|
+
return self._studio
|
|
88
|
+
|
|
89
|
+
@studio.setter
|
|
90
|
+
def studio(self, studio: Any) -> None:
|
|
91
|
+
"""Attaching a StudioEngine (here or later) makes it the user directory,
|
|
92
|
+
unless one was given explicitly."""
|
|
93
|
+
self._studio = studio
|
|
94
|
+
if self._explicit_directory is None:
|
|
95
|
+
self.directory = StudioDirectory(studio) if studio is not None else None
|
|
96
|
+
|
|
97
|
+
def _init_schema(self) -> None:
|
|
98
|
+
with self._db_lock:
|
|
99
|
+
self._conn.execute(
|
|
100
|
+
"""
|
|
101
|
+
CREATE TABLE IF NOT EXISTS fleetmesh_auth_sessions (
|
|
102
|
+
session_token TEXT PRIMARY KEY,
|
|
103
|
+
principal_id TEXT NOT NULL,
|
|
104
|
+
did TEXT NOT NULL,
|
|
105
|
+
pubkey_hex TEXT NOT NULL,
|
|
106
|
+
handle TEXT NOT NULL,
|
|
107
|
+
display_name TEXT NOT NULL,
|
|
108
|
+
provider TEXT NOT NULL,
|
|
109
|
+
auth_method TEXT NOT NULL,
|
|
110
|
+
roles_json TEXT NOT NULL,
|
|
111
|
+
scopes_json TEXT NOT NULL,
|
|
112
|
+
metadata_json TEXT NOT NULL,
|
|
113
|
+
issued_at INTEGER NOT NULL,
|
|
114
|
+
expires_at INTEGER NOT NULL
|
|
115
|
+
)
|
|
116
|
+
"""
|
|
117
|
+
)
|
|
118
|
+
self._conn.execute(
|
|
119
|
+
"CREATE TABLE IF NOT EXISTS fleetmesh_auth_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
|
|
120
|
+
)
|
|
121
|
+
# Earlier versions kept a ticket-signing key here and signed users'
|
|
122
|
+
# portable tickets with it, which logged them all in as that key.
|
|
123
|
+
# Nothing signs with it now; a secret nobody uses is only a risk.
|
|
124
|
+
self._conn.execute("DELETE FROM fleetmesh_auth_meta WHERE key = 'issuer_sk_hex'")
|
|
125
|
+
self._conn.commit()
|
|
126
|
+
|
|
127
|
+
_init_db = _init_schema
|
|
128
|
+
|
|
129
|
+
def register_provider(self, provider: AuthProviderPlugin) -> None:
|
|
130
|
+
self.providers[provider.provider_id] = provider
|
|
131
|
+
|
|
132
|
+
def list_providers(self) -> List[Dict[str, Any]]:
|
|
133
|
+
return [p.describe() for p in self.providers.values()]
|
|
134
|
+
|
|
135
|
+
def get_widget_config(
|
|
136
|
+
self,
|
|
137
|
+
preset: str = "studio",
|
|
138
|
+
overrides: Optional[Dict[str, Any]] = None,
|
|
139
|
+
) -> Dict[str, Any]:
|
|
140
|
+
cfg: AuthWidgetConfig = resolve_widget_config(preset, overrides=overrides)
|
|
141
|
+
data = cfg.to_dict()
|
|
142
|
+
data["providers_detail"] = [
|
|
143
|
+
self.providers[pid].describe()
|
|
144
|
+
for pid in cfg.enabled_providers
|
|
145
|
+
if pid in self.providers
|
|
146
|
+
]
|
|
147
|
+
return data
|
|
148
|
+
|
|
149
|
+
def issue_challenge(self, domain: Optional[str] = None) -> Dict[str, Any]:
|
|
150
|
+
ch = self.web_auth.issue_challenge()
|
|
151
|
+
return {
|
|
152
|
+
"ok": True,
|
|
153
|
+
"challenge_id": ch["challenge"],
|
|
154
|
+
"challenge": ch["challenge"],
|
|
155
|
+
"challenge_text": ch["auth_message"],
|
|
156
|
+
"auth_message": ch["auth_message"],
|
|
157
|
+
"auth_message_sha256": ch["auth_message_sha256"],
|
|
158
|
+
"domain": domain or self.domain,
|
|
159
|
+
"instance_url": ch["instance_url"],
|
|
160
|
+
"expires_at": ch["expires_at"],
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
def _infer_provider_order(self, payload: Dict[str, Any]) -> List[str]:
|
|
164
|
+
explicit = str(payload.get("provider") or payload.get("provider_id") or "").strip().lower()
|
|
165
|
+
if explicit and explicit in self.providers:
|
|
166
|
+
return [explicit]
|
|
167
|
+
|
|
168
|
+
method = str(payload.get("auth_method") or payload.get("method") or "").strip().lower()
|
|
169
|
+
if (
|
|
170
|
+
method in ("nip46_bunker", "nip07_extension", "nip07_ext", "private_key", "schnorr_key", "did", "did_challenge")
|
|
171
|
+
or payload.get("bunker_uri")
|
|
172
|
+
or payload.get("secret_key")
|
|
173
|
+
or payload.get("private_key")
|
|
174
|
+
or payload.get("signature_hex")
|
|
175
|
+
or payload.get("signature")
|
|
176
|
+
or payload.get("auth_event")
|
|
177
|
+
):
|
|
178
|
+
return ["sovereign_key"]
|
|
179
|
+
|
|
180
|
+
if method == "portable_ticket" or str(payload.get("portable_ticket") or payload.get("ticket") or "").startswith(("mtpass_", "fmpass_")):
|
|
181
|
+
return ["sovereign_key"]
|
|
182
|
+
|
|
183
|
+
if method == "api_key" or str(payload.get("api_key") or "").startswith("mtk_"):
|
|
184
|
+
return ["meshtube"]
|
|
185
|
+
|
|
186
|
+
if method == "operator_token" or payload.get("operator_token"):
|
|
187
|
+
return ["local_operator", "meshtube"]
|
|
188
|
+
|
|
189
|
+
return ["meshtube", "local_operator"]
|
|
190
|
+
|
|
191
|
+
def _persist_session(
|
|
192
|
+
self,
|
|
193
|
+
session_token: str,
|
|
194
|
+
principal: AuthPrincipal,
|
|
195
|
+
now: int,
|
|
196
|
+
expires_at: int,
|
|
197
|
+
) -> None:
|
|
198
|
+
with self._db_lock:
|
|
199
|
+
self._conn.execute(
|
|
200
|
+
"""
|
|
201
|
+
INSERT OR REPLACE INTO fleetmesh_auth_sessions (
|
|
202
|
+
session_token, principal_id, did, pubkey_hex, handle, display_name,
|
|
203
|
+
provider, auth_method, roles_json, scopes_json, metadata_json,
|
|
204
|
+
issued_at, expires_at
|
|
205
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
206
|
+
""",
|
|
207
|
+
(
|
|
208
|
+
session_token,
|
|
209
|
+
principal.principal_id,
|
|
210
|
+
principal.did,
|
|
211
|
+
principal.pubkey_hex,
|
|
212
|
+
principal.handle,
|
|
213
|
+
principal.display_name,
|
|
214
|
+
principal.provider,
|
|
215
|
+
principal.auth_method,
|
|
216
|
+
json.dumps(principal.roles),
|
|
217
|
+
json.dumps(principal.scopes),
|
|
218
|
+
json.dumps(principal.metadata),
|
|
219
|
+
now,
|
|
220
|
+
expires_at,
|
|
221
|
+
),
|
|
222
|
+
)
|
|
223
|
+
self._conn.commit()
|
|
224
|
+
|
|
225
|
+
def _load_persisted_session(self, session_token: str, now: int) -> tuple[Optional[sqlite3.Row], bool]:
|
|
226
|
+
with self._db_lock:
|
|
227
|
+
row = self._conn.execute(
|
|
228
|
+
"SELECT * FROM fleetmesh_auth_sessions WHERE session_token = ? LIMIT 1",
|
|
229
|
+
(session_token,),
|
|
230
|
+
).fetchone()
|
|
231
|
+
if row is not None and int(row["expires_at"]) < now:
|
|
232
|
+
self._conn.execute(
|
|
233
|
+
"DELETE FROM fleetmesh_auth_sessions WHERE session_token = ?",
|
|
234
|
+
(session_token,),
|
|
235
|
+
)
|
|
236
|
+
self._conn.commit()
|
|
237
|
+
return None, True
|
|
238
|
+
return row, False
|
|
239
|
+
|
|
240
|
+
def authenticate(
|
|
241
|
+
self,
|
|
242
|
+
payload: Dict[str, Any],
|
|
243
|
+
*,
|
|
244
|
+
app_preset: str = "studio",
|
|
245
|
+
required_role: Optional[str] = None,
|
|
246
|
+
) -> Dict[str, Any]:
|
|
247
|
+
norm_payload = dict(payload or {})
|
|
248
|
+
if "method" in norm_payload and "auth_method" not in norm_payload:
|
|
249
|
+
m = str(norm_payload["method"])
|
|
250
|
+
alias_map = {
|
|
251
|
+
"nip07_ext": "nip07_extension",
|
|
252
|
+
"schnorr_key": "private_key",
|
|
253
|
+
"did_challenge": "did",
|
|
254
|
+
"service_provider": "service_login",
|
|
255
|
+
}
|
|
256
|
+
norm_payload["auth_method"] = alias_map.get(m, m)
|
|
257
|
+
if "signature" in norm_payload and "signature_hex" not in norm_payload:
|
|
258
|
+
norm_payload["signature_hex"] = norm_payload["signature"]
|
|
259
|
+
if "challenge" in norm_payload and "challenge_id" not in norm_payload:
|
|
260
|
+
norm_payload["challenge_id"] = norm_payload["challenge"]
|
|
261
|
+
if "pubkey" in norm_payload and "pubkey_hex" not in norm_payload:
|
|
262
|
+
norm_payload["pubkey_hex"] = norm_payload["pubkey"]
|
|
263
|
+
|
|
264
|
+
context = {
|
|
265
|
+
"web_auth": self.web_auth,
|
|
266
|
+
"studio": self.studio,
|
|
267
|
+
"directory": self.directory,
|
|
268
|
+
"domain": self.domain,
|
|
269
|
+
"app_preset": app_preset,
|
|
270
|
+
"allow_any_sovereign_key": self.allow_any_sovereign_key,
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
provider_order = self._infer_provider_order(norm_payload)
|
|
274
|
+
last_error = "authentication_failed"
|
|
275
|
+
auth_res: Optional[Dict[str, Any]] = None
|
|
276
|
+
|
|
277
|
+
# No engine-wide lock here: providers may wait on the network (bunker
|
|
278
|
+
# round-trips), and the statements they run lock for themselves.
|
|
279
|
+
for pid in provider_order:
|
|
280
|
+
provider = self.providers.get(pid)
|
|
281
|
+
if provider is None:
|
|
282
|
+
continue
|
|
283
|
+
res = provider.authenticate(norm_payload, context)
|
|
284
|
+
if res.get("ok"):
|
|
285
|
+
auth_res = res
|
|
286
|
+
break
|
|
287
|
+
last_error = str(res.get("error") or last_error)
|
|
288
|
+
|
|
289
|
+
if not auth_res or not auth_res.get("ok"):
|
|
290
|
+
return {"ok": False, "error": last_error}
|
|
291
|
+
|
|
292
|
+
principal: AuthPrincipal = auth_res["principal"]
|
|
293
|
+
|
|
294
|
+
target_role = required_role or norm_payload.get("required_role")
|
|
295
|
+
if target_role and not principal.has_role(str(target_role)):
|
|
296
|
+
return {
|
|
297
|
+
"ok": False,
|
|
298
|
+
"error": "insufficient_role",
|
|
299
|
+
"required_role": str(target_role),
|
|
300
|
+
"roles": list(principal.roles),
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
now = int(time.time())
|
|
304
|
+
expires_at = now + self.session_ttl_sec
|
|
305
|
+
session_token = f"fmauth_{secrets.token_urlsafe(24)}"
|
|
306
|
+
|
|
307
|
+
# No portable ticket here. A ticket is the identity of the key that
|
|
308
|
+
# signs it, and the server holds no user's key; the panel mints one
|
|
309
|
+
# in the browser with the user's own key or signer extension.
|
|
310
|
+
|
|
311
|
+
principal.session_token = session_token
|
|
312
|
+
principal.issued_at = now
|
|
313
|
+
principal.expires_at = expires_at
|
|
314
|
+
|
|
315
|
+
self._link_session(session_token, principal, now, expires_at)
|
|
316
|
+
self._persist_session(session_token, principal, now, expires_at)
|
|
317
|
+
|
|
318
|
+
return {
|
|
319
|
+
"ok": True,
|
|
320
|
+
"session_token": session_token,
|
|
321
|
+
"token": session_token,
|
|
322
|
+
"expires_at": expires_at,
|
|
323
|
+
"principal": principal.to_dict(),
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
def _link_session(self, token: str, principal: AuthPrincipal, issued_at: int, expires_at: int) -> None:
|
|
327
|
+
"""Carry the session into the app's own session tables, when it keeps any."""
|
|
328
|
+
if self.directory is None:
|
|
329
|
+
return
|
|
330
|
+
operator_pks = frozenset(p.lower() for p in self._key_provider.operator_pubkeys)
|
|
331
|
+
self.directory.link_session(token, principal, issued_at, expires_at, operator_pks)
|
|
332
|
+
|
|
333
|
+
def verify_session(
|
|
334
|
+
self,
|
|
335
|
+
token: str,
|
|
336
|
+
*,
|
|
337
|
+
required_role: Optional[str] = None,
|
|
338
|
+
) -> Dict[str, Any]:
|
|
339
|
+
clean = (token or "").strip()
|
|
340
|
+
if clean.lower().startswith("bearer "):
|
|
341
|
+
clean = clean[7:].strip()
|
|
342
|
+
if not clean:
|
|
343
|
+
return {"ok": False, "error": "missing_session_token"}
|
|
344
|
+
|
|
345
|
+
now = int(time.time())
|
|
346
|
+
row, expired = self._load_persisted_session(clean, now)
|
|
347
|
+
if expired:
|
|
348
|
+
return {"ok": False, "error": "expired_session_token"}
|
|
349
|
+
|
|
350
|
+
if row is not None:
|
|
351
|
+
roles = json.loads(row["roles_json"] or "[]")
|
|
352
|
+
scopes = json.loads(row["scopes_json"] or "[]")
|
|
353
|
+
metadata = json.loads(row["metadata_json"] or "{}")
|
|
354
|
+
principal = AuthPrincipal(
|
|
355
|
+
principal_id=row["principal_id"],
|
|
356
|
+
did=row["did"],
|
|
357
|
+
pubkey=row["pubkey_hex"],
|
|
358
|
+
handle=row["handle"],
|
|
359
|
+
display_name=row["display_name"],
|
|
360
|
+
provider_id=row["provider"],
|
|
361
|
+
auth_method=row["auth_method"],
|
|
362
|
+
roles=roles,
|
|
363
|
+
scopes=scopes,
|
|
364
|
+
session_token=clean,
|
|
365
|
+
admin_token=clean if ("admin" in roles or "moderator" in roles or "node_operator" in roles) else "",
|
|
366
|
+
issued_at=int(row["issued_at"]),
|
|
367
|
+
expires_at=int(row["expires_at"]),
|
|
368
|
+
metadata=metadata,
|
|
369
|
+
)
|
|
370
|
+
if self.directory is not None and not self.directory.has_session(clean):
|
|
371
|
+
self._link_session(clean, principal, int(row["issued_at"]), int(row["expires_at"]))
|
|
372
|
+
if required_role and not principal.has_role(required_role):
|
|
373
|
+
return {
|
|
374
|
+
"ok": False,
|
|
375
|
+
"error": "insufficient_role",
|
|
376
|
+
"required_role": required_role,
|
|
377
|
+
"roles": principal.roles,
|
|
378
|
+
}
|
|
379
|
+
return {"ok": True, "principal": principal.to_dict()}
|
|
380
|
+
|
|
381
|
+
if self.directory is not None:
|
|
382
|
+
app_principal = self.directory.resolve_session(clean, now, self.session_ttl_sec)
|
|
383
|
+
if app_principal is not None:
|
|
384
|
+
if required_role and not app_principal.has_role(required_role):
|
|
385
|
+
return {"ok": False, "error": "insufficient_role"}
|
|
386
|
+
return {"ok": True, "principal": app_principal.to_dict()}
|
|
387
|
+
|
|
388
|
+
return {"ok": False, "error": "invalid_session_token"}
|
|
389
|
+
|
|
390
|
+
def revoke_session(self, token: str) -> Dict[str, Any]:
|
|
391
|
+
clean = (token or "").strip()
|
|
392
|
+
if clean.lower().startswith("bearer "):
|
|
393
|
+
clean = clean[7:].strip()
|
|
394
|
+
if not clean:
|
|
395
|
+
return {"ok": False, "error": "missing_session_token"}
|
|
396
|
+
with self._db_lock:
|
|
397
|
+
self._conn.execute(
|
|
398
|
+
"DELETE FROM fleetmesh_auth_sessions WHERE session_token = ?",
|
|
399
|
+
(clean,),
|
|
400
|
+
)
|
|
401
|
+
self._conn.commit()
|
|
402
|
+
if self.directory is not None:
|
|
403
|
+
self.directory.revoke_session(clean)
|
|
404
|
+
return {"ok": True}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Mountable HTTP route handlers for `/api/fauth/*` across FleetMesh web services."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any, Dict, Optional
|
|
5
|
+
from urllib.parse import parse_qs
|
|
6
|
+
|
|
7
|
+
from fleetmesh_auth.engine import FleetmeshAuthEngine
|
|
8
|
+
from fleetmesh_auth.principal import resolve_widget_config
|
|
9
|
+
from fleetmesh_auth.ui_widget import render_auth_widget_js
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def extract_request_token(handler: Any, payload: Optional[Dict[str, Any]] = None) -> str:
|
|
13
|
+
"""Extract a session/auth token from HTTP headers, query string, or JSON body."""
|
|
14
|
+
headers = getattr(handler, "headers", {}) or {}
|
|
15
|
+
for hdr in (
|
|
16
|
+
"X-Fleetmesh-Auth",
|
|
17
|
+
"Authorization",
|
|
18
|
+
"X-Admin-Token",
|
|
19
|
+
"X-Session-Token",
|
|
20
|
+
"X-MeshTube-Key",
|
|
21
|
+
):
|
|
22
|
+
val = str(headers.get(hdr) or "").strip()
|
|
23
|
+
if val:
|
|
24
|
+
if val.lower().startswith("bearer "):
|
|
25
|
+
val = val[7:].strip()
|
|
26
|
+
if val:
|
|
27
|
+
return val
|
|
28
|
+
if payload:
|
|
29
|
+
for key in ("token", "session_token", "api_key"):
|
|
30
|
+
val = str(payload.get(key) or "").strip()
|
|
31
|
+
if val:
|
|
32
|
+
return val
|
|
33
|
+
return ""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def handle_fauth_get(
|
|
37
|
+
handler: Any,
|
|
38
|
+
engine: FleetmeshAuthEngine,
|
|
39
|
+
path: str,
|
|
40
|
+
query_string: str = "",
|
|
41
|
+
) -> bool:
|
|
42
|
+
"""Handle `GET /api/fauth/*` requests on a BaseHTTPRequestHandler-compatible handler.
|
|
43
|
+
|
|
44
|
+
Returns ``True`` if the path matched `/api/fauth/*` and a response was sent.
|
|
45
|
+
"""
|
|
46
|
+
if not path.startswith("/api/fauth/"):
|
|
47
|
+
return False
|
|
48
|
+
|
|
49
|
+
qs = parse_qs(query_string or "")
|
|
50
|
+
preset = (qs.get("preset") or ["studio"])[0]
|
|
51
|
+
|
|
52
|
+
if path == "/api/fauth/config":
|
|
53
|
+
cfg = engine.get_widget_config(preset=preset)
|
|
54
|
+
handler._send_json(200, {"ok": True, "config": cfg})
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
if path == "/api/fauth/providers":
|
|
58
|
+
handler._send_json(200, {"ok": True, "providers": engine.list_providers()})
|
|
59
|
+
return True
|
|
60
|
+
|
|
61
|
+
if path == "/api/fauth/challenge":
|
|
62
|
+
domain = (qs.get("domain") or [engine.domain])[0]
|
|
63
|
+
res = engine.issue_challenge(domain=domain)
|
|
64
|
+
handler._send_json(200, res)
|
|
65
|
+
return True
|
|
66
|
+
|
|
67
|
+
if path == "/api/fauth/session":
|
|
68
|
+
token = (qs.get("token") or [""])[0] or extract_request_token(handler)
|
|
69
|
+
req_role = (qs.get("required_role") or [None])[0]
|
|
70
|
+
res = engine.verify_session(token, required_role=req_role)
|
|
71
|
+
handler._send_json(200 if res.get("ok") else 401, res)
|
|
72
|
+
return True
|
|
73
|
+
|
|
74
|
+
if path == "/api/fauth/widget.js":
|
|
75
|
+
cfg = resolve_widget_config(preset)
|
|
76
|
+
js_body = render_auth_widget_js(cfg).encode("utf-8")
|
|
77
|
+
handler.send_response(200)
|
|
78
|
+
handler.send_header("Content-Type", "application/javascript; charset=utf-8")
|
|
79
|
+
handler.send_header("Content-Length", str(len(js_body)))
|
|
80
|
+
handler.send_header("Cache-Control", "no-store")
|
|
81
|
+
handler.end_headers()
|
|
82
|
+
handler.wfile.write(js_body)
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
handler._send_json(404, {"ok": False, "error": "unknown_fauth_endpoint", "path": path})
|
|
86
|
+
return True
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def handle_fauth_post(
|
|
90
|
+
handler: Any,
|
|
91
|
+
engine: FleetmeshAuthEngine,
|
|
92
|
+
path: str,
|
|
93
|
+
payload: Dict[str, Any],
|
|
94
|
+
) -> bool:
|
|
95
|
+
"""Handle `POST /api/fauth/*` requests on a BaseHTTPRequestHandler-compatible handler.
|
|
96
|
+
|
|
97
|
+
Returns ``True`` if the path matched `/api/fauth/*` and a response was sent.
|
|
98
|
+
"""
|
|
99
|
+
if not path.startswith("/api/fauth/"):
|
|
100
|
+
return False
|
|
101
|
+
|
|
102
|
+
body = payload or {}
|
|
103
|
+
|
|
104
|
+
if path == "/api/fauth/challenge":
|
|
105
|
+
domain = str(body.get("domain") or engine.domain)
|
|
106
|
+
res = engine.issue_challenge(domain=domain)
|
|
107
|
+
handler._send_json(200, res)
|
|
108
|
+
return True
|
|
109
|
+
|
|
110
|
+
if path in ("/api/fauth/login", "/api/fauth/verify"):
|
|
111
|
+
preset = str(body.get("app_preset") or body.get("preset") or "studio")
|
|
112
|
+
req_role = body.get("required_role")
|
|
113
|
+
res = engine.authenticate(
|
|
114
|
+
body,
|
|
115
|
+
app_preset=preset,
|
|
116
|
+
required_role=str(req_role) if req_role else None,
|
|
117
|
+
)
|
|
118
|
+
status = 200 if res.get("ok") else 401
|
|
119
|
+
handler._send_json(status, res)
|
|
120
|
+
return True
|
|
121
|
+
|
|
122
|
+
if path == "/api/fauth/logout":
|
|
123
|
+
token = extract_request_token(handler, body)
|
|
124
|
+
res = engine.revoke_session(token)
|
|
125
|
+
handler._send_json(200, res)
|
|
126
|
+
return True
|
|
127
|
+
|
|
128
|
+
handler._send_json(404, {"ok": False, "error": "unknown_fauth_endpoint", "path": path})
|
|
129
|
+
return True
|