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/src/gateway/ws.c b/src/gateway/ws.c index 11b68a02..0bce15e2 100644 --- a/src/gateway/ws.c +++ b/src/gateway/ws.c @@ -66,6 +66,7 @@ typedef struct ws_msg { typedef struct { ws_conn_t wsi; int conn_id; + int replies_only; } ws_conn_entry_t; static ws_conn_entry_t g_conns[MAX_CONNECTIONS]; @@ -132,7 +133,7 @@ int ws_next_conn_id(void) return atomic_fetch_add(&g_next_conn_id, 1) + 1; } -int ws_register_conn(int conn_id, ws_conn_t wsi) +static int ws_register_conn_with_mode(int conn_id, ws_conn_t wsi, int replies_only) { int registered = 0; pthread_mutex_lock(&g_mutex); @@ -140,6 +141,7 @@ int ws_register_conn(int conn_id, ws_conn_t wsi) if (g_conns[i].wsi == NULL) { g_conns[i].wsi = wsi; g_conns[i].conn_id = conn_id; + g_conns[i].replies_only = replies_only; registered = 1; break; } @@ -148,6 +150,25 @@ int ws_register_conn(int conn_id, ws_conn_t wsi) return registered ? 0 : -1; } +#ifdef SHELLCLAW_WS_TEST +int ws_test_register_reply_conn(int conn_id, ws_conn_t wsi) +{ + return ws_register_conn_with_mode(conn_id, wsi, 1); +} +#endif + +int ws_register_conn(int conn_id, ws_conn_t wsi) +{ + int replies_only = 0; +#ifndef SHELLCLAW_WS_TEST + /* libwebsockets keeps the request headers during the established callback. */ + char value[16]; + const char *view = lws_get_urlarg_by_name(wsi, "view=", value, sizeof(value)); + replies_only = view && strcmp(view, "chat") == 0; +#endif + return ws_register_conn_with_mode(conn_id, wsi, replies_only); +} + static void ws_free_outgoing(ws_msg_t *m) { if (!m) @@ -398,7 +419,7 @@ void ws_broadcast_text(const char *text) pthread_mutex_lock(&g_mutex); for (i = 0; i < MAX_CONNECTIONS; i++) { ws_msg_t *m; - if (!g_conns[i].wsi) + if (!g_conns[i].wsi || g_conns[i].replies_only) continue; if (g_outgoing_count >= MAX_QUEUE) break; diff --git a/src/gateway/ws.h b/src/gateway/ws.h index 0d0fcbae..d6259813 100644 --- a/src/gateway/ws.h +++ b/src/gateway/ws.h @@ -32,7 +32,7 @@ static inline int ws_text_payload_fits(size_t len_out) typedef void *ws_conn_t; /** - * Register a WebSocket connection. Called when connection is established. + * Register a WebSocket connection during the libwebsockets established callback. * * @param conn_id Unique connection ID (e.g. incrementing integer). * @param wsi libwebsockets wsi (stored as ws_conn_t). @@ -83,7 +83,7 @@ int ws_pop_incoming(char *session_id_out, size_t session_size, */ int ws_send_to(const char *session_id, const char *text); -/** Queue @p text for every connected WebSocket client. */ +/** Queue @p text for open WebSockets that receive broadcast events. */ void ws_broadcast_text(const char *text); /** diff --git a/tests/test_web_dashboard.js b/tests/test_web_dashboard.js index d0f8451c..4723668c 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,36 @@ function assert(cond, msg) { } } +function testPairedChatDisplaysRepliesAsText() { + let connection; + const location = { protocol: 'https:', host: 'localhost', hash: '#/chat' }; + const log = { textContent: '' }; + const elements = { app: {}, 'chat-log': 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) { + this.url = url; + this.protocols = protocols; + connection = this; + }, + }); + const replies = ['The card is blue.', '{"type":"provider_status","providers":[]}', + '"Café" azul']; + replies.forEach(text => connection.onmessage({ data: text })); + assert(log.textContent === replies.join('\n') + '\n', 'chat displays each reply as text'); + assert(log.innerHTML === undefined, 'chat does not insert reply markup'); + assert(connection.url === 'wss://localhost/ws?view=chat', 'chat requests the replies-only socket'); + assert(connection.protocols.length === 2 && connection.protocols[0] === 'ws' && + connection.protocols[1] === 'bearer.' + token, 'paired chat offers both WebSocket protocols'); +} + +testPairedChatDisplaysRepliesAsText(); + assert(escapeHtml(null) === '', 'null'); assert(escapeHtml(undefined) === '', 'undefined'); assert(escapeHtml('').indexOf('