Skip to content

feat(python): add URL security policy to a2ui_core - #4119

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

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

Conversation

@nan-yu

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

Copy link
Copy Markdown
Collaborator

Summary

Adds the URL security policy from the proposal in #4102 to the Python core SDK (a2ui_core), with the same shape as the TypeScript reference in #4104. Part of #4045, stacked on #4102 (base feat/url-security-spec).

A host sets one policy on the processor. Every surface then checks URL props marked with x-a2ui-url-context (plus the basic catalog's built-in list) as they resolve, openUrl checks its URL before the host's handler sees it, and blocked URLs are reported once per surface as a redacted URL_BLOCKED warning. The Python harness now runs conformance/core/url_security_policy.yaml (32/32) and claims python-core for F-CORE-46.

Reviewer focus

  1. security/url_security_policy.py: the baseline and host parser. Hosts come from urllib.parse.urlsplit and are normalized for ASCII, dotted-decimal IPv4, compressed IPv6, and percent-decoding ([::%31], numeric shorthands such as 127.1, and non-ASCII hosts are blocked). A host the normalizer can't read is blocked.
  2. resolution/generic_binder.py: BehaviorNode.url_context and catchall, read from the schema keyword at any depth (surviving unions, allOf merges, list marks, and code-defined additionalProperties, with the stricter context winning on conflict), plus top-level overrides from the built-in list and url_properties. A STATIC URL prop falls back to DYNAMIC when its value is a binding.
  3. catalog/catalog.py: Catalog.from_json rejects unknown x-a2ui-url-context values and non-none marks under additionalProperties, patternProperties, or unevaluatedProperties.
  4. basic_catalog/_open_url.py: the headless openUrl. Without an open_url_handler, an allowed call does nothing (Python has no browser to open). An async handler runs on the surface's running loop, and the SDK keeps a reference to its task until it finishes.

Changes

  1. New a2ui.core.security package, re-exported from a2ui.core: UrlSecurityPolicy (protocol with sanitize_url(url, context, info=None)), PermissiveUrlSecurityPolicy, AllowlistUrlSecurityPolicy, UrlContext, UrlContextAnnotation, URL_CONTEXTS, URL_CONTEXT_KEYWORD, UrlCheckInfo, UrlPropertyMap, UrlRewriteHook, OpenUrlHandler, url_property(), url_context_of, apply_url_security_policy, redact_url, BASIC_CATALOG_URL_PROPERTIES.
  2. MessageProcessorOptions.url_security_policy and open_url_handler, passed to every surface the processor creates, including the stand-in surfaces for agent calls (RpcHandler takes the same keyword arguments).
  3. sanitize_url on SurfaceModel, DataContext and ComponentContext. The surface reports a blocked URL once (bounded FIFO memory of 256 keys, keyed by URL length and first 2048 characters) with redactedUrl, context and the camelCase info fields; the full URL never leaves the surface. A non-string URL (such as an unset optional prop) resolves to None without a warning. redact_url follows the shared rule: scheme://host[:port] only for an http(s) URL without unsafe characters whose host passes the baseline, otherwise the scheme alone.
  4. GenericBinder filters every resolved value of a marked prop (literal, data-bound, formatString, nested in arrays, objects, unions, allOf merges, and code-defined maps; a data-bound list is filtered item by item). Blocked values resolve to None. The basic catalog URL props are marked by catalog ID and also by component model class, so they stay marked in catalogs with other IDs.
  5. The v0.9 theme iconUrl goes through the policy: blocked is removed, rewritten is replaced, and the policy runs once even when blocked.
  6. openUrl (v0.9 and v1.0) runs the policy as navigation; a blocked URL raises A2uiUrlBlockedError, reported once with error code URL_BLOCKED (without a duplicate warning). This replaces the scheme-only check, which accepted hostless URLs such as https:evil.com. The user-activation rule is unchanged.
  7. Conformance: tests/url_security_policy_runner.py implements url_policy_check, url_policy_resolution, url_policy_entries, and url_redact; the suite skip is removed; python-core added to F-CORE-46.claimedBy.
  8. tests/test_url_security_policy.py covers url_property on Pydantic models, host url_properties (including arrays and catchalls), catalog load rejections, warning redaction and bounds, ComponentContext and RpcHandler fallback info, policies that raise, invalid host entries, theme iconUrl, and sync/async open-URL handlers.
  9. CHANGELOG and README.

Impact & risks

  1. Behavior change, marked as breaking in the CHANGELOG: under the default permissive policy, basic catalog media props holding javascript:, SVG data: URLs, URLs with spaces or backslashes, numeric shorthand hosts, or non-ASCII hosts now resolve to None, and openUrl errors use URL_BLOCKED instead of EXPRESSION_ERROR. Relative openUrl URLs are now allowed, as in the proposal.
  2. UrlSecurityPolicy is a Protocol; allow_svg_data_urls and url_properties are optional attributes read with getattr, matching the optional fields in TypeScript.
  3. This branch and feat(web_core): add URL security policy and plumb it to components and functions #4104 both edit F-CORE-46.claimedBy; whichever merges second needs a one-line merge.

Testing

  1. uv run --all-packages pytest (core, agent, a2a, adk, conformance/tests): 6608 passed (with 412 skipped, 13 deselected, 3 xfailed, 33 subtests passed).
  2. Conformance: core/url_security_policy.yaml 32/32 in the Python harness; check_executed_cases.py --harness python-core verified 922 cases across 30 active suites.
  3. uv run pyink --check ., uv run --all-packages mypy ., license check on all modified and added files.

🤖 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 introduces a comprehensive URL security policy framework for the A2UI core, adding APIs like UrlSecurityPolicy, PermissiveUrlSecurityPolicy, and AllowlistUrlSecurityPolicy to control media loading, navigation, and iframe embedding. It integrates URL sanitization across MessageProcessor, SurfaceModel, DataContext, and ComponentContext, and updates the basic catalogs to enforce these policies. Feedback on the changes highlights two important issues: first, a potential crash in surface_model.py if an unhashable URL type is used as a dictionary key when reporting blocked URLs; second, the use of the deprecated loop parameter in asyncio.ensure_future within _open_url.py which should be removed.

) -> None:
if self._disposed:
return
key = (url, context, info.component_id, info.property_name, info.function_name)

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.

high

If url is not a hashable type (for example, if a custom component or host dynamically passes a dict or list to sanitize_url), creating a tuple key with url will raise a TypeError: unhashable type and crash the message processor. To prevent this, we should ensure the key uses a hashable representation of the URL, such as converting non-string URLs to their string representation.

        url_key = url if isinstance(url, str) else str(url)
        key = (url_key, context, info.component_id, info.property_name, info.function_name)

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.

Fixed in 013e65a. The baseline already blocks non-string URLs (as the TS SDK does), so they still return None and report redactedUrl: "invalid"; the de-duplication key now uses the URL for strings and <type name> otherwise, so an unhashable value such as a list from a data binding no longer raises. DataContext and ComponentContext delegate to SurfaceModel.sanitize_url, so they share the fix. Tests cover direct calls, a data-bound list, and both contexts.

🤖 Agent-generated

except Exception: # pylint: disable=broad-exception-caught
logger.exception("The open-URL handler failed.")
return
task = asyncio.ensure_future(awaitable, loop=loop)

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 loop parameter in asyncio.ensure_future has been deprecated since Python 3.8 and can be safely omitted. Since loop is already the running loop of the current thread, asyncio.ensure_future(awaitable) is sufficient and avoids deprecation warnings in newer Python versions.

Suggested change
task = asyncio.ensure_future(awaitable, loop=loop)
task = asyncio.ensure_future(awaitable)

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.

Fixed in 013e65a. asyncio.ensure_future is only reached when running_loop() returned the running loop, so the loop= argument was redundant; it's dropped and the check calls running_loop() directly.

🤖 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-python-core branch from 013e65a to 8c9862a Compare December 3, 2026 00:36
@nan-yu
nan-yu force-pushed the feat/url-security-python-core branch from 8c9862a to 80770b7 Compare December 3, 2026 00:48
@nan-yu
nan-yu force-pushed the feat/url-security-python-core branch from 80770b7 to be5a99b Compare December 3, 2026 00:49
@nan-yu
nan-yu force-pushed the feat/url-security-python-core branch from be5a99b to b987053 Compare December 3, 2026 00:59
@nan-yu
nan-yu force-pushed the feat/url-security-python-core branch from 14f301b to 0f6cc36 Compare December 3, 2026 19:10
@nan-yu
nan-yu force-pushed the feat/url-security-python-core branch from d71aac4 to 68dce69 Compare December 3, 2026 19:28
Adds the UrlSecurityPolicy contract, the permissive and allowlist policies,
the processor options url_security_policy and open_url_handler, sanitize_url
on surfaces and contexts, resolver filtering of props marked with
x-a2ui-url-context (plus the basic catalog built-in list), redacted
URL_BLOCKED warnings, and openUrl through the policy. Runs the shared
url_security_policy conformance suite and claims python-core for F-CORE-46.
…rop the loop argument (#4045)

A non-string URL, such as a list from a data binding, is blocked by the
baseline but was used in the report de-duplication key, which raised for
unhashable values. asyncio.ensure_future already uses the running loop.
…ies, and report a blocked theme icon without re-running the policy (#4045)
@nan-yu
nan-yu force-pushed the feat/url-security-python-core branch from 68dce69 to 99ea6eb 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