Skip to content

feat(swift): add URL security policy to A2UICore - #4121

Draft
nan-yu wants to merge 19 commits into
feat/url-security-specfrom
feat/url-security-swift-core
Draft

nan-yu wants to merge 19 commits into
feat/url-security-specfrom
feat/url-security-swift-core

Conversation

@nan-yu

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

Copy link
Copy Markdown
Collaborator

Summary

Adds the URL security policy to the Swift core (A2UICore and BasicCatalog), following the TypeScript reference in #4104 with Swift names. Part of #4045. Stacked on #4102 (base feat/url-security-spec).

A host sets one policy on MessageProcessor(urlSecurityPolicy:). Every surface uses it to filter URL properties as they resolve, and openUrl checks its URL before the host's OpenURLHandler sees it.

Reviewer focus

  1. URLBaseline and HTTPAuthority parse URLs by hand instead of with Foundation's URL, so the checks match the proposal byte for byte (no trimming or normalization). Hosts compare as lowercase ASCII, so a non-ASCII host never matches an allowlist entry; it's blocked, not let through. A host whose last label is a number must be dotted-decimal IPv4 (127.1, 0x7f.0.0.1, and 256.0.0.1 are blocked), and IPv6 hosts are parsed with the WHATWG IPv6 parser so [0:0::1] matches a [::1] entry (IPAddressHost).
  2. Blocked values resolve to JSONValue.null, at the top level and inside lists and objects, so list positions stay stable. A rewritten value keeps the binding's identity and setter.
  3. Swift had no warning stream, so this adds URLBlockedWarning on SurfaceViewModel.urlBlockedPublisher and an aggregate MessageProcessor.urlBlockedPublisher. Errors still go to ActionHandling.
  4. FunctionHandler gains urlSecurityPolicy and sanitizeURL(_:context:info:) with default implementations (baseline only), so existing handlers keep compiling. A DataContext keeps its handler's policy, so a URL checked after the handler is gone (the context holds it weakly) still goes through the host's policy.

Changes

  1. New Security/ folder in A2UICore: URLSecurityPolicy, PermissiveURLSecurityPolicy, AllowlistURLSecurityPolicy (host lists with *. wildcards and ports, allowRelative, rewrite hooks, allowSVGDataURLs, urlProperties), URLContext, URLContextAnnotation, URLCheckInfo, URLBaseline, URLSchema (helpers for x-a2ui-url-context), URLBlockedWarning, and URLBlockedError.
  2. NodeResolver filters every resolved value of a URL property: the host's urlProperties entry wins, then the schema annotation (also inside allOf/anyOf/oneOf branches; conflicting marks use the stricter context, and an unknown value counts as iframe), then a built-in list for the basic catalogs (Image.url, Video.url, Video.posterUrl, AudioPlayer.url). The schema generator also marks those basic props, so the checks follow the components into derive()d catalogs. Data-bound, formatString, nested, and marked additionalProperties map values are covered, and each change resolves and checks again.
  3. sanitizeURL(_:context:info:) on SurfaceViewModel, DataContext, and NodeResolver. Blocked URLs are reported once per place (bounded memory of 256), with only scheme://host[:port], the data: media type, or the scheme.
  4. MessageProcessor passes the policy to surfaces and to the RPC handler (for calls without a surface), and removes or rewrites the v0.9 theme's iconUrl.
  5. OpenURLFunction checks its URL as navigation and throws URLBlockedError (code URL_BLOCKED). The user activation rule and the weakly held OpenURLHandler are unchanged.
  6. BasicCatalog.sanitizeMediaURL(_:) is deprecated and now runs the baseline.
  7. The Swift conformance harness runs core/url_security_policy.yaml (both actions), and F-CORE-46 claims swift-core.
  8. Entries in swift/CHANGELOG.md under Unreleased.

Impact & risks

  1. Breaking: openUrl throws URLBlockedError instead of FunctionError for blocked URLs, and the baseline is stricter than the old scheme check (https:host, spaces, and control characters are rejected).
  2. With the default permissive policy, media props now also drop SVG and non-media data: URLs. The SwiftUI views still call the deprecated helper; the stacked SwiftUI PR removes those calls.
  3. conformance/README.md still says no core harness runs the suite; the TypeScript PR rewrites that sentence, so I left it alone to avoid a conflict.

Testing

  1. Swift isn't available locally, so the Swift Core (iOS) workflow runs on this branch through workflow_dispatch (the workflow only runs on pull requests to main).
  2. Shared suite: all 30 url_security_policy.yaml cases run in URLSecurityPolicyConformanceTests.
  3. New URLSecurityPolicyTests cover what the suite doesn't: invalid host entries, numeric and IPv6 hosts, non-ASCII hosts under a wildcard, warning redaction and dedupe, the host property map and none, the theme icon (blocked and rewritten), a rewritten openUrl URL reaching the handler, and the DataContext default.
  4. uv run --project conformance pytest conformance/tests and scripts/fix_licenses.py --check pass.

🤖 Agent-generated

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@nan-yu

nan-yu commented Nov 10, 2026

Copy link
Copy Markdown
Collaborator Author

/gemini review

🤖 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 implements a comprehensive URL security policy framework for the Swift core SDK. It introduces the URLSecurityPolicy protocol, along with permissive and allowlist-based implementations (PermissiveURLSecurityPolicy and AllowlistURLSecurityPolicy), a baseline check utility (URLBaseline), and related models for context, warnings, and error handling. SurfaceViewModel, MessageProcessor, and NodeResolver have been updated to integrate URL sanitization and publish blocked URL warnings. Additionally, OpenURLFunction now validates URLs against the active security policy, throwing a new URLBlockedError when blocked. Feedback on the changes suggests a potential performance improvement in HTTPAuthority.swift to limit the length of parsed port bytes, preventing potential issues with an excessive number of leading zeros.

Comment on lines +115 to +119
let significant = portBytes.drop { $0 == UInt8(ascii: "0") }
guard significant.count <= 5 else { return nil }
let value = significant.reduce(0) { $0 * 10 + Int($1 - UInt8(ascii: "0")) }
guard value <= 65535 else { return nil }
port = value == defaultPort ? nil : value

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.

medium

The port parsing logic checks if the number of significant digits is less than or equal to 5 (significant.count <= 5). However, if the port string contains an extremely large number of leading zeros (e.g., more than 256 leading zeros), it could potentially cause performance issues or excessive memory allocation when converting or slicing. Consider limiting the maximum length of the input portBytes slice before processing to prevent potential denial-of-service or memory exhaustion issues.

Suggested change
let significant = portBytes.drop { $0 == UInt8(ascii: "0") }
guard significant.count <= 5 else { return nil }
let value = significant.reduce(0) { $0 * 10 + Int($1 - UInt8(ascii: "0")) }
guard value <= 65535 else { return nil }
port = value == defaultPort ? nil : value
guard portBytes.count <= 10 else { return nil }
let significant = portBytes.drop { $0 == UInt8(ascii: "0") }

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.

I left the length check out on purpose. The other SDKs accept any number of leading zeros: the WHATWG URL parser (TypeScript), Python's urlsplit and Dart's Uri all read https://host:00080/ and a port with 200 leading zeros as port 80. Capping portBytes at 10 bytes would make Swift block URLs that the other three allow, and the allowlist verdict should match across SDKs.

The current code is already bounded: drop(while:) is one lazy pass with no copy, the work is linear in a string that has already been read, and the significant.count <= 5 check stops the value from overflowing before it's built. In 354b6e0 I added a comment saying so and a test that a port with 300 leading zeros still matches localhost:8080 (and 008081 doesn't).

🤖 Agent-generated

@nan-yu
nan-yu force-pushed the feat/url-security-spec branch from 53f8e27 to 183e38e Compare December 3, 2026 00:31
@nan-yu
nan-yu force-pushed the feat/url-security-swift-core branch 5 times, most recently from 86007a7 to aa70192 Compare December 3, 2026 19:09
@nan-yu
nan-yu force-pushed the feat/url-security-swift-core branch from a9b6972 to 67e9551 Compare December 3, 2026 19:27
nan-yu added 14 commits December 3, 2026 19:28
Adds URLSecurityPolicy, the permissive and allowlist policies, the shared
baseline, resolver filtering of URL properties (x-a2ui-url-context, the
basic catalog built-in list, and the host's property map), redacted
URL_BLOCKED warnings, and openUrl checks through the policy. Runs the
shared url_security_policy.yaml suite and claims F-CORE-46 for swift-core.
…re IPv6 allowlist entries by address (#4045)

Hosts whose last label is a number must be dotted-decimal IPv4 addresses,
allowlist entries match ASCII hosts only, and IPv6 hosts are parsed and
compared in one written form, as the shared suite now requires.
#4045)

Browsers decode %XX in a host before reading it, so 127%2E1 is 127.1 and
cdn%2Eexample.com is cdn.example.com. An invalid escape, or a decoded
forbidden character such as % or /, makes the URL invalid.
…tes in the policy (#4045)

Entries with a leading dot or a percent escape, and wildcards over IP
addresses, now throw at construction. AllowlistURLSecurityPolicy checks a
rewritten URL against the baseline itself, for hosts that call it directly,
and a host percent-decoded to invalid UTF-8 makes the URL invalid.
…4045)

Browsers map such hosts with IDNA, which can turn fullwidth digits and
dots into a numeric IPv4 address that the dotted-decimal rule would block.
…policy in data contexts (#4045)

The resolver now finds an x-a2ui-url-context mark inside allOf, anyOf, and
oneOf branches, keeps it when allOf branches list the property again
without it, and checks the values of a map whose additionalProperties
schema is marked. A DataContext keeps its handler's policy, so a URL
checked after the handler is gone still goes through the host's policy.
The theme's iconUrl is reported without running the policy twice.
…cting URL marks (#4045)

The schema generator marks Image.url, Video.url, Video.posterUrl, and
AudioPlayer.url, so derived catalogs keep the checks. Conflicting marks
resolve to the stricter context (iframe, navigation, media), an unknown
value counts as iframe, and the URL_BLOCKED dedupe key keeps only the
URL's length and first 2048 characters.
…openUrl once (#4045)

A mark on a list property checks each item and leaves null in place of a
blocked one, as in the TypeScript reference. openUrl applies the policy
without a URL_BLOCKED warning, since its thrown URLBlockedError already
reports the blocked URL; DataContext.sanitizeURL gains reportsBlockedURL.
@nan-yu
nan-yu force-pushed the feat/url-security-swift-core branch from 67e9551 to 9c3f568 Compare December 3, 2026 19:28

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