Skip to content
Myr

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

3 files+284 added−4 removed

modified:src/click/termui.py+24 added-4 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 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 lines
modified:tests/test_termui.py+256 added
986 unmodified lines
987988 assert result.output == expected_output989 assert not result.stderr990 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1991992993class _CustomTypeNoValue(click.ParamType):994 name = "custom"995996 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 value100010011002class _CustomTypeWithRawValue(click.ParamType):1003 name = "custom_raw"10041005 def convert(self, value, param, ctx):1006 if value == "bad":1007 self.fail(f"rejected: {value}", param, ctx)1008 return value100910101011class _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 """10161017 name = "password"10181019 def convert(self, value, param, ctx):1020 if len(value) < 10:1021 self.fail(f"{value} is too short", param, ctx)1022 return value102310241025class _MixedQuotedAndRawType(click.ParamType):1026 """Custom type that mentions the user input both quoted (built-in1027 pattern) and raw within the same message.1028 """10291030 name = "mixed"10311032 def convert(self, value, param, ctx):1033 self.fail(f"got {value!r} which is the same as {value}", param, ctx)103410351036class _StaticMessageType(click.ParamType):1037 """Custom type whose error message never references the value."""10381039 name = "static"10401041 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(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)1191def test_hide_input_error_message(1192 runner, type, user_input, expected_fragment, unexpected_fragment1193):1194 """https://github.com/pallets/click/issues/2809"""11951196 @click.command()1197 @click.option("--password", prompt=True, hide_input=True, type=type)1198 def cli(password):1199 click.echo(password)12001201 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
modified:CHANGES.rst+4 added
51 unmodified lines
52- 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`6061Version 8.3.362-------------63
1364 unmodified lines