Skip to content

🛡️ Sentinel: Fix CSV Injection in log sanitization#222

Merged
abhimehro merged 7 commits intomainfrom
sentinel-csv-injection-fix-4975783286757750034
Feb 16, 2026
Merged

🛡️ Sentinel: Fix CSV Injection in log sanitization#222
abhimehro merged 7 commits intomainfrom
sentinel-csv-injection-fix-4975783286757750034

Conversation

@abhimehro
Copy link
Owner

Fix CSV Injection in log sanitization by preserving quotes for dangerous strings.


PR created automatically by Jules for task 4975783286757750034 started by @abhimehro

**Vulnerability:**
The `sanitize_for_log` function in `main.py` was stripping quotes from `repr()` output for aesthetic reasons. This allowed strings starting with `=`, `+`, `-`, or `@` to be interpreted as formulas if the logs were exported to CSV and opened in spreadsheet software (CSV Injection / Formula Injection).

**Fix:**
Modified `sanitize_for_log` to detect strings starting with these dangerous characters. If detected, the function now retains the surrounding quotes provided by `repr()`, forcing spreadsheet software to treat the value as a string literal.

**Verification:**
- Added `tests/test_csv_injection.py` to verify the fix and ensure regression handling for normal strings.
- Fixed a flaky test in `tests/test_push_rules_perf.py` that was failing due to module reloading issues in the test suite.
- Ran all tests successfully with `pytest`.

**Impact:**
Prevents potential formula execution on administrative machines analyzing logs.

Co-authored-by: abhimehro <84992105+abhimehro@users.noreply.github.com>
@google-labs-jules
Copy link

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

Copilot AI review requested due to automatic review settings February 14, 2026 10:41
@trunk-io
Copy link

trunk-io bot commented Feb 14, 2026

😎 Merged manually by @abhimehro - details.

@github-actions
Copy link

👋 Development Partner is reviewing this PR. Will provide feedback shortly.

@gemini-code-assist
Copy link

Summary of Changes

Hello @abhimehro, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical security vulnerability by implementing a fix for CSV Injection in the sanitize_for_log function. The change ensures that log entries, when potentially viewed in spreadsheet applications, do not inadvertently execute malicious formulas. This significantly enhances the security posture of the logging mechanism by preventing data from being misinterpreted, and it is supported by new unit tests and updated internal documentation.

Highlights

  • CSV Injection Fix: Fixed a CSV Injection vulnerability in the sanitize_for_log function by ensuring that strings starting with dangerous characters (like =, +, -, @) retain their quotes when logged, preventing them from being interpreted as formulas in spreadsheet software.
  • New Test Suite: Introduced a new dedicated test file, tests/test_csv_injection.py, to thoroughly validate the CSV injection prevention logic and ensure proper handling of both dangerous and normal strings.
  • Documentation Update: Updated the internal security documentation (.jules/sentinel.md) with details about the CSV Injection vulnerability, its learning, and the implemented prevention strategy.
Changelog
  • .jules/sentinel.md
    • Added a new entry detailing the CSV Injection vulnerability in sanitize_for_log, including its learning and prevention.
  • main.py
    • Modified the sanitize_for_log function to check for dangerous prefixes (=, +, -, @) at the beginning of input strings.
    • Implemented logic to preserve the repr() output (including quotes) for strings with dangerous prefixes, forcing spreadsheet software to treat them as string literals.
  • tests/test_csv_injection.py
    • Added a new test file to specifically test the CSV injection prevention logic in sanitize_for_log.
    • Included test cases for strings with dangerous prefixes to verify that quotes are correctly preserved.
    • Added test cases for normal strings to confirm that existing quote-stripping behavior is maintained.
    • Included a test for empty input handling.
  • tests/test_push_rules_perf.py
    • Refactored the @patch decorator in test_push_rules_skips_validation_for_existing to use with patch.object for improved mocking context management.
Activity
  • PR created automatically by Jules for task 4975783286757750034, initiated by @abhimehro.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively addresses a CSV injection vulnerability within the log sanitization logic. The core change in main.py correctly preserves quotes for strings that could be misinterpreted as formulas, and the addition of dedicated unit tests in tests/test_csv_injection.py is excellent for ensuring this security fix is robust. I have one minor suggestion to improve the readability and style of the implementation.

Copy link

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 fixes a CSV injection vulnerability in the sanitize_for_log() function by preserving quotes around strings that start with formula-trigger characters (=, +, -, @). When logs are exported to CSV and opened in spreadsheet applications like Excel, these characters can trigger formula execution, potentially leading to code execution or data exfiltration.

Changes:

  • Enhanced sanitize_for_log() to detect and preserve repr() quotes for strings starting with CSV injection characters
  • Added comprehensive test coverage for CSV injection prevention scenarios
  • Documented the vulnerability and prevention strategy in .jules/sentinel.md

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 5 comments.

File Description
main.py Added CSV injection prevention logic to sanitize_for_log() that preserves quotes for dangerous strings
tests/test_csv_injection.py New test file with comprehensive coverage for CSV injection prevention and normal string behavior
.jules/sentinel.md Added documentation of the CSV injection vulnerability, learning points, and prevention approach
tests/test_push_rules_perf.py Refactored test to use context manager pattern instead of decorator-based mocking (unrelated to CSV fix)

Comment on lines +101 to +125
def test_push_rules_skips_validation_for_existing(self):
"""
Test that is_valid_rule is NOT called for rules that are already in existing_rules.
"""
mock_is_valid.return_value = True
hostnames = ["h1", "h2"]
# h1 is already known, h2 is new
existing_rules = {"h1"}

main.push_rules(
self.profile_id,
self.folder_name,
self.folder_id,
self.do,
self.status,
hostnames,
existing_rules,
self.client
)

# h1 is in existing_rules, so we should skip validation for it.
# h2 is NOT in existing_rules, so we should validate it.
# So is_valid_rule should be called EXACTLY once, with "h2".
mock_is_valid.assert_called_once_with("h2")
with patch.object(main, "is_valid_rule") as mock_is_valid:
mock_is_valid.return_value = True
hostnames = ["h1", "h2"]
# h1 is already known, h2 is new
existing_rules = {"h1"}

main.push_rules(
self.profile_id,
self.folder_name,
self.folder_id,
self.do,
self.status,
hostnames,
existing_rules,
self.client
)

# h1 is in existing_rules, so we should skip validation for it.
# h2 is NOT in existing_rules, so we should validate it.
# So is_valid_rule should be called EXACTLY once, with "h2".
mock_is_valid.assert_called_once_with("h2")
Copy link

Copilot AI Feb 14, 2026

Choose a reason for hiding this comment

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

This test refactoring appears unrelated to the CSV injection fix described in the PR title and description. The change from decorator-based @patch("main.is_valid_rule") to context manager with patch.object(main, "is_valid_rule") is a valid refactoring, but it's unclear why it's included in this PR focused on security fixes. Consider moving unrelated refactorings to a separate PR to maintain clear separation of concerns and make reviews easier.

Copilot uses AI. Check for mistakes.
Comment on lines +11 to +64
class TestCSVInjection(unittest.TestCase):
def test_csv_injection_prevention(self):
"""
Verify that sanitize_for_log correctly keeps quotes around strings
that start with characters known to trigger formula execution in spreadsheets
(CSV Injection).
"""
# Test cases for CSV injection characters
dangerous_inputs = [
"=cmd|' /C calc'!A0",
"+cmd|' /C calc'!A0",
"-cmd|' /C calc'!A0",
"@cmd|' /C calc'!A0",
]

for inp in dangerous_inputs:
sanitized = main.sanitize_for_log(inp)
# Should keep quotes (repr adds them)
# repr("=...") -> "'=...'"
# So sanitized should start with ' or "
self.assertTrue(sanitized.startswith("'") or sanitized.startswith('"'),
f"Input '{inp}' should be quoted to prevent CSV injection. Got: {sanitized}")

# Should contain the input
self.assertIn(inp, sanitized)

def test_normal_string_behavior(self):
"""
Verify that normal strings (not starting with =, +, -, @) still have
their outer quotes stripped, preserving existing behavior.
"""
safe_inputs = [
"NormalString",
"Folder Name",
"12345",
"<script>alert(1)</script>", # XSS attempt (handled by repr escaping but checked here for quote stripping)
]

for inp in safe_inputs:
sanitized = main.sanitize_for_log(inp)
# Should NOT start with quote (unless repr escaped something inside and used different quotes, but for simple strings it shouldn't)
# Actually, repr("NormalString") is 'NormalString'. Stripped -> NormalString.
# repr("Folder Name") is 'Folder Name'. Stripped -> Folder Name.
self.assertFalse(sanitized.startswith("'") and sanitized.endswith("'"),
f"Input '{inp}' should have outer quotes stripped. Got: {sanitized}")

# For strict check:
self.assertEqual(sanitized, repr(inp)[1:-1])

def test_empty_input(self):
"""Verify empty input handling."""
self.assertEqual(main.sanitize_for_log(""), "")
self.assertEqual(main.sanitize_for_log(None), "None")

Copy link

Copilot AI Feb 14, 2026

Choose a reason for hiding this comment

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

Missing test coverage for edge cases: The tests don't cover scenarios where dangerous CSV injection characters might appear after sanitization steps like token redaction or basic auth removal. For example, if a TOKEN value is "=secret" and appears at the start of a string, after redaction it becomes "[REDACTED]" which starts with a safe character. However, if a string like "prefix=secret" has "prefix" redacted to become "=secret", the dangerous character is exposed. Consider adding tests that verify the interaction between redaction and CSV injection prevention.

Copilot uses AI. Check for mistakes.
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@github-actions
Copy link

👋 Development Partner is reviewing this PR. Will provide feedback shortly.

abhimehro and others added 2 commits February 14, 2026 15:35
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@github-actions
Copy link

👋 Development Partner is reviewing this PR. Will provide feedback shortly.

1 similar comment
@github-actions
Copy link

👋 Development Partner is reviewing this PR. Will provide feedback shortly.

@github-actions
Copy link

👋 Development Partner is reviewing this PR. Will provide feedback shortly.

@github-actions
Copy link

👋 Development Partner is reviewing this PR. Will provide feedback shortly.

@abhimehro abhimehro merged commit e65488f into main Feb 16, 2026
8 of 11 checks passed
@github-actions
Copy link

👋 Development Partner is reviewing this PR. Will provide feedback shortly.

@abhimehro abhimehro deleted the sentinel-csv-injection-fix-4975783286757750034 branch February 16, 2026 02:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants