Skip to content

Conversation

@meatsnails
Copy link
Collaborator

@meatsnails meatsnails commented Dec 30, 2025

Pull Request

Description

If your PR is related to an issue, please include the issue number below:

Related Issue: Closes #1125 #786

Type of Change:

  • Bug fix (non-breaking change which fixes an issue)

Guidelines

  • My code follows the style guidelines of this project (formatted with Ruff)

  • I have performed a self-review of my own code

  • I have commented my code, particularly in hard-to-understand areas

  • I have made corresponding changes to the documentation if needed

  • My changes generate no new warnings

  • I have tested this change

  • Any dependent changes have been merged and published in downstream modules

  • I have added all appropriate labels to this PR

  • I have followed all of these guidelines.

How Has This Been Tested? (if applicable)

tested by sending various messages with the problems described in the issues (see screenshots)

Screenshots (if applicable)

image

Additional Information

"rm -rf ." wouldn't work on pretty much any linux and or unix-like system but i left it in just incase (and it keeps the code cleaner)

Summary by Sourcery

Tighten harmful command detection for dangerous rm usages to cover additional edge cases.

Bug Fixes:

  • Ensure harmful-command detection only triggers on rm as a standalone command token.
  • Expand detection of dangerous rm targets to include paths starting with a dot (e.g., ./).

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Dec 30, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Tightens the harmful shell command detector for destructive rm invocations by making the rm token match more precise and expanding the set of root-like path prefixes that are treated as dangerous.

Sequence diagram for harmful command detection during message handling

sequenceDiagram
    actor User
    participant ChatClient
    participant Server
    participant HarmfulCommandDetector

    User->>ChatClient: Send message
    ChatClient->>Server: Submit message content
    Server->>HarmfulCommandDetector: check_message(message_text)
    HarmfulCommandDetector->>HarmfulCommandDetector: apply_regex_for_rm_detection
    alt matches_dangerous_rm
        HarmfulCommandDetector-->>Server: result(harmful=True)
        Server-->>ChatClient: block_or_warn_user
    else no_dangerous_rm
        HarmfulCommandDetector-->>Server: result(harmful=False)
        Server-->>ChatClient: accept_and_display_message
    end
Loading

Flow diagram for updated harmful rm command regex logic

flowchart TD
    A[Start harmful rm detection] --> B[Input shell_like text]
    B --> C{Match privilege prefix?}
    C -->|sudo/doas/run0 or none| D[Match rm token with word boundaries: \brm\b]
    D --> E{Match rm options?}
    E -->|yes or none| F{Match dangerous path prefix?}
    F -->|/ or ∕ or ~ or /. or *| G[Dangerous path detected]
    F -->|/bin,/boot,/etc,/lib,/proc,/rooin,/sys,/tmp,/usr,/var,/var/log,/network.,/system| G
    G --> H[Flag message as harmful]
    F -->|no match| I[No dangerous rm detected]
    H --> J[End]
    I --> J
Loading

File-Level Changes

Change Details Files
Improve precision of rm command matching in the harmful command regex.
  • Require rm to be matched as a standalone word using word boundaries to avoid flagging commands where rm appears as a substring.
  • Preserve existing optional privilege-escalation prefixes and rm option handling around the command token.
src/tux/plugins/atl/harmfulcommands.py
Broaden detection of dangerous target paths for rm commands.
  • Extend the root/home indicator character class to also treat paths starting with a dot as dangerous (e.g., ./, .config).
  • Keep existing coverage of path prefixes like /, ∕, ~, and wildcard targets while still flowing into the critical system paths portion of the regex.
src/tux/plugins/atl/harmfulcommands.py

Assessment against linked issues

Issue Objective Addressed Explanation
#1125 Detect and warn on variants of the rm -rf command that use a leading ./ (e.g., sudo rm -rf ./*) so they are treated as harmful like the root / version.

Possibly linked issues

  • Warning bypass #1125: The PR refines the harmfulcommands regex, directly improving harmful command detection as requested in the issue.
  • #: PR refines the harmful command regex for rm, directly addressing the false positive edge cases described in the issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link

coderabbitai bot commented Dec 30, 2025

Caution

Review failed

The pull request is closed.

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

Require whole-word matching for "rm" and extend the dangerous-rm pattern to recognize dot-prefixed relative paths (e.g., ./ or ../) so additional rm variants are detected.

Changes

Cohort / File(s) Summary
Harmful Command Detection Regex Updates
src/tux/plugins/atl/harmfulcommands.py
Updated DANGEROUS_RM_COMMANDS: replaced r"rm\s+" with r"\brm\b\s+" to require whole-word rm; expanded root/home indicator from `r"(?:[/\∕~]\s*

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Corrected some edge cases' is vague and does not clearly indicate the specific changes being made to the harmfulcommands module. Consider a more specific title like 'fix(harmfulcommands): Improve rm command detection with word boundaries and dot-prefixed paths' to better convey the nature of the regex fixes.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed The pull request description is comprehensive and related to the changeset, providing context about the bug fixes, testing approach, and linking to related issues.
Linked Issues check ✅ Passed The pull request successfully addresses issue #1125 by expanding rm detection to include dot-prefixed paths like './' and improving detection with word boundaries.
Out of Scope Changes check ✅ Passed All changes are focused on improving the dangerous rm command detection regex patterns, directly aligned with the linked issue requirements.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a5a1826 and fc3dd4b.

📒 Files selected for processing (1)
  • src/tux/plugins/atl/harmfulcommands.py

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • Including . in the [/\∕~/.] character class makes any rm on a dot-prefixed path (e.g., rm .bashrc) match as “harmful”; if the intent is to catch rm -rf . / ./ specifically, consider a more targeted pattern like (?:\./|\s+\.) instead of a bare . in the character class to avoid false positives.
  • Since the behavior of rm -rf . is nuanced across systems and shells, it would be helpful to encode the assumption about treating . as dangerous directly in a short code comment near the regex, so future changes don’t accidentally widen or narrow that behavior.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Including `.` in the `[/\∕~/.]` character class makes any `rm` on a dot-prefixed path (e.g., `rm .bashrc`) match as “harmful”; if the intent is to catch `rm -rf .` / `./` specifically, consider a more targeted pattern like `(?:\./|\s+\.)` instead of a bare `.` in the character class to avoid false positives.
- Since the behavior of `rm -rf .` is nuanced across systems and shells, it would be helpful to encode the assumption about treating `.` as dangerous directly in a short code comment near the regex, so future changes don’t accidentally widen or narrow that behavior.

## Individual Comments

### Comment 1
<location> `src/tux/plugins/atl/harmfulcommands.py:28-29` </location>
<code_context>
     r"(?:-[frR]+|--force|--recursive|--no-preserve-root|\s+)*"
     # Root/home indicators
-    r"(?:[/\∕~]\s*|\*|"  # noqa: RUF001
+    r"(?:[/\∕~/.]\s*|\*|"  # noqa: RUF001
     # Critical system paths
     r"/(?:bin|boot|etc|lib|proc|rooin|sys|tmp|usr|var(?:/log)?|network\.|system))"
</code_context>

<issue_to_address>
**suggestion (bug_risk):** The added `.` in the character class makes the rule very broad and will flag benign commands like `rm .foo` or `rm .`.

Including `.` in this class makes any `rm` of hidden files or `.` itself count as harmful, which is much broader than the prior `/ ∕ ~` behavior. If you mainly want to catch `./` and `../`, consider matching those explicitly (e.g., `r"(?:[/\∕~]|\.(?:/|\.))."`) instead of treating any leading `.` as a root indicator, to avoid false positives like `rm .gitignore` or `rm ./*.log`.

```suggestion
    # Root/home indicators
    r"(?:[/\∕~]\s*|\.(?:/|\.)\s*|\*|"  # noqa: RUF001
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@sentry
Copy link

sentry bot commented Dec 30, 2025

❌ 1 Tests Failed:

Tests completed Failed Passed Skipped
421 1 420 69
View the full list of 1 ❄️ flaky test(s)
tests/database/test_database_migrations.py::TestSchemaErrorHandlingThroughService::test_operations_on_disconnected_service

Flake rate in main: 100.00% (Passed 0 times, Failed 2 times)

Stack Traces | 0.009s run time
.venv/lib/python3.13.../sqlalchemy/engine/base.py:143: in __init__
    self._dbapi_connection = engine.raw_connection()
                             ^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/engine/base.py:3309: in raw_connection
    return self.pool.connect()
           ^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:447: in connect
    return _ConnectionFairy._checkout(self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:1264: in _checkout
    fairy = _ConnectionRecord.checkout(pool)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:711: in checkout
    rec = pool._do_get()
          ^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/impl.py:177: in _do_get
    with util.safe_reraise():
         ^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/util/langhelpers.py:224: in __exit__
    raise exc_value.with_traceback(exc_tb)
.venv/lib/python3.13.../sqlalchemy/pool/impl.py:175: in _do_get
    return self._create_connection()
           ^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:388: in _create_connection
    return _ConnectionRecord(self)
           ^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:673: in __init__
    self.__connect()
.venv/lib/python3.13.../sqlalchemy/pool/base.py:899: in __connect
    with util.safe_reraise():
         ^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/util/langhelpers.py:224: in __exit__
    raise exc_value.with_traceback(exc_tb)
.venv/lib/python3.13.../sqlalchemy/pool/base.py:895: in __connect
    self.dbapi_connection = connection = pool._invoke_creator(self)
                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/engine/create.py:661: in connect
    return dialect.connect(*cargs, **cparams)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/engine/default.py:630: in connect
    return self.loaded_dbapi.connect(*cargs, **cparams)  # type: ignore[no-any-return]  # NOQA: E501
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../dialects/postgresql/psycopg.py:812: in connect
    await_only(creator_fn(*arg, **kw))
.venv/lib/python3.13.../sqlalchemy/util/_concurrency_py3k.py:132: in await_only
    return current.parent.switch(awaitable)  # type: ignore[no-any-return,attr-defined] # noqa: E501
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/util/_concurrency_py3k.py:196: in greenlet_spawn
    value = await result
            ^^^^^^^^^^^^
.venv/lib/python3.13....../site-packages/psycopg/connection_async.py:145: in connect
    raise type(last_ex)("\n".join(lines)).with_traceback(None)
E   psycopg.OperationalError: connection failed: connection to server at "127.0.0.1", port 5432 failed: Connection refused
E   	Is the server running on that host and accepting TCP/IP connections?
E   Multiple connection attempts failed. All failures were:
E   - host: 'localhost', port: 5432, hostaddr: '::1': connection failed: connection to server at "::1", port 5432 failed: Connection refused
E   	Is the server running on that host and accepting TCP/IP connections?
E   - host: 'localhost', port: 5432, hostaddr: '127.0.0.1': connection failed: connection to server at "127.0.0.1", port 5432 failed: Connection refused
E   	Is the server running on that host and accepting TCP/IP connections?

The above exception was the direct cause of the following exception:
tests/database/test_database_migrations.py:310: in test_operations_on_disconnected_service
    await guild_controller.create_guild(guild_id=TEST_GUILD_ID)
.../database/controllers/guild.py:67: in create_guild
    return await self.create(id=guild_id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.../controllers/base/base_controller.py:141: in create
    return await self._crud.create(**kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.../controllers/base/crud.py:43: in create
    await session.commit()
.venv/lib/python3.13.../ext/asyncio/session.py:1000: in commit
    await greenlet_spawn(self.sync_session.commit)
.venv/lib/python3.13.../sqlalchemy/util/_concurrency_py3k.py:201: in greenlet_spawn
    result = context.throw(*sys.exc_info())
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/orm/session.py:2030: in commit
    trans.commit(_to_root=True)
<string>:2: in commit
    ???
.venv/lib/python3.13.../sqlalchemy/orm/state_changes.py:137: in _go
    ret_value = fn(self, *arg, **kw)
                ^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/orm/session.py:1311: in commit
    self._prepare_impl()
<string>:2: in _prepare_impl
    ???
.venv/lib/python3.13.../sqlalchemy/orm/state_changes.py:137: in _go
    ret_value = fn(self, *arg, **kw)
                ^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/orm/session.py:1286: in _prepare_impl
    self.session.flush()
.venv/lib/python3.13.../sqlalchemy/orm/session.py:4331: in flush
    self._flush(objects)
.venv/lib/python3.13.../sqlalchemy/orm/session.py:4466: in _flush
    with util.safe_reraise():
         ^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/util/langhelpers.py:224: in __exit__
    raise exc_value.with_traceback(exc_tb)
.venv/lib/python3.13.../sqlalchemy/orm/session.py:4427: in _flush
    flush_context.execute()
.venv/lib/python3.13.../sqlalchemy/orm/unitofwork.py:466: in execute
    rec.execute(self)
.venv/lib/python3.13.../sqlalchemy/orm/unitofwork.py:642: in execute
    util.preloaded.orm_persistence.save_obj(
.venv/lib/python3.13.../sqlalchemy/orm/persistence.py:68: in save_obj
    ) in _organize_states_for_save(base_mapper, states, uowtransaction):
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/orm/persistence.py:223: in _organize_states_for_save
    for state, dict_, mapper, connection in _connections_for_states(
.venv/lib/python3.13.../sqlalchemy/orm/persistence.py:1759: in _connections_for_states
    connection = uowtransaction.transaction.connection(base_mapper)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
<string>:2: in connection
    ???
.venv/lib/python3.13.../sqlalchemy/orm/state_changes.py:137: in _go
    ret_value = fn(self, *arg, **kw)
                ^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/orm/session.py:1037: in connection
    return self._connection_for_bind(bind, execution_options)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
<string>:2: in _connection_for_bind
    ???
.venv/lib/python3.13.../sqlalchemy/orm/state_changes.py:137: in _go
    ret_value = fn(self, *arg, **kw)
                ^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/orm/session.py:1173: in _connection_for_bind
    conn = self._parent._connection_for_bind(
<string>:2: in _connection_for_bind
    ???
.venv/lib/python3.13.../sqlalchemy/orm/state_changes.py:137: in _go
    ret_value = fn(self, *arg, **kw)
                ^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/orm/session.py:1187: in _connection_for_bind
    conn = bind.connect()
           ^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/engine/base.py:3285: in connect
    return self._connection_cls(self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/engine/base.py:145: in __init__
    Connection._handle_dbapi_exception_noconnection(
.venv/lib/python3.13.../sqlalchemy/engine/base.py:2448: in _handle_dbapi_exception_noconnection
    raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
.venv/lib/python3.13.../sqlalchemy/engine/base.py:143: in __init__
    self._dbapi_connection = engine.raw_connection()
                             ^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/engine/base.py:3309: in raw_connection
    return self.pool.connect()
           ^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:447: in connect
    return _ConnectionFairy._checkout(self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:1264: in _checkout
    fairy = _ConnectionRecord.checkout(pool)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:711: in checkout
    rec = pool._do_get()
          ^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/impl.py:177: in _do_get
    with util.safe_reraise():
         ^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/util/langhelpers.py:224: in __exit__
    raise exc_value.with_traceback(exc_tb)
.venv/lib/python3.13.../sqlalchemy/pool/impl.py:175: in _do_get
    return self._create_connection()
           ^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:388: in _create_connection
    return _ConnectionRecord(self)
           ^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/pool/base.py:673: in __init__
    self.__connect()
.venv/lib/python3.13.../sqlalchemy/pool/base.py:899: in __connect
    with util.safe_reraise():
         ^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/util/langhelpers.py:224: in __exit__
    raise exc_value.with_traceback(exc_tb)
.venv/lib/python3.13.../sqlalchemy/pool/base.py:895: in __connect
    self.dbapi_connection = connection = pool._invoke_creator(self)
                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/engine/create.py:661: in connect
    return dialect.connect(*cargs, **cparams)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/engine/default.py:630: in connect
    return self.loaded_dbapi.connect(*cargs, **cparams)  # type: ignore[no-any-return]  # NOQA: E501
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../dialects/postgresql/psycopg.py:812: in connect
    await_only(creator_fn(*arg, **kw))
.venv/lib/python3.13.../sqlalchemy/util/_concurrency_py3k.py:132: in await_only
    return current.parent.switch(awaitable)  # type: ignore[no-any-return,attr-defined] # noqa: E501
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../sqlalchemy/util/_concurrency_py3k.py:196: in greenlet_spawn
    value = await result
            ^^^^^^^^^^^^
.venv/lib/python3.13....../site-packages/psycopg/connection_async.py:145: in connect
    raise type(last_ex)("\n".join(lines)).with_traceback(None)
E   sqlalchemy.exc.OperationalError: (psycopg.OperationalError) connection failed: connection to server at "127.0.0.1", port 5432 failed: Connection refused
E   	Is the server running on that host and accepting TCP/IP connections?
E   Multiple connection attempts failed. All failures were:
E   - host: 'localhost', port: 5432, hostaddr: '::1': connection failed: connection to server at "::1", port 5432 failed: Connection refused
E   	Is the server running on that host and accepting TCP/IP connections?
E   - host: 'localhost', port: 5432, hostaddr: '127.0.0.1': connection failed: connection to server at "127.0.0.1", port 5432 failed: Connection refused
E   	Is the server running on that host and accepting TCP/IP connections?
E   (Background on this error at: https://sqlalche..../e/20/e3q8)

To view more test analytics, go to the [Prevent Tests Dashboard](https://All Things Linux.sentry.io/prevent/tests/?preventPeriod=30d&integratedOrgName=allthingslinux&repository=tux&branch=meatsnails%2Ftux%3Amain)

Copy link

@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 (1)
src/tux/plugins/atl/harmfulcommands.py (1)

29-29: Fix successfully addresses issue #1125, but consider removing duplicate character.

The addition of . to the character class correctly fixes the bypass issue by now matching patterns like ./, ./*, etc. However, the character class [/\∕~/.] contains the forward slash / twice (positions 1 and 4), which is redundant.

🔎 Proposed cleanup to remove duplicate
-    r"(?:[/\∕~/.]\s*|\*|"  # noqa: RUF001
+    r"(?:[/\∕~.]\s*|\*|"  # noqa: RUF001
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f78fb5c and cd56624.

📒 Files selected for processing (1)
  • src/tux/plugins/atl/harmfulcommands.py
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Use strict type hints with Type | None instead of Optional[Type]
Use NumPy docstrings for documenting functions and classes
Prefer absolute imports; relative imports allowed only within the same module
Organize imports in order: stdlib → third-party → local
Use 88 character line length
Use snake_case for functions and variables, PascalCase for classes, UPPER_CASE for constants
Always add imports to the top of the file unless absolutely necessary
Use async/await for I/O operations
Use custom exceptions for business logic with context logging and meaningful user messages
Use Pydantic for data validation
Keep files to a maximum of 1600 lines
Use one class or function per file when possible
Use descriptive filenames
Add appropriate logging to services and error handlers

Files:

  • src/tux/plugins/atl/harmfulcommands.py
⏰ 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). (3)
  • GitHub Check: Run All Tests (3.13.8)
  • GitHub Check: Sourcery review
  • GitHub Check: Seer Code Review
🔇 Additional comments (1)
src/tux/plugins/atl/harmfulcommands.py (1)

25-25: Excellent improvement to reduce false positives.

Adding word boundaries \b around "rm" prevents the regex from matching substrings within unrelated words (e.g., "confirm", "alarm"), significantly reducing false positives while maintaining correct detection of the actual rm command.

Comment on lines 29 to 31
r"(?:[/\∕~/.]\s*|\*|" # noqa: RUF001
# Critical system paths
r"/(?:bin|boot|etc|lib|proc|rooin|sys|tmp|usr|var(?:/log)?|network\.|system))"

This comment was marked as outdated.

@meatsnails meatsnails closed this Dec 30, 2025
r"(?:-[frR]+|--force|--recursive|--no-preserve-root|\s+)*"
# Root/home indicators
r"(?:[/\∕~]\s*|\*|" # noqa: RUF001
r"(?:[/\∕~]\s*|\.(?:/|\.)\s*|\*|" # noqa: RUF001
Copy link

Choose a reason for hiding this comment

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

Bug: The regex \.(?:/|\.)\s* fails to detect the harmful command rm -rf . because it doesn't account for a single dot followed by a space, leaving a gap in the safety check.
Severity: CRITICAL | Confidence: High

🔍 Detailed Analysis

The updated regex pattern \.(?:/|\.)\s* in the is_harmful() function is designed to detect harmful commands targeting dot-prefixed paths. However, this pattern requires the dot to be followed by either a forward slash (/) or another dot (.). As a result, it fails to match a command like rm -rf ., where the dot is followed by a space. The underlying assumption that rm -rf . is not a dangerous command is incorrect; it recursively deletes all contents of the current directory. This gap in detection means the bot will not warn users about this destructive command, defeating a core safety feature.

💡 Suggested Fix

Modify the regex pattern to correctly identify a single dot (.) as a target for commands like rm. The pattern should be updated to match a bare dot followed by whitespace, in addition to the existing ./ and .. cases. This will ensure commands like rm -rf . are properly flagged.

🤖 Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent.
Verify if this is a real issue. If it is, propose a fix; if not, explain why it's not
valid.

Location: src/tux/plugins/atl/harmfulcommands.py#L29

Potential issue: The updated regex pattern `\.(?:/|\.)\s*` in the `is_harmful()`
function is designed to detect harmful commands targeting dot-prefixed paths. However,
this pattern requires the dot to be followed by either a forward slash (`/`) or another
dot (`.`). As a result, it fails to match a command like `rm -rf .`, where the dot is
followed by a space. The underlying assumption that `rm -rf .` is not a dangerous
command is incorrect; it recursively deletes all contents of the current directory. This
gap in detection means the bot will not warn users about this destructive command,
defeating a core safety feature.

Did we get this right? 👍 / 👎 to inform future reviews.
Reference ID: 8012009

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.

Warning bypass

2 participants