From 3c7d67da23cdac5f1557dc3b20b751b125b5b1bc Mon Sep 17 00:00:00 2001 From: Emily Date: Sat, 16 Aug 2025 02:29:43 +0100 Subject: [PATCH] lib: deprecate `fromHexString` on dodgy inputs See . --- lib/tests/misc.nix | 28 +++++++--------------------- lib/trivial.nix | 19 +++++++++++++------ 2 files changed, 20 insertions(+), 27 deletions(-) diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index ce07750d7ca0..6b9767fbc5d4 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -386,35 +386,21 @@ runTests { expected = 9223372036854775807; }; + testFromHexStringLeadingZeroes = { + expr = fromHexString "00ffffffffffffff"; + expected = 72057594037927935; + }; + testFromHexStringWithPrefix = { - expr = fromHexString "0Xf"; + expr = fromHexString "0xf"; expected = 15; }; - # FIXME: This might be bad and should potentially be deprecated. - testFromHexStringQuestionableMixedCase = { + testFromHexStringMixedCase = { expr = fromHexString "eEeEe"; expected = 978670; }; - # FIXME: This is probably bad and should potentially be deprecated. - testFromHexStringQuestionableUnderscore = { - expr = fromHexString "F_f"; - expected = 255; - }; - - # FIXME: This is definitely bad and should be deprecated. - testFromHexStringBadComment = { - expr = fromHexString "0 # oops"; - expected = 0; - }; - - # FIXME: Oh my god. - testFromHexStringAwfulInjection = { - expr = fromHexString "1\nwhoops = {}"; - expected = 1; - }; - testToBaseDigits = { expr = toBaseDigits 2 6; expected = [ diff --git a/lib/trivial.nix b/lib/trivial.nix index d1887f6a3ce4..7e4c5f549ee7 100644 --- a/lib/trivial.nix +++ b/lib/trivial.nix @@ -1119,14 +1119,21 @@ in ``` */ fromHexString = - value: + str: let - noPrefix = lib.strings.removePrefix "0x" (lib.strings.toLower value); + match = builtins.match "(0x)?([0-7]?[0-9A-Fa-f]{1,15})" str; in - let - parsed = builtins.fromTOML "v=0x${noPrefix}"; - in - parsed.v; + if match != null then + (builtins.fromTOML "v=0x${builtins.elemAt match 1}").v + else + # TODO: Turn this into a `throw` in 26.05. + assert lib.warn "fromHexString: ${ + lib.generators.toPretty { } str + } is not a valid input and will be rejected in 26.05" true; + let + noPrefix = lib.strings.removePrefix "0x" (lib.strings.toLower str); + in + (builtins.fromTOML "v=0x${noPrefix}").v; /** Convert the given positive integer to a string of its hexadecimal