Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/utcp/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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, `const` and `default` included, which the Python SDK writes for every unset keyword and the TypeScript SDK rejects. 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.
- **Breaking:** `VariableLoader` adds `toJson`; custom implementations must add it. `UtcpClientConfig.toJson` writes the shared configuration format and round-trips through `fromJson`; loaders are written when their `toJson` is not null.
Expand Down
16 changes: 12 additions & 4 deletions packages/utcp/lib/src/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
19 changes: 14 additions & 5 deletions packages/utcp/test/support/fake_protocol.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
16 changes: 16 additions & 0 deletions packages/utcp/test/unit/client_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions packages/utcp_socket/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 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
Expand Down
28 changes: 21 additions & 7 deletions packages/utcp_socket/lib/src/encodings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, ResponseDecoder> _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'])
Expand Down
16 changes: 16 additions & 0 deletions packages/utcp_socket/test/unit/encodings_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ void main() {
}
});

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',
'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),
Encoding.getByName(name)!.decode,
reason: name,
);
}
});

test('latin-1 decodes every byte', () {
expect(decode('latin-1', [0x63, 0x61, 0x66, 0xE9]), 'café');
});
Expand Down
2 changes: 1 addition & 1 deletion packages/utcp_websocket/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## 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}`.

## 0.1.1

Expand Down
3 changes: 2 additions & 1 deletion packages/utcp_websocket/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.)
Expand Down
28 changes: 23 additions & 5 deletions packages/utcp_websocket/lib/src/websocket_security.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand Down
2 changes: 1 addition & 1 deletion packages/utcp_websocket/lib/utcp_websocket.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Original file line number Diff line number Diff line change
Expand Up @@ -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',
]) {
Expand All @@ -95,11 +95,9 @@ void main() {
expect(
() => WebSocketCallTemplate.fromJson({'url': url}),
throwsA(
isA<FormatException>().having(
(e) => e.message,
'message',
contains("Field 'url'"),
),
isA<FormatException>()
.having((e) => e.message, 'message', contains("Field 'url'"))
.having((e) => e, 'exception', isA<UtcpSecurityException>()),
),
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<UtcpSecurityException>()),
);
await expectLater(
substituting.callToolStreaming('m.t').toList(),
throwsA(isA<UtcpSecurityException>()),
);
});
});

test('an insecure OAuth2 token URL is refused before any request', () async {
const template = WebSocketCallTemplate(
url: 'wss://tools.example.com/ws',
Expand Down
Loading