Show custom error message in prompt with `hide_input=True` (#3256)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents fc6c7c4, 61bdc2a · Browse files · 3 files·+284 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+284 added−4 removed
- tests:+256 added−0 removed
- other:+28 added−4 removed
Provenance
- Commit
c943271- Tree
f5d65fa- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
fc6c7c4- Parent 2
61bdc2a
3 files changed+284 added−4 removed
modified:src/click/termui.py+24 added-4 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- echo(_("Error: The value you entered was invalid."), err=err)207- else:208- 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+256 added
986 unmodified lines987 988 assert result.output == expected_output989 assert not result.stderr990 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1991+992+993+class _CustomTypeNoValue(click.ParamType):994+ name = "custom"995+996+ def convert(self, value, param, ctx):997+ if len(value) < 4:998+ self.fail("Password must be at least 4 characters", param, ctx)999+ return value1000+1001+1002+class _CustomTypeWithRawValue(click.ParamType):1003+ name = "custom_raw"1004+1005+ def convert(self, value, param, ctx):1006+ if value == "bad":1007+ self.fail(f"rejected: {value}", param, ctx)1008+ return value1009+1010+1011+class _PasswordLengthType(click.ParamType):1012+ """Mirrors the issue's original use case: a password validator1013+ that references the user-typed value in its error message without1014+ quoting it.1015+ """1016+1017+ name = "password"1018+1019+ def convert(self, value, param, ctx):1020+ if len(value) < 10:1021+ self.fail(f"{value} is too short", param, ctx)1022+ return value1023+1024+1025+class _MixedQuotedAndRawType(click.ParamType):1026+ """Custom type that mentions the user input both quoted (built-in1027+ pattern) and raw within the same message.1028+ """1029+1030+ name = "mixed"1031+1032+ def convert(self, value, param, ctx):1033+ self.fail(f"got {value!r} which is the same as {value}", param, ctx)1034+1035+1036+class _StaticMessageType(click.ParamType):1037+ """Custom type whose error message never references the value."""1038+1039+ name = "static"1040+1041+ 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(1087+ click.INT,1088+ "bad",1089+ "'***' is not a valid integer",1090+ "bad",1091+ id="builtin-int-masks-repr-value",1092+ ),1093+ pytest.param(1094+ _CustomTypeNoValue(),1095+ "bad",1096+ "Password must be at least 4 characters",1097+ None,1098+ id="custom-no-value-shows-message",1099+ ),1100+ pytest.param(1101+ _CustomTypeWithRawValue(),1102+ "bad",1103+ "rejected: '***'",1104+ "bad",1105+ id="custom-raw-value-masked",1106+ ),1107+ pytest.param(1108+ _PasswordLengthType(),1109+ "PASSWORD",1110+ "'***' is too short",1111+ "PASSWORD",1112+ id="unquoted-custom-message-should-mask-not-fallback",1113+ ),1114+ pytest.param(1115+ _MixedQuotedAndRawType(),1116+ "leakybits",1117+ "got '***' which is the same as '***'",1118+ "leakybits",1119+ id="mixed-quoted-and-raw-both-masked-at-source",1120+ ),1121+ pytest.param(1122+ click.IntRange(min=10, max=99),1123+ "1",1124+ "is not in the range",1125+ None,1126+ id="intrange-numeric-substring-falls-back-to-generic",1127+ ),1128+ pytest.param(1129+ _StaticMessageType(),1130+ "ent",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+)1191+def test_hide_input_error_message(1192+ runner, type, user_input, expected_fragment, unexpected_fragment1193+):1194+ """https://github.com/pallets/click/issues/2809"""1195+1196+ @click.command()1197+ @click.option("--password", prompt=True, hide_input=True, type=type)1198+ def cli(password):1199+ click.echo(password)1200+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.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.stderrmodified:CHANGES.rst+4 added
51 unmodified lines52 - Use :class:`ValueError` message when conversion in :class:`FuncParamType` would53 fail. :issue:`3105` :pr:`3211`54 - Add ``click.get_pager_file`` for file-like access to an output55 pager. :pr:`1572`56+- Show custom error messages from types when :func:`prompt` with57+ ``hide_input=True`` fails validation, instead of always showing a58+ generic message. Built-in type messages mask the input value.59+ :issue:`2809` :pr:`3256`60 61 Version 8.3.362 -------------63 1364 unmodified lines