From 07014e0506063b4cea9c5d6c68565131d3c9364a Mon Sep 17 00:00:00 2001 From: Adrianno Esnarriaga <10134911+adriannoes@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:15:38 -0300 Subject: [PATCH 1/2] fix(gateway): require pairing for WebSocket connections --- README.md | 2 +- docs/ARCHITECTURE.md | 2 +- docs/SECURITY.md | 2 +- src/gateway/http_lws.c | 72 ++++++++++++++++--------------------- tests/test_web_dashboard.js | 23 ++++++++++++ web/js/app.js | 3 +- 6 files changed, 58 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 1afa7a3b..bbc1cf59 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for PR workflow, coding standards, and th **Jetson install (v1.0):** `./scripts/install.sh`, `./scripts/build_llama_jetson.sh`, `./scripts/download_model.sh phi3` — details in [`docs/HARDWARE_JETSON.md`](docs/HARDWARE_JETSON.md) and [`docs/LOCAL_INFERENCE.md`](docs/LOCAL_INFERENCE.md). -**WebSocket auth (breaking vs early gateway builds):** browsers cannot send `Authorization` on WebSocket; use subprotocol `bearer.` when opening `/ws` (see `web/js/app.js`). +**WebSocket authentication.** Pair with the gateway before opening `/ws`. For a browser client, offer both `ws` and `bearer.` as subprotocols. The gateway selects `ws` and reads the token from the other entry. For a native client, offer `ws` and send the token in `Authorization: Bearer `. **Debug (macOS):** Symbols in `tests-dSYM/`. Use `lldb build/test_agent` then `settings set target.debug-file-search-path tests-dSYM`. Old `.dSYM` in repo root? Run `make clean-root-dsym`. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bd52b266..a198f3b3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -86,7 +86,7 @@ Convention: one primary `.c` + `.h` per module; new tools go in `src/tools/` (not `Authorization` header). +- **WebSocket.** The gateway selects the `ws` subprotocol and validates the pairing token before the connection opens. See [WebSocket authentication](../README.md) for the browser and native client contracts. - **Hardware API:** `/api/hardware/*` — board info, GPIO snapshot, tegrastats on Jetson; sensor/camera panels stubbed “Coming in v1.2”. - **Rate limits:** per-IP on `/asap`; per-token on camera snapshot (1/sec) when enabled. - **Signed manifest:** `GET /.well-known/asap/manifest.json` builds and signs the JSON synchronously in the HTTP handler (single-threaded today; not safe for concurrent manifest builds without locking). diff --git a/docs/SECURITY.md b/docs/SECURITY.md index c6ac5e10..8caabdf3 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -300,7 +300,7 @@ This section summarizes Jetson Orin Nano Super / JetPack 6.2.x concerns that do |------|------------------|----------------------------| | Sandbox isolation | [`src/sandbox/sandbox.c`](../src/sandbox/sandbox.c), [`src/sandbox/sandbox_landlock.c`](../src/sandbox/sandbox_landlock.c) | user ns + `unshare` + PID-1 fork, Landlock workspace bound, cgroups v2, fail-closed isolation | | Command policy | [`src/sandbox/allowlist.c`](../src/sandbox/allowlist.c) | Blocklist (incl. Jetson GPU + Argus), workspace path containment (DiD) | -| Gateway auth | [`src/gateway/http_lws.c`](../src/gateway/http_lws.c) | `requires_auth()` Bearer gate for `/api/*` | +| Gateway auth | [`src/gateway/http_lws.c`](../src/gateway/http_lws.c) | The gateway validates the bearer token for `/api/*` and during the WebSocket handshake. | | Hardware HTTP API | [`src/gateway/routes_hardware.c`](../src/gateway/routes_hardware.c) | Read-only GET handlers, camera POST deferred stub | | Rate limits | [`src/gateway/rate_limit.c`](../src/gateway/rate_limit.c) | Per-IP `/asap` RPM (64-slot table); reuses expired windows; **fail-closed** (429) when table is full and no slot expired | | Camera spawn | [`src/hardware/hardware_camera.c`](../src/hardware/hardware_camera.c) | argv-only `execvp`, validated resolution/type/path | diff --git a/src/gateway/http_lws.c b/src/gateway/http_lws.c index 97940070..7f53a8ec 100644 --- a/src/gateway/http_lws.c +++ b/src/gateway/http_lws.c @@ -16,6 +16,7 @@ #include #include #include +#include static void http_lws_tx_completed(struct lws *wsi) { @@ -129,41 +130,32 @@ const char *http_request_bearer_token(struct lws *wsi, char *buf, size_t buf_siz return buf + 7; } -/** WebSocket upgrade: Bearer from Authorization (or custom header); browser may send bearer. subprotocol. */ -static int ws_copy_upgrade_token(struct lws *wsi, char *token_out, size_t token_size) +/* Browsers offer ws for negotiation and bearer. for authentication. */ +static const char *ws_subprotocol_token(char *list) { - char auth_buf[256]; - const char *token; - if (!wsi || !token_out || token_size == 0) return -1; - token_out[0] = '\0'; - token = http_request_bearer_token(wsi, auth_buf, sizeof(auth_buf)); - if (!token) { - int n = lws_hdr_custom_copy(wsi, auth_buf, sizeof(auth_buf), "authorization", 13); - if (n > 7 && strncmp(auth_buf, "Bearer ", 7) == 0) - token = auth_buf + 7; + char *next = NULL; + for (char *entry = strtok_r(list, ",", &next); entry; + entry = strtok_r(NULL, ",", &next)) { + entry += strspn(entry, " \t"); + char *end = entry + strlen(entry); + while (end > entry && (end[-1] == ' ' || end[-1] == '\t')) + end--; + *end = '\0'; + if (end - entry > 7 && strncmp(entry, "bearer.", 7) == 0) + return entry + 7; } - if (token && token[0] != '\0') { - size_t len = strlen(token); - if (len >= token_size) len = token_size - 1; - memcpy(token_out, token, len); - token_out[len] = '\0'; + return NULL; +} + +static int ws_upgrade_allowed(const http_server_ctx_t *ctx, struct lws *wsi) +{ + char header[512]; + if (!ctx || !ctx->auth) return 0; - } - { - char proto[512]; - int n = lws_hdr_copy(wsi, proto, sizeof(proto), WSI_TOKEN_COLON_PROTOCOL); - if (n <= 0) - n = lws_hdr_custom_copy(wsi, proto, sizeof(proto), "sec-websocket-protocol", 22); - if (n > 7 && strncmp(proto, "bearer.", 7) == 0) { - const char *sub = proto + 7; - size_t len = (size_t)(n - 7); - if (len >= token_size) len = token_size - 1; - memcpy(token_out, sub, len); - token_out[len] = '\0'; - return token_out[0] != '\0' ? 0 : -1; - } - } - return -1; + const char *token = http_request_bearer_token(wsi, header, sizeof(header)); + if (!token && lws_hdr_copy(wsi, header, sizeof(header), WSI_TOKEN_PROTOCOL) > 0) + token = ws_subprotocol_token(header); + return token && auth_validate_token(ctx->auth, token); } static int is_static_path(const char *uri, int uri_len, int method) @@ -190,6 +182,10 @@ int http_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, { http_server_ctx_t *ctx = http_ctx_get(); (void)user; + /* libwebsockets calls the HTTP protocol before it selects ws. */ + if (reason == LWS_CALLBACK_HTTP_CONFIRM_UPGRADE && in && + strcasecmp(in, "websocket") == 0) + return ws_upgrade_allowed(ctx, wsi) ? 0 : -1; if (!ctx) return 0; switch (reason) { case LWS_CALLBACK_HTTP: { @@ -437,15 +433,9 @@ int ws_callback(struct lws *wsi, enum lws_callback_reasons reason, void *user, http_server_ctx_t *ctx = http_ctx_get(); (void)user; switch (reason) { - case LWS_CALLBACK_HTTP_CONFIRM_UPGRADE: { - char token_buf[256] = {0}; - if (!ctx || !ctx->auth) return -1; - if (ws_copy_upgrade_token(wsi, token_buf, sizeof(token_buf)) != 0) - return -1; - if (!auth_validate_token(ctx->auth, token_buf)) - return -1; - return 0; - } + case LWS_CALLBACK_HTTP_CONFIRM_UPGRADE: + case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: + return ws_upgrade_allowed(ctx, wsi) ? 0 : -1; case LWS_CALLBACK_ESTABLISHED: { int conn_id = ws_next_conn_id(); lws_set_wsi_user(wsi, (void *)(intptr_t)conn_id); diff --git a/tests/test_web_dashboard.js b/tests/test_web_dashboard.js index d0f8451c..80749794 100644 --- a/tests/test_web_dashboard.js +++ b/tests/test_web_dashboard.js @@ -5,6 +5,9 @@ */ 'use strict'; +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); const dash = require('../web/js/dashboardView.js'); const hw = require('../web/js/hardwareView.js'); const escapeHtml = dash.escapeHtml; @@ -19,6 +22,26 @@ function assert(cond, msg) { } } +function testPairedChatProtocols() { + let connection; + const location = { protocol: 'https:', host: 'localhost', hash: '#/chat' }; + const elements = { app: {}, 'chat-log': {}, 'chat-input': {} }; + const token = '1234567890abcdef1234567890abcdef'; + const script = fs.readFileSync(path.join(__dirname, '../web/js/app.js'), 'utf8'); + vm.runInNewContext(script, { + location, + window: { location, addEventListener() {} }, + document: { getElementById: id => elements[id], querySelectorAll: () => [] }, + localStorage: { getItem: key => key === 'shellclaw_token' ? token : null }, + WebSocket: function (url, protocols) { connection = { url, protocols }; }, + }); + assert(connection && connection.url === 'wss://localhost/ws', 'paired chat WebSocket URL'); + assert(connection.protocols.length === 2 && connection.protocols[0] === 'ws' && + connection.protocols[1] === 'bearer.' + token, 'paired chat offers both WebSocket protocols'); +} + +testPairedChatProtocols(); + assert(escapeHtml(null) === '', 'null'); assert(escapeHtml(undefined) === '', 'undefined'); assert(escapeHtml('').indexOf('