Skip to content

Conversation

@NarayanBavisetti
Copy link
Collaborator

@NarayanBavisetti NarayanBavisetti commented Aug 29, 2025

Description

improved the HTML validation by adding custom tags and attributes with proper validation.

Type of Change

  • Improvement (change that would cause existing functionality to not work as expected)

Summary by CodeRabbit

  • New Features

    • Expanded support for rich text: images, mentions, links, emojis, tables, code blocks, callouts, and horizontal rules.
    • Broader link handling: explicit allowance for http/https, mailto, and tel schemes.
  • Bug Fixes

    • Improved HTML sanitization that better preserves safe attributes (including data-*) and blocks unsafe content.
    • Sanitization now reports removed tags/attributes for observability and returns clearer success/failure results.

Copilot AI review requested due to automatic review settings August 29, 2025 14:40
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 29, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds a formal HTML sanitization policy (CUSTOM_TAGS, ALLOWED_TAGS, ATTRIBUTES, SAFE_PROTOCOLS), a diff helper to detect removed tags/attributes, and updates validate_html_content to sanitize via nh3.clean, log removals, and return (is_valid, error_msg, clean_html).

Changes

Cohort / File(s) Summary of Changes
HTML sanitization and validation updates
apps/api/plane/utils/content_validator.py
Added CUSTOM_TAGS, ALLOWED_TAGS (merged with nh3.ALLOWED_TAGS), ATTRIBUTES, and SAFE_PROTOCOLS; implemented _compute_html_sanitization_diff(before_html, after_html); updated validate_html_content to call nh3.clean(..., tags=ALLOWED_TAGS, attributes=ATTRIBUTES, url_schemes=SAFE_PROTOCOLS), log removed tags/attributes via log_exception when present, and return (True, None, clean_html) or (False, "Failed to sanitize HTML", None); minor docstring formatting tweak.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant Validator as validate_html_content
  participant NH3 as nh3.clean
  participant Diff as _compute_html_sanitization_diff
  participant Logger as log_exception

  Caller->>Validator: validate_html_content(html_content)
  Validator->>NH3: clean(html_content, tags=ALLOWED_TAGS, attributes=ATTRIBUTES, url_schemes=SAFE_PROTOCOLS)
  NH3-->>Validator: clean_html
  alt removals detected
    Validator->>Diff: _compute_html_sanitization_diff(html_content, clean_html)
    Diff-->>Validator: {removed_tags, removed_attributes}
    Validator->>Logger: log_exception(JSON_summary, warning=True)
  end
  Validator-->>Caller: (True/False, error_msg|None, clean_html|None)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • dheeru0198

Poem

In my burrow of bytes I nibble the mess,
Snipping stray tags with tidy finesse.
I log tiny crumbs that the sanitizer shied,
Hop-scotch the HTML clean, safe, and wide. 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore-validate-html-validation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@makeplane
Copy link

makeplane bot commented Aug 29, 2025

Pull Request Linked with Plane Work Items

Comment Automatically Generated by Plane

This comment was marked as outdated.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/api/plane/utils/content_validator.py (1)

236-272: Add tests for sanitizer policy (tags, attributes, schemes)

High-risk area; add unit tests covering: img/src retained, a[target+rel] retained, link inert, custom tags preserved, disallowed tags stripped, data: in anchors rejected, size limit path, and diff logging path.

I can scaffold pytest tests for validate_html_content and the diff helper if helpful.

🧹 Nitpick comments (3)
apps/api/plane/utils/content_validator.py (3)

241-243: Return empty string for clean_html on empty input

Stabilizes return types for callers (str vs None).

Apply:

-    if not html_content:
-        return True, None, None
+    if not html_content:
+        return True, None, ""

256-268: Sanitization logging may be noisy

Every removal logs a warning. Consider sampling or demoting to info to avoid log flood on rich documents.

Example:

-        if diff.get("removed_tags") or diff.get("removed_attributes"):
+        # Log only when notable removals occur
+        total_removed = sum(diff.get("removed_tags", {}).values()) + sum(
+            len(v) for v in diff.get("removed_attributes", {}).values()
+        )
+        if total_removed >= 5:
             try:
                 import json

96-98: Comment vs behavior mismatch (“dynamically include all data-*”)

The code doesn’t dynamically include data-* seen in input. Either implement the behavior or adjust the comment to avoid misleading future changes.

I can draft a lightweight pre-scan (bs4) to collect data-* names and union them into MERGED_ATTRIBUTES["*"] per-call if you want.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4293892 and 7a7faaf.

📒 Files selected for processing (2)
  • apps/api/plane/db/models/page.py (1 hunks)
  • apps/api/plane/utils/content_validator.py (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/api/plane/utils/content_validator.py (1)
apps/api/plane/utils/exception_logger.py (1)
  • log_exception (9-20)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
apps/api/plane/db/models/page.py (1)

61-61: Whitespace-only change — safe to merge

No functional impact, no migration needed. Verify your formatter doesn’t fight this in future diffs.

apps/api/plane/utils/content_validator.py (2)

117-121: Attribute case consistency: aspectRatio vs aspectratio

HTML attribute names are case-insensitive and usually lowercased by parsers. Using aspectRatio for some tags and aspectratio for others will drop attributes unexpectedly. Normalize to lowercase (or the exact case your editor serializes).

Would you confirm the actual attribute casing emitted by the editor for image/imageComponent? If it’s lowercase, update those entries accordingly.

Also applies to: 150-150


20-62: Inline data URIs will be flagged by validate_binary_data
The new check rejects any data:<type>/<subtype>;base64 patterns, but we have inline data URIs used for default favicons in apps/api/plane/utils/content_validator.py (lines 146 and 167). Please confirm whether data-URI-based icons should be permitted—if so, we’ll need to whitelist data: URIs or adjust the validator to align with product expectations.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR improves HTML validation by expanding the sanitization capabilities to support custom editor tags and attributes. The changes enhance content validation while providing better observability of sanitization operations.

  • Added custom tag support for editor-specific components (images, mentions, tables, code blocks, etc.)
  • Expanded allowed attributes to include data-* attributes and component-specific properties
  • Introduced diff tracking to log when content is sanitized or removed

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (2)
apps/api/plane/utils/content_validator.py (2)

214-233: Use merged attributes in nh3.clean and gate expensive diff/logging

This repeats earlier feedback; current call still passes ATTRIBUTES and will strip required attrs. Also gate the diff/logging to when content actually changes.

Apply:

-        clean_html = nh3.clean(
+        clean_html = nh3.clean(
             html_content,
             tags=ALLOWED_TAGS,
-            attributes=ATTRIBUTES,
+            attributes=MERGED_ATTRIBUTES,
             url_schemes=ALLOWED_URL_SCHEMES,
         )
-        # Report removals to logger (Sentry) if anything was stripped
-        diff = _compute_html_sanitization_diff(html_content, clean_html)
-        if diff.get("removed_tags") or diff.get("removed_attributes"):
+        # Report removals to logger (Sentry) only if anything was stripped
+        if clean_html != html_content:
+            diff = _compute_html_sanitization_diff(html_content, clean_html)
+            if diff.get("removed_tags") or diff.get("removed_attributes"):
             try:
                 import json

147-147: Remove global allowance for data: URLs

Allowing data: globally enables unsafe anchors (e.g., data:text/html). Remove it now; if inline images are a requirement, reintroduce via a per-attribute allowlist (only data:image/*;base64 for img/src).

Apply:

-ALLOWED_URL_SCHEMES = {"http", "https", "mailto", "tel", "data"}
+ALLOWED_URL_SCHEMES = {"http", "https", "mailto", "tel"}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7a7faaf and abfbd76.

📒 Files selected for processing (1)
  • apps/api/plane/utils/content_validator.py (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/api/plane/utils/content_validator.py (1)
apps/api/plane/utils/exception_logger.py (1)
  • log_exception (9-20)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Lint API
🔇 Additional comments (1)
apps/api/plane/utils/content_validator.py (1)

22-23: Docstring tweak looks good

No issues with clarity.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (4)
apps/api/plane/utils/content_validator.py (4)

118-118: Anchor hardening: preserve rel and enforce safe targets

You added target but not rel; add rel (done above) and consider restricting target to [_self, _blank, _parent, _top] via a small post-pass if needed.


67-87: Do not allow native elements in user content

in body can trigger network fetches and abuse. Remove it from CUSTOM_TAGS.
 CUSTOM_TAGS = {
@@
-    "link",
@@
 }

88-148: Passing ATTRIBUTES as-is overwrites nh3 defaults (breaks core attrs like img[src])

Deep-merge your custom map with nh3.ALLOWED_ATTRIBUTES; also preserve a.rel and drop the separate link entry.

 ATTRIBUTES = {
@@
-    "a": {"href", "target"},
+    "a": {"href", "target", "rel"},
@@
-    "link": {"href", "target"},
@@
     # image-component (from editor extension and seeds)
     "image-component": {"src", "id", "width", "height", "aspectratio", "alignment"},
 }
+
+# Merge nh3 defaults with our custom attributes
+MERGED_ATTRIBUTES = {k: set(v) for k, v in nh3.ALLOWED_ATTRIBUTES.items()}
+for _tag, _attrs in ATTRIBUTES.items():
+    MERGED_ATTRIBUTES.setdefault(_tag, set()).update(_attrs)

Notes:

  • Merging keeps native attrs (src, alt, srcset, etc.) without having to redefine them.
  • If you must support both aspectRatio and aspectratio, keep both intentionally. Otherwise, normalize one casing.

215-233: Use merged attributes, add CSS sanitizer, and avoid unnecessary diffing

Passing ATTRIBUTES drops defaults; also only compute the diff when content changed.

-        clean_html = nh3.clean(
+        clean_html = nh3.clean(
             html_content,
             tags=ALLOWED_TAGS,
-            attributes=ATTRIBUTES,
-            url_schemes=SAFE_PROTOCOLS,
+            attributes=MERGED_ATTRIBUTES,
+            url_schemes=SAFE_PROTOCOLS,
+            css_sanitizer=CSS_SANITIZER if 'CSS_SANITIZER' in globals() else None,
         )
-        # Report removals to logger (Sentry) if anything was stripped
-        diff = _compute_html_sanitization_diff(html_content, clean_html)
-        if diff.get("removed_tags") or diff.get("removed_attributes"):
+        # Report removals to logger (Sentry) only if content changed
+        if clean_html != html_content:
+            diff = _compute_html_sanitization_diff(html_content, clean_html)
+            if diff.get("removed_tags") or diff.get("removed_attributes"):
             try:
                 import json
@@
             log_exception(
                 f"HTML sanitization removals: {summary}",
                 warning=True,
             )
🧹 Nitpick comments (2)
apps/api/plane/utils/content_validator.py (2)

88-101: Comment promises “dynamic data- allow” but it isn’t implemented*

Either implement dynamic inclusion of data-* keys or drop the claim. Right now only the explicit list is allowed.

-        # (wildcards like data-* are NOT supported by nh3; we add known keys
-        # here and dynamically include all data-* seen in the input below)
+        # (wildcards like data-* are NOT supported by nh3; we add known keys here)

153-200: Make diff helper cheap and resilient

  • Skip BeautifulSoup work when there are no sanitizer changes.
  • Short-circuit if bs4 isn’t available.
  • Narrow exceptions only around parsing.
 def _compute_html_sanitization_diff(before_html: str, after_html: str):
@@
-    try:
+    if before_html == after_html:
+        return {"removed_tags": {}, "removed_attributes": {}}
+    if BeautifulSoup is None:
+        return {"removed_tags": {}, "removed_attributes": {}}
+    try:
@@
-        soup_before = BeautifulSoup(before_html or "", "html.parser")
-        soup_after = BeautifulSoup(after_html or "", "html.parser")
+        soup_before = BeautifulSoup(before_html or "", "html.parser")
+        soup_after = BeautifulSoup(after_html or "", "html.parser")
@@
-    except Exception:
+    except Exception:
         # Best-effort only; if diffing fails we don't block the request
         return {"removed_tags": {}, "removed_attributes": {}}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between abfbd76 and ee655b0.

📒 Files selected for processing (1)
  • apps/api/plane/utils/content_validator.py (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Build and lint web apps
🔇 Additional comments (5)
apps/api/plane/utils/content_validator.py (5)

150-150: LGTM: Safe URL protocols

Good hardening by excluding data:. Keep it this way unless you add a per-attribute data: allowlist (e.g., only data:image/... for img).


120-122: Attribute casing: confirm aspectRatio vs aspectratio

You allow camelCase on image/imageComponent and lowercase on image-component. Confirm both are required; otherwise normalize to one to reduce surprises.

Also applies to: 146-148


5-7: bs4 dependency verified
beautifulsoup4==4.12.3 is already pinned in apps/api/requirements/base.txt, so all from bs4 import BeautifulSoup usages are supported.


207-209: Return empty string for empty input to keep return-type stable
Callers expect sanitized_html to be a str when is_valid is True; returning None is inconsistent.

-    if not html_content:
-        return True, None, None
+    if not html_content:
+        return True, None, ""

90-98: Sanitize or disable style attributes
nh3.clean doesn’t accept a Bleach-style CSSSanitizer. Instead, configure your nh3.Cleaner with filter_style_properties (or an attribute_filter) to whitelist/transform allowed CSS, or temporarily disable "style" in your ALLOWED_ATTRIBUTES.

Example refactors:

# apps/api/plane/utils/content_validator.py
-from nh3 import clean
+from nh3 import Cleaner

 # replace your existing clean call...
-cleaned = clean(html, **options)
+cleaner = Cleaner(**options, filter_style_properties={"color", "background", "margin", /* etc */})
+cleaned = cleaner.clean(html)
# apps/api/plane/utils/content_validator.py:90-98
-        "style",
+        # "style",  # re-enable after adding filter_style_properties/attribute_filter

Likely an incorrect or invalid review comment.

@sriramveeraghanta sriramveeraghanta merged commit 9965fc7 into preview Sep 3, 2025
6 of 8 checks passed
@sriramveeraghanta sriramveeraghanta deleted the chore-validate-html-validation branch September 3, 2025 14:26
sriramveeraghanta pushed a commit that referenced this pull request Sep 3, 2025
* chore: improved the html validation

* chore: removed the models changes

* chore: removed extra filters

* chore: changed the protocols
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.

5 participants