-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
7560 lines (6550 loc) · 281 KB
/
Copy pathapp.py
File metadata and controls
7560 lines (6550 loc) · 281 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Full Hub application with both API and GUI routes.
This module is for LOCAL DEVELOPMENT ONLY. It includes:
- All API routes from api_app.py
- GUI routes (login, callback, logout, home, profile, livekit-test, agent detail)
For Lambda deployment, use api_app.py instead (via lambda_handler.py).
"""
from __future__ import annotations
import base64
import dataclasses
import html
import json
import logging
import os
import secrets
import uuid
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional
from agent_hub.action_service import (
ActionServiceError,
approve_action,
create_action,
load_action,
mark_action_completed,
record_action_dispatch_started,
reject_action,
reserve_action_for_execution,
)
from agent_hub.auth import (
AuthenticatedUser,
ensure_user_row,
list_cognito_users,
lookup_cognito_user_by_email,
)
from agent_hub.broadcast import broadcast_event
from agent_hub.cognito import (
CognitoAuthError,
CognitoUserInfo, # noqa: F401 — used via module attr in tests
build_login_url,
build_logout_url,
get_user_info_from_tokens,
)
from agent_hub.livekit_tokens import mint_livekit_join_token # noqa: F401 — used via module attr in tests
from agent_hub.memberships import (
SpaceInfo, # noqa: F401 — used via module attr in tests
check_agent_permission,
grant_membership,
list_agents_for_user,
list_spaces_for_user,
revoke_membership,
update_membership,
)
from agent_hub.memory_taxonomy import (
classify_memory_kinds,
memory_kind_options,
normalize_memory_kind,
)
from agent_hub.personas import DEFAULT_AGENT_PERSONA_INSTRUCTIONS, DEFAULT_AGENT_PERSONA_NAME
from agent_hub.secrets import get_secret_json
from agent_hub.session_tokens import mint_ws_session_token
# Import the API app and its shared state
from api_app import (
LiveKitTokenIn,
LiveKitTokenOut,
_get_db,
_get_s3,
_get_sqs,
_mint_livekit_token_for_user,
_session_secret,
api_app,
get_config,
)
from daylily_auth_cognito.browser.session import (
CONFIG_STATE_KEY,
CognitoWebAuthError,
CognitoWebSessionConfig,
SessionPrincipal,
clear_session_principal,
complete_cognito_callback,
load_session_principal,
)
from daylily_tapdb.web import TapdbHostBridge, TapdbHostNavLink, create_tapdb_dag_router, create_tapdb_web_app
from fastapi import FastAPI as _FastAPI
from fastapi import HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel, Field
from starlette.responses import Response
logger = logging.getLogger(__name__)
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
# Avoid leaking AWS response payloads (can include secrets) in local logs.
for _name in ("botocore", "urllib3", "httpcore", "httpx"):
logging.getLogger(_name).setLevel(logging.WARNING)
# -----------------------------
# Startup Configuration Validation
# -----------------------------
class ConfigurationError(Exception):
"""Raised when critical configuration is missing or invalid."""
pass
def _is_placeholder(value: str | None) -> bool:
"""Check if a value is a placeholder or empty."""
if not value:
return True
v = str(value).strip().upper()
return v in ("", "REPLACE_ME", "CHANGEME", "TODO", "XXX", "YOUR_KEY_HERE", "YOUR_SECRET_HERE")
def _validate_critical_secrets(cfg) -> list[str]:
"""Validate all critical secrets at startup.
Returns a list of configuration errors. Empty list means all valid.
"""
errors: list[str] = []
# 1. Cognito Configuration
if not cfg.cognito_user_pool_id:
errors.append("COGNITO_USER_POOL_ID not set")
if not cfg.cognito_user_pool_client_id:
errors.append("COGNITO_APP_CLIENT_ID not set")
if not cfg.cognito_domain:
errors.append("COGNITO_DOMAIN not set")
# 2. Database Configuration (required for any operation)
if not cfg.db_resource_arn:
errors.append("DB_RESOURCE_ARN not set")
if not cfg.db_secret_arn:
errors.append("DB_SECRET_ARN not set")
# 3. LiveKit Configuration (required for voice/video features)
if not cfg.livekit_url:
errors.append("LIVEKIT_URL not set")
if not cfg.livekit_secret_arn:
errors.append("LIVEKIT_SECRET_ARN not set")
else:
try:
# Clear cache to get fresh value
get_secret_json.cache_clear()
lk_secret = get_secret_json(cfg.livekit_secret_arn)
lk_api_key = lk_secret.get("api_key", "")
lk_api_secret = lk_secret.get("api_secret", "")
if _is_placeholder(lk_api_key):
errors.append("LiveKit api_key is a placeholder (REPLACE_ME). Update secret in AWS Secrets Manager.")
if _is_placeholder(lk_api_secret):
errors.append("LiveKit api_secret is a placeholder (REPLACE_ME). Update secret in AWS Secrets Manager.")
except Exception as e:
errors.append(f"Failed to read LiveKit secret: {e}")
# 4. OpenAI Configuration (required for embeddings/AI features)
if cfg.openai_secret_arn:
try:
# Clear cache to get fresh value
get_secret_json.cache_clear()
openai_secret = get_secret_json(cfg.openai_secret_arn)
openai_api_key = openai_secret.get("api_key", "")
if _is_placeholder(openai_api_key):
errors.append("OpenAI api_key is a placeholder (REPLACE_ME). Update secret in AWS Secrets Manager.")
except Exception as e:
errors.append(f"Failed to read OpenAI secret: {e}")
# 5. Session Secret (required for secure sessions)
if not cfg.session_secret_key and not cfg.session_secret_arn:
errors.append(
"SESSION_SECRET_KEY or SESSION_SECRET_ARN not set - sessions will use random key (not persistent)"
)
return errors
def validate_configuration_or_fail():
"""Validate all critical configuration and fail hard if any issues.
This is called at startup to ensure the GUI won't run with misconfigured secrets.
"""
cfg = get_config()
errors = _validate_critical_secrets(cfg)
if errors:
logger.critical("Critical configuration validation failed with %d issue(s).", len(errors))
raise ConfigurationError("Critical configuration validation failed.")
# Use the API app as the base - all API routes are already defined
app = api_app
# Get config from api_app
_cfg = get_config()
# Setup Jinja2 templates and static files
_TEMPLATES_DIR = Path(__file__).parent / "templates"
_STATIC_DIR = Path(__file__).parent / "static"
# Mount static files
app.mount("/static", StaticFiles(directory=str(_STATIC_DIR)), name="static")
# Setup Jinja2 templates
templates = Jinja2Templates(directory=str(_TEMPLATES_DIR))
@dataclass(frozen=True)
class TapdbRuntimeConfig:
config_path: str
env_name: str
class MarvainTapdbConfigError(RuntimeError):
"""Raised when the embedded TapDB runtime is not configured."""
_tapdb_web_asgi_app: Any | None = None
_tapdb_dag_asgi_app: Any | None = None
_TAPDB_MOUNT_PATH = "/tapdb"
def _requested_app_path(scope: dict[str, Any]) -> str:
root_path = str(scope.get("root_path") or "").rstrip("/")
path = str(scope.get("path") or "") or "/"
target = f"{root_path}{path}" or "/"
query_string = scope.get("query_string") or b""
if query_string:
target = f"{target}?{query_string.decode('utf-8')}"
return target
def _tapdb_child_scope(scope: dict[str, Any], user: AuthenticatedUser) -> dict[str, Any]:
scoped = dict(scope)
path = str(scoped.get("path") or "")
if path == _TAPDB_MOUNT_PATH:
scoped["path"] = "/"
elif path.startswith(f"{_TAPDB_MOUNT_PATH}/"):
scoped["path"] = path[len(_TAPDB_MOUNT_PATH) :]
root_path = str(scoped.get("root_path") or "").rstrip("/")
if not root_path.endswith(_TAPDB_MOUNT_PATH):
scoped["root_path"] = f"{root_path}{_TAPDB_MOUNT_PATH}"
scoped["marvain_authenticated_user"] = user
scoped["tapdb_host_user"] = _tapdb_user_payload(user)
return scoped
def _resolve_tapdb_runtime_config() -> TapdbRuntimeConfig:
config_path = str(os.getenv("MARVAIN_TAPDB_CONFIG_PATH") or os.getenv("TAPDB_CONFIG_PATH") or "").strip()
if not config_path:
raise MarvainTapdbConfigError(
"TapDB runtime is not configured. Set TAPDB_CONFIG_PATH or MARVAIN_TAPDB_CONFIG_PATH."
)
resolved = Path(config_path).expanduser().resolve()
if not resolved.exists():
raise MarvainTapdbConfigError(f"TapDB config file not found: {resolved}")
env_name = str(os.getenv("MARVAIN_TAPDB_ENV") or os.getenv("TAPDB_ENV") or _cfg.stage or "").strip()
if not env_name:
raise MarvainTapdbConfigError("TapDB environment is not configured. Set TAPDB_ENV or MARVAIN_TAPDB_ENV.")
return TapdbRuntimeConfig(config_path=str(resolved), env_name=env_name)
def _tapdb_user_payload(user: AuthenticatedUser) -> dict[str, Any]:
return {
"uid": str(user.user_id),
"username": str(user.email),
"email": str(user.email),
"display_name": str(user.email),
"role": "admin",
"is_active": True,
}
def _tapdb_host_user(request: Request) -> dict[str, Any] | None:
scoped_tapdb_user = request.scope.get("tapdb_host_user")
if isinstance(scoped_tapdb_user, dict):
return scoped_tapdb_user
scoped_user = request.scope.get("marvain_authenticated_user")
user = scoped_user if isinstance(scoped_user, AuthenticatedUser) else _gui_get_user(request)
if not user:
return None
return _tapdb_user_payload(user)
def _tapdb_host_bridge() -> TapdbHostBridge:
return TapdbHostBridge(
auth_mode="host_session",
service_name="marvain",
app_name="TapDB",
shell_title="Marvain TapDB",
shell_subtitle="Native semantic graph",
home_url="/",
login_url="/login",
logout_url="/logout",
resolve_user=_tapdb_host_user,
nav_links=(TapdbHostNavLink(label="Marvain", href="/"),),
)
def _build_tapdb_web_asgi_app() -> Any:
cfg = _resolve_tapdb_runtime_config()
return create_tapdb_web_app(
config_path=cfg.config_path,
env_name=cfg.env_name,
host_bridge=_tapdb_host_bridge(),
)
def _get_tapdb_web_asgi_app() -> Any:
global _tapdb_web_asgi_app
if _tapdb_web_asgi_app is None:
_tapdb_web_asgi_app = _build_tapdb_web_asgi_app()
return _tapdb_web_asgi_app
def _build_tapdb_dag_asgi_app() -> _FastAPI:
cfg = _resolve_tapdb_runtime_config()
dag_app = _FastAPI()
router = create_tapdb_dag_router(
config_path=cfg.config_path,
env_name=cfg.env_name,
service_name="marvain",
)
dag_app.include_router(router)
return dag_app
def _get_tapdb_dag_asgi_app() -> Any:
global _tapdb_dag_asgi_app
if _tapdb_dag_asgi_app is None:
_tapdb_dag_asgi_app = _build_tapdb_dag_asgi_app()
return _tapdb_dag_asgi_app
def _tapdb_config_error_response(exc: Exception) -> JSONResponse:
logger.info("TapDB runtime configuration unavailable: %s", exc.__class__.__name__)
return JSONResponse(
status_code=503,
content={
"detail": "TapDB runtime is not configured. Set TAPDB_CONFIG_PATH or MARVAIN_TAPDB_CONFIG_PATH.",
"code": "tapdb_runtime_not_configured",
},
)
def _tapdb_runtime_error_response(_exc: Exception) -> JSONResponse:
return JSONResponse(
status_code=503,
content={
"detail": (
"TapDB runtime is not available. Check TAPDB_CONFIG_PATH or MARVAIN_TAPDB_CONFIG_PATH "
"and TAPDB_ENV or MARVAIN_TAPDB_ENV."
),
"code": "tapdb_runtime_unavailable",
},
)
async def _dispatch_asgi_app(asgi_app: Any, request: Request) -> Response:
body = await request.body()
sent_body = False
async def receive() -> dict[str, Any]:
nonlocal sent_body
if sent_body:
return {"type": "http.request", "body": b"", "more_body": False}
sent_body = True
return {"type": "http.request", "body": body, "more_body": False}
status_code = 500
headers: list[tuple[bytes, bytes]] = []
chunks: list[bytes] = []
async def send(message: dict[str, Any]) -> None:
nonlocal status_code, headers
if message["type"] == "http.response.start":
status_code = int(message["status"])
headers = list(message.get("headers") or [])
elif message["type"] == "http.response.body":
chunks.append(message.get("body") or b"")
await asgi_app(request.scope, receive, send)
return Response(
content=b"".join(chunks),
status_code=status_code,
headers={k.decode("latin-1"): v.decode("latin-1") for k, v in headers},
)
class MarvainTapdbMount:
"""Lazy TapDB UI mount guarded by the Marvain browser session."""
async def __call__(self, scope, receive, send) -> None:
request = Request(scope, receive)
user = _gui_get_user(request)
if not user:
if str(scope.get("path") or "").startswith("/api/"):
await JSONResponse(status_code=401, content={"detail": "Not authenticated"})(scope, receive, send)
return
await RedirectResponse(url="/login", status_code=302)(scope, receive, send)
return
try:
tapdb_app = _get_tapdb_web_asgi_app()
await tapdb_app(_tapdb_child_scope(scope, user), receive, send)
except MarvainTapdbConfigError as exc:
await _tapdb_config_error_response(exc)(scope, receive, send)
except (RuntimeError, ValueError) as exc:
await _tapdb_config_error_response(exc)(scope, receive, send)
except Exception as exc:
logger.warning("Embedded TapDB request failed: %s", exc.__class__.__name__)
await _tapdb_runtime_error_response(exc)(scope, receive, send)
app.mount("/tapdb", MarvainTapdbMount(), name="tapdb")
async def _api_tapdb_dag_proxy(request: Request) -> Response:
user = _gui_get_user(request)
if not user:
return JSONResponse(status_code=401, content={"detail": "Not authenticated"})
try:
return await _dispatch_asgi_app(_get_tapdb_dag_asgi_app(), request)
except MarvainTapdbConfigError as exc:
return _tapdb_config_error_response(exc)
except (RuntimeError, ValueError) as exc:
return _tapdb_config_error_response(exc)
app.add_api_route("/api/dag", _api_tapdb_dag_proxy, methods=["GET", "POST"], name="api_tapdb_dag_root")
app.add_api_route("/api/dag/{path:path}", _api_tapdb_dag_proxy, methods=["GET", "POST"], name="api_tapdb_dag")
@app.middleware("http")
async def _gui_cache_control_middleware(request: Request, call_next):
"""Disable caching for dynamic GUI pages to avoid stale auth/script state."""
response = await call_next(request)
path = str(request.url.path or "")
if path.startswith("/static/"):
return response
if path.startswith("/api/"):
if path == "/api/ws-auth-token":
response.headers["Cache-Control"] = "no-store"
return response
response.headers["Cache-Control"] = "no-store"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
# -----------------------------
# Startup Event - Validate Configuration
# -----------------------------
@app.on_event("startup")
async def startup_validate_configuration():
"""Validate critical configuration on startup.
This runs when the GUI server starts and will raise an exception
(crashing the server) if critical secrets are missing or invalid.
"""
logger.info("Validating critical configuration...")
validate_configuration_or_fail()
logger.info("Configuration validation passed - all critical secrets are set")
# -----------------------------
# GUI Routes (local development only)
# -----------------------------
def _parse_expires_at(value: str | None):
"""Parse a consent expiry value.
The consent modal uses <input type="date"> which submits 'YYYY-MM-DD'. Treat
that as inclusive (expires end-of-day UTC), not midnight, so "today" works.
"""
if not value:
return None
v = str(value).strip()
if not v:
return None
from datetime import date, datetime, timezone
from datetime import time as dt_time
try:
if len(v) == 10 and v[4] == "-" and v[7] == "-":
d = date.fromisoformat(v)
return datetime.combine(d, dt_time(23, 59, 59), tzinfo=timezone.utc)
dt = datetime.fromisoformat(v.replace("Z", "+00:00"))
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt
except Exception:
return None
def _get_ws_context(request: Request) -> dict[str, str | None]:
"""Get WebSocket context for template rendering.
Returns dict with ws_url only; token is fetched via authenticated API call.
"""
raw_ws_url = getattr(_cfg, "ws_api_url", None)
ws_url = raw_ws_url.strip() if isinstance(raw_ws_url, str) else None
return {
"ws_url": ws_url,
}
def _cookie_secure(request: Request) -> bool:
# Prefer explicit config for reverse-proxy/Tailscale setups.
if str(os.getenv("HTTPS_ENABLED", "")).strip().lower() in ("true", "1", "yes"):
return True
xf_proto = str(request.headers.get("x-forwarded-proto") or "").split(",", 1)[0].strip().lower()
if xf_proto == "https":
return True
try:
return str(request.url.scheme).lower() == "https"
except Exception:
return False
def _public_base_url(request: Request) -> str:
"""Resolve the externally-reachable base URL for OAuth redirects.
For remote access (e.g. via Tailscale serve), the GUI may be reachable at a
different hostname/scheme than the local bind address. Set PUBLIC_BASE_URL
to the externally reachable origin (no path), e.g.:
https://my-host.tailnet-123.ts.net
"""
raw = str(os.getenv("PUBLIC_BASE_URL", "")).strip()
if raw:
return raw.rstrip("/")
return str(request.base_url).rstrip("/")
def _web_session_config(request: Request) -> CognitoWebSessionConfig:
base_url = _public_base_url(request)
return CognitoWebSessionConfig(
domain=str(_cfg.cognito_domain or ""),
client_id=str(_cfg.cognito_user_pool_client_id or ""),
redirect_uri=f"{base_url}/auth/callback",
logout_uri=f"{base_url}/logged-out",
session_secret_key=_session_secret,
session_cookie_name="marvain_session",
session_max_age=3600 * 8,
public_base_url=base_url,
auth_mode="cognito",
scope="openid email profile aws.cognito.signin.user.admin",
client_secret=_cfg.cognito_user_pool_client_secret,
same_site="lax",
allow_insecure_http=base_url.startswith("http://"),
server_instance_id=f"marvain-{_cfg.stage}",
)
def _register_web_session_config(request: Request) -> CognitoWebSessionConfig:
session_cfg = _web_session_config(request)
request.app.state.__dict__[CONFIG_STATE_KEY] = session_cfg
return session_cfg
def _safe_next_path(next_path: str | None) -> str:
"""Return a safe relative path to redirect to after login.
We only allow absolute-path relative URLs like "/profile".
"""
nxt = str(next_path or "").strip()
if not nxt:
return "/"
if not nxt.startswith("/"):
return "/"
if nxt.startswith("//"):
return "/"
# Prevent obvious scheme-like or header injection forms.
if ":" in nxt or "\r" in nxt or "\n" in nxt:
return "/"
return nxt
def _gui_path(request: Request, path: str) -> str:
"""Prefix `path` with ASGI root_path (e.g. API Gateway stage).
Starlette/FastAPI do not automatically apply `root_path` to string URLs like
"/login". We do it explicitly so redirects/links work behind stage-based
deployments.
"""
root = str(request.scope.get("root_path") or "")
if not root:
return path
if root.endswith("/") and path.startswith("/"):
return root[:-1] + path
return root + path
def _safe_next_app_path(request: Request, next_path: str | None) -> str:
"""Return a safe app-internal path (no root_path prefix) for the `next` param."""
nxt = _safe_next_path(next_path)
root = str(request.scope.get("root_path") or "")
if root and nxt.startswith(root):
# Strip root_path if a caller included it.
nxt = nxt[len(root) :] or "/"
if not nxt.startswith("/"):
nxt = "/" + nxt
nxt = _safe_next_path(nxt)
return nxt
def _encode_next_cookie(path: str) -> str:
"""Encode a normalized next-path for safe storage in a cookie."""
# Path is already normalized by _safe_next_app_path; we further make it opaque.
data = path.encode("utf-8")
return base64.urlsafe_b64encode(data).decode("ascii")
def _decode_next_cookie(value: Optional[str]) -> str:
"""Decode a next-path from cookie storage, falling back to root on error."""
if not value:
return "/"
try:
raw = base64.urlsafe_b64decode(value.encode("ascii"), validate=True)
path = raw.decode("utf-8", errors="strict")
except Exception:
return "/"
# Re-apply safety normalization to be defensive.
return _safe_next_path(path)
def _gui_get_user(request: Request) -> AuthenticatedUser | None:
"""Get the authenticated user from the session."""
if not request.session.get("user_sub") or not request.session.get("email"):
return None
_register_web_session_config(request)
try:
principal = load_session_principal(request)
except Exception:
logger.exception("Invalid GUI session principal")
request.session.clear()
return None
if principal is None:
return None
user_sub = principal.user_sub
email = principal.email
app_context = dict(principal.app_context or {})
user_id = str(app_context.get("user_id") or "").strip()
if not user_id:
# User exists in session but doesn't have a user_id - need to ensure row
try:
user_id = ensure_user_row(_get_db(), cognito_sub=user_sub, email=email)
app_context["user_id"] = user_id
request.session["app_context"] = app_context
except Exception:
logger.exception("Failed to ensure user row")
return None
return AuthenticatedUser(
user_id=user_id,
cognito_sub=user_sub,
email=email,
)
def _gui_redirect_to_login(*, request: Request, next_path: str | None = None, clear_session: bool = False) -> Response:
safe_next = _safe_next_app_path(request, next_path)
request.session["_marvain_login_next"] = safe_next
resp: Response = RedirectResponse(url=_gui_path(request, "/login"), status_code=302)
if clear_session:
clear_session_principal(request)
request.session["_marvain_login_next"] = safe_next
return resp
def _gui_html_page(*, title: str, body_html: str) -> HTMLResponse:
# Minimal HTML; no templating dependency in Phase 4.
t = html.escape(title)
doc = (
"<!doctype html>\n"
"<html><head><meta charset='utf-8'>"
f"<title>{t}</title>"
"<meta name='viewport' content='width=device-width, initial-scale=1'>"
"</head><body style='font-family: system-ui, -apple-system, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem;'>"
f"{body_html}"
"</body></html>"
)
return HTMLResponse(content=doc)
def _gui_error_page(*, request: Request, title: str, message: str, status_code: int = 400) -> HTMLResponse:
login_href = html.escape(_gui_path(request, "/login"))
body = f"<h1>{html.escape(title)}</h1><p>{html.escape(message)}</p><p><a href='{login_href}'>Log in</a></p>"
resp = _gui_html_page(title=title, body_html=body)
resp.status_code = status_code
return resp
@app.get("/login", name="login", response_model=None)
def gui_login(request: Request, next: str | None = None) -> Response:
"""Initiate Cognito login flow."""
# Check if Cognito is configured
if not _cfg.cognito_user_pool_id or not _cfg.cognito_domain:
return _gui_error_page(
request=request,
title="Authentication Not Configured",
message="Cognito authentication is not configured. Please set COGNITO_USER_POOL_ID and COGNITO_DOMAIN.",
status_code=503,
)
session_cfg = _register_web_session_config(request)
state = secrets.token_urlsafe(32)
request.session[session_cfg.state_session_key] = state
stored_next = request.session.pop("_marvain_login_next", None)
request.session[session_cfg.next_path_session_key] = _safe_next_app_path(request, next or stored_next)
try:
cfg = dataclasses.replace(_cfg, cognito_redirect_uri=session_cfg.redirect_uri)
login_url = build_login_url(cfg, state=state)
return RedirectResponse(url=login_url, status_code=302)
except CognitoAuthError as e:
logger.error(f"Failed to build login URL: {e}")
return _gui_error_page(
request=request,
title="Authentication Error",
message=str(e),
status_code=500,
)
@app.get("/auth/callback", name="auth_callback")
async def gui_auth_callback(
request: Request,
code: str | None = None,
state: str | None = None,
error: str | None = None,
error_description: str | None = None,
) -> Response:
"""Handle OAuth callback from Cognito."""
# Check for OAuth errors from Cognito
if error:
logger.warning(f"OAuth error: {error} - {error_description}")
return _gui_error_page(
request=request,
title="Authentication Error",
message=f"{error}: {error_description or 'Unknown error'}",
status_code=400,
)
if not code:
return _gui_error_page(
request=request,
title="Missing Authorization Code",
message="No authorization code was provided by the identity provider.",
status_code=400,
)
try:
session_cfg = _register_web_session_config(request)
cfg = dataclasses.replace(_cfg, cognito_redirect_uri=session_cfg.redirect_uri)
async def resolve_principal(tokens: dict[str, Any], _request: Request) -> SessionPrincipal:
id_token = tokens.get("id_token")
access_token = tokens.get("access_token")
if not id_token:
raise CognitoWebAuthError("missing_id_token", "No ID token in response from identity provider")
cognito_user = await get_user_info_from_tokens(cfg, str(id_token), str(access_token or ""))
user_id = ensure_user_row(
_get_db(),
cognito_sub=cognito_user.sub,
email=cognito_user.email,
)
logger.info(f"User {cognito_user.email} ({cognito_user.sub}) logged in")
return SessionPrincipal(
user_sub=cognito_user.sub,
email=cognito_user.email,
name=cognito_user.name,
roles=cognito_user.roles,
cognito_groups=cognito_user.cognito_groups,
app_context={"user_id": user_id},
)
resp = await complete_cognito_callback(
request,
session_cfg,
code=code,
state=state,
resolve_principal=resolve_principal,
)
resp.headers["Cache-Control"] = "no-store"
return resp
except CognitoWebAuthError as e:
logger.error(f"Cognito web auth error: {e}")
return _gui_error_page(
request=request,
title="Authentication Error",
message=str(e),
status_code=e.status_code,
)
except CognitoAuthError as e:
logger.error(f"Cognito auth error: {e}")
return _gui_error_page(
request=request,
title="Authentication Error",
message=str(e),
status_code=401,
)
except Exception:
logger.exception("Unexpected error during OAuth callback")
return _gui_error_page(
request=request,
title="Authentication Error",
message="An unexpected error occurred. Please try again.",
status_code=500,
)
@app.get("/logout", name="logout")
def gui_logout(request: Request) -> Response:
"""Clear session and redirect to Cognito logout or logged-out page."""
clear_session_principal(request)
request.session.clear()
resp: Response
if _cfg.cognito_domain and _cfg.cognito_user_pool_client_id:
# Redirect to Cognito logout
try:
logout_url = build_logout_url(_cfg, redirect_uri=f"{_public_base_url(request)}/logged-out")
resp = RedirectResponse(url=logout_url, status_code=302)
except CognitoAuthError:
resp = RedirectResponse(url=_gui_path(request, "/logged-out"), status_code=302)
else:
resp = RedirectResponse(url=_gui_path(request, "/logged-out"), status_code=302)
resp.headers["Cache-Control"] = "no-store"
return resp
@app.get("/logged-out", name="logged_out")
def gui_logged_out(request: Request) -> HTMLResponse:
login_href = html.escape(_gui_path(request, "/login"))
return _gui_html_page(title="Logged out", body_html=f"<h1>Logged out</h1><p><a href='{login_href}'>Log in</a></p>")
@app.get("/api/ws-auth-token", name="api_ws_auth_token")
async def api_ws_auth_token(request: Request) -> JSONResponse:
"""Return a Marvain session-scoped WS auth token for the current GUI user."""
user = _gui_get_user(request)
if not user:
raise HTTPException(status_code=401, detail="Not authenticated")
token = mint_ws_session_token(
secret_key=_session_secret,
user_id=user.user_id,
cognito_sub=user.cognito_sub,
email=user.email,
)
resp = JSONResponse({"access_token": token, "token_type": "marvain_session"})
resp.headers["Cache-Control"] = "no-store"
return resp
@app.get("/", name="gui_home")
def gui_home(request: Request) -> Response:
"""Home dashboard - central hub with status overview and navigation."""
user = _gui_get_user(request)
if not user:
return _gui_redirect_to_login(
request=request, next_path=str(request.scope.get("path") or "/"), clear_session=False
)
db = _get_db()
# Get agents for user
agents = list_agents_for_user(db, user_id=user.user_id)
# Get spaces for user
spaces = list_spaces_for_user(db, user_id=user.user_id)
# Get pending actions count
pending_actions = 0
try:
rows = db.query(
"""
SELECT COUNT(*) as cnt FROM actions a
INNER JOIN agent_memberships m ON a.agent_id = m.agent_id
WHERE m.user_id = :user_id::uuid AND m.revoked_at IS NULL AND a.status = 'proposed'
""",
{"user_id": str(user.user_id)},
)
if rows:
pending_actions = rows[0].get("cnt", 0) or 0
except Exception as e:
logger.warning(f"Failed to fetch pending actions: {e}")
# Convert agents to dicts for template
agents_data = [
{
"agent_id": str(a.agent_id),
"name": a.name,
"role": a.role,
"disabled": a.disabled,
}
for a in agents
]
# Get devices count and recent devices for the user's agents
devices_count = 0
devices_data: list[dict] = []
agent_ids = [str(a.agent_id) for a in agents]
if agent_ids:
try:
placeholders = ", ".join(f":id{i}" for i in range(len(agent_ids)))
params = {f"id{i}": aid for i, aid in enumerate(agent_ids)}
count_rows = db.query(
f"SELECT COUNT(*) as cnt FROM devices WHERE agent_id::TEXT IN ({placeholders})",
params,
)
if count_rows:
devices_count = count_rows[0].get("cnt", 0) or 0
dev_rows = db.query(
f"""SELECT d.device_id::TEXT as device_id, d.name,
a.name as agent_name, d.revoked_at
FROM devices d
JOIN agents a ON a.agent_id = d.agent_id
WHERE d.agent_id::TEXT IN ({placeholders})
ORDER BY d.created_at DESC LIMIT 5""",
params,
)
for row in dev_rows:
devices_data.append(
{
"device_id": str(row.get("device_id", "")),
"name": row.get("name") or "Unnamed Device",
"agent_name": row.get("agent_name", ""),
"revoked": row.get("revoked_at") is not None,
}
)
except Exception as e:
logger.warning(f"Failed to fetch devices for home: {e}")
# --- Dense dashboard: recent actions (last 10) ---
recent_actions: list[dict] = []
if agent_ids:
try:
placeholders = ", ".join(f":id{i}" for i in range(len(agent_ids)))
params = {f"id{i}": aid for i, aid in enumerate(agent_ids)}
act_rows = db.query(
f"""SELECT ac.action_id::TEXT as action_id, ac.kind, ac.status,
ac.created_at::TEXT as created_at,
a.name as agent_name
FROM actions ac
JOIN agents a ON a.agent_id = ac.agent_id
WHERE ac.agent_id::TEXT IN ({placeholders})
ORDER BY ac.created_at DESC LIMIT 10""",
params,
)
for row in act_rows:
recent_actions.append(
{
"action_id": row.get("action_id", ""),
"kind": row.get("kind", ""),
"status": row.get("status", ""),
"created_at": row.get("created_at", ""),
"agent_name": row.get("agent_name", ""),
}
)
except Exception as e:
logger.warning(f"Failed to fetch recent actions for home: {e}")
# --- Dense dashboard: agent online/offline via device heartbeats ---
agents_status: list[dict] = []
if agent_ids:
try:
placeholders = ", ".join(f":id{i}" for i in range(len(agent_ids)))
params = {f"id{i}": aid for i, aid in enumerate(agent_ids)}
status_rows = db.query(
f"""SELECT a.agent_id::TEXT as agent_id, a.name, a.disabled,
COALESCE(d.online_count, 0) as online_devices,
COALESCE(d.total_count, 0) as total_devices
FROM agents a
LEFT JOIN (