Repository navigation
Expand file tree
/
Copy pathweb_app.py
More file actions
7254 lines (6041 loc) · 344 KB
/
Copy pathweb_app.py
File metadata and controls
7254 lines (6041 loc) · 344 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
"""FastAPI/Uvicorn entrypoint for the v5.0.5 Chuanxu Web application.
The database-backed services are the authoritative implementation. This
entrypoint intentionally contains only HTTP concerns and exposes the same
session, CSRF, capability, Channel, Barrier, and Enrollment contracts to
Dashboard and external Skill clients.
"""
from __future__ import annotations
import asyncio
from contextlib import contextmanager
import functools
import json
import io
import logging
import os
import queue
import secrets
import socket
import sys
import threading
from email.parser import BytesParser
from email.policy import HTTP
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional
from urllib.parse import urlsplit
from fastapi import Cookie, Depends, FastAPI, Header, HTTPException, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.encoders import jsonable_encoder
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field, StrictBool
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.concurrency import run_in_threadpool
try:
from lib import effective_capabilities, product_identity, network_access
from lib import identity_api, external_identity_api, agent_gateway_api, compliance_api, connection, governed_contracts, security_lifecycle, organization_api, security_domain_api, platform_capabilities, native_agent_api, native_runtime, model_usage_api, model_governance_api, model_capability_api, deployment_adapters, runtime_isolation, db4a2a, embedding_governance, admin_management, cursor_pagination, task_plan_api, knowledge_api, memory_lifecycle, skill_api, tool_registry, spec_api, graph_production_profile, platform_agent_pool, host_provisioning, platform_governance_graph as governance_graph_module
except ModuleNotFoundError as exc:
# Only a missing top-level package means this is the source tree. Do not
# hide missing packaged dependencies by incorrectly falling back to shared.
if exc.name != "lib":
raise
from shared.lib import effective_capabilities, product_identity, network_access
from shared.lib import identity_api, external_identity_api, agent_gateway_api, compliance_api, connection, governed_contracts, security_lifecycle, organization_api, security_domain_api, platform_capabilities, native_agent_api, native_runtime, model_usage_api, model_governance_api, model_capability_api, deployment_adapters, runtime_isolation, db4a2a, embedding_governance, admin_management, cursor_pagination, task_plan_api, knowledge_api, memory_lifecycle, skill_api, tool_registry, spec_api, graph_production_profile, platform_agent_pool, host_provisioning, platform_governance_graph as governance_graph_module
VERSION = "5.0.5"
logger = logging.getLogger(__name__)
WEB_ROOT = Path(__file__).resolve().parent / "web"
if not WEB_ROOT.is_dir():
WEB_ROOT = Path(__file__).resolve().parent.parent / "web"
# Pin the physical asset directory. A compatibility symlink used by packaged
# tests can disappear while this process continues serving requests.
WEB_ROOT = WEB_ROOT.resolve()
DIST_ROOT = WEB_ROOT / "dist"
DEFAULT_NODE_ID = agent_gateway_api.local_node_id()
_COMPLIANCE_CONTROLLER_STOP = threading.Event()
_NATIVE_RUNTIME_STOP = threading.Event()
_ENTERPRISE_COMPLIANCE_PATHS = (
"/api/compliance",
"/api/agents/{agent_id}/posture",
"/api/agents/{agent_id}/activate",
"/api/agents/{agent_id}/compliance-profile",
"/api/agents/{agent_id}/compliance-control",
"/api/agents/{agent_id}/compliance-violation",
"/api/gateway/evidence",
"/api/gateway/remediations/{case_id}/respond",
)
_VALID_PROFILES = {"production", "graph-preview", "development", "experimental-4.2"}
_PUBLIC_LEGACY_API = {
"/api/health",
"/api/login",
"/portal/api/register",
"/portal/api/login",
}
_TOKEN_LEGACY_API = {
"/api/admin/agent/register",
"/api/admin/agent/recover",
"/api/agents/register",
"/api/agents/heartbeat",
}
_MFA_SETUP_ALLOWED_PATHS = {
"/api/auth/mfa/enroll",
"/api/auth/mfa/confirm",
"/api/auth/logout",
"/portal/api/auth/mfa/enroll",
"/portal/api/auth/mfa/confirm",
"/portal/api/auth/logout",
}
def _edition_features():
try:
from lib import edition_features
except ModuleNotFoundError:
try:
from shared.lib import edition_features
except ModuleNotFoundError:
return None
return edition_features
def _runtime_profile() -> str:
"""Return a validated, build-aware profile without exposing configuration."""
features = _edition_features()
default = str(getattr(features, "PROFILE", "production") or "production")
requested = str(os.environ.get("CX_RUNTIME_PROFILE", default) or default).strip()
if requested not in _VALID_PROFILES:
requested = default if default in _VALID_PROFILES else "production"
return requested
app = FastAPI(title=product_identity.identity()["name_en"] + " AI Agent Management Platform", version=VERSION)
def _correlation_id(request: Request) -> str:
current = str(getattr(request.state, "correlation_id", "") or "")
if current:
return current
supplied = str(request.headers.get("X-Correlation-ID") or "").strip()
if 8 <= len(supplied) <= 128 and all(character.isalnum() or character in "-_.:" for character in supplied):
current = supplied
else:
current = "cx_" + secrets.token_hex(16)
request.state.correlation_id = current
return current
def _error_response(request: Request, status: int, code: str, message: str, retryable: Optional[bool] = None,
recovery_action: str = "") -> JSONResponse:
correlation = _correlation_id(request)
safe_message = str(message or "Request failed")[:500]
body = {
"code": str(code or "REQUEST_FAILED")[:96],
"message": safe_message,
"correlation_id": correlation,
"retryable": status in {408, 429, 502, 503, 504} if retryable is None else bool(retryable),
"detail": safe_message,
}
if recovery_action:
body["recovery_action"] = recovery_action[:96]
return JSONResponse(body, status_code=status, headers={"X-Correlation-ID": correlation})
@app.exception_handler(StarletteHTTPException)
async def governed_http_error(request: Request, exc: StarletteHTTPException):
# Status/path/cause type are useful without logging bodies, credentials or
# database exception text. Correlation survives handled service failures.
logger.warning("HTTP failure correlation_id=%s status=%s path=%s cause=%s code=%s",
_correlation_id(request), exc.status_code, request.url.path,
type(exc.__cause__).__name__ if exc.__cause__ else "none",
exc.detail.get("code", "HTTP_"+str(exc.status_code)) if isinstance(exc.detail, dict) else "HTTP_"+str(exc.status_code))
detail = exc.detail
code = "HTTP_" + str(exc.status_code)
message = "Request failed"
retryable = None
if isinstance(detail, dict):
code = str(detail.get("code") or code)
message = str(detail.get("message") or detail.get("detail") or message)
retryable = detail.get("retryable")
else:
message = str(detail or message)
return _error_response(request, int(exc.status_code), code, message, retryable,
str(detail.get("recovery_action") or "") if isinstance(detail, dict) else "")
@app.exception_handler(RequestValidationError)
async def governed_validation_error(request: Request, _exc: RequestValidationError):
return _error_response(request, 422, "VALIDATION_ERROR", "Request validation failed", False)
@app.exception_handler(Exception)
async def governed_unhandled_error(request: Request, exc: Exception):
logger.exception("Unhandled request failure correlation_id=%s", _correlation_id(request), exc_info=exc)
return _error_response(request, 500, "INTERNAL_ERROR", "Internal request failed", False)
def _path_capability(path: str) -> Optional[str]:
"""Map every product entry point to one installation capability."""
normalized = "/" + str(path or "").lstrip("/")
if normalized.startswith("/portal"):
return "portal"
if normalized.startswith("/app/"):
page = normalized.split("/", 3)[2]
return {
"monitor": "monitor", "agents": "agents", "tasks": "tasks",
"workspaces": "workspaces", "knowledge": "knowledge", "memory": "memory",
"skills": "skills", "specs": "specs", "branches": "branches",
"collab": "collaboration", "loops": "loops", "graph": "graph",
"channels": "channels", "barriers": "barriers", "approvals": "approvals",
"compliance": "compliance", "audit": "audit_view", "users": "users",
"organization": "organization", "security-domains": "security_domains", "platform": "platform_config",
"native-agents": "agent_provisioning", "deployment": "deployment_governance",
"wallboard": "wallboard",
}.get(page)
if normalized.startswith("/api/agents/") and any(part in normalized for part in ("/posture", "/activate", "/compliance-")):
return "compliance"
rules = (
(("/api/platform", "/api/model-gateway"), "platform_config"),
(("/api/monitor",), "monitor"),
(("/api/wallboard", "/api/model-usage"), "wallboard"),
(("/api/model-finance",), "model_finance"),
(("/api/model-evidence",), "external_model_evidence"),
(("/api/agents/",), "agents"),
(("/api/tasks", "/api/execution", "/ap/v1/agent/tasks"), "tasks"),
(("/api/workspaces", "/api/work-contracts", "/api/handoffs", "/api/context/", "/api/context-publications", "/api/artifact-candidates", "/api/diagnostics/", "/api/agent-gateway/continuity/"), "workspaces"),
(("/api/knowledge", "/api/gateway/knowledge", "/api/agent-gateway/knowledge"), "knowledge"),
(("/api/memory", "/api/gateway/memory", "/api/agent-gateway/memory"), "memory"),
(("/api/skills", "/api/skill", "/api/agent/skills"), "skills"),
(("/api/specs",), "specs"),
(("/api/branches", "/api/branch"), "branches"),
(("/api/collab",), "collaboration"),
(("/api/loops",), "loops"),
(("/api/graphs", "/api/graph-", "/api/graph/"), "graph"),
(("/api/channels", "/api/gateway/channels", "/api/agent-gateway/channels", "/api/gateway/events"), "channels"),
(("/api/barriers", "/api/gateway/barriers", "/api/agent-gateway/barriers"), "barriers"),
(("/api/approvals",), "approvals"),
(("/api/compliance", "/api/gateway/evidence", "/api/gateway/remediations"), "compliance"),
(("/api/audit", "/api/traces", "/api/evidence", "/api/legal-holds"), "audit_view"),
(("/api/users", "/api/registration"), "users"),
(("/api/organization",), "organization"),
(("/api/security-domains",), "security_domains"),
(("/api/embedding",), "embedding_governance"),
(("/api/deployment-runs",), "deployment_governance"),
)
for prefixes, capability in rules:
if any(
normalized == prefix.rstrip("/")
or normalized.startswith(prefix.rstrip("/") + "/")
for prefix in prefixes
):
return capability
return None
def _graph_operation_capability(path: str) -> Optional[str]:
"""Use the same operation classification as legacy HTTP and workers."""
normalized = "/" + str(path or "").lstrip("/")
if normalized.startswith("/api/graphs/") and normalized.endswith("/import"):
return "graph_manifest_draft_import"
if normalized.endswith("/fork"):
return "graph_checkpoint_fork"
if normalized.endswith("/replay"):
return "graph_replay"
if normalized.endswith("/migrate"):
return "graph_dynamic_migration"
return effective_capabilities.graph_operation(path)
@app.middleware("http")
async def enforce_platform_capability(request: Request, call_next):
capability = _path_capability(request.url.path)
# Serve the SPA shell before authentication/capability checks. The shell
# contains the login form; API requests remain governed below, so an
# unavailable optional capability must not make the login page unreachable.
if request.url.path.startswith("/app/"):
capability = None
if capability:
try:
enabled = platform_capabilities.is_enabled(capability)
except (platform_capabilities.CapabilityServiceUnavailable, platform_capabilities.CapabilityError):
return JSONResponse(
{"detail": {"code": "CAPABILITY_SERVICE_UNAVAILABLE", "capability": capability}},
status_code=503,
)
if not enabled:
return JSONResponse(
{"detail": {"code": "CAPABILITY_DISABLED", "capability": capability}},
status_code=409,
)
graph_capability = _graph_operation_capability(request.url.path)
if graph_capability:
try:
graph_state = graph_production_profile.state(graph_capability)
controlled = False
if graph_state == "CONTROLLED":
session = _session_from_request(request)
if session:
access = identity_api.effective_access(str(session["principal_id"]), "platform.manage")
controlled = access.get("decision") == "ALLOW"
elif graph_capability == "a2a_gateway" and request.url.path.startswith("/api/a2a/"):
# A2A is also a Gateway surface. A controlled capability
# must admit a current Agent transport before the route
# dependency performs its binding and scope checks; the
# browser-session-only check here used to reject valid
# external Agents with GRAPH_CAPABILITY_CONTROLLED.
authorization = request.headers.get("Authorization", "")
raw_token = authorization[7:].strip() if authorization.lower().startswith("bearer ") else ""
agent_id = request.headers.get("X-Agent-Id", "").strip()
instance_id = request.headers.get("X-Agent-Instance", "").strip()
if raw_token and agent_id and instance_id:
controlled = bool(agent_gateway_api.authenticate_access_token(
raw_token, agent_id, instance_id, "agents.operate", operation="agents.operate",
))
if not controlled:
return JSONResponse({"detail": {"code": "GRAPH_CAPABILITY_CONTROLLED", "capability": graph_capability}}, status_code=403)
graph_production_profile.require(graph_capability, controlled=controlled)
except graph_production_profile.ProfileConflict as exc:
return JSONResponse({"detail": {"code": "GRAPH_CAPABILITY_BLOCKED", "message": str(exc)}}, status_code=409)
except graph_production_profile.ProfileUnavailable:
return JSONResponse({"detail": {"code": "GRAPH_CAPABILITY_UNAVAILABLE", "capability": graph_capability}}, status_code=503)
return await call_next(request)
@app.middleware("http")
async def enforce_database_read_only_session(request: Request, call_next):
"""Fence every authenticated browser mutation for a DB-marked identity."""
if request.method not in {"GET", "HEAD", "OPTIONS"} and request.url.path not in {
"/api/auth/logout", "/portal/api/auth/logout",
}:
scope = "PORTAL" if request.url.path.startswith("/portal/") else "DASHBOARD"
session = _session_from_request(request, scope)
if session:
try:
with _schema_owner_context():
read_only = identity_api.is_global_read_only_principal(str(session["principal_id"]))
except Exception:
return JSONResponse({"detail": "Authorization service unavailable"}, status_code=503)
if read_only:
return JSONResponse({"detail": "This session is read-only"}, status_code=403)
return await call_next(request)
@app.middleware("http")
async def clear_agent_database_context(request: Request, call_next):
"""Clear DB identity and renew authenticated inactivity Sessions."""
try:
response = await call_next(request)
session = getattr(request.state, "cx_session", None)
raw_session_id = getattr(request.state, "cx_session_id", "")
session_scope = getattr(request.state, "cx_session_scope", "DASHBOARD")
session_exit_paths = {
"/api/auth/logout",
"/portal/api/auth/logout",
"/portal/api/agent/release",
}
if session and raw_session_id and request.url.path not in session_exit_paths and response.status_code < 400:
_set_session_cookie(response, {"session_id": raw_session_id}, session_scope, request.url.port)
expires_at = _browser_session_expiry(session.get("expires_at"))
if expires_at:
response.headers["X-Session-Expires-At"] = expires_at
return response
finally:
clear_context = getattr(connection, "set_agent_context", None)
if callable(clear_context):
clear_context(None)
@app.middleware("http")
async def attach_correlation_id(request: Request, call_next):
correlation = _correlation_id(request)
response = await call_next(request)
response.headers["X-Correlation-ID"] = correlation
return response
# Last registered middleware is outermost. Preserve the original TCP peer in
# the ASGI server (--no-proxy-headers); this layer owns explicit proxy trust.
app.add_middleware(network_access.SourceIPMiddleware,
trusted_proxy_cidrs=os.environ.get("CX_TRUSTED_PROXY_CIDRS", ""))
def _local_node_id() -> str:
return agent_gateway_api.local_node_id()
@contextmanager
def _schema_owner_context():
"""Run human identity checks outside any Business Agent context."""
previous = connection.get_current_agent_id()
if previous:
connection.set_agent_context(None)
try:
yield
finally:
connection.set_agent_context(previous)
def _gateway_request_context(func):
"""Fence one synchronous Gateway call to its worker-thread invocation."""
@functools.wraps(func)
def wrapped(*args: Any, **kwargs: Any):
clear_context = getattr(connection, "set_agent_context", None)
if callable(clear_context):
clear_context(None)
try:
return func(*args, **kwargs)
finally:
if callable(clear_context):
clear_context(None)
return wrapped
def _reclaim_local_agents() -> int:
"""Reclaim only Portal and Gateway leases owned by this process node."""
reclaimed = 0
try:
try:
from lib import agent_api
except ModuleNotFoundError:
from shared.lib import agent_api
reclaimed += int(agent_api.reclaim_portal_agents(_local_node_id()) or 0)
except Exception:
pass
try:
reclaimed += int(agent_gateway_api.reclaim_local_instances(_local_node_id()) or 0)
except Exception:
pass
return reclaimed
def _start_compliance_controller() -> None:
"""Run only the deterministic Controller; leases make multi-node safe."""
features = _edition_features()
if features is not None and not features.has_feature("compliance"):
return
def worker() -> None:
try:
from lib import compliance_controller
except ModuleNotFoundError:
from shared.lib import compliance_controller
while not _COMPLIANCE_CONTROLLER_STOP.is_set():
try:
if platform_capabilities.is_enabled("compliance"):
compliance_controller.run_once(_local_node_id(), limit=50)
except Exception:
logger.debug("Compliance Controller cycle failed", exc_info=True)
_COMPLIANCE_CONTROLLER_STOP.wait(30)
threading.Thread(target=worker, name="cx-compliance-controller", daemon=True).start()
def _start_native_runtime() -> None:
"""Run the reference local Worker; database leases coordinate nodes."""
def worker() -> None:
while not _NATIVE_RUNTIME_STOP.is_set():
try:
native_runtime.execute_one(node_id=_local_node_id())
except Exception:
logger.debug("Native Runtime cycle failed", exc_info=True)
_NATIVE_RUNTIME_STOP.wait(2)
threading.Thread(target=worker, name="cx-native-runtime", daemon=True).start()
def _bootstrap_native_agents() -> None:
"""Initialize platform-owned Agent identities after database migration.
A v4.3.5 database does not have the additive v4.3.6 tables yet. Startup
remains compatible in that state; the migration runner is authoritative
and the next restart will complete bootstrap.
"""
try:
native_agent_api.bootstrap_native_agents()
except Exception:
logger.info("Native Agent bootstrap is pending migration", exc_info=True)
def _bootstrap_admin_management() -> None:
"""Initialize v4.4.1 management objects after their additive migration."""
try:
admin_management.initialize()
except Exception:
logger.info("Platform Administration bootstrap is pending migration", exc_info=True)
def _bootstrap_managed_node() -> None:
"""Record this platform runtime as an Admin Agent node automatically."""
try:
host = os.environ.get("CX_NODE_HOST", "").strip() or agent_gateway_api.local_node_id().split(":", 1)[0]
module_dir = Path(__file__).resolve().parent
deployment_dir = module_dir.parent if module_dir.name == "scripts" else module_dir
platform_agent_pool.ensure_managed_node(
node_key=DEFAULT_NODE_ID, host_reference=host, roles=["ADMIN_AGENT"],
actor="SYSTEM_BOOTSTRAP", agent_info_path=str(deployment_dir),
reason="Platform startup collected the local runtime node metadata",
)
except Exception:
logger.info("Managed node discovery is pending migration", exc_info=True)
def _remove_enterprise_compliance_routes() -> None:
"""Keep Enterprise compliance HTTP surfaces out of Community runtimes."""
features = _edition_features()
if features is None or features.has_feature("compliance"):
return
app.router.routes[:] = [
route for route in app.router.routes
if getattr(route, "path", "") not in _ENTERPRISE_COMPLIANCE_PATHS
]
@app.on_event("startup")
def on_startup() -> None:
# Recovery is deliberately node-scoped; another collaborating Dashboard
# node keeps its leases and active Agent assignment.
_remove_enterprise_compliance_routes()
_reclaim_local_agents()
_COMPLIANCE_CONTROLLER_STOP.clear()
_NATIVE_RUNTIME_STOP.clear()
_bootstrap_native_agents()
_bootstrap_admin_management()
_bootstrap_managed_node()
_start_compliance_controller()
_start_native_runtime()
@app.on_event("shutdown")
def on_shutdown() -> None:
_COMPLIANCE_CONTROLLER_STOP.set()
_NATIVE_RUNTIME_STOP.set()
_reclaim_local_agents()
try:
identity_api.connection.close_pool()
except Exception:
pass
def _legacy_module():
"""Load the established page/API implementation only for compatibility routes."""
try:
from visualization import server as legacy
except ModuleNotFoundError:
from shared.visualization import server as legacy
return legacy
def _build_legacy_handler(method: str, path: str, query: str, headers: Dict[str, str], body: bytes, wfile: Any):
"""Build an in-process legacy handler backed by the supplied writer."""
legacy = _legacy_module()
raw_headers = "".join(f"{key}: {value}\r\n" for key, value in headers.items()) + "\r\n"
handler = legacy.VisHandler.__new__(legacy.VisHandler)
handler.rfile = io.BytesIO(body or b"")
handler.wfile = wfile
handler.headers = BytesParser(policy=HTTP).parsebytes(raw_headers.encode("latin-1"))
handler.request_version = "HTTP/1.1"
handler.command = method
handler.path = path + (("?" + query) if query else "")
handler.requestline = f"{method} {handler.path} HTTP/1.1"
handler.client_address = (headers.get("x-forwarded-for", "127.0.0.1"), 0)
# Match FastAPI's Host-derived request port, without mutating process-wide
# configuration shared by simultaneous compatibility requests.
try:
handler._cx_cookie_port = str(urlsplit("//" + str(handler.headers.get("Host", ""))).port
or os.environ.get("MEMORY_SERVER_PORT", "8000"))
except ValueError:
handler._cx_cookie_port = os.environ.get("MEMORY_SERVER_PORT", "8000")
handler.server = type("CompatServer", (), {
"server_name": "chuanxu",
"server_port": int(os.environ.get("MEMORY_SERVER_PORT", "8000")),
})()
handler.close_connection = True
return handler
def _run_legacy_handler(handler: Any, method: str) -> None:
legacy = _legacy_module()
token = legacy._request_cookie_port.set(handler._cx_cookie_port)
try:
if method == "GET":
handler.do_GET()
elif method == "POST":
handler.do_POST()
else:
handler.do_GET()
finally:
legacy._request_cookie_port.reset(token)
def _parse_legacy_response_head(head: bytes) -> tuple[int, Dict[str, str]]:
lines = head.split(b"\r\n")
try:
status_code = int(lines[0].split(None, 2)[1])
except (IndexError, ValueError):
status_code = 502
response_headers: Dict[str, str] = {}
for line in lines[1:]:
if b":" not in line:
continue
key, value = line.split(b":", 1)
name = key.decode("latin-1")
if name.lower() in {"content-length", "transfer-encoding", "connection"}:
continue
response_headers[name] = value.lstrip().decode("latin-1")
return status_code, response_headers
class _LegacyStreamWriter:
"""Expose BaseHTTPRequestHandler output as incrementally consumable chunks."""
_END = object()
def __init__(self) -> None:
self._head_buffer = bytearray()
self._chunks: queue.Queue[Any] = queue.Queue(maxsize=64)
self.headers_ready = threading.Event()
self.closed = threading.Event()
self.status_code = 502
self.response_headers: Dict[str, str] = {}
self.error: Optional[BaseException] = None
def write(self, data: bytes) -> int:
if self.closed.is_set():
raise BrokenPipeError("stream client disconnected")
payload = bytes(data)
if not self.headers_ready.is_set():
self._head_buffer.extend(payload)
marker = self._head_buffer.find(b"\r\n\r\n")
if marker < 0:
return len(data)
head = bytes(self._head_buffer[:marker])
payload = bytes(self._head_buffer[marker + 4:])
self._head_buffer.clear()
self.status_code, self.response_headers = _parse_legacy_response_head(head)
self.headers_ready.set()
if payload:
self._put(payload)
return len(data)
def flush(self) -> None:
return None
def _put(self, item: Any) -> None:
while not self.closed.is_set():
try:
self._chunks.put(item, timeout=0.2)
return
except queue.Full:
continue
raise BrokenPipeError("stream client disconnected")
def finish(self, error: Optional[BaseException] = None) -> None:
self.error = error
if not self.headers_ready.is_set():
self.headers_ready.set()
try:
self._put(self._END)
except BrokenPipeError:
pass
def iter_chunks(self) -> Iterator[bytes]:
try:
while True:
chunk = self._chunks.get()
if chunk is self._END:
if self.error:
logger.error("Legacy streaming handler failed: %s", self.error)
return
yield chunk
finally:
self.closed.set()
def _clear_legacy_thread_context() -> None:
clear_context = getattr(connection, "set_agent_context", None)
if callable(clear_context):
clear_context(None)
def _legacy_stream_worker(handler: Any, method: str, writer: _LegacyStreamWriter) -> None:
error: Optional[BaseException] = None
try:
_run_legacy_handler(handler, method)
except (BrokenPipeError, ConnectionResetError):
pass
except BaseException as exc:
error = exc
finally:
_clear_legacy_thread_context()
writer.finish(error)
async def _legacy_stream_dispatch(
method: str, path: str, query: str, headers: Dict[str, str], body: bytes,
) -> Response:
writer = _LegacyStreamWriter()
handler = _build_legacy_handler(method, path, query, headers, body, writer)
worker = threading.Thread(
target=_legacy_stream_worker,
args=(handler, method, writer),
name="portal-stream",
daemon=True,
)
worker.start()
await asyncio.to_thread(writer.headers_ready.wait)
if writer.error and not writer.response_headers:
return JSONResponse({"error": str(writer.error)}, status_code=500)
return StreamingResponse(
writer.iter_chunks(),
status_code=writer.status_code,
headers=writer.response_headers,
media_type=None,
)
def _legacy_dispatch(method: str, path: str, query: str, headers: Dict[str, str], body: bytes) -> Response:
"""Run a non-streaming legacy handler without starting a second listener.
The compatibility bridge is deliberately request-local: it does not own a
socket, thread, session store, scheduler, or database connection. FastAPI
remains the only network entrypoint while v4.1 pages and clients keep their
existing contracts during the React migration.
"""
handler = _build_legacy_handler(method, path, query, headers, body, io.BytesIO())
try:
_run_legacy_handler(handler, method)
except Exception as exc: # the legacy handler normally serializes errors itself
payload = json.dumps({"error": str(exc)}).encode("utf-8")
return Response(payload, status_code=500, media_type="application/json")
finally:
# The legacy handler may set a Business Agent identity for Portal
# operations. FastAPI reuses this event-loop thread between requests,
# so never carry that identity into the next human authorization check.
clear_context = getattr(connection, "set_agent_context", None)
if callable(clear_context):
clear_context(None)
raw = handler.wfile.getvalue()
marker = raw.find(b"\r\n\r\n")
if marker < 0:
return Response(raw, status_code=502, media_type="text/plain")
head, payload = raw[:marker], raw[marker + 4:]
status_code, response_headers = _parse_legacy_response_head(head)
return Response(payload, status_code=status_code, headers=response_headers)
def _legacy_read_dispatch(request: Request, path: str, body: bytes) -> Response:
"""Keep read admission and synchronous DB work in one fenced worker.
Legacy reads share the bounded ASGI worker pool with synchronous routes.
A slow query must not block the event loop or other responses. Admission
and dispatch stay on the same thread, and no Agent identity survives a
successful, denied or failed invocation of that reusable worker.
"""
_clear_legacy_thread_context()
try:
denied = _legacy_gate(request, path)
if denied is not None:
return denied
return _legacy_dispatch(request.method, path, request.url.query, dict(request.headers), body)
finally:
_clear_legacy_thread_context()
def _legacy_required_action(path: str, method: str) -> Optional[str]:
"""Map compatibility APIs to the same coarse permission boundary as React."""
rules = (
("/api/monitor", "agents.read"),
("/api/agents", "agents.read"),
("/api/tasks", "tasks.read"),
("/api/workspaces", "workspaces.read"),
("/api/knowledge", "knowledge.read"),
("/api/memory", "memory.read"),
("/api/skills", "skills.read"),
("/api/skill", "skills.read"),
("/api/agent/skills", "skills.read"),
("/api/specs", "specs.read"),
("/api/branches", "branches.read"),
("/api/branch", "branches.read"),
("/api/collab", "collab.read"),
("/api/loops", "loops.read"),
("/api/graphs", "graphs.read"),
("/api/graph-", "graphs.read"),
("/api/graph/", "graphs.read"),
("/api/approvals", "approvals.read"),
("/api/audit", "audit.read"),
("/api/traces", "audit.read"),
("/api/tools", "tools.read"),
("/api/events", "notifications.read"),
("/api/users", "users.read"),
("/api/registration", "users.read"),
("/api/governance", "security.read"),
("/api/execution", "tasks.read"),
("/ap/v1/agent/tasks", "tasks.read"),
)
for prefix, action in rules:
if path == prefix or path.startswith(prefix + "/"):
if method in {"POST", "PUT", "PATCH", "DELETE"}:
return {
"agents.read": "agents.operate",
"tasks.read": "tasks.write",
"workspaces.read": "workspaces.write",
"knowledge.read": "knowledge.write",
"memory.read": "memory.write",
"skills.read": "skills.write",
"specs.read": "specs.write",
"branches.read": "branches.write",
"collab.read": "collab.write",
"loops.read": "loops.write",
"graphs.read": "graphs.write",
"approvals.read": "approvals.decide",
"audit.read": "audit.export",
"tools.read": "tools.write",
"notifications.read": "notifications.write",
}.get(action, action)
return action
return None
def _legacy_gate(request: Request, path: str) -> Optional[Response]:
"""Apply session, Agent-token, CSRF and coarse permission checks to legacy APIs."""
if not path.startswith(("/api/", "/portal/api/", "/ap/")):
return None
if path in _TOKEN_LEGACY_API and path not in {"/api/agents/heartbeat"}:
try:
native_agent_api.enforce_external_registration_allowed()
except PermissionError as exc:
return JSONResponse({"error": "External Agent registration is disabled"}, status_code=409)
except Exception:
return JSONResponse({"error": "External Agent registration policy unavailable"}, status_code=503)
return None
if path in _PUBLIC_LEGACY_API or path in _TOKEN_LEGACY_API:
return None
agent_id = request.headers.get("X-Agent-Id", "").strip()
agent_token = request.headers.get("X-Agent-Token", "").strip()
if agent_id or agent_token:
try:
try:
from lib import agent_registration
except ModuleNotFoundError:
from shared.lib import agent_registration
valid = bool(agent_id and agent_token and agent_registration.authenticate_agent(agent_id, agent_token))
except Exception:
valid = False
if not valid:
return JSONResponse({"error": "Registered Agent authentication required"}, status_code=401)
# Agent requests carry their own admission proof and must not be
# forced to manufacture a human CSRF token.
return None
entry = "PORTAL" if path.startswith("/portal/api/") else "APP"
session = _session_from_request(
request, "PORTAL" if entry == "PORTAL" else "DASHBOARD"
)
if not session:
return JSONResponse({"error": "Authentication required"}, status_code=401)
try:
with _schema_owner_context():
allowed = identity_api.entry_allowed(str(session["principal_id"]), entry)
if not allowed:
return JSONResponse({"error": f"{entry.title()} access is disabled"}, status_code=403)
except Exception:
return JSONResponse({"error": "Entry-access policy is unavailable"}, status_code=503)
if str(session.get("mfa_level") or "NONE").upper() == "SETUP":
return JSONResponse({"error": "MFA setup required"}, status_code=403)
if request.method in {"POST", "PUT", "PATCH", "DELETE"}:
if not identity_api.verify_csrf(session, request.headers.get("X-CSRF-Token", "")):
return JSONResponse({"error": "CSRF validation failed"}, status_code=403)
action = _legacy_required_action(path, request.method)
if action:
try:
with _schema_owner_context():
access = identity_api.effective_access(str(session["principal_id"]), action)
except Exception:
return JSONResponse({"error": "Authorization service unavailable"}, status_code=503)
if access.get("decision") != "ALLOW":
return JSONResponse({"error": "permission denied", "access": access}, status_code=403)
return None
@app.get("/static/{file_path:path}")
def static_file(file_path: str) -> Response:
candidates = [
DIST_ROOT / file_path,
Path(__file__).resolve().parent / "visualization" / "static" / file_path,
Path(__file__).resolve().parent / "visualization" / "static" / "brand" / file_path,
Path(__file__).resolve().parent / "scripts" / "visualization" / "static" / file_path,
Path(__file__).resolve().parent.parent / "scripts" / "visualization" / "static" / "brand" / file_path,
Path(__file__).resolve().parent.parent / "business_plan" / "brand" / "visual_system" / "assets" / Path(file_path).name,
]
for candidate in candidates:
if candidate.is_file():
# The control-plane UI is security-sensitive. Do not let a browser
# reuse an older bundle after a session-boundary or UI correction.
return FileResponse(candidate, headers={"Cache-Control": "no-store"})
raise HTTPException(status_code=404, detail="Static asset not found")
class RegistrationBody(BaseModel):
display_name: str = Field(min_length=1, max_length=256)
username: str = Field(min_length=3, max_length=128)
password: str = Field(min_length=12, max_length=1024)
email: str = Field(default="", max_length=320)
mobile: str = Field(default="", max_length=64)
invite_code: str = Field(default="", max_length=512)
registration_token: str = Field(default="", max_length=512)
class HumanRegistrationTokenBody(BaseModel):
expires_in_seconds: int = Field(default=3600, ge=60, le=604800)
reason: str = Field(min_length=1, max_length=2000)
class RegistrationFieldPolicyBody(BaseModel):
field_state: str = Field(min_length=1, max_length=16)
expected_version: int = Field(ge=0)
reason: str = Field(min_length=1, max_length=2000)
class RegistrationTokenPolicyBody(BaseModel):
required: bool
expected_version: int = Field(ge=0)
reason: str = Field(min_length=1, max_length=2000)
class PortalConnectionPolicyBody(BaseModel):
max_connections: int = Field(ge=1, le=32)
expected_version: int = Field(ge=0)
reason: str = Field(min_length=1, max_length=2000)
class ExternalProviderBody(BaseModel):
provider_key: str = Field(min_length=1, max_length=128)
adapter_type: str = Field(min_length=1, max_length=128)
protocol_type: str = Field(min_length=1, max_length=64)
issuer: str = Field(default="", max_length=512)
tenant_reference: str = Field(default="", max_length=256)
endpoints: Dict[str, Any] = Field(default_factory=dict)
redirect_allowlist: list[str] = Field(default_factory=list, max_length=20)
scopes: list[str] = Field(default_factory=list, max_length=100)
credential_reference: str = Field(default="", max_length=256)
attribute_mapping: Dict[str, Any] = Field(default_factory=dict)
registration_policy: str = Field(default="APPROVAL", max_length=32)
status: str = Field(default="DISABLED", max_length=24)
expected_version: int = Field(default=0, ge=0)
reason: str = Field(min_length=1, max_length=2000)
class ExternalLoginStartBody(BaseModel):
provider_id: str = Field(min_length=1, max_length=128)
entry: str = Field(default="PORTAL", max_length=16)
redirect_uri: str = Field(default="", max_length=2048)
class ExternalLoginCallbackBody(BaseModel):
transaction_id: str = Field(min_length=1, max_length=128)
state: str = Field(min_length=1, max_length=512)
nonce: str = Field(min_length=1, max_length=512)
callback_digest: str = Field(min_length=1, max_length=512)
class LoginBody(BaseModel):
username: str = Field(min_length=1, max_length=128)
password: str = Field(min_length=1, max_length=1024)
mfa_code: str = Field(default="", max_length=32)
class PasswordResetRequestBody(BaseModel):
username: str = Field(min_length=1, max_length=128)
class PasswordResetConsumeBody(BaseModel):
token: str = Field(min_length=20, max_length=512)
new_password: str = Field(min_length=12, max_length=1024)
reason: str = Field(default="password reset", max_length=2000)
class IdentityLinkBody(BaseModel):
target_principal_id: str = Field(min_length=1, max_length=128)
identity_type: str = Field(min_length=1, max_length=16)
provider: str = Field(min_length=1, max_length=256)
subject_key: str = Field(min_length=1, max_length=512)
reason: str = Field(min_length=1, max_length=2000)
class MfaPolicyBody(BaseModel):
required: bool
reason: str = Field(min_length=1, max_length=2000)
class MfaEnrollBody(BaseModel):
target_principal_id: str = Field(default="", max_length=128)
reason: str = Field(min_length=1, max_length=2000)
class MfaConfirmBody(BaseModel):
factor_id: str = Field(min_length=1, max_length=128)
code: str = Field(min_length=6, max_length=32)
reason: str = Field(default="MFA enrollment confirmation", min_length=1, max_length=2000)
class OrganizationChangeBody(BaseModel):
reason: str = Field(min_length=1, max_length=2000)
operations: list[Dict[str, Any]] = Field(default_factory=list, max_length=1000)
idempotency_key: str = Field(default="", max_length=256)
class OrganizationOperationBody(BaseModel):
operation: Dict[str, Any]
reason: str = Field(default="MFA enrollment confirmation", max_length=2000)
class OrganizationWorkflowBody(BaseModel):
reason: str = Field(default="", max_length=2000)
class RecoveryCodesBody(BaseModel):
target_principal_id: str = Field(default="", max_length=128)