config: require at least one digit when parsing numbers

If the input to strtoimax() or strtoumax() does not contain any digits then they return zero and set `end` to point to the start of the input string. git_parse_[un]signed() do not check `end` and so fail to return an error and instead return a value of zero if the input string is a valid units factor without any digits (e.g "k"). Tests are added to check that 'git config --int' and OPT_MAGNITUDE() reject a units specifier without a leading digit. Helped-by: Jeff King <peff@peff.net> Signed-off-by: Phillip Wood <phillip.wood@dunelm.org.uk> Signed-off-by: Taylor Blau <me@ttaylorr.com>

Phillip Wood committed Nov 9, 2022 at 14:16 UTC 7595c0ece1d45ca540f26cecf485285f5ce8186f
3 files changed +21
config.c
+8
@@ -1167,6 +1167,10 @@ static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1167 val = strtoimax(value, &end, 0);
1168 if (errno == ERANGE)
1169 return 0;
1170 + if (end == value) {
1171 + errno = EINVAL;
1172 + return 0;
1173 + }
1174 factor = get_unit_factor(end);
1175 if (!factor) {
1176 errno = EINVAL;
@@ -1202,6 +1206,10 @@ static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1206 val = strtoumax(value, &end, 0);
1207 if (errno == ERANGE)
1208 return 0;
1209 + if (end == value) {
1210 + errno = EINVAL;
1211 + return 0;
1212 + }
1213 factor = get_unit_factor(end);
1214 if (!factor) {
1215 errno = EINVAL;
t/t0040-parse-options.sh
+7
@@ -714,4 +714,11 @@ test_expect_success 'negative magnitude' '
714 grep "non-negative integer" err &&
715 test_must_be_empty out
716 '
717 +
718 +test_expect_success 'magnitude with units but no numbers' '
719 + test_must_fail test-tool parse-options --magnitude m >out 2>err &&
720 + grep "non-negative integer" err &&
721 + test_must_be_empty out
722 +'
723 +
724 test_done
t/t1300-config.sh
+6
@@ -2228,6 +2228,12 @@ test_expect_success '--type rejects unknown specifiers' '
2228 test_i18ngrep "unrecognized --type argument" error
2229 '
2230
2231 +test_expect_success '--type=int requires at least one digit' '
2232 + test_must_fail git config --type int --default m some.key >out 2>error &&
2233 + grep "bad numeric config value" error &&
2234 + test_must_be_empty out
2235 +'
2236 +
2237 test_expect_success '--replace-all does not invent newlines' '
2238 q_to_tab >.git/config <<-\EOF &&
2239 [abc]key