Editorial HTML as data: safe storage and predictable presentation

A contract for source HTML and sanitized representations in MySQL 8.4: policy versions, a separate candidate, explicit acceptance, and browser-page checks.

A glass filter and ribbons: a conceptual illustration of an allowed document representation.

An author pastes a paragraph with a link, a code sample, and a small table into an editor. The preview looks good, and the document is saved. A month later, the policy for allowed attributes changes. Which body should the reader now receive: the original HTML, the already cleaned string, or the result of processing it again? The answer comes from the stored document's contract.

The article on text escaping separated literal text from permitted markup at output time. Here, time becomes another factor: the source outlives a particular version of the rules. I therefore consider three separate objects: the source document, the accepted sanitized representation, and the page in the browser. This independent teaching example extends one Symfony application; it does not reproduce a working CMS editor or schema.

The source makes the decision reproducible

Source HTML is author input. Even when it comes from a familiar editor, it cannot be inserted directly into a page. Imports, pasting from another document, or a new editor version can introduce a different structure. The source answers “what was submitted,” rather than “what the browser may execute.”

The sanitized representation contains the result of a particular policy. It stores the source hash, the rules' version and hash, and the resulting HTML's hash alongside it. A version is convenient for people; a hash helps detect implementation changes under an unchanged name. This checks provenance inside trusted storage. It is not cryptographic protection against an administrator who can rewrite both data and hashes.

Object Why it is stored Access
Source Reprocessing and author comparison Internal service only; escaped text when inspected
Derived Accepted result of a defined policy Read after provenance checks
Rendered page Reading and interaction HTML response and actual browser behavior

The public route receives only the representation selected by the current pointer. There is no need to place the source in a hidden page element or send it to the client “just in case.” Permission to read an article does not imply permission to edit its original.

Define the vocabulary before the filter

Symfony HTML Sanitizer builds a new structure from allowed elements and attributes. For this example, I define a small vocabulary before execution: h2, h3, paragraphs, emphasis, quotations, lists, pre/code, line breaks, and simple tables. The page title remains a separate text field; an authored h1 inside the body is unnecessary.

Tables allow caption, thead, tbody, tr, th, and td, with the scope attribute on th. Merged cells, arbitrary classes, inline styles, and widths are outside this exercise. This reduces the variations that need explanation and verification. A need for more complex tables is a reason to revisit the contract, rather than allow every attribute at once.

Links keep href only for https; relative addresses, http, javascript, and data are rejected. The link label should remain. The application forces rel to noopener noreferrer and discards an authored target. This policy does not establish that the destination is trustworthy: editorial source review remains a separate task.

Extra div and span wrappers are removed while preserving allowed descendants. An unknown element is dropped with its subtree by default. Scripts, styles, forms, embedded documents, SVG, MathML, and images are outside the vocabulary. Images deliberately have a separate lifecycle here; having a cover does not authorize arbitrary img elements in the body.

Preserve the end of a long article

The source limit is 30,000 UTF-8 bytes. The application checks it before sanitization and rejects the entire save if the document is too large or incorrectly encoded. The author should receive a clear message and retain their input for correction.

This matters because Symfony documents truncation above max_input_length. Silently accepting the beginning of a document is not a successful article save. The sanitizer's internal limit remains a second bound; validation before it determines the behavior of the complete operation. Bytes and visible characters differ: Ukrainian letters may occupy more than one byte.

Empty source is allowed in this lab and produces an empty fragment. That decision is separate from publication readiness. An “article must have content” rule can belong to editorial acceptance, but should not silently change HTML policy.

Saving has one source of truth

The teaching service handles one synthetic document in MySQL 8.4 through native PDO MySQL; its tables use InnoDB. Its first save writes the immutable source, the v1 result, and the current pointer in one data transaction. If the operation is interrupted, the reader should not see a pointer without its document. Reinitializing an existing source is rejected, so the command cannot accidentally overwrite the manuscript.

Before running the service, prepare the schema and separate migrator and data-access accounts, then explicitly run the migrator. Table and constraint creation finishes before the business transaction: MySQL DDL can cause an implicit commit, so this is not an atomic schema upgrade combined with saving the document. The runtime account has no CREATE, ALTER, or DROP privileges; reading a document does not create the schema. This transition does not automatically copy data from the old SQLite store either.

A representation's key depends on the hashes of the source, policy, and result. Building the same candidate again can return the same identity. Before reading, the service checks the stored bytes and their provenance. If the rules or environment have changed, it refuses to display the stale representation; the operator must build and inspect a new candidate. This is deliberately strict and visible behavior for a teaching lab.

The policy hash in this example includes the policy file, component version, and PHP version. A real product needs a stable description of every input affecting the result and managed access to old rules. A dependency update can also change the output without an editorial vocabulary change. This is why provenance should not be reduced to a single v1 string.

New rules produce a candidate

For v1 → v2, I choose a small visible change: a link loses its title attribute while keeping its address and label. Reprocessing reads the original source, creates a separate representation, and leaves the accepted pointer on v1. Cleaning an already sanitized string instead of the original harms reproducibility: previously removed data cannot return from it.

The candidate has its own preview route. The author compares text, table structure, links, and code; a separate acceptance command then changes the pointer. That command requires the identity of the current representation the author saw during review. If another process has changed the selection, stale acceptance is rejected. This narrowly protects the transition; it does not implement draft history or a complete editorial workflow.

The old result is not overwritten. Its version and provenance distinguish it from the new one. Rejecting the candidate requires no source “restoration”: the source never changed. However, a dangerous old policy may need revocation before author review; the product must separately define temporary refusal to serve content and assign responsibility. Keeping every old representation available indefinitely should not be automatic.

Template insertion completes one boundary

The service returns Twig Markup only after checking the derived representation. The template outputs that object into the HTML body and escapes the preview label normally. Twig explains that raw only marks a value safe for escaping. The filter itself does not inspect the document, so unrestricted use on source would break the agreement.

No new HTML from the request is appended to the checked result. Another context—JavaScript, CSS, an attribute, or a text notification—requires a separate representation. One sanitized fragment is not a universal format for every channel.

Fixtures must protect the content too

Expectations are frozen before sanitizer execution. The positive document includes a heading, list, code containing literal <script> text, and a table. Negative cases cover active subtrees, event handlers, forbidden attributes, and addresses with mixed case or an HTML entity in the scheme. Searching for the word script in a string is unsuitable: it can be a legitimate code quotation.

Expectations compare the element tree, text, and addresses. PHP 8.4+ provides Dom\HTMLDocument::createFromString for HTML parsing; its result is not a browser run either. Separate tests must check sanitization idempotence, reconnecting to the same MySQL schema, source immutability, rejection of corrupt derived content, and explicit candidate acceptance. A finite set of examples does not establish complete XSS safety.

Storage checks use actual MySQL 8.4 in a guarded disposable fixture through the shared App\Infrastructure\MysqlLab helper. Setup explicitly runs the migrator; runtime operations and data assertions perform no DDL. Separate native PDO connections share the same schema to check persisted state after reconnection. Checks cover source immutability, rejection of corrupt derived content, and explicit candidate acceptance. This is a finite fixture set, not proof of complete XSS safety or a substitute for browser checks.

One document on two screens

Desktop and mobile should receive the same accepted representation. Different line wrapping is acceptable; a missing table cell or inaccessible link is not. In the browser, compare text, href values, code content, and table structure, then check scrolling, keyboard focus, and element geometry.

A wide table can scroll inside the article region, and long code inside its own block. The reader must reach the last column without shifting the entire page horizontally. Focus must stay visible, and a long token must not hide adjacent text. These are properties of the template and CSS in a real browser; identical HTML bytes cannot establish them.

Browser checks compared accepted v1 before the transition, candidate v2 and accepted v2 after a restart at widths of 1366 and 390 px. Text, code, caption, table rows and cells, link addresses and rel values matched; v2 removed only the link title. On the narrow screen, the table and code scrolled within their own areas without horizontal page overflow, and the last cell was reachable. Tab focused the document area and link with a visible outline. Document routes returned HTTP 200; an auxiliary favicon.ico 404 was recorded separately. This checks these states and sizes, rather than providing a general guarantee of XSS safety or usability.

The contract's practical value emerges during change: the source preserves author intent, the policy defines the permitted representation, and explicit acceptance selects the current result. Browser verification adds the final necessary answer: whether the reader can actually use what the system stored.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

File config/editorial_html.services.yaml:

services:
    _defaults:
        autowire: true
        autoconfigure: true

    app.editorial_html.runtime:
        class: PDO
        arguments:
            $dsn: '%env(DEMO_EDITORIAL_DB_DSN)%'
            $username: '%env(DEMO_EDITORIAL_DB_USER)%'
            $password: '%env(DEMO_EDITORIAL_DB_PASSWORD)%'
            $options:
                !php/const PDO::ATTR_ERRMODE: !php/const PDO::ERRMODE_EXCEPTION
                !php/const PDO::ATTR_DEFAULT_FETCH_MODE: !php/const PDO::FETCH_ASSOC
                !php/const PDO::ATTR_EMULATE_PREPARES: false

    app.editorial_html.migrator:
        class: PDO
        arguments:
            $dsn: '%env(DEMO_EDITORIAL_DB_DSN)%'
            $username: '%env(DEMO_EDITORIAL_DB_MIGRATOR_USER)%'
            $password: '%env(DEMO_EDITORIAL_DB_MIGRATOR_PASSWORD)%'
            $options:
                !php/const PDO::ATTR_ERRMODE: !php/const PDO::ERRMODE_EXCEPTION
                !php/const PDO::ATTR_DEFAULT_FETCH_MODE: !php/const PDO::FETCH_ASSOC
                !php/const PDO::ATTR_EMULATE_PREPARES: false

    App\EditorialHtml\Policy: ~
    App\EditorialHtml\DocumentStore:
        arguments:
            $db: '@app.editorial_html.runtime'
    App\Controller\EditorialHtmlController:
        autowire: true
        autoconfigure: true
        tags: ['controller.service_arguments']
    App\EditorialHtml\HtmlCommand:
        autowire: true
        autoconfigure: true
        arguments:
            $fixturePath: '%kernel.project_dir%/fixtures/editorial-html/article.html'
when@test:
    services:
        App\EditorialHtml\Policy:
            public: true
        App\EditorialHtml\DocumentStore:
            autowire: true
            public: true
            arguments:
                $db: '@app.editorial_html.runtime'

For a local run, create a separate empty schema and two distinct accounts as a MySQL administrator. Replace the placeholders with your own values. Runtime has DML only; supply the migrator only to a separate initialization process. Save runtime variables in untracked .env.local. This example does not transfer data from old SQLite files.

CREATE DATABASE demo_html CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin;
CREATE USER 'demo_html_r'@'127.0.0.1' IDENTIFIED BY '<runtime-password>';
CREATE USER 'demo_html_m'@'127.0.0.1' IDENTIFIED BY '<migrator-password>';
GRANT SELECT, INSERT, UPDATE, DELETE ON demo_html.* TO 'demo_html_r'@'127.0.0.1';
GRANT CREATE, ALTER, INDEX, REFERENCES, SELECT, INSERT, UPDATE, DELETE, TRIGGER ON demo_html.* TO 'demo_html_m'@'127.0.0.1';
DEMO_EDITORIAL_DB_DSN="mysql:host=127.0.0.1;port=3306;dbname=demo_html;charset=utf8mb4"
DEMO_EDITORIAL_DB_USER=demo_html_r
DEMO_EDITORIAL_DB_PASSWORD="<runtime-password>"
read -r -p 'Migrator user: ' DEMO_EDITORIAL_DB_MIGRATOR_USER
read -r -s -p 'Migrator password: ' DEMO_EDITORIAL_DB_MIGRATOR_PASSWORD
printf '
'
export DEMO_EDITORIAL_DB_MIGRATOR_USER DEMO_EDITORIAL_DB_MIGRATOR_PASSWORD
php bin/console app:editorial-html init
unset DEMO_EDITORIAL_DB_MIGRATOR_USER DEMO_EDITORIAL_DB_MIGRATOR_PASSWORD

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/EditorialHtml
  1. Symfony Core Reimporting content: where updates are allowed and where to stop
  2. Symfony Core Editing a published article: how to avoid losing another edit
  3. Symfony Core Twig and untrusted text: handling HTML, links and quotations