Skip to content

Add MaskedArg to hide a secret argument of a list command - #181

Merged
penguinolog merged 2 commits into
python-useful-helpers:masterfrom
cscutcher:masked-arg
Nov 13, 2026
Merged

penguinolog merged 2 commits into
python-useful-helpers:masterfrom
cscutcher:masked-arg

Conversation

@cscutcher

@cscutcher cscutcher commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What do these changes do?

Adds MaskedArg, so a caller can mark one element of a list command as secret.
The process gets the real value; the logs, ExecResult.cmd, the exceptions and the context repr get the masked one.

from exec_helpers import MaskedArg

helper.check_call(["tool", MaskedArg.option("pass", password), "--verbose"])
# executed: tool '--pass=two secret words' --verbose
# logged:   tool '--pass=<*masked*>' --verbose

Why: log_mask_re runs over the command after shlex.join, so the rule has to know shlex.quote's rules to be correct.1
The obvious rules don't hold up once the password has a space or a newline in it:

Password --pass=(\S+) --pass=(.+)
two secret words tool '--pass=<*masked*> secret words' --verbose tool '--pass=<*masked*> (eats the rest of the command)
line1\nline2 tool '--pass=<*masked*>\nline2' --verbose same, . stops at the newline

We hit this for real with a DB root password (the first fix used \S+).
A correct rule is possible, but it's not something I'd expect anyone to get right first time:

r"""--pass=((?<='--pass=)(?:[^']|'"'"')*|(?<!'--pass=)[^\s']*)"""

MaskedArg sidesteps that by masking per argument, before the join.

The type:

@dataclasses.dataclass(frozen=True, slots=True)
class MaskedArg:
    arg: str = dataclasses.field(repr=False)  # passed to the process
    arg_for_log: str                          # shown everywhere else

    @classmethod
    def secret(cls, arg: str) -> Self: ...
    # secret(v)        -> '<*masked*>'

    @classmethod
    def option(cls, name: str, value: str) -> Self: ...
    # option("pass", v) -> '--pass=<*masked*>'
    # option("p", v)    -> '-p<*masked*>'

    @classmethod
    def regex(cls, arg: str, rule: str | re.Pattern[str]) -> Self: ...
    # mask_command(arg, rule) on this one argument

It reuses the existing <*masked*> marker, so the length of the secret isn't leaked either.

option() takes the bare name and follows the usual conventions: a long name gives GNU's --name=value,2 a single character gives POSIX's -nvalue.3
An option and its value as separate arguments don't need a helper at all: ["--pass", MaskedArg.secret(v)].

How it's wired:

  • CommandT becomes str | Iterable[str | MaskedArg].
    A list command is materialised once, then joined twice: with arg for execution, with arg_for_log for everything else.
  • The log form travels as a new keyword-only command_for_log on open_execute_context, _exec_command and _log_command_execute (defaults to None, meaning "same as command").
  • open_execute_context runs the log form through _prepare_command too.
    So chroot and sudo_mode, which quote the command again inside sh -c, don't break the masking in the context repr.
  • log_mask_re still applies on top of the log form, so existing rules keep working.
  • Covered for Subprocess (with and without a shell), async_api.Subprocess, SSHClient and execute_together.

Are there changes in behavior for the user?

Nothing changes unless you pass a MaskedArg.

  • Plain str commands can't carry a MaskedArg; they keep using log_mask_re.
  • The masked argument is shell-quoted in the log ('--pass=<*masked*>'), because shlex quotes <*>.
    I left that alone so the logged command stays valid shell, but happy to special-case it if you'd rather.
  • Only the command is masked: if the process echoes the secret on stdout/stderr, that still gets logged, same as today.

Related issue number

None found for per-argument masking (searched issues/PRs for "mask").

Follows on from #180, which fixed log_mask_re itself.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (test/test_masked_arg.py: spaces, quotes, newline, shell syntax, a following argument, generator commands, chroot/sudo repr, shell=False, async, SSH, execute_together)
  • Documentation reflects the changes (README section next to log_mask_re, new doc/source/MaskedArg.rst, command type in the Sphinx pages)

A couple of things I wasn't sure about, so very open to steering:

  1. Naming: MaskedArg and the three constructors are my best guess; happy to rename.
  2. Version: I put .. versionadded:: 8.3.0 everywhere, guessing the next minor.
  3. Public signature: command_for_log on open_execute_context is public API now. The alternative was letting it accept the un-joined list, which felt like a bigger change to its contract.

Footnotes

  1. https://docs.python.org/3/library/shlex.html#shlex.quote ↩

  2. https://sourceware.org/glibc/manual/latest/html_node/Argument-Syntax.html: "To specify an argument for a long option, write --name=value." ↩

  3. https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap12.html, 12.1 item 2(a): implementations "shall also permit applications to specify the option and option-argument in the same argument string". ↩

@cscutcher
cscutcher force-pushed the masked-arg branch 2 times, most recently from 86a9727 to f5439da Compare November 11, 2026 12:37
@coveralls

coveralls commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Coverage Report for CI Build 43413784220

Coverage increased (+0.9%) to 89.583%

Details

  • Coverage increased (+0.9%) from the base build.
  • Patch coverage: 52 of 52 lines across 6 files are fully covered (100%).
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 1986
Covered Lines: 1824
Line Coverage: 91.84%
Relevant Branches: 462
Covered Branches: 369
Branch Coverage: 79.87%
Branches in Coverage %: Yes
Coverage Strength: 7.02 hits per line

💛 - Coveralls

log_mask_re matches the joined, shell-quoted command, so the rule has to
model shlex quoting: --pass=(\S+) leaks the rest of a value with spaces,
--pass=(.+) also hides the next arguments and still leaks after a
newline.

MaskedArg is masked per argument, before the command is joined:

    helper.execute(["tool", MaskedArg.option("pass", password), "-v"])
    # executed: tool '--pass=two words' -v
    # logged:   tool '--pass=<*masked*>' -v

- MaskedArg(arg, arg_for_log) is a frozen dataclass, its repr hides arg.
- Constructors: secret(arg), option(name, value) and regex(arg, rule).
  option() takes the bare name and follows the CLI conventions: a long
  name gives GNU's --name=value, a single character POSIX's -nvalue.
  An option and its value as separate arguments need no helper:
  ["--pass", MaskedArg.secret(value)].
- CommandT accepts MaskedArg items. A list command is joined twice: with
  arg for execution and with arg_for_log for the log, ExecResult.cmd,
  the exceptions and the context repr. log_mask_re still applies on top.
- open_execute_context, _exec_command and _log_command_execute take a
  keyword-only command_for_log. The context prepares it with chroot and
  sudo like the command, so their extra quoting does not matter.
- Covers Subprocess (with and without shell), async Subprocess,
  SSHClient and execute_together.
@cscutcher
cscutcher marked this pull request as ready for review November 11, 2026 13:26
Comment thread exec_helpers/_helpers.py Outdated
"""
if not _OPTION_NAME.fullmatch(name):
raise ValueError(f"Option name is expected without leading dashes, as alphanumerics and dashes: {name!r}")
flag = f"-{name}" if len(name) == 1 else f"--{name}="

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Option may be fully without dashes: dd if=... of=...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fair point. With the factory methods I was mostly going for the common cases, and anything more unusual can still build a MaskedArg directly.

Happy to add dd-style support though if you feel it's important. How about a new MaskedArg.key_value(key, value, sep="=") that does no dash detection at all, so MaskedArg.key_value("if", path) gives if=<*masked*>.

WDYT?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Sounds good. Not super critical now, but nice to have on cases like kubectl calls with values override

option() always adds - or --, so an argument like dd's if=... could
only be built with the raw constructor.

- key_value(key, value, sep="=") writes the key exactly as given:
  key_value("if", path) is if=<path>, shown as if=<*masked*>.
- An empty key is rejected.
- option() now builds its argument through key_value, adding the
  dashes and choosing the separator itself.
@penguinolog
penguinolog merged commit 89b33a1 into python-useful-helpers:master Nov 13, 2026
17 checks passed
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