diff --git a/.github/workflows/unit-dart-sdk.yml b/.github/workflows/unit-dart-sdk.yml index 18ad355f18..531816271d 100644 --- a/.github/workflows/unit-dart-sdk.yml +++ b/.github/workflows/unit-dart-sdk.yml @@ -40,3 +40,9 @@ jobs: - name: Run tests run: dart test --exclude-tags requires-server + + - name: Run browser base URL tests + run: | + export CHROME_EXECUTABLE="$(command -v google-chrome)" + "$CHROME_EXECUTABLE" --version + dart test --platform chrome test/client/base_url_web_test.dart test/client/base_url_test.dart diff --git a/sdks/community/dart/README.md b/sdks/community/dart/README.md index bd4e954a08..d0df951205 100644 --- a/sdks/community/dart/README.md +++ b/sdks/community/dart/README.md @@ -86,6 +86,18 @@ final client = AgUiClient( ); ``` +### Relative base URLs on the web + +For same-origin or reverse-proxied Flutter Web deployments, `baseUrl` can be +`api/agui` or `/api/agui`. With ``, the first resolves to +`/my-app/api/agui`, while the leading-slash form resolves to `/api/agui` at the +origin root. Resolution uses the current document's `baseURI`, including when +running inside an iframe, rather than the parent page's location. + +Native platforms require an absolute HTTP(S) base URL. Absolute URLs retain +strict validation. Relative bases must be paths without query strings or +fragments; empty and scheme-relative (`//host/path`) values are rejected. + ### Stream Agent Responses ```dart diff --git a/sdks/community/dart/lib/src/client/base_uri_stub.dart b/sdks/community/dart/lib/src/client/base_uri_stub.dart new file mode 100644 index 0000000000..b02ba21791 --- /dev/null +++ b/sdks/community/dart/lib/src/client/base_uri_stub.dart @@ -0,0 +1,2 @@ +/// Native clients have no ambient HTTP document URL. +Uri? get documentBaseUri => null; diff --git a/sdks/community/dart/lib/src/client/base_uri_web.dart b/sdks/community/dart/lib/src/client/base_uri_web.dart new file mode 100644 index 0000000000..f67e59a4c8 --- /dev/null +++ b/sdks/community/dart/lib/src/client/base_uri_web.dart @@ -0,0 +1,7 @@ +import 'dart:js_interop'; + +@JS('document.baseURI') +external JSString get _documentBaseUri; + +/// Use this document, including its base href, rather than the parent frame. +Uri? get documentBaseUri => Uri.tryParse(_documentBaseUri.toDart); diff --git a/sdks/community/dart/lib/src/client/base_url.dart b/sdks/community/dart/lib/src/client/base_url.dart new file mode 100644 index 0000000000..a094ad8cc7 --- /dev/null +++ b/sdks/community/dart/lib/src/client/base_url.dart @@ -0,0 +1,40 @@ +import 'base_uri_stub.dart' if (dart.library.js_interop) 'base_uri_web.dart'; +import 'errors.dart'; +import 'validators.dart'; + +/// Resolve browser path references without changing absolute URL handling. +String resolveBaseUrl(String baseUrl) { + // Validate before resolution so normalization cannot hide invalid input. + Validators.validateUrl(baseUrl, 'baseUrl', allowRelative: true); + final uri = Uri.parse(baseUrl); + if (uri.hasScheme) { + return baseUrl; + } + + if (uri.hasQuery || uri.hasFragment) { + throw ValidationError( + 'Relative baseUrl must be a path without a query or fragment', + field: 'baseUrl', + constraint: 'path-only', + value: baseUrl, + ); + } + + final base = documentBaseUri; + if (base == null || (base.scheme != 'http' && base.scheme != 'https')) { + throw ValidationError( + 'Relative baseUrl requires an HTTP(S) browser document; ' + 'use an absolute HTTP(S) URL on native platforms', + field: 'baseUrl', + constraint: 'absolute-url-required', + value: baseUrl, + ); + } + final resolved = base.resolveUri(uri).toString(); + Validators.validateUrl(resolved, 'baseUrl'); + // runAgent appends a slash before its endpoint. Avoid a duplicate slash + // for relative bases such as "/", ".", or "api/"; preserve absolute inputs. + return resolved.endsWith('/') + ? resolved.substring(0, resolved.length - 1) + : resolved; +} diff --git a/sdks/community/dart/lib/src/client/client.dart b/sdks/community/dart/lib/src/client/client.dart index c605ada07f..b9ca0f0006 100644 --- a/sdks/community/dart/lib/src/client/client.dart +++ b/sdks/community/dart/lib/src/client/client.dart @@ -11,6 +11,7 @@ import '../events/events.dart'; import '../sse/sse_client.dart'; import '../sse/sse_message.dart'; import '../types/types.dart'; +import 'base_url.dart'; import 'config.dart'; import 'errors.dart'; import 'validators.dart'; @@ -80,7 +81,7 @@ class AgUiClient { CancelToken? cancelToken, }) { // Validate inputs - Validators.validateUrl(config.baseUrl, 'baseUrl'); + final baseUrl = resolveBaseUrl(config.baseUrl); Validators.requireNonEmpty(endpoint, 'endpoint'); // Tighten the scheme test: `startsWith('http')` would accept httpfoo:// @@ -91,7 +92,7 @@ class AgUiClient { if (isAbsolute) { Validators.validateUrl(endpoint, 'endpoint'); } - final fullEndpoint = isAbsolute ? endpoint : '${config.baseUrl}/$endpoint'; + final fullEndpoint = isAbsolute ? endpoint : '$baseUrl/$endpoint'; return _runAgentInternal(fullEndpoint, input, cancelToken: cancelToken); } diff --git a/sdks/community/dart/lib/src/client/config.dart b/sdks/community/dart/lib/src/client/config.dart index 63e0e5ec1b..458e404898 100644 --- a/sdks/community/dart/lib/src/client/config.dart +++ b/sdks/community/dart/lib/src/client/config.dart @@ -15,6 +15,12 @@ import '../sse/backoff_strategy.dart'; /// ``` class AgUiClientConfig { /// Base URL for the AG-UI server. + /// + /// On the web, path-relative values resolve against document.baseURI, + /// including the current document's base href. A leading slash resolves + /// from that origin's root. Native platforms require an absolute HTTP(S) + /// URL. Relative values must be paths without queries or fragments. Empty values + /// and scheme-relative URLs are not supported. final String baseUrl; /// Default headers to include with all requests diff --git a/sdks/community/dart/lib/src/client/validators.dart b/sdks/community/dart/lib/src/client/validators.dart index 2c54dd43b4..d0200ed1fc 100644 --- a/sdks/community/dart/lib/src/client/validators.dart +++ b/sdks/community/dart/lib/src/client/validators.dart @@ -15,6 +15,13 @@ class Validators { static final RegExp _kUrlControlChars = RegExp('[\x00-\x1f\x7f\u0085\u2028\u2029]'); + // Match encoded controls without decoding unrelated bytes: legacy URLs + // can contain non-UTF-8 percent escapes, which Uri.parse accepts. + static final RegExp _kEncodedUrlControlChars = RegExp( + '%(?:0[0-9a-f]|1[0-9a-f]|7f)|%c2%85|%e2%80%a[89]', + caseSensitive: false, + ); + /// Validates that a string is not empty static void requireNonEmpty(String? value, String fieldName) { if (value == null || value.isEmpty) { @@ -46,27 +53,23 @@ class Validators { /// (C0 + Unicode line-terminators), non-http/https schemes, and /// credential-bearing URLs (`http://user:pass@host/`). /// - /// **Defense-in-depth note.** The credentials block - /// (`uri.userInfo.isNotEmpty`) ALSO defends against percent-encoded - /// control-char injection (e.g. `http://%0a:@host/` → newline in - /// `userInfo` after `Uri.parse` decodes it). If the no-credentials rule - /// is ever relaxed, ALSO run `_kUrlControlChars` against - /// `uri.userInfo`, `uri.path`, `uri.query`, and `uri.fragment` — those - /// fields are percent-decoded at access time, so the top-of-function - /// string check on the raw URL string is not sufficient on its own. - static void validateUrl(String? url, String fieldName) { + /// [allowRelative] also permits path references without a scheme or authority. + /// These must be resolved and validated again before making a request. + /// + /// **Defense-in-depth note.** Credentials and control characters are + /// checked independently. Both raw controls and their percent-encoded + /// byte sequences are rejected before URI resolution can normalize paths. + /// Unrelated percent escapes are preserved, including non-UTF-8 bytes. + static void validateUrl( + String? url, + String fieldName, { + bool allowRelative = false, + }) { requireNonEmpty(url, fieldName); - // Reject embedded control characters and DEL before delegating to - // `Uri.parse`. `Uri.parse('http://example.com/\nfoo')` returns a - // valid Uri with `\n` in the path, which then flows into HTTP - // request lines as a header-injection vector. The check covers: - // • C0 controls (`\x00`–`\x1f`) and DEL (`\x7f`) — including `\t`, - // `\n`, `\r`. - // • U+0085 (NEL), U+2028 (LS), U+2029 (PS) — Unicode logical-line - // terminators that Dart's `Uri.parse` accepts verbatim and a naive - // custom transport re-emitting the URL into an HTTP header line - // would interpret as a line break. + // Reject raw C0 controls, DEL, and Unicode line terminators before + // parsing can encode or normalize them. These checks also protect + // transports that might reflect URL components into request lines. if (_kUrlControlChars.hasMatch(url!)) { throw ValidationError( 'URL contains control characters for "$fieldName"', @@ -77,12 +80,24 @@ class Validators { } try { + // URI component getters retain percent escapes. Check the original + // reference before parsing/resolution can normalize away path segments. + if (_kEncodedUrlControlChars.hasMatch(url)) { + throw ValidationError( + 'URL contains percent-encoded control characters for "$fieldName"', + field: fieldName, + constraint: 'no-control-chars', + value: url, + ); + } final uri = Uri.parse(url); // `uri.hasAuthority` is true for `http://` (authority = empty string, // host = ""). Add the explicit `uri.host.isEmpty` guard so bare-scheme // URLs like `http://` are rejected as invalid rather than passing // through to the scheme / credentials checks. - if (!uri.hasScheme || !uri.hasAuthority || uri.host.isEmpty) { + final isRelative = !uri.hasScheme && !uri.hasAuthority; + if (!(allowRelative && isRelative) && + (!uri.hasScheme || !uri.hasAuthority || uri.host.isEmpty)) { throw ValidationError( 'Invalid URL format or empty host for "$fieldName"', field: fieldName, @@ -90,7 +105,7 @@ class Validators { value: url, ); } - if (uri.scheme != 'http' && uri.scheme != 'https') { + if (uri.hasScheme && uri.scheme != 'http' && uri.scheme != 'https') { throw ValidationError( 'URL scheme must be http or https for "$fieldName"', field: fieldName, @@ -109,14 +124,8 @@ class Validators { value: url, ); } - // Defense-in-depth: also check percent-DECODED host / path / query / - // fragment. `Uri.parse` decodes percent-escapes at access time, so a - // raw URL like `http://host/%0a/foo` passes the top-of-function string - // check but `uri.path` returns a newline — a header-injection vector - // for any consumer that reflects these fields into HTTP request lines. - // `uri.host` is included because Dart allows percent-encoded IDNA host - // labels, and the decoded host can carry control characters that a - // custom transport places into `Host:` headers. + // Defense-in-depth for components exposed by Uri. Percent-encoded + // controls have already been checked in the original reference above. for (final part in [uri.host, uri.path, uri.query, uri.fragment]) { if (_kUrlControlChars.hasMatch(part)) { throw ValidationError( diff --git a/sdks/community/dart/test/client/base_url_native_test.dart b/sdks/community/dart/test/client/base_url_native_test.dart new file mode 100644 index 0000000000..f16e128b07 --- /dev/null +++ b/sdks/community/dart/test/client/base_url_native_test.dart @@ -0,0 +1,23 @@ +@TestOn('vm') +library; + +import 'package:ag_ui/src/client/base_url.dart'; +import 'package:ag_ui/src/client/errors.dart'; +import 'package:test/test.dart'; + +void main() { + for (final value in ['api/agui', '/api/agui']) { + test('native rejects relative base $value with clear error', () { + expect( + () => resolveBaseUrl(value), + throwsA( + isA().having( + (error) => error.constraint, + 'constraint', + 'absolute-url-required', + ), + ), + ); + }); + } +} diff --git a/sdks/community/dart/test/client/base_url_test.dart b/sdks/community/dart/test/client/base_url_test.dart new file mode 100644 index 0000000000..b66542afbb --- /dev/null +++ b/sdks/community/dart/test/client/base_url_test.dart @@ -0,0 +1,55 @@ +import 'package:ag_ui/src/client/base_url.dart'; +import 'package:ag_ui/src/client/errors.dart'; +import 'package:test/test.dart'; + +void main() { + test('absolute base URLs are unchanged', () { + for (final value in [ + 'https://example.com/api', + 'http://localhost:8000', + 'https://example.com/%E9', + 'https://example.com/%FF', + ]) { + expect(resolveBaseUrl(value), value); + } + }); + + for (final value in [ + '', + '//example.com/api', + '//user:pass@example.com/api', + 'ftp://example.com/api', + 'https://user:pass@example.com/api', + 'http://', + 'api?token=value', + 'api#fragment', + '?token=value', + '#fragment', + 'api/%0a/run', + 'api/%0d/../run', + 'api/%E2%80%A8/run', + 'https://example.com/%0a/run', + 'api/\nrun', + 'api/\r/../run', + 'api/\u2028run', + 'https://example.com/\nrun', + ]) { + test('rejects unsafe base URL ${value.codeUnits}', () { + final containsControl = value.contains('%0') || + value.contains('%E2%80%A8') || + RegExp('[\x00-\x1f\x7f\u2028]').hasMatch(value); + expect( + () => resolveBaseUrl(value), + throwsA( + containsControl + ? isA().having( + (error) => error.constraint, + 'constraint', + 'no-control-chars', + ) + : isA(), + ), + ); + }); + } +} diff --git a/sdks/community/dart/test/client/base_url_web_test.dart b/sdks/community/dart/test/client/base_url_web_test.dart new file mode 100644 index 0000000000..3184286e77 --- /dev/null +++ b/sdks/community/dart/test/client/base_url_web_test.dart @@ -0,0 +1,156 @@ +@TestOn('browser') +library; + +import 'dart:js_interop'; + +import 'package:ag_ui/ag_ui.dart'; +import 'package:ag_ui/src/client/base_url.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:test/test.dart'; + +@JS('window') +external JSObject get _window; + +@JS('window.parent') +external JSObject get _parent; + +@JS('document') +external _Document get _document; + +extension type _Document(JSObject _) implements JSObject { + external String get baseURI; + external _Element get head; + external _Element createElement(String tag); + external _Element? querySelector(String selector); +} + +extension type _Element(JSObject _) implements JSObject { + external String? getAttribute(String name); + external void setAttribute(String name, String value); + external void removeAttribute(String name); + external void prepend(_Element element); + external void remove(); +} + +void main() { + late _Element base; + late bool created; + String? oldHref; + + setUp(() { + final existing = _document.querySelector('base'); + created = existing == null; + base = existing ?? _document.createElement('base'); + oldHref = base.getAttribute('href'); + if (created) { + _document.head.prepend(base); + } + }); + + tearDown(() { + if (created) { + base.remove(); + } else if (oldHref == null) { + base.removeAttribute('href'); + } else { + base.setAttribute('href', oldHref!); + } + }); + + Future expectRequest(String baseUrl, String expected) async { + var calls = 0; + final client = AgUiClient( + config: AgUiClientConfig(baseUrl: baseUrl), + httpClient: MockClient((request) async { + calls++; + expect(request.url.toString(), expected); + expect(request.method, 'POST'); + return http.Response( + '', + 200, + headers: {'content-type': 'text/event-stream'}, + ); + }), + ); + addTearDown(client.close); + await client + .runAgent('run', const SimpleRunAgentInput(messages: [])) + .toList(); + expect(calls, 1); + } + + test('uses the test iframe document rather than its parent', () async { + // package:test loads browser suites in an iframe. + expect(_window == _parent, isFalse); + base.setAttribute('href', '/iframe-app/'); + final origin = Uri.parse(_document.baseURI).origin; + await expectRequest('api/agui', '$origin/iframe-app/api/agui/run'); + }); + + test('rejects credential-bearing document bases', () { + base.setAttribute('href', 'https://user:pass@example.com/app/'); + expect(() => resolveBaseUrl('api'), throwsA(isA())); + }); + + test('rejects non-HTTP document bases', () { + base.setAttribute('href', 'file:///app/'); + expect(() => resolveBaseUrl('api'), throwsA(isA())); + }); + + test('path-relative base honors this document base href', () async { + base.setAttribute('href', '/my-app/'); + final origin = Uri.parse(_document.baseURI).origin; + await expectRequest('api/agui', '$origin/my-app/api/agui/run'); + }); + + test('root and trailing-slash paths do not add duplicate slashes', () async { + base.setAttribute('href', '/my-app/'); + final origin = Uri.parse(_document.baseURI).origin; + await expectRequest('/', '$origin/run'); + await expectRequest('.', '$origin/my-app/run'); + await expectRequest('api/', '$origin/my-app/api/run'); + }); + + test('root-relative base stays at the origin root', () async { + base.setAttribute('href', '/my-app/'); + final origin = Uri.parse(_document.baseURI).origin; + await expectRequest('/api/agui', '$origin/api/agui/run'); + }); + + test('without base href uses this document URL', () async { + base.removeAttribute('href'); + final expected = Uri.parse(_document.baseURI).resolve('api/agui'); + await expectRequest('api/agui', '$expected/run'); + }); + + test('path-relative URL uses an absolute cross-origin document base', + () async { + base.setAttribute('href', 'https://backend.example/app/'); + await expectRequest('api/agui', 'https://backend.example/app/api/agui/run'); + await expectRequest('/api/agui', 'https://backend.example/api/agui/run'); + }); + + test('dot segments resolve against the document base', () async { + base.setAttribute('href', '/my-app/nested/'); + final origin = Uri.parse(_document.baseURI).origin; + await expectRequest('../api/agui', '$origin/my-app/api/agui/run'); + await expectRequest('./api/agui', '$origin/my-app/nested/api/agui/run'); + }); + + test('absolute URL ignores document base href', () async { + base.setAttribute('href', '/my-app/'); + await expectRequest( + 'https://example.com/api', + 'https://example.com/api/run', + ); + }); + + test('reads changed base href for each call', () async { + base.setAttribute('href', '/first/'); + final origin = Uri.parse(_document.baseURI).origin; + await expectRequest('api', '$origin/first/api/run'); + base.setAttribute('href', '/second/'); + await expectRequest('api', '$origin/second/api/run'); + }); +}