diff --git a/src/Application/Exception/BaseErrorHandler.php b/src/Application/Exception/BaseErrorHandler.php index 947d5fbd..ddbac085 100644 --- a/src/Application/Exception/BaseErrorHandler.php +++ b/src/Application/Exception/BaseErrorHandler.php @@ -77,7 +77,7 @@ protected function json($exception, mixed $code = null): void } if (app_env("APP_ENV") != "production") { - $response["trace"] = $exception->getTrace(); + $response["trace"] = $exception->getTraceAsString(); } response()->status($status); diff --git a/src/Configuration/LoggerConfiguration.php b/src/Configuration/LoggerConfiguration.php index 577782a4..116bc1bc 100644 --- a/src/Configuration/LoggerConfiguration.php +++ b/src/Configuration/LoggerConfiguration.php @@ -78,7 +78,14 @@ private function loadFrontLogger(Logger $monolog, $error_handler): void $handler = new CallbackHandler( function ($exception, $inspector, $run) use ($monolog, $error_handler) { - $monolog->error($exception->getMessage(), $exception->getTrace()); + $monolog->error($exception->getMessage(), [ + 'exception' => $exception::class, + 'file' => $exception->getFile() . ':' . $exception->getLine(), + // A string trace: never serialize the frame args, which may + // hold objects whose jsonSerialize() runs a query (and would + // throw here on an already-aborted transaction). + 'trace' => $exception->getTraceAsString(), + ]); $result = call_user_func_array([new $error_handler(), 'handle'], [$exception]); diff --git a/src/Database/Connection/Adapters/PostgreSQLAdapter.php b/src/Database/Connection/Adapters/PostgreSQLAdapter.php index 99bb6918..af9daf46 100644 --- a/src/Database/Connection/Adapters/PostgreSQLAdapter.php +++ b/src/Database/Connection/Adapters/PostgreSQLAdapter.php @@ -88,6 +88,11 @@ protected function makePdo(#[\SensitiveParameter] array $config): PDO $options = [ PDO::ATTR_DEFAULT_FETCH_MODE => $config['fetch'] ?? $this->fetch, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + // Opt-in per connection. Behind a pooler a server-side prepared + // statement can outlive a schema change and fail with SQLSTATE + // 0A000 "cached plan must not change result type"; with emulated + // prepares nothing is cached on the server and PDO quotes values. + PDO::ATTR_EMULATE_PREPARES => (bool) ($config['emulate_prepares'] ?? false), ]; // Build the PDO connection diff --git a/src/Database/QueryBuilder.php b/src/Database/QueryBuilder.php index 8d375205..9ecb77a8 100644 --- a/src/Database/QueryBuilder.php +++ b/src/Database/QueryBuilder.php @@ -723,7 +723,9 @@ public function whereIn(string $column, array $range): QueryBuilder $this->where_data_binding = array_merge($this->where_data_binding, $range); $map = array_map(fn() => '?', $range); - $in = implode(', ', $map); + // An empty list is `in (null)`: valid SQL that matches no row, + // where `in ()` is a syntax error (SQLSTATE 42601). + $in = $range === [] ? 'null' : implode(', ', $map); } else { $in = (string) $range; } diff --git a/src/Queue/Adapters/QueueAdapter.php b/src/Queue/Adapters/QueueAdapter.php index d1e4815a..6dc1a133 100644 --- a/src/Queue/Adapters/QueueAdapter.php +++ b/src/Queue/Adapters/QueueAdapter.php @@ -443,7 +443,11 @@ protected function logError(Throwable $exception): void error_log($exception->getMessage()); try { - logger()->error($exception->getMessage(), $exception->getTrace()); + logger()->error($exception->getMessage(), [ + 'exception' => $exception::class, + 'file' => $exception->getFile() . ':' . $exception->getLine(), + 'trace' => $exception->getTraceAsString(), + ]); } catch (Throwable $loggerException) { // Logger not available, already logged to error_log } diff --git a/src/Validation/Rules/EmailRule.php b/src/Validation/Rules/EmailRule.php index 9bd0e6a8..eafa0dbe 100644 --- a/src/Validation/Rules/EmailRule.php +++ b/src/Validation/Rules/EmailRule.php @@ -23,7 +23,7 @@ protected function compileEmail(string $key, string $masque): void return; } - if (Str::isMail($this->inputs[$key])) { + if (is_string($this->inputs[$key] ?? null) && Str::isMail($this->inputs[$key])) { return; } diff --git a/src/Validation/Rules/NullableRule.php b/src/Validation/Rules/NullableRule.php index 7b9ced40..cf089675 100644 --- a/src/Validation/Rules/NullableRule.php +++ b/src/Validation/Rules/NullableRule.php @@ -23,7 +23,7 @@ protected function compileNullable(string $key, string $masque): bool return false; } - if (isset($this->inputs[$key]) && !Str::isEmpty($this->inputs[$key])) { + if (!$this->isBlankInput($this->inputs[$key] ?? null)) { return false; } @@ -31,4 +31,31 @@ protected function compileNullable(string $key, string $masque): bool return true; } + + /** + * Whether a submitted value counts as "nothing was sent". + * + * Inputs arrive with their native type when the request body is JSON, so + * false, 0 and 0.0 are real values and must be validated by the rules that + * follow; only null, a blank string and an empty array are absent. + * + * @param mixed $value + * @return bool + */ + private function isBlankInput(mixed $value): bool + { + if ($value === null) { + return true; + } + + if (is_string($value)) { + return Str::isEmpty($value); + } + + if (is_array($value)) { + return $value === []; + } + + return false; + } } diff --git a/src/Validation/Rules/StringRule.php b/src/Validation/Rules/StringRule.php index 1fe6b97a..6f4a6a3b 100644 --- a/src/Validation/Rules/StringRule.php +++ b/src/Validation/Rules/StringRule.php @@ -132,7 +132,7 @@ protected function compileAlphaNum(string $key, string $masque): void return; } - if (Str::isAlphaNum($this->inputs[$key])) { + if (is_string($this->inputs[$key] ?? null) && Str::isAlphaNum($this->inputs[$key])) { return; } @@ -205,7 +205,9 @@ protected function compileSize(string $key, string $masque): void $length = (int)end($match); - if (Str::len($this->inputs[$key]) == $length) { + $size = $this->inputSize($key); + + if ($size !== null && $size == $length) { return; } @@ -240,7 +242,7 @@ protected function compileLower(string $key, string $masque): void return; } - if (Str::isLower($this->inputs[$key])) { + if (is_string($this->inputs[$key] ?? null) && Str::isLower($this->inputs[$key])) { return; } @@ -269,7 +271,7 @@ protected function compileUpper(string $key, string $masque): void return; } - if (Str::isUpper($this->inputs[$key])) { + if (is_string($this->inputs[$key] ?? null) && Str::isUpper($this->inputs[$key])) { return; } @@ -298,7 +300,7 @@ protected function compileAlpha(string $key, string $masque): void return; } - if (Str::isAlpha($this->inputs[$key])) { + if (is_string($this->inputs[$key] ?? null) && Str::isAlpha($this->inputs[$key])) { return; } @@ -330,7 +332,9 @@ protected function compileMin(string $key, string $masque): void $length = (int)end($match); - if (Str::len($this->inputs[$key]) >= $length) { + $size = $this->inputSize($key); + + if ($size !== null && $size >= $length) { return; } @@ -368,7 +372,9 @@ protected function compileMax(string $key, string $masque): void $length = (int)end($match); - if (Str::len($this->inputs[$key]) <= $length) { + $size = $this->inputSize($key); + + if ($size !== null && $size <= $length) { return; } @@ -423,4 +429,28 @@ protected function compileSame(string $key, string $masque): void "message" => $this->last_message ]; } + + /** + * The quantity that min, max and size compare against their bound. + * + * Mirrors the convention documented by the between rule: a native number + * (as decoded from a JSON body) is compared by value, a string by its + * character length. Numeric strings keep length semantics so form inputs + * such as phone numbers or postal codes behave as before. Anything else + * (bool, array, object) yields null and fails the rule instead of + * throwing a TypeError from the string-typed Str helpers. + * + * @param string $key + * @return int|float|null + */ + private function inputSize(string $key): int|float|null + { + $value = $this->inputs[$key] ?? null; + + return match (true) { + is_int($value) || is_float($value) => $value, + is_string($value) => Str::len($value), + default => null, + }; + } } diff --git a/tests/Database/ConnectionTest.php b/tests/Database/ConnectionTest.php index fcc2dfdd..6edc9cdd 100644 --- a/tests/Database/ConnectionTest.php +++ b/tests/Database/ConnectionTest.php @@ -186,6 +186,30 @@ public function test_pgsql_pdo_connection() $this->assertEquals('pgsql', $pdo->getAttribute(PDO::ATTR_DRIVER_NAME)); } + public function test_pgsql_emulate_prepares_is_off_by_default() + { + $pdo = static::$pgsqlAdapter->getConnection(); + + $this->assertFalse((bool) $pdo->getAttribute(PDO::ATTR_EMULATE_PREPARES)); + } + + /** + * Behind a connection pooler a server-side prepared statement can outlive a + * schema change and fail with SQLSTATE 0A000 "cached plan must not change + * result type". `emulate_prepares` lets a connection opt out of + * server-side prepares; PDO then quotes the values itself. + */ + public function test_pgsql_emulate_prepares_can_be_enabled_per_connection() + { + $config = static::$config["database"]['connections']['pgsql']; + $config['emulate_prepares'] = true; + + $pdo = (new PostgreSQLAdapter($config))->getConnection(); + + $this->assertTrue((bool) $pdo->getAttribute(PDO::ATTR_EMULATE_PREPARES)); + $this->assertEquals('pgsql', $pdo->getAttribute(PDO::ATTR_DRIVER_NAME)); + } + public function test_pgsql_adapter_name() { $this->assertEquals('pgsql', static::$pgsqlAdapter->getName()); diff --git a/tests/Database/Query/QueryBuilderTest.php b/tests/Database/Query/QueryBuilderTest.php index 8f6f8d6b..d242ee68 100644 --- a/tests/Database/Query/QueryBuilderTest.php +++ b/tests/Database/Query/QueryBuilderTest.php @@ -373,6 +373,30 @@ public function test_where_rejects_unsafe_column_identifier() $builder->where('1=1 UNION SELECT password FROM admins -- ', '=', 'x'); } + /** + * whereIn() with an empty list used to build `column in ()`, which is + * invalid SQL (SQLSTATE 42601). An empty list means "match nothing", and + * `in (null)` is valid everywhere and matches no row. + */ + public function test_where_in_with_empty_list_matches_nothing() + { + $pdo = new \PDO('sqlite::memory:'); + $pdo->exec('create table users (id integer primary key, name text)'); + $pdo->exec("insert into users (id, name) values (1, 'a'), (2, 'b')"); + + $builder = new QueryBuilder('users', $pdo); + $builder->whereIn('id', []); + + $this->assertStringContainsString('id in (null)', $builder->toSql()); + + $property = (new \ReflectionObject($builder))->getProperty('where_data_binding'); + $property->setAccessible(true); + $this->assertSame([], $property->getValue($builder)); + + $this->assertSame([], (array) (new QueryBuilder('users', $pdo))->whereIn('id', [])->get()); + $this->assertCount(1, (array) (new QueryBuilder('users', $pdo))->whereIn('id', [2])->get()); + } + /** * SQL-injection guard: whereBetween must bind both bounds as placeholders * instead of concatenating them into the statement. diff --git a/tests/Validation/ValidatorTypedInputTest.php b/tests/Validation/ValidatorTypedInputTest.php new file mode 100644 index 00000000..3cb8c6bf --- /dev/null +++ b/tests/Validation/ValidatorTypedInputTest.php @@ -0,0 +1,160 @@ + true], ['flag' => 'nullable|boolean']); + $this->assertFalse($validation->fails()); + } + + public function test_nullable_boolean_accepts_real_false() + { + // false is a value, not an absence: it must reach the boolean rule and pass. + $validation = Validator::make(['flag' => false], ['flag' => 'nullable|boolean']); + $this->assertFalse($validation->fails()); + } + + public function test_nullable_boolean_still_rejects_non_boolean_string() + { + $validation = Validator::make(['flag' => 'yes'], ['flag' => 'nullable|boolean']); + $this->assertTrue($validation->fails()); + $this->assertSame(['flag'], $validation->getCorruptedFields()); + } + + public function test_nullable_boolean_rejects_array_without_throwing() + { + $validation = Validator::make(['flag' => ['a']], ['flag' => 'nullable|boolean']); + $this->assertTrue($validation->fails()); + } + + public function test_nullable_accepts_native_integer_and_float() + { + $this->assertFalse(Validator::make(['n' => 5], ['n' => 'nullable|int'])->fails()); + $this->assertFalse(Validator::make(['n' => 0], ['n' => 'nullable|int'])->fails()); + $this->assertFalse(Validator::make(['n' => 3.5], ['n' => 'nullable|number'])->fails()); + } + + public function test_nullable_treats_null_empty_string_and_empty_array_as_absent() + { + $this->assertFalse(Validator::make(['n' => null], ['n' => 'nullable|int'])->fails()); + $this->assertFalse(Validator::make(['n' => ''], ['n' => 'nullable|int'])->fails()); + $this->assertFalse(Validator::make(['n' => ' '], ['n' => 'nullable|int'])->fails()); + $this->assertFalse(Validator::make(['n' => []], ['n' => 'nullable|int'])->fails()); + $this->assertFalse(Validator::make([], ['n' => 'nullable|int'])->fails()); + } + + public function test_nullable_zero_values_are_not_treated_as_absent() + { + // 0 and false are real values and must be validated by the following rules. + $this->assertTrue(Validator::make(['n' => 0], ['n' => 'nullable|email'])->fails()); + $this->assertTrue(Validator::make(['n' => false], ['n' => 'nullable|email'])->fails()); + } + + // ==================== max / min / size ==================== + + public function test_max_compares_native_numbers_numerically() + { + $this->assertFalse(Validator::make(['n' => 5], ['n' => 'required|max:10'])->fails()); + $this->assertFalse(Validator::make(['n' => 10], ['n' => 'required|max:10'])->fails()); + $this->assertTrue(Validator::make(['n' => 11], ['n' => 'required|max:10'])->fails()); + $this->assertTrue(Validator::make(['n' => 10.5], ['n' => 'required|max:10'])->fails()); + } + + public function test_min_compares_native_numbers_numerically() + { + $this->assertFalse(Validator::make(['n' => 3], ['n' => 'required|min:3'])->fails()); + $this->assertFalse(Validator::make(['n' => 3.5], ['n' => 'required|min:3'])->fails()); + $this->assertTrue(Validator::make(['n' => 2], ['n' => 'required|min:3'])->fails()); + } + + public function test_size_compares_native_numbers_numerically() + { + $this->assertFalse(Validator::make(['n' => 3], ['n' => 'required|size:3'])->fails()); + $this->assertTrue(Validator::make(['n' => 30], ['n' => 'required|size:3'])->fails()); + } + + public function test_max_min_size_keep_length_semantics_for_strings() + { + // Numeric strings (form input) stay on length semantics, so a phone + // number declared max:10 keeps working. + $this->assertFalse(Validator::make(['s' => '0612345678'], ['s' => 'required|max:10'])->fails()); + $this->assertTrue(Validator::make(['s' => '1234'], ['s' => 'required|max:3'])->fails()); + $this->assertTrue(Validator::make(['s' => 'fr'], ['s' => 'required|min:5'])->fails()); + $this->assertFalse(Validator::make(['s' => 'bow'], ['s' => 'required|size:3'])->fails()); + } + + public function test_max_min_size_fail_on_boolean_and_array_without_throwing() + { + $this->assertTrue(Validator::make(['v' => true], ['v' => 'required|max:3'])->fails()); + $this->assertTrue(Validator::make(['v' => false], ['v' => 'required|min:1'])->fails()); + $this->assertTrue(Validator::make(['v' => ['a']], ['v' => 'required|size:1'])->fails()); + } + + // ==================== string-only rules ==================== + + public function test_string_only_rules_fail_on_non_strings_without_throwing() + { + $this->assertTrue(Validator::make(['v' => 5], ['v' => 'required|alpha'])->fails()); + $this->assertTrue(Validator::make(['v' => true], ['v' => 'required|alphanum'])->fails()); + $this->assertTrue(Validator::make(['v' => 1.5], ['v' => 'required|lower'])->fails()); + $this->assertTrue(Validator::make(['v' => false], ['v' => 'required|upper'])->fails()); + $this->assertTrue(Validator::make(['v' => true], ['v' => 'required|email'])->fails()); + $this->assertTrue(Validator::make(['v' => ['a@b.c']], ['v' => 'required|email'])->fails()); + } + + public function test_string_only_rules_still_pass_on_valid_strings() + { + $this->assertFalse(Validator::make(['v' => 'bow'], ['v' => 'required|alpha'])->fails()); + $this->assertFalse(Validator::make(['v' => 'bow5'], ['v' => 'required|alphanum'])->fails()); + $this->assertFalse(Validator::make(['v' => 'bow'], ['v' => 'required|lower'])->fails()); + $this->assertFalse(Validator::make(['v' => 'BOW'], ['v' => 'required|upper'])->fails()); + $this->assertFalse(Validator::make(['v' => 'bow@bowphp.com'], ['v' => 'required|email'])->fails()); + } + + // ==================== full JSON payload ==================== + + public function test_typical_json_payload_validates_end_to_end() + { + $payload = [ + 'name' => 'Milou', + 'active' => false, + 'age' => 7, + 'score' => 9.5, + 'tags' => ['dog'], + 'nickname' => null, + ]; + + $validation = Validator::make($payload, [ + 'name' => 'required|alpha|max:50', + 'active' => 'nullable|boolean', + 'age' => 'required|int|min:0|max:120', + 'score' => 'nullable|number|between:0,10', + 'nickname' => 'nullable|alpha', + ]); + + $this->assertFalse($validation->fails(), json_encode($validation->getMessages())); + } +}