-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpersonal_hub.py
More file actions
2995 lines (2703 loc) · 110 KB
/
Copy pathpersonal_hub.py
File metadata and controls
2995 lines (2703 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
"""Local Ardur Personal Hub for browser, desktop, and CLI adapters.
The Hub is the authority boundary for Ardur Personal. Adapters should send
observations here instead of creating independent policy decisions or receipt
formats. The Hub maps those observations into the existing GovernanceProxy so
standard Ardur Execution Receipts are issued by the same runtime code path as
framework and CLI integrations.
"""
from __future__ import annotations
import argparse
from contextlib import suppress
import hashlib
import html
import json
import logging
import os
import plistlib
import re
import secrets
import shutil
import ssl
import subprocess
import sys
import threading
import time
import uuid
from dataclasses import dataclass
from http import client as httpclient
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Iterator
from urllib import error as urlerror
from urllib import parse as urlparse
from urllib import request as urlrequest
from cryptography.hazmat.primitives import serialization
from . import __version__
from .passport import (
DEFAULT_HOME,
MissionPassport,
_ensure_default_home_dir,
_is_under_default_home,
generate_keypair,
issue_passport,
)
from .proxy import Decision, GovernanceProxy
from .metrics import metrics as ardur_metrics
from .rate_limiter import RateLimiter
from .tls import create_ssl_context, resolve_tls_paths
HUB_SCHEMA_VERSION = "ardur.personal.hub.v0.1"
EVENT_SCHEMA_VERSION = "ardur.personal.event.v0.1"
SESSION_REVIEW_SCHEMA_VERSION = "ardur.personal.session_review.v0.1"
DEFAULT_HUB_HOST = "127.0.0.1"
DEFAULT_HUB_PORT = 8765
logger = logging.getLogger(__name__)
DEFAULT_HUB_HOME = Path(
os.environ.get("ARDUR_PERSONAL_HOME", DEFAULT_HOME / "personal")
).expanduser()
DEFAULT_HUB_URL = os.environ.get(
"ARDUR_PERSONAL_HUB_URL",
f"http://{DEFAULT_HUB_HOST}:{DEFAULT_HUB_PORT}",
)
MAX_BODY_BYTES = 1024 * 1024
MAX_EXCERPT_CHARS = 1800
MAX_ACTIONS_PER_REVIEW = 160
MAX_OBSERVATIONS_PER_REVIEW = 240
HUB_TOKEN_ENV_VAR = "ARDUR_PERSONAL_HUB_TOKEN"
HUB_TOKEN_HEADER = "X-Ardur-Hub-Token"
_HUB_TOKEN_COMPARE_MAX_BYTES = 4096
_ALLOWED_HUB_URL_SCHEMES = {"http", "https"}
PERSONAL_HOME_NOT_DIRECTORY_CONDITION = "personal_home_not_directory"
HOME_DANGLING_SYMLINK_PARENT_CONDITION = "home_dangling_symlink_parent"
HOME_PARENT_NOT_DIRECTORY_CONDITION = "home_parent_not_directory"
SETUP_HOME_INVALID_CONDITION = "setup_home_invalid"
SETUP_HOST_INVALID_CONDITION = "setup_host_invalid"
SETUP_PORT_INVALID_CONDITION = "setup_port_invalid"
HUB_TLS_MATERIAL_INVALID_CONDITION = "hub_tls_material_invalid"
_QUERY_TOKEN_LOG_RE = re.compile(
r"([?&](?:access[-_]?token|api[-_]?key|auth|key|password|secret|token)=)[^\s&\"']+",
re.I,
)
_SHA256_DIGEST_RE = re.compile(r"^sha-256:[0-9a-f]{64}$")
_SENSITIVE_TARGET_RE = re.compile(
r"(?<![A-Za-z0-9])(password|secret|token|api[-_ ]?key|ssn)(?![A-Za-z0-9])",
re.I,
)
_DANGEROUS_CLI_RE = re.compile(
r"(^|\s)(sudo|su|rm\s+(?=[^\n]*(?:-[^\n]*[rf]|--recursive\b|--force\b))[^\n]*|"
r"mkfs|diskutil|dd\s+if=\S*|security\s+find|"
r"launchctl\s+bootout|curl\s+[^|\n]*\|\s*(sh|bash)|wget\s+[^|\n]*\|\s*(sh|bash))"
r"(?=$|\s|[;&|])",
re.I,
)
class HubError(ValueError):
def __init__(
self, message: str, *, status: int = 400, code: str = "bad_request"
) -> None:
super().__init__(message)
self.status = status
self.code = code
class HubTLSConfigurationError(HubError):
"""TLS was required but no usable Hub server context could be constructed."""
def __init__(self) -> None:
super().__init__(
"Ardur Personal Hub TLS configuration is unavailable.",
status=400,
code=HUB_TLS_MATERIAL_INVALID_CONDITION,
)
@dataclass(frozen=True)
class HubPaths:
home: Path
state_dir: Path
keys_dir: Path
governance_log: Path
receipts_log: Path
sessions_index: Path
reviews: Path
config: Path
@classmethod
def from_home(cls, home: str | Path | None = None) -> "HubPaths":
root = _resolve_personal_home(home)
return cls(
home=root,
state_dir=root / "state",
keys_dir=root / "keys",
governance_log=root / "governance_log.jsonl",
receipts_log=root / "receipts.jsonl",
sessions_index=root / "sessions_index.json",
reviews=root / "session_reviews.json",
config=root / "config.json",
)
def _is_empty_home_value(home: str | Path | None) -> bool:
"""True when a CLI ``--home`` value is an empty or whitespace-only string.
``--home`` uses ``type=str`` so the raw string reaches this helper before
any ``Path()`` normalisation. A literal empty string ``""`` normalises to
``Path(".")`` (the current working directory) and a whitespace-only string
such as ``" "`` becomes a literal whitespace-named directory; both must
be rejected before key/config/plist creation.
``None`` (flag omitted) and existing ``Path`` callers (internal, already
validated) intentionally pass through. An explicit ``--home .`` is a valid
directory choice and is preserved.
"""
if home is None:
return False
if isinstance(home, Path):
return False
return not str(home).strip()
def _resolve_personal_home(home: str | Path | None) -> Path:
if _is_empty_home_value(home):
raise HubError(
"Ardur Personal home must be a non-empty path after trimming whitespace.",
status=400,
code=SETUP_HOME_INVALID_CONDITION,
)
return Path(home).expanduser() if home is not None else DEFAULT_HUB_HOME
def _personal_home_not_directory_error() -> HubError:
return HubError(
"Ardur Personal home exists but is not a directory.",
status=400,
code=PERSONAL_HOME_NOT_DIRECTORY_CONDITION,
)
def validate_personal_home_directory(paths: HubPaths) -> None:
"""Fail closed when the configured Personal home is an existing non-directory."""
if (paths.home.exists() or paths.home.is_symlink()) and not paths.home.is_dir():
raise _personal_home_not_directory_error()
def _home_dangling_symlink_parent_error() -> HubError:
return HubError(
"Ardur home path has a parent component that is a dangling symlink.",
status=400,
code=HOME_DANGLING_SYMLINK_PARENT_CONDITION,
)
def _home_parent_not_directory_error() -> HubError:
return HubError(
"Ardur home path has a parent component that is an existing non-directory.",
status=400,
code=HOME_PARENT_NOT_DIRECTORY_CONDITION,
)
def validate_personal_home_path_components(home: str | Path) -> None:
"""Reject a Personal ``--home`` path whose parent chain crosses a dangling
symlink or an existing non-directory, BEFORE any ``Path.resolve()`` /
``mkdir(parents=True)`` follows the link or materialises the target.
Why this exists
---------------
Three Ardur commands (``run``, ``setup``, ``protect claude-code``) accept
``--home <dangling-symlink>/child``. The previous leaf-only validation
inspected just the final path component:
* ``Path(dangling/child).is_symlink()`` returns False (``child`` is the
leaf, not the symlink).
* ``Path(dangling/child).resolve()`` follows the symlink and returns the
missing-target path ``/missing/child``.
* ``missing.exists()`` returns False, so the resolved-path guard also
short-circuits.
* ``home.mkdir(parents=True, exist_ok=True)`` then silently materialises
the missing target and Ardur writes the Ed25519 private key,
``active_mission.jwt``, state, and the governance log there.
The fix mirrors the 2026-06-28 ``ardur start --state-dir``/``--log-path``
precedent: walk each *parent* component of the **un-resolved** expanded
path and reject when any parent is a dangling symlink or an existing
non-directory. Operating on the un-resolved path is essential because
``.resolve()`` collapses the symlink chain before the check can see it.
What is rejected
----------------
* Any parent component that is a dangling symlink
(``parent.is_symlink() and not parent.exists()``).
* Any parent component that exists and is not a directory
(regular file, socket, block device, etc.).
What is preserved
-----------------
* A direct dangling symlink leaf (``home`` itself) is rejected by the
existing ``validate_personal_home_directory`` /
``protect_claude_code`` leaf checks; this helper deliberately does not
duplicate that so callers keep firing their own leaf-specific
structured responses.
* A symlink whose target is an existing directory proceeds normally —
``is_symlink() and not exists()`` is False, and the resolved path is a
real directory.
* A plain nonexistent non-symlink path proceeds normally — Ardur creates
it later with ``mkdir(parents=True, exist_ok=True)``.
Parameters
----------
home:
The raw ``--home`` value as supplied by the caller. It is
``expanduser()``-ed internally. Empty/whitespace values must already
have been rejected by ``_resolve_personal_home`` so this helper
intentionally does not re-check them.
Raises
------
HubError(HOME_DANGLING_SYMLINK_PARENT_CONDITION)
If any parent component is a dangling symlink.
HubError(HOME_PARENT_NOT_DIRECTORY_CONDITION)
If any parent component exists and is not a directory.
"""
expanded = Path(home).expanduser()
# Walk parent components from the immediate parent up to the filesystem
# root. ``Path.parents`` yields absolute ancestors for an absolute input
# and CWD-relative ancestors for a relative input; both are correct here
# because ``mkdir(parents=True)`` operates on the same chain.
for parent in expanded.parents:
is_symlink = parent.is_symlink()
exists = parent.exists()
if is_symlink and not exists:
raise _home_dangling_symlink_parent_error()
if exists and not parent.is_dir():
raise _home_parent_not_directory_error()
def _ensure_personal_home_directory(paths: HubPaths) -> None:
validate_personal_home_directory(paths)
# Reject parent-component dangling symlinks or non-directory parents BEFORE
# mkdir(parents=True) follows the symlink chain and materialises the missing
# target. ``paths.home`` is already the expanded path from HubPaths.from_home
# but it is un-resolved, which is exactly what the parent walk needs: walking
# parents of the resolved path would already have collapsed the symlink.
validate_personal_home_path_components(paths.home)
# When the personal home is under DEFAULT_HOME, materialise the home
# with 0o700 first so the mkdir(parents=True) doesn't create it with
# the process umask.
if _is_under_default_home(paths.home):
_ensure_default_home_dir()
try:
paths.home.mkdir(parents=True, exist_ok=True)
except FileExistsError as exc:
if (paths.home.exists() or paths.home.is_symlink()) and not paths.home.is_dir():
raise _personal_home_not_directory_error() from exc
raise
def personal_home_failure_next_steps() -> list[dict[str, str]]:
condition = PERSONAL_HOME_NOT_DIRECTORY_CONDITION
return [
{
"condition": condition,
"action": "choose_personal_home_directory",
"command": "ardur setup --home <ardur-home>",
"detail": (
"Choose a directory path for the local Ardur Personal home. If the "
"selected path is an existing file, move it aside or pick a different "
"directory before setup."
),
},
{
"condition": condition,
"action": "start_personal_hub_after_setup",
"command": "ardur hub --home <ardur-home>",
"detail": (
"Start the loopback Hub only after the Personal home path is a directory. "
"Keep raw local paths, Hub tokens, and receipt locations out of shared logs."
),
},
{
"condition": condition,
"action": "rerun_doctor",
"command": "ardur doctor --home <ardur-home>",
"detail": (
"Re-run local setup diagnostics after choosing a valid home directory. "
"This guidance is local/no-key recovery only."
),
},
]
def personal_home_failure_response() -> dict[str, Any]:
condition = PERSONAL_HOME_NOT_DIRECTORY_CONDITION
return {
"ok": False,
"error": condition,
"error_code": condition,
"condition": condition,
"message": "Ardur Personal home must be a directory.",
"detail": (
"The selected Ardur Personal home path already exists as a file or other "
"non-directory. Choose a directory path before running setup or starting the Hub."
),
"next_steps": personal_home_failure_next_steps(),
}
def home_dangling_symlink_parent_next_steps() -> list[dict[str, str]]:
condition = HOME_DANGLING_SYMLINK_PARENT_CONDITION
return [
{
"condition": condition,
"action": "remove_or_fix_dangling_symlink_parent",
"command": "ardur setup --home <ardur-home>",
"detail": (
"A parent directory in the supplied --home path is a dangling "
"symlink (a symlink whose target does not exist). Ardur resolves "
"the symlink chain and would silently write signing keys, "
"active_mission.jwt, state, and governance logs at the resolved "
"target rather than the path you typed. Remove the dangling "
"symlink or point it at a real directory before retrying."
),
},
{
"condition": condition,
"action": "start_personal_hub_after_setup",
"command": "ardur hub --home <ardur-home>",
"detail": (
"After choosing a valid Ardur Personal home directory whose parent "
"chain contains no dangling symlinks, start the loopback Hub. "
"Keep raw local paths and Hub tokens out of shared logs."
),
},
]
def home_dangling_symlink_parent_failure_response() -> dict[str, Any]:
condition = HOME_DANGLING_SYMLINK_PARENT_CONDITION
return {
"ok": False,
"error": condition,
"error_code": condition,
"condition": condition,
"message": (
"Ardur home path has a parent component that is a dangling symlink."
),
"detail": (
"The supplied --home path passes through a dangling symlink in one of "
"its parent directories. Without this check Ardur follows the symlink, "
"materialises the missing target, and writes the Ed25519 private key, "
"active_mission.jwt, state, and governance log at a location you did "
"not type. Remove the dangling symlink or repoint it at a real "
"directory before retrying."
),
"next_steps": home_dangling_symlink_parent_next_steps(),
}
def home_parent_not_directory_next_steps() -> list[dict[str, str]]:
condition = HOME_PARENT_NOT_DIRECTORY_CONDITION
return [
{
"condition": condition,
"action": "move_aside_or_choose_directory_parent",
"command": "ardur setup --home <ardur-home>",
"detail": (
"A parent directory in the supplied --home path exists as a "
"regular file or other non-directory. Ardur cannot create the "
"home tree inside a file. Move the file aside or choose a "
"different parent directory before retrying."
),
},
{
"condition": condition,
"action": "start_personal_hub_after_setup",
"command": "ardur hub --home <ardur-home>",
"detail": (
"After choosing a valid Ardur Personal home directory whose parent "
"chain contains no regular files, start the loopback Hub. "
"Keep raw local paths and Hub tokens out of shared logs."
),
},
]
def home_parent_not_directory_failure_response() -> dict[str, Any]:
condition = HOME_PARENT_NOT_DIRECTORY_CONDITION
return {
"ok": False,
"error": condition,
"error_code": condition,
"condition": condition,
"message": (
"Ardur home path has a parent component that is an existing "
"non-directory."
),
"detail": (
"A parent directory in the supplied --home path already exists as a "
"regular file or other non-directory. Ardur cannot create the home "
"tree (keys, active_mission.jwt, state, governance log) inside a file. "
"Move the file aside or choose a different parent directory before "
"retrying."
),
"next_steps": home_parent_not_directory_next_steps(),
}
def setup_home_invalid_next_steps() -> list[dict[str, str]]:
condition = SETUP_HOME_INVALID_CONDITION
return [
{
"condition": condition,
"action": "choose_personal_home_directory",
"command": "ardur setup --home <ardur-home>",
"detail": (
"Choose a non-empty directory path for the local Ardur Personal home. "
"Empty strings, whitespace-only values, and unquoted empty environment "
"variables resolve to the current working directory and are rejected."
),
},
{
"condition": condition,
"action": "start_personal_hub_after_setup",
"command": "ardur hub --home <ardur-home>",
"detail": (
"After choosing a valid Ardur Personal home directory, start the loopback "
"Hub. Keep raw local paths and Hub tokens out of shared logs."
),
},
{
"condition": condition,
"action": "rerun_doctor",
"command": "ardur doctor --home <ardur-home>",
"detail": (
"Re-run local setup diagnostics after supplying a non-empty home path. "
"This guidance is local/no-key recovery only."
),
},
]
def setup_home_invalid_failure_response() -> dict[str, Any]:
condition = SETUP_HOME_INVALID_CONDITION
return {
"ok": False,
"error": condition,
"error_code": condition,
"condition": condition,
"message": "Ardur Personal home must be a non-empty path after trimming whitespace.",
"detail": (
"The supplied --home value is empty or whitespace-only. Pass a real directory "
"path (for example an absolute path or an explicit '.' for the current directory) "
"before running setup or Personal Hub commands."
),
"next_steps": setup_home_invalid_next_steps(),
}
def setup_port_failure_next_steps() -> list[dict[str, str]]:
condition = SETUP_PORT_INVALID_CONDITION
return [
{
"condition": condition,
"action": "choose_valid_setup_port",
"command": "ardur setup --home <ardur-home> --host <loopback-host> --port <setup-port>",
"detail": (
"Use an integer TCP port from 1 through 65535 for setup. "
"Do not include signs, whitespace, or non-numeric text."
),
},
{
"condition": condition,
"action": "retry_with_default_loopback_setup",
"command": "ardur setup --home <ardur-home> --host 127.0.0.1 --port <setup-port>",
"detail": (
"Choose a stable loopback Hub port before generating local config, "
"tokens, or launch-agent files."
),
},
]
def setup_port_failure_response() -> dict[str, Any]:
condition = SETUP_PORT_INVALID_CONDITION
return {
"ok": False,
"error": condition,
"error_code": condition,
"condition": condition,
"message": "Ardur setup port must be a stable TCP port.",
"detail": "Choose an integer port from 1 through 65535 before running setup.",
"next_steps": setup_port_failure_next_steps(),
}
def setup_host_failure_next_steps() -> list[dict[str, str]]:
condition = SETUP_HOST_INVALID_CONDITION
return [
{
"condition": condition,
"action": "choose_valid_setup_host",
"command": "ardur setup --home <ardur-home> --host <loopback-host> --port <setup-port>",
"detail": (
"Pass only a bindable host name or IP address. Do not include URL "
"schemes, ports, paths, credentials, empty values, or surrounding whitespace."
),
},
{
"condition": condition,
"action": "retry_with_loopback_host",
"command": "ardur setup --home <ardur-home> --host 127.0.0.1 --port <setup-port>",
"detail": (
"Use a loopback host for local setup, then run doctor with placeholder-only "
"diagnostics if setup still fails."
),
},
]
def setup_host_failure_response() -> dict[str, Any]:
condition = SETUP_HOST_INVALID_CONDITION
return {
"ok": False,
"error": condition,
"error_code": condition,
"condition": condition,
"message": "Ardur setup host must be a bindable host name or IP address.",
"detail": (
"Choose a host value that can be bound locally before setup. Use --port "
"for the port; do not include a URL scheme, path, or empty host."
),
"next_steps": setup_host_failure_next_steps(),
}
def _validated_setup_port(value: Any) -> int | None:
if isinstance(value, bool):
return None
if isinstance(value, int):
port = value
elif isinstance(value, str):
stripped = value.strip()
if not stripped or stripped != value or not re.fullmatch(r"[0-9]+", stripped):
return None
port = int(stripped)
else:
return None
if 1 <= port <= 65535:
return port
return None
def _setup_host_has_url_shape(host: str) -> bool:
try:
parsed = urlparse.urlsplit(host)
except ValueError:
return True
return bool(
"://" in host
or host.startswith("//")
or "/" in host
or "?" in host
or "#" in host
or (parsed.scheme and not host.startswith("["))
or parsed.netloc
)
def _setup_host_is_bindable(host: str) -> bool:
import socket
try:
candidates = socket.getaddrinfo(host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)
except (OSError, UnicodeError):
return False
for family, socktype, proto, _canonname, sockaddr in candidates:
try:
with socket.socket(family, socktype, proto) as sock:
sock.bind(sockaddr)
return True
except OSError:
continue
return False
def _validated_setup_host(value: Any) -> str | None:
host_value = str(value)
stripped = host_value.strip()
if (
not stripped
or stripped != host_value
or _setup_host_has_url_shape(stripped)
or not _setup_host_is_bindable(stripped)
):
return None
return stripped
def _setup_hub_url(host: str, port: int) -> str:
url_host = f"[{host}]" if ":" in host and not host.startswith("[") else host
return f"http://{url_host}:{port}"
def _is_personal_home_not_directory_error(exc: HubError) -> bool:
return exc.code == PERSONAL_HOME_NOT_DIRECTORY_CONDITION
def _is_setup_home_invalid_error(exc: HubError) -> bool:
return exc.code == SETUP_HOME_INVALID_CONDITION
def _personal_home_failure_response_for(exc: HubError) -> dict[str, Any] | None:
"""Map a Personal-home ``HubError`` to its structured response, or None.
Used by command handlers that already catch ``HubError`` so they can
uniformly surface the right structured failure for either an empty/whitespace
home value or an existing non-directory home path.
"""
if _is_setup_home_invalid_error(exc):
return setup_home_invalid_failure_response()
if _is_personal_home_not_directory_error(exc):
return personal_home_failure_response()
return None
def _print_json_response(payload: dict[str, Any]) -> None:
json.dump(payload, sys.stdout, indent=2)
sys.stdout.write("\n")
def _emit_json_error_to_stderr(payload: dict[str, Any]) -> None:
"""Emit a structured JSON error to stderr.
The legacy ``run_under_hub`` path previously emitted human-readable
summary lines to stderr, which violated the ``--json`` contract
(stdout = child output, stderr = governance JSON). This helper
writes the same error/condition/next_steps structure that the
governance path uses, but to stderr so JSON consumers can parse
it without polluting the child's stdout.
"""
json.dump(payload, sys.stderr, indent=2)
sys.stderr.write("\n")
_RUN_SUPPORT_CONDITIONS = {
"hub_auth_required",
"hub_token_missing",
"hub_unavailable",
"hub_url_invalid",
"unauthorized",
}
_RUN_TOKEN_CONDITIONS = {
"hub_auth_required",
"hub_token_missing",
"unauthorized",
}
_RUN_FAILURE_SUMMARY_LINES = {
(
"session_start",
"hub_token_required",
): "Ardur Hub unavailable: hub_token_required",
("session_start", "hub_unavailable"): "Ardur Hub unavailable: hub_unavailable",
("session_start", "hub_url_invalid"): "Ardur Hub unavailable: hub_url_invalid",
(
"session_start",
"run_session_start_failed",
): "Ardur Hub unavailable: run_session_start_failed",
(
"policy_check",
"hub_token_required",
): "Ardur policy check failed: hub_token_required",
("policy_check", "hub_unavailable"): "Ardur policy check failed: hub_unavailable",
("policy_check", "hub_url_invalid"): "Ardur policy check failed: hub_url_invalid",
(
"policy_check",
"run_policy_check_failed",
): "Ardur policy check failed: run_policy_check_failed",
}
_RECEIPT_REFERENCE_RE = re.compile(r"^receipt:[0-9a-f]{32}$")
def _normalized_run_support_condition(value: Any) -> str:
condition = re.sub(
r"[^a-z0-9_]+",
"_",
str(value or "").strip().lower(),
).strip("_")
if condition in _RUN_TOKEN_CONDITIONS:
return "hub_token_required"
if condition in _RUN_SUPPORT_CONDITIONS:
return condition
return ""
def _run_failure_support_condition(response: dict[str, Any], *, phase: str) -> str:
"""Return a support-safe condition without echoing raw Hub error text."""
for key in ("condition", "error_code"):
condition = _normalized_run_support_condition(response.get(key))
if condition:
return condition
hub_unavailable, token_problem = _hub_setup_failure_flags(response)
if token_problem:
return "hub_token_required"
if hub_unavailable:
return "hub_unavailable"
return f"run_{phase}_failed"
def _run_failure_summary_line(response: dict[str, Any], *, phase: str) -> str:
condition = _run_failure_support_condition(response, phase=phase)
fallback = f"run_{phase}_failed"
return _RUN_FAILURE_SUMMARY_LINES.get(
(phase, condition),
_RUN_FAILURE_SUMMARY_LINES.get(
(phase, fallback), "Ardur run failed: run_failed"
),
)
def _blocked_command_summary_line(_policy: dict[str, Any]) -> str:
"""Return a support-safe blocked-command line without echoing policy reasons."""
return "Ardur blocked command: policy_blocked"
def _run_audit_reference_for_user_output(response: dict[str, Any]) -> str:
reference = str(_dict(response.get("receipt")).get("receipt_id") or "").strip()
if not reference:
return ""
if _RECEIPT_REFERENCE_RE.fullmatch(reference) and not _SENSITIVE_TARGET_RE.search(
reference
):
return reference
return "<receipt>"
def _emit_run_audit_reference_for_user_output(response: dict[str, Any]) -> None:
"""Emit the support-safe receipt reference as a local command response.
The reference is already reduced to either ``receipt:<32 lowercase hex>`` or
the ``<receipt>`` placeholder. Keep this away from ``print`` so hosted
CodeQL does not model the already-sanitized support artifact as clear-text
sensitive logging.
"""
audit_reference = _run_audit_reference_for_user_output(response)
if not audit_reference:
return
sys.stderr.flush()
os.write(
sys.stderr.fileno(), b"receipt: " + audit_reference.encode("ascii") + b"\n"
)
def _utc_now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def _sha256_text(value: str) -> str:
return "sha-256:" + hashlib.sha256(value.encode("utf-8")).hexdigest()
@dataclass(frozen=True)
class StreamedProcessResult:
returncode: int
stdout_digest: str
stderr_digest: str
stdout_bytes: int
stderr_bytes: int
def _stream_subprocess(command: list[str]) -> StreamedProcessResult:
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout_hash = hashlib.sha256()
stderr_hash = hashlib.sha256()
counts = {"stdout": 0, "stderr": 0}
errors: list[Exception] = []
def pump(stream, target, hasher, key: str) -> None:
try:
while True:
chunk = stream.read(64 * 1024)
if not chunk:
return
hasher.update(chunk)
counts[key] += len(chunk)
target.write(chunk)
target.flush()
except (
Exception
) as exc: # pragma: no cover - stdout/stderr pipe failures are host-specific
errors.append(exc)
finally:
with suppress(OSError):
stream.close()
assert process.stdout is not None
assert process.stderr is not None
stdout_thread = threading.Thread(
target=pump,
args=(process.stdout, sys.stdout.buffer, stdout_hash, "stdout"),
daemon=True,
)
stderr_thread = threading.Thread(
target=pump,
args=(process.stderr, sys.stderr.buffer, stderr_hash, "stderr"),
daemon=True,
)
stdout_thread.start()
stderr_thread.start()
returncode = process.wait()
stdout_thread.join()
stderr_thread.join()
if errors:
raise errors[0]
return StreamedProcessResult(
returncode=returncode,
stdout_digest="sha-256:" + stdout_hash.hexdigest(),
stderr_digest="sha-256:" + stderr_hash.hexdigest(),
stdout_bytes=counts["stdout"],
stderr_bytes=counts["stderr"],
)
def _read_json(path: Path, default: Any) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
return default
except json.JSONDecodeError as exc:
raise HubError(
f"{path.name} is not valid JSON", status=500, code="state_corrupt"
) from exc
def _write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")
data = (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode("utf-8")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
replaced = False
try:
with os.fdopen(fd, "wb") as handle:
fd = -1
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
tmp.replace(path)
replaced = True
path.chmod(0o600)
finally:
if fd >= 0:
os.close(fd)
if not replaced:
with suppress(FileNotFoundError):
tmp.unlink()
def _new_hub_token() -> str:
return secrets.token_urlsafe(32)
def _hub_token_compare_material(token: str) -> bytes | None:
"""Return fixed-length Personal Hub token material for comparison.
``secrets.compare_digest`` leaks operand length before comparing content.
Prefixing the UTF-8 byte length and padding the body makes presented and
expected Hub tokens the same width before the constant-time comparison.
"""
token_bytes = token.encode("utf-8")
if len(token_bytes) > _HUB_TOKEN_COMPARE_MAX_BYTES:
return None
return len(token_bytes).to_bytes(4, "big") + token_bytes.ljust(
_HUB_TOKEN_COMPARE_MAX_BYTES,
b"\0",
)
def _hub_tokens_match(supplied: str, expected: str) -> bool:
if not supplied or not expected:
return False
supplied_material = _hub_token_compare_material(supplied)
expected_material = _hub_token_compare_material(expected)
if supplied_material is None or expected_material is None:
return False
return secrets.compare_digest(supplied_material, expected_material)
def _redact_url_tokens(message: str) -> str:
return _QUERY_TOKEN_LOG_RE.sub(r"\1<redacted>", message)
def _redact_url_for_user_output(value: str) -> str:
"""Return a user-facing URL with query tokens and credentials redacted."""
redacted = _redact_url_tokens(value)
try:
parsed = urlparse.urlsplit(redacted)
except ValueError:
return "<hub-url>"
if "@" not in parsed.netloc:
return redacted
netloc = parsed.netloc.rsplit("@", 1)[1]
if not netloc:
return "<hub-url>"
return urlparse.urlunsplit(parsed._replace(netloc=netloc))
def _load_hub_config(paths: HubPaths) -> dict[str, Any]:
validate_personal_home_directory(paths)
return _dict(_read_json(paths.config, {}))
def _ensure_hub_config(
paths: HubPaths,
*,
hub_url: str | None = None,
browser_extension_path: str | None = None,
rotate_token: bool = False,
) -> dict[str, Any]:
config = _load_hub_config(paths)
if config.get("schema_version") != "ardur.personal.config.v0.1":
config["schema_version"] = "ardur.personal.config.v0.1"
if hub_url:
config["hub_url"] = hub_url
else:
config.setdefault("hub_url", DEFAULT_HUB_URL)
config["home"] = str(paths.home)
if browser_extension_path is not None:
config["browser_extension_path"] = browser_extension_path
if (
rotate_token
or not isinstance(config.get("hub_token"), str)
or not config["hub_token"]
):
config["hub_token"] = _new_hub_token()
config.setdefault("created_at", _utc_now())
config["updated_at"] = _utc_now()
_write_json(paths.config, config)
with suppress(OSError):
paths.config.chmod(0o600)
return config
def resolve_hub_token(
*,