Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: escape code blocks for markdown formatting #6089

Merged
merged 1 commit into from
Mar 7, 2025

Conversation

Ice3man543
Copy link
Member

@Ice3man543 Ice3man543 commented Mar 6, 2025

Proposed changes

Does escaping of code blocks

Checklist

  • Pull request is created against the dev branch
  • All checks passed (lint, unit/integration/regression tests etc.) with my changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

  • New Features

    • Improved Markdown code block formatting now escapes special characters and automatically removes conflicting markers, ensuring a cleaner and more consistent display.
  • Bug Fixes

    • Adjustments to report rendering enhance the sanitization of Markdown content, reducing the risk of unintended formatting issues.

@auto-assign auto-assign bot requested a review from dwisiswant0 March 6, 2025 13:06
Copy link
Contributor

coderabbitai bot commented Mar 6, 2025

Walkthrough

The changes add a new utility function for safely formatting Markdown code blocks by escaping backticks and backslashes. The CreateCodeBlock methods in both Markdown and Jira exporters have been updated—one to incorporate escaping via the new function and the other to remove occurrences of "{code}". Additional tests have been introduced to validate the escaping logic and to check for Markdown injection vulnerabilities during report description creation, with necessary import statements added.

Changes

File(s) Change Summary
pkg/.../markdown_formatter.go Added new function escapeCodeBlockMarkdown that escapes backticks and backslashes; updated CreateCodeBlock to use this function; added import for strings.
pkg/.../markdown_utils_test.go Introduced TestEscapeCodeBlockMarkdown with multiple test cases to validate escaping logic (backticks, backslashes, code blocks, etc.).
pkg/.../format_utils_test.go Added TestCreateReportDescription_MarkdownInjection to ensure that report descriptions are sanitized against Markdown injection; added new imports for fmt and output.
pkg/.../jira/jira.go Modified CreateCodeBlock to remove "{code}" from the content using strings.ReplaceAll, ensuring that literal "{code}" strings do not affect output formatting.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant MF as MarkdownFormatter
    participant ESC as escapeCodeBlockMarkdown
    Caller->>MF: Call CreateCodeBlock(content)
    MF->>ESC: Escape backticks and backslashes
    ESC-->>MF: Return escaped content
    MF->>Caller: Return formatted Markdown code block
Loading
sequenceDiagram
    participant Caller as Caller
    participant JF as Jira Formatter
    Caller->>JF: Call CreateCodeBlock(content)
    JF->>JF: Remove "{code}" from content
    JF->>Caller: Return cleaned, formatted code block
Loading

Poem

I'm a hopping rabbit, coding under the moon,
Escaping stray backticks like a merry tune.
Backslashes and glitches I now defuse,
With markdown magic, all errors lose.
My paws tap the keys in springtime delight,
A bunny's code dance in the soft twilight.
🐇✨ Happy hops and bug-free nights!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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

Documentation and Community

  • 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.

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: 0

🧹 Nitpick comments (2)
pkg/reporting/exporters/markdown/util/markdown_formatter.go (1)

31-46: Well-designed escaping function with clear documentation.

The escapeCodeBlockMarkdown function is well-implemented and properly documented, focusing on the minimum set of characters that need escaping for security while preserving readability.

One suggestion for a minor improvement:

func escapeCodeBlockMarkdown(text string) string {
-	minimalChars := []string{
-		"\\", "`",
-	}
+	minimalChars := []string{"\\", "`"}

	result := text
	for _, char := range minimalChars {
		result = strings.ReplaceAll(result, char, "\\"+char)
	}
	return result
}
pkg/reporting/format/format_utils_test.go (1)

52-75: Excellent security test for Markdown injection.

This test is a valuable addition that verifies protection against Markdown injection attacks in the report description. The test correctly checks that malicious payload patterns cannot break out of code blocks.

Minor suggestion: Consider removing the debug print statement on line 71:

	result := CreateReportDescription(event, &util.MarkdownFormatter{}, false)
-	fmt.Println(result)

	require.NotContains(t, result, "```\r\n\r\nReferences:\r\n- https://rce.ee/pwned")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3a3f5e2 and 489760d.

📒 Files selected for processing (4)
  • pkg/reporting/exporters/markdown/util/markdown_formatter.go (3 hunks)
  • pkg/reporting/exporters/markdown/util/markdown_utils_test.go (1 hunks)
  • pkg/reporting/format/format_utils_test.go (2 hunks)
  • pkg/reporting/trackers/jira/jira.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Tests (macOS-latest)
  • GitHub Check: Tests (windows-latest)
  • GitHub Check: Tests (ubuntu-latest)
🔇 Additional comments (6)
pkg/reporting/trackers/jira/jira.go (1)

31-33: Good implementation of content escaping for Jira code blocks.

This change correctly prevents Jira formatting issues by removing any {code} tags that might be present in the content, which could otherwise prematurely close code blocks.

pkg/reporting/exporters/markdown/util/markdown_formatter.go (2)

4-5: Added required import for string operations.

The addition of the strings package is necessary for the new escaping functionality.


14-16: Good implementation of code block content escaping.

The code now properly escapes content passed to code blocks, preventing potential markdown injection vulnerabilities.

pkg/reporting/format/format_utils_test.go (2)

3-5: Added necessary import for new test function.

The fmt package is correctly added for the new test.


11-12: Added necessary import for output package.

This import is required for working with the ResultEvent type in the new test.

pkg/reporting/exporters/markdown/util/markdown_utils_test.go (1)

93-142: Comprehensive test coverage for the escaping function.

Excellent test suite for the escapeCodeBlockMarkdown function with thorough coverage of various edge cases:

  • Regular text without special characters
  • Text with backticks
  • Text with backslashes
  • Text with both backticks and backslashes
  • Complete code blocks
  • Already escaped characters
  • Multiple consecutive backticks

This ensures the escaping logic is robust against various input patterns.

@ehsandeep ehsandeep merged commit d10b7f7 into dev Mar 7, 2025
22 checks passed
@ehsandeep ehsandeep deleted the escaping-markdown-content branch March 7, 2025 09:15
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.

3 participants