From 8a6de79f09248f8e0a1360ea2be3cada8acfe3bb Mon Sep 17 00:00:00 2001 From: blackax Date: Thu, 3 Dec 2026 17:45:26 -0800 Subject: [PATCH 1/2] feat: opt-in redact_output masks secrets in tool results - New redact_output setting (default off): execute, execute_on_group and converted ToolError text pass through ssh_mcp.redact before returning to the client - Masks passwords/tokens/keys (key=value, quoted, Authorization, Bearer, URL password, PEM blocks); logins, e-mails, IPs and host names stay visible - Linear-time rules, run off the event loop; documented in README, CHANGELOG and servers.example.toml --- CHANGELOG.md | 4 + README.md | 5 + config/servers.example.toml | 6 + src/ssh_mcp/models.py | 13 + src/ssh_mcp/redact.py | 168 ++++++++++++ src/ssh_mcp/server.py | 26 +- tests/test_redact.py | 534 ++++++++++++++++++++++++++++++++++++ tests/test_server.py | 139 ++++++++++ 8 files changed, 892 insertions(+), 3 deletions(-) create mode 100644 src/ssh_mcp/redact.py create mode 100644 tests/test_redact.py diff --git a/CHANGELOG.md b/CHANGELOG.md index dc6047b..82cf309 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 **`reuse_connection` per-server option (default `true`).** Setting `reuse_connection = false` on a `[servers.*]` block makes every `execute`, `execute_on_group`, `upload_file` and `download_file` operation on that server open a brand-new SSH connection and close it, waiting for the close, right after the operation — on success or error — without ever storing it in the connection pool. It governs only operations run on that host itself: a jump host used as a tunnel is still reached through the shared pool and stays cached (tunnels use direct-tcpip channels, not exec channels). This is needed for Windows OpenSSH hosts that run a `ForceCommand` wrapper: Windows OpenSSH hands every exec channel after the first on one connection the first channel's `SSH_ORIGINAL_COMMAND`, so with a cached connection every command after the first returned the first command's output. The key must be a TOML boolean; a non-boolean value is rejected at load. With the default `true`, behaviour is unchanged. +**`redact_output` setting (default `false`).** With `redact_output = true` in `[settings]`, `execute` and `execute_on_group` mask secrets in their final result string — stdout, stderr, the echoed command and error text, plus the text of any error the tool raises — before returning it, in a worker thread so a large output does not stall the event loop. Masked: PEM private keys (`[REDACTED PRIVATE KEY]`; an unterminated block from truncated output is masked up to the `[... output truncated at N bytes]` marker, the next blank line or an `Exit code:` line, so stderr, the exit line and later servers of a group result survive); `key=value` / `key: value` pairs for `password`, `passphrase`, `pwd`, `secret` (also `secret_key`, `secret_access_key`), `token`, `api_key`, `access_key` and `client_secret`, plus `pass` / `passwd` with `=` only (key names also match as the tail of a longer name such as `PGPASSWORD` or `dbPassword`; the key and separator are kept, and quoted values are masked through their closing quote, escape-aware); `Authorization:` headers and `Bearer` tokens; and the password of `scheme://user:pass@host` URLs (`scheme://user:[REDACTED]@host`; only the authority is parsed, so a port followed by a query-string e-mail is left alone). Logins, e-mail addresses, IP addresses and host names are left readable on purpose. The rules are heuristic and run in time linear in the output length (`src/ssh_mcp/redact.py`; deliberately not `ssh._redact_secrets`, which is superlinear). The key must be a TOML boolean; a non-boolean value is rejected at load. With the default `false`, behaviour is unchanged. + +`redact_output` edge behaviour: a `pwd` / `PWD` value starting with `/` (`PWD=/home/x`, `OLDPWD=/tmp`) stays visible, so a password beginning with `/` after `pwd=` is not masked; `secret_key_base` is masked; an unquoted `Authorization:` value stops at a quote that closes nothing, so `curl -H "Authorization: Bearer x" https://host/` keeps its closing quote and the URL; a URL's authority ends at a quote or angle bracket; a URL whose login is a key word (`https://token:pw@host/x`) keeps its login and host; and a quoted value cut off right after a backslash is masked in full. + ## [0.9.3] - 2026-12-01 > **Why 0.9.3 and not 0.10.0:** nothing here makes a configuration that started on 0.9.2 refuse to start. The runtime dependency changes are lockfile-only patches (`opentelemetry-api`, `pydantic`); the only new declared floor is a uv constraint, and the container image's interpreter move adds no configuration surface. diff --git a/README.md b/README.md index aadd43c..87c2ac4 100644 --- a/README.md +++ b/README.md @@ -324,6 +324,7 @@ max_command_bytes = 65536 # reject longer command strings at the tool bounda connection_idle_timeout = 300 # seconds; eviction scan runs every 60s known_hosts = true # false removes MITM protection max_parallel_hosts = 10 # process-wide concurrency cap for group execution (1..100) +redact_output = false # true masks secrets in execute / execute_on_group results (default false) [groups] production = { description = "Production servers" } @@ -351,6 +352,10 @@ Note two things about the timeouts, because the names invite confusion: `max_parallel_hosts` bounds the whole process, not a single call: the semaphore is built once at startup, so concurrent `execute_on_group` calls share the same budget rather than each getting their own. +`redact_output` (boolean, default `false`) is opt-in output masking. With `redact_output = true`, `execute` and `execute_on_group` pass their final result — stdout, stderr, the echoed command and error text, plus the text of any error the tool raises — through a redactor before returning it: PEM private keys become `[REDACTED PRIVATE KEY]` (an unterminated block, from truncated output, is masked up to the truncation marker, the next blank line or an `Exit code:` line); `key=value` / `key: value` pairs whose key is `password`, `passphrase`, `pwd`, `secret` (also `secret_key`, `secret_access_key`), `token`, `api_key`, `access_key` or `client_secret` keep the key and separator and have the value replaced by `[REDACTED]`, and `pass` / `passwd` do the same with `=` only (so `/etc/passwd:` lines are left alone); keys match as the tail of a longer name too (`PGPASSWORD`, `dbPassword`, `"accessToken"`), so a harmless name ending in one (`bypass=1`) is masked as well; quoted values are masked through the closing quote (escape-aware), which covers connection strings like `Password=x;`; `Authorization:` headers and `Bearer` tokens are masked; and the password of `scheme://user:pass@host` URLs is replaced (`scheme://user:[REDACTED]@host`, the user stays). Logins, e-mail addresses, IP addresses and host names are deliberately left readable so output stays diagnosable. The rules are heuristic — a secret printed with no key name is not recognised — and run in linear time, off the event loop. `upload_file` and `download_file` return only a confirmation message, so they are unaffected. + +Edge behaviour of `redact_output`: a `pwd` / `PWD` value that starts with `/` (`PWD=/home/x`, `OLDPWD=/tmp` in `env` output) is the working directory and stays visible, so a password beginning with `/` after `pwd=` is not masked; `secret_key_base` is masked; an unquoted `Authorization:` value stops at a quote that closes nothing (`curl -H "Authorization: Bearer x" https://host/` keeps its closing quote and the URL); and a URL's authority ends at a quote or angle bracket, so `["http://host:8080","ops@example.com"]` is not read as credentials. + Per-server overrides (`hostname`, `port`, `user`, `identity_file`, `jump_host`, `default_dir`, `timeout`) take precedence over `~/.ssh/config`. See [config/servers.example.toml](https://github.com/blackaxgit/ssh-mcp/blob/main/config/servers.example.toml) for the annotated reference. `reuse_connection` (boolean, default `true`) controls connection caching for one server. With `reuse_connection = false`, every `execute`, `execute_on_group`, `upload_file` and `download_file` operation on that server opens a brand-new SSH connection and closes it as soon as the operation finishes (success or error); nothing is cached, so each call pays a full connect and handshake. The setting governs only operations run on that host itself: a jump host used as a tunnel is always reached through the shared connection pool and stays cached whatever its own `reuse_connection` says (tunnels use direct-tcpip channels, not exec channels, so the Windows issue below does not apply to them). Set it to `false` on **Windows hosts whose `sshd` uses a `ForceCommand` wrapper**: Windows OpenSSH gives every exec channel after the first on one SSH connection the *first* channel's `SSH_ORIGINAL_COMMAND`, so over a cached connection every command after the first would silently return the first command's output. Linux and MikroTik hosts are unaffected and should keep the default. diff --git a/config/servers.example.toml b/config/servers.example.toml index 5d63bc2..1e1ca7d 100644 --- a/config/servers.example.toml +++ b/config/servers.example.toml @@ -46,6 +46,12 @@ known_hosts = true # exhaust file descriptors or trigger fleet-wide load spikes. max_parallel_hosts = 10 +# Opt-in: mask secrets (PEM private keys, password/token/api_key-style +# key=value pairs, Authorization/Bearer values, URL passwords) in everything +# execute / execute_on_group return. Logins, e-mails, IPs and host names stay +# readable. Heuristic, so it is not a substitute for keeping secrets off hosts. +# redact_output = true + # ============================================================================= # GROUP DEFINITIONS # ============================================================================= diff --git a/src/ssh_mcp/models.py b/src/ssh_mcp/models.py index 8370f9c..3bad4b7 100644 --- a/src/ssh_mcp/models.py +++ b/src/ssh_mcp/models.py @@ -102,6 +102,18 @@ class Settings: reaper closes them, so open descriptors can still exceed this number. Bounded to 1..100 to keep fleet-wide load spikes and descriptor growth in check. + redact_output: Mask secrets in everything the execute tools return + from remote hosts (default False, so output is returned verbatim). + When true, ``execute`` and ``execute_on_group`` run their final + result string — stdout, stderr, the echoed command and any error + text, including the text of a converted exception — through + ``ssh_mcp.redact.redact_output`` (in a worker thread): PEM private + keys, ``key=value`` / ``key: value`` secrets (password, token, + api_key, ...), ``Authorization`` / ``Bearer`` credentials and the + password part of ``scheme://user:pass@host`` URLs. Logins, e-mail + addresses, IPs and host names are left alone. Heuristic: it + cannot recognise a secret that carries no key name. Must be a + TOML boolean. """ # ``validate_default=True`` is load-bearing on the path fields: pydantic @@ -117,6 +129,7 @@ class Settings: connection_idle_timeout: int = Field(default=300, ge=10) known_hosts: bool = True max_parallel_hosts: int = Field(default=10, ge=1, le=100) + redact_output: bool = Field(default=False, strict=True) @field_validator("ssh_config_path", "transfer_root") @classmethod diff --git a/src/ssh_mcp/redact.py b/src/ssh_mcp/redact.py new file mode 100644 index 0000000..347dc18 --- /dev/null +++ b/src/ssh_mcp/redact.py @@ -0,0 +1,168 @@ +"""Opt-in masking of secrets in text returned from remote hosts. + +Applied by the MCP tools to their final result string when +``Settings.redact_output`` is true (default false). This is deliberately +separate from ``ssh._redact_secrets``, which scrubs *commands* for logging and +is superlinear on large input; remote output can be up to +``max_output_bytes`` (10 MiB at most) per stream, so every pattern here must +run in time linear in the text length. + +How linearity is kept (Python's ``re`` has no timeout, so this is by +construction, not by measurement alone): + +* no nested quantifiers and no alternation whose branches can match the same + characters at the same position; +* every unbounded repetition is a negated character class that stops at a + delimiter the *next* part of the pattern needs, so a failed attempt re-scans + at most up to that delimiter, and attempts at later start positions begin + past it; +* the key names are plain literals, not preceded by a ``\\w*`` that every start + position would rescan. + +Deliberately NOT masked, because they are needed to diagnose problems: +logins, e-mail addresses, IP addresses and host names. Only the secret part +of a URL's userinfo is masked, never the user. + +Known limits: the rules are heuristic. A secret that carries no key name +(a bare token printed on its own line), or one split across the output +truncation marker, is not recognised. Key names match as the tail of a longer +name on purpose (``PGPASSWORD``, ``dbPassword``, ``REDISPASS``), so a +harmless name that merely ends in one of them (``bypass=1``) is masked too. +The exception is ``pwd``: ``PWD=/home/x`` and ``OLDPWD=/tmp`` (a value +starting with ``/``) stay visible, so a password that begins with ``/`` after +``pwd=`` is not masked. +""" + +from __future__ import annotations + +import re + +_FLAGS = re.IGNORECASE + +# The ``[... output truncated at N bytes]`` marker ssh.py appends after a cut +# stream. Secrets are masked up to it, never across it, so the reader can still +# see why the output stopped. +_TRUNCATION = r"\n\[\.\.\. output truncated at \d+ bytes\]" + +# Rule 1: PEM private key, BEGIN line through the matching END line. +# An unterminated block (output truncated mid-key) is masked up to the first +# of: the truncation marker, a blank line, a line starting ``Exit code:`` or +# the end of the text — so stderr, the exit line and later servers of a group +# result survive. The legacy encrypted layout (``Proc-Type:`` / ``DEK-Info:`` +# headers, then a blank line, then the body) is skipped over explicitly so +# that blank line does not end a complete block early. +_PEM_STOP = r"\n[ \t\r]*\n|\nExit code:|" + _TRUNCATION +_PEM = re.compile( + r"-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY-----" + r"(?:(?:\n(?:Proc-Type|DEK-Info):[^\n]*)+(?:\n[ \t\r]*\n)?)?" + r"[\s\S]*?" + r"(?:-----END [A-Z0-9 ]{0,40}PRIVATE KEY-----" + r"|(?=" + _PEM_STOP + r")" + r"|\Z)", + _FLAGS, +) + +# A quoted string, escape-aware (``\"`` does not close it) and single-line. +# Masked through the closing quote; when the closing quote never comes because +# the stream was truncated, through to the truncation marker / end of text — +# including a lone trailing backslash cut off right before it. Any other +# unclosed quote does not match here and falls back to an unquoted run, so a +# stray quote cannot swallow the rest of the output. +_END_OF_STREAM = r"(?=" + _TRUNCATION + r"|\Z)" +_DQ = r'"[^"\\\n]*(?:\\.[^"\\\n]*)*(?:"|\\?' + _END_OF_STREAM + r")" +_SQ = r"'[^'\\\n]*(?:\\.[^'\\\n]*)*(?:'|\\?" + _END_OF_STREAM + r")" + +# Rule 3a: ``Authorization: `` — the header name and separator +# stay, everything after them (a quoted string, else the rest of the line, so +# multi-field schemes such as Digest are covered) is masked. An unquoted value +# stops at a quote that closes nothing, so ``curl -H "Authorization: Bearer x" +# https://host/`` keeps its closing ``"`` and the URL; balanced double-quoted +# segments inside it (Digest's ``username="bob", response="ff"``) are part of +# the value. +_AUTHORIZATION = re.compile( + r"""(authorization["']?[ \t]*[:=][ \t]*)(?:""" + + _DQ + + "|" + + _SQ + + r"""|["']?[^\r\n"']+(?:"[^"\r\n]*"[^\r\n"']*)*)""", + _FLAGS, +) + +# Rule 3b: a bare ``Bearer `` outside any Authorization header. +_BEARER = re.compile( + r"(?]*:)[^\s/?#\"'<>]*@") + +# Rule 2: ``key=value`` / ``key: value`` (also JSON/YAML ``"key": "value"``). +# Key names match anywhere, including as the tail of a longer name, so +# ``PGPASSWORD``, ``dbPassword``, ``"accessToken"`` and ``SECRET_KEY`` are +# covered. ``pass`` and ``passwd`` are too common in ordinary logs and +# ``/etc/passwd`` lines to take a ``:`` separator, so they take only ``=``. +# There is no bare ``auth`` key (``auth: user=`` is a log line, not a +# secret); ``Authorization`` is rule 3. The value is a quoted string or a run +# of characters up to whitespace or one of ``,;&`` — which covers connection +# strings (``Password=x;``) and query strings (``?token=x&``). +_KEYS_ANY_SEPARATOR = ( + r"password|passphrase|secret(?:[_-]?access)?(?:[_-]?key(?:[_-]?base)?)?" + r"|token|api[_-]?key|access[_-]?key|client[_-]?secret" +) +# ``pwd`` is the shell's working directory as often as it is a password +# (``PWD=/home/x``, ``OLDPWD=/tmp`` in ``env`` output), so a value that starts +# with ``/`` (optionally quoted) is left alone for it alone. +_SEPARATOR = r"[\"']?[ \t]*[=:]" +_KEY_VALUE = re.compile( + r"((?:(?:" + + _KEYS_ANY_SEPARATOR + + r")" + + _SEPARATOR + + r"|pwd" + + _SEPARATOR + + r"(?![ \t]*[\"']?/)" + + r"|(?:passwd|pass)[\"']?[ \t]*=)[ \t]*)" + # A value that is already a masked URL password (``[REDACTED]@host``, from + # rule 4 running first) is skipped: ``https://token:pw@host/x`` must keep + # its host, not be erased by the ``token:`` key. + + r"(?!\[REDACTED\]@)" + + r"(?:" + + _DQ + + "|" + + _SQ + + r"|[^\s,;&]+)", + _FLAGS, +) + + +def redact_output(text: str) -> str: + """Mask secrets in ``text`` and return the result. + + Rules, applied in this order: + + 1. PEM private keys -> ``[REDACTED PRIVATE KEY]``. + 2. ``Authorization: ...`` -> ``Authorization: [REDACTED]`` and + ``Bearer `` -> ``Bearer [REDACTED]``. + 3. URL credentials ``scheme://user:pass@host`` -> + ``scheme://user:[REDACTED]@host``. + 4. ``key=value`` / ``key: value`` for password, passphrase, pwd, secret + (also ``secret_key`` / ``secret_access_key``), token, api_key, + access_key and client_secret, plus ``pass`` / ``passwd`` with ``=`` + only (case-insensitive, also as the tail of a longer name) -> the key + and separator are kept, the value becomes ``[REDACTED]``. + + Runs in time linear in ``len(text)`` and is idempotent. + """ + text = _PEM.sub("[REDACTED PRIVATE KEY]", text) + text = _AUTHORIZATION.sub(r"\1[REDACTED]", text) + text = _BEARER.sub(r"\1[REDACTED]", text) + text = _URL_CREDENTIALS.sub(r"\1[REDACTED]@", text) + return _KEY_VALUE.sub(r"\1[REDACTED]", text) diff --git a/src/ssh_mcp/server.py b/src/ssh_mcp/server.py index ed38330..6d5b82a 100644 --- a/src/ssh_mcp/server.py +++ b/src/ssh_mcp/server.py @@ -42,6 +42,7 @@ format_group_table, format_server_table, ) +from ssh_mcp.redact import redact_output from ssh_mcp.ssh import SSHManager, _redact_secrets # --------------------------------------------------------------------------- @@ -388,7 +389,7 @@ async def wrapper(*args: Any, **kwargs: Any) -> str: redacted = _redact_secrets(str(e)) redacted_tb = _redact_secrets("".join(traceback.format_exception(e))) logger.error("%s failed: %s\n%s", tool_name, redacted, redacted_tb) - raise ToolError(redacted) from e + raise ToolError(await _finalize_output(redacted)) from e return cast(F, wrapper) @@ -445,6 +446,21 @@ async def list_groups() -> str: return format_group_table(groups, server_counts) +async def _finalize_output(text: str) -> str: + """Mask secrets in a tool's result text when ``redact_output`` is on. + + Applied to the fully formatted string, not to ``ExecResult`` fields, so + stdout, stderr, the echoed command and error text are all covered in one + place; ``_mcp_tool`` also runs the text of a converted exception through + it. The redaction runs in a worker thread so a large output does not + stall the event loop. A no-op (the text is returned as-is) when the + setting is off, or when the server is not initialised yet. + """ + if _registry is not None and _registry.settings.redact_output: + return await asyncio.to_thread(redact_output, text) + return text + + def _check_command_length(command: str, max_bytes: int) -> None: """Reject an over-long ``command`` before it reaches the SSH layer. @@ -520,11 +536,13 @@ async def execute( worst case is 2x that setting. A truncated stream ends with ``[... output truncated at N bytes]``, and hitting the cap TERMINATES the remote process rather than letting it keep writing. + With ``redact_output = true`` in ``[settings]``, secrets in the whole + result are masked (see ``ssh_mcp.redact``). """ ssh = _get_ssh() _check_command_length(command, _get_registry().settings.max_command_bytes) result = await ssh.execute(server, command, timeout, working_dir, force, dry_run) - return format_exec_result(result) + return await _finalize_output(format_exec_result(result)) @mcp.tool() @@ -573,13 +591,15 @@ async def execute_on_group( Returns: Formatted summary showing per-server results, success/failure counts, and aggregate exit status. + With ``redact_output = true`` in ``[settings]``, secrets in the whole + summary are masked (see ``ssh_mcp.redact``). """ ssh = _get_ssh() _check_command_length(command, _get_registry().settings.max_command_bytes) results = await ssh.execute_on_group( group, command, timeout, working_dir, fail_fast, force, dry_run ) - return format_group_results(results, group) + return await _finalize_output(format_group_results(results, group)) @mcp.tool() diff --git a/tests/test_redact.py b/tests/test_redact.py new file mode 100644 index 0000000..8313fcb --- /dev/null +++ b/tests/test_redact.py @@ -0,0 +1,534 @@ +"""Tests for ``ssh_mcp.redact.redact_output`` and the ``redact_output`` setting.""" + +from __future__ import annotations + +import time +from pathlib import Path + +import pytest + +from ssh_mcp.config import ConfigError, ServerRegistry +from ssh_mcp.models import Settings +from ssh_mcp.redact import redact_output + +_MIB = 1024 * 1024 +# Measured around 0.1 s for the worst case below; the bound is generous so a +# slow CI runner does not flake, yet a quadratic regression (minutes on 1 MiB) +# still fails it. +_TIME_BOUND_S = 5.0 + + +def _pem(kind: str = "RSA ", body: str = "abc") -> str: + """A complete (fake) PEM block, assembled from parts.""" + dashes = "-" * 5 + return ( + f"{dashes}BEGIN {kind}PRIVATE KEY{dashes}\n{body}\n" + f"{dashes}END {kind}PRIVATE KEY{dashes}" + ) + + +def _begin(kind: str = "RSA ") -> str: + """Just the BEGIN line of a PEM private key (a truncated block).""" + dashes = "-" * 5 + return f"{dashes}BEGIN {kind}PRIVATE KEY{dashes}" + + +class TestPemPrivateKey: + def test_full_block_replaced(self) -> None: + text = f"before\n{_pem()}\nafter" + + assert redact_output(text) == "before\n[REDACTED PRIVATE KEY]\nafter" + + @pytest.mark.parametrize("kind", ["RSA ", "EC ", "DSA ", "ENCRYPTED ", ""]) + def test_header_variants(self, kind: str) -> None: + assert redact_output(_pem(kind)) == "[REDACTED PRIVATE KEY]" + + def test_case_insensitive(self) -> None: + assert redact_output(_pem().lower()) == "[REDACTED PRIVATE KEY]" + + def test_two_blocks_each_replaced(self) -> None: + block = _pem() + + assert redact_output(f"{block}\nmid\n{block}") == ( + "[REDACTED PRIVATE KEY]\nmid\n[REDACTED PRIVATE KEY]" + ) + + def test_truncated_block_runs_to_end_of_text(self) -> None: + text = "x\n-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA\nQ2xmZ" # gitleaks:allow (synthetic fixture) + + assert redact_output(text) == "x\n[REDACTED PRIVATE KEY]" + + def test_truncated_block_keeps_truncation_marker(self) -> None: + text = ( + "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA" + "\n[... output truncated at 1024 bytes]" + ) + + out = redact_output(text) + + assert out == "[REDACTED PRIVATE KEY]\n[... output truncated at 1024 bytes]" + assert "MIIEow" not in out + + def test_public_key_block_untouched(self) -> None: + text = "-----BEGIN PUBLIC KEY-----\nabc\n-----END PUBLIC KEY-----" + + assert redact_output(text) == text + + def test_unterminated_block_stops_at_blank_line(self) -> None: + text = f"{_begin()}\nMIIEow\n\nSTDERR:\nerr\n\nExit code: 1 (5ms)" + + assert redact_output(text) == ( + "[REDACTED PRIVATE KEY]\n\nSTDERR:\nerr\n\nExit code: 1 (5ms)" + ) + + def test_unterminated_block_stops_at_exit_code_line(self) -> None: + text = f"{_begin()}\nMIIEow\nExit code: 1 (5ms)" + + assert redact_output(text) == "[REDACTED PRIVATE KEY]\nExit code: 1 (5ms)" + + def test_unterminated_block_in_group_result_spares_later_servers(self) -> None: + text = ( + "Executing on group 'g' (2 servers)...\n\n" + f"[web1] (exit 0, 5ms)\n{_begin()}\nMIIEow\n\n" + "[web2] (exit 0, 6ms)\ntoken=abc\n\nSummary: 2 succeeded, 0 failed" + ) + + out = redact_output(text) + + assert "MIIEow" not in out + assert "abc" not in out + assert "[web2] (exit 0, 6ms)\ntoken=[REDACTED]" in out + assert out.endswith("Summary: 2 succeeded, 0 failed") + + def test_legacy_encrypted_block_with_blank_line_replaced_whole(self) -> None: + body = "Proc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,0011\n\nQUJD\nREVG" + + assert redact_output(_pem(body=body)) == "[REDACTED PRIVATE KEY]" + + def test_complete_block_then_later_text_untouched(self) -> None: + out = redact_output(f"{_pem()}\n\nuser=bob\n\nExit code: 0 (1ms)") + + assert out == "[REDACTED PRIVATE KEY]\n\nuser=bob\n\nExit code: 0 (1ms)" + + +class TestKeyValue: + @pytest.mark.parametrize( + "key", + [ + "password", + "passphrase", + "pwd", + "secret", + "secret_key", + "secret-key", + "secret_access_key", + "token", + "api_key", + "api-key", + "apikey", + "access_key", + "client_secret", + ], + ) + @pytest.mark.parametrize("sep", ["=", ": ", " = "]) + def test_each_key_and_separator(self, key: str, sep: str) -> None: + out = redact_output(f"{key}{sep}hunter2") + + assert out == f"{key}{sep}[REDACTED]" + + @pytest.mark.parametrize("key", ["pass", "passwd"]) + def test_pass_and_passwd_take_only_equals(self, key: str) -> None: + assert redact_output(f"{key}=hunter2") == f"{key}=[REDACTED]" + assert redact_output(f"{key}: hunter2") == f"{key}: hunter2" + + def test_case_insensitive_and_key_case_preserved(self) -> None: + assert redact_output("PASSWORD=Hunter2") == "PASSWORD=[REDACTED]" + assert redact_output("Api_Key: abcDEF") == "Api_Key: [REDACTED]" + + def test_prefixed_names_match(self) -> None: + assert redact_output("DB_PASSWORD=x") == "DB_PASSWORD=[REDACTED]" + assert redact_output("X-Api-Key: abc") == "X-Api-Key: [REDACTED]" + assert redact_output("github_token=abc") == "github_token=[REDACTED]" + assert redact_output("AWS_SECRET_ACCESS_KEY=abc") == ( + "AWS_SECRET_ACCESS_KEY=[REDACTED]" + ) + + def test_connection_string_keeps_other_fields(self) -> None: + out = redact_output("Server=db1;User Id=sa;Password=s3cr3t;Database=app") + + assert out == "Server=db1;User Id=sa;Password=[REDACTED];Database=app" + + def test_query_string_stops_at_ampersand(self) -> None: + out = redact_output("GET /x?token=abc123&user=bob&page=2") + + assert out == "GET /x?token=[REDACTED]&user=bob&page=2" + + def test_comma_terminates_value(self) -> None: + assert redact_output("password=abc,user=bob") == "password=[REDACTED],user=bob" + + def test_quoted_values_with_spaces(self) -> None: + assert redact_output('password="a b c" next') == "password=[REDACTED] next" + assert redact_output("secret: 'a b' next") == "secret: [REDACTED] next" + + def test_escaped_quote_inside_quoted_value(self) -> None: + out = redact_output(r'password="ab\"cd ef" next=1') + + assert out == "password=[REDACTED] next=1" + + def test_escaped_quote_inside_single_quoted_value(self) -> None: + out = redact_output(r"token: 'ab\'cd' next") + + assert out == "token: [REDACTED] next" + + def test_truncated_quoted_value_masked_to_marker(self) -> None: + text = 'cfg password="abc def\n[... output truncated at 1024 bytes]' + + out = redact_output(text) + + assert out == "cfg password=[REDACTED]\n[... output truncated at 1024 bytes]" + + def test_truncated_quoted_value_masked_to_end_of_text(self) -> None: + assert redact_output("token='abc def") == "token=[REDACTED]" + + @pytest.mark.parametrize( + "text", + [ + 'password="abc\\', + 'password="abc def\\', + "token='abc def\\", + 'password="abc def\\\n[... output truncated at 1024 bytes]', + ], + ) + def test_value_truncated_after_backslash_fully_masked(self, text: str) -> None: + out = redact_output(text) + + assert "abc" not in out + assert "def" not in out + assert "\\" not in out.split("\n")[0] + + def test_stray_quote_does_not_swallow_later_lines(self) -> None: + out = redact_output('password="abc\nuser=bob\n') + + assert out == "password=[REDACTED]\nuser=bob\n" + + def test_json_style(self) -> None: + out = redact_output('{"user": "bob", "password": "hunter2", "n": 1}') + + assert out == '{"user": "bob", "password": [REDACTED], "n": 1}' + + def test_value_on_next_line_is_not_taken(self) -> None: + text = "Password:\nnext line" + + assert redact_output(text) == text + + @pytest.mark.parametrize( + "text", + [ + "passphrase_hint is unset", + "password for bob", + "token_count=5", + "bypass: yes", + "authority=example", + "dovecot: auth: passwd-file(john@ex.com,1.2.3.4)", + "auth: user=, method=PLAIN", + "auth=ok", + "/etc/passwd:john:x:1000:1000::/home/john:/bin/bash", + "passwd: john", + "pass: 1 failed: 0", + ], + ) + def test_ordinary_log_lines_untouched(self, text: str) -> None: + assert redact_output(text) == text + + @pytest.mark.parametrize( + ("text", "expected"), + [ + ("PGPASSWORD=x", "PGPASSWORD=[REDACTED]"), + ("REDISPASS=x", "REDISPASS=[REDACTED]"), + ("dbPassword=x", "dbPassword=[REDACTED]"), + ("userPassword: {SSHA}x", "userPassword: [REDACTED]"), + ('"accessToken": "x"', '"accessToken": [REDACTED]'), + ("SECRET_KEY=x", "SECRET_KEY=[REDACTED]"), + ("secret-key: x", "secret-key: [REDACTED]"), + ("MYSQL_PWD=x", "MYSQL_PWD=[REDACTED]"), + ], + ) + def test_prefixed_variable_names_masked(self, text: str, expected: str) -> None: + assert redact_output(text) == expected + + @pytest.mark.parametrize("text", ["secret_key_base=abc", "SECRET_KEY_BASE=abc"]) + def test_secret_key_base_masked(self, text: str) -> None: + key = text.split("=")[0] + + assert redact_output(text) == f"{key}=[REDACTED]" + + @pytest.mark.parametrize( + "text", + [ + "PWD=/home/x", + "OLDPWD=/tmp", + "pwd: /var/log", + 'PWD="/home/x"', + "export PWD=/srv/app", + ], + ) + def test_pwd_with_path_value_stays_visible(self, text: str) -> None: + assert redact_output(text) == text + + def test_pwd_with_other_value_masked(self) -> None: + assert redact_output("PWD=hunter2") == "PWD=[REDACTED]" + assert redact_output("MYSQL_PWD: abc") == "MYSQL_PWD: [REDACTED]" + + +class TestAuthorizationAndBearer: + def test_authorization_header_redacted(self) -> None: + out = redact_output("Authorization: Bearer abc.def.ghi\nHost: x") + + assert out == "Authorization: [REDACTED]\nHost: x" + + def test_authorization_basic_and_case(self) -> None: + out = redact_output("authorization: Basic dXNlcjpwYXNz") + + assert out == "authorization: [REDACTED]" + + def test_authorization_digest_whole_line(self) -> None: + out = redact_output('Authorization: Digest username="bob", response="ff"') + + assert out == "Authorization: [REDACTED]" + + def test_authorization_json_quoted(self) -> None: + out = redact_output('{"Authorization": "Bearer abc", "x": 1}') + + assert out == '{"Authorization": [REDACTED], "x": 1}' + + def test_unquoted_authorization_stops_at_unbalanced_quote(self) -> None: + out = redact_output('curl -H "Authorization: Bearer x" https://host/') + + assert out == 'curl -H "Authorization: [REDACTED]" https://host/' + + def test_single_quoted_header_in_curl(self) -> None: + out = redact_output("curl -H 'Authorization: Bearer x' https://host/") + + assert out == "curl -H 'Authorization: [REDACTED]' https://host/" + + def test_authorization_with_stray_leading_quote_still_masked(self) -> None: + out = redact_output('Authorization: "Bearer abc def\nnext') + + assert "abc" not in out + assert out.endswith("\nnext") + + def test_bare_bearer_token(self) -> None: + out = redact_output("curl -H 'x-up: Bearer eyJhbGci.abc_-=' http://h") + + assert "eyJhbGci" not in out + assert "Bearer [REDACTED]" in out + + def test_bearer_without_token_untouched(self) -> None: + assert redact_output("bearer\nbonds") == "bearer\nbonds" + + +class TestUrlCredentials: + def test_password_masked_user_kept(self) -> None: + out = redact_output("origin postgres://app:s3cr3t@db1.example.com:5432/x") + + assert out == "origin postgres://app:[REDACTED]@db1.example.com:5432/x" + + def test_empty_user(self) -> None: + assert ( + redact_output("redis://:pw@cache:6379") == "redis://:[REDACTED]@cache:6379" + ) + + def test_other_schemes(self) -> None: + assert redact_output("https://u:p@h/") == "https://u:[REDACTED]@h/" + assert redact_output("ftp://u:p@h/") == "ftp://u:[REDACTED]@h/" + + def test_password_containing_at_sign_masked_whole(self) -> None: + assert redact_output("mysql://u:p@ss@h/db") == "mysql://u:[REDACTED]@h/db" + + def test_userinfo_without_password_untouched(self) -> None: + text = "git clone ssh://git@github.com/org/repo.git" + + assert redact_output(text) == text + + def test_host_port_untouched(self) -> None: + text = "http://example.com:8080/path user@example.com" + + assert redact_output(text) == text + + @pytest.mark.parametrize( + "text", + [ + "http://host:8080?mail=ops@example.com", + "http://host:8080#ops@example.com", + "http://host:8080/x@y.z", + "http://host:8080 ops@example.com", + ], + ) + def test_port_then_email_outside_authority_untouched(self, text: str) -> None: + assert redact_output(text) == text + + @pytest.mark.parametrize( + "text", + [ + '["http://host:8080","ops@example.com"]', + ",ops@example.com", + "'http://host:8080','ops@example.com'", + ], + ) + def test_quotes_and_angle_brackets_end_the_authority(self, text: str) -> None: + assert redact_output(text) == text + + @pytest.mark.parametrize( + ("text", "expected"), + [ + ("https://token:pw@host/x", "https://token:[REDACTED]@host/x"), + ("postgres://password:pw@db", "postgres://password:[REDACTED]@db"), + ("ftp://secret:pw@h:21/p", "ftp://secret:[REDACTED]@h:21/p"), + ("", ""), + ], + ) + def test_keyword_login_keeps_login_and_host(self, text: str, expected: str) -> None: + assert redact_output(text) == expected + + +class TestNotMasked: + """Owner decision: logins, e-mails, IPs and host names stay readable.""" + + def test_logins_emails_ips_hosts_untouched(self) -> None: + text = ( + "login: bob\nuser=alice\nContact ops@example.com or admin@corp.io\n" + "ssh root@10.0.0.5 -p 2222\nlisten 192.168.1.10:443 db1.internal.example\n" + "Accepted publickey for deploy from 203.0.113.7 port 51234" + ) + + assert redact_output(text) == text + + def test_plain_text_returned_unchanged(self) -> None: + text = "uptime: 14:32:01 up 142 days\nExit code: 0 (150ms)" + + assert redact_output(text) == text + + def test_empty_string(self) -> None: + assert redact_output("") == "" + + +class TestTruncationMarker: + def test_secret_before_marker_masked_marker_kept(self) -> None: + text = "log\npassword=hunter2\n[... output truncated at 1024 bytes]" + + out = redact_output(text) + + assert out == "log\npassword=[REDACTED]\n[... output truncated at 1024 bytes]" + + def test_secret_cut_by_truncation_still_masked(self) -> None: + out = redact_output("token=abcd\n[... output truncated at 1024 bytes]") + + assert "abcd" not in out + assert out.endswith("[... output truncated at 1024 bytes]") + + +class TestIdempotentAndCombined: + def test_idempotent(self) -> None: + text = ( + "password=x\nAuthorization: Bearer y\nredis://:z@h\n" + "-----BEGIN PRIVATE KEY-----\nk" # gitleaks:allow (synthetic fixture) + ) + + once = redact_output(text) + + assert redact_output(once) == once + + def test_exec_result_shape(self) -> None: + text = ( + "[web1] $ mysql --password=hunter2 -e 'select 1'\n" + "pass=hunter2\n\nSTDERR:\ntoken=abc\n\nExit code: 1 (10ms)" + ) + + out = redact_output(text) + + assert "hunter2" not in out + assert "abc" not in out + assert out.endswith("Exit code: 1 (10ms)") + + +class TestLinearTime: + """1 MiB of adversarial input must finish far inside the bound.""" + + _CASES = { + "plain": "ordinary output line\n" * (_MIB // 21), + "keys": "password=hunter2;token: abc&x=1\n" * (_MIB // 33), + "key_repeat": "password=" * (_MIB // 9), + "unclosed_dquote": 'password="' * (_MIB // 10), + "unclosed_squote": "token='" * (_MIB // 7), + "pem_begin_repeat": "-----BEGIN PRIVATE KEY-----" * (_MIB // 27), + "pem_long_header": "-----BEGIN " + "A" * _MIB, + "pem_unterminated": "-----BEGIN PRIVATE KEY-----\n" + "A" * _MIB, # gitleaks:allow (synthetic fixture) + "url_marker_repeat": "://a:" * (_MIB // 5), + "url_long_host": "http://" + "a" * _MIB, + "long_word": "a" * _MIB, + "dash_word": "a-" * (_MIB // 2), + "key_prefix_repeat": "token_" * (_MIB // 6), + "key_then_spaces": "password:" + " " * _MIB + "\n", + "authorization_repeat": "authorization:" * (_MIB // 14), + "bearer_repeat": "bearer " * (_MIB // 7), + "pem_blank_repeat": "-----BEGIN PRIVATE KEY-----\n\n" * (_MIB // 29), + "pem_marker_repeat": ( + "-----BEGIN PRIVATE KEY-----\n[... output truncated at 1 bytes]" + ) + * (_MIB // 63), + "dq_escapes": 'password="' + "\\\\\\" * (_MIB // 3), + "dq_backslash_run": 'password="' + "\\" * _MIB, + "url_colon_run": "http://" + "a:" * (_MIB // 2), + "url_at_run": "http://u:" + "@" * _MIB, + "authorization_quote_pairs": "authorization: x" + '""' * (_MIB // 2), + "authorization_unbalanced": 'authorization: x"' + "a" * _MIB, + "url_quote_run": "://u:" + '"' * _MIB, + } + + @pytest.mark.parametrize("name", sorted(_CASES)) + def test_one_mib_within_bound(self, name: str) -> None: + text = self._CASES[name] + + start = time.perf_counter() + redact_output(text) + elapsed = time.perf_counter() - start + + assert elapsed < _TIME_BOUND_S, f"{name}: {elapsed:.2f}s" + + +class TestSettingParsing: + _TEMPLATE = """ +[settings] +{extra} + +[servers.s1] +description = "one" +""" + + def _load(self, tmp_path: Path, extra: str) -> ServerRegistry: + f = tmp_path / "redact.toml" + f.write_text(self._TEMPLATE.format(extra=extra)) + return ServerRegistry(str(f)) + + def test_default_is_off(self) -> None: + assert Settings().redact_output is False + + def test_omitted_key_is_off(self, tmp_path: Path) -> None: + assert self._load(tmp_path, "").settings.redact_output is False + + def test_true_parsed(self, tmp_path: Path) -> None: + registry = self._load(tmp_path, "redact_output = true") + + assert registry.settings.redact_output is True + + def test_false_parsed(self, tmp_path: Path) -> None: + registry = self._load(tmp_path, "redact_output = false") + + assert registry.settings.redact_output is False + + @pytest.mark.parametrize("raw", ['"true"', "1", "0", '"yes"']) + def test_non_bool_rejected_naming_key(self, tmp_path: Path, raw: str) -> None: + with pytest.raises(ConfigError) as exc_info: + self._load(tmp_path, f"redact_output = {raw}") + + assert "redact_output" in str(exc_info.value) diff --git a/tests/test_server.py b/tests/test_server.py index 1f98fd2..d49aff7 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -399,6 +399,145 @@ async def test_tool_error_passthrough(self, mock_init: MagicMock) -> None: await server_module.execute_on_group(group="test-prod", command="rm -rf /") +# --------------------------------------------------------------------------- +# redact_output setting — applied to the execute tools' final string +# --------------------------------------------------------------------------- + + +class TestRedactOutputSetting: + """``execute`` and ``execute_on_group`` mask secrets only when opted in.""" + + _CONFIG = """ +[settings] +redact_output = {value} + +[groups] +g1 = {{ description = "Group" }} + +[servers.web1] +description = "Web" +groups = ["g1"] +""" + + def _init( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, value: str + ) -> MagicMock: + cfg = tmp_path / "redact.toml" + cfg.write_text(self._CONFIG.format(value=value)) + mock_ssh = MagicMock(spec=SSHManager) + monkeypatch.setattr(server_module, "_registry", ServerRegistry(str(cfg))) + monkeypatch.setattr(server_module, "_ssh", mock_ssh) + return mock_ssh + + @staticmethod + def _result() -> ExecResult: + return ExecResult( + server="web1", + command="env", + stdout="DB_PASSWORD=hunter2\nuser=bob host=10.0.0.5 ops@example.com", + stderr="token=abc123", + exit_code=0, + duration_ms=5, + ) + + @pytest.mark.parametrize("value", ["true", "false"]) + async def test_execute( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, value: str + ) -> None: + mock_ssh = self._init(monkeypatch, tmp_path, value) + mock_ssh.execute = AsyncMock(return_value=self._result()) + + out = await server_module.execute(server="web1", command="env") + + if value == "true": + assert "hunter2" not in out + assert "abc123" not in out + assert "DB_PASSWORD=[REDACTED]" in out + assert "token=[REDACTED]" in out + # Logins, hosts, e-mail addresses and IPs stay readable. + assert "user=bob host=10.0.0.5 ops@example.com" in out + else: + assert "DB_PASSWORD=hunter2" in out + assert "token=abc123" in out + assert "[REDACTED]" not in out + + @pytest.mark.parametrize("value", ["true", "false"]) + async def test_execute_on_group( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, value: str + ) -> None: + mock_ssh = self._init(monkeypatch, tmp_path, value) + failed = ExecResult( + server="web2", + command="env", + stdout="", + stderr="", + exit_code=None, + error="login failed: Password=s3cr3t;", + ) + mock_ssh.execute_on_group = AsyncMock(return_value=[self._result(), failed]) + + out = await server_module.execute_on_group(group="g1", command="env") + + if value == "true": + assert "hunter2" not in out + assert "s3cr3t" not in out + assert "DB_PASSWORD=[REDACTED]" in out + assert "user=bob host=10.0.0.5 ops@example.com" in out + else: + assert "hunter2" in out + assert "s3cr3t" in out + assert "[REDACTED]" not in out + + async def test_default_config_does_not_redact(self, mock_init: MagicMock) -> None: + """The shared ``tmp_config_file`` omits the key: behaviour unchanged.""" + mock_init.execute = AsyncMock(return_value=self._result()) + + out = await server_module.execute(server="test-web1", command="env") + + assert "DB_PASSWORD=hunter2" in out + + @pytest.mark.parametrize("value", ["true", "false"]) + async def test_converted_exception_text( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, value: str + ) -> None: + """The text of an exception turned into a ToolError follows the setting.""" + mock_ssh = self._init(monkeypatch, tmp_path, value) + mock_ssh.execute = AsyncMock( + side_effect=RuntimeError("remote said dbToken: qq77x and user bob") + ) + + with pytest.raises(ToolError) as exc_info: + await server_module.execute(server="web1", command="env") + + message = str(exc_info.value) + if value == "true": + assert "qq77x" not in message + assert "dbToken: [REDACTED]" in message + assert "user bob" in message + else: + assert "dbToken: qq77x" in message + + async def test_redaction_runs_off_the_event_loop( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + import threading + + mock_ssh = self._init(monkeypatch, tmp_path, "true") + mock_ssh.execute = AsyncMock(return_value=self._result()) + threads: list[int] = [] + + def spy(text: str) -> str: + threads.append(threading.get_ident()) + return text + + monkeypatch.setattr(server_module, "redact_output", spy) + + await server_module.execute(server="web1", command="env") + + assert threads + assert threads[0] != threading.get_ident() + + # --------------------------------------------------------------------------- # upload_file # --------------------------------------------------------------------------- From d453d0a5a669063d71c70289c02b0559bd53f63b Mon Sep 17 00:00:00 2001 From: blackax Date: Thu, 3 Dec 2026 18:01:42 -0800 Subject: [PATCH 2/2] style: ruff format test_redact --- tests/test_redact.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_redact.py b/tests/test_redact.py index 8313fcb..207591e 100644 --- a/tests/test_redact.py +++ b/tests/test_redact.py @@ -462,7 +462,8 @@ class TestLinearTime: "unclosed_squote": "token='" * (_MIB // 7), "pem_begin_repeat": "-----BEGIN PRIVATE KEY-----" * (_MIB // 27), "pem_long_header": "-----BEGIN " + "A" * _MIB, - "pem_unterminated": "-----BEGIN PRIVATE KEY-----\n" + "A" * _MIB, # gitleaks:allow (synthetic fixture) + "pem_unterminated": "-----BEGIN PRIVATE KEY-----\n" + + "A" * _MIB, # gitleaks:allow (synthetic fixture) "url_marker_repeat": "://a:" * (_MIB // 5), "url_long_host": "http://" + "a" * _MIB, "long_word": "a" * _MIB,