Repository navigation
Expand file tree
/
Copy pathbiomodstack_tailnet.py
More file actions
2604 lines (2432 loc) · 110 KB
/
Copy pathbiomodstack_tailnet.py
File metadata and controls
2604 lines (2432 loc) · 110 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
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime
import base64
import binascii
import fcntl
import hashlib
import ipaddress
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import time
from typing import Any, Iterator, Mapping, cast
import urllib.error
import urllib.parse
import urllib.request
from biomodstack_runtime_profile import load_install_profile
from biomodstack_services import systemd_exec_arg, systemd_value
from biomodstack_services import (
API_SERVICE,
CONTAINER_RUNTIME_MODE,
DEVELOPMENT_WORKFLOW_ADAPTER_PORT,
DEVELOPMENT_WORKFLOW_ADAPTER_SERVICE,
DEV_RUNTIME_MODE,
FRONTEND_SERVICE,
ServiceManagerError,
daemon_reload,
git_build_identity,
listener_pids,
render_user_units,
run_systemctl,
service_is_active,
runtime_api_health_url,
runtime_api_port,
runtime_frontend_port,
runtime_frontend_url,
wait_for_http,
)
STATE_ROOT = Path.home() / ".local" / "state" / "biomodstack"
SELECTION_STATE_PATH = STATE_ROOT / "tailnet-environment.json"
SELECTION_LOCK_PATH = STATE_ROOT / "tailnet-environment.lock"
SUPPORTED_ENVIRONMENTS = ("development", "production")
CANONICAL_DEVELOPMENT_ROOT = Path.home() / "biomodstack" / "dev-test-canonical"
CANONICAL_PRODUCTION_ROOT = Path.home() / "biomodstack" / "prod-main-canonical"
CONTROL_PATH = "/api/tailnet-environment"
PRODUCTION_API_PORT = 18000
# Tailnet's authenticated selector is a Development control surface. Keep the
# old local names as aliases for compatibility with callers, but never bind the
# selector policy to the Production execution adapter.
WORKFLOW_ADAPTER_PORT = DEVELOPMENT_WORKFLOW_ADAPTER_PORT
WORKFLOW_ADAPTER_SERVICE = DEVELOPMENT_WORKFLOW_ADAPTER_SERVICE
DEFAULT_CONTROL_TARGET = f"http://127.0.0.1:{DEVELOPMENT_WORKFLOW_ADAPTER_PORT}"
LEGACY_CONTROL_TARGET = "http://127.0.0.1:8001/api/workflow-adapter/tailnet-environment"
PRIOR_LOOPBACK_CONTROL_TARGET = "http://127.0.0.2:8001"
STATS_TOOLKIT_TARGET = "http://127.0.0.1:18180"
LEGACY_GLOBAL_SERVE_HANDLERS: Mapping[str, frozenset[str]] = {
# The original embed mapping mounted the Stats server root. The governed
# application now lives at /stats; allow only this exact prior target to be
# migrated transactionally while continuing to reject foreign owners.
"/stats/embed": frozenset({STATS_TOOLKIT_TARGET}),
"/api/mobile-apk": frozenset({
"http://127.0.0.1:8000/api/mobile-apk",
"http://127.0.0.1:18000/api/mobile-apk",
}),
"/api/mobile-ui": frozenset({
"http://127.0.0.1:8000/api/mobile-ui",
"http://127.0.0.1:18000/api/mobile-ui",
}),
}
DEPRECATED_SERVE_HANDLERS: Mapping[str, str] = {
"/am": "http://127.0.0.1:5174/am",
"/vlm": "http://127.0.0.1:8010",
}
PRODUCTION_TAILNET_PROXY_PORT = 18081
PRODUCTION_TAILNET_PROXY_CONTAINER = "biomodstack-tailnet-production-proxy"
PRODUCTION_TAILNET_PROXY_IMAGE = "nginx@sha256:65645c7bb6a0661892a8b03b89d0743208a18dd2f3f17a54ef4b76fb8e2f2a10"
PRODUCTION_TAILNET_PROXY_IMAGE_ID = "sha256:6769dc3a703c719c1d2756bda113659be28ae16cf0da58dd5fd823d6b9a050ea"
HOST_PROC_HELPER_IMAGE = "python:3.10-slim-bookworm@sha256:9643927a6fc74bd81b0f1bbb5cce3cb4a491f46b4c5dbee770f28e575f180015"
MANAGED_API_IMAGE_ID = "sha256:74bf34e32e2f5d0f72d3f6d117c1b4877c169e7a62c0da06ea05b75d5e0cd12c"
MANAGED_WEB_IMAGE_ID = "sha256:7e79b645349216a2457cd2f64af53beb26d9041c7911ed8438d6708239017c3e"
_IMAGE_ID_PATTERN = re.compile(r"sha256:[0-9a-f]{64}")
PRODUCTION_TAILNET_PROXY_CONFIG = Path("docker/tailnet-production-proxy.conf")
PRODUCTION_TAILNET_PROXY_SHA_LABEL = "com.biomodstack.tailnet-proxy-config-sha"
_TAILSCALE_LOGIN_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9@._+\-]{0,253}$")
_GIT_REVISION_PATTERN = re.compile(r"^[0-9a-f]{40}$")
_BUILD_TIME_PATTERN = re.compile(
r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.\d{1,9})?Z$"
)
class TailnetEnvironmentError(ServiceManagerError):
"""Raised when an environment switch cannot be completed safely."""
def _configured_control_target(environment: Mapping[str, str] | None = None) -> str:
values = os.environ if environment is None else environment
target = values.get("BMS_TAILNET_CONTROL_TARGET", DEFAULT_CONTROL_TARGET).rstrip("/")
parsed = urllib.parse.urlsplit(target)
try:
address = ipaddress.ip_address(parsed.hostname or "")
port = parsed.port
except ValueError as exc:
raise TailnetEnvironmentError(
"BMS_TAILNET_CONTROL_TARGET must be the workflow adapter's loopback HTTP target on port 18001"
) from exc
if (
parsed.scheme != "http"
or parsed.username is not None
or parsed.password is not None
or not address.is_loopback
or port != 18001
or parsed.path not in ("", "/")
or parsed.query
or parsed.fragment
):
raise TailnetEnvironmentError(
"BMS_TAILNET_CONTROL_TARGET must be the workflow adapter's loopback HTTP target on port 18001"
)
return f"http://{address.compressed}:18001"
CONTROL_TARGET = _configured_control_target()
LEGACY_CONTROL_TARGETS = frozenset({
LEGACY_CONTROL_TARGET,
"http://127.0.0.1:8001",
PRIOR_LOOPBACK_CONTROL_TARGET,
})
GLOBAL_SERVE_HANDLERS: Mapping[str, str] = {
CONTROL_PATH: CONTROL_TARGET,
"/api/mobile-apk": "http://127.0.0.1:18003/api/mobile-apk",
"/api/mobile-ui": "http://127.0.0.1:18003/api/mobile-ui",
"/stats/embed": f"{STATS_TOOLKIT_TARGET}/stats",
"/stats/assets": f"{STATS_TOOLKIT_TARGET}/stats/assets",
"/stats/embed/health/live": f"{STATS_TOOLKIT_TARGET}/health/live",
"/stats/embed/health/ready": f"{STATS_TOOLKIT_TARGET}/health/ready",
"/stats/embed/api/v1/capabilities": f"{STATS_TOOLKIT_TARGET}/api/v1/capabilities",
"/stats/embed/api/v1/tools": f"{STATS_TOOLKIT_TARGET}/api/v1/tools",
}
def _managed_image_id(environment_name: str, sealed_default: str) -> str:
"""Resolve a deploy-time image receipt without weakening its exact-ID contract."""
value = os.environ.get(environment_name, sealed_default)
if not _IMAGE_ID_PATTERN.fullmatch(value):
raise TailnetEnvironmentError(f"{environment_name} is not an exact Docker image ID")
return value
def _host_user_systemd_dir() -> Path:
# systemd --user always reads the login manager's real home configuration;
# never let a Cordova/Gradle XDG_CONFIG_HOME override redirect ownership files.
return Path.home() / ".config" / "systemd" / "user"
@dataclass(frozen=True)
class EnvironmentSpec:
environment: str
runtime_mode: str
runtime_target: str
frontend_url: str
api_health_url: str
serve_target: str
frontend_port: int
api_port: int
@dataclass(frozen=True)
class ServeSnapshot:
origin: str
root_proxy: str
handlers: dict[str, dict[str, Any]]
raw: dict[str, Any]
def environment_spec(environment: str | None, *, project_root: Path | None = None) -> EnvironmentSpec:
normalized = str(environment or "").strip().lower()
if normalized not in SUPPORTED_ENVIRONMENTS:
raise TailnetEnvironmentError(
"Tailnet environment must be selected explicitly: development or production"
)
root = (project_root or Path(__file__).resolve().parent).resolve()
runtime_mode = DEV_RUNTIME_MODE if normalized == "development" else CONTAINER_RUNTIME_MODE
frontend_url = runtime_frontend_url(runtime_mode, project_root=root)
frontend_port = runtime_frontend_port(runtime_mode, project_root=root)
# Each canonical lane owns its own API and database: test/Development uses
# the isolated 18002 API while main/Production uses the container API.
api_port = runtime_api_port(runtime_mode, project_root=root)
api_health_url = runtime_api_health_url(runtime_mode, project_root=root)
# Production nginx owns both /bms/ and /api and redirects / to /bms/. Development
# Vite owns / and its canonical /api proxy. Mapping the origin, not a source path,
# keeps absolute /api requests on the selected environment.
serve_port = frontend_port if runtime_mode == DEV_RUNTIME_MODE else PRODUCTION_TAILNET_PROXY_PORT
serve_target = f"http://127.0.0.1:{serve_port}"
return EnvironmentSpec(
environment=normalized,
runtime_mode=runtime_mode,
runtime_target="dev" if runtime_mode == DEV_RUNTIME_MODE else "prod",
frontend_url=frontend_url,
api_health_url=api_health_url,
serve_target=serve_target,
frontend_port=frontend_port,
api_port=api_port,
)
def _contains_true(value: object) -> bool:
if value is True:
return True
if isinstance(value, Mapping):
return any(_contains_true(nested) for nested in value.values())
if isinstance(value, list):
return any(_contains_true(item) for item in value)
return False
def _contains_enabled_funnel(value: object) -> bool:
if isinstance(value, Mapping):
for key, nested in value.items():
normalized_key = str(key).casefold()
if normalized_key == "funnel" and nested is True:
return True
if normalized_key == "allowfunnel" and _contains_true(nested):
return True
if _contains_enabled_funnel(nested):
return True
elif isinstance(value, list):
return any(_contains_enabled_funnel(item) for item in value)
return False
def _canonical_loopback_http_target(value: object) -> str | None:
if not isinstance(value, str):
return None
try:
parsed = urllib.parse.urlsplit(value)
port = parsed.port
except ValueError:
return None
if (
parsed.scheme != "http"
or parsed.hostname != "127.0.0.1"
or parsed.username is not None
or parsed.password is not None
or port is None
or not 1 <= port <= 65535
or parsed.netloc != f"127.0.0.1:{port}"
or parsed.path not in ("", "/")
or parsed.query
or parsed.fragment
):
return None
return f"http://127.0.0.1:{port}"
def serve_snapshot(status: Mapping[str, object]) -> ServeSnapshot:
raw = dict(status)
if _contains_enabled_funnel(raw):
raise TailnetEnvironmentError("Tailscale Funnel is enabled; refusing to modify public exposure")
web = raw.get("Web")
if not isinstance(web, Mapping) or not web:
raise TailnetEnvironmentError("Tailscale Serve has no HTTPS web host to update")
candidates: list[tuple[str, Mapping[str, object]]] = []
for host, config in web.items():
if not isinstance(config, Mapping):
continue
handlers = config.get("Handlers")
if isinstance(handlers, Mapping) and "/" in handlers:
candidates.append((str(host), handlers))
if len(candidates) != 1:
raise TailnetEnvironmentError("Tailscale Serve must expose exactly one root handler")
host, raw_handlers = candidates[0]
root_handler = raw_handlers.get("/")
if not isinstance(root_handler, Mapping):
raise TailnetEnvironmentError("Tailscale Serve root handler is invalid")
root_proxy = _canonical_loopback_http_target(root_handler.get("Proxy"))
if root_proxy is None:
raise TailnetEnvironmentError("Tailscale Serve root must proxy a canonical loopback HTTP target")
normalized_handlers: dict[str, dict[str, Any]] = {}
for path, handler in raw_handlers.items():
if isinstance(handler, Mapping):
normalized_handlers[str(path)] = dict(handler)
# Receipts are consumed by JavaScript with an exact canonical target
# contract. Never retain an otherwise tolerated root slash in the emitted
# handler after canonicalizing root_proxy.
normalized_handlers["/"]["Proxy"] = root_proxy
hostname = host.rsplit(":", 1)[0] if host.endswith(":443") else host
return ServeSnapshot(
origin=f"https://{hostname}",
root_proxy=root_proxy,
handlers=normalized_handlers,
raw=raw,
)
def _run(command: list[str], *, timeout: float = 60.0) -> subprocess.CompletedProcess[str]:
result = subprocess.run(
command,
check=False,
capture_output=True,
text=True,
timeout=timeout,
)
if result.returncode != 0:
detail = result.stderr.strip() or result.stdout.strip() or f"exit {result.returncode}"
raise TailnetEnvironmentError(f"{' '.join(command)} failed: {detail}")
return result
def _read_serve_snapshot() -> ServeSnapshot:
result = _run(["tailscale", "serve", "status", "--json"])
try:
status = json.loads(result.stdout)
except json.JSONDecodeError as exc:
raise TailnetEnvironmentError("Tailscale Serve returned invalid JSON") from exc
if not isinstance(status, Mapping):
raise TailnetEnvironmentError("Tailscale Serve status must be a JSON object")
return serve_snapshot(status)
def _set_serve_root(target: str) -> None:
if _canonical_loopback_http_target(target) != target:
raise TailnetEnvironmentError("refusing non-loopback Tailnet proxy target")
_run(["tailscale", "serve", "--bg", "--yes", target])
def _set_serve_path(path: str, target: str) -> None:
allowed_targets = dict(GLOBAL_SERVE_HANDLERS)
allowed_targets[CONTROL_PATH] = CONTROL_TARGET
if path == CONTROL_PATH and target in LEGACY_CONTROL_TARGETS:
pass
elif target in LEGACY_GLOBAL_SERVE_HANDLERS.get(path, frozenset()):
pass
elif allowed_targets.get(path) != target:
raise TailnetEnvironmentError("refusing an unexpected global Tailnet path mapping")
parsed = urllib.parse.urlsplit(target)
target_origin = f"{parsed.scheme}://{parsed.netloc}"
if (
_canonical_loopback_http_target(target_origin) != target_origin
or (parsed.path and not parsed.path.startswith("/"))
or parsed.query
or parsed.fragment
):
raise TailnetEnvironmentError("refusing a non-loopback global Tailnet target")
_run(["tailscale", "serve", "--bg", "--yes", f"--set-path={path}", target])
def _clear_serve_path(path: str) -> None:
if path not in GLOBAL_SERVE_HANDLERS and path not in DEPRECATED_SERVE_HANDLERS:
raise TailnetEnvironmentError("refusing to clear an unexpected Tailnet path")
_run(["tailscale", "serve", "--bg", "--yes", f"--set-path={path}", "off"])
def _restore_control_route(snapshot: ServeSnapshot) -> None:
prior_control = snapshot.handlers.get(CONTROL_PATH)
if prior_control is None:
_clear_serve_path(CONTROL_PATH)
return
prior_target = str(prior_control.get("Proxy", "")).rstrip("/")
if prior_target != CONTROL_TARGET and prior_target not in LEGACY_CONTROL_TARGETS:
raise TailnetEnvironmentError("prior Tailnet control target is not restorable")
_set_serve_path(CONTROL_PATH, prior_target)
def _ensure_control_route(snapshot: ServeSnapshot) -> bool:
existing = snapshot.handlers.get(CONTROL_PATH)
if existing is not None:
existing_target = str(existing.get("Proxy", "")).rstrip("/")
if existing_target == CONTROL_TARGET:
return False
if existing_target not in LEGACY_CONTROL_TARGETS:
raise TailnetEnvironmentError(
f"Tailnet control path is already owned by an unexpected target: {existing}"
)
try:
# Treat the CLI call as an ambiguous mutation: it can apply the route and
# then disconnect before returning success.
_set_serve_path(CONTROL_PATH, CONTROL_TARGET)
installed = _read_serve_snapshot()
handler = installed.handlers.get(CONTROL_PATH)
if not isinstance(handler, Mapping) or str(handler.get("Proxy", "")).rstrip("/") != CONTROL_TARGET:
raise TailnetEnvironmentError("Tailnet control-path installation did not verify")
except Exception as exc:
_restore_control_route(snapshot)
restored = _read_serve_snapshot()
if restored.raw != snapshot.raw:
raise TailnetEnvironmentError(
f"control-path installation failed and rollback did not restore Serve: {exc}"
) from exc
raise
return True
def _control_route_needs_mutation(snapshot: ServeSnapshot) -> bool:
"""Preflight the control route without mutating it."""
existing = snapshot.handlers.get(CONTROL_PATH)
if existing is None:
return True
existing_target = str(existing.get("Proxy", "")).rstrip("/")
if existing_target == CONTROL_TARGET:
return False
if existing_target not in LEGACY_CONTROL_TARGETS:
raise TailnetEnvironmentError(
f"Tailnet control path is already owned by an unexpected target: {existing}"
)
return True
def ensure_global_tailnet_routes() -> ServeSnapshot:
"""Install global routes and remove exact dead legacy mappings without changing `/`.
The operation rejects conflicting managed-route owners, preserves arbitrary
unrelated handlers byte-for-byte, and rolls back to the exact prior Serve
document if any setter, removal, or verification step fails.
"""
prior = _read_serve_snapshot()
expected_handlers = dict(prior.handlers)
mutations: list[tuple[str, str | None]] = []
for path, target in GLOBAL_SERVE_HANDLERS.items():
existing = prior.handlers.get(path)
if existing is None:
mutations.append((path, target))
else:
existing_target = str(existing.get("Proxy", "")).rstrip("/")
allowed_existing = {target}
if path == CONTROL_PATH:
allowed_existing.update(LEGACY_CONTROL_TARGETS)
allowed_existing.update(LEGACY_GLOBAL_SERVE_HANDLERS.get(path, frozenset()))
if existing_target not in allowed_existing:
raise TailnetEnvironmentError(
f"global Tailnet path {path} is already owned by an unexpected target: {existing}"
)
if existing_target != target:
mutations.append((path, target))
expected_handlers[path] = {"Proxy": target}
for path, dead_target in DEPRECATED_SERVE_HANDLERS.items():
existing = prior.handlers.get(path)
if existing is None:
continue
existing_target = str(existing.get("Proxy", "")).rstrip("/")
if existing_target == dead_target:
mutations.append((path, None))
expected_handlers.pop(path, None)
attempted: list[tuple[str, str | None]] = []
try:
for path, target in mutations:
attempted.append((path, target))
if target is None:
_clear_serve_path(path)
else:
_set_serve_path(path, target)
installed = _read_serve_snapshot()
if installed.root_proxy != prior.root_proxy:
raise TailnetEnvironmentError("global Tailnet policy changed Serve root")
if installed.handlers != expected_handlers:
raise TailnetEnvironmentError("global Tailnet policy installation did not verify")
return installed
except Exception as exc:
rollback_errors: list[str] = []
for path, _target in reversed(attempted):
try:
previous = prior.handlers.get(path)
if previous is None:
_clear_serve_path(path)
else:
previous_target = str(previous.get("Proxy", "")).rstrip("/")
if path in DEPRECATED_SERVE_HANDLERS:
_run([
"tailscale", "serve", "--bg", "--yes",
f"--set-path={path}", previous_target,
])
else:
_set_serve_path(path, previous_target)
except Exception as rollback_exc:
rollback_errors.append(f"{path}: {rollback_exc}")
try:
restored = _read_serve_snapshot()
if restored.raw != prior.raw:
raise TailnetEnvironmentError("Serve bytes differ from the prior snapshot")
except Exception as rollback_exc:
rollback_errors.append(f"verification: {rollback_exc}")
detail = f"; rollback also failed: {' | '.join(rollback_errors)}" if rollback_errors else ""
raise TailnetEnvironmentError(
f"global Tailnet policy installation failed: {exc}{detail}"
) from exc
def _url_probe(
url: str,
*,
expect_json: bool = False,
expected_final_url: str | None = None,
timeout: float = 20.0,
) -> dict[str, object]:
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
request = urllib.request.Request(
url,
headers={"Accept": "application/json" if expect_json else "text/html,*/*"},
)
try:
with opener.open(request, timeout=timeout) as response:
status = int(response.status)
body = response.read(1024 * 1024)
final_url = response.geturl()
requested = urllib.parse.urlsplit(url)
final = urllib.parse.urlsplit(final_url)
expected = expected_final_url or url
if (
final.scheme != requested.scheme
or final.netloc != requested.netloc
or final.username is not None
or final.password is not None
or final_url != expected
):
raise TailnetEnvironmentError(
f"health probe did not terminate at its canonical endpoint: "
f"{url} -> {final_url}; expected {expected}"
)
except (urllib.error.URLError, TimeoutError, OSError) as exc:
raise TailnetEnvironmentError(f"health probe failed for {url}: {exc}") from exc
if status != 200:
raise TailnetEnvironmentError(f"health probe returned HTTP {status} for {url}")
payload: object = None
if expect_json:
try:
payload = json.loads(body)
except json.JSONDecodeError as exc:
raise TailnetEnvironmentError(f"health probe returned invalid JSON for {url}") from exc
if not isinstance(payload, Mapping):
raise TailnetEnvironmentError(f"health probe returned a non-object for {url}")
if payload.get("status") != "healthy":
raise TailnetEnvironmentError(f"selected API is not healthy at {url}")
return {
"url": url,
"final_url": final_url,
"status": status,
"payload": payload,
}
def _api_build_identity(probe: Mapping[str, object], *, source: str) -> dict[str, str]:
payload = probe.get("payload")
if not isinstance(payload, Mapping):
raise TailnetEnvironmentError(f"{source} API health has no build provenance")
build = payload.get("build")
if not isinstance(build, Mapping):
raise TailnetEnvironmentError(f"{source} API health has no build provenance")
raw_identity = {
"revision": str(build.get("revision", "")),
"build_id": str(build.get("build_id", "")),
"build_time": str(build.get("build_time", "")),
}
identity = {key: value.strip() for key, value in raw_identity.items()}
if not _GIT_REVISION_PATTERN.fullmatch(identity["revision"]) or not all(identity.values()):
raise TailnetEnvironmentError(f"{source} API health has incomplete build provenance")
if (
raw_identity != identity
or len(identity["build_id"].encode("utf-16-le")) // 2 > 256
):
raise TailnetEnvironmentError(f"{source} API health has noncanonical build provenance")
build_time_match = _BUILD_TIME_PATTERN.fullmatch(identity["build_time"])
if build_time_match is None:
raise TailnetEnvironmentError(f"{source} API health has invalid build time")
try:
parsed_build_time = datetime.strptime(build_time_match.group(1), "%Y-%m-%dT%H:%M:%S")
except ValueError as exc:
raise TailnetEnvironmentError(f"{source} API health has invalid build time") from exc
if parsed_build_time.year < 2000:
raise TailnetEnvironmentError(f"{source} API health has invalid build time")
liveness = payload.get("liveness")
readiness = payload.get("readiness")
if (
payload.get("status") != "healthy"
or not isinstance(liveness, Mapping)
or liveness.get("alive") is not True
or not isinstance(readiness, Mapping)
or readiness.get("ready") is not True
):
raise TailnetEnvironmentError(f"{source} API health is not live and ready")
return identity
def _wait_for_healthy_api(
url: str,
*,
timeout_seconds: float = 90.0,
) -> dict[str, object]:
"""Wait for HTTP and semantic API readiness after service startup."""
deadline = time.monotonic() + timeout_seconds
last_error: TailnetEnvironmentError | None = None
while time.monotonic() < deadline:
try:
probe = _url_probe(url, expect_json=True)
_api_build_identity(probe, source="local")
return probe
except TailnetEnvironmentError as exc:
last_error = exc
time.sleep(0.25)
if last_error is not None:
raise last_error
raise TailnetEnvironmentError(f"selected API did not become healthy at {url}")
def _git_revision(root: Path) -> str:
resolved_root = root.resolve()
top_level = Path(
_run(["git", "-C", str(resolved_root), "rev-parse", "--show-toplevel"])
.stdout.strip()
).resolve()
if top_level != resolved_root:
raise TailnetEnvironmentError("Tailnet selector source is not the canonical Git root")
revision = _run(["git", "-C", str(resolved_root), "rev-parse", "HEAD"]).stdout.strip()
if not _GIT_REVISION_PATTERN.fullmatch(revision):
raise TailnetEnvironmentError("Tailnet selector source revision is invalid")
dirty = _run([
"git", "-C", str(resolved_root), "status", "--porcelain=v1", "--untracked-files=all"
]).stdout.strip()
if dirty:
raise TailnetEnvironmentError("Tailnet selector source is not clean; uncommitted changes exist")
return revision
def _validate_canonical_environment_root(root: Path, environment: str) -> str:
normalized = str(environment).strip().lower()
if normalized not in SUPPORTED_ENVIRONMENTS:
raise TailnetEnvironmentError("Tailnet environment must be development or production")
branch = "test" if normalized == "development" else "main"
resolved = root.resolve()
revision = _git_revision(resolved)
# The managed Development sync owns a detached checkout of origin/test (the
# local test branch belongs to another worktree), so a detached HEAD is the
# deployed shape. Only an attached HEAD on a different branch is wrong; the
# exact origin/<branch> revision match below applies either way.
symbolic = subprocess.run(
["git", "-C", str(resolved), "symbolic-ref", "--quiet", "--short", "HEAD"],
check=False,
capture_output=True,
text=True,
timeout=60.0,
)
if symbolic.returncode not in (0, 1):
detail = symbolic.stderr.strip() or f"exit {symbolic.returncode}"
raise TailnetEnvironmentError(f"could not read canonical {normalized} HEAD: {detail}")
actual_branch = symbolic.stdout.strip() if symbolic.returncode == 0 else ""
if actual_branch and actual_branch != branch:
raise TailnetEnvironmentError(
f"canonical {normalized} source must be branch {branch} or detached at origin/{branch}, "
f"found {actual_branch}"
)
remote_revision = _run(
["git", "-C", str(resolved), "rev-parse", f"origin/{branch}"]
).stdout.strip()
if revision != remote_revision:
raise TailnetEnvironmentError(
f"canonical {normalized} source does not exactly match origin/{branch}"
)
return revision
def _canonical_environment_root(environment: str) -> Path:
normalized = str(environment).strip().lower()
if normalized not in SUPPORTED_ENVIRONMENTS:
raise TailnetEnvironmentError("Tailnet environment must be development or production")
# The installed lane owns source selection, never the caller's BMS_HOME.
configured = load_install_profile().get(f"{normalized}_project_root")
if isinstance(configured, str) and configured.strip():
return Path(configured).expanduser().resolve()
if normalized == "development":
return CANONICAL_DEVELOPMENT_ROOT.resolve()
if normalized == "production":
return CANONICAL_PRODUCTION_ROOT.resolve()
raise TailnetEnvironmentError("Tailnet environment must be development or production")
def _pid_report_for_pids(pids: list[int]) -> list[dict[str, object]]:
reports: list[dict[str, object]] = []
for pid in sorted(set(pids)):
proc = Path("/proc") / str(pid)
try:
cmdline = (proc / "cmdline").read_bytes().replace(b"\0", b" ").decode("utf-8", errors="replace").strip()
except OSError:
cmdline = ""
try:
cwd = os.readlink(proc / "cwd")
except OSError:
cwd = None
try:
cgroup = (proc / "cgroup").read_text(encoding="utf-8")
except OSError:
cgroup = ""
reports.append(
{
"pid": pid,
"cwd": cwd,
"cmdline": cmdline,
"argv": _process_argv(pid),
"executable": (
str(executable) if (executable := _process_executable(pid)) is not None else None
),
"cgroup": cgroup,
"build_revision": (
_pid_environment_value(pid, "VITE_BMS_BUILD_SHA")
or _pid_environment_value(pid, "BMS_BUILD_SHA")
),
}
)
return reports
def _pid_report(port: int) -> list[dict[str, object]]:
return _pid_report_for_pids(listener_pids(port))
def _pid_environment_value(pid: int, key: str) -> str | None:
try:
entries = (Path("/proc") / str(pid) / "environ").read_bytes().split(b"\0")
except OSError:
return None
prefix = key.encode("ascii") + b"="
for entry in entries:
if entry.startswith(prefix):
return entry[len(prefix):].decode("utf-8", errors="replace")
return None
def _process_cgroup(pid: int) -> str:
try:
return (Path("/proc") / str(pid) / "cgroup").read_text(encoding="utf-8")
except OSError:
return ""
def _process_argv(pid: int) -> list[str]:
try:
return [
item.decode("utf-8", errors="strict")
for item in (Path("/proc") / str(pid) / "cmdline").read_bytes().split(b"\0")
if item
]
except (OSError, UnicodeDecodeError):
return []
def _process_executable(pid: int) -> Path | None:
try:
return (Path("/proc") / str(pid) / "exe").resolve(strict=True)
except OSError:
return None
def _process_in_exact_container_cgroup(cgroup: object, container_id: str) -> bool:
if not re.fullmatch(r"[0-9a-f]{64}", container_id):
return False
expected = {
f"/docker/{container_id}",
f"/system.slice/docker-{container_id}.scope",
}
lines = [line for line in str(cgroup).splitlines() if line]
matches = [re.fullmatch(r"[0-9]+:[^:]*:(/.*)", line) for line in lines]
if not lines or any(match is None for match in matches):
return False
paths = [match.group(1) for match in matches if match is not None]
return any(path in expected for path in paths) and all(
path == "/" or path in expected for path in paths
)
def _process_in_exact_systemd_unit(cgroup: object, service: str) -> bool:
if not re.fullmatch(r"[A-Za-z0-9_.@-]+\.service", service):
return False
pattern = re.compile(
rf"^/user\.slice/user-(\d+)\.slice/user@\1\.service/app\.slice/{re.escape(service)}$"
)
lines = [line for line in str(cgroup).splitlines() if line]
matches = [re.fullmatch(r"[0-9]+:[^:]*:(/.*)", line) for line in lines]
if not lines or any(match is None for match in matches):
return False
paths = [match.group(1) for match in matches if match is not None]
return any(pattern.fullmatch(path) for path in paths) and all(
path == "/" or pattern.fullmatch(path) for path in paths
)
def _trusted_node_executables() -> set[Path]:
trusted: set[Path] = set()
for candidate in (Path("/usr/bin/node"), Path("/usr/bin/nodejs")):
try:
trusted.add(candidate.resolve(strict=True))
except OSError:
continue
return trusted
def _dev_frontend_matches_root(
spec: EnvironmentSpec,
root: Path,
*,
reports: list[dict[str, object]] | None = None,
) -> bool:
expected = str((root / "platform" / "frontend").resolve())
revision = _git_revision(root)
if _listener_bind_addresses(spec.frontend_port) != {"127.0.0.1"}:
return False
if reports is None:
reports = _exclusive_listener_reports(spec.frontend_port)
if not reports:
return False
for report in reports:
pid = report.get("pid")
raw_argv = report.get("argv")
argv = raw_argv if isinstance(raw_argv, list) and all(isinstance(item, str) for item in raw_argv) else []
raw_executable = report.get("executable")
executable = Path(raw_executable).resolve() if isinstance(raw_executable, str) else None
expected_vite = (Path(expected) / "node_modules" / "vite" / "bin" / "vite.js").resolve()
if (
report.get("cwd") != expected
or not isinstance(pid, int)
or _pid_environment_value(pid, "VITE_BMS_BUILD_SHA") != revision
or report.get("build_revision") != revision
or executable is None
or executable not in _trusted_node_executables()
or len(argv) != 6
or Path(argv[1]).resolve() != expected_vite
or argv[2:] != ["--host", "127.0.0.1", "--port", str(spec.frontend_port)]
or not _process_in_exact_systemd_unit(report.get("cgroup", ""), FRONTEND_SERVICE)
):
return False
return True
def _atomic_write(path: Path, content: str | bytes, *, mode: int = 0o600) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
temporary = Path(temporary_name)
try:
if isinstance(content, bytes):
with os.fdopen(descriptor, "wb") as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
else:
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
handle.write(content)
handle.flush()
os.fsync(handle.fileno())
os.chmod(temporary, mode)
metadata_fd = os.open(temporary, os.O_RDONLY)
try:
os.fsync(metadata_fd)
finally:
os.close(metadata_fd)
os.replace(temporary, path)
directory_fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
finally:
temporary.unlink(missing_ok=True)
def _install_operator_development_frontend(root: Path, mutation_ledger: set[str] | None = None) -> None:
units = render_user_units(project_root=root, runtime_mode=DEV_RUNTIME_MODE)
frontend = units[FRONTEND_SERVICE]
dev_api_target = f"http://127.0.0.1:{runtime_api_port(DEV_RUNTIME_MODE, project_root=root)}"
expected_line = f"Environment=BMS_DEV_API_PROXY_TARGET={dev_api_target}"
if expected_line not in frontend:
raise TailnetEnvironmentError("could not render the canonical development frontend proxy contract")
revision = _git_revision(root)
build_identity = git_build_identity(root)
build_time = build_identity["build_time"]
build_id = build_identity["build_id"]
home_line = "Environment=" + systemd_value(f"BMS_HOME={root}")
required_identity_lines = (
home_line,
f"Environment=VITE_BMS_BUILD_SHA={revision}",
f"Environment=VITE_BMS_BUILD_ID={build_id}",
f"Environment=VITE_BMS_BUILD_TIME={build_time}",
)
if any(line not in frontend for line in required_identity_lines):
raise TailnetEnvironmentError("development frontend unit has no exact canonical source identity")
if mutation_ledger is not None:
mutation_ledger.add("frontend_files")
_atomic_write(_host_user_systemd_dir() / FRONTEND_SERVICE, frontend)
_atomic_write(
_host_user_systemd_dir() / f"{FRONTEND_SERVICE}.d" / "99-tailnet-canonical-source.conf",
"[Service]\n"
f"Environment={systemd_value('BMS_HOME=' + str(root))}\n"
f"Environment=BMS_DEV_API_PROXY_TARGET={dev_api_target}\n"
# Build identity stays with the generated base unit across later syncs.
f"WorkingDirectory={systemd_value(root / 'platform/frontend')}\n"
"ExecStartPre=\n"
f"ExecStartPre=/usr/bin/sh -c 'test \"$BMS_DEV_API_PROXY_TARGET\" = \"{dev_api_target}\"'\n"
f"ExecStartPre=/usr/bin/env python3 {systemd_exec_arg(root / 'scripts/rotate_biomodstack_logs.py')}\n"
"ExecStart=\n"
f"ExecStart=/usr/bin/node {systemd_exec_arg(root / 'platform/frontend/node_modules/vite/bin/vite.js')} "
"--host 127.0.0.1 --port 18082\n",
)
daemon_reload(project_root=root)
def _adapter_matches_root(root: Path) -> bool:
expected = str((root / "platform" / "api").resolve())
revision = _git_revision(root)
reports = _exclusive_listener_reports(WORKFLOW_ADAPTER_PORT)
if not reports:
return False
for report in reports:
pid = report.get("pid")
if not (
report.get("cwd") == expected
and isinstance(pid, int)
and _pid_environment_value(pid, "BMS_TAILNET_CONTROL_SOURCE_REVISION") == revision
):
return False
return True
def _tailnet_owner_login() -> str:
result = _run(["tailscale", "status", "--json"])
try:
status = json.loads(result.stdout)
user_id = str(status["Self"]["UserID"])
login = str(status["User"][user_id]["LoginName"]).strip()
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
raise TailnetEnvironmentError("could not resolve the Tailnet owner identity") from exc
if not _TAILSCALE_LOGIN_PATTERN.fullmatch(login):
raise TailnetEnvironmentError("Tailnet owner identity is malformed")
return login
def _install_adapter_control_policy(
root: Path,
runtime_revision: str,
mutation_ledger: set[str] | None = None,
) -> str:
login = _tailnet_owner_login()
revision = _git_revision(root)
if not _GIT_REVISION_PATTERN.fullmatch(runtime_revision):
raise TailnetEnvironmentError("managed API runtime revision is malformed")
api_image_id = _managed_image_id("BMS_MANAGED_API_IMAGE_ID", MANAGED_API_IMAGE_ID)
web_image_id = _managed_image_id("BMS_MANAGED_WEB_IMAGE_ID", MANAGED_WEB_IMAGE_ID)
dropin = _host_user_systemd_dir() / f"{WORKFLOW_ADAPTER_SERVICE}.d" / "99-tailnet-canonical-source.conf"
if mutation_ledger is not None:
mutation_ledger.add("adapter_files")
_atomic_write(
dropin,
"[Service]\n"
f"Environment={systemd_value('BMS_HOME=' + str(root))}\n"
f"Environment=BMS_TAILNET_CONTROL_SOURCE_REVISION={revision}\n"
f"Environment=BMS_MANAGED_API_IMAGE_ID={api_image_id}\n"
f"Environment=BMS_MANAGED_WEB_IMAGE_ID={web_image_id}\n"
"Environment=BMS_WORKFLOW_ADAPTER_BIND_HOST=127.0.0.1\n"
"Environment=BMS_WORKFLOW_ADAPTER_LANE=development\n"
"Environment=BMS_TAILNET_CONTROL_TRUSTED_PROXY_HOSTS=127.0.0.1,::1\n"
f"Environment=BMS_TAILNET_CONTROL_ALLOWED_TAILSCALE_USERS={login}\n"
"ExecStartPre=\n"
f"ExecStartPre=/usr/bin/env python3 {systemd_exec_arg(root / 'scripts/rotate_biomodstack_logs.py')}\n"
"ExecStart=\n"
f"ExecStart={systemd_exec_arg(root / 'scripts/run_biomodstack_workflow_adapter.sh')}\n",
)
return login
def _listener_bind_addresses(port: int) -> set[str]:
result = _run(["ss", "-H", "-ltn", "sport", "=", f":{port}"])
addresses: set[str] = set()
for line in result.stdout.splitlines():
fields = line.split()
if len(fields) < 4:
continue
endpoint = fields[3]
if endpoint.startswith("[") and "]:" in endpoint:
addresses.add(endpoint[1:endpoint.rfind("]:")])
elif ":" in endpoint:
addresses.add(endpoint.rsplit(":", 1)[0])
return addresses
def _adapter_identity_policy_matches(
root: Path,
login: str,
*,
runtime_revision: str,
reports: list[dict[str, object]] | None = None,
) -> bool:
addresses = _listener_bind_addresses(WORKFLOW_ADAPTER_PORT)