Repository navigation
Conversation
There was a problem hiding this comment.
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.
| return parsed.hasPort | ||
| ? '$scheme://${parsed.host}:${parsed.port}' | ||
| : '$scheme://${parsed.host}'; |
There was a problem hiding this comment.
There was a problem hiding this comment.
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
53f8e27 to
183e38e
Compare
051d74a to
1bc1d4c
Compare
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'.
… host after the last @ (#4045)
5eeec2c to
714890c
Compare
Summary
Adds the URL security policy to
a2ui_core, following the TypeScript reference in #4104 with Dart naming. Part of #4045. Stacked on #4102 (basefeat/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, andopenUrlgoes through it before the host's handler.Reviewer focus
GenericBinder: howx-a2ui-url-contextis read (next to the$refor on a schema it leads to), and how the basic catalog list and the host'surlPropertiesmap are layered over the schema (_withUrlPropertyOverrides).security/url_security_policy.dart. Dart'sUriis not a WHATWG parser, so the checks lean on the regexes first (https?://plus a non-slash, no control characters, spaces or backslashes) and useUri.tryParseonly for the host.openUrlbehavior change: relative URLs now reach the handler (as relativeUris), like the TS baseline, andhttps:evil.exampleis now rejected, which fixes the missing authority check. A relative URL thatUri's dot-segment removal turns into//hostis blocked.Uri(which does no WHATWG host normalization): anhttp(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.GenericBinder: marks on union branches,allOfparts, lists and objects (pushed down to the values inside), and code-definedadditionalProperties/patternPropertiesvalues; differing marks resolve to the stricter context.Catalog.fromJsonrejects unknown values and marks under map keywords.Changes
lib/src/security/:UrlContext,UrlCheckInfo,UrlSecurityPolicy,PermissiveUrlSecurityPolicy(default),applyUrlSecurityPolicy(checks without reporting, for code outside a surface) andredactUrl(the sharedredactedUrlrule), plus the package-internal baseline.AllowlistUrlSecurityPolicy: per-context host lists,*.wildcards, ports (a written-out default port still limits the port),allowRelative, rewrite hooks,urlProperties.UrlSchema.media()/.navigation()/.iframe(),urlContextKeyword, and the built-in basic catalog listbasicCatalogUrlProperties.MessageProcessorgainsurlSecurityPolicyandopenUrlHandler, passed to eachSurfaceModeland toRpcHandler(for calls that target no surface). The v0.9 themeiconUrlis checked asmedia(blocked: removed, rewritten: replaced).sanitizeUrlonSurfaceModel,DataContextandComponentContext. Blocked URLs are reported once per surface (bounded memory) asURL_BLOCKEDwarnings;A2uiWarning.detailscarriesredactedUrl,contextand the known info, never the full URL.GenericBinderfilters 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 theirImage/Video/AudioPlayerURL props against the component schemas, so the checks follow the components into catalogs made withderive().openUrl(basic catalog, both versions) checksnavigationthrough the context, prefers the processor'sopenUrlHandlerover the catalog callback, keeps the user-activation rule, and throwsA2uiUrlBlockedError(URL_BLOCKED), reported once as that error. The old scheme list is gone.Catalog.toJson()keepsx-a2ui-url-contextoncommonTypesRefschemas;Catalog.fromJsonrejects an unknown value or a mark underadditionalProperties,unevaluatedPropertiesorpatternProperties.url_policy_check/url_policy_resolutionharness, claimsdart-coreforF-CORE-46, and updates the suite note inconformance/README.md.Impact & risks
openUrlrejects URLs with whitespace or control characters (no longer trimmed) andhttp(s)URLs without an authority, reports them asURL_BLOCKED, and passes relative URLs through.PermissiveUrlSecurityPolicy), so apps that set nothing see changes only for URLs the baseline blocks (javascript:, SVG and non-mediadata:URLs, and so on).conformance/features.yamland 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 (
mainplus the spec). Local checks with Flutter stable (Dart 3.14):a2ui_core:flutter analyze --fatal-infos,dart format --set-exit-if-changed,flutter test(2542 pass, allurl_security_policy.yamlcases included),check_executed_cases.py --harness dart-core(919 cases) andcheck_feature_coverage.pyclean,dart test -P performancepasses.a2ui_flutteranda2ui_agent: analyze and tests pass.test/url_security_policy_test.dartcover host rules (numeric, non-ASCII, escapes, IPv6, oversized ports), entry validation, rewrite re-checks, marks in nested/union/map schemas,Catalog.fromJsonrejection,derive(),openUrldot segments, themeiconUrl, and the blocked-URL memory.flutter_packages_test.ymldispatched on this branch: green.🤖 Agent-generated