Skip to content

feat(dart): add URL security policy to a2ui_core - #4114

Draft
nan-yu wants to merge 21 commits into
feat/url-security-specfrom
feat/url-security-dart-core
Draft

nan-yu wants to merge 21 commits into
feat/url-security-specfrom
feat/url-security-dart-core

Conversation

@nan-yu

@nan-yu nan-yu commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds the URL security policy to a2ui_core, following the TypeScript reference in #4104 with Dart naming. Part of #4045. Stacked on #4102 (base feat/url-security-spec).

A host sets one policy on MessageProcessor. Every surface, data context and component context uses it, the resolver filters URL props before components see them, and openUrl goes through it before the host's handler.

Reviewer focus

  1. GenericBinder: how x-a2ui-url-context is read (next to the $ref or on a schema it leads to), and how the basic catalog list and the host's urlProperties map are layered over the schema (_withUrlPropertyOverrides).
  2. Baseline parity with TypeScript in security/url_security_policy.dart. Dart's Uri is not a WHATWG parser, so the checks lean on the regexes first (https?:// plus a non-slash, no control characters, spaces or backslashes) and use Uri.tryParse only for the host.
  3. openUrl behavior change: relative URLs now reach the handler (as relative Uris), like the TS baseline, and https:evil.example is now rejected, which fixes the missing authority check. A relative URL that Uri's dot-segment removal turns into //host is blocked.
  4. Host rules agreed across SDKs on top of Uri (which does no WHATWG host normalization): an http(s) host whose last label is a number must be dotted-decimal IPv4; any non-ASCII character, escape that browsers reject, IPvFuture literal or oversized port blocks the URL; allowlists compare IPv6 entries as parsed addresses and reject entries that could never match.
  5. Mark lookup in GenericBinder: marks on union branches, allOf parts, lists and objects (pushed down to the values inside), and code-defined additionalProperties / patternProperties values; differing marks resolve to the stricter context. Catalog.fromJson rejects unknown values and marks under map keywords.

Changes

  1. New lib/src/security/:
    1. UrlContext, UrlCheckInfo, UrlSecurityPolicy, PermissiveUrlSecurityPolicy (default), applyUrlSecurityPolicy (checks without reporting, for code outside a surface) and redactUrl (the shared redactedUrl rule), plus the package-internal baseline.
    2. AllowlistUrlSecurityPolicy: per-context host lists, *. wildcards, ports (a written-out default port still limits the port), allowRelative, rewrite hooks, urlProperties.
    3. UrlSchema.media() / .navigation() / .iframe(), urlContextKeyword, and the built-in basic catalog list basicCatalogUrlProperties.
  2. MessageProcessor gains urlSecurityPolicy and openUrlHandler, passed to each SurfaceModel and to RpcHandler (for calls that target no surface). The v0.9 theme iconUrl is checked as media (blocked: removed, rewritten: replaced).
  3. sanitizeUrl on SurfaceModel, DataContext and ComponentContext. Blocked URLs are reported once per surface (bounded memory) as URL_BLOCKED warnings; A2uiWarning.details carries redactedUrl, context and the known info, never the full URL.
  4. GenericBinder filters every resolved value of a marked prop (literal, data-bound, formatString, async function results, nested in lists, maps, unions; a binding that resolves to a list is checked item by item). A blocked value resolves to null. Binders of one component type share the scraped behavior tree, cached per catalog, so the mark lookup doesn't add to each binder's construction. The basic catalogs record their Image/Video/AudioPlayer URL props against the component schemas, so the checks follow the components into catalogs made with derive().
  5. openUrl (basic catalog, both versions) checks navigation through the context, prefers the processor's openUrlHandler over the catalog callback, keeps the user-activation rule, and throws A2uiUrlBlockedError (URL_BLOCKED), reported once as that error. The old scheme list is gone.
  6. Catalog.toJson() keeps x-a2ui-url-context on commonTypesRef schemas; Catalog.fromJson rejects an unknown value or a mark under additionalProperties, unevaluatedProperties or patternProperties.
  7. Conformance: removes the Dart skip, adds the url_policy_check / url_policy_resolution harness, claims dart-core for F-CORE-46, and updates the suite note in conformance/README.md.

Impact & risks

  1. Breaking (recorded in CHANGELOG): openUrl rejects URLs with whitespace or control characters (no longer trimmed) and http(s) URLs without an authority, reports them as URL_BLOCKED, and passes relative URLs through.
  2. Default behavior for media props is the baseline only (PermissiveUrlSecurityPolicy), so apps that set nothing see changes only for URLs the baseline blocks (javascript:, SVG and non-media data: URLs, and so on).
  3. conformance/features.yaml and the README suite note touch the same lines as feat(web_core): add URL security policy and plumb it to components and functions #4104; whichever merges second needs a trivial conflict fix.

Testing

Rebased on #4102 (main plus the spec). Local checks with Flutter stable (Dart 3.14):

  1. a2ui_core: flutter analyze --fatal-infos, dart format --set-exit-if-changed, flutter test (2542 pass, all url_security_policy.yaml cases included), check_executed_cases.py --harness dart-core (919 cases) and check_feature_coverage.py clean, dart test -P performance passes.
  2. a2ui_flutter and a2ui_agent: analyze and tests pass.
  3. New unit tests in test/url_security_policy_test.dart cover host rules (numeric, non-ASCII, escapes, IPv6, oversized ports), entry validation, rewrite re-checks, marks in nested/union/map schemas, Catalog.fromJson rejection, derive(), openUrl dot segments, theme iconUrl, and the blocked-URL memory.
  4. flutter_packages_test.yml dispatched on this branch: green.

🤖 Agent-generated

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a URL security policy framework for the Dart SDK (a2ui_core), allowing hosts to restrict and sanitize URLs loaded, opened, or embedded by components and functions. It adds UrlSecurityPolicy, AllowlistUrlSecurityPolicy, and PermissiveUrlSecurityPolicy, integrating them into MessageProcessor, SurfaceModel, DataContext, and GenericBinder. It also includes extensive conformance and unit tests. A critical issue was identified in url_security_policy.dart where parsed.hasPort is called on a Dart Uri object, which does not exist and will cause a compilation error; using parsed.origin is recommended instead.

Comment on lines +359 to +361
return parsed.hasPort
? '$scheme://${parsed.host}:${parsed.port}'
: '$scheme://${parsed.host}';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The Uri class in Dart does not have a hasPort property, which will cause a compilation error. Since the scheme is guaranteed to be http or https and the host is non-empty here, you can use parsed.origin to safely get the normalized scheme://host[:port] representation.

      return parsed.origin;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Uri.hasPort does exist in dart:core (it is true when the URI has an explicit port; Dart drops a default port while normalizing), and dart analyze and the CI build compile this code. I am keeping it as written: origin would also work, but it throws for URIs it does not consider to have an origin, so I would need a second guard.

🤖 Agent-generated

nan-yu added 15 commits December 3, 2026 19:28
Add UrlSecurityPolicy, PermissiveUrlSecurityPolicy, AllowlistUrlSecurityPolicy
and UrlContext, with the shared baseline every policy runs. MessageProcessor
takes urlSecurityPolicy and openUrlHandler and passes them to its surfaces and
RpcHandler. SurfaceModel, DataContext and ComponentContext gain sanitizeUrl,
which reports a blocked URL once as a redacted URL_BLOCKED warning.

GenericBinder filters props marked with x-a2ui-url-context (UrlSchema helpers),
the basic catalog media props and the v0.9 theme iconUrl. openUrl goes through
the policy as navigation, which also adds the missing authority check, and
fails with A2uiUrlBlockedError.

Run the url_security_policy conformance suite and claim dart-core for F-CORE-46.
…nd parsed IPv6 addresses (#4045)

Follows the shared rules for host parsing: an http(s) host whose last label
is a number must be a dotted-decimal IPv4 address (Uri keeps 127.1,
0x7f.0.0.1 and 256.0.0.1 as names, while browsers read or reject them), an
allowlist never matches a host Uri percent-encoded (non-ASCII, such as
faß.de), and IPv6 entries compare as parsed addresses, so [::1] matches
[0:0::1].
…browsers reject (#4045)

An allowlist entry with non-ASCII characters could never match, so the
constructor now throws ArgumentError pointing at the punycode form, as the
other SDKs do. The baseline also blocks an http(s) host that keeps a
percent escape of an ASCII character, a stray %, or escaped bytes that
aren't UTF-8 (bad%ZZhost, a%40b.example, a%C3.example, IPv6 zone ids),
which browsers reject but Uri accepts.
An entry such as 127.1 or 0x7f.0.0.1 names a host the baseline always
blocks, so it could never match. The constructor now throws ArgumentError
for it, as Python does.
…d re-check rewrites (#4045)

Follows the shared rules: the baseline blocks an http(s) host with a
non-ASCII character (browsers map some, such as fullwidth digits and dots,
to numeric IPv4 hosts). An allowlist entry with a leading dot or a
wildcard over an IP address throws ArgumentError like the other entries
that could never match, and AllowlistUrlSecurityPolicy.sanitizeUrl checks
what a rewrite hook returns with the baseline, for hosts that call the
policy directly.
…ies, unions and lists (#4045)

The binder only applied x-a2ui-url-context to a leaf value's own schema.
A mark on an additionalProperties or patternProperties value, on one branch
of a union whose resolved behavior came from another branch (a URL or a
list of URLs), or on a list or object schema was ignored, so those values
reached components unchecked. Object behaviors now keep URL-carrying
catchall and pattern behaviors, a union with a URL branch checks every
value it takes, and a mark on a list or object applies to the values inside
and to a value that isn't a list or object.
…logs that reuse them (#4045)

The built-in URL list applied only under the basic catalogs' own ids, so
the same components in a catalog made with derive() (or any catalog
reusing their schemas) loaded any URL. The basic catalogs now record their
components' URL properties against the component schemas, which derived
and renderer catalogs share.
…segment hosts (#4045)

- An http(s) URL with a port too large for an int made Uri.port throw out
  of the baseline, redaction, the binder and processMessages; it is now
  blocked. IPvFuture hosts ([v1.x]) are blocked as browsers reject them.
- openUrl refuses a relative URL that Uri's dot-segment removal turns into
  //host, which a handler stringifying the Uri would open as another host,
  and reports an unparsable allowed URL as such instead of as blocked.
- A blocked theme iconUrl is reported without asking the policy again.
- The URL_BLOCKED memory keeps at most 2 KB of each URL plus its length.
- Allowlist entries with an empty label, a port above 65535, an escape, or
  an IPvFuture literal throw ArgumentError, as other never-matching entries
  do.
…rks to the stricter context, report openUrl once (#4045)

Follows the shared decisions: Catalog.fromJson throws A2uiCatalogError for
an unknown x-a2ui-url-context value or a mark under additionalProperties,
unevaluatedProperties or patternProperties; marks that differ on one
property resolve to the stricter context (iframe over navigation over
media), and an unknown value in a code-defined schema counts as iframe;
openUrl reports a blocked URL only as its URL_BLOCKED error, without the
extra warning.
…by schema position (#4045)

- A host urlProperties entry now marks a list or object property too (the
  mark covers the values inside), as in TypeScript; it used to apply only
  to value properties.
- Catalog.fromJson's URL mark check reads property names as names, skips
  data keywords (const, enum, default, examples), and allows "none" under
  a map keyword.
- Allowlist entries with a percent escape throw ArgumentError instead of
  being decoded.
…behavior trees (#4045)

A marked property whose binding resolves to a list now has each item
checked (blocked items become null, propertyName 'p[]'), as web_core
does, instead of losing the whole list.

Binders of one component type now share the schema's behavior tree,
cached per catalog and protocol generation. The URL annotation scan had
doubled binder construction time; it is now below the pre-feature cost.
…permissive policy's repeat baseline (#4045)

A 4 MB data: image took about 160 ms per check (the regular expression
scan, run twice); it now takes about 7 ms.
…accept empty-label entries, and bracket IPv6 in redacted URLs (#4045)
…ions and export redactUrl (#4045)

redactUrl now follows the shared rule: a host that fails the baseline
host checks redacts to the scheme, a trailing dot and a default port are
dropped, and IPv6 is compressed in brackets. applyUrlSecurityPolicy and
basicCatalogUrlProperties are public, as in web_core and Python, and the
iframe warning reads 'an iframe URL'.
@nan-yu
nan-yu force-pushed the feat/url-security-dart-core branch from 5eeec2c to 714890c Compare December 3, 2026 19:29

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant