Problem/Motivation

https://www.drupal.org/sa-core-2025-004 added some XSS filtering code to the link module which ideally would live in core itself.

The aim is not to introduce new APIs or make BC breaking changes in Security Advisories, but now the SA has been released the code can be refactored in a public issue.

Steps to reproduce

Code in question: https://git.drupalcode.org/project/drupal/-/commit/b112cf535a8edd5a981c2...

Proposed resolution

Per the comments in \Drupal\link\AttributeXss:

/**
 * Defines a class for attribute XSS filtering.
 *
 * @internal This class was added for a security fix and will be folded into
 *   the \Drupal\Component\Utility\Xss class in a public issue.
 */
final class AttributeXss {

Remaining tasks

  1. This issue is postponed on #2664570: Move Attribute classes under Drupal\Component.

User interface changes

tbc

Introduced terminology

tbc

API changes

tbc

Data model changes

tbc

Release notes snippet

tbc

Issue fork drupal-3514968

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

mcdruid created an issue. See original summary.

larowlan’s picture

In addition we should try to resolve #3525428: Menu link attributes no longer stored in menu_tree since SA-CORE-2025-004 patch - we need to make XSS::attributes support HTML5 instead of XHTML.
The former allows underscores in attributes, the later does not.

dcam made their first commit to this issue’s fork.

dcam’s picture

It's currently failing Drupal\Tests\Component\DrupalComponentTest::testNoCoreInComponent() with the error:

Checking for illegal reference to 'Drupal\Core' namespace in /var/www/html/core/lib/Drupal/Component/Utility/Xss.php

I assume it's because we use Drupal\Core\Template\Attribute in the moved function.

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.

benjifisher’s picture

Status: Active » Needs work

There is an active MR, so the issue status should not be Active. There are failing tests, so I am setting the status to NW.

dcam’s picture

sanitizeAttributes() creates an instance of Drupal\Core\Template\Attribute, which isn't allowed because Component libraries aren't supposed to call Core libraries. That's why the test is failing. The test exists to prevent that from happening. So we can't move sanitizeAttributes() into the XSS utility as-is.

benjifisher’s picture

I worked on this issue with Claude (Opus 5.5). Here are the prompts I gave. I think they give an idea of how the collaboration works. I hope it is not too hard to guess the context when I replied to Claude'a lengthy responses.

Now for a harder problem. I am reviewing a merge request (MR) for Drupal core. Read core/modules/link/src/AttributeXss.php, especially the comment at the top. The problem is that this class uses Drupal\Core\Template\Attribute, and we cannot reference a Core class from a Component class. What options do we have? Can the Attribute class be moved to the Component namesake, or enough of it for the purposes of this issue? Can we rewrite the code in AttributeXss so that it does not use the Attribute class (and then move that rewritten code to the Xss class in the Component namespace)?

Oops. I meant "namespace", not "namesake", but that did not confuse Claude.

Claude's initial suggestion was to add a 30-line helper function to the Xss class. That would not have solved the problem of code drift going forward.

My second prompt:

Preventing drift is exactly the point of this MR, and the comment I mentioned. Perhaps I should say what I meant by moving "part of" the Attribute class. There is at least one precedent in Drupal core for Component and Core versions of a class: the Core PluginBase extends the Component class of the same name. I wonder if we could create a Component version of the Attribute class that has enough functionality to support sanitizeAttributes(), and then have the Core Attributes class extend this new class.

I was sloppy to put "part of" in quotes, since that was not part of the first prompt. I should have said "enough of". Again, Claude was not confused.

Claude suggested a klugy way to handle the Core and Component versions of the value classes, hence my third prompt:

Would the value classes in Core add anything to the ones in the Component namespace, or would they exist only to protect existing reference to them? If the latter is true, then we could deprecate the Core value classes for eventual removal. I am not concerned about making a larger change than the current MR: the important thing is long-term maintainability. I plan to keep the reviewer role on this issue, so do not create a new branch. Any recommendations I make will be considered by other developers.

My final prompt. It turns out that core.moved_classes has been used several times; all but one use have been removed as part of the deprecation/removal strategy.

yes, draft the issue comment. Point out the naming decision, and recommend HtmlAttributes. Include some details about core.moved_classes: it is unfamiliar to me and may be unfamiliar to other core contributors; that is not surprising if, as you say, it has been used only once. List the methods that would have to be moved to the Component Attributes class to support this issue as well as the methods that have to stay in the Core class. Include the point about Unit tests that do not boot a kernel. Even if there are no such test in Drupal core, we will want to mention that in a change record.

The rest of this comment was drafted by Claude. I shortened it, but I did not verify its claims (e.g. the dependencies among the Component classes).

Proposed structure

Naming: HtmlAttributes

The classes have to live in Drupal\Component\Utility (the drupal/core-utility package), next to Xss. They cannot use Drupal\Component\Render (the drupal/core-render package) because that would cause a circular dependency. The only use of Component\Render in the moved code is PlainTextOutput::renderFromHtml(), which is a one-liner and can be inlined.

Using the same class name would give Drupal\Component\Utility\Attribute. That would be confusing since "Attribute" in Drupal now usually means a PHP attribute. I recommend Drupal\Component\Utility\HtmlAttributes, with the value classes named to match:

  • Drupal\Core\Template\AttributeValueBase → Drupal\Component\Utility\HtmlAttributeValueBase
  • Drupal\Core\Template\AttributeString → Drupal\Component\Utility\HtmlAttributeString
  • Drupal\Core\Template\AttributeArray → Drupal\Component\Utility\HtmlAttributeArray
  • Drupal\Core\Template\AttributeBoolean → Drupal\Component\Utility\HtmlAttributeBoolean

This also avoids use ... as ... as in PluginBase (where the Core and Component classes have the same name).

The value classes: move them completely and deprecate the Core names

The four value classes depend only on Drupal\Component\Utility\Html. Move them completely and deprecate the old names using core.moved_classes (details below). This must be a complete move: with a class alias, the old and new names refer to the same class.

Using aliases instead of empty deprecated subclasses matters here. With empty subclasses, HtmlAttributes would create HtmlAttributeArray objects, and contrib code that checks $attributes['class'] instanceof \Drupal\Core\Template\AttributeArray would silently start getting FALSE. With an alias, the check still passes.

Core references to update: core/lib/Drupal/Core/Htmx/Htmx.php and core/modules/system/tests/src/Unit/Pager/PreprocessPagerTest.php.

HtmlAttributes (Component) and Attribute (Core)

Unlike the value classes, the Core Attribute class adds real functionality and should stay (not deprecated). It is also the class that every theme and module creates with new Attribute(), and the class allowed by TwigSandboxPolicy (which uses instanceof, so it keeps working).

Required in HtmlAttributes for this issue (all Xss::sanitizeAttributes() needs is (string) new HtmlAttributes($values)):

  • the $storage property (already protected, so render-cache entries serialized before the change still unserialize)
  • __construct()
  • offsetSet()
  • createAttributeValue() (with PlainTextOutput::renderFromHtml() inlined, as explained above)
  • __toString()

Must stay in Core Attribute:

  • implements MarkupInterface, together with jsonSerialize(), which MarkupInterface requires through \JsonSerializable. Twig autoescaping trusts MarkupInterface objects; without it, {{ attributes }} would be HTML-escaped. The interface is in Component\Render, so HtmlAttributes cannot implement it (see the circular dependency above).
  • An override of __toString() that carries #[JsonSchema(...)] and returns parent::__toString(). JsonSchema is a Core class, and PHP attributes are not inherited.
  • merge(Attribute $collection). If this moved to HtmlAttributes with the parameter type widened to HtmlAttributes, any contrib subclass that overrides merge(\Drupal\Core\Template\Attribute $collection) would fatal for narrowing a parameter type. It is the only method with a class-typed parameter.

Not needed for this issue, but I recommend moving them to HtmlAttributes so that the implementation lives in one place. None of them depend on Core; the only dependency is Drupal\Component\Utility\NestedArray.

  • offsetGet(), offsetUnset(), offsetExists(), getIterator() (with implements \ArrayAccess, \IteratorAggregate moving to HtmlAttributes)
  • addClass(), removeClass(), getClass(), hasClass()
  • setAttribute(), hasAttribute(), removeAttribute()
  • toArray(), storage(), __clone()

Splitting the ArrayAccess methods between the two classes (only offsetSet() in Component) would be awkward, which is another reason to move the whole group.

About core.moved_classes

This mechanism may be unfamiliar to some core contributors, so here is a summary. It was added in #3502882: Add a classloader that can handle class moves (Drupal 11.2.0) and has been used for a handful of moves in 11.x (for example, the node forms in #2391313: Move node forms to standard namespace, Drupal\node\Form and the block_content classes in #3255804: Hidden dependency on block_content in layout_builder). Most of those entries were removed with other deprecated code, so today core/core.services.yml has a single entry.

  • Moves are declared in a container parameter: core.moved_classes in core/core.services.yml, or MODULE.moved_classes in a module's *.services.yml. BackwardsCompatibilityClassLoaderPass merges them into a moved_classes parameter.
  • At the end of DrupalKernel::boot(), Drupal\Core\ClassLoader\BackwardsCompatibilityClassLoader is registered with spl_autoload_register(). When the autoloader cannot find an old class name, this loader calls class_alias($new, $old).
  • If the entry has all of deprecation_version, removed_version and change_record, the loader first triggers the standard message: "Class %s is deprecated in %s and is removed from %s, use %s instead. See %s".
  • The old files are deleted. That is what allows the regular autoloader to miss, so that the BC loader gets a chance.

For this issue, the entries would look like this (versions to be decided):

core.moved_classes:
  'Drupal\Core\Template\AttributeValueBase':
    class: 'Drupal\Component\Utility\HtmlAttributeValueBase'
    deprecation_version: drupal:12.Y.0
    removed_version: drupal:13.0.0
    change_record: https://www.drupal.org/node/...
  'Drupal\Core\Template\AttributeString':
    class: 'Drupal\Component\Utility\HtmlAttributeString'
    # same keys
  'Drupal\Core\Template\AttributeArray':
    class: 'Drupal\Component\Utility\HtmlAttributeArray'
    # same keys
  'Drupal\Core\Template\AttributeBoolean':
    class: 'Drupal\Component\Utility\HtmlAttributeBoolean'
    # same keys

Limitation for the change record: the BC loader is registered only when the kernel boots. Code that runs without a booted kernel cannot use the old class names at all: they cause a "class not found" error, not a deprecation message. This includes PHPUnit Unit tests (UnitTestCase) in contrib and custom code, and scripts that include autoload.php without bootstrapping Drupal. Kernel, Functional and FunctionalJavascript tests, and normal requests, are not affected. The change record should tell developers to update references in unit tests to the new class names.

Another effect: objects serialized under the old names (for example, in the render cache) unserialize correctly after boot, through the alias, but they trigger deprecation messages until caches are rebuilt.

If this limitation is considered too strict, the alternative precedent is a stub file at the old location that calls class_alias() (see core/lib/Drupal/Core/Serialization/Yaml.php), with a @trigger_error() added. That works without a kernel, but it is not the mechanism core has been using for recent class moves.

The parser

The MR deletes the copy of the parser in AttributeXss::attributes() and reuses Xss::attributes(). Reusing it is right: the two copies have already drifted (Xss also skips srcdoc; the change should get a test). But Xss::attributes() returns strings like href="...", and the new formatSanitizedAttributes() converts them back to name => value pairs. That conversion has two bugs:

  1. The class handling runs inside the loop, so any attribute after class explodes an array: Xss::sanitizeAttributes(['class href' => 'http://example.com']) throws TypeError: explode(): Argument #2 ($string) must be of type string, array given. That is exactly the "mangled name" case the method exists to handle.
  2. Entities are decoded before trim($value, '"'), so a real trailing quote is stripped: ['title' => 'a=b "c"'] returns 'a=b "c'. AttributeXss::sanitizeAttributes() returns 'a=b "c"'.

Instead of converting the strings back, I suggest having one internal parser that collects name => value pairs. The existing protected attributes() becomes a thin wrapper that formats them into its current string output for filter(), and sanitizeAttributes() uses the pairs directly. Please add regression tests for both bugs.

Suggested plan

  1. Move the value classes to Drupal\Component\Utility (deleting the old files) and add the core.moved_classes entries and a change record.
  2. Add Drupal\Component\Utility\HtmlAttributes, and make Drupal\Core\Template\Attribute extend it, keeping only what is listed above under "Must stay in Core".
  3. Fold the parser as described above.
  4. Move sanitizeAttributes() to Xss, using HtmlAttributes, and remove or deprecate Drupal\link\AttributeXss (it is @internal and final).
  5. Port AttributeXssTest to XssTest, and keep DrupalComponentTest passing.

Steps 1 and 2 could be a separate prerequisite issue if that makes review easier: Issue scope guidelines for Drupal core issues.

norman.lol’s picture

Wall of text

benjifisher’s picture

Title: Refactor \Drupal\link\AttributeXss from SA-CORE-2025-004 » [PP-1] Refactor \Drupal\link\AttributeXss from SA-CORE-2025-004
Issue summary: View changes
Status: Needs work » Postponed
Related issues: +#2664570: Move Attribute classes under Drupal\Component

Luckily, @luke.leber pointed me to #2664570: Move Attribute classes under Drupal\Component: my plan to move most of the Attribute class to the Component namespace fits with that issue. I am postponing this issue on that one, and I will try to push that one forward.

@normal.lol:

I am sorry for the length of that comment. My goal was to give enough detail for someone else to implement the plan while I kept the reviewer role, but I could have worked harder to shorten the text.