Skip to content
Open
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
6 changes: 6 additions & 0 deletions .github/workflows/unit-dart-sdk.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 12 additions & 0 deletions sdks/community/dart/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<base href="/my-app/">`, 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
Expand Down
2 changes: 2 additions & 0 deletions sdks/community/dart/lib/src/client/base_uri_stub.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/// Native clients have no ambient HTTP document URL.
Uri? get documentBaseUri => null;
7 changes: 7 additions & 0 deletions sdks/community/dart/lib/src/client/base_uri_web.dart
Original file line number Diff line number Diff line change
@@ -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);
40 changes: 40 additions & 0 deletions sdks/community/dart/lib/src/client/base_url.dart
Original file line number Diff line number Diff line change
@@ -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;
}
5 changes: 3 additions & 2 deletions sdks/community/dart/lib/src/client/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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://
Expand All @@ -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);
}
Expand Down
6 changes: 6 additions & 0 deletions sdks/community/dart/lib/src/client/config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
67 changes: 38 additions & 29 deletions sdks/community/dart/lib/src/client/validators.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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"',
Expand All @@ -77,20 +80,32 @@ 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,
constraint: 'valid-url',
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,
Expand All @@ -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(
Expand Down
23 changes: 23 additions & 0 deletions sdks/community/dart/test/client/base_url_native_test.dart
Original file line number Diff line number Diff line change
@@ -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<ValidationError>().having(
(error) => error.constraint,
'constraint',
'absolute-url-required',
),
),
);
});
}
}
55 changes: 55 additions & 0 deletions sdks/community/dart/test/client/base_url_test.dart
Original file line number Diff line number Diff line change
@@ -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<ValidationError>().having(
(error) => error.constraint,
'constraint',
'no-control-chars',
)
: isA<ValidationError>(),
),
);
});
}
}
Loading
Loading