diff --git a/deps/cloudxr/webxr_client/helpers/oobControlToken.test.ts b/deps/cloudxr/webxr_client/helpers/oobControlToken.test.ts new file mode 100644 index 0000000000..51de2d0c8b --- /dev/null +++ b/deps/cloudxr/webxr_client/helpers/oobControlToken.test.ts @@ -0,0 +1,136 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @jest-environment jsdom + */ + +type TokenModule = typeof import('./oobControlToken'); + +let captureOobControlToken: TokenModule['captureOobControlToken']; +let getOobControlToken: TokenModule['getOobControlToken']; + +const HUB = 'oobEnable=1&serverIP=10.0.0.5&port=48322'; + +function visit(url: string): void { + window.history.replaceState({ keep: 'me' }, '', url); +} + +function hubQuery(): URLSearchParams { + return new URLSearchParams(HUB); +} + +// Fresh module per test: the in-memory fallback map is module state. +beforeEach(async () => { + window.sessionStorage.clear(); + jest.resetModules(); + ({ captureOobControlToken, getOobControlToken } = await import('./oobControlToken')); +}); + +describe('captureOobControlToken', () => { + it('lifts a fragment token, strips it, and keeps the route and history state', () => { + visit(`/client/?${HUB}#/real/dexmate?controlToken=abc-123_XYZ`); + captureOobControlToken(); + expect(window.location.hash).toBe('#/real/dexmate'); + expect(window.location.search).toBe(`?${HUB}`); + expect(window.history.state).toEqual({ keep: 'me' }); + expect(getOobControlToken(hubQuery())).toBe('abc-123_XYZ'); + }); + + it('handles a fragment with no route', () => { + visit(`/client/?${HUB}#?controlToken=tok`); + captureOobControlToken(); + expect(window.location.hash).toBe(''); + expect(getOobControlToken(hubQuery())).toBe('tok'); + }); + + it('round-trips a URL-encoded token', () => { + visit(`/client/?${HUB}#/real?controlToken=${encodeURIComponent('a&b=c?d#e')}`); + captureOobControlToken(); + expect(getOobControlToken(hubQuery())).toBe('a&b=c?d#e'); + }); + + it('reads a legacy query token and strips it, keeping other params', () => { + visit(`/client/?${HUB}&controlToken=legacy#/real`); + captureOobControlToken(); + expect(window.location.search).toBe(`?${HUB}`); + expect(window.location.hash).toBe('#/real'); + expect(getOobControlToken(hubQuery())).toBe('legacy'); + }); + + it('prefers the fragment token when both are present', () => { + visit(`/client/?${HUB}&controlToken=old#/real?controlToken=new`); + captureOobControlToken(); + expect(getOobControlToken(hubQuery())).toBe('new'); + expect(window.location.search).not.toContain('controlToken'); + expect(window.location.hash).toBe('#/real'); + }); + + it('keeps the stored token across a reload that carries none', () => { + visit(`/client/?${HUB}#/real?controlToken=tok`); + captureOobControlToken(); + visit(`/client/?${HUB}#/real`); + captureOobControlToken(); + expect(getOobControlToken(hubQuery())).toBe('tok'); + }); + + it('replaces a stale stored token with a newly supplied one', () => { + visit(`/client/?${HUB}#/real?controlToken=stale`); + captureOobControlToken(); + visit(`/client/?${HUB}#/real?controlToken=fresh`); + captureOobControlToken(); + expect(getOobControlToken(hubQuery())).toBe('fresh'); + }); + + it('does not reuse one hub endpoint token for another', () => { + visit(`/client/?${HUB}#/real?controlToken=tok`); + captureOobControlToken(); + expect(getOobControlToken(new URLSearchParams('serverIP=10.0.0.6&port=48322'))).toBeUndefined(); + expect(getOobControlToken(new URLSearchParams('serverIP=10.0.0.5&port=49000'))).toBeUndefined(); + }); + + it('leaves the URL alone when there is no token', () => { + visit(`/client/?${HUB}#/real`); + captureOobControlToken(); + expect(window.location.href).toContain(`?${HUB}#/real`); + expect(getOobControlToken(hubQuery())).toBeUndefined(); + }); + + it('prefers the fresh in-memory token over a stale stored one when the write is denied', () => { + window.sessionStorage.setItem('oobControlToken:10.0.0.5:48322', 'stale'); + const spy = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('quota'); + }); + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + visit(`/client/?${HUB}#/real?controlToken=fresh`); + captureOobControlToken(); + expect(getOobControlToken(hubQuery())).toBe('fresh'); + spy.mockRestore(); + warn.mockRestore(); + }); + + it('still serves the token for this page load when sessionStorage is denied', () => { + const spy = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('denied'); + }); + const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + visit(`/client/?${HUB}#/real?controlToken=memonly`); + captureOobControlToken(); + expect(getOobControlToken(hubQuery())).toBe('memonly'); + expect(warn).toHaveBeenCalled(); + spy.mockRestore(); + warn.mockRestore(); + }); +}); diff --git a/deps/cloudxr/webxr_client/helpers/oobControlToken.ts b/deps/cloudxr/webxr_client/helpers/oobControlToken.ts new file mode 100644 index 0000000000..6eb590a6d9 --- /dev/null +++ b/deps/cloudxr/webxr_client/helpers/oobControlToken.ts @@ -0,0 +1,101 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * OOB control token delivery. + * + * The host puts the token in the URL fragment (`#/route?controlToken=…`) so it is + * never sent in an HTTP request target or Referer. The page lifts it into + * sessionStorage (tab-scoped, keyed by hub endpoint so a reload keeps auth) and + * strips it from the address bar. A `?controlToken=` query is still read for + * hand-built bookmarks, but that URL has already been sent over the network. + */ + +const PARAM = 'controlToken'; +const STORAGE_PREFIX = 'oobControlToken:'; + +// Fallback when sessionStorage is denied: survives this page load only. +const memoryTokens = new Map(); + +function endpointKey(search: URLSearchParams): string { + const host = (search.get('serverIP') ?? '').trim(); + const port = (search.get('port') ?? '').trim(); + return `${STORAGE_PREFIX}${host}:${port}`; +} + +function storeToken(key: string, token: string): void { + memoryTokens.set(key, token); + try { + window.sessionStorage.setItem(key, token); + } catch { + console.warn( + '[Teleop] sessionStorage unavailable; OOB control token will not survive a reload' + ); + } +} + +function loadToken(key: string): string | null { + // This page load's token wins: a denied write must not fall back to an older stored one. + const current = memoryTokens.get(key); + if (current) return current; + try { + return window.sessionStorage.getItem(key) || null; + } catch { + return null; + } +} + +/** + * Lifts a control token out of the URL (fragment first, then legacy query) into + * session storage and removes it from the address bar. Call before anything + * rewrites or reads the fragment. A supplied token replaces any stored one; + * with none supplied the stored token for this endpoint is kept. + */ +export function captureOobControlToken(): void { + const { pathname, search, hash } = window.location; + const searchParams = new URLSearchParams(search); + + // Fragment layout: `#?`; split at the first '?'. + const fragment = hash.replace(/^#/, ''); + const split = fragment.indexOf('?'); + const route = split === -1 ? fragment : fragment.slice(0, split); + const fragmentParams = new URLSearchParams(split === -1 ? '' : fragment.slice(split + 1)); + + const token = fragmentParams.get(PARAM) || searchParams.get(PARAM); + if (!searchParams.has(PARAM) && !fragmentParams.has(PARAM)) return; + + if (token) storeToken(endpointKey(searchParams), token); + + searchParams.delete(PARAM); + fragmentParams.delete(PARAM); + const newSearch = searchParams.toString(); + const newFragmentParams = fragmentParams.toString(); + const newHash = + route || newFragmentParams + ? `#${route}${newFragmentParams ? `?${newFragmentParams}` : ''}` + : ''; + window.history.replaceState( + window.history.state, + '', + `${pathname}${newSearch ? `?${newSearch}` : ''}${newHash}` + ); +} + +/** Control token for the hub named by the current `serverIP`/`port` query, if any. */ +export function getOobControlToken(search: URLSearchParams): string | undefined { + return loadToken(endpointKey(search)) ?? undefined; +} diff --git a/deps/cloudxr/webxr_client/src/App.tsx b/deps/cloudxr/webxr_client/src/App.tsx index ee9ff03d1d..87728d88ac 100644 --- a/deps/cloudxr/webxr_client/src/App.tsx +++ b/deps/cloudxr/webxr_client/src/App.tsx @@ -50,6 +50,7 @@ import type { NetworkMetricsUpdate, RenderMetricsUpdate, } from '@helpers/metricsUpdates'; +import { getOobControlToken } from '@helpers/oobControlToken'; import { overridePressureObserver } from '@helpers/overridePressureObserver'; import { kPerformanceOptions } from '@helpers/PerformanceProfiles'; import CloudXRComponent from '@helpers/react/CloudXRComponent'; @@ -1002,7 +1003,7 @@ function AppContent() { let previousPresenceMessage: string | undefined; const channel = new HeadsetControlChannel({ url: hubWsUrl, - token: readUrlParam(p, 'controlToken') ?? undefined, + token: getOobControlToken(p), onPresenceRecovery: state => { const messages: Record = { paused: 'Headset paused', diff --git a/deps/cloudxr/webxr_client/src/index.tsx b/deps/cloudxr/webxr_client/src/index.tsx index 6072847eff..a3e315ffca 100644 --- a/deps/cloudxr/webxr_client/src/index.tsx +++ b/deps/cloudxr/webxr_client/src/index.tsx @@ -18,11 +18,16 @@ import React from 'react'; import ReactDOM from 'react-dom/client'; +import { captureOobControlToken } from '@helpers/oobControlToken'; + import App from './App'; import { mountBuildInfoOverlayIfRequested } from './BuildInfoOverlay'; // Start the React app immediately in the 3d-ui container function startApp() { + // Before React: App canonicalizes the URL fragment on mount. + captureOobControlToken(); + const reactContainer = document.getElementById('3d-ui'); if (reactContainer) { diff --git a/deps/cloudxr/webxr_client/tests/playwright/OobControlTokenTest.spec.js b/deps/cloudxr/webxr_client/tests/playwright/OobControlTokenTest.spec.js new file mode 100644 index 0000000000..6cbd30e1d2 --- /dev/null +++ b/deps/cloudxr/webxr_client/tests/playwright/OobControlTokenTest.spec.js @@ -0,0 +1,108 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// @ts-check +const { spawn } = require('child_process'); +const path = require('path'); +const { createInterface } = require('readline'); +const { test, expect } = require('@playwright/test'); + +/** + * The real App.tsx (app-mock build, :8082) delivering the OOB control token to a real + * OOBControlHub (tests/python/core/cloudxr/oob_hub_test_server.py): token in the URL fragment -> + * authenticated register -> token stripped from the URL -> reload -> authenticated register again. + * The hub speaks plain ws:// on loopback while the app dials wss://, so the page's WebSocket is + * bridged to the hub with page.routeWebSocket. Does not cover adb launch or a real CloudXR stream. + */ + +const HUB_SCRIPT = path.resolve( + __dirname, + '../../../../../tests/python/core/cloudxr/oob_hub_test_server.py' +); +// Must match TEST_CONTROL_TOKEN in oob_hub_test_server.py. +const HUB_TOKEN = 'oob-hub-test-token'; +const ROUTE = 'sim/isaaclab'; +const HUB_QUERY = 'oobEnable=1&serverIP=127.0.0.1&port=48322'; + +/** Starts the hub; `connectedCount()` is how many snapshots so far showed a connected headset. */ +async function startHub() { + const proc = spawn('python3', [HUB_SCRIPT], { stdio: ['ignore', 'pipe', 'pipe'] }); + let connected = 0; + const port = await new Promise((resolve, reject) => { + proc.once('error', reject); + proc.once('exit', code => reject(new Error(`hub exited early (${code})`))); + createInterface({ input: proc.stdout }).on('line', line => { + const ready = /^READY (\d+)$/.exec(line); + if (ready) resolve(Number(ready[1])); + if ( + line.startsWith('SNAPSHOT ') && + JSON.parse(line.slice(9)).headsets.some(h => h.connected) + ) { + connected += 1; + } + }); + }); + return { proc, port, connectedCount: () => connected }; +} + +/** Bridges the page's wss://…/oob/v1/ws to the plain-ws hub. */ +async function bridgeHub(page, hubPort) { + await page.routeWebSocket(/\/oob\/v1\/ws/, ws => { + const upstream = new WebSocket(`ws://127.0.0.1:${hubPort}`); + const queued = []; + upstream.onopen = () => queued.splice(0).forEach(m => upstream.send(m)); + upstream.onmessage = event => ws.send(event.data); + upstream.onclose = () => ws.close(); + ws.onMessage(message => + upstream.readyState === 1 ? upstream.send(message) : queued.push(message) + ); + ws.onClose(() => upstream.close()); + }); +} + +let hub; +test.beforeEach(async () => { + hub = await startHub(); +}); +test.afterEach(() => { + hub?.proc.kill('SIGKILL'); +}); + +test('fragment token authenticates with the hub, is stripped, and survives a reload', async ({ + page, +}) => { + const requests = []; + page.on('request', request => + requests.push(`${request.url()} ${request.headers().referer ?? ''}`) + ); + await bridgeHub(page, hub.port); + + await page.goto(`http://localhost:8082/?${HUB_QUERY}#/${ROUTE}?controlToken=${HUB_TOKEN}`); + await expect.poll(() => hub.connectedCount(), { timeout: 20000 }).toBe(1); + + const afterLoad = new URL(page.url()); + expect(afterLoad.hash).toBe(`#/${ROUTE}`); + expect(afterLoad.search).toBe(`?${HUB_QUERY}`); + + await page.reload(); + await expect.poll(() => hub.connectedCount(), { timeout: 20000 }).toBe(2); + expect(new URL(page.url()).hash).toBe(`#/${ROUTE}`); + + expect(requests.filter(r => r.includes(HUB_TOKEN))).toEqual([]); +}); + +test('a legacy query token authenticates and is stripped', async ({ page }) => { + await bridgeHub(page, hub.port); + await page.goto(`http://localhost:8082/?${HUB_QUERY}&controlToken=${HUB_TOKEN}#/${ROUTE}`); + await expect.poll(() => hub.connectedCount(), { timeout: 20000 }).toBe(1); + expect(page.url()).not.toContain('controlToken'); +}); + +test('without a token the hub rejects the headset', async ({ page }) => { + await bridgeHub(page, hub.port); + await page.goto(`http://localhost:8082/?${HUB_QUERY}#/${ROUTE}`); + await page.waitForTimeout(5000); + expect(hub.connectedCount()).toBe(0); +}); diff --git a/docs/source/references/oob_teleop_control.rst b/docs/source/references/oob_teleop_control.rst index 8588e651a6..c118a55fe3 100644 --- a/docs/source/references/oob_teleop_control.rst +++ b/docs/source/references/oob_teleop_control.rst @@ -74,6 +74,13 @@ and is **not compatible with** ``--usb-local``: TELEOP_OOB_HUB_ONLY=1 python -m isaaccapture.cloudxr.service run --accept-eula --setup-oob +Hub-only mode does not launch the headset or deliver a bookmark, so build the +headset URL yourself (Quick start, Step 2 — manual fallback) with the +session token. With ``CONTROL_TOKEN`` +unset, the generated token is printed in the startup banner on the service's +stdout; under ``service start`` that is ``service.log`` in the logs directory. +Set ``CONTROL_TOKEN`` yourself to avoid looking it up there. + You should see output confirming the hub is running: .. code-block:: text @@ -130,11 +137,11 @@ This heartbeat does not refresh stream-metric timestamps. If the adb automation fails (e.g. headset not paired), you can manually open the client URL on the headset browser with **all three** required query parameters — ``oobEnable``, ``serverIP``, and ``port`` — plus the hub's -``controlToken``: +``controlToken`` in the URL fragment: .. parsed-literal:: - |web_client_url|\ ?oobEnable=1&serverIP=&port=48322&controlToken= + |web_client_url|\ ?oobEnable=1&serverIP=&port=48322#?controlToken= Replace ```` with the streaming host's LAN IP. The ``port`` must match the proxy port (default 48322). ```` is the value of @@ -568,9 +575,24 @@ prints it in the startup banner. Requests without the token, and WebSocket - WebSocket: ``"token"`` field in the ``register`` payload - HTTP: ``?token=`` query parameter or ``X-Control-Token`` header -The headset bookmark carries the token as ``controlToken`` in the URL query, so -the hosting server and any proxy logs can see it. Treat bookmark URLs as -secrets and prefer a client served from the streaming host (``--host-client``). +An application that embeds ``CloudXRService(setup_oob=True)`` has no startup +banner. Read the token from ``service.control_token`` (``None`` without +``setup_oob``); it is never written to the logs. + +The headset bookmark carries the token in the URL fragment +(``#?controlToken=``), which the browser never sends in a +request or ``Referer``. The web client moves it into ``sessionStorage`` for that +tab and removes it from the address bar, so reloads keep working. Treat bookmark +URLs as secrets anyway: the fragment is visible to the page, to ``adb`` command +arguments and to anyone who sees the URL. + +A client build older than this change only reads ``?controlToken=`` from the +query and will not authenticate against a fragment bookmark. With +``--host-client`` with ``--setup-oob`` the host refuses a cached ``bundle.js`` that +lacks fragment support; rebuild ``deps/cloudxr/webxr_client`` and point +``TELEOP_WEB_CLIENT_STATIC_DIR`` at the build output. A hand-built +``?controlToken=`` query link still works, but that URL has already been sent in +the request. Web client integration ---------------------- @@ -580,7 +602,7 @@ The web client connects to the hub when the page URL contains .. parsed-literal:: - |web_client_url|\ ?oobEnable=1&serverIP=10.0.0.1&port=48322&controlToken= + |web_client_url|\ ?oobEnable=1&serverIP=10.0.0.1&port=48322#?controlToken= The client builds ``wss://{serverIP}:{port}/oob/v1/ws`` and: diff --git a/src/python/isaaccapture/cloudxr/oob_teleop_env.py b/src/python/isaaccapture/cloudxr/oob_teleop_env.py index 993f6f5b47..34effae2b8 100644 --- a/src/python/isaaccapture/cloudxr/oob_teleop_env.py +++ b/src/python/isaaccapture/cloudxr/oob_teleop_env.py @@ -260,9 +260,13 @@ def _write_atomic_bytes(dest: Path, data: bytes) -> None: _REQUIRED_WEB_CLIENT_ASSETS = ("index.html", "bundle.js") # Hardcoded — any new async chunk emitted by webpack must be added here manually. _OPTIONAL_WEB_CLIENT_ASSETS = ("bundle.emulator.js",) +# Storage-key literal from webxr_client/helpers/oobControlToken.ts; survives minification. +_OOB_TOKEN_FRAGMENT_MARKER = b"oobControlToken:" -def require_web_client_static_dir(*, require_health_probe: bool = False) -> Path: +def require_web_client_static_dir( + *, require_health_probe: bool = False, require_fragment_token: bool = False +) -> Path: """Ensure web client static assets exist under :func:`resolve_web_client_static_dir`. Creates the directory if needed. If ``index.html``, ``bundle.js``, or @@ -271,8 +275,9 @@ def require_web_client_static_dir(*, require_health_probe: bool = False) -> Path Idempotent: safe to call from both :class:`~.launcher.CloudXRLauncher` and ``wss.run`` (second call skips network when files are present). OOB automation requires - the current browser health protocol; a non-empty older cache is not a - compatible substitute. + the current browser health protocol, and any OOB use requires fragment + control-token support (*require_fragment_token*); a non-empty older cache is + not a compatible substitute. Raises: RuntimeError: If the path is invalid or downloads/final validation fail. @@ -316,16 +321,22 @@ def require_web_client_static_dir(*, require_health_probe: bool = False) -> Path fp = p / name if not fp.is_file() or fp.stat().st_size == 0: raise RuntimeError(f"Web client file missing or empty after fetch: {fp}") + required = [] if require_health_probe: + required += [b"healthProbe", b"healthReport"] + if require_fragment_token: + required.append(_OOB_TOKEN_FRAGMENT_MARKER) + if required: bundle = p / "bundle.js" try: bundle_bytes = bundle.read_bytes() except OSError as exc: raise RuntimeError(f"Cannot read WebXR bundle {bundle}: {exc}") from exc - if b"healthProbe" not in bundle_bytes or b"healthReport" not in bundle_bytes: + missing = [m.decode() for m in required if m not in bundle_bytes] + if missing: raise RuntimeError( - f"WebXR bundle {bundle} lacks the OOB healthProbe/healthReport " - "protocol. Build deps/cloudxr/webxr_client with `npm run build` " + f"WebXR bundle {bundle} lacks required OOB support ({', '.join(missing)}). " + "Build deps/cloudxr/webxr_client with `npm run build` " "and set TELEOP_WEB_CLIENT_STATIC_DIR to its build directory. " "An older non-empty static cache is not replaced automatically." ) @@ -535,8 +546,9 @@ def build_headset_bookmark_url( CloudXR streaming backend rather than refused. A HashRouter fragment is appended at the end when ``TELEOP_CLIENT_ROUTE`` - is set (e.g. ``#/real/gear/dexmate``); by default no fragment is added - and the WebXR client picks its own landing route. + is set (e.g. ``#/real/gear/dexmate``); by default the WebXR client picks its + own landing route. The control token rides in the same fragment as + ``?controlToken=...`` so it is never sent over the network in the request. """ cfg = stream_config or {} if not cfg.get("serverIP") or cfg.get("port") is None: @@ -546,8 +558,6 @@ def build_headset_bookmark_url( params: dict[str, str] = {} if oob_enable: params["oobEnable"] = "1" - if control_token: - params["controlToken"] = control_token params["serverIP"] = str(cfg["serverIP"]) params["port"] = str(int(cfg["port"])) v = cfg.get("codec") @@ -594,9 +604,11 @@ def build_headset_bookmark_url( sep = "&" if "?" in base else "?" url = f"{base}{sep}{q}" route = teleop_client_route_from_env() - if route: - url = f"{url}#{route}" - return url + fragment = route + if oob_enable and control_token: + # Fragment, not query: it is never sent in a request target or Referer. + fragment += "?" + urlencode({"controlToken": control_token}) + return f"{url}#{fragment}" if fragment else url def redact_control_token(text: str) -> str: @@ -693,10 +705,8 @@ def print_oob_hub_startup_banner( bookmark_display = build_headset_bookmark_url( web_client_base=web_base, stream_config=stream_cfg, - control_token=None, + control_token=token, ) - if token: - bookmark_display = f"{bookmark_display}&controlToken={token}" bookmark_display = redact_control_token(bookmark_display) wss_primary = f"wss://{primary_host}:{port}{OOB_WS_PATH}" diff --git a/src/python/isaaccapture/cloudxr/service/_service.py b/src/python/isaaccapture/cloudxr/service/_service.py index fa7b8f436f..6605ef9261 100644 --- a/src/python/isaaccapture/cloudxr/service/_service.py +++ b/src/python/isaaccapture/cloudxr/service/_service.py @@ -170,6 +170,7 @@ def __init__( self._device_profile = device_profile self._accept_eula = accept_eula self._setup_oob = setup_oob + self._control_token: str | None = None self._usb_local = usb_local self._host_client = host_client @@ -183,7 +184,8 @@ def __init__( from ..oob_teleop_env import require_web_client_static_dir # noqa: PLC0415 require_web_client_static_dir( - require_health_probe=setup_oob and not os.getenv("TELEOP_OOB_HUB_ONLY") + require_health_probe=setup_oob and not os.getenv("TELEOP_OOB_HUB_ONLY"), + require_fragment_token=setup_oob, ) self._runtime_proc: subprocess.Popen | None = None @@ -606,6 +608,17 @@ def wss_log_path(self) -> Path | None: """Path to the WSS proxy log file, or ``None`` if not yet started.""" return self._wss_log_path + @property + def control_token(self) -> str | None: + """OOB hub control token, or ``None`` without *setup_oob*. + + The exact value the running hub enforces, fixed when the proxy starts: + later ``CONTROL_TOKEN`` changes do not alter it. A secret, so never + logged; embedded owners read it here to authenticate or build a headset + URL. + """ + return self._control_token + # ------------------------------------------------------------------ # Private helpers # ------------------------------------------------------------------ @@ -841,6 +854,12 @@ def _start_wss_proxy_thread( setup_oob = self._setup_oob usb_local = self._usb_local host_client = self._host_client + if setup_oob: + # Resolved once and handed to the hub, so the accessor cannot drift + # from what the hub enforces if CONTROL_TOKEN changes later. + from ..oob_teleop_env import resolve_control_token # noqa: PLC0415 + + self._control_token = resolve_control_token() def _run_wss() -> None: asyncio.set_event_loop(loop) @@ -864,6 +883,7 @@ def _on_listening() -> None: on_oob_status=self._publish_oob_status, on_oob_fatal=self._on_oob_fatal, connect_requested=self._connect_requested, + control_token=self._control_token, ) ) if ( diff --git a/src/python/isaaccapture/cloudxr/wss.py b/src/python/isaaccapture/cloudxr/wss.py index 353ff00a01..f1abd1d06d 100755 --- a/src/python/isaaccapture/cloudxr/wss.py +++ b/src/python/isaaccapture/cloudxr/wss.py @@ -603,9 +603,13 @@ async def run( on_oob_status: Callable[[dict], object] | None = None, on_oob_fatal: Callable[[Exception], object] | None = None, connect_requested: asyncio.Event | None = None, + control_token: str | None = None, ) -> None: """Start the WSS proxy server and run until *stop_future* is resolved. + *control_token* is the hub token a service already resolved; when ``None`` + the hub resolves ``CONTROL_TOKEN`` (or a generated one) itself. + *on_listening* is called once the socket is bound and accepting, which is the only point a caller in another thread can distinguish a proxy that is serving from one still generating certificates or about to fail on a @@ -674,7 +678,7 @@ async def report_fatal(error: Exception, circumstance: str) -> None: if setup_oob: from .oob_teleop_hub import OOBControlHub # noqa: PLC0415 - control_token = resolve_control_token() + control_token = control_token or resolve_control_token() initial = { **default_initial_stream_config(resolved_port), **client_ui_fields_from_env(), @@ -716,7 +720,8 @@ async def handler(ws) -> None: from .oob_teleop_env import require_web_client_static_dir # noqa: PLC0415 _host_client_static_dir = require_web_client_static_dir( - require_health_probe=setup_oob and not os.getenv("TELEOP_OOB_HUB_ONLY") + require_health_probe=setup_oob and not os.getenv("TELEOP_OOB_HUB_ONLY"), + require_fragment_token=setup_oob, ) http_handler = _make_http_handler( diff --git a/tests/python/core/cloudxr/test_launcher.py b/tests/python/core/cloudxr/test_launcher.py index 840b1ce552..4ca879bd40 100644 --- a/tests/python/core/cloudxr/test_launcher.py +++ b/tests/python/core/cloudxr/test_launcher.py @@ -688,7 +688,9 @@ def test_run_embedded_owns_a_service(self, tmp_path): assert launcher.owns_runtime is True mocks["popen"].assert_called_once() - mocks["static_client"].assert_called_once_with(require_health_probe=False) + mocks["static_client"].assert_called_once_with( + require_health_probe=False, require_fragment_token=False + ) def test_run_embedded_stops_what_it_started(self, tmp_path): with _live(False), mock_service_deps(tmp_path, ready=True) as mocks: diff --git a/tests/python/core/cloudxr/test_oob_teleop_env.py b/tests/python/core/cloudxr/test_oob_teleop_env.py index 954259fe00..9684cffde4 100644 --- a/tests/python/core/cloudxr/test_oob_teleop_env.py +++ b/tests/python/core/cloudxr/test_oob_teleop_env.py @@ -205,15 +205,48 @@ def test_build_headset_bookmark_url_minimal() -> None: assert q["port"] == ["48322"] -def test_build_headset_bookmark_url_with_token() -> None: - """control_token is included as controlToken in the bookmark URL query string.""" +def test_build_headset_bookmark_url_token_rides_in_fragment( + clear_teleop_env: None, +) -> None: + """The control token goes in the fragment so it never reaches a request target.""" u = build_headset_bookmark_url( web_client_base="https://h.test/", stream_config={"serverIP": "10.0.0.1", "port": 48322}, control_token="secret123", ) - q = parse_qs(urlparse(u).query) - assert q["controlToken"] == ["secret123"] + parts = urlparse(u) + assert "controlToken" not in parse_qs(parts.query) + assert "secret123" not in parts.query + assert parts.fragment == "?controlToken=secret123" + + +def test_build_headset_bookmark_url_token_follows_route( + clear_teleop_env: None, monkeypatch: pytest.MonkeyPatch +) -> None: + """With a route, the token is a parameter of that fragment, and is URL-encoded.""" + monkeypatch.setenv("TELEOP_CLIENT_ROUTE", "/real/dexmate") + u = build_headset_bookmark_url( + web_client_base="https://h.test/", + stream_config={"serverIP": "10.0.0.1", "port": 48322}, + control_token="a&b=c?d#e", + ) + fragment = urlparse(u).fragment + route, _, params = fragment.partition("?") + assert route == "/real/dexmate" + assert parse_qs(params)["controlToken"] == ["a&b=c?d#e"] + + +def test_build_headset_bookmark_url_no_token_when_oob_disabled( + clear_teleop_env: None, +) -> None: + """The token only authenticates hub operations, so it is omitted without OOB.""" + u = build_headset_bookmark_url( + web_client_base="https://h.test/", + stream_config={"serverIP": "10.0.0.1", "port": 48322}, + control_token="secret123", + oob_enable=False, + ) + assert "secret123" not in u def test_build_headset_bookmark_url_with_replay_overrides() -> None: @@ -617,12 +650,29 @@ def test_oob_static_dir_rejects_cached_bundle_without_health_protocol( bundle.write_bytes(b"old WebXR client") monkeypatch.setenv(TELEOP_WEB_CLIENT_STATIC_DIR_ENV, str(tmp_path)) - with pytest.raises(RuntimeError, match="lacks the OOB healthProbe"): + with pytest.raises(RuntimeError, match=r"lacks required OOB support .*healthProbe"): require_web_client_static_dir(require_health_probe=True) + # Health protocol alone is not enough for OOB: the bundle must also read a fragment token. bundle.write_bytes(b'"healthProbe" "healthReport"') + with pytest.raises(RuntimeError, match="oobControlToken"): + require_web_client_static_dir( + require_health_probe=True, require_fragment_token=True + ) + + # Hub-only OOB has no health probe but still delivers the token in the fragment. + with pytest.raises(RuntimeError, match="oobControlToken"): + require_web_client_static_dir(require_fragment_token=True) + + # Ordinary hosted streaming (no OOB) accepts an older bundle. + assert require_web_client_static_dir() == tmp_path.resolve() + + bundle.write_bytes(b'"healthProbe" "healthReport" "oobControlToken:"') assert ( - require_web_client_static_dir(require_health_probe=True) == tmp_path.resolve() + require_web_client_static_dir( + require_health_probe=True, require_fragment_token=True + ) + == tmp_path.resolve() ) @@ -932,3 +982,16 @@ def test_oob_replay_recording_from_env( assert oob_replay_recording_from_env() == "" monkeypatch.setenv("TELEOP_OOB_RECORDING", " /tmp/take-7.json ") assert oob_replay_recording_from_env() == "/tmp/take-7.json" + + +def test_hub_only_banner_shows_generated_token( + clear_teleop_env: None, monkeypatch: pytest.MonkeyPatch, capsys +) -> None: + """Hub-only delivers no bookmark; the banner is where operators get the token.""" + monkeypatch.setenv("TELEOP_OOB_HUB_ONLY", "1") + monkeypatch.setattr(oob_teleop_env_under_test, "_generated_control_token", None) + + print_oob_hub_startup_banner(lan_host="10.0.0.1") + out = capsys.readouterr().out + token = oob_teleop_env_under_test.resolve_control_token() + assert f"this session's token is: {token}" in out diff --git a/tests/python/core/cloudxr/test_service.py b/tests/python/core/cloudxr/test_service.py index 353287b0aa..a07fdd4345 100644 --- a/tests/python/core/cloudxr/test_service.py +++ b/tests/python/core/cloudxr/test_service.py @@ -105,7 +105,9 @@ def test_oob_rejects_incompatible_webxr_bundle_before_runtime_spawn(self, tmp_pa CloudXRService( install_dir=str(tmp_path), setup_oob=True, usb_local=True ) - require_static.assert_called_once_with(require_health_probe=True) + require_static.assert_called_once_with( + require_health_probe=True, require_fragment_token=True + ) mocks["popen"].assert_not_called() def test_construction_stores_parameters(self, tmp_path): @@ -537,6 +539,53 @@ async def proxy(*, stop_future, on_listening, connect_requested, **kwargs): finally: service._stop_wss_proxy() + @pytest.mark.parametrize("hub_only", [False, True]) + @pytest.mark.parametrize("configured", ["operator-chosen", None]) + def test_control_token_is_the_one_the_hub_enforces( + self, tmp_path, monkeypatch, configured, hub_only + ): + from isaaccapture.cloudxr.oob_teleop_hub import OOBControlHub + + hubs = [] + + async def proxy(*, stop_future, on_listening, control_token, **kwargs): + hubs.append(OOBControlHub(control_token=control_token)) + on_listening() + await stop_future + + if configured: + monkeypatch.setenv("CONTROL_TOKEN", configured) + else: + monkeypatch.delenv("CONTROL_TOKEN", raising=False) + if hub_only: + monkeypatch.setenv("TELEOP_OOB_HUB_ONLY", "1") + else: + monkeypatch.delenv("TELEOP_OOB_HUB_ONLY", raising=False) + with ( + mock_service_deps(tmp_path, wss=False), + _stub_wss(proxy), + patch("isaaccapture.cloudxr.oob_teleop_adb.require_adb_on_path"), + ): + service = CloudXRService(setup_oob=True) + try: + token = service.control_token + assert token and hubs[0].check_token(token) + if configured: + assert token == configured + # The hub keeps its start-up token whatever the environment does. + monkeypatch.setenv("CONTROL_TOKEN", "changed-later") + assert service.control_token == token + monkeypatch.delenv("CONTROL_TOKEN") + assert service.control_token == token + assert hubs[0].check_token(token) + finally: + service._stop_wss_proxy() + + def test_control_token_is_none_without_oob(self, tmp_path): + with mock_service_deps(tmp_path): + service = CloudXRService() + assert service.control_token is None + def test_stopping_before_connect_does_not_launch_headset(self, tmp_path): from cloudxr_py_test_ns.wss import _wait_for_connect