Postponed
Project:
Drupal core
Version:
main
Component:
link.module
Priority:
Normal
Category:
Task
Assigned:
Unassigned
Reporter:
Created:
24 Mar 2025 at 10:10 UTC
Updated:
11 Oct 2026 at 16:58 UTC
Jump to comment: Most recent
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.
Code in question: https://git.drupalcode.org/project/drupal/-/commit/b112cf535a8edd5a981c2...
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 {
tbc
tbc
tbc
tbc
tbc
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
Comment #2
larowlanIn 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.
Comment #5
dcam commentedIt's currently failing
Drupal\Tests\Component\DrupalComponentTest::testNoCoreInComponent()with the error:I assume it's because we use
Drupal\Core\Template\Attributein the moved function.Comment #7
benjifisherThere is an active MR, so the issue status should not be Active. There are failing tests, so I am setting the status to NW.
Comment #8
dcam commentedsanitizeAttributes()creates an instance ofDrupal\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 movesanitizeAttributes()into the XSS utility as-is.Comment #9
benjifisherI 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.
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
Xssclass. That would not have solved the problem of code drift going forward.My second prompt:
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:
My final prompt. It turns out that
core.moved_classeshas been used several times; all but one use have been removed as part of the deprecation/removal strategy.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:
HtmlAttributesThe classes have to live in
Drupal\Component\Utility(thedrupal/core-utilitypackage), next toXss. They cannot useDrupal\Component\Render(thedrupal/core-renderpackage) because that would cause a circular dependency. The only use ofComponent\Renderin the moved code isPlainTextOutput::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 recommendDrupal\Component\Utility\HtmlAttributes, with the value classes named to match:Drupal\Core\Template\AttributeValueBase→Drupal\Component\Utility\HtmlAttributeValueBaseDrupal\Core\Template\AttributeString→Drupal\Component\Utility\HtmlAttributeStringDrupal\Core\Template\AttributeArray→Drupal\Component\Utility\HtmlAttributeArrayDrupal\Core\Template\AttributeBoolean→Drupal\Component\Utility\HtmlAttributeBooleanThis also avoids
use ... as ...as inPluginBase(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 usingcore.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,
HtmlAttributeswould createHtmlAttributeArrayobjects, and contrib code that checks$attributes['class'] instanceof \Drupal\Core\Template\AttributeArraywould silently start gettingFALSE. With an alias, the check still passes.Core references to update:
core/lib/Drupal/Core/Htmx/Htmx.phpandcore/modules/system/tests/src/Unit/Pager/PreprocessPagerTest.php.HtmlAttributes(Component) andAttribute(Core)Unlike the value classes, the Core
Attributeclass adds real functionality and should stay (not deprecated). It is also the class that every theme and module creates withnew Attribute(), and the class allowed byTwigSandboxPolicy(which usesinstanceof, so it keeps working).Required in
HtmlAttributesfor this issue (allXss::sanitizeAttributes()needs is(string) new HtmlAttributes($values)):$storageproperty (alreadyprotected, so render-cache entries serialized before the change still unserialize)__construct()offsetSet()createAttributeValue()(withPlainTextOutput::renderFromHtml()inlined, as explained above)__toString()Must stay in Core
Attribute:implements MarkupInterface, together withjsonSerialize(), whichMarkupInterfacerequires through\JsonSerializable. Twig autoescaping trustsMarkupInterfaceobjects; without it,{{ attributes }}would be HTML-escaped. The interface is inComponent\Render, soHtmlAttributescannot implement it (see the circular dependency above).__toString()that carries#[JsonSchema(...)]and returnsparent::__toString().JsonSchemais a Core class, and PHP attributes are not inherited.merge(Attribute $collection). If this moved toHtmlAttributeswith the parameter type widened toHtmlAttributes, any contrib subclass that overridesmerge(\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
HtmlAttributesso that the implementation lives in one place. None of them depend on Core; the only dependency isDrupal\Component\Utility\NestedArray.offsetGet(),offsetUnset(),offsetExists(),getIterator()(withimplements \ArrayAccess, \IteratorAggregatemoving toHtmlAttributes)addClass(),removeClass(),getClass(),hasClass()setAttribute(),hasAttribute(),removeAttribute()toArray(),storage(),__clone()Splitting the
ArrayAccessmethods between the two classes (onlyoffsetSet()in Component) would be awkward, which is another reason to move the whole group.About
core.moved_classesThis 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.ymlhas a single entry.core.moved_classesincore/core.services.yml, orMODULE.moved_classesin a module's*.services.yml.BackwardsCompatibilityClassLoaderPassmerges them into amoved_classesparameter.DrupalKernel::boot(),Drupal\Core\ClassLoader\BackwardsCompatibilityClassLoaderis registered withspl_autoload_register(). When the autoloader cannot find an old class name, this loader callsclass_alias($new, $old).deprecation_version,removed_versionandchange_record, the loader first triggers the standard message: "Class %s is deprecated in %s and is removed from %s, use %s instead. See %s".For this issue, the entries would look like this (versions to be decided):
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 includeautoload.phpwithout 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()(seecore/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 reusesXss::attributes(). Reusing it is right: the two copies have already drifted (Xssalso skipssrcdoc; the change should get a test). ButXss::attributes()returns strings likehref="...", and the newformatSanitizedAttributes()converts them back toname => valuepairs. That conversion has two bugs:classhandling runs inside the loop, so any attribute afterclassexplodes an array:Xss::sanitizeAttributes(['class href' => 'http://example.com'])throwsTypeError: explode(): Argument #2 ($string) must be of type string, array given. That is exactly the "mangled name" case the method exists to handle.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 => valuepairs. The existing protectedattributes()becomes a thin wrapper that formats them into its current string output forfilter(), andsanitizeAttributes()uses the pairs directly. Please add regression tests for both bugs.Suggested plan
Drupal\Component\Utility(deleting the old files) and add thecore.moved_classesentries and a change record.Drupal\Component\Utility\HtmlAttributes, and makeDrupal\Core\Template\Attributeextend it, keeping only what is listed above under "Must stay in Core".sanitizeAttributes()toXss, usingHtmlAttributes, and remove or deprecateDrupal\link\AttributeXss(it is@internalandfinal).AttributeXssTesttoXssTest, and keepDrupalComponentTestpassing.Steps 1 and 2 could be a separate prerequisite issue if that makes review easier: Issue scope guidelines for Drupal core issues.
Comment #10
norman.lolWall of text
Comment #11
benjifisherLuckily, @luke.leber pointed me to #2664570: Move Attribute classes under Drupal\Component: my plan to move most of the
Attributeclass 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.