arrayview 0.58.2__py3-none-any.whl → 0.58.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
arrayview/_io.py CHANGED
@@ -2242,18 +2242,24 @@ def _load_file_series(path, *, load="lazy", stack="auto"):
2242
2242
  # spellings produce the same session instead of one of them failing.
2243
2243
  if any(len(files) != 1 for files in patients.values()):
2244
2244
  flat = sorted(fpath for files in patients.values() for fpath in files)
2245
- return _series_from_file_matrix(
2245
+ series, meta = _series_from_file_matrix(
2246
2246
  [[fpath] for fpath in flat], load=load, stack=stack
2247
2247
  )
2248
+ series.case_names = _distinguishing_path_parts(flat)
2249
+ return series, meta
2248
2250
 
2249
2251
  # NIfTI-only → preserve canonical reorientation + lazy dataobj slicing
2252
+ # Label each case like --match does, so the viewer shows names, not 1..N.
2253
+ first_files = [patients[pdir][0] for pdir in sorted(patients)]
2250
2254
  if all_nifti:
2251
- return _load_nifti_series(path, load=load, stack=stack)
2252
-
2253
- # ── build file matrix ──────────────────────────────────────────
2254
- file_matrix = [[patients[pdir][0]] for pdir in sorted(patients)]
2255
-
2256
- return _series_from_file_matrix(file_matrix, load=load, stack=stack)
2255
+ series, meta = _load_nifti_series(path, load=load, stack=stack)
2256
+ else:
2257
+ # ── build file matrix ──────────────────────────────────────────
2258
+ series, meta = _series_from_file_matrix(
2259
+ [[f] for f in first_files], load=load, stack=stack
2260
+ )
2261
+ series.case_names = _distinguishing_path_parts(first_files)
2262
+ return series, meta
2257
2263
 
2258
2264
 
2259
2265
  def _load_nifti_series(path, *, load="lazy", stack="auto"):
arrayview/_launch_plan.py CHANGED
@@ -154,6 +154,9 @@ class LaunchEnvironmentSnapshot:
154
154
  ssh_client: bool
155
155
  hostname: str
156
156
  cli_default_server: ServerSnapshot | None = None
157
+ # This user's own reusable server on another port, found only when the
158
+ # requested port is held by something we cannot reuse (shared machines).
159
+ own_server: ServerSnapshot | None = None
157
160
 
158
161
  def to_dict(self) -> dict:
159
162
  return asdict(self)
@@ -379,28 +382,39 @@ def plan_launch(
379
382
  and intent.port == 8123
380
383
  and environment is Environment.VSCODE_REMOTE
381
384
  and facts.cli_default_server is not None
382
- and _server_reusable(facts.cli_default_server)
385
+ and _server_reusable(facts.cli_default_server, facts.hostname)
383
386
  ):
384
387
  port = facts.cli_default_server.port
385
388
  server = facts.cli_default_server
386
389
  reasons.append("reuse_remote_cli_default_server")
387
390
 
388
- if server.arrayview_server_alive and not _server_reusable(server):
391
+ if (
392
+ intent.invocation in {Invocation.CLI, Invocation.VSCODE_EXPLORER}
393
+ and server.port_busy
394
+ and not _server_reusable(server, facts.hostname)
395
+ and facts.own_server is not None
396
+ and _server_reusable(facts.own_server, facts.hostname)
397
+ ):
398
+ # The requested port belongs to someone else; our own server already
399
+ # runs elsewhere. Reuse it rather than starting one more per launch.
400
+ port = facts.own_server.port
401
+ server = facts.own_server
402
+ reasons.append("reuse_own_server_on_other_port")
403
+
404
+ if server.arrayview_server_alive and not _server_reusable(server, facts.hostname):
389
405
  port += 1
390
406
  reasons.append("incompatible_server_new_port")
391
407
  server = ServerSnapshot(port, False, False)
392
408
 
409
+ # A remote VS Code window forwards whichever port the server ends up on,
410
+ # so a port held by something else (e.g. another user's stale forward on a
411
+ # shared host) is skipped exactly as it is locally.
393
412
  busy_foreign = server.port_busy and not server.arrayview_server_alive
394
- if busy_foreign and environment is Environment.VSCODE_REMOTE:
395
- return _failed_plan(
396
- intent, facts, LaunchFailure.REMOTE_PORT_CONFLICT,
397
- "remote_forwarding_requires_requested_port", effective_port=port,
398
- )
399
413
  if busy_foreign:
400
414
  port += 1
401
415
  reasons.append("scan_from_next_port")
402
416
 
403
- if _server_reusable(server):
417
+ if _server_reusable(server, facts.hostname):
404
418
  owner = ServerOwner.EXISTING
405
419
  registration = Registration.HTTP_LOAD
406
420
  reasons.append("reuse_compatible_server")
@@ -535,6 +549,7 @@ def snapshot_launch_environment(
535
549
  """Capture launch-relevant facts without importing the server stack."""
536
550
  inv = _coerce_invocation(invocation)
537
551
  env_vars = _snapshot_env_vars()
552
+ primary = _server_snapshot(port)
538
553
  in_jupyter = _platform_bool("_in_jupyter")
539
554
  in_julia = _platform_bool("_is_julia_env")
540
555
  in_vscode_terminal = _platform_bool("_in_vscode_terminal")
@@ -559,7 +574,7 @@ def snapshot_launch_environment(
559
574
  env_vars=env_vars,
560
575
  config_default=_config_window_default(environment.value),
561
576
  native_backend=_native_window_gui(),
562
- server=_server_snapshot(port),
577
+ server=primary,
563
578
  in_jupyter=in_jupyter,
564
579
  in_julia=in_julia,
565
580
  in_vscode_terminal=in_vscode_terminal,
@@ -575,6 +590,11 @@ def snapshot_launch_environment(
575
590
  and port == 8123
576
591
  else None
577
592
  ),
593
+ own_server=(
594
+ _own_server_snapshot(primary, socket.gethostname())
595
+ if inv in {Invocation.CLI, Invocation.VSCODE_EXPLORER}
596
+ else None
597
+ ),
578
598
  )
579
599
 
580
600
 
@@ -675,15 +695,51 @@ def _server_snapshot(port: int) -> ServerSnapshot:
675
695
  )
676
696
 
677
697
 
678
- def _server_reusable(server: ServerSnapshot) -> bool:
698
+ def _own_server_snapshot(
699
+ primary: ServerSnapshot, hostname: str
700
+ ) -> ServerSnapshot | None:
701
+ """Find this user's reusable server when the requested port is not one.
702
+
703
+ The instance registry is per user and per machine, so it never lists
704
+ another user's server or one reached through a port forward.
705
+ """
706
+ if not primary.port_busy or _server_reusable(primary, hostname):
707
+ return None
708
+ try:
709
+ from arrayview._instance_registry import InstanceRegistry
710
+
711
+ records = InstanceRegistry().discover()
712
+ except Exception:
713
+ return None
714
+ for record in records:
715
+ if record.port == primary.port:
716
+ continue
717
+ snapshot = _server_snapshot(record.port)
718
+ if (
719
+ snapshot.server_instance_id == record.instance_id
720
+ and _server_reusable(snapshot, hostname)
721
+ ):
722
+ return snapshot
723
+ return None
724
+
725
+
726
+ def _server_reusable(server: ServerSnapshot, hostname: str | None = None) -> bool:
679
727
  same_user = (
680
728
  server.server_uid == os.geteuid()
681
729
  if hasattr(os, "geteuid")
682
730
  else True
683
731
  )
732
+ # Same uid on another machine (shared accounts, port forwards) is not ours:
733
+ # it cannot open our file paths.
734
+ same_host = (
735
+ hostname is None
736
+ or server.server_hostname is None
737
+ or server.server_hostname == hostname
738
+ )
684
739
  return (
685
740
  server.arrayview_server_alive
686
741
  and same_user
742
+ and same_host
687
743
  and server.server_instance_id is not None
688
744
  and server.server_protocol_version == "1"
689
745
  and "identity-fenced-load" in server.server_capabilities
arrayview/_launcher.py CHANGED
@@ -1038,6 +1038,12 @@ def _server_alive(port: int, timeout: float = 0.5) -> bool:
1038
1038
 
1039
1039
  def _server_pid(port: int) -> int | None:
1040
1040
  """Return the pid of the responding ArrayView server, or None if unreachable."""
1041
+ pids = _server_pids(port)
1042
+ return None if pids is None else pids[0]
1043
+
1044
+
1045
+ def _server_pids(port: int) -> tuple[int | None, int | None] | None:
1046
+ """Return (pid, parent pid) of the responding ArrayView server, or None."""
1041
1047
  url = f"http://{_LOOPBACK_HOST}:{port}/ping"
1042
1048
  try:
1043
1049
  with urllib.request.urlopen(url, timeout=0.5) as resp:
@@ -1045,7 +1051,7 @@ def _server_pid(port: int) -> int | None:
1045
1051
  return None
1046
1052
  payload = json.loads(resp.read().decode("utf-8"))
1047
1053
  if payload.get("ok") is True and payload.get("service") == "arrayview":
1048
- return payload.get("pid")
1054
+ return payload.get("pid"), payload.get("ppid")
1049
1055
  except Exception:
1050
1056
  pass
1051
1057
  return None
@@ -1099,6 +1105,9 @@ def _planned_server_snapshot(launch_context, port: int):
1099
1105
  cli_default = launch_context.evidence.cli_default_server
1100
1106
  if cli_default is not None and cli_default.port == port:
1101
1107
  return cli_default
1108
+ own = getattr(launch_context.evidence, "own_server", None)
1109
+ if own is not None and own.port == port:
1110
+ return own
1102
1111
  return expected
1103
1112
 
1104
1113
 
@@ -1196,6 +1205,18 @@ def _relay_array_to_server(
1196
1205
  f"No transaction-compatible ArrayView relay found on "
1197
1206
  f"{relay_host}:{port}; update or restart the remote ArrayView server"
1198
1207
  )
1208
+ # A relay normally reaches the user's own server on another machine through
1209
+ # a reverse tunnel. A server on *this* machine owned by someone else is
1210
+ # just another user's ArrayView on a shared port: never send it our data.
1211
+ if (
1212
+ hasattr(os, "geteuid")
1213
+ and status.get("hostname") == socket.gethostname()
1214
+ and isinstance(status.get("uid"), int)
1215
+ and status.get("uid") != os.geteuid()
1216
+ ):
1217
+ raise RuntimeError(
1218
+ f"Port {port} belongs to another user's ArrayView on this machine"
1219
+ )
1199
1220
  current_server_id = str(status["instance_id"])
1200
1221
  if expected_server_id is not None and expected_server_id != current_server_id:
1201
1222
  raise RuntimeError("The selected relay server was replaced before upload")
@@ -2629,7 +2650,10 @@ def _wait_for_spawned_server(
2629
2650
  return False
2630
2651
  except Exception:
2631
2652
  return False
2632
- if _server_pid(port) == expected_pid:
2653
+ # On Windows a venv's python.exe is a launcher that runs the real
2654
+ # interpreter as its child: the listener then reports *proc* as parent.
2655
+ pids = _server_pids(port)
2656
+ if pids is not None and expected_pid in pids:
2633
2657
  return True
2634
2658
  time.sleep(0.02)
2635
2659
  return False
@@ -2901,7 +2925,7 @@ _TUTORIAL_EXTRAS: dict[str, str] = {}
2901
2925
 
2902
2926
 
2903
2927
  def _register_tutorial_extras(port: int, expected_server_id: str | None = None) -> None:
2904
- """Register the tutorial's vector-field and ragged-collection sessions.
2928
+ """Register the tutorial's vector-field, MRI-head and ragged-collection sessions.
2905
2929
 
2906
2930
  Best effort: a failure here costs two sections, not the tour, so it is
2907
2931
  traced and swallowed rather than allowed to fail a launch that has already
@@ -2943,6 +2967,19 @@ def _register_tutorial_extras_impl(port, bundle, expected_server_id) -> None:
2943
2967
  except Exception as exc: # pragma: no cover - best effort
2944
2968
  _trace_launch_event("tutorial.extra_failed", extra="flow", error=str(exc))
2945
2969
 
2970
+ try:
2971
+ head = _load_session_from_filepath(
2972
+ port,
2973
+ bundle.head_file,
2974
+ "mri-head",
2975
+ expected_server_id=expected_server_id,
2976
+ )
2977
+ head_sid = head.get("sid")
2978
+ if head_sid and "error" not in head:
2979
+ _TUTORIAL_EXTRAS["head"] = str(head_sid)
2980
+ except Exception as exc: # pragma: no cover - best effort
2981
+ _trace_launch_event("tutorial.extra_failed", extra="head", error=str(exc))
2982
+
2946
2983
  try:
2947
2984
  stack = _load_session_from_filepath(
2948
2985
  port,
@@ -0,0 +1,199 @@
1
+ """Refuse connections from other users on the same machine.
2
+
3
+ The server binds loopback, but on a shared host every user can reach
4
+ loopback ports, and nothing in a request says who sent it. On Linux the
5
+ kernel does know: the client end of a loopback TCP connection is a socket
6
+ owned by the uid that opened it. We look that socket up by its exact
7
+ 4-tuple (sock_diag netlink, the mechanism ``ss`` uses; /proc/net/tcp as a
8
+ fallback) and refuse the request when it belongs to a different, non-root
9
+ user.
10
+
11
+ Every legitimate path ends in a process owned by the server's user: the
12
+ CLI, the VS Code opener, VS Code's Remote-SSH/tunnel port forwarders, an
13
+ ``ssh -L``/``-R`` session, a local browser, a Jupyter proxy. Another user's
14
+ VS Code forward (or their ArrayView, or anything else) does not.
15
+
16
+ Not enforced when the owner cannot be determined (non-Linux, a peer outside
17
+ this network namespace such as a container port mapping, a non-loopback
18
+ client): behaviour there is unchanged. ``ARRAYVIEW_ALLOW_OTHER_USERS=1``
19
+ disables the check for deliberate shared setups.
20
+
21
+ ``GET /ping`` stays open: other users' launchers and openers read the
22
+ server's uid and hostname from it to decide not to use this server.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import ipaddress
28
+ import os
29
+ import socket
30
+ import struct
31
+ import sys
32
+
33
+ _OPEN_PATHS = frozenset({"/ping"})
34
+ _DENY_MESSAGE = b"This ArrayView belongs to another user on this machine."
35
+
36
+ # sock_diag constants (linux/sock_diag.h, linux/inet_diag.h)
37
+ _NETLINK_SOCK_DIAG = 4
38
+ _SOCK_DIAG_BY_FAMILY = 20
39
+ _NLM_F_REQUEST = 1
40
+ _NLMSG_ERROR = 2
41
+ _NLMSG_DONE = 3
42
+ _ALL_TCP_STATES = 0xFFF
43
+ _NOCOOKIE = 0xFFFFFFFF
44
+
45
+
46
+ def _enabled() -> bool:
47
+ return sys.platform.startswith("linux") and os.environ.get(
48
+ "ARRAYVIEW_ALLOW_OTHER_USERS", ""
49
+ ).strip().lower() not in {"1", "true", "yes", "on"}
50
+
51
+
52
+ def _addr_words(ip: ipaddress._BaseAddress) -> bytes:
53
+ raw = ip.packed
54
+ return raw + b"\0" * (16 - len(raw))
55
+
56
+
57
+ def _diag_uid(family: int, src, dst) -> int | None:
58
+ """uid owning the TCP socket whose local end is *src* and remote *dst*."""
59
+ src_ip = ipaddress.ip_address(src[0])
60
+ dst_ip = ipaddress.ip_address(dst[0])
61
+ req = struct.pack(
62
+ "=BBBBI", family, socket.IPPROTO_TCP, 0, 0, _ALL_TCP_STATES
63
+ ) + struct.pack(">HH", src[1], dst[1]) + _addr_words(src_ip) + _addr_words(
64
+ dst_ip
65
+ ) + struct.pack("=III", 0, _NOCOOKIE, _NOCOOKIE)
66
+ header = struct.pack(
67
+ "=IHHII", 16 + len(req), _SOCK_DIAG_BY_FAMILY, _NLM_F_REQUEST, 1, 0
68
+ )
69
+ with socket.socket(
70
+ socket.AF_NETLINK, socket.SOCK_DGRAM, _NETLINK_SOCK_DIAG
71
+ ) as nl:
72
+ nl.settimeout(0.5)
73
+ nl.sendto(header + req, (0, 0))
74
+ data = nl.recv(65536)
75
+ offset = 0
76
+ while offset + 16 <= len(data):
77
+ length, msg_type = struct.unpack_from("=IH", data, offset)
78
+ if length < 16:
79
+ break
80
+ if msg_type in (_NLMSG_DONE, _NLMSG_ERROR):
81
+ return None
82
+ if msg_type == _SOCK_DIAG_BY_FAMILY:
83
+ body = offset + 16
84
+ # inet_diag_msg: 4 bytes, id (48), expires, rqueue, wqueue, uid, inode
85
+ uid = struct.unpack_from("=I", data, body + 4 + 48 + 12)[0]
86
+ return int(uid)
87
+ offset += (length + 3) & ~3
88
+ return None
89
+
90
+
91
+ def _proc_addr(text: str) -> tuple[ipaddress._BaseAddress, int]:
92
+ host, port = text.split(":")
93
+ raw = bytes.fromhex(host)
94
+ # /proc prints each 32-bit word in host (little-endian) byte order.
95
+ words = b"".join(raw[i : i + 4][::-1] for i in range(0, len(raw), 4))
96
+ return ipaddress.ip_address(words), int(port, 16)
97
+
98
+
99
+ def _proc_uid(src, dst) -> int | None:
100
+ want_src = (ipaddress.ip_address(src[0]), int(src[1]))
101
+ want_dst = (ipaddress.ip_address(dst[0]), int(dst[1]))
102
+ for table in ("/proc/net/tcp", "/proc/net/tcp6"):
103
+ try:
104
+ with open(table, encoding="ascii") as handle:
105
+ next(handle, None)
106
+ for line in handle:
107
+ fields = line.split()
108
+ if len(fields) < 8:
109
+ continue
110
+ if (
111
+ _proc_addr(fields[1]) == want_src
112
+ and _proc_addr(fields[2]) == want_dst
113
+ ):
114
+ return int(fields[7])
115
+ except (OSError, ValueError):
116
+ continue
117
+ return None
118
+
119
+
120
+ def _normalise(host: str) -> str:
121
+ ip = ipaddress.ip_address(host.split("%", 1)[0])
122
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
123
+ return str(ip.ipv4_mapped)
124
+ return str(ip)
125
+
126
+
127
+ def peer_uid(client, server) -> int | None:
128
+ """Owner uid of the client end of this loopback connection, if knowable."""
129
+ if not client or not server:
130
+ return None
131
+ try:
132
+ client_host = ipaddress.ip_address(client[0].split("%", 1)[0])
133
+ if not client_host.is_loopback and not (
134
+ isinstance(client_host, ipaddress.IPv6Address)
135
+ and client_host.ipv4_mapped is not None
136
+ and client_host.ipv4_mapped.is_loopback
137
+ ):
138
+ return None
139
+ src = (client[0].split("%", 1)[0], int(client[1]))
140
+ dst = (server[0].split("%", 1)[0], int(server[1]))
141
+ except (ValueError, TypeError, IndexError):
142
+ return None
143
+ family = socket.AF_INET6 if ":" in src[0] else socket.AF_INET
144
+ try:
145
+ uid = _diag_uid(family, src, dst)
146
+ except OSError:
147
+ uid = None
148
+ if uid is None and family == socket.AF_INET6:
149
+ # Dual-stack listener: the client may have connected over IPv4.
150
+ try:
151
+ uid = _diag_uid(
152
+ socket.AF_INET, (_normalise(src[0]), src[1]),
153
+ (_normalise(dst[0]), dst[1]),
154
+ )
155
+ except (OSError, ValueError):
156
+ uid = None
157
+ if uid is None:
158
+ try:
159
+ uid = _proc_uid(
160
+ (_normalise(src[0]), src[1]), (_normalise(dst[0]), dst[1])
161
+ )
162
+ except ValueError:
163
+ uid = None
164
+ return uid
165
+
166
+
167
+ def is_foreign_peer(client, server) -> bool:
168
+ if not _enabled():
169
+ return False
170
+ uid = peer_uid(client, server)
171
+ return uid is not None and uid != 0 and uid != os.geteuid()
172
+
173
+
174
+ class PeerOwnerGuard:
175
+ """ASGI middleware: refuse HTTP and WebSocket from other local users."""
176
+
177
+ def __init__(self, app) -> None:
178
+ self.app = app
179
+
180
+ async def __call__(self, scope, receive, send) -> None:
181
+ kind = scope.get("type")
182
+ if kind not in ("http", "websocket") or scope.get("path") in _OPEN_PATHS:
183
+ await self.app(scope, receive, send)
184
+ return
185
+ if not is_foreign_peer(scope.get("client"), scope.get("server")):
186
+ await self.app(scope, receive, send)
187
+ return
188
+ if kind == "websocket":
189
+ await send({"type": "websocket.close", "code": 4403})
190
+ return
191
+ await send({
192
+ "type": "http.response.start",
193
+ "status": 403,
194
+ "headers": [
195
+ (b"content-type", b"text/plain; charset=utf-8"),
196
+ (b"content-length", str(len(_DENY_MESSAGE)).encode()),
197
+ ],
198
+ })
199
+ await send({"type": "http.response.body", "body": _DENY_MESSAGE})