Skip to content
Myr

Implement a regex-based solution to hide hidden input

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kevin Deldycke · committed by Kevin Deldycke · parent efd4daf · Browse files · 2 files+162 added−21 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+162 added−21 removed

  • tests:+138 added−4 removed
  • other:+24 added−17 removed

2 files+162 added−21 removed

modified:src/click/termui.py+24 added-17 removed
2 unmodified lines
3import collections.abc as cabc4import inspect5import io6import itertools7import re8import sys9import typing as t10from contextlib import AbstractContextManager11from contextlib import redirect_stdout
41 unmodified lines
53}54_ansi_reset_all = "\033[0m"555657_HIDDEN_INPUT_MASK = "'***'"585960def _mask_hidden_input(message: str, value: str) -> str:61 """Replace occurrences of ``value`` in ``message`` with a fixed mask.6263 Both ``repr(value)`` (the form built-in :class:`ParamType` errors use64 via ``{value!r}``) and the raw value are masked. The raw-value pass65 uses word-boundary lookarounds so a substring like ``"1"`` does not66 match inside ``"10"``, and ``"ent"`` does not match inside67 ``"Authentication"``. The empty string is skipped to avoid matching68 at every boundary.69 """70 message = message.replace(repr(value), _HIDDEN_INPUT_MASK)71 if value:72 message = re.sub(73 rf"(?<!\w){re.escape(value)}(?!\w)", _HIDDEN_INPUT_MASK, message74 )75 return message767778def hidden_prompt_func(prompt: str) -> str:79 import getpass8081 return getpass.getpass(prompt)
141 unmodified lines
223 break224 try:225 result = value_proc(value)226 except UsageError as e:205 if hide_input:206 repr_val = repr(value)207 if repr_val in e.message:208 # Built-in type pattern: mask the repr'd value.209 msg = e.message.replace(repr_val, "'***'")210 elif value in e.message:211 # Raw value found: could be a coincidental or212 # unquoted match. Ambiguous, use generic.213 msg = _("The value you entered was invalid.")214 else:215 # Value not found: show as-is, assuming custom216 # types with hide_input=True avoid leaking input.217 msg = e.message218219 echo(_("Error: {msg}").format(msg=msg), err=err)220 else:221 echo(_("Error: {e.message}").format(e=e), err=err)227 message = _mask_hidden_input(e.message, value) if hide_input else e.message228 echo(_("Error: {message}").format(message=message), err=err)229 continue230 if not confirmation_prompt:231 return result232 while True:
709 unmodified lines
modified:tests/test_termui.py+138 added-4 removed
1040 unmodified lines
1041 def convert(self, value, param, ctx):1042 self.fail("Authentication failed for this account", param, ctx)104310441045class _RejectAllRawType(click.ParamType):1046 """Always rejects, with the raw value (unquoted) in the message."""10471048 name = "reject_all_raw"10491050 def convert(self, value, param, ctx):1051 self.fail(f"rejected: {value}", param, ctx)105210531054class _MultiRawType(click.ParamType):1055 """Mentions the raw value multiple times in the same message."""10561057 name = "multi_raw"10581059 def convert(self, value, param, ctx):1060 self.fail(f"got {value} but {value} is bad", param, ctx)106110621063class _MultiReprType(click.ParamType):1064 """Mentions ``repr(value)`` multiple times in the same message."""10651066 name = "multi_repr"10671068 def convert(self, value, param, ctx):1069 self.fail(f"got {value!r} and {value!r}", param, ctx)107010711072class _ApostropheReprType(click.ParamType):1073 """Custom type whose ``repr(value)`` switches to double quotes when1074 the value itself contains a single quote.1075 """10761077 name = "apostrophe_repr"10781079 def convert(self, value, param, ctx):1080 self.fail(f"rejected {value!r}", param, ctx)108110821083@pytest.mark.parametrize(1084 ("type", "user_input", "expected_fragment", "unexpected_fragment"),1085 [1086 pytest.param(
12 unmodified lines
1099 ),1100 pytest.param(1101 _CustomTypeWithRawValue(),1102 "bad",1065 "The value you entered was invalid",1103 "rejected: '***'",1104 "bad",1067 id="custom-raw-value-falls-back-to-generic",1105 id="custom-raw-value-masked",1106 ),1107 pytest.param(1108 _PasswordLengthType(),1109 "PASSWORD",
3 unmodified lines
1113 ),1114 pytest.param(1115 _MixedQuotedAndRawType(),1116 "leakybits",1079 "Error:",1117 "got '***' which is the same as '***'",1118 "leakybits",1081 id="repr-branch-leaves-raw-occurrence-visible",1119 id="mixed-quoted-and-raw-both-masked-at-source",1120 ),1121 pytest.param(1122 click.IntRange(min=10, max=99),1123 "1",
7 unmodified lines
1131 "Authentication failed for this account",1132 None,1133 id="partial-word-match-falls-back-to-generic",1134 ),1135 # When the raw (unquoted) value appears in the message, mask it instead1136 # of replacing the whole message with a generic fallback that throws1137 # useful information away.1138 pytest.param(1139 _RejectAllRawType(),1140 "secret",1141 "rejected: '***'",1142 "secret",1143 id="raw-value-should-be-masked-not-fallback",1144 ),1145 # When the raw value occurs more than1146 # once unquoted, every occurrence must be masked.1147 pytest.param(1148 _MultiRawType(),1149 "secret",1150 "got '***' but '***' is bad",1151 "secret",1152 id="multi-occurrence-raw-mask-all",1153 ),1154 pytest.param(1155 _MultiReprType(),1156 "secret",1157 "got '***' and '***'",1158 "secret",1159 id="multi-occurrence-repr-mask-all",1160 ),1161 pytest.param(1162 _PasswordLengthType(),1163 "a.b*c+",1164 "'***' is too short",1165 "a.b*c+",1166 id="regex-special-chars-must-be-escaped",1167 ),1168 pytest.param(1169 _PasswordLengthType(),1170 "пароль",1171 "'***' is too short",1172 "пароль",1173 id="unicode-value-masked",1174 ),1175 pytest.param(1176 _ApostropheReprType(),1177 "it's",1178 "rejected '***'",1179 "it's",1180 id="apostrophe-in-value-uses-double-quote-repr",1181 ),1182 pytest.param(1183 _MixedQuotedAndRawType(),1184 "leakybits",1185 "got '***' which is the same as '***'",1186 "leakybits",1187 id="mixed-quoted-and-raw-mask-both",1188 ),1189 ],1190)1191def test_hide_input_error_message(1192 runner, type, user_input, expected_fragment, unexpected_fragment
8 unmodified lines
1201 result = runner.invoke(cli, input=user_input)1202 assert expected_fragment in result.output1203 if unexpected_fragment is not None:1204 assert unexpected_fragment not in result.output120512061207def test_hide_input_confirmation_prompt_mismatch_unaffected(runner):1208 """The ``hide_input`` mask logic only applies to ``value_proc``1209 failures. The separate ``confirmation_prompt`` mismatch path must1210 keep emitting its own message, with no value leak from either entry.1211 """12121213 @click.command()1214 @click.option("--password", prompt=True, confirmation_prompt=True, hide_input=True)1215 def cli(password):1216 click.echo(f"got: {password}")12171218 # First pair mismatches, second pair matches.1219 result = runner.invoke(cli, input="firstone\nsecondone\nfinalone\nfinalone\n")1220 assert "Error: The two entered values do not match." in result.output1221 assert "firstone" not in result.output1222 assert "secondone" not in result.output1223 # Successful prompt echoes the final value back via the command body.1224 assert "got: finalone" in result.output1225 assert result.exit_code == 0122612271228def test_hide_input_value_never_leaks_when_err_true(runner):1229 """``click.prompt(..., err=True)`` routes its error message to1230 stderr. The masking logic must apply on that path too: the raw1231 input must not appear on either stream.1232 """12331234 @click.command()1235 def cli():1236 value = click.prompt(1237 "Password",1238 hide_input=True,1239 type=_PasswordLengthType(),1240 err=True,1241 )1242 click.echo(value)12431244 result = runner.invoke(cli, input="leaky\n", mix_stderr=False)1245 assert "leaky" not in result.stdout1246 assert "leaky" not in result.stderr