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
Provenance
- Commit
61bdc2a- Tree
f5d65fa- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
efd4daf
2 files changed+162 added−21 removed
modified:src/click/termui.py+24 added-17 removed
2 unmodified lines3 import collections.abc as cabc4 import inspect5 import io6 import itertools7+import re8 import sys9 import typing as t10 from contextlib import AbstractContextManager11 from contextlib import redirect_stdout41 unmodified lines53 }54 _ansi_reset_all = "\033[0m"55 56 57+_HIDDEN_INPUT_MASK = "'***'"58+59+60+def _mask_hidden_input(message: str, value: str) -> str:61+ """Replace occurrences of ``value`` in ``message`` with a fixed mask.62+63+ 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 message76+77+78 def hidden_prompt_func(prompt: str) -> str:79 import getpass80 81 return getpass.getpass(prompt)141 unmodified lines223 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.message218-219- 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 linesmodified:tests/test_termui.py+138 added-4 removed
1040 unmodified lines1041 def convert(self, value, param, ctx):1042 self.fail("Authentication failed for this account", param, ctx)1043 1044 1045+class _RejectAllRawType(click.ParamType):1046+ """Always rejects, with the raw value (unquoted) in the message."""1047+1048+ name = "reject_all_raw"1049+1050+ def convert(self, value, param, ctx):1051+ self.fail(f"rejected: {value}", param, ctx)1052+1053+1054+class _MultiRawType(click.ParamType):1055+ """Mentions the raw value multiple times in the same message."""1056+1057+ name = "multi_raw"1058+1059+ def convert(self, value, param, ctx):1060+ self.fail(f"got {value} but {value} is bad", param, ctx)1061+1062+1063+class _MultiReprType(click.ParamType):1064+ """Mentions ``repr(value)`` multiple times in the same message."""1065+1066+ name = "multi_repr"1067+1068+ def convert(self, value, param, ctx):1069+ self.fail(f"got {value!r} and {value!r}", param, ctx)1070+1071+1072+class _ApostropheReprType(click.ParamType):1073+ """Custom type whose ``repr(value)`` switches to double quotes when1074+ the value itself contains a single quote.1075+ """1076+1077+ name = "apostrophe_repr"1078+1079+ def convert(self, value, param, ctx):1080+ self.fail(f"rejected {value!r}", param, ctx)1081+1082+1083 @pytest.mark.parametrize(1084 ("type", "user_input", "expected_fragment", "unexpected_fragment"),1085 [1086 pytest.param(12 unmodified lines1099 ),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 lines1113 ),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 lines1131 "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 )1191 def test_hide_input_error_message(1192 runner, type, user_input, expected_fragment, unexpected_fragment8 unmodified lines1201 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.output1205+1206+1207+def 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+ """1212+1213+ @click.command()1214+ @click.option("--password", prompt=True, confirmation_prompt=True, hide_input=True)1215+ def cli(password):1216+ click.echo(f"got: {password}")1217+1218+ # 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 == 01226+1227+1228+def 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+ """1233+1234+ @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)1243+1244+ result = runner.invoke(cli, input="leaky\n", mix_stderr=False)1245+ assert "leaky" not in result.stdout1246+ assert "leaky" not in result.stderr