From 02c3a6a335d5e013e5abb723da51aca1ab0c71f2 Mon Sep 17 00:00:00 2001 From: Joey Smith Date: Tue, 3 Nov 2026 20:33:16 -0600 Subject: [PATCH] Reject custom In specifications that cannot be expanded safely CustomSpecification::expand() split the specification on the two placeholder forms it knew and passed every other character through to vsprintf. Two consequences: - A sprintf modifier inside a placeholder, as in %1$05s, was not recognised, so the placeholder reached the rendered SQL intact and vsprintf then formatted the bound parameter name rather than the value. - A conversion other than %s, such as %d or %f, was left for vsprintf to consume, which shifted every later parameter by one. Both now go through one tokenizer that matches a placeholder carrying any sprintf modifier. A conversion other than the string conversion, plain and positional placeholders mixed in one specification, and an unescaped percent sign are all rejected with a named constructor. Modifiers are accepted and ignored, because the value they would format is a placeholder name rather than a value. Escaped percents are skipped by the tokenizer and left for AbstractSql to unescape exactly once. ArgumentPlaceholders is extracted from CustomSpecification so that the validation does not push either class past the complexity gate. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/Sql/Predicate/ArgumentPlaceholders.php | 71 +++++++ src/Sql/Predicate/CustomSpecification.php | 180 +++++++++++------- .../Exception/InvalidArgumentException.php | 16 ++ .../Sql/Predicate/CustomSpecificationTest.php | 46 +++++ .../InvalidArgumentExceptionTest.php | 12 ++ test/unit/Sql/Predicate/InTest.php | 9 + 6 files changed, 266 insertions(+), 68 deletions(-) create mode 100644 src/Sql/Predicate/ArgumentPlaceholders.php diff --git a/src/Sql/Predicate/ArgumentPlaceholders.php b/src/Sql/Predicate/ArgumentPlaceholders.php new file mode 100644 index 000000000..402483fac --- /dev/null +++ b/src/Sql/Predicate/ArgumentPlaceholders.php @@ -0,0 +1,71 @@ +getType(), + [ArgumentType::Identifier, ArgumentType::Identifiers, ArgumentType::Literal], + strict: true, + ); + } + + /** + * Placeholder text for every value each argument renders, keyed by argument index + * + * @param list $arguments + * @return array + */ + public static function runs(array $arguments): array + { + $runs = []; + $position = 1; + foreach ($arguments as $index => $argument) { + $count = $argument instanceof Values ? count($argument->getValue()) : 1; + + $runs[$index] = self::run($position, $count); + $position += $count; + } + + return $runs; + } + + /** + * Positional placeholders for $count values, starting at $position + */ + private static function run(int $position, int $count): string + { + return 0 === $count + ? 'NULL' + : implode(', ', array_map( + static fn(int $offset): string => "%{$offset}\$s", + range($position, $position + $count - 1), + )); + } +} diff --git a/src/Sql/Predicate/CustomSpecification.php b/src/Sql/Predicate/CustomSpecification.php index 24b024a60..5856a50d5 100644 --- a/src/Sql/Predicate/CustomSpecification.php +++ b/src/Sql/Predicate/CustomSpecification.php @@ -4,69 +4,100 @@ namespace PhpDb\Sql\Predicate; -use PhpDb\Sql\Argument\Values; use PhpDb\Sql\ArgumentInterface; -use PhpDb\Sql\ArgumentType; use PhpDb\Sql\Predicate\Exception\InvalidArgumentException; use function array_count_values; -use function array_map; use function count; -use function implode; -use function in_array; -use function preg_split; -use function range; -use function substr; - -use const PREG_SPLIT_DELIM_CAPTURE; +use function preg_match; +use function preg_replace; +use function preg_replace_callback; +use function str_contains; +use function str_replace; /** * Aligns a user-supplied predicate specification with the values its arguments render * * A custom specification refers to each argument with a single placeholder, plain (%s) or - * positional (%2$s), but a Values argument renders one value per list item. Each placeholder - * is replaced by positional placeholders for every value its argument renders, so %2$s becomes - * %2$s, %3$s for a two-value list and NULL for an empty one. + * positional (%2$s). Each placeholder is replaced by the positional placeholders for every value + * its argument renders, which ArgumentPlaceholders maps. + * + * Only the string conversion is supported. Width, precision, sign, padding and alignment + * modifiers are accepted but ignored, because the value they would format is a placeholder name + * rather than a value. A literal percent must be written as %%, which is left in place for the + * caller to unescape exactly once. * * @internal */ final class CustomSpecification { + /** + * A placeholder in plain (%s) or positional (%2$s) form, with any sprintf modifiers + * + * Escaped percents are skipped, so they never match and are therefore never rewritten. + */ + private const string PLACEHOLDER = '/%%(*SKIP)(*FAIL)|%(?:(\d+)\$)?[-+ 0\']*\d*(?:\.\d+)?([a-zA-Z])/'; + + /** + * A positional placeholder, and any placeholder that is not positional + * + * Escaped percents are skipped, so they never count as either style. + */ + private const string POSITIONAL_PLACEHOLDER = '/%%(*SKIP)(*FAIL)|%\d+\$/'; + private const string PLAIN_PLACEHOLDER = '/%%(*SKIP)(*FAIL)|%(?!\d+\$)/'; + /** * @param list $arguments - * @throws InvalidArgumentException When a placeholder names a missing argument, or an - * argument that binds values is not referenced exactly once. + * @throws InvalidArgumentException When a placeholder names a missing argument, an argument + * that binds values is not referenced exactly once, a conversion other than the string + * conversion is used, plain and positional placeholders are mixed, or a percent sign is + * not escaped. */ public static function expand(string $specification, array $arguments): string { - $offsets = self::offsets($arguments); + self::assertPlaceholdersAreWellFormed($specification); + + $runs = ArgumentPlaceholders::runs($arguments); $referenced = []; $sequential = 0; - $expanded = ''; - - /** @var list $parts */ - $parts = preg_split('/%%(*SKIP)(*FAIL)|(%(?:\d+\$)?s)/', $specification, flags: PREG_SPLIT_DELIM_CAPTURE); - foreach ($parts as $part => $text) { - if (0 === ($part % 2)) { - $expanded .= $text; - continue; - } - $index = '%s' === $text ? $sequential++ : (int) substr($text, offset: 1, length: -2) - 1; - $argument = $arguments[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange( - $specification, - $index + 1, - count($arguments), + $expanded = preg_replace_callback( + self::PLACEHOLDER, + static function (array $match) use ($specification, $runs, &$referenced, &$sequential): string { + [$placeholders, $index] = self::expandPlaceholder( + match: $match, + specification: $specification, + runs: $runs, + sequential: $sequential, ); - $referenced[] = $index; - $expanded .= self::placeholders($argument, $offsets[$index] ?? 1); - } + $referenced[] = $index; + + return $placeholders; + }, + $specification, + ); + + self::assertBoundArgumentsReferencedOnce($specification, $arguments, $referenced); + + return $expanded ?? ''; + } + /** + * Reject a specification that does not reference every bound argument exactly once + * + * @param list $arguments + * @param list $referenced + */ + private static function assertBoundArgumentsReferencedOnce( + string $specification, + array $arguments, + array $referenced, + ): void { $references = array_count_values($referenced); foreach ($arguments as $index => $argument) { $count = $references[$index] ?? 0; - if (1 !== $count && self::bindsValues($argument)) { + if (1 !== $count && ArgumentPlaceholders::bindsValues($argument)) { throw InvalidArgumentException::forSpecificationArgumentNotReferencedOnce( $specification, $index + 1, @@ -74,52 +105,65 @@ public static function expand(string $specification, array $arguments): string ); } } - - return $expanded; } /** - * Whether rendering the argument binds parameters, so repeating or omitting it would misalign them + * Reject a specification whose placeholders and percent signs cannot be expanded */ - private static function bindsValues(ArgumentInterface $argument): bool + private static function assertPlaceholdersAreWellFormed(string $specification): void { - return ! in_array( - $argument->getType(), - [ArgumentType::Identifier, ArgumentType::Identifiers, ArgumentType::Literal], - strict: true, + $literals = preg_replace( + pattern: self::PLACEHOLDER, + replacement: '', + subject: $specification, ); - } - /** - * Position of each argument's first rendered value - * - * @param list $arguments - * @return array - */ - private static function offsets(array $arguments): array - { - $offsets = []; - $position = 1; - foreach ($arguments as $index => $argument) { - $offsets[$index] = $position; - $position += $argument instanceof Values ? count($argument->getValue()) : 1; + if (str_contains(str_replace( + search: '%%', + replace: '', + subject: (string) $literals, + ), '%')) { + throw InvalidArgumentException::forSpecificationUnsupportedConversion($specification, '%'); } - return $offsets; + $positional = preg_match(self::POSITIONAL_PLACEHOLDER, $specification); + $plain = preg_match(self::PLAIN_PLACEHOLDER, $specification); + + if (1 === $positional && 1 === $plain) { + throw InvalidArgumentException::forSpecificationMixedPlaceholderStyles($specification); + } } /** - * Positional placeholders for every value an argument renders, starting at $offset + * Placeholders for one match, and the index of the argument it references + * + * @param array $match + * @param array $runs + * @return array{string, int} */ - private static function placeholders(ArgumentInterface $argument, int $offset): string - { - $count = $argument instanceof Values ? count($argument->getValue()) : 1; - - return 0 === $count - ? 'NULL' - : implode(', ', array_map( - static fn(int $position): string => "%{$position}\$s", - range($offset, $offset + $count - 1), - )); + private static function expandPlaceholder( + array $match, + string $specification, + array $runs, + int &$sequential, + ): array { + if ('s' !== ($match[2] ?? '')) { + throw InvalidArgumentException::forSpecificationUnsupportedConversion( + $specification, + $match[0] ?? '', + ); + } + + $positional = $match[1] ?? ''; + $index = '' === $positional ? $sequential++ : (int) $positional - 1; + + return [ + $runs[$index] ?? throw InvalidArgumentException::forSpecificationArgumentOutOfRange( + $specification, + $index + 1, + count($runs), + ), + $index, + ]; } } diff --git a/src/Sql/Predicate/Exception/InvalidArgumentException.php b/src/Sql/Predicate/Exception/InvalidArgumentException.php index 100c52668..f381b82c6 100644 --- a/src/Sql/Predicate/Exception/InvalidArgumentException.php +++ b/src/Sql/Predicate/Exception/InvalidArgumentException.php @@ -39,6 +39,10 @@ class InvalidArgumentException extends Exception\InvalidArgumentException final public const string SPECIFICATION_ARGUMENT_OUT_OF_RANGE = 'Specification "%s" references argument %d, but only %d arguments are available'; + final public const string SPECIFICATION_MIXED_PLACEHOLDER_STYLES = 'Specification "%s" mixes plain (%%s) and positional (%%N$s) placeholders; use one style throughout'; + + final public const string SPECIFICATION_UNSUPPORTED_CONVERSION = 'Specification "%s" contains the unsupported conversion "%s"; only %%s and %%N$s placeholders are supported and a literal percent must be escaped as %%%%'; + public static function forInvalidCombination(): self { return new self(self::INVALID_COMBINATION); @@ -114,4 +118,16 @@ public static function forSpecificationArgumentOutOfRange( ): self { return new self(sprintf(self::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, $specification, $position, $available)); } + + public static function forSpecificationMixedPlaceholderStyles(string $specification): self + { + return new self(sprintf(self::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, $specification)); + } + + public static function forSpecificationUnsupportedConversion( + string $specification, + string $conversion, + ): self { + return new self(sprintf(self::SPECIFICATION_UNSUPPORTED_CONVERSION, $specification, $conversion)); + } } diff --git a/test/unit/Sql/Predicate/CustomSpecificationTest.php b/test/unit/Sql/Predicate/CustomSpecificationTest.php index 4dfec38ee..114097d4d 100644 --- a/test/unit/Sql/Predicate/CustomSpecificationTest.php +++ b/test/unit/Sql/Predicate/CustomSpecificationTest.php @@ -6,6 +6,7 @@ use PhpDb\Sql\Argument; use PhpDb\Sql\ArgumentInterface; +use PhpDb\Sql\Predicate\ArgumentPlaceholders; use PhpDb\Sql\Predicate\CustomSpecification; use PhpDb\Sql\Predicate\Exception\InvalidArgumentException; use PhpDb\Sql\Select; @@ -17,6 +18,7 @@ use function sprintf; +#[CoversClass(ArgumentPlaceholders::class)] #[CoversClass(CustomSpecification::class)] #[Group('unit')] final class CustomSpecificationTest extends TestCase @@ -60,6 +62,26 @@ public static function expansionProvider(): array [Argument::identifier('id'), Argument::values([1, 2])], "%1\$s IN (%2\$s, %3\$s) AND 'a%%s' <> ''", ], + 'width modifier ignored' => [ + '%1$s = ANY (ARRAY[%2$05s])', + [Argument::identifier('id'), Argument::values([1, 2])], + '%1$s = ANY (ARRAY[%2$s, %3$s])', + ], + 'precision modifier ignored' => [ + '%.2s = ANY (ARRAY[%s])', + [Argument::identifier('id'), Argument::values([1, 2])], + '%1$s = ANY (ARRAY[%2$s, %3$s])', + ], + 'padding modifier ignored' => [ + "%'10s IN (%s)", + [Argument::identifier('id'), Argument::values([1, 2])], + '%1$s IN (%2$s, %3$s)', + ], + 'escape left for the caller' => [ + '100%% > 0', + [], + '100%% > 0', + ], 'empty list' => [ '%1$s = ANY (ARRAY[%2$s])', [Argument::identifier('id'), Argument::values([])], @@ -119,6 +141,30 @@ public static function inconsistentSpecificationProvider(): array $inList, sprintf(InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, '%s IN (%s) OR %s', 3, 2), ], + 'unsupported conversion' => [ + '%1$s IN (%2$d)', + $inList, + sprintf(InvalidArgumentException::SPECIFICATION_UNSUPPORTED_CONVERSION, '%1$s IN (%2$d)', '%2$d'), + ], + 'unescaped percent in text' => [ + '%1$s IN (%2$s) AND 50% > 0', + $inList, + sprintf( + InvalidArgumentException::SPECIFICATION_UNSUPPORTED_CONVERSION, + '%1$s IN (%2$s) AND 50% > 0', + '%', + ), + ], + 'unescaped trailing percent' => [ + '%1$s IN (%2$s)%', + $inList, + sprintf(InvalidArgumentException::SPECIFICATION_UNSUPPORTED_CONVERSION, '%1$s IN (%2$s)%', '%'), + ], + 'mixed placeholder styles' => [ + '%2$s IN (%s)', + $inList, + sprintf(InvalidArgumentException::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, '%2$s IN (%s)'), + ], ]; } diff --git a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php index aaecb87f7..ebe1c1972 100644 --- a/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php +++ b/test/unit/Sql/Predicate/Exception/InvalidArgumentExceptionTest.php @@ -28,6 +28,8 @@ #[CoversMethod(InvalidArgumentException::class, 'forPredicateWithStringKey')] #[CoversMethod(InvalidArgumentException::class, 'forSpecificationArgumentNotReferencedOnce')] #[CoversMethod(InvalidArgumentException::class, 'forSpecificationArgumentOutOfRange')] +#[CoversMethod(InvalidArgumentException::class, 'forSpecificationMixedPlaceholderStyles')] +#[CoversMethod(InvalidArgumentException::class, 'forSpecificationUnsupportedConversion')] final class InvalidArgumentExceptionTest extends TestCase { /** @return array, string}> */ @@ -99,6 +101,16 @@ public static function namedConstructorProvider(): array ['%1$s IN (%3$s)', 3, 2], InvalidArgumentException::SPECIFICATION_ARGUMENT_OUT_OF_RANGE, ], + 'specification mixed placeholder styles' => [ + 'forSpecificationMixedPlaceholderStyles', + ['%1$s IN (%s)'], + InvalidArgumentException::SPECIFICATION_MIXED_PLACEHOLDER_STYLES, + ], + 'specification unsupported conversion' => [ + 'forSpecificationUnsupportedConversion', + ['%1$s IN (%2$d)', '%2$d'], + InvalidArgumentException::SPECIFICATION_UNSUPPORTED_CONVERSION, + ], ]; } diff --git a/test/unit/Sql/Predicate/InTest.php b/test/unit/Sql/Predicate/InTest.php index 8c5132ffd..3ebf863ad 100644 --- a/test/unit/Sql/Predicate/InTest.php +++ b/test/unit/Sql/Predicate/InTest.php @@ -45,6 +45,11 @@ public static function customSpecificationPreparedProvider(): array 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[:where1, :where2])', ['where1' => 1, 'where2' => 2], ], + 'two values, width modifier' => [ + (new In('id', [1, 2]))->setSpecification('%1$s = ANY (ARRAY[%2$05s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[:where1, :where2])', + ['where1' => 1, 'where2' => 2], + ], 'three values, plain placeholders' => [ (new In('id', [1, 2, 3]))->setSpecification('%s = ANY (ARRAY[%s])'), 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[:where1, :where2, :where3])', @@ -70,6 +75,10 @@ public static function customSpecificationSqlProvider(): array (new In('id', [1, 2]))->setSpecification('%1$s = ANY (ARRAY[%2$s])'), 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[\'1\', \'2\'])', ], + 'two values, width modifier' => [ + (new In('id', [1, 2]))->setSpecification('%1$s = ANY (ARRAY[%2$05s])'), + 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[\'1\', \'2\'])', + ], 'three values, plain placeholders' => [ (new In('id', [1, 2, 3]))->setSpecification('%s = ANY (ARRAY[%s])'), 'SELECT "t".* FROM "t" WHERE "id" = ANY (ARRAY[\'1\', \'2\', \'3\'])',