Skip to content
ERPForAll DocsDevelopment

    HTML sanitising: the removal report and strict mode

    The engine provides cleaning and strict validation. The FIELDS integration adds final registry policies and transaction-scoped field diagnostics. Transport delivery and the form adapter are separate integration work; this page does not claim a deployed editor.

    erp_html::sanitize(input, &policy, &limits, mode) returns a SanitizeResult: the cleaned markup and a RemovalReport saying what the policy took out.

    result.report() (or into_parts().1) is a RemovalReport. Its entries are grouped by (kind, name, reason):

    • RemovalKind: Tag, Attribute, Css, Url, Comment.
    • name: lower-case tag, attribute or CSS property name; (invalid) when the name is not a usable identifier; conditional or unstable for comments. Removed values (bodies, URLs, style text) are never copied into the report.
    • count: how many times it happened. sample_locations(): the one-based document-order ordinal of the node being visited, for the first few occurrences only (default 8, host-lowerable with Limits::with_report_samples). The DOM keeps no source offsets. The generated fragment root is normally skipped; if it carries retained attributes, those are reported first at ordinal 1 and the children follow. Tokens the parser discards before building the DOM are not collector events.

    Entries come in order of first encounter, so the same input gives the same report. Only the first cleaning pass reports; the reparse gate’s second pass never adds entries.

    Harmless canonicalisation is not reported: the html and body wrappers of the HTML namespace, doctype, parser repair of tag soup, ordinary comments, and comment-only or whitespace-only fragments (which serialise as empty without a report). Within style attributes, empty or whitespace-only declarations (such as style="" or style=" ; "), empty style attributes resulting from them, and CSS comments inside style values (e.g. /* ... */) are likewise dropped as formatting canonicalisation rather than reported removals. A foreign-content element that happens to be named html (inside <svg>) is a reported removal. Attributes discarded with an unwrapped element are also reported: event handlers use EventHandler, unknown attributes use ForbiddenAttribute, and otherwise allowed attributes use RemovedWithElement. Killed subtrees are represented by their root removal; their descendants are not visited. An earlier CSS declaration dropped because a later one overrides it is reported as DuplicateCss.

    use erp_html::{sanitize, DefaultPolicy, HtmlSanitizeError, Limits, SanitizeMode, SanitizePolicy};
    let policy = SanitizePolicy::Default(DefaultPolicy::new());
    let limits = Limits::ceiling();
    let clean = sanitize("<p onclick=\"x()\">hello</p>", &policy, &limits, SanitizeMode::Clean)?;
    assert_eq!(clean.output().as_str(), "<p>hello</p>");
    let rejected = sanitize("<p onclick=\"x()\">hello</p>", &policy, &limits, SanitizeMode::Strict);
    assert_eq!(rejected, Err(HtmlSanitizeError::DisallowedContent { report: clean.report().clone() }));
    # Ok::<(), HtmlSanitizeError>(())

    Strict means “nothing was removed by policy”. The rejection carries the same report Clean would have returned. Budget and report-limit failures keep their own error kinds and win over strict rejection. Mapping the rejection to a user-facing validation error belongs to the FIELDS slice.

    Limits::with_report_bytes (ceiling 1,000,000) bounds the size of the aggregated report. Repeats of one feature raise its count and retain samples up to the sample cap. A lowered byte budget can be exceeded by a new entry or sample; the result is HtmlSanitizeError::ReportTooLarge { limit }, never a truncated report. The report is also charged against the shared working_bytes and work_units budgets.

    #[field(html)] selects the default sanitizer. Native and owned declarations can use html_policy(HtmlPolicy::Sanitize(HtmlSanitizePolicy::Default(HtmlDefaultPolicy::new()))); the SDK reexports these policy types. The with_strip_classes, with_sanitize_style, with_strip_style and with_xml_output builders only strengthen or format that policy. #[field(html, sanitize = false)] stores untrusted text, still bounded and NUL-checked. Its description says sanitized=false and html_render_mode=sandbox; it must never be inserted into a live markup sink. Sanitized storage is not a browser trust capability either.

    Host create/write, translated updates, saved defaults, compute output, virtual records, upsert and the translation importer (.po and data-file translations) admit HTML before publishing or storing values. The importer uses the transaction’s mode and retains its reports with the translation language; it admits every imported value, also one the overwrite mode then does not store, so its reports and strict refusals cover those values too. A transaction retains each nonempty report with model, field and optional translation language. tx.html_reports() borrows them; tx.take_html_reports() transfers them. Take reports inside an Orm::run closure before commit, outside any savepoint or onchange (taking them there is a programming error, because what is inside may still be rolled back), and publish them only after the operation commits successfully. An onchange admits draft values and drops their reports when it ends. Commit, rollback and reset clear the transaction channel. Savepoint rollback drops reports created within that savepoint; reports already taken are never resurrected. A retried operation must return only the successful attempt’s reports.

    The transaction channel refuses writes when retained diagnostics exceed 1,000,000 bytes; it does not truncate entries. Engine limits still apply to each input. This is an admission limit, not a performance claim. tx.require_strict_html() only increases rejection for the rest of the attempt, including across savepoint rollback. Strict failures retain the engine’s typed HtmlSanitizeError source, including its removal report, and validation failures cannot be committed as successful writes.

    The legacy erp_fields::convert::{to_cell,validate_cell} APIs return only a cell, so HTML uses strict default validation there. To clean and preserve diagnostics, call erp_fields::html::{convert_value,convert_cell} and consume both HtmlConversion::into_parts() components. A returned cell alone is not an operation result and does not grant rendering trust.

    Named presets, including email_outgoing, remain unavailable for now. WASM declarations refuse presets and sanitize overrides by name; native policy types cannot represent tag/attribute/form/comment relaxations. This does not claim the complete SPEC-HTML-050 preset error taxonomy or properties integration. Generic RPC/import/job/mail report delivery still needs INTEGRATE; callers must not discard the transaction report channel or claim that ORM admission alone completes their protocol.