From a7df710da1c32a1210b410d62e7386178a0d4db3 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 3 Nov 2026 11:21:02 -0500 Subject: [PATCH 1/2] Pre-release review fixes: socket and websocket (#4) - utcp_socket: response_byte_format accepts every name 0.1.1 accepted via Encoding.getByName; the str() request format change is marked Breaking. - utcp_websocket: a URL variable resolving to an insecure address fails discovery with a result and calls with UtcpSecurityException; the parse-time URL check is marked Breaking. - utcp: registerManual returns a failure when substitution makes the manual template invalid. --- packages/utcp/CHANGELOG.md | 1 + packages/utcp/lib/src/client.dart | 16 +++++-- packages/utcp/test/support/fake_protocol.dart | 19 ++++++-- packages/utcp/test/unit/client_test.dart | 16 +++++++ packages/utcp_socket/CHANGELOG.md | 4 +- packages/utcp_socket/lib/src/encodings.dart | 28 ++++++++--- .../utcp_socket/test/unit/encodings_test.dart | 25 ++++++++++ packages/utcp_websocket/CHANGELOG.md | 3 +- packages/utcp_websocket/README.md | 3 +- .../lib/src/websocket_security.dart | 28 +++++++++-- .../unit/websocket_call_template_test.dart | 12 ++--- ...websocket_communication_protocol_test.dart | 46 +++++++++++++++++++ 12 files changed, 169 insertions(+), 32 deletions(-) diff --git a/packages/utcp/CHANGELOG.md b/packages/utcp/CHANGELOG.md index 8bcdf8e..5376bdf 100644 --- a/packages/utcp/CHANGELOG.md +++ b/packages/utcp/CHANGELOG.md @@ -1,5 +1,6 @@ ## Unreleased +- `registerManual` returns an unsuccessful result instead of throwing when a substituted variable makes the manual call template invalid, such as a URL variable a transport refuses. - A tool's `inputs` and `outputs` schemas drop keywords whose value is null, which the Python SDK writes for every unset keyword and the TypeScript SDK rejects. `const` and `default` keep a null value. Added `JsonSchema.fromJson`. - **Breaking:** `ToolRepository` adds `removeTool` and `toJson`, and `ToolSearchStrategy` adds `toJson`; custom implementations must add them. `InMemoryToolRepository.removeTool` also drops the tool from its manual. - `UtcpClientConfig.toJson` writes the shared configuration format and round-trips through `fromJson`; loaders are written when their new `VariableLoader.toJson` is not null. diff --git a/packages/utcp/lib/src/client.dart b/packages/utcp/lib/src/client.dart index 6146d40..3c3949d 100644 --- a/packages/utcp/lib/src/client.dart +++ b/packages/utcp/lib/src/client.dart @@ -213,10 +213,18 @@ class UtcpClient { CallTemplate manualCallTemplate, String name, ) async { - final processed = await substituteCallTemplateVariables( - _callTemplates.parse({...manualCallTemplate.toJson(), 'name': name}), - name, - ); + final CallTemplate processed; + try { + processed = await substituteCallTemplateVariables( + _callTemplates.parse({...manualCallTemplate.toJson(), 'name': name}), + name, + ); + } on FormatException catch (e) { + // A substituted value can make the template invalid, such as a + // `${URL}` that resolves to an address the transport refuses. + _log.warning("Error registering manual '$name': ${e.message}"); + return RegisterManualResult.failure(manualCallTemplate, [e.message]); + } final protocol = _protocolFor(processed.callTemplateType); final result = await withCallTemplateRegistry( _callTemplates, diff --git a/packages/utcp/test/support/fake_protocol.dart b/packages/utcp/test/support/fake_protocol.dart index f4c5dd1..19b8667 100644 --- a/packages/utcp/test/support/fake_protocol.dart +++ b/packages/utcp/test/support/fake_protocol.dart @@ -78,11 +78,20 @@ class FakeCallTemplate extends CallTemplate { super.allowedCommunicationProtocols, }); - factory FakeCallTemplate.fromJson(JsonMap json) => FakeCallTemplate( - name: json.optString('name'), - token: json.optString('token'), - allowedCommunicationProtocols: json.allowedCommunicationProtocols, - ); + /// Throws a [FormatException] for the token [malformedToken]. + factory FakeCallTemplate.fromJson(JsonMap json) { + final token = json.optString('token'); + if (token == malformedToken) { + throw const FormatException("Field 'token' is malformed."); + } + return FakeCallTemplate( + name: json.optString('name'), + token: token, + allowedCommunicationProtocols: json.allowedCommunicationProtocols, + ); + } + + static const malformedToken = 'malformed'; static const type = 'fake'; diff --git a/packages/utcp/test/unit/client_test.dart b/packages/utcp/test/unit/client_test.dart index 482a277..c880a87 100644 --- a/packages/utcp/test/unit/client_test.dart +++ b/packages/utcp/test/unit/client_test.dart @@ -79,6 +79,22 @@ void main() { expect(await client.config.toolRepository.getManual('m'), isNull); }); + test( + 'a template made invalid by a substituted variable fails discovery', + () async { + final (client, _) = await clientWith( + const UtcpManual(tools: []), + variables: {'m_TOKEN': FakeCallTemplate.malformedToken}, + ); + final result = await client.registerManual( + const FakeCallTemplate(name: 'm', token: r'${TOKEN}'), + ); + expect(result.success, isFalse); + expect(result.errors, ["Field 'token' is malformed."]); + expect(await client.config.toolRepository.getManual('m'), isNull); + }, + ); + test( 'tools using a protocol the manual does not allow are dropped', () async { diff --git a/packages/utcp_socket/CHANGELOG.md b/packages/utcp_socket/CHANGELOG.md index 3dbc91a..01c7089 100644 --- a/packages/utcp_socket/CHANGELOG.md +++ b/packages/utcp_socket/CHANGELOG.md @@ -1,8 +1,8 @@ ## Unreleased -- A `text` request without a template writes non-string arguments as Python's `str()` does (`True`, `None`, `['a', 1]`) instead of as JSON, matching the Python SDK. +- **Breaking:** a `text` request without a template writes non-string arguments as Python's `str()` does instead of as JSON, matching the Python SDK: `{n: 1, flag: true}` now sends `1 True` instead of `1 true`, and `null` and lists become `None` and `['a', 1]`. - Delimiters accept `\N{name}` escapes for the names and aliases of Basic Latin, Latin-1 Supplement, General Punctuation and U+FEFF (such as `\N{NUL}` or `\N{RECORD SEPARATOR}`); other names fail when the template is parsed. -- `response_byte_format` accepts Python's encoding names, including `latin-1`, `utf-16` (`-le`, `-be`) and `cp1252`, and an unsupported one fails when the template is parsed instead of after the request is sent. +- `response_byte_format` accepts Python's encoding names, including `latin-1`, `utf-16` (`-le`, `-be`) and `cp1252`, and still every name 0.1.1 accepted (such as `us`, `csascii` and `iso-ir-100`). Case and punctuation are ignored. An unsupported name fails when the template is parsed instead of after the request is sent. - `max_response_size` applies only to `stream` framing, as in the Python SDK. Length-prefix, delimiter and fixed-length responses are capped by the new `TcpCommunicationProtocol(maxFrameBytes: ...)`, 10 MiB by default. ## 0.1.1 diff --git a/packages/utcp_socket/lib/src/encodings.dart b/packages/utcp_socket/lib/src/encodings.dart index c31f427..f1df4d2 100644 --- a/packages/utcp_socket/lib/src/encodings.dart +++ b/packages/utcp_socket/lib/src/encodings.dart @@ -5,26 +5,40 @@ import 'dart:typed_data'; /// not valid in the encoding. typedef ResponseDecoder = String Function(Uint8List bytes); -/// The decoder for a `response_byte_format`, looked up the way Python's -/// `codecs.lookup` normalizes names (case, `-`, `_` and spaces ignored), or -/// null when the encoding is not supported. +/// The decoder for a `response_byte_format`, or null when the encoding is +/// not supported. +/// +/// Case and every character other than a letter or digit are ignored, a +/// superset of how Python's `codecs.lookup` normalizes names, so +/// `iso_646.irv:1991` finds `iso646irv1991`. /// /// Supports the UTF-8, ASCII, Latin-1, UTF-16 and Windows-1252 families, /// which covers the names used with the Python SDK in practice. ResponseDecoder? responseDecoder(String name) => _decoders[name.toLowerCase().replaceAll(_separators, '')]; -final _separators = RegExp('[-_ ]'); +final _separators = RegExp('[^a-z0-9]'); /// The error for a `response_byte_format` [responseDecoder] does not know. String unsupportedResponseByteFormat(String name) => "Unsupported response_byte_format '$name'. Supported: utf-8, ascii, " 'latin-1, utf-16, utf-16-le, utf-16-be, cp1252.'; +// Python's aliases, which include every name `Encoding.getByName` knows. final Map _decoders = { - for (final name in ['utf8', 'u8', 'utf', 'cp65001']) name: utf8.decode, - for (final name in ['ascii', 'usascii', '646']) name: ascii.decode, - for (final name in ['latin1', 'latin', 'l1', 'iso88591', '88591', 'cp819']) + for (final name in [ + 'utf8', 'u8', 'utf', 'cp65001', 'csutf8', 'utf8ucs2', 'utf8ucs4', // + ]) + name: utf8.decode, + for (final name in [ + 'ascii', 'usascii', '646', 'us', 'cp367', 'ibm367', 'csascii', // + 'iso646us', 'isoir6', 'ansix341968', 'ansix341986', 'iso646irv1991', + ]) + name: ascii.decode, + for (final name in [ + 'latin1', 'latin', 'l1', 'iso88591', '88591', 'cp819', 'ibm819', // + 'csisolatin1', 'isoir100', 'iso885911987', '8859', 'iso8859', + ]) name: latin1.decode, for (final name in ['utf16', 'u16']) name: _utf16Bom, for (final name in ['utf16le', 'unicodelittleunmarked']) diff --git a/packages/utcp_socket/test/unit/encodings_test.dart b/packages/utcp_socket/test/unit/encodings_test.dart index 2626bc4..c4b7927 100644 --- a/packages/utcp_socket/test/unit/encodings_test.dart +++ b/packages/utcp_socket/test/unit/encodings_test.dart @@ -33,6 +33,31 @@ void main() { } }); + test('every name Encoding.getByName knows, which 0.1.1 used, resolves', () { + final bytes = Uint8List.fromList([0x61, 0xC3, 0xA9]); + for (final name in [ + 'iso_8859-1:1987', 'iso-ir-100', 'iso_8859-1', 'iso-8859-1', // + 'latin1', 'l1', 'ibm819', 'cp819', 'csisolatin1', 'iso-ir-6', + 'ansi_x3.4-1968', 'ansi_x3.4-1986', 'iso_646.irv:1991', 'iso646-us', + 'us-ascii', 'us', 'ibm367', 'cp367', 'csascii', 'ascii', 'csutf8', + 'utf-8', + ]) { + expect(responseDecoder(name), isNotNull, reason: name); + final String expected; + try { + expected = Encoding.getByName(name.toUpperCase())!.decode(bytes); + } on FormatException { + expect( + () => responseDecoder(name)!(bytes), + throwsFormatException, + reason: name, + ); + continue; + } + expect(responseDecoder(name)!(bytes), expected, reason: name); + } + }); + test('latin-1 decodes every byte', () { expect(decode('latin-1', [0x63, 0x61, 0x66, 0xE9]), 'café'); }); diff --git a/packages/utcp_websocket/CHANGELOG.md b/packages/utcp_websocket/CHANGELOG.md index 46b38fc..85c2f1b 100644 --- a/packages/utcp_websocket/CHANGELOG.md +++ b/packages/utcp_websocket/CHANGELOG.md @@ -1,6 +1,7 @@ ## Unreleased -- `WebSocketCallTemplate.fromJson` rejects a `url` that is neither `wss://` nor `ws://` to a loopback address, as the Python reference does; the check when connecting stays. +- **Breaking:** `WebSocketCallTemplate.fromJson` rejects a `url` that is neither `wss://` nor `ws://` to a loopback address, as the Python reference does, so a document with one fails when the client is created. A host placeholder counts as remote: `ws://${HOST}:8765/ws` fails even with `HOST=localhost`; use `wss://`, a literal loopback host, or a whole-URL variable such as `${WS_URL}`. +- A URL variable that resolves to an insecure address, such as `${WS_URL}` set to `ws://evil.example/ws`, fails discovery with an unsuccessful `RegisterManualResult` and a call with a `UtcpSecurityException`. The rejection is both a `FormatException` and a `UtcpSecurityException`. ## 0.1.1 diff --git a/packages/utcp_websocket/README.md b/packages/utcp_websocket/README.md index 37c9a26..141c007 100644 --- a/packages/utcp_websocket/README.md +++ b/packages/utcp_websocket/README.md @@ -114,7 +114,8 @@ The same rules as the core HTTP transport: - `wss://` anywhere; plain `ws://` only to `localhost`, `127.0.0.0/8` or `::1` (`isSecureWebSocketUrl`, `ensureSecureWebSocketUrl`). The URL is checked when the template is parsed, as in the Python reference, with each `${VAR}` treated as a non-loopback value, and again - on the substituted URL when connecting. + when the client parses the substituted template: discovery then returns a failed result and a + call throws a `UtcpSecurityException`. A template built in code is checked when connecting. - A redirect of the upgrade request is never followed: it would carry the handshake headers to a host the URL check never saw. (Dart's `WebSocket.connect` follows them, so the VM handshake is done by this package.) diff --git a/packages/utcp_websocket/lib/src/websocket_security.dart b/packages/utcp_websocket/lib/src/websocket_security.dart index e94cf0b..513d695 100644 --- a/packages/utcp_websocket/lib/src/websocket_security.dart +++ b/packages/utcp_websocket/lib/src/websocket_security.dart @@ -32,20 +32,38 @@ final _variablePlaceholder = RegExp(r'\$\{\w+\}|\$\w+'); final _literalScheme = RegExp(r'^[a-zA-Z][a-zA-Z0-9+.-]*://'); -/// Throws a [FormatException] when [url], as written in a call template, -/// can never pass [ensureSecureWebSocketUrl]. +/// Throws an [InsecureWebSocketUrlException] when [url], as written in a +/// call template, can never pass [ensureSecureWebSocketUrl]. /// /// Variables are substituted only when the template is used, so each /// `${VAR}` is checked as a value that is not loopback: `wss://${HOST}` and /// `ws://localhost:${PORT}` pass, `ws://${HOST}` does not. A URL without a -/// literal scheme, such as `${WS_URL}`, cannot be judged yet and passes. The -/// connection checks the substituted URL again. +/// literal scheme, such as `${WS_URL}`, cannot be judged yet and passes; the +/// client checks it when it parses the substituted template. void checkWebSocketUrlTemplate(String url) { if (!_literalScheme.hasMatch(url) && _variablePlaceholder.hasMatch(url)) { return; } if (isSecureWebSocketUrl(url.replaceAll(_variablePlaceholder, '1'))) return; - throw FormatException("Field 'url': ${_insecureUrlMessage(url)}"); + throw InsecureWebSocketUrlException( + "Field 'url': ${_insecureUrlMessage(url)}", + ); +} + +/// A call template's `url` is not `wss://` or loopback `ws://`. +/// +/// A [FormatException], so a document with such a URL fails to parse, and a +/// [UtcpSecurityException], so a call whose substituted URL is refused fails +/// as any other security rejection does. +final class InsecureWebSocketUrlException extends UtcpSecurityException + implements FormatException { + const InsecureWebSocketUrlException(super.message); + + @override + Object? get source => null; + + @override + int? get offset => null; } String _insecureUrlMessage(String url) => diff --git a/packages/utcp_websocket/test/unit/websocket_call_template_test.dart b/packages/utcp_websocket/test/unit/websocket_call_template_test.dart index 2ff2520..72e2610 100644 --- a/packages/utcp_websocket/test/unit/websocket_call_template_test.dart +++ b/packages/utcp_websocket/test/unit/websocket_call_template_test.dart @@ -67,11 +67,11 @@ void main() { 'ws://localhost:8080/ws', 'ws://127.0.0.1/ws', 'ws://[::1]:9000/ws', - // Variables are filled in later; the connection checks the result. + // Variables are filled in later; the client checks the result. r'wss://${HOST}/ws', r'ws://localhost:${PORT}/ws', r'ws://localhost:$PORT/ws', - // No literal scheme yet: only the connection can check it. + // No literal scheme yet: only the substituted URL can be checked. r'${WS_URL}', r'${WS_URL}/path', ]) { @@ -95,11 +95,9 @@ void main() { expect( () => WebSocketCallTemplate.fromJson({'url': url}), throwsA( - isA().having( - (e) => e.message, - 'message', - contains("Field 'url'"), - ), + isA() + .having((e) => e.message, 'message', contains("Field 'url'")) + .having((e) => e, 'exception', isA()), ), ); }); diff --git a/packages/utcp_websocket/test/unit/websocket_communication_protocol_test.dart b/packages/utcp_websocket/test/unit/websocket_communication_protocol_test.dart index 67bf4fd..176dd92 100644 --- a/packages/utcp_websocket/test/unit/websocket_communication_protocol_test.dart +++ b/packages/utcp_websocket/test/unit/websocket_communication_protocol_test.dart @@ -48,6 +48,52 @@ void main() { expect(result.errors.single, contains('WebSocket URL')); }); + group('a variable that resolves to plain ws to a remote host', () { + late UtcpClient substituting; + + setUp(() async { + substituting = await UtcpClient.create( + config: UtcpClientConfig( + variables: const {'m_WS_URL': 'ws://evil.example/ws'}, + environment: const {}, + ), + protocols: [protocol], + ); + }); + tearDown(() => substituting.close()); + + test('fails discovery with a result', () async { + final result = await substituting.registerManual( + const WebSocketCallTemplate(name: 'm', url: r'${WS_URL}'), + ); + expect(result.success, isFalse); + expect(result.errors.single, contains('WebSocket URL')); + expect(await substituting.config.toolRepository.getManual('m'), isNull); + }); + + test('fails a call with a security error', () async { + await substituting.config.toolRepository.saveManual( + const WebSocketCallTemplate(name: 'm', url: 'wss://tools.example/ws'), + const UtcpManual( + tools: [ + Tool( + name: 'm.t', + toolCallTemplate: WebSocketCallTemplate(url: r'${WS_URL}'), + ), + ], + ), + ); + await expectLater( + substituting.callTool('m.t'), + throwsA(isA()), + ); + await expectLater( + substituting.callToolStreaming('m.t').toList(), + throwsA(isA()), + ); + }); + }); + test('an insecure OAuth2 token URL is refused before any request', () async { const template = WebSocketCallTemplate( url: 'wss://tools.example.com/ws', From 6d85e948901dc4b9c9436c54c575339cf3e70cf4 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 3 Nov 2026 11:36:47 -0500 Subject: [PATCH 2/2] Polish: keep the insecure-URL exception private, simplify encoding test, trim changelogs --- packages/utcp_socket/CHANGELOG.md | 2 +- .../utcp_socket/test/unit/encodings_test.dart | 21 ++++++------------- packages/utcp_websocket/CHANGELOG.md | 1 - .../utcp_websocket/lib/utcp_websocket.dart | 2 +- 4 files changed, 8 insertions(+), 18 deletions(-) diff --git a/packages/utcp_socket/CHANGELOG.md b/packages/utcp_socket/CHANGELOG.md index 01c7089..e595505 100644 --- a/packages/utcp_socket/CHANGELOG.md +++ b/packages/utcp_socket/CHANGELOG.md @@ -2,7 +2,7 @@ - **Breaking:** a `text` request without a template writes non-string arguments as Python's `str()` does instead of as JSON, matching the Python SDK: `{n: 1, flag: true}` now sends `1 True` instead of `1 true`, and `null` and lists become `None` and `['a', 1]`. - Delimiters accept `\N{name}` escapes for the names and aliases of Basic Latin, Latin-1 Supplement, General Punctuation and U+FEFF (such as `\N{NUL}` or `\N{RECORD SEPARATOR}`); other names fail when the template is parsed. -- `response_byte_format` accepts Python's encoding names, including `latin-1`, `utf-16` (`-le`, `-be`) and `cp1252`, and still every name 0.1.1 accepted (such as `us`, `csascii` and `iso-ir-100`). Case and punctuation are ignored. An unsupported name fails when the template is parsed instead of after the request is sent. +- `response_byte_format` accepts Python's encoding names and aliases, such as `latin-1`, `utf-16-le`, `cp1252`, `us` and `iso-ir-100`, ignoring case and punctuation. An unsupported name fails when the template is parsed instead of after the request is sent. An unsupported name fails when the template is parsed instead of after the request is sent. - `max_response_size` applies only to `stream` framing, as in the Python SDK. Length-prefix, delimiter and fixed-length responses are capped by the new `TcpCommunicationProtocol(maxFrameBytes: ...)`, 10 MiB by default. ## 0.1.1 diff --git a/packages/utcp_socket/test/unit/encodings_test.dart b/packages/utcp_socket/test/unit/encodings_test.dart index c4b7927..63c70db 100644 --- a/packages/utcp_socket/test/unit/encodings_test.dart +++ b/packages/utcp_socket/test/unit/encodings_test.dart @@ -33,8 +33,7 @@ void main() { } }); - test('every name Encoding.getByName knows, which 0.1.1 used, resolves', () { - final bytes = Uint8List.fromList([0x61, 0xC3, 0xA9]); + test('accepts every name Encoding.getByName knows', () { for (final name in [ 'iso_8859-1:1987', 'iso-ir-100', 'iso_8859-1', 'iso-8859-1', // 'latin1', 'l1', 'ibm819', 'cp819', 'csisolatin1', 'iso-ir-6', @@ -42,19 +41,11 @@ void main() { 'us-ascii', 'us', 'ibm367', 'cp367', 'csascii', 'ascii', 'csutf8', 'utf-8', ]) { - expect(responseDecoder(name), isNotNull, reason: name); - final String expected; - try { - expected = Encoding.getByName(name.toUpperCase())!.decode(bytes); - } on FormatException { - expect( - () => responseDecoder(name)!(bytes), - throwsFormatException, - reason: name, - ); - continue; - } - expect(responseDecoder(name)!(bytes), expected, reason: name); + expect( + responseDecoder(name), + Encoding.getByName(name)!.decode, + reason: name, + ); } }); diff --git a/packages/utcp_websocket/CHANGELOG.md b/packages/utcp_websocket/CHANGELOG.md index 85c2f1b..b577540 100644 --- a/packages/utcp_websocket/CHANGELOG.md +++ b/packages/utcp_websocket/CHANGELOG.md @@ -1,7 +1,6 @@ ## Unreleased - **Breaking:** `WebSocketCallTemplate.fromJson` rejects a `url` that is neither `wss://` nor `ws://` to a loopback address, as the Python reference does, so a document with one fails when the client is created. A host placeholder counts as remote: `ws://${HOST}:8765/ws` fails even with `HOST=localhost`; use `wss://`, a literal loopback host, or a whole-URL variable such as `${WS_URL}`. -- A URL variable that resolves to an insecure address, such as `${WS_URL}` set to `ws://evil.example/ws`, fails discovery with an unsuccessful `RegisterManualResult` and a call with a `UtcpSecurityException`. The rejection is both a `FormatException` and a `UtcpSecurityException`. ## 0.1.1 diff --git a/packages/utcp_websocket/lib/utcp_websocket.dart b/packages/utcp_websocket/lib/utcp_websocket.dart index 50cbdc8..9dbb320 100644 --- a/packages/utcp_websocket/lib/utcp_websocket.dart +++ b/packages/utcp_websocket/lib/utcp_websocket.dart @@ -3,4 +3,4 @@ library; export 'src/websocket_call_template.dart'; export 'src/websocket_communication_protocol.dart'; -export 'src/websocket_security.dart'; +export 'src/websocket_security.dart' hide InsecureWebSocketUrlException;