Command.can_run leaves ctx.command and ctx.permission_state changed when a parent or the cog refuses #6821

Closed
opened 2026-10-26 05:34:32 +01:00 by cool-aid-man · 5 comments
cool-aid-man commented 2026-10-26 05:34:32 +01:00 (Migrated from github.com)

What Red version are you using?

3.5.24

What were you trying to do?

Check whether the author of a command could run a different command, by calling other_command.can_run(ctx, check_all_parents=True) on the current invocation's context. Help formatters do this to decide what to list, and so do cogs that gate one command on another.

What did you expect to happen?

Expected: can_run returns True or False and leaves ctx as it was. Its own comment says it only borrows ctx.command "so contexts invoking other commands can be checked with this command as well", and its finally puts ctx.command and ctx.permission_state back.

What actually happened?

When the check is refused by a parent (check_all_parents=True) or by the cog (a top-level command), can_run returns False before reaching the try/finally. ctx.command stays set to the probed command, and ctx.permission_state keeps whatever the parent checks set.

https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/develop/redbot/core/commands/commands.py#L435-L462

original_command = ctx.command
original_state = ctx.permission_state
ctx.command = self

if check_all_parents is True:
    ....
        if result is False:
            return False          # ctx.command is never restored

if self.parent is None and self.cog is not None:
    ret = await self.cog.requires.verify(ctx)
    if ret is False:
        return False              # ctx.command is never restored

try:
    return await self.requires.verify(ctx)
finally:
    ctx.command = original_command
    .....

The stale ctx.command then changes what the rest of the invocation does. ctx.cog is read from it, so in on_command_error Red's "the cog has its own error handler" check looks at the wrong cog. A cog that forwards an error with bot.on_command_error(ctx, error, unhandled_by_cog=True) gets that error handled twice, and ctx.send_help() sends help for the wrong command.

With the cog below, a plain member (not an admin, not the bot owner) runs [p]needsarg with no argument. They get help for the admin-only locked sub command twice, and never the help for needsarg:

[p]needsarg
-> Syntax: [p]locked sub     A subcommand of the admin-only group.
-> Syntax: [p]locked sub     A subcommand of the admin-only group.

Same result with [p]helpset verifyexists on and off. The bot owner never sees it, because Requires.verify lets owners through before any refusal.

How can we reproduce this error?

  1. Save this as canrunrepro/__init__.py in a cog path ([p]addpath <folder>), then [p]load canrunrepro.
from redbot.core import commands


class Locked(commands.Cog):
    """Has no error handler of its own."""

    @commands.group()
    @commands.admin()
    async def locked(self, ctx: commands.Context):
        """An admin-only group."""

    @locked.command()
    async def sub(self, ctx: commands.Context):
        """A subcommand of the admin-only group."""


class Repro(commands.Cog):
    """Has its own error handler, which hands the error back to Red."""

    @commands.command()
    async def probe(self, ctx: commands.Context):
        """Show ctx.command before and after a can_run check."""
        before = ctx.command
        ok = await ctx.bot.get_command("locked sub").can_run(ctx, check_all_parents=True)
        await ctx.send(f"can_run={ok} | ctx.command before={before} | after={ctx.command}")

    @commands.command()
    async def needsarg(self, ctx: commands.Context, arg: str):
        """Run with no argument to raise MissingRequiredArgument."""

    async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError):
        # Stands in for a help formatter or permission check that asks about another command.
        await ctx.bot.get_command("locked sub").can_run(ctx, check_all_parents=True)
        await ctx.bot.on_command_error(ctx, error, unhandled_by_cog=True)


async def setup(bot):
    await bot.add_cog(Locked())
    await bot.add_cog(Repro())
  1. From an account that is not the bot owner and not an admin, run [p]probe:
    can_run=False | ctx.command before=probe | after=locked sub
    
    From the bot owner, the same command shows after=probe.
  2. From the same non-admin account, run [p]needsarg with no argument. You get two help messages, both for locked sub (see above).

Anything else?

I'm happy to open a PR (with tests).

### What Red version are you using? 3.5.24 ### What were you trying to do? Check whether the author of a command could run a *different* command, by calling `other_command.can_run(ctx, check_all_parents=True)` on the current invocation's context. Help formatters do this to decide what to list, and so do cogs that gate one command on another. ### What did you expect to happen? Expected: `can_run` returns True or False and leaves `ctx` as it was. Its own comment says it only borrows `ctx.command` "so contexts invoking other commands can be checked with this command as well", and its `finally` puts `ctx.command` and `ctx.permission_state` back. ### What actually happened? When the check is refused by a **parent** (`check_all_parents=True`) or by the **cog** (a top-level command), `can_run` returns `False` *before* reaching the `try/finally`. `ctx.command` stays set to the probed command, and `ctx.permission_state` keeps whatever the parent checks set. https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/develop/redbot/core/commands/commands.py#L435-L462 ```python original_command = ctx.command original_state = ctx.permission_state ctx.command = self if check_all_parents is True: .... if result is False: return False # ctx.command is never restored if self.parent is None and self.cog is not None: ret = await self.cog.requires.verify(ctx) if ret is False: return False # ctx.command is never restored try: return await self.requires.verify(ctx) finally: ctx.command = original_command ..... ``` The stale `ctx.command` then changes what the rest of the invocation does. `ctx.cog` is read from it, so in `on_command_error` Red's "the cog has its own error handler" check looks at the wrong cog. A cog that forwards an error with `bot.on_command_error(ctx, error, unhandled_by_cog=True)` gets that error handled **twice**, and `ctx.send_help()` sends help for the **wrong command**. With the cog below, a plain member (not an admin, not the bot owner) runs `[p]needsarg` with no argument. They get help for the admin-only `locked sub` command twice, and never the help for `needsarg`: ```text [p]needsarg -> Syntax: [p]locked sub A subcommand of the admin-only group. -> Syntax: [p]locked sub A subcommand of the admin-only group. ``` Same result with `[p]helpset verifyexists` on and off. The bot owner never sees it, because `Requires.verify` lets owners through before any refusal. ### How can we reproduce this error? 1. Save this as `canrunrepro/__init__.py` in a cog path (`[p]addpath <folder>`), then `[p]load canrunrepro`. ```python from redbot.core import commands class Locked(commands.Cog): """Has no error handler of its own.""" @commands.group() @commands.admin() async def locked(self, ctx: commands.Context): """An admin-only group.""" @locked.command() async def sub(self, ctx: commands.Context): """A subcommand of the admin-only group.""" class Repro(commands.Cog): """Has its own error handler, which hands the error back to Red.""" @commands.command() async def probe(self, ctx: commands.Context): """Show ctx.command before and after a can_run check.""" before = ctx.command ok = await ctx.bot.get_command("locked sub").can_run(ctx, check_all_parents=True) await ctx.send(f"can_run={ok} | ctx.command before={before} | after={ctx.command}") @commands.command() async def needsarg(self, ctx: commands.Context, arg: str): """Run with no argument to raise MissingRequiredArgument.""" async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError): # Stands in for a help formatter or permission check that asks about another command. await ctx.bot.get_command("locked sub").can_run(ctx, check_all_parents=True) await ctx.bot.on_command_error(ctx, error, unhandled_by_cog=True) async def setup(bot): await bot.add_cog(Locked()) await bot.add_cog(Repro()) ``` 2. From an account that is **not** the bot owner and **not** an admin, run `[p]probe`: ```text can_run=False | ctx.command before=probe | after=locked sub ``` From the bot owner, the same command shows `after=probe`. 3. From the same non-admin account, run `[p]needsarg` with no argument. You get two help messages, both for `locked sub` (see above). ### Anything else? I'm happy to open a PR (with tests).
Grawty commented 2026-10-28 20:34:39 +01:00 (Migrated from github.com)

I've reproduced this and have a fix with regression tests ready (restores ctx.command and ctx.permission_state on every return path in Command.can_run). I'll open a PR shortly unless someone is already working on it.

I've reproduced this and have a fix with regression tests ready (restores `ctx.command` and `ctx.permission_state` on every return path in `Command.can_run`). I'll open a PR shortly unless someone is already working on it.
cool-aid-man commented 2026-10-28 20:47:30 +01:00 (Migrated from github.com)

Well, I had the PR ready as mentioned earlier, I was just waiting for an ORG member to comment on this

Well, I had the PR ready as mentioned earlier, I was just waiting for an ORG member to comment on this
Grawty commented 2026-10-28 20:52:25 +01:00 (Migrated from github.com)

Thanks for the heads-up! Since you had yours ready, please go ahead and open it. I'll close mine in favor of yours.

Thanks for the heads-up! Since you had yours ready, please go ahead and open it. I'll close mine in favor of yours.
Jackenmen commented 2026-11-02 17:40:48 +01:00 (Migrated from github.com)

Looks valid.

Check whether the author of a command could run a different command, by calling other_command.can_run(ctx, check_all_parents=True) on the current invocation's context. Help formatters do this to decide what to list, and so do cogs that gate one command on another.

FYI, you should prefer Command.can_see for the help formatter case (it does still call out to can_run() but also checks the Command.hidden's value).

I'm happy to open a PR (with tests).

You can make a PR. Not sure about adding the tests - we don't really have mocks or anything of the sort for anything command related.

Looks valid. > Check whether the author of a command could run a _different_ command, by calling `other_command.can_run(ctx, check_all_parents=True)` on the current invocation's context. Help formatters do this to decide what to list, and so do cogs that gate one command on another. FYI, you should prefer `Command.can_see` for the help formatter case (it does still call out to `can_run()` but also checks the `Command.hidden`'s value). > I'm happy to open a PR (with tests). You can make a PR. Not sure about adding the tests - we don't really have mocks or anything of the sort for anything command related.
cool-aid-man commented 2026-11-03 17:58:53 +01:00 (Migrated from github.com)

Done!
And regarding the tests: I added two lightweight unit tests in tests/core/test_commands.py that only mock ctx.command, permission_state, and requires.verify (no full bot or Discord harness)

(Though, If you'd prefer not to have mock-based tests for commands in the repo, let me know and I'm completely happy to drop the test commit!)

Done! And regarding the tests: I added two lightweight unit tests in `tests/core/test_commands.py` that only mock `ctx.command`, `permission_state`, and `requires.verify` (no full bot or Discord harness) (Though, If you'd prefer not to have mock-based tests for commands in the repo, let me know and I'm completely happy to drop the test commit!)
Sign in to join this conversation.
No labels
Automated PR
Blocked
Blocked By: Damage Control
Blocked By: Dependency
Blocked By: Other PR
Breaking Change
Category: CI
Category: Cogs - Admin
Category: Cogs - Alias
Category: Cogs - Audio
Category: Cogs - Bank
Category: Cogs - Cleanup
Category: Cogs - CustomCommands
Category: Cogs - Dev
Category: Cogs - Downloader
Category: Cogs - Economy
Category: Cogs - Filter
Category: Cogs - General
Category: Cogs - Image
Category: Cogs - Mod
Category: Cogs - Modlog
Category: Cogs - Mutes
Category: Cogs - Permissions
Category: Cogs - Reports
Category: Cogs - Streams
Category: Cogs - Trivia
Category: Cogs - Trivia - Lists
Category: Cogs - Warnings
Category: Core - API - App Commands Package
Category: Core - API - Audio
Category: Core - API - Bank
Category: Core - API - Commands Package
Category: Core - API - Config
Category: Core - API - Other
Category: Core - API - Utils Package
Category: Core - Bot Class
Category: Core - Bot Commands
Category: Core - Command-line Interfaces
Category: Core - Downloader
Category: Core - Help
Category: Core - i18n
Category: Core - Modlog
Category: Core - Other Internals
Category: Core - RPC/ZMQ
Category: Docker
Category: Docs - Changelogs
Category: Docs - For Developers
Category: Docs - Install Guides
Category: Docs - Other
Category: Docs - User Guides
Category: Meta
Category: RPC/ZMQ methods
Category: Vendored Packages
Changelog Entry: Added
Changelog Entry: Pending
Changelog Entry: Skipped
Closed: Duplicate
Closed: External
Closed: Invalid
Closed: User Error
Closed: Won't Fix
Complex Issue
Docs-only
Feature Branch
Good First Issue
Help Wanted
High Priority
Needs Backport To stable-docs
No Activity
No Repro
QA: Bypassed
QA: Changes Requested
QA: Passed
Release Blocker
Status: Accepted
Status: Frozen
Status: In Progress
Status: Needs Discussion
Status: Needs Info
Status: Needs Triage
Status: PRs Welcome
Type: Bug
Type: Dependency Update
Type: Deprecation
Type: Enhancement
Type: Feature
Type: Informational
Type: Merge
Type: Optimisation
Type: Question
Type: Removal
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Mrcoolgamer11/Red-DiscordBot#6821
No description provided.