From b32a8cba6d305a0312423746d8f1fcbe9dae0114 Mon Sep 17 00:00:00 2001 From: papac Date: Mon, 15 Jun 2026 02:14:16 +0000 Subject: [PATCH 01/23] Update CHANGELOG --- CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fcaba53..18fc20ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 5.4.0 - 2026-06-15 + +### What's Changed + +* Update CHANGELOG by @papac in https://github.com/bowphp/framework/pull/416 +* refactor(console): add index to stub models by @papac in https://github.com/bowphp/framework/pull/418 +* fix(database): fix hasMany and hosOne relations by @papac in https://github.com/bowphp/framework/pull/419 +* fix(cache): fix database cache by @papac in https://github.com/bowphp/framework/pull/420 +* fix(session): fix database adaptor by @papac in https://github.com/bowphp/framework/pull/421 + +**Full Changelog**: https://github.com/bowphp/framework/compare/5.3.40...5.4.0 + ## 5.3.40 - 2026-06-10 ### What's Changed @@ -340,6 +352,7 @@ Database::transaction(fn() => $user->update(['name' => ''])); + ``` From 973753c9581f654c969effeeac5fb264a779a794 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Mon, 22 Jun 2026 01:45:02 +0000 Subject: [PATCH 02/23] Many Bugs fixed and new methods MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - file() — the broken !is_uploaded_file(...) === UPLOAD_ERR_OK check (always false due to precedence) now correctly rejects non-uploaded files while preserving the array/multi-file path. - locale() — the delimiter-less regex ('^([a-z]+)[-_]?/i') that warned and never matched is now '/([a-z]+)[-_]?/i', with null guards for a missing header. - query() / post() — return type was array but returned scalars (guaranteed TypeError); now mixed with a $default argument matching get()'s contract. - time() — read the non-existent $_SESSION['REQUEST_TIME']; now returns an int from $_SERVER['REQUEST_TIME']. - old() — $fallback had no default, fataling on old('x'); now defaults to null (also fixed the fullback typo). - hostname() / path() — guarded against undefined $_SERVER indices (CLI/tests) and fixed strpos truthiness with !== false. Methods added: isMethod(string) — match the request method. input(key, default) — alias of get(). boolean(key, default) — coerce an input to bool (1/true/on/yes). bearerToken() — extract the token from an Authorization: Bearer … header. --- src/Http/Request.php | 130 ++++++++++++++++++++++++++++++++++--------- 1 file changed, 105 insertions(+), 25 deletions(-) diff --git a/src/Http/Request.php b/src/Http/Request.php index 33bf2aad..2d64c0a1 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -120,30 +120,32 @@ public function capture() * Retrieve query variables * * @param string|null $key - * @return array + * @param mixed $default + * @return mixed */ - public function query(?string $key = null): array + public function query(?string $key = null, mixed $default = null): mixed { if ($key === null) { return $this->query; } - return $this->query[$key] ?? []; + return $this->query[$key] ?? $default; } /** * Get posted data * * @param string|null $key - * @return array + * @param mixed $default + * @return mixed */ - public function post(?string $key = null): array + public function post(?string $key = null, mixed $default = null): mixed { if ($key === null) { return $this->post; } - return $this->post[$key] ?? []; + return $this->post[$key] ?? $default; } /** @@ -210,6 +212,17 @@ public function method(): ?string return $method; } + /** + * Check that the request method matches the given one. + * + * @param string $method + * @return bool + */ + public function isMethod(string $method): bool + { + return strtoupper($method) === $this->method(); + } + /** * Retrieve a value or a collection of values. * @@ -228,6 +241,36 @@ public function get(string $key, mixed $default = null): mixed return $value; } + /** + * Alias of get, retrieve an input value. + * + * @param string $key + * @param mixed|null $default + * @return mixed + */ + public function input(string $key, mixed $default = null): mixed + { + return $this->get($key, $default); + } + + /** + * Retrieve an input value as a boolean. + * + * Truthy values are 1, "1", true, "true", "on" and "yes". + * + * @param string $key + * @param bool $default + * @return bool + */ + public function boolean(string $key, bool $default = false): bool + { + if (!$this->has($key)) { + return $default; + } + + return filter_var($this->get($key), FILTER_VALIDATE_BOOLEAN); + } + /** * Get the request ID * @@ -317,7 +360,7 @@ private function scheme(): string */ public function hostname(): string { - return $_SERVER['HTTP_HOST']; + return $_SERVER['HTTP_HOST'] ?? ''; } /** @@ -327,9 +370,9 @@ public function hostname(): string */ public function domain(): string { - $part = explode(':', $this->hostname() ?? ''); + $part = explode(':', $this->hostname()); - return $part[0] ?? 'unknown'; + return $part[0] ?: 'unknown'; } /** @@ -339,25 +382,24 @@ public function domain(): string */ public function path(): string { - $position = strpos($_SERVER['REQUEST_URI'], '?'); + $request_uri = $_SERVER['REQUEST_URI'] ?? '/'; + $position = strpos($request_uri, '?'); - if ($position) { - $uri = substr($_SERVER['REQUEST_URI'], 0, $position); - } else { - $uri = $_SERVER['REQUEST_URI']; + if ($position !== false) { + return substr($request_uri, 0, $position); } - return $uri; + return $request_uri; } /** - * Get path sent by client. + * Get the request time as a UNIX timestamp. * - * @return string + * @return int */ - public function time(): string + public function time(): int { - return $_SESSION['REQUEST_TIME']; + return (int) ($_SERVER['REQUEST_TIME'] ?? time()); } /** @@ -402,7 +444,7 @@ public function file(string $key): UploadedFile|Collection|null return null; } - if (!is_uploaded_file($_FILES[$key]['tmp_name']) === UPLOAD_ERR_OK) { + if (!is_array($_FILES[$key]['tmp_name']) && !is_uploaded_file($_FILES[$key]['tmp_name'])) { return null; } @@ -430,14 +472,14 @@ public function file(string $key): UploadedFile|Collection|null * Get previous request data * * @param string $key - * @param mixed $fullback + * @param mixed $fallback * @return mixed */ - public function old(string $key, mixed $fullback): mixed + public function old(string $key, mixed $fallback = null): mixed { $old = Session::getInstance()->get('__bow.old', []); - return $old[$key] ?? $fullback; + return $old[$key] ?? $fallback; } /** @@ -531,7 +573,23 @@ public function referer(): string */ public function ip(): ?string { - return $_SERVER['REMOTE_ADDR'] ?? null; + $candidates = [ + $_SERVER['HTTP_CF_CONNECTING_IP'] ?? null, + isset($_SERVER['HTTP_X_FORWARDED_FOR']) + ? explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0] + : null, + $_SERVER['HTTP_X_REAL_IP'] ?? null, + $_SERVER['REMOTE_ADDR'] ?? null, + ]; + + foreach ($candidates as $candidate) { + $ip = trim((string) $candidate); + if ($ip !== '' && filter_var($ip, FILTER_VALIDATE_IP) !== false) { + return $ip; + } + } + + return null; } /** @@ -557,9 +615,15 @@ public function locale(): ?string { $accept_language = $this->getHeader('accept-language'); + if (!$accept_language) { + return null; + } + $tmp = explode(';', $accept_language)[0]; - preg_match('^([a-z]+)[-_]?/i', $tmp, $match); + if (!preg_match('/([a-z]+)[-_]?/i', $tmp, $match)) { + return null; + } return end($match); } @@ -644,6 +708,22 @@ public function userAgent(): ?string return $this->getHeader('USER_AGENT'); } + /** + * Get the Bearer token from the Authorization header. + * + * @return ?string + */ + public function bearerToken(): ?string + { + $authorization = $this->getHeader('authorization'); + + if ($authorization && str_starts_with($authorization, 'Bearer ')) { + return substr($authorization, 7); + } + + return null; + } + /** * Get session information * From 6f64ce82b58b63bb15d7d15327bcfd84a340a133 Mon Sep 17 00:00:00 2001 From: papac Date: Mon, 22 Jun 2026 01:52:23 +0000 Subject: [PATCH 03/23] Update CHANGELOG --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18fc20ef..bd93e1af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 5.4.10 - 2026-06-22 + +### What's Changed + +* Many Bugs fixed and new methods by @papac in https://github.com/bowphp/framework/pull/422 +* Update CHANGELOG by @papac in https://github.com/bowphp/framework/pull/423 + +**Full Changelog**: https://github.com/bowphp/framework/compare/5.4.0...5.4.10 + ## 5.4.0 - 2026-06-15 ### What's Changed @@ -353,6 +362,7 @@ Database::transaction(fn() => $user->update(['name' => ''])); + ``` From d13599804488af85b88f5dd06160fbf5dcf2f4d6 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Wed, 15 Jul 2026 02:23:56 +0000 Subject: [PATCH 04/23] fix(queue): add beanstalkd type error --- src/Queue/Adapters/BeanstalkdAdapter.php | 74 +++++++++++++++++++++--- src/Queue/Adapters/QueueAdapter.php | 14 ++++- 2 files changed, 78 insertions(+), 10 deletions(-) diff --git a/src/Queue/Adapters/BeanstalkdAdapter.php b/src/Queue/Adapters/BeanstalkdAdapter.php index 9ae58d0b..2f2dcf7b 100644 --- a/src/Queue/Adapters/BeanstalkdAdapter.php +++ b/src/Queue/Adapters/BeanstalkdAdapter.php @@ -8,6 +8,7 @@ use Pheanstalk\Contract\JobIdInterface; use Pheanstalk\Contract\PheanstalkPublisherInterface; use Pheanstalk\Pheanstalk; +use Pheanstalk\Values\Job; use Pheanstalk\Values\Timeout; use Pheanstalk\Values\TubeName; use RuntimeException; @@ -180,12 +181,12 @@ private function executeTask(QueueTask $task): void /** * Handle task failure * - * @param JobIdInterface|null $job + * @param Job|null $job * @param QueueTask|null $task * @param Throwable $exception * @return void */ - private function handleTaskFailure(?JobIdInterface $job, ?QueueTask $task, Throwable $exception): void + private function handleTaskFailure(?Job $job, ?QueueTask $task, Throwable $exception): void { $this->logError($exception); @@ -195,16 +196,18 @@ private function handleTaskFailure(?JobIdInterface $job, ?QueueTask $task, Throw return; } - cache("task:failed:" . $task->getId(), method_exists($task, 'getData') ? $task->getData() : ""); - + // Poison message: the reserved body could not be unserialized into a + // QueueTask ($task is null), so there is no task id to key on and no + // task to retry. Keep the raw body for inspection, then delete the job + // BEFORE dereferencing $task below — leaving it would redeliver on TTR + // and crash-loop the worker. if (is_null($task)) { + $this->recordFailedPayload("task:failed:job:" . $job->getId(), $job->getData()); $this->pheanstalk->delete($job); return; } - $task->onException($exception); - - if ($task->taskShouldBeDelete()) { + if ($this->resolveFailedTask($job, $task, $exception)) { $this->pheanstalk->delete($job); } else { $this->releaseTask($job, $task); @@ -213,6 +216,63 @@ private function handleTaskFailure(?JobIdInterface $job, ?QueueTask $task, Throw $this->sleep(1); } + /** + * Run the task defined failure handling and decide whether to drop the job + * + * Everything the task exposes here is overridable, so it is user code: + * getId(), getData(), onException() and taskShouldBeDelete() may all throw. + * A throw must not escape, otherwise the job is never deleted nor released, + * it redelivers on TTR and the worker crash-loops on it. getPriority() and + * getDelay(), used when releasing, are final and cannot throw. + * + * @param Job $job + * @param QueueTask $task + * @param Throwable $exception + * @return bool Whether the job should be deleted + */ + private function resolveFailedTask(Job $job, QueueTask $task, Throwable $exception): bool + { + try { + $this->recordFailedPayload( + "task:failed:" . $task->getId(), + method_exists($task, 'getData') ? $task->getData() : "" + ); + + $task->onException($exception); + + return $task->taskShouldBeDelete(); + } catch (Throwable $taskException) { + $this->logError($taskException); + + // The task cannot handle its own failure, so retrying it would most + // likely break the same way. Keep the raw body under the job id, + // since the task id may be exactly what failed, then drop the job. + $this->recordFailedPayload("task:failed:job:" . $job->getId(), $job->getData()); + + return true; + } + } + + /** + * Store the failed payload for later inspection + * + * Recording is best effort: the cache is not guaranteed to be configured in + * a worker process, and a throw here would escape the failure handler and + * kill the worker before the job is deleted, making it redeliver on TTR. + * + * @param string $key + * @param mixed $payload + * @return void + */ + private function recordFailedPayload(string $key, mixed $payload): void + { + try { + cache($key, $payload); + } catch (Throwable $exception) { + $this->logError($exception); + } + } + /** * Release the task back to the queue for retry * diff --git a/src/Queue/Adapters/QueueAdapter.php b/src/Queue/Adapters/QueueAdapter.php index 32ca6e81..6b0d07ae 100644 --- a/src/Queue/Adapters/QueueAdapter.php +++ b/src/Queue/Adapters/QueueAdapter.php @@ -387,15 +387,23 @@ protected function logProcessedTask(QueueTask $task): void /** * Log failed task * - * @param QueueTask $task + * The task is nullable because a failure can occur before the task is + * resolved, typically when the payload cannot be unserialized. + * + * @param QueueTask|null $task * @param \Throwable $e * @return void */ - protected function logFailedTask(QueueTask $task, \Throwable $e): void + protected function logFailedTask(?QueueTask $task, \Throwable $e): void { if (static::$suppressLogging) { return; } - error_log('Task failed: ' . $e->getMessage() . "\n" . $e->getTraceAsString()); + + $description = is_null($task) + ? 'unresolved task' + : get_class($task) . ' with ID: ' . $task->getId(); + + error_log('Task failed: ' . $description . ', ' . $e->getMessage() . "\n" . $e->getTraceAsString()); } } From 40d1fcddb5ab12c1eacae8d11da93d6d6d0fc735 Mon Sep 17 00:00:00 2001 From: papac Date: Wed, 15 Jul 2026 02:28:04 +0000 Subject: [PATCH 05/23] Update CHANGELOG --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd93e1af..7095b738 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 5.4.11 - 2026-07-15 + +### What's Changed + +* Update CHANGELOG by @papac in https://github.com/bowphp/framework/pull/425 +* fix(queue): add beanstalkd type error by @papac in https://github.com/bowphp/framework/pull/424 + +**Full Changelog**: https://github.com/bowphp/framework/compare/5.4.10...5.4.11 + ## 5.4.10 - 2026-06-22 ### What's Changed @@ -363,6 +372,7 @@ Database::transaction(fn() => $user->update(['name' => ''])); + ``` From 11665be4cf2848f7a5ffc4f0c1fa1f4d882339a4 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Wed, 15 Jul 2026 02:48:04 +0000 Subject: [PATCH 06/23] fix(queue): add beanstalkd type error --- src/Queue/Adapters/BeanstalkdAdapter.php | 53 ++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/src/Queue/Adapters/BeanstalkdAdapter.php b/src/Queue/Adapters/BeanstalkdAdapter.php index 2f2dcf7b..6796dd7d 100644 --- a/src/Queue/Adapters/BeanstalkdAdapter.php +++ b/src/Queue/Adapters/BeanstalkdAdapter.php @@ -7,6 +7,7 @@ use Bow\Queue\QueueTask; use Pheanstalk\Contract\JobIdInterface; use Pheanstalk\Contract\PheanstalkPublisherInterface; +use Pheanstalk\Exception\ConnectionException; use Pheanstalk\Pheanstalk; use Pheanstalk\Values\Job; use Pheanstalk\Values\Timeout; @@ -26,6 +27,17 @@ class BeanstalkdAdapter extends QueueAdapter */ private const QUEUE_CACHE_KEY = "beanstalkd:queues"; + /** + * Seconds the server is allowed to hold a reserve before answering + * + * Pheanstalk 8 adds this to the socket receive timeout while it waits, so + * any value is safe there. Pheanstalk 5 does not, and reads with the plain + * receive timeout, which defaults to 10 seconds: past that the socket read + * expires before beanstalkd answers and an idle tube surfaces as a + * connection error instead of "no job". Stay below it to support both. + */ + private const RESERVE_TIMEOUT = 5; + /** * The Pheanstalk client instance * @@ -144,14 +156,17 @@ public function getPriority(int $priority): int */ public function run(?string $queue = null): void { - $queueName = $this->getQueue($queue); - $this->pheanstalk->watch(new TubeName($queueName)); + $job = $this->reserveNextJob($this->getQueue($queue)); + + // The tube stayed empty for the whole reserve window, or the server is + // unreachable. Neither is a task failure, so there is nothing to report. + if (is_null($job)) { + return; + } $task = null; - $job = null; try { - $job = $this->pheanstalk->reserve(); $task = $this->unserializeProducer($job->getData()); $this->executeTask($task); @@ -163,6 +178,36 @@ public function run(?string $queue = null): void } } + /** + * Reserve the next job to process on the given tube + * + * An idle tube is not a failure and must not be reported as one. A plain + * reserve() blocks server side until a job shows up, so the socket read + * expires first and an empty queue surfaces as "Socket error 35: Resource + * temporarily unavailable" logged as a failed task on every idle window. + * reserveWithTimeout() lets beanstalkd answer TIMED_OUT instead, which + * Pheanstalk reports as null. + * + * @param string $queueName + * @return Job|null + */ + private function reserveNextJob(string $queueName): ?Job + { + try { + $this->pheanstalk->watch(new TubeName($queueName)); + + return $this->pheanstalk->reserveWithTimeout(self::RESERVE_TIMEOUT); + } catch (ConnectionException $exception) { + // The server is unreachable, which says nothing about any task. + // Pheanstalk drops the socket on this and reconnects on the next + // command, so back off rather than spin on reconnect attempts. + $this->logError($exception); + $this->sleep(1); + + return null; + } + } + /** * Execute the task * From 7e9ca6115729ee6c0d2b3689d528b73ac4931963 Mon Sep 17 00:00:00 2001 From: papac Date: Wed, 15 Jul 2026 02:50:59 +0000 Subject: [PATCH 07/23] Update CHANGELOG --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7095b738..94819fea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 5.4.12 - 2026-07-15 + +### What's Changed + +* Update CHANGELOG by @papac in https://github.com/bowphp/framework/pull/426 +* fix(queue): add beanstalkd type error by @papac in https://github.com/bowphp/framework/pull/427 + +**Full Changelog**: https://github.com/bowphp/framework/compare/5.4.11...5.4.12 + ## 5.4.11 - 2026-07-15 ### What's Changed @@ -373,6 +382,7 @@ Database::transaction(fn() => $user->update(['name' => ''])); + ``` From dd5216e4a839a730d1497b8d714beb1c3a756273 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Fri, 17 Jul 2026 13:42:17 +0000 Subject: [PATCH 08/23] try to fix --- src/Database/Connection/AbstractConnection.php | 6 +++--- src/Database/Connection/Adapters/MysqlAdapter.php | 4 ++-- src/Database/Connection/Adapters/PostgreSQLAdapter.php | 4 ++-- src/Database/Connection/Adapters/SqliteAdapter.php | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Database/Connection/AbstractConnection.php b/src/Database/Connection/AbstractConnection.php index 4f5984d5..00a65166 100644 --- a/src/Database/Connection/AbstractConnection.php +++ b/src/Database/Connection/AbstractConnection.php @@ -67,7 +67,7 @@ abstract class AbstractConnection * * @param array $config */ - public function __construct(array $config) + public function __construct(#[\SensitiveParameter] array $config) { $this->config = $config; @@ -95,7 +95,7 @@ public function __construct(array $config) * @param array $config * @return void */ - abstract protected function validateConfig(array $config): void; + abstract protected function validateConfig(#[\SensitiveParameter] array $config): void; /** * Build a PDO instance from the given configuration. @@ -103,7 +103,7 @@ abstract protected function validateConfig(array $config): void; * @param array $config * @return PDO */ - abstract protected function makePdo(array $config): PDO; + abstract protected function makePdo(#[\SensitiveParameter] array $config): PDO; /** * Build (eagerly) the write connection. diff --git a/src/Database/Connection/Adapters/MysqlAdapter.php b/src/Database/Connection/Adapters/MysqlAdapter.php index b8bb4910..f32c2498 100644 --- a/src/Database/Connection/Adapters/MysqlAdapter.php +++ b/src/Database/Connection/Adapters/MysqlAdapter.php @@ -30,7 +30,7 @@ class MysqlAdapter extends AbstractConnection * @param array $config * @return void */ - protected function validateConfig(array $config): void + protected function validateConfig(#[\SensitiveParameter] array $config): void { // Check the existence of database definition if (!isset($config['database'])) { @@ -44,7 +44,7 @@ protected function validateConfig(array $config): void * @param array $config * @return PDO */ - protected function makePdo(array $config): PDO + protected function makePdo(#[\SensitiveParameter] array $config): PDO { // Build of the mysql dsn if (isset($config['socket']) && !empty($config['socket'])) { diff --git a/src/Database/Connection/Adapters/PostgreSQLAdapter.php b/src/Database/Connection/Adapters/PostgreSQLAdapter.php index a6535c1a..99bb6918 100644 --- a/src/Database/Connection/Adapters/PostgreSQLAdapter.php +++ b/src/Database/Connection/Adapters/PostgreSQLAdapter.php @@ -29,7 +29,7 @@ class PostgreSQLAdapter extends AbstractConnection * @param array $config * @return void */ - protected function validateConfig(array $config): void + protected function validateConfig(#[\SensitiveParameter] array $config): void { // Check the existence of database definition if (!isset($config['database'])) { @@ -43,7 +43,7 @@ protected function validateConfig(array $config): void * @param array $config * @return PDO */ - protected function makePdo(array $config): PDO + protected function makePdo(#[\SensitiveParameter] array $config): PDO { // Build of the pgsql dsn if (isset($config['socket']) && !is_null($config['socket']) && !empty($config['socket'])) { diff --git a/src/Database/Connection/Adapters/SqliteAdapter.php b/src/Database/Connection/Adapters/SqliteAdapter.php index 3dbb5f47..45c4f257 100644 --- a/src/Database/Connection/Adapters/SqliteAdapter.php +++ b/src/Database/Connection/Adapters/SqliteAdapter.php @@ -23,7 +23,7 @@ class SqliteAdapter extends AbstractConnection * @param array $config * @return void */ - protected function validateConfig(array $config): void + protected function validateConfig(#[\SensitiveParameter] array $config): void { if (!isset($config['driver'])) { throw new InvalidArgumentException("Please select the right sqlite driver"); @@ -40,7 +40,7 @@ protected function validateConfig(array $config): void * @param array $config * @return PDO */ - protected function makePdo(array $config): PDO + protected function makePdo(#[\SensitiveParameter] array $config): PDO { // Build the PDO connection $pdo = new PDO('sqlite:' . $config['database']); From 235c06c484ec387bf0099ff7c34929d702bb239b Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sat, 18 Jul 2026 03:16:22 +0000 Subject: [PATCH 09/23] sec(): fix many security issues --- src/Database/QueryBuilder.php | 75 +++++++++++++++++++++++++++-- src/Queue/Adapters/QueueAdapter.php | 23 ++++++++- src/Security/Tokenize.php | 12 ++--- tests/Queue/EventQueueTest.php | 2 + tests/Queue/MailQueueTest.php | 2 + tests/Queue/NotifierQueueTest.php | 2 + tests/Queue/QueueTest.php | 3 ++ 7 files changed, 108 insertions(+), 11 deletions(-) diff --git a/src/Database/QueryBuilder.php b/src/Database/QueryBuilder.php index 7b54926c..b352478f 100644 --- a/src/Database/QueryBuilder.php +++ b/src/Database/QueryBuilder.php @@ -70,6 +70,17 @@ class QueryBuilder implements JsonSerializable */ protected ?string $having = null; + /** + * Bound values for the having clause. + * + * Kept separate from where bindings because having placeholders appear + * after where placeholders in the assembled SQL; they are merged in the + * correct positional order when the having clause is appended. + * + * @var array + */ + protected array $having_data_binding = []; + /** * Order By statement collector * @@ -404,6 +415,34 @@ private static function isComparisonOperator(mixed $comparator): bool ], true); } + /** + * Guard a column/identifier that is interpolated straight into SQL. + * + * Clauses like order by, group by and having name a column instead of + * binding a value, so the identifier cannot be a placeholder and is + * concatenated into the statement. Restrict it to a plain (optionally + * table-qualified) identifier so it can never carry an injected fragment. + * Raw expressions are intentionally not accepted here. + * + * @param string $identifier + * @param string $clause + * @return string + * @throws QueryBuilderException + */ + private static function assertSafeIdentifier(string $identifier, string $clause): string + { + $trimmed = trim($identifier); + + if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/', $trimmed)) { + throw new QueryBuilderException( + "Unsafe identifier passed to {$clause}: [{$identifier}]. " + . "Only a plain or table-qualified column name is allowed." + ); + } + + return $trimmed; + } + /** * Formats the select request * @@ -464,6 +503,15 @@ public function toSql(): string if (!is_null($this->having)) { $sql .= ' having ' . $this->having; + + // having placeholders come after where placeholders in the SQL, + // so appending their values here keeps the positional order. + $this->where_data_binding = array_merge( + $this->where_data_binding, + $this->having_data_binding + ); + $this->having_data_binding = []; + $this->having = null; } } @@ -877,7 +925,7 @@ public function group(string $column) public function groupBy(string $column): QueryBuilder { if (is_null($this->group)) { - $this->group = $column; + $this->group = static::assertSafeIdentifier($column, 'groupBy'); } return $this; @@ -904,10 +952,21 @@ public function having( $comparator = '='; } + $column = static::assertSafeIdentifier($column, 'having'); + + // Bind the value with a placeholder, exactly like where(). A subquery + // is inlined; any scalar is parameterised so it can never be injected. + if ($value instanceof QueryBuilder) { + $indicator = '(' . $value->toSql() . ')'; + } else { + $indicator = '?'; + $this->having_data_binding[] = $value; + } + if (is_null($this->having)) { - $this->having = $column . ' ' . $comparator . ' ' . $value; + $this->having = $column . ' ' . $comparator . ' ' . $indicator; } else { - $this->having .= ' ' . $boolean . ' ' . $column . ' ' . $comparator . ' ' . $value; + $this->having .= ' ' . $boolean . ' ' . $column . ' ' . $comparator . ' ' . $indicator; } return $this; @@ -926,6 +985,8 @@ public function orderBy(string $column, string $type = 'asc'): QueryBuilder $type = 'asc'; } + $column = static::assertSafeIdentifier($column, 'orderBy'); + if (is_null($this->order)) { $this->order = 'order by ' . $column . ' ' . strtolower($type); } else { @@ -977,6 +1038,14 @@ private function aggregate($aggregate, $column): mixed if (!is_null($this->having)) { $sql .= ' having ' . $this->having; + + // Keep having values positionally after where values. + $this->where_data_binding = array_merge( + $this->where_data_binding, + $this->having_data_binding + ); + $this->having_data_binding = []; + $this->having = null; } } diff --git a/src/Queue/Adapters/QueueAdapter.php b/src/Queue/Adapters/QueueAdapter.php index 6b0d07ae..8277508d 100644 --- a/src/Queue/Adapters/QueueAdapter.php +++ b/src/Queue/Adapters/QueueAdapter.php @@ -5,6 +5,8 @@ namespace Bow\Queue\Adapters; use Bow\Queue\QueueTask; +use Bow\Security\Crypto; +use RuntimeException; use Throwable; abstract class QueueAdapter @@ -97,7 +99,12 @@ abstract public function push(QueueTask $task): bool; */ public function serializeProducer(QueueTask $task): string { - return serialize($task); + // Authenticate the payload (encrypt-then-MAC) so a worker will only ever + // unserialize bytes this application produced. Without this, anyone able + // to write to the queue backend could deliver a crafted serialized + // object and trigger PHP object injection (RCE via a POP chain) when the + // worker deserializes it. + return Crypto::encrypt(serialize($task)); } /** @@ -108,7 +115,19 @@ public function serializeProducer(QueueTask $task): string */ public function unserializeProducer(string $task): QueueTask { - return unserialize($task); + // Verify integrity BEFORE unserialize(). Crypto::decrypt fails closed + // (returns false) on a tampered, forged or wrong-key payload, so crafted + // bytes never reach unserialize(). Only payloads produced by + // serializeProducer() with this application's key get past this point. + $plain = Crypto::decrypt($task); + + if ($plain === false) { + throw new RuntimeException( + 'Queue payload failed integrity verification and was rejected.' + ); + } + + return unserialize($plain); } /** diff --git a/src/Security/Tokenize.php b/src/Security/Tokenize.php index a7b9b873..a51338d5 100644 --- a/src/Security/Tokenize.php +++ b/src/Security/Tokenize.php @@ -65,17 +65,17 @@ public static function makeCsrfToken(?int $time = null): bool } /** - * GGenerate an encrypted key + * Generate a cryptographically strong token. + * + * Drawn from 32 bytes (256 bits) of CSPRNG output. The previous version + * seeded only 6 random bytes mixed with a time/uniqid/rand() salt, so the + * real entropy floor was ~48 bits and the salt (non-CSPRNG) added none. * * @return string */ public static function make(): string { - $salt = date('Y-m-d H:i:s', time() - 10000) . uniqid((string)rand(), true); - - $token = base64_encode(base64_encode(openssl_random_pseudo_bytes(6)) . $salt); - - return Str::slice(hash('sha256', $token), 1, 62); + return Str::slice(hash('sha256', random_bytes(32)), 1, 62); } /** diff --git a/tests/Queue/EventQueueTest.php b/tests/Queue/EventQueueTest.php index 5a11f755..48399493 100644 --- a/tests/Queue/EventQueueTest.php +++ b/tests/Queue/EventQueueTest.php @@ -6,6 +6,7 @@ use Bow\Configuration\EnvConfiguration; use Bow\Configuration\LoggerConfiguration; use Bow\Database\DatabaseConfiguration; +use Bow\Security\CryptoConfiguration; use Bow\Event\EventQueueTask; use Bow\Mail\MailConfiguration; use Bow\Queue\Adapters\QueueAdapter; @@ -33,6 +34,7 @@ public static function setUpBeforeClass(): void QueueConfiguration::class, DatabaseConfiguration::class, EnvConfiguration::class, + CryptoConfiguration::class, LoggerConfiguration::class, MailConfiguration::class, ViewConfiguration::class, diff --git a/tests/Queue/MailQueueTest.php b/tests/Queue/MailQueueTest.php index a63a2ae0..74d3459e 100644 --- a/tests/Queue/MailQueueTest.php +++ b/tests/Queue/MailQueueTest.php @@ -6,6 +6,7 @@ use Bow\Configuration\EnvConfiguration; use Bow\Configuration\LoggerConfiguration; use Bow\Database\DatabaseConfiguration; +use Bow\Security\CryptoConfiguration; use Bow\Mail\Envelop; use Bow\Mail\MailConfiguration; use Bow\Mail\MailQueueTask; @@ -30,6 +31,7 @@ public static function setUpBeforeClass(): void QueueConfiguration::class, DatabaseConfiguration::class, EnvConfiguration::class, + CryptoConfiguration::class, LoggerConfiguration::class, MailConfiguration::class, ViewConfiguration::class, diff --git a/tests/Queue/NotifierQueueTest.php b/tests/Queue/NotifierQueueTest.php index 77c8550f..0708947e 100644 --- a/tests/Queue/NotifierQueueTest.php +++ b/tests/Queue/NotifierQueueTest.php @@ -6,6 +6,7 @@ use Bow\Configuration\EnvConfiguration; use Bow\Configuration\LoggerConfiguration; use Bow\Database\DatabaseConfiguration; +use Bow\Security\CryptoConfiguration; use Bow\Mail\MailConfiguration; use Bow\Notifier\Notifier; use Bow\Notifier\NotifierQueueTask; @@ -33,6 +34,7 @@ public static function setUpBeforeClass(): void DatabaseConfiguration::class, QueueConfiguration::class, EnvConfiguration::class, + CryptoConfiguration::class, LoggerConfiguration::class, MailConfiguration::class, ViewConfiguration::class, diff --git a/tests/Queue/QueueTest.php b/tests/Queue/QueueTest.php index 29121045..e0ef9ac8 100644 --- a/tests/Queue/QueueTest.php +++ b/tests/Queue/QueueTest.php @@ -7,6 +7,7 @@ use Bow\Configuration\LoggerConfiguration; use Bow\Database\Database; use Bow\Database\DatabaseConfiguration; +use Bow\Security\CryptoConfiguration; use Bow\Mail\Mail; use Bow\Queue\Adapters\BeanstalkdAdapter; use Bow\Queue\Adapters\DatabaseAdapter; @@ -50,6 +51,8 @@ public static function setUpBeforeClass(): void DatabaseConfiguration::class, CacheConfiguration::class, EnvConfiguration::class, + // Queue payloads are now authenticated, so the worker needs the key. + CryptoConfiguration::class, ]); $config = TestingConfiguration::getConfig(); From e8366936a8adfb14c058d9a0b75c40162563d76a Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sat, 18 Jul 2026 03:43:41 +0000 Subject: [PATCH 10/23] formatting --- ROADMAP.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 077d513e..037e93a2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,18 +124,18 @@ Highlights from the latest iterations — already merged into `5.x`. Full detail | Task | Status | Priority | Notes | | ---------------------------------------------------------------- | ------ | -------- | ---------------------------------------------------------------- | -| Fix middleware attribute test (shared state between tests) | ✅ Done | - | `Router::$routes` converted to instance state | +| Fix middleware attribute test (shared state between tests) | ✅ Done | - | `Router::$routes` converted to instance state | | Fix Pagination tests calling `total()` instead of `totalPages()` | ✅ Done | - | 24 tests fixed | -| Fix Barry model `array` cast returning `stdClass` | ✅ Done | - | `Model::executeDataCasting` + `parseToJson($value, assoc: true)` | -| Fix Validator `nullable\|required` priority | ✅ Done | - | `nullable` no longer short-circuits `required` | -| Fix `EnvTest` singleton pollution between tests | ✅ Done | - | `Env::reset()` added | -| Fix `SchedulerCommand` (`routes/scheduler.php` loading) | ✅ Done | - | `loadSchedulerFile()` updated, tolerates missing Loader | -| Remove dead `Model::$soft_delete` property | ✅ Done | - | Replaced with a fully functional trait | -| Improve `addEnum` / `changeEnum` error messages | ✅ Done | - | Explicitly mention the `size` key | -| Standardize method signatures | ✅ Done | - | PHP 8.1+ nullable types | -| Fix `(double)` → `(float)` cast | ✅ Done | - | `Model.php` | -| Handle `array_key_exists` with null key | ✅ Done | - | `Console.php` | -| Create test directory if missing | ✅ Done | - | `CustomCommand.php` | +| Fix Barry model `array` cast returning `stdClass` | ✅ Done | - | `Model::executeDataCasting` + `parseToJson($value, assoc: true)`| +| Fix Validator `nullable\|required` priority | ✅ Done | - | `nullable` no longer short-circuits `required` | +| Fix `EnvTest` singleton pollution between tests | ✅ Done | - | `Env::reset()` added | +| Fix `SchedulerCommand` (`routes/scheduler.php` loading) | ✅ Done | - | `loadSchedulerFile()` updated, tolerates missing Loader | +| Remove dead `Model::$soft_delete` property | ✅ Done | - | Replaced with a fully functional trait | +| Improve `addEnum` / `changeEnum` error messages | ✅ Done | - | Explicitly mention the `size` key | +| Standardize method signatures | ✅ Done | - | PHP 8.1+ nullable types | +| Fix `(double)` → `(float)` cast | ✅ Done | - | `Model.php` | +| Handle `array_key_exists` with null key | ✅ Done | - | `Console.php` | +| Create test directory if missing | ✅ Done | - | `CustomCommand.php` | ### Documentation From f33780dc3fb0160cb662cfefe9c55dd4279de005 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sat, 18 Jul 2026 04:00:37 +0000 Subject: [PATCH 11/23] feat(): config encrypt method to config --- src/Queue/Adapters/QueueAdapter.php | 66 ++++++++++++++++++++++++----- src/Security/Crypto.php | 59 ++++++++++++++++++++++++++ tests/Config/stubs/config/queue.php | 8 ++++ 3 files changed, 122 insertions(+), 11 deletions(-) diff --git a/src/Queue/Adapters/QueueAdapter.php b/src/Queue/Adapters/QueueAdapter.php index 8277508d..c21916b4 100644 --- a/src/Queue/Adapters/QueueAdapter.php +++ b/src/Queue/Adapters/QueueAdapter.php @@ -64,6 +64,14 @@ abstract class QueueAdapter */ protected static bool $suppressLogging = false; + /** + * Cached queue payload protection mode ('encrypt' | 'sign'), resolved once + * from config on first use. Null until resolved. + * + * @var ?string + */ + private ?string $payload_protection = null; + /** * Enable or disable logging suppression * @@ -99,12 +107,43 @@ abstract public function push(QueueTask $task): bool; */ public function serializeProducer(QueueTask $task): string { - // Authenticate the payload (encrypt-then-MAC) so a worker will only ever - // unserialize bytes this application produced. Without this, anyone able - // to write to the queue backend could deliver a crafted serialized - // object and trigger PHP object injection (RCE via a POP chain) when the - // worker deserializes it. - return Crypto::encrypt(serialize($task)); + // Authenticate the payload so a worker will only ever unserialize bytes + // this application produced. Without this, anyone able to write to the + // queue backend could deliver a crafted serialized object and trigger PHP + // object injection (RCE via a POP chain) when the worker deserializes it. + // + // 'encrypt' (default) also keeps the payload confidential in the broker; + // 'sign' leaves it readable for debugging while staying tamper-proof. + $serialized = serialize($task); + + return $this->payloadProtection() === 'sign' + ? Crypto::sign($serialized) + : Crypto::encrypt($serialized); + } + + /** + * Resolve the configured queue payload protection mode. + * + * 'encrypt' (confidential + tamper-proof) is the secure default; only an + * explicit config('queue.payload_protection') === 'sign' opts into the + * readable-but-signed format. Falls back to 'encrypt' when config is not + * booted, so the secure behaviour holds in every context. + * + * @return string + */ + private function payloadProtection(): string + { + if ($this->payload_protection === null) { + try { + $mode = config('queue.payload_protection'); + } catch (Throwable) { + $mode = null; + } + + $this->payload_protection = $mode === 'sign' ? 'sign' : 'encrypt'; + } + + return $this->payload_protection; } /** @@ -115,11 +154,16 @@ public function serializeProducer(QueueTask $task): string */ public function unserializeProducer(string $task): QueueTask { - // Verify integrity BEFORE unserialize(). Crypto::decrypt fails closed - // (returns false) on a tampered, forged or wrong-key payload, so crafted - // bytes never reach unserialize(). Only payloads produced by - // serializeProducer() with this application's key get past this point. - $plain = Crypto::decrypt($task); + // Verify integrity BEFORE unserialize(). Both schemes fail closed + // (return false) on a tampered, forged or wrong-key payload, so crafted + // bytes never reach unserialize(). We accept either the signed or the + // encrypted format regardless of the configured mode, so flipping + // queue.payload_protection during a rollout never drops in-flight jobs. + $plain = Crypto::verify($task); + + if ($plain === false) { + $plain = Crypto::decrypt($task); + } if ($plain === false) { throw new RuntimeException( diff --git a/src/Security/Crypto.php b/src/Security/Crypto.php index 27a2dd25..04ba6be5 100644 --- a/src/Security/Crypto.php +++ b/src/Security/Crypto.php @@ -30,6 +30,12 @@ class Crypto */ private const HEADER = 'BOW2:'; + /** + * Header tagging an authenticated-but-unencrypted (signed) payload. The ':' + * keeps it distinguishable from an encrypted (BOW2:) or base64 value. + */ + private const SIGN_HEADER = 'BOWS1:'; + /** * The authentication tag length in bytes (HMAC-SHA256). */ @@ -136,6 +142,59 @@ public static function decrypt(string $data): string|bool ); } + /** + * Produce a tamper-proof but *readable* payload. + * + * Unlike encrypt(), the data is not enciphered — only a detached + * HMAC-SHA256 tag is prepended — so the payload stays inspectable in transit + * (e.g. a queue backend) while still being protected against tampering and + * forgery. Use when integrity matters but confidentiality does not. + * + * @param string $data + * @return string + */ + public static function sign(string $data): string + { + $mac = hash_hmac('sha256', $data, static::deriveKey('sign', static::resolveKey()), true); + + return self::SIGN_HEADER . base64_encode($mac) . '.' . $data; + } + + /** + * Verify a signed payload, returning the original data or false on a bad tag. + * + * Fails closed (false) on a wrong header, truncation, tampering or wrong key, + * exactly like decrypt(). + * + * @param string $data + * @return string|bool + */ + public static function verify(string $data): string|bool + { + if (!str_starts_with($data, self::SIGN_HEADER)) { + return false; + } + + $body = substr($data, strlen(self::SIGN_HEADER)); + $dot = strpos($body, '.'); + + if ($dot === false) { + return false; + } + + $mac = base64_decode(substr($body, 0, $dot), true); + + if ($mac === false || strlen($mac) !== self::MAC_LENGTH) { + return false; + } + + $payload = substr($body, $dot + 1); + $calculated = hash_hmac('sha256', $payload, static::deriveKey('sign', static::resolveKey()), true); + + // Constant-time compare; reject before the caller trusts the payload. + return hash_equals($calculated, $mac) ? $payload : false; + } + /** * Decrypt a value produced by the legacy (static IV, unauthenticated) * format. Kept only so data encrypted before the upgrade keeps working. diff --git a/tests/Config/stubs/config/queue.php b/tests/Config/stubs/config/queue.php index 01dfb8fd..8ffe882a 100644 --- a/tests/Config/stubs/config/queue.php +++ b/tests/Config/stubs/config/queue.php @@ -6,6 +6,14 @@ */ "default" => "sync", + /** + * How queue payloads are protected on the wire: + * "encrypt" — confidential + tamper-proof (default, recommended) + * "sign" — tamper-proof but readable in the broker (easier to debug) + * Both require security.key to be configured. + */ + "payload_protection" => "encrypt", + /** * The queue drive connection */ From ee6466b3db1e67245eb2e7727f8be0bb452f30d7 Mon Sep 17 00:00:00 2001 From: papac Date: Wed, 15 Jul 2026 02:28:04 +0000 Subject: [PATCH 12/23] Update CHANGELOG --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd93e1af..7095b738 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 5.4.11 - 2026-07-15 + +### What's Changed + +* Update CHANGELOG by @papac in https://github.com/bowphp/framework/pull/425 +* fix(queue): add beanstalkd type error by @papac in https://github.com/bowphp/framework/pull/424 + +**Full Changelog**: https://github.com/bowphp/framework/compare/5.4.10...5.4.11 + ## 5.4.10 - 2026-06-22 ### What's Changed @@ -363,6 +372,7 @@ Database::transaction(fn() => $user->update(['name' => ''])); + ``` From c2cbbb0051cde74d6b96f8c086251e7919cbb4aa Mon Sep 17 00:00:00 2001 From: papac Date: Wed, 15 Jul 2026 02:50:59 +0000 Subject: [PATCH 13/23] Update CHANGELOG --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7095b738..94819fea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 5.4.12 - 2026-07-15 + +### What's Changed + +* Update CHANGELOG by @papac in https://github.com/bowphp/framework/pull/426 +* fix(queue): add beanstalkd type error by @papac in https://github.com/bowphp/framework/pull/427 + +**Full Changelog**: https://github.com/bowphp/framework/compare/5.4.11...5.4.12 + ## 5.4.11 - 2026-07-15 ### What's Changed @@ -373,6 +382,7 @@ Database::transaction(fn() => $user->update(['name' => ''])); + ``` From f1d961ad77f832ff87ab19e782bf71ace1f0d03d Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Mon, 10 Aug 2026 21:11:01 +0000 Subject: [PATCH 14/23] fix(queue): fix payload deserialization --- src/Application/Application.php | 21 ++- src/Http/Request.php | 55 ++++++- src/Queue/Adapters/BeanstalkdAdapter.php | 20 --- src/Queue/Adapters/QueueAdapter.php | 63 +++++++- src/Queue/Adapters/RabbitMQAdapter.php | 115 ++++++++++++-- tests/Application/ApplicationTest.php | 6 + tests/Http/RequestTest.php | 58 +++++++ tests/Queue/QueueAdapterSerializationTest.php | 63 ++++++++ tests/Queue/RabbitMQAdapterMessageTest.php | 146 ++++++++++++++++++ tests/Queue/Stubs/FailingQueueTaskStub.php | 27 ++++ 10 files changed, 528 insertions(+), 46 deletions(-) create mode 100644 tests/Http/RequestTest.php create mode 100644 tests/Queue/QueueAdapterSerializationTest.php create mode 100644 tests/Queue/RabbitMQAdapterMessageTest.php create mode 100644 tests/Queue/Stubs/FailingQueueTaskStub.php diff --git a/src/Application/Application.php b/src/Application/Application.php index a221efa6..5f2d9122 100644 --- a/src/Application/Application.php +++ b/src/Application/Application.php @@ -146,6 +146,18 @@ public function run(): bool $this->router->setPrefix(''); + // Raised here rather than from Request::capture(), which runs during + // this class's constructor — too early for the container or the error + // handler to turn it into a response. By now both are up, so a bad + // payload is a rendered 400 instead of an uncaught PHP fatal. + $invalid_json_payload = $this->request->getInvalidJsonPayload(); + + if (!is_null($invalid_json_payload)) { + throw new BadRequestException( + "The request json payload is invalid: " . $invalid_json_payload, + ); + } + $method = $this->request->method(); // We verify the existence of the method of the request in @@ -213,12 +225,17 @@ public function send(): bool * @param int $code * @return void */ - private function sendResponse(mixed $response, int $code = 200): void + private function sendResponse(mixed $response, ?int $code = null): void { if ($response instanceof ResponseInterface) { $response->sendContent(); } else { - echo $this->response->send($response, $code); + // Carry the status the response already holds. A controller that + // returned response()->json($data, 404) has set it on this very + // instance, and passing a hardcoded 200 here overwrote it — every + // json() error answered 200 with an error body, so clients could + // not tell success from failure. + echo $this->response->send($response, $code ?? $this->response->getCode()); } } diff --git a/src/Http/Request.php b/src/Http/Request.php index 2d64c0a1..51f125fd 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -64,6 +64,13 @@ class Request */ private bool $capture = false; + /** + * Why the JSON payload could not be decoded, when it could not be. + * + * @var string|null + */ + private ?string $invalid_json_payload = null; + /** * Check if file exists * @@ -91,12 +98,30 @@ public function capture() $this->id = "req_" . sha1(uniqid() . time()); if ($this->getHeader('content-type') == 'application/json') { - try { - $data = json_decode(file_get_contents("php://input"), true, 1024, JSON_THROW_ON_ERROR); - } catch (Throwable $e) { - throw new BadRequestException( - "The request json payload is invalid: " . $e->getMessage(), - ); + $raw = (string) file_get_contents("php://input"); + + // A bodyless request is not a malformed one. Clients routinely send + // "Content-Type: application/json" on a POST/DELETE that carries no + // payload, and json_decode('') throws — a throw this early cannot be + // rendered, because capture() runs from Application::__construct + // before the container binds "response", which BadRequestException + // needs. The client would get a raw PHP fatal instead of a 400. + if (trim($raw) === '') { + $data = []; + } else { + try { + $data = json_decode($raw, true, 1024, JSON_THROW_ON_ERROR); + } catch (Throwable $e) { + // Recorded, not thrown. capture() runs from + // Application::__construct, which is too early for ANY + // exception to be rendered: the container has not bound + // "response" yet and the error handler is installed later + // in the boot, so a throw here reaches the client as a raw + // PHP fatal instead of a 400. Application::run() raises it + // once both are in place. + $this->invalid_json_payload = $e->getMessage(); + $data = []; + } } } else { $data = $_POST ?? []; @@ -116,6 +141,17 @@ public function capture() $this->capture = true; } + /** + * The JSON decoding error for this request, or null when the payload was + * absent or well-formed. + * + * @return string|null + */ + public function getInvalidJsonPayload(): ?string + { + return $this->invalid_json_payload; + } + /** * Retrieve query variables * @@ -234,7 +270,12 @@ public function get(string $key, mixed $default = null): mixed { $value = $this->input[$key] ?? $default; - if (is_callable($value)) { + // Only a callable *default* may be resolved — a closure or an invokable + // object. Never a string or an array: those can come straight from the + // request, and is_callable() is true for the name of any defined + // function, so `?field=phpinfo` would call it and return its result in + // place of the input the caller asked for. + if (is_object($value) && is_callable($value)) { return $value(); } diff --git a/src/Queue/Adapters/BeanstalkdAdapter.php b/src/Queue/Adapters/BeanstalkdAdapter.php index 6796dd7d..c80e0e59 100644 --- a/src/Queue/Adapters/BeanstalkdAdapter.php +++ b/src/Queue/Adapters/BeanstalkdAdapter.php @@ -298,26 +298,6 @@ private function resolveFailedTask(Job $job, QueueTask $task, Throwable $excepti } } - /** - * Store the failed payload for later inspection - * - * Recording is best effort: the cache is not guaranteed to be configured in - * a worker process, and a throw here would escape the failure handler and - * kill the worker before the job is deleted, making it redeliver on TTR. - * - * @param string $key - * @param mixed $payload - * @return void - */ - private function recordFailedPayload(string $key, mixed $payload): void - { - try { - cache($key, $payload); - } catch (Throwable $exception) { - $this->logError($exception); - } - } - /** * Release the task back to the queue for retry * diff --git a/src/Queue/Adapters/QueueAdapter.php b/src/Queue/Adapters/QueueAdapter.php index c21916b4..d1e4815a 100644 --- a/src/Queue/Adapters/QueueAdapter.php +++ b/src/Queue/Adapters/QueueAdapter.php @@ -171,7 +171,48 @@ public function unserializeProducer(string $task): QueueTask ); } - return unserialize($plain); + $producer = unserialize($plain); + + // The payload is authentic but names a class this process cannot load: + // the task was renamed or removed, the worker runs an older revision than + // the producer, or another application shares the broker. PHP hands back a + // __PHP_Incomplete_Class, which the QueueTask return type would surface as + // an opaque TypeError. Name the class instead so the poison payload the + // adapters record points straight at the missing task. + if (!$producer instanceof QueueTask) { + throw new RuntimeException(sprintf( + 'Queue payload does not hold a %s, got %s.', + QueueTask::class, + $this->describeProducer($producer) + )); + } + + return $producer; + } + + /** + * Describe what came out of the payload for the rejection message + * + * A __PHP_Incomplete_Class keeps the original class name in a magic property, + * which get_class() does not expose, so read it out to report the task the + * worker is missing rather than the placeholder type. + * + * @param mixed $producer + * @return string + */ + private function describeProducer(mixed $producer): string + { + if (!is_object($producer)) { + return get_debug_type($producer); + } + + if (!$producer instanceof \__PHP_Incomplete_Class) { + return $producer::class; + } + + $name = ((array) $producer)['__PHP_Incomplete_Class_Name'] ?? 'unknown'; + + return sprintf('the unloadable class %s', $name); } /** @@ -418,6 +459,26 @@ final protected function generateId(): string return md5(uniqid((string) time(), true) . bin2hex(random_bytes(10)) . str_uuid() . microtime(true)); } + /** + * Store the failed payload for later inspection + * + * Recording is best effort: the cache is not guaranteed to be configured in + * a worker process, and a throw here would escape the failure handler and + * kill the worker before the message is settled, making it redeliver. + * + * @param string $key + * @param mixed $payload + * @return void + */ + protected function recordFailedPayload(string $key, mixed $payload): void + { + try { + cache($key, $payload); + } catch (Throwable $exception) { + $this->logError($exception); + } + } + /** * Log processing task * diff --git a/src/Queue/Adapters/RabbitMQAdapter.php b/src/Queue/Adapters/RabbitMQAdapter.php index 86d0c63b..bcd950a5 100644 --- a/src/Queue/Adapters/RabbitMQAdapter.php +++ b/src/Queue/Adapters/RabbitMQAdapter.php @@ -79,22 +79,7 @@ public function push(QueueTask $task): bool public function run(?string $queue = null): void { $queue = $this->getQueue($queue); - $callback = function ($msg) { - $task = $this->unserializeProducer($msg->body); - try { - $this->logProcessingTask($task); - if (!method_exists($task, 'process')) { - throw new \RuntimeException('Task does not have a process or handle method.'); - } - $task->process(); - $this->logProcessedTask($task); - $msg->ack(); - } catch (\Throwable $e) { - $this->logFailedTask($task, $e); - // Optionally requeue: set second param to true to requeue - $msg->nack(false, false); // reject and don't requeue - } - }; + $callback = fn ($msg) => $this->processMessage($msg); $this->channel->basic_qos(null, 1, null); $this->channel->basic_consume($queue, '', false, false, false, false, $callback); while ($this->channel->is_consuming()) { @@ -109,6 +94,104 @@ public function run(?string $queue = null): void } } + /** + * Process a consumed message + * + * @param object $msg + * @return void + */ + protected function processMessage(object $msg): void + { + $task = null; + + try { + // unserializeProducer() belongs inside the try: a payload that fails + // integrity verification, or that names a task class this worker + // cannot load, throws here. Letting it escape the consumer callback + // leaves the message neither acked nor nacked, so the broker + // redelivers it and the worker crash-loops on the same poison bytes. + $task = $this->unserializeProducer($msg->body); + + $this->logProcessingTask($task); + + if (!method_exists($task, 'process')) { + throw new RuntimeException('Task does not have a process or handle method.'); + } + + $task->process(); + $this->logProcessedTask($task); + $msg->ack(); + } catch (\Throwable $e) { + $this->handleMessageFailure($msg, $task, $e); + } + } + + /** + * Settle a message whose processing failed + * + * Mirrors the beanstalkd adapter: the task decides, through onException() + * and taskShouldBeDelete(), whether the failure is terminal. A transient + * failure is requeued instead of being dropped on the first throw, and the + * throttle keeps a permanently failing task from spinning the worker hot. + * + * AMQP has no per-message delay without a delayed-exchange plugin, so + * getDelay() cannot be honoured here; the requeue is immediate. + * + * @param object $msg + * @param QueueTask|null $task + * @param \Throwable $exception + * @return void + */ + private function handleMessageFailure(object $msg, ?QueueTask $task, \Throwable $exception): void + { + $this->logFailedTask($task, $exception); + + // Poison message: the body never became a task, so there is no id to key + // on and nothing to retry — a requeue would redeliver the same bytes for + // ever. Keep the raw body for inspection and reject it for good. + if (is_null($task)) { + $this->recordFailedPayload("task:failed:body:" . md5($msg->body), $msg->body); + $msg->nack(false, false); + + return; + } + + $msg->nack(!$this->resolveFailedTask($task, $exception), false); + + $this->sleep(1); + } + + /** + * Run the task defined failure handling and decide whether to drop the message + * + * onException() and taskShouldBeDelete() are both overridable, so they are + * user code and may throw. A throw must not escape, otherwise the message is + * never settled, it redelivers and the worker crash-loops on it. + * + * @param QueueTask $task + * @param \Throwable $exception + * @return bool Whether the message should be dropped + */ + private function resolveFailedTask(QueueTask $task, \Throwable $exception): bool + { + try { + $this->recordFailedPayload( + "task:failed:" . $task->getId(), + method_exists($task, 'getData') ? $task->getData() : "" + ); + + $task->onException($exception); + + return $task->taskShouldBeDelete(); + } catch (\Throwable $taskException) { + $this->logError($taskException); + + // The task cannot handle its own failure, so retrying it would most + // likely break the same way. Drop it rather than requeue for ever. + return true; + } + } + /** * Get the queue size * diff --git a/tests/Application/ApplicationTest.php b/tests/Application/ApplicationTest.php index 0ebd2fbb..7f9e7ae1 100644 --- a/tests/Application/ApplicationTest.php +++ b/tests/Application/ApplicationTest.php @@ -44,6 +44,8 @@ private function createRequestMock(string $method = 'GET', string $path = '/'): $request->allows()->path()->andReturns($path); $request->allows()->get("_method")->andReturns(""); $request->allows()->domain()->andReturns("localhost"); + // run() asks whether the JSON body failed to decode; null = it did not. + $request->allows()->getInvalidJsonPayload()->andReturns(null); return $request; } @@ -57,6 +59,9 @@ private function createResponseMock(int $expectedStatus = 200): Response $response->allows()->withHeader('X-Powered-By', 'Bow Framework'); $response->allows()->status($expectedStatus); $response->allows()->send(Mockery::any(), Mockery::any())->andReturn(''); + // sendResponse() now reads the status already held by the response + // instead of overwriting it with a hardcoded 200. + $response->allows()->getCode()->andReturns($expectedStatus); return $response; } @@ -146,6 +151,7 @@ public function test_disable_powered_by_mention() $response->shouldNotReceive('withHeader')->with('X-Powered-By', Mockery::any()); $response->allows()->status(200); $response->allows()->send(Mockery::any(), Mockery::any())->andReturn(''); + $response->allows()->getCode()->andReturns(200); $config = $this->createConfigMock(); diff --git a/tests/Http/RequestTest.php b/tests/Http/RequestTest.php new file mode 100644 index 00000000..d0093159 --- /dev/null +++ b/tests/Http/RequestTest.php @@ -0,0 +1,58 @@ +assertTrue(is_callable($value), "fixture {$value} must be a real function"); + + $_POST = ['field' => $value]; + + $request = new Request(); + $request->capture(); + + $this->assertSame($value, $request->get('field')); + } + + /** A callable default is the feature this guard must preserve. */ + public function testCallableDefaultIsStillResolved(): void + { + $request = new Request(); + $request->capture(); + + $this->assertSame('resolved', $request->get('absent', fn () => 'resolved')); + $this->assertSame('plain', $request->get('absent', 'plain')); + } + + /** @return array */ + public static function callableLookingInput(): array + { + return [ + 'php builtin' => ['phpinfo'], + 'string function' => ['trim'], + 'array function' => ['compact'], + ]; + } +} diff --git a/tests/Queue/QueueAdapterSerializationTest.php b/tests/Queue/QueueAdapterSerializationTest.php new file mode 100644 index 00000000..4661b933 --- /dev/null +++ b/tests/Queue/QueueAdapterSerializationTest.php @@ -0,0 +1,63 @@ +adapter = new class extends QueueAdapter { + public function configure(array $config): QueueAdapter + { + return $this; + } + + public function push(QueueTask $task): bool + { + return true; + } + }; + } + + public function test_it_round_trips_a_task(): void + { + $payload = $this->adapter->serializeProducer(new BasicQueueTaskStub("round-trip")); + + $this->assertInstanceOf(BasicQueueTaskStub::class, $this->adapter->unserializeProducer($payload)); + } + + public function test_it_rejects_a_payload_whose_task_class_is_not_loadable(): void + { + // A task enqueued by a producer running code the worker does not have: + // the class was renamed, removed, or lives in another service. unserialize() + // yields a __PHP_Incomplete_Class, which must not escape as a TypeError. + $payload = Crypto::encrypt('O:35:"App\Tasks\SyncWhatsAppTemplatesTask":0:{}'); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('App\Tasks\SyncWhatsAppTemplatesTask'); + + $this->adapter->unserializeProducer($payload); + } + + public function test_it_rejects_a_payload_that_does_not_hold_a_task(): void + { + $payload = Crypto::encrypt(serialize(['id' => 1])); + + $this->expectException(RuntimeException::class); + + $this->adapter->unserializeProducer($payload); + } +} diff --git a/tests/Queue/RabbitMQAdapterMessageTest.php b/tests/Queue/RabbitMQAdapterMessageTest.php new file mode 100644 index 00000000..739488a5 --- /dev/null +++ b/tests/Queue/RabbitMQAdapterMessageTest.php @@ -0,0 +1,146 @@ +adapter = new class extends RabbitMQAdapter { + public function consume(object $message): void + { + $this->processMessage($message); + } + + // The failure path throttles with a real sleep; tests must not pay it. + public function sleep(int $seconds): void + { + } + }; + } + + public function test_it_acknowledges_a_processed_message(): void + { + $message = $this->message( + $this->adapter->serializeProducer(new BasicQueueTaskStub("rabbitmq_ack")) + ); + + $this->adapter->consume($message); + + $this->assertSame(1, $message->acked); + $this->assertSame(0, $message->nacked); + } + + public function test_it_nacks_a_payload_whose_task_class_is_not_loadable(): void + { + // The unserialize failure must not escape the consumer callback: an + // unacked, unnacked message is redelivered forever and crash-loops the + // worker on the same poison payload. + $message = $this->message(Crypto::encrypt('O:35:"App\Tasks\SyncWhatsAppTemplatesTask":0:{}')); + + $this->adapter->consume($message); + + $this->assertSame(0, $message->acked); + $this->assertSame(1, $message->nacked); + $this->assertFalse($message->requeued); + } + + public function test_it_nacks_a_tampered_payload(): void + { + $message = $this->message("not-a-valid-payload"); + + $this->adapter->consume($message); + + $this->assertSame(0, $message->acked); + $this->assertSame(1, $message->nacked); + $this->assertFalse($message->requeued); + } + + public function test_it_requeues_a_task_that_failed_but_may_be_retried(): void + { + // A transient failure (broker blip, timeout) must go back on the queue + // instead of being discarded on the first throw. + $message = $this->message($this->adapter->serializeProducer( + $this->failingTask() + )); + + $this->adapter->consume($message); + + $this->assertSame(0, $message->acked); + $this->assertSame(1, $message->nacked); + $this->assertTrue($message->requeued); + } + + public function test_it_drops_a_failed_task_that_asked_to_be_deleted(): void + { + $message = $this->message($this->adapter->serializeProducer( + $this->failingTask(dropAfterFailure: true) + )); + + $this->adapter->consume($message); + + $this->assertSame(0, $message->acked); + $this->assertSame(1, $message->nacked); + $this->assertFalse($message->requeued); + } + + /** + * Build a failing task the way push() delivers one: with an id already set. + */ + private function failingTask(bool $dropAfterFailure = false): FailingQueueTaskStub + { + $task = new FailingQueueTaskStub($dropAfterFailure); + $task->setId("rabbitmq-failing-task"); + + return $task; + } + + private function message(string $body): object + { + return new class ($body) { + public int $acked = 0; + public int $nacked = 0; + public bool $requeued = false; + + public function __construct(public string $body) + { + } + + public function ack(): void + { + $this->acked++; + } + + public function nack(bool $requeue = false, bool $multiple = false): void + { + $this->nacked++; + $this->requeued = $requeue; + } + }; + } +} diff --git a/tests/Queue/Stubs/FailingQueueTaskStub.php b/tests/Queue/Stubs/FailingQueueTaskStub.php new file mode 100644 index 00000000..d7827596 --- /dev/null +++ b/tests/Queue/Stubs/FailingQueueTaskStub.php @@ -0,0 +1,27 @@ +dropAfterFailure) { + $this->deleteTask(); + } + } +} From e47595db9145664383a8d11279144d03179405c4 Mon Sep 17 00:00:00 2001 From: papac Date: Mon, 28 Sep 2026 19:10:36 +0000 Subject: [PATCH 15/23] Update CHANGELOG --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94819fea..bcae3d22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 5.4.13 - 2026-09-28 + +### What's Changed + +* Update CHANGELOG by @papac in https://github.com/bowphp/framework/pull/428 +* fix(queue): Return value must be of type Bow\Queue\QueueTask, __PHP_Incomplete_Class returned by @papac in https://github.com/bowphp/framework/pull/429 + +**Full Changelog**: https://github.com/bowphp/framework/compare/5.4.12...5.4.13 + ## 5.4.12 - 2026-07-15 ### What's Changed @@ -383,6 +392,7 @@ Database::transaction(fn() => $user->update(['name' => ''])); + ``` From 0227030b8d35947fd1811f1b41bd1c9a58fc5b60 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sun, 4 Oct 2026 06:26:35 +0000 Subject: [PATCH 16/23] Security hardening across query builder, storage, auth, mail and crypto - Database\QueryBuilder: bind whereBetween/whereNotBetween range values (SQL injection) and validate column/table identifiers in where*, join, select, aggregate, distinct, increment and insert/update keys through assertSafeIdentifier (wildcards allowed only where legitimate). - Storage\DiskFilesystemService::path(): confine resolved paths to the base directory and reject traversal (arbitrary read/write/delete). - Mail\Envelop: strip CR/LF/NUL from header-bound values (header/SMTP injection, CWE-93). - Middleware\CsrfMiddleware: reject empty tokens and compare with hash_equals (null==null bypass and timing). - Auth\SessionGuard + Session::regenerate(): rotate the session id on login while preserving data (session fixation). - Security\Crypto::decrypt(): fail closed on non-authenticated legacy (static-IV) input unless explicitly opted in via allowLegacy(). - Http: sanitize download filename; basename() the explicit upload target. Adds regression tests for the above. --- src/Auth/Guards/SessionGuard.php | 8 ++ src/Database/QueryBuilder.php | 78 +++++++++++++++---- src/Http/Response.php | 9 ++- src/Http/UploadedFile.php | 4 + src/Mail/Envelop.php | 40 +++++++++- src/Middleware/CsrfMiddleware.php | 14 +++- src/Security/Crypto.php | 26 +++++++ src/Session/Session.php | 7 +- src/Storage/Service/DiskFilesystemService.php | 34 +++++++- tests/Database/Query/QueryBuilderTest.php | 31 ++++++++ tests/Filesystem/DiskFilesystemTest.php | 21 +++++ tests/Hashing/SecurityTest.php | 31 ++++++++ tests/Mail/EnvelopHeaderInjectionTest.php | 62 +++++++++++++++ 13 files changed, 336 insertions(+), 29 deletions(-) create mode 100644 tests/Mail/EnvelopHeaderInjectionTest.php diff --git a/src/Auth/Guards/SessionGuard.php b/src/Auth/Guards/SessionGuard.php index 29b357f6..35bf29f8 100644 --- a/src/Auth/Guards/SessionGuard.php +++ b/src/Auth/Guards/SessionGuard.php @@ -63,6 +63,10 @@ public function attempts(array $credentials, bool $remember = false): bool $password = $credentials[$fields['password']]; if (Hash::check($password, $user->{$fields['password']})) { + // Rotate the session ID on privilege elevation (anti session + // fixation). regenerate() preserves data, so the stored user below + // lives under the new ID. + $this->getSession()->regenerate(); $this->getSession()->put($this->session_key, $user); if ($remember) { @@ -127,6 +131,10 @@ public function guest(): bool */ public function login(Authentication $user, bool $remember = false): bool { + // Rotate the session ID on privilege elevation (anti session fixation). + // regenerate() preserves data, so the stored user below lives under the + // new ID. + $this->getSession()->regenerate(); $this->getSession()->add($this->session_key, $user); if ($remember) { diff --git a/src/Database/QueryBuilder.php b/src/Database/QueryBuilder.php index b352478f..8d375205 100644 --- a/src/Database/QueryBuilder.php +++ b/src/Database/QueryBuilder.php @@ -352,6 +352,8 @@ public function where( ); } + $column = $this->assertSafeIdentifier($column, 'where'); + if ($value instanceof QueryBuilder) { $indicator = "(" . $value->toSql() . ")"; } else { @@ -429,11 +431,17 @@ private static function isComparisonOperator(mixed $comparator): bool * @return string * @throws QueryBuilderException */ - private static function assertSafeIdentifier(string $identifier, string $clause): string + private function assertSafeIdentifier(string $identifier, string $clause, bool $allowWildcard = false): string { $trimmed = trim($identifier); - if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/', $trimmed)) { + // Aggregates and SELECT lists may legitimately use "*" (and + // "table.*"); WHERE/JOIN/ORDER BY/GROUP BY identifiers may not. + $pattern = $allowWildcard + ? '/^(\*|[A-Za-z_][A-Za-z0-9_]*(\.(\*|[A-Za-z_][A-Za-z0-9_]*))?)$/' + : '/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/'; + + if (!preg_match($pattern, $trimmed)) { throw new QueryBuilderException( "Unsafe identifier passed to {$clause}: [{$identifier}]. " . "Only a plain or table-qualified column name is allowed." @@ -565,6 +573,8 @@ public function setTable(string $table): QueryBuilder */ public function whereNull(string $column): QueryBuilder { + $column = $this->assertSafeIdentifier($column, 'whereNull'); + if (is_null($this->where)) { $this->where = $column . ' is null'; } else { @@ -584,6 +594,8 @@ public function whereNull(string $column): QueryBuilder */ public function whereNotNull(string $column): QueryBuilder { + $column = $this->assertSafeIdentifier($column, 'whereNotNull'); + if (is_null($this->where)) { $this->where = $column . ' is not null'; } else { @@ -602,15 +614,18 @@ public function whereNotNull(string $column): QueryBuilder */ public function whereNotBetween(string $column, array $range): QueryBuilder { + $column = $this->assertSafeIdentifier($column, 'whereNotBetween'); $range = (array) $range; - $between = implode(' and ', $range); if (is_null($this->where)) { - $this->where = $column . ' not between ' . $between; + $this->where = $column . ' not between ? and ?'; } else { - $this->where .= ' and ' . $column . ' not between ' . $between; + $this->where .= ' and ' . $column . ' not between ? and ?'; } + $this->where_data_binding[] = $range[0]; + $this->where_data_binding[] = $range[1]; + return $this; } @@ -625,15 +640,18 @@ public function whereNotBetween(string $column, array $range): QueryBuilder */ public function whereBetween(string $column, array $range): QueryBuilder { + $column = $this->assertSafeIdentifier($column, 'whereBetween'); $range = (array) $range; - $between = implode(' and ', $range); if (is_null($this->where)) { - $this->where = $column . ' between ' . $between; + $this->where = $column . ' between ? and ?'; } else { - $this->where .= ' and ' . $column . ' between ' . $between; + $this->where .= ' and ' . $column . ' between ? and ?'; } + $this->where_data_binding[] = $range[0]; + $this->where_data_binding[] = $range[1]; + return $this; } @@ -675,6 +693,8 @@ public function whereNotIn(string $column, array $range) $in = (string) $range; } + $column = $this->assertSafeIdentifier($column, 'whereNotIn'); + if (is_null($this->where)) { $this->where = $column . ' not in (' . $in . ')'; } else { @@ -708,6 +728,8 @@ public function whereIn(string $column, array $range): QueryBuilder $in = (string) $range; } + $column = $this->assertSafeIdentifier($column, 'whereIn'); + if (is_null($this->where)) { $this->where = $column . ' in (' . $in . ')'; } else { @@ -732,7 +754,7 @@ public function join( mixed $comparator = '=', ?string $second = null ): QueryBuilder { - $table = $this->getPrefix() . $table; + $table = $this->getPrefix() . $this->assertSafeIdentifier($table, 'join'); if (is_null($this->join)) { $this->join = ''; @@ -746,6 +768,9 @@ public function join( $comparator = '='; } + $first = $this->assertSafeIdentifier($first, 'join'); + $second = $this->assertSafeIdentifier($second, 'join'); + // Building the join query $this->join .= 'inner join ' . $table . ' on ' . $first . ' ' . $comparator . ' ' . $second; @@ -791,7 +816,7 @@ public function leftJoin( mixed $comparator = '=', ?string $second = null ): QueryBuilder { - $table = $this->getPrefix() . $table; + $table = $this->getPrefix() . $this->assertSafeIdentifier($table, 'join'); if (is_null($this->join)) { $this->join = ''; @@ -805,6 +830,9 @@ public function leftJoin( $comparator = '='; } + $first = $this->assertSafeIdentifier($first, 'join'); + $second = $this->assertSafeIdentifier($second, 'join'); + // Building the join query $this->join .= 'left join ' . $table . ' on ' . $first . ' ' . $comparator . ' ' . $second . ' '; @@ -827,7 +855,7 @@ public function rightJoin( mixed $comparator = '=', ?string $second = null ): QueryBuilder { - $table = $this->getPrefix() . $table; + $table = $this->getPrefix() . $this->assertSafeIdentifier($table, 'join'); if (is_null($this->join)) { $this->join = ''; @@ -841,6 +869,9 @@ public function rightJoin( $comparator = '='; } + $first = $this->assertSafeIdentifier($first, 'join'); + $second = $this->assertSafeIdentifier($second, 'join'); + $this->join .= 'right join ' . $table . ' on ' . $first . ' ' . $comparator . ' ' . $second; return $this; @@ -925,7 +956,7 @@ public function group(string $column) public function groupBy(string $column): QueryBuilder { if (is_null($this->group)) { - $this->group = static::assertSafeIdentifier($column, 'groupBy'); + $this->group = $this->assertSafeIdentifier($column, 'groupBy'); } return $this; @@ -952,7 +983,7 @@ public function having( $comparator = '='; } - $column = static::assertSafeIdentifier($column, 'having'); + $column = $this->assertSafeIdentifier($column, 'having'); // Bind the value with a placeholder, exactly like where(). A subquery // is inlined; any scalar is parameterised so it can never be injected. @@ -985,7 +1016,7 @@ public function orderBy(string $column, string $type = 'asc'): QueryBuilder $type = 'asc'; } - $column = static::assertSafeIdentifier($column, 'orderBy'); + $column = $this->assertSafeIdentifier($column, 'orderBy'); if (is_null($this->order)) { $this->order = 'order by ' . $column . ' ' . strtolower($type); @@ -1016,6 +1047,7 @@ public function max(string $column): int|float */ private function aggregate($aggregate, $column): mixed { + $column = $this->assertSafeIdentifier($column, 'aggregate', true); $sql = 'select ' . $aggregate . '(' . $column . ') from ' . $this->table; // Adding the join clause @@ -1344,6 +1376,8 @@ public function select(array $select = ['*']) foreach ($select as $key => $value) { if ($value instanceof QueryBuilder) { $select[$key] = '(' . $value->toSql() . ')'; + } else { + $select[$key] = $this->assertSafeIdentifier((string) $value, 'select', true); } } @@ -1386,8 +1420,14 @@ public function jump(int $offset = 0): QueryBuilder */ public function update(array $data = []): int { + $columns = array_keys($data); + + foreach ($columns as $column) { + $this->assertSafeIdentifier((string) $column, 'update'); + } + $sql = 'update ' . $this->table . ' set '; - $sql .= implode(' = ?, ', array_keys($data)) . ' = ?'; + $sql .= implode(' = ?, ', $columns) . ' = ?'; if (!is_null($this->where)) { $sql .= ' where ' . $this->where; @@ -1481,6 +1521,7 @@ public function decrement(string $column, int $step = 1): int */ private function incrementAction(string $column, int $step = 1, string $direction = '+') { + $column = $this->assertSafeIdentifier($column, 'incrementAction'); $sql = 'update ' . $this->table . ' set ' . $column . ' = ' . $column . ' ' . $direction . ' ' . $step; if (!is_null($this->where)) { @@ -1505,6 +1546,8 @@ private function incrementAction(string $column, int $step = 1, string $directio */ public function distinct(string $column) { + $column = $this->assertSafeIdentifier($column, 'distinct', true); + if (!is_null($this->select)) { $this->select .= ", distinct $column"; } else { @@ -1619,6 +1662,11 @@ public function insert(array $values): int private function insertOne(array $values): int { $fields = array_keys($values); + + foreach ($fields as $field) { + $this->assertSafeIdentifier((string) $field, 'insertOne'); + } + $column = implode(', ', $fields); $sql = 'insert into ' . $this->table . '(' . $column . ') values'; diff --git a/src/Http/Response.php b/src/Http/Response.php index cbff3beb..344b59ff 100644 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -108,6 +108,9 @@ public function getCode(): int /** * Download the given file as an argument * + * Note: $file is expected to be a trusted, caller-controlled path. Never + * pass unsanitized user input as $file, as it is read directly from disk. + * * @param string $file * @param ?string $filename * @param array $headers @@ -124,9 +127,13 @@ public function download( $filename = basename($file); } + // Sanitize the filename used in the Content-Disposition header to prevent + // header injection and path disclosure (strip directory, CR/LF and quotes). + $filename = str_replace(["\r", "\n", '"'], '', basename($filename)); + $disposition = $headers["disposition"] ?? 'attachment'; - $this->withHeader('Content-Disposition', $disposition . '; filename=' . $filename); + $this->withHeader('Content-Disposition', $disposition . '; filename="' . $filename . '"'); $this->withHeader('Content-Type', $type); $file_size = filesize($file); diff --git a/src/Http/UploadedFile.php b/src/Http/UploadedFile.php index bfd4ad51..9b9e9903 100644 --- a/src/Http/UploadedFile.php +++ b/src/Http/UploadedFile.php @@ -140,6 +140,10 @@ public function moveTo(string $to, ?string $filename = null): bool if (is_null($filename)) { $filename = $this->getHashName(); + } else { + // Strip any directory component from an explicit filename to prevent + // path traversal outside of the destination directory. + $filename = basename($filename); } if (!is_dir($to)) { diff --git a/src/Mail/Envelop.php b/src/Mail/Envelop.php index ff543de2..72c2422b 100644 --- a/src/Mail/Envelop.php +++ b/src/Mail/Envelop.php @@ -137,11 +137,25 @@ protected function setBoundary(string $boundary): void */ public function withHeader(string $key, string $value): Envelop { + $key = $this->sanitizeHeaderValue($key); + $value = $this->sanitizeHeaderValue($value); + $this->headers[] = "$key: $value"; return $this; } + /** + * Strip CR/LF/NUL from a header-bound value to prevent header injection + * + * @param string $value + * @return string + */ + private function sanitizeHeaderValue(string $value): string + { + return str_replace(["\r", "\n", "\0"], '', $value); + } + /** * Define the receiver * @@ -151,10 +165,10 @@ public function withHeader(string $key, string $value): Envelop */ public function to(string|array $to): Envelop { - $recipients = (array)$to; + $recipients = (array) $to; - foreach ($recipients as $to) { - $this->to[] = $this->formatEmail($to); + foreach ($recipients as $item) { + $this->to[] = $this->formatEmail($item); } return $this; @@ -236,7 +250,7 @@ public function compileHeaders(): string */ public function subject(string $subject): Envelop { - $this->subject = $subject; + $this->subject = $this->sanitizeHeaderValue($subject); return $this; } @@ -250,6 +264,9 @@ public function subject(string $subject): Envelop */ public function from(string $from, ?string $name = null): Envelop { + $from = $this->sanitizeHeaderValue($from); + $name = ($name !== null) ? $this->sanitizeHeaderValue($name) : null; + $this->from = ($name !== null) ? (ucwords($name) . " <{$from}>") : $from; return $this; @@ -305,6 +322,9 @@ public function text(string $text): Envelop */ public function addBcc(string $mail, ?string $name = null): Envelop { + $mail = $this->sanitizeHeaderValue($mail); + $name = ($name !== null) ? $this->sanitizeHeaderValue($name) : null; + $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; $this->headers[] = "Bcc: $mail"; @@ -335,6 +355,9 @@ public function bcc(string $mail, ?string $name = null): Envelop */ public function addCc(string $mail, ?string $name = null): Envelop { + $mail = $this->sanitizeHeaderValue($mail); + $name = ($name !== null) ? $this->sanitizeHeaderValue($name) : null; + $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; $this->headers[] = "Cc: $mail"; @@ -364,6 +387,9 @@ public function cc(string $mail, ?string $name = null): Envelop */ public function addReplyTo(string $mail, ?string $name = null): Envelop { + $mail = $this->sanitizeHeaderValue($mail); + $name = ($name !== null) ? $this->sanitizeHeaderValue($name) : null; + $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; $this->headers[] = "Replay-To: $mail"; @@ -393,6 +419,9 @@ public function replyTo(string $mail, ?string $name = null): Envelop */ public function addReturnPath(string $mail, ?string $name = null): Envelop { + $mail = $this->sanitizeHeaderValue($mail); + $name = ($name !== null) ? $this->sanitizeHeaderValue($name) : null; + $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; $this->headers[] = "Return-Path: $mail"; @@ -410,6 +439,9 @@ public function addReturnPath(string $mail, ?string $name = null): Envelop */ public function returnPath(string $mail, ?string $name = null): Envelop { + $mail = $this->sanitizeHeaderValue($mail); + $name = ($name !== null) ? $this->sanitizeHeaderValue($name) : null; + $mail = ($name !== null) ? (ucwords($name) . " <{$mail}>") : $mail; $this->headers[] = "Return-Path: $mail"; diff --git a/src/Middleware/CsrfMiddleware.php b/src/Middleware/CsrfMiddleware.php index 7d32f54d..16acde17 100644 --- a/src/Middleware/CsrfMiddleware.php +++ b/src/Middleware/CsrfMiddleware.php @@ -25,8 +25,14 @@ public function process(Request $request, callable $next, array $args = []): mix } } + $session = (string) $request->session()->get('_token'); + if ($request->isAjax()) { - if ($request->getHeader('x-csrf-token') === session('_token')) { + $provided = (string) $request->getHeader('x-csrf-token'); + + // Reject empties then constant-time compare, so an unset session + // token can no longer be matched by an absent/empty header. + if ($session !== '' && hash_equals($session, $provided)) { return $next($request); } @@ -37,7 +43,11 @@ public function process(Request $request, callable $next, array $args = []): mix ); } - if ($request->get('_token') == $request->session()->get('_token')) { + $provided = (string) $request->get('_token'); + + // Reject empties then constant-time compare, so an unset session token + // can no longer be matched by an absent/empty form token. + if ($session !== '' && hash_equals($session, $provided)) { return $next($request); } diff --git a/src/Security/Crypto.php b/src/Security/Crypto.php index 04ba6be5..3f9023d2 100644 --- a/src/Security/Crypto.php +++ b/src/Security/Crypto.php @@ -22,6 +22,15 @@ class Crypto */ private static string $cipher = 'AES-256-CBC'; + /** + * Whether decrypt() may fall back to the unauthenticated legacy format + * (static IV, no MAC) for values lacking the BOW2: header. Disabled by + * default so decrypt() fails closed; opt in only to read old ciphertexts. + * + * @var bool + */ + private static bool $allow_legacy = false; + /** * Header tagging the authenticated (random-IV + HMAC) payload format. * @@ -56,6 +65,17 @@ public static function setKey(string $key, ?string $cipher = null): void } } + /** + * Allow or forbid decrypt() from falling back to the unauthenticated legacy + * format. Off by default; enable only while migrating old ciphertexts. + * + * @param bool $allow + */ + public static function allowLegacy(bool $allow = true): void + { + static::$allow_legacy = $allow; + } + /** * Encrypt data. * @@ -107,6 +127,12 @@ public static function decrypt(string $data): string|bool $key = static::resolveKey(); if (!str_starts_with($data, self::HEADER)) { + // Fail closed on non-authenticated input unless the legacy format + // has been explicitly re-enabled for migration. + if (!static::$allow_legacy) { + return false; + } + return static::decryptLegacy($data, $key); } diff --git a/src/Session/Session.php b/src/Session/Session.php index 19348927..15b085cf 100644 --- a/src/Session/Session.php +++ b/src/Session/Session.php @@ -121,13 +121,12 @@ public function regenerate(): void $this->start(); // Rotate the underlying session ID and delete the previous record so a - // fixated/leaked ID can no longer be reused, then clear the values. + // fixated/leaked ID can no longer be reused. session_regenerate_id(true) + // deletes the old file while PRESERVING $_SESSION, so authenticated data + // survives the rotation (do NOT flush/destroy here). if (PHP_SESSION_ACTIVE === session_status()) { session_regenerate_id(true); } - - $this->flush(); - $this->start(); } /** diff --git a/src/Storage/Service/DiskFilesystemService.php b/src/Storage/Service/DiskFilesystemService.php index 361549a0..c61bb8f6 100644 --- a/src/Storage/Service/DiskFilesystemService.php +++ b/src/Storage/Service/DiskFilesystemService.php @@ -6,6 +6,7 @@ use Bow\Http\UploadedFile; use Bow\Storage\Contracts\FilesystemInterface; +use Bow\Storage\Exception\ResourceException; use RuntimeException; class DiskFilesystemService implements FilesystemInterface @@ -108,11 +109,38 @@ public function put(string $file, string $content): bool */ public function path(string $file): string { - if (preg_match('#^' . $this->base_directory . '#', $file)) { - return $file; + $base = rtrim($this->base_directory, DIRECTORY_SEPARATOR); + + // Join the file to the base directory unless it is already an absolute + // path located inside the base directory (plain prefix check, not regex). + if ($file === $base || str_starts_with($file, $base . DIRECTORY_SEPARATOR)) { + $path = $file; + } else { + $path = $base . DIRECTORY_SEPARATOR . ltrim($file, '/'); + } + + // Reject any parent-directory traversal segment before touching the disk. + if (in_array('..', explode('/', str_replace('\\', '/', $path)), true)) { + throw new ResourceException( + sprintf('The path "%s" is outside of the base directory.', $file) + ); + } + + // Resolve the target (or its parent, for files that do not exist yet) and + // make sure the result stays confined to the base directory, guarding + // against symlink escapes. + $resolved = realpath($path) ?: realpath(dirname($path)); + + if ($resolved !== false + && $resolved !== $base + && !str_starts_with($resolved . DIRECTORY_SEPARATOR, $base . DIRECTORY_SEPARATOR) + ) { + throw new ResourceException( + sprintf('The path "%s" is outside of the base directory.', $file) + ); } - return rtrim($this->base_directory, '/') . '/' . ltrim($file, '/'); + return $path; } /** diff --git a/tests/Database/Query/QueryBuilderTest.php b/tests/Database/Query/QueryBuilderTest.php index b5231406..8f6f8d6b 100644 --- a/tests/Database/Query/QueryBuilderTest.php +++ b/tests/Database/Query/QueryBuilderTest.php @@ -359,6 +359,37 @@ public function test_shared_lock_flag_resets_after_to_sql(string $name) $this->assertStringNotContainsString('lock in share mode', $sql); } + /** + * SQL-injection guard: a malicious column name must be rejected. + * + * Uses a local in-memory SQLite PDO so it needs no external connection. + */ + public function test_where_rejects_unsafe_column_identifier() + { + $builder = new QueryBuilder('users', new \PDO('sqlite::memory:')); + + $this->expectException(QueryBuilderException::class); + + $builder->where('1=1 UNION SELECT password FROM admins -- ', '=', 'x'); + } + + /** + * SQL-injection guard: whereBetween must bind both bounds as placeholders + * instead of concatenating them into the statement. + */ + public function test_where_between_binds_both_bounds() + { + $builder = new QueryBuilder('users', new \PDO('sqlite::memory:')); + $builder->whereBetween('price', ['0', '100 OR 1=1 -- ']); + + $this->assertStringContainsString('price between ? and ?', $builder->toSql()); + + $property = (new \ReflectionObject($builder))->getProperty('where_data_binding'); + $property->setAccessible(true); + + $this->assertSame(['0', '100 OR 1=1 -- '], $property->getValue($builder)); + } + /** * @return array */ diff --git a/tests/Filesystem/DiskFilesystemTest.php b/tests/Filesystem/DiskFilesystemTest.php index a973cc0c..da1291f0 100644 --- a/tests/Filesystem/DiskFilesystemTest.php +++ b/tests/Filesystem/DiskFilesystemTest.php @@ -3,6 +3,7 @@ namespace Bow\Tests\Filesystem; use Bow\Http\UploadedFile; +use Bow\Storage\Exception\ResourceException; use Bow\Storage\Service\DiskFilesystemService; use Bow\Storage\Storage; use Bow\Tests\Config\TestingConfiguration; @@ -82,6 +83,26 @@ public function test_get_path_by_passed_the_right_path() $this->assertEquals($this->storage->path($path), $path); } + public function test_path_rejects_traversal() + { + $this->expectException(ResourceException::class); + + $this->storage->path('../../x'); + } + + public function test_get_does_not_leak_outside_base_directory() + { + $secret = dirname($this->storage->getBaseDirectory()) . '/secret_regression.txt'; + file_put_contents($secret, 'TOP-SECRET'); + + try { + $this->expectException(ResourceException::class); + $this->storage->get('../secret_regression.txt'); + } finally { + @unlink($secret); + } + } + public function test_is_directory() { $this->storage->makeDirectory("is_directory"); diff --git a/tests/Hashing/SecurityTest.php b/tests/Hashing/SecurityTest.php index e544bf0d..06d75410 100644 --- a/tests/Hashing/SecurityTest.php +++ b/tests/Hashing/SecurityTest.php @@ -28,4 +28,35 @@ public function test_should_check_hash_value() $this->assertTrue(Hash::check('bow', $hashed)); } + + public function test_decrypt_fails_closed_on_non_authenticated_input() + { + $key = file_get_contents(__DIR__ . '/stubs/.key'); + Crypto::setkey($key, 'AES-256-CBC'); + Crypto::allowLegacy(false); + + // A legacy (static-IV, unauthenticated) ciphertext with no BOW2: header. + $cipher = 'AES-256-CBC'; + $iv = substr(sha1($key), 0, (int) openssl_cipher_iv_length($cipher)); + $legacy = openssl_encrypt('secret', $cipher, $key, 0, $iv); + + $this->assertFalse(Crypto::decrypt($legacy)); + $this->assertFalse(Crypto::decrypt('garbage')); + } + + public function test_decrypt_reads_legacy_only_when_opted_in() + { + $key = file_get_contents(__DIR__ . '/stubs/.key'); + Crypto::setkey($key, 'AES-256-CBC'); + + $cipher = 'AES-256-CBC'; + $iv = substr(sha1($key), 0, (int) openssl_cipher_iv_length($cipher)); + $legacy = openssl_encrypt('secret', $cipher, $key, 0, $iv); + + Crypto::allowLegacy(true); + $this->assertEquals('secret', Crypto::decrypt($legacy)); + + Crypto::allowLegacy(false); + $this->assertFalse(Crypto::decrypt($legacy)); + } } diff --git a/tests/Mail/EnvelopHeaderInjectionTest.php b/tests/Mail/EnvelopHeaderInjectionTest.php new file mode 100644 index 00000000..9211715f --- /dev/null +++ b/tests/Mail/EnvelopHeaderInjectionTest.php @@ -0,0 +1,62 @@ +subject("Hi\r\nBcc: victim@evil.com"); + + $subject = $envelop->getSubject(); + + $this->assertStringNotContainsString("\r", $subject); + $this->assertStringNotContainsString("\n", $subject); + $this->assertSame("HiBcc: victim@evil.com", $subject); + } + + public function test_with_header_strips_crlf_from_key_and_value() + { + $envelop = new Envelop(false); + $envelop->withHeader("X-Test\r\nBcc: x@evil", "v\r\nCc: y@evil"); + + $compiled = $envelop->compileHeaders(); + + $this->assertStringNotContainsString("\nBcc:", $compiled); + $this->assertStringNotContainsString("\nCc:", $compiled); + + foreach ($envelop->getHeaders() as $header) { + $this->assertStringNotContainsString("\r", $header); + $this->assertStringNotContainsString("\n", $header); + } + } + + public function test_from_strips_crlf() + { + $envelop = new Envelop(false); + $envelop->from("bob@example.com\r\nBcc: x@evil", "Bob\r\nName"); + + $from = $envelop->getFrom(); + + $this->assertStringNotContainsString("\r", $from); + $this->assertStringNotContainsString("\n", $from); + } + + public function test_copy_and_reply_headers_strip_crlf() + { + $envelop = new Envelop(false); + $envelop->addBcc("bcc@example.com\r\nSubject: hacked"); + $envelop->addCc("cc@example.com\r\nSubject: hacked"); + $envelop->addReplyTo("reply@example.com\r\nSubject: hacked"); + $envelop->addReturnPath("return@example.com\r\nSubject: hacked"); + + foreach ($envelop->getHeaders() as $header) { + $this->assertStringNotContainsString("\r", $header); + $this->assertStringNotContainsString("\n", $header); + } + } +} From a072199c1541e1c70c97fdb9ac63da2bde05465a Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Tue, 13 Oct 2026 09:05:05 +0000 Subject: [PATCH 17/23] Validator: stop crashing on native JSON input types A JSON body is decoded with native types, so a field declared `nullable|boolean` received a real false and the nullable rule passed it to the string-typed Str::isEmpty(), throwing a TypeError (HTTP 500) before the boolean rule ever ran. The same assumption broke nullable with ints, floats and arrays, max/min/size with numbers and booleans, and alpha, alphanum, lower, upper and email with any non-string. - NullableRule: a value is absent only when null, a blank string or an empty array; false, 0 and 0.0 are real values and reach the next rules. - StringRule: max, min and size compare native numbers by value and strings by length, following the convention documented by between. Numeric strings keep length semantics so form inputs are unchanged. Booleans and arrays fail the rule instead of throwing. - alpha, alphanum, lower, upper and email fail cleanly on non-strings. Adds a database-free regression test class covering each case and a full JSON payload. --- src/Validation/Rules/EmailRule.php | 2 +- src/Validation/Rules/NullableRule.php | 29 +++- src/Validation/Rules/StringRule.php | 44 ++++- tests/Validation/ValidatorTypedInputTest.php | 160 +++++++++++++++++++ 4 files changed, 226 insertions(+), 9 deletions(-) create mode 100644 tests/Validation/ValidatorTypedInputTest.php 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/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())); + } +} From 70a1026af42e02e04f355081a68ca2ff24cbcd11 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Tue, 13 Oct 2026 09:05:05 +0000 Subject: [PATCH 18/23] Database: empty whereIn() list and pgsql emulate_prepares option whereIn() with an empty array built `column in ()`, invalid SQL (SQLSTATE 42601) that `php bow migrate` hit on a project with no migrations yet. An empty list now compiles to `in (null)`, valid everywhere and matching no row. PostgreSQLAdapter honours a per-connection `emulate_prepares` config key (default false). 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 PDO quotes the values itself and nothing is cached on the server. Both were previously re-applied as vendor patches by an application; regression tests added for each. --- .../Connection/Adapters/PostgreSQLAdapter.php | 5 ++++ src/Database/QueryBuilder.php | 4 +++- tests/Database/ConnectionTest.php | 24 +++++++++++++++++++ tests/Database/Query/QueryBuilderTest.php | 24 +++++++++++++++++++ 4 files changed, 56 insertions(+), 1 deletion(-) 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/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. From 54c3216384faab1e465bcdfcd3f210ffd762220b Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Tue, 13 Oct 2026 09:06:28 +0000 Subject: [PATCH 19/23] Log and report exception traces as strings, never raw frames getTrace() returns frames with their arguments, and serializing those can run code: an argument object whose jsonSerialize() issues a query throws again when the transaction is already aborted, so the logger itself failed while reporting the original error. - LoggerConfiguration and QueueAdapter log the exception class, file:line and getTraceAsString() as context instead of the frame array. - BaseErrorHandler puts getTraceAsString() in the non-production JSON response instead of the frame array. --- src/Application/Exception/BaseErrorHandler.php | 2 +- src/Configuration/LoggerConfiguration.php | 9 ++++++++- src/Queue/Adapters/QueueAdapter.php | 6 +++++- 3 files changed, 14 insertions(+), 3 deletions(-) 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/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 } From eee339a878bf9f3303ea3f4275e391a74b707bbc Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Tue, 13 Oct 2026 09:19:06 +0000 Subject: [PATCH 20/23] CI: replace the removed MinIO images so docker compose starts again Every test job has failed at "docker compose up" since late September: MinIO removed minio/minio and minio/mc from Docker Hub (the registry now answers "object not found") and quay.io requires a login, so the pull of the minio-init container aborted the whole stack and PHPUnit never ran. - docker-compose: the minio service now uses bitnamilegacy/minio, which serves the same API on the same ports and creates the public "tests" bucket itself through MINIO_DEFAULT_BUCKETS. The minio-init service and its mc image are gone; the healthcheck polls /minio/health/ready. - tests workflow: the wait step polls the bucket over HTTP instead of waiting for the removed init container. Verified locally: the S3 test suite passes against the new service, and the other compose images still resolve on Docker Hub. --- .github/workflows/tests.yml | 13 ++++++++++--- docker-compose.yml | 27 +++++++++------------------ 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 7834613a..5660a2d3 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -54,10 +54,17 @@ jobs: sleep 2 done - - name: Wait for MinIO bucket initialization + - name: Wait for the MinIO test bucket run: | - echo "Waiting for MinIO bucket initialization..." - docker wait bowphp_minio_init || true + echo "Waiting for the public 'tests' bucket on MinIO..." + for i in {1..30}; do + if [ "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9000/tests/)" = "200" ]; then + echo "MinIO bucket is ready!" + break + fi + echo "Waiting for MinIO... ($i/30)" + sleep 2 + done - name: Cache Composer packages id: composer-cache diff --git a/docker-compose.yml b/docker-compose.yml index c7113c82..d992ccce 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -146,7 +146,12 @@ services: retries: 5 minio: container_name: bowphp_minio - image: minio/minio + # MinIO removed its images from Docker Hub (minio/minio and minio/mc + # now return "object not found") and quay.io requires a login, which + # broke `docker compose up` in CI. Bitnami's frozen legacy archive is + # the drop-in: same API and ports, and it creates the test bucket + # itself through MINIO_DEFAULT_BUCKETS, so no `mc` init container. + image: bitnamilegacy/minio:latest restart: unless-stopped ports: - "9000:9000" @@ -154,29 +159,15 @@ services: environment: MINIO_ROOT_USER: minioadmin MINIO_ROOT_PASSWORD: minioadmin - command: server /data --console-address ":9001" + # bucket:policy — a public "tests" bucket, as minio-init used to create. + MINIO_DEFAULT_BUCKETS: "tests:public" networks: - bowphp_network healthcheck: - test: ["CMD", "mc", "alias", "set", "local", "http://localhost:9000", "minioadmin", "minioadmin"] + test: ["CMD", "curl", "-sf", "http://localhost:9000/minio/health/ready"] interval: 10s timeout: 5s retries: 5 - minio-init: - container_name: bowphp_minio_init - image: minio/mc - depends_on: - minio: - condition: service_healthy - entrypoint: > - /bin/sh -c " - mc alias set local http://minio:9000 minioadmin minioadmin; - mc mb --ignore-existing local/tests; - mc anonymous set public local/tests; - exit 0; - " - networks: - - bowphp_network zookeeper: container_name: bowphp_zookeeper image: confluentinc/cp-zookeeper:7.5.0 From 9a79ac8b5e1f3ff3f89242c3e70cf4bdebba7404 Mon Sep 17 00:00:00 2001 From: papac Date: Tue, 13 Oct 2026 09:49:20 +0000 Subject: [PATCH 21/23] Update CHANGELOG --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bcae3d22..ac0e478a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 5.4.15 - 2026-10-13 + +### What's Changed + +* Validator JSON types, empty whereIn, pgsql emulate_prepares, string traces by @papac in https://github.com/bowphp/framework/pull/431 +* Update CHANGELOG by @papac in https://github.com/bowphp/framework/pull/432 +* CI: replace the removed MinIO images so docker compose starts again by @papac in https://github.com/bowphp/framework/pull/433 + +**Full Changelog**: https://github.com/bowphp/framework/compare/5.4.14...5.4.15 + ## 5.4.13 - 2026-09-28 ### What's Changed @@ -393,6 +403,7 @@ Database::transaction(fn() => $user->update(['name' => ''])); + ``` From 6b5e9668f0a932e7dbe0165a9c56e200d12942f2 Mon Sep 17 00:00:00 2001 From: Franck DAKIA Date: Sat, 17 Oct 2026 02:37:12 +0000 Subject: [PATCH 22/23] Container: fail clearly on an unbound interface or abstract class Capsule::resolve() returned the key itself when the class was not instantiable, so make() on an interface or abstract class with no binding handed back the type's *name* as a string. Callers expecting an instance broke far from the cause, most visibly as "Compass::getInjectParameter(): Return value must be of type ?object, string returned" when a controller constructor depended on an interface nobody had bound. resolve() now throws ContainerException::notInstantiable(), whose message names the type, says whether it is an interface or an abstract class, and shows the bind() call to add. Covers make(), makeWith() and dependencies resolved while building another class. --- src/Container/Capsule.php | 10 +++- .../Exception/ContainerException.php | 33 +++++++++++++ tests/Container/CapsuleTest.php | 48 +++++++++++++++++++ tests/Container/Stubs/AbstractRepository.php | 8 ++++ 4 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 src/Container/Exception/ContainerException.php create mode 100644 tests/Container/Stubs/AbstractRepository.php diff --git a/src/Container/Capsule.php b/src/Container/Capsule.php index 28634c42..9b65d4c2 100644 --- a/src/Container/Capsule.php +++ b/src/Container/Capsule.php @@ -5,6 +5,7 @@ namespace Bow\Container; use ArrayAccess; +use Bow\Container\Exception\ContainerException; use Closure; use InvalidArgumentException; use ReflectionClass; @@ -86,14 +87,19 @@ public function makeWith(string $key, array $parameters = []): mixed * * @param string $key * @return mixed - * @throws + * @throws ContainerException when $key is an interface or abstract class without a binding + * @throws \ReflectionException when $key is not a class at all */ private function resolve(string $key): mixed { $reflection = new ReflectionClass($key); + // An interface or abstract class with no binding cannot be built. + // Returning the key here handed a *string* to every caller expecting + // an instance, which surfaced far away as a TypeError in the + // controller injector. Fail here, naming the missing binding. if (!$reflection->isInstantiable()) { - return $key; + throw ContainerException::notInstantiable($key); } $constructor = $reflection->getConstructor(); diff --git a/src/Container/Exception/ContainerException.php b/src/Container/Exception/ContainerException.php new file mode 100644 index 00000000..38f80808 --- /dev/null +++ b/src/Container/Exception/ContainerException.php @@ -0,0 +1,33 @@ +bind(%s::class, Concrete::class).', + $key, + $kind, + $key + )); + } +} diff --git a/tests/Container/CapsuleTest.php b/tests/Container/CapsuleTest.php index 08fc65c2..661d1c69 100644 --- a/tests/Container/CapsuleTest.php +++ b/tests/Container/CapsuleTest.php @@ -3,6 +3,8 @@ namespace Bow\Tests\Container; use Bow\Container\Capsule; +use Bow\Container\Exception\ContainerException; +use Bow\Tests\Container\Stubs\AbstractRepository; use Bow\Tests\Container\Stubs\FileLogger; use Bow\Tests\Container\Stubs\LoggerInterface; use Bow\Tests\Container\Stubs\MyClass; @@ -217,6 +219,52 @@ public function test_array_access_offset_unset() $capsule->make('removable'); } + /** + * Regression: make() on an interface with no binding used to return the + * interface *name* (a string), which then blew up far away as + * "Compass::getInjectParameter(): Return value must be of type ?object, + * string returned" when a controller depended on that interface. + */ + public function test_make_unbound_interface_throws_a_clear_exception() + { + $capsule = new Capsule(); + + $this->expectException(ContainerException::class); + $this->expectExceptionMessage(PaymentGatewayInterface::class); + + $capsule->make(PaymentGatewayInterface::class); + } + + public function test_make_unbound_abstract_class_throws_a_clear_exception() + { + $capsule = new Capsule(); + + $this->expectException(ContainerException::class); + $this->expectExceptionMessage('abstract class'); + + $capsule->make(AbstractRepository::class); + } + + public function test_make_with_unbound_interface_throws_a_clear_exception() + { + $capsule = new Capsule(); + + $this->expectException(ContainerException::class); + + $capsule->makeWith(PaymentGatewayInterface::class, []); + } + + public function test_dependency_on_unbound_interface_throws_a_clear_exception() + { + // OrderService needs a PaymentGatewayInterface; nothing is bound. + $capsule = new Capsule(); + + $this->expectException(ContainerException::class); + $this->expectExceptionMessage(PaymentGatewayInterface::class); + + $capsule->make(OrderService::class); + } + public function test_make_with_parameters() { $capsule = new Capsule(); diff --git a/tests/Container/Stubs/AbstractRepository.php b/tests/Container/Stubs/AbstractRepository.php new file mode 100644 index 00000000..3a0f1ad1 --- /dev/null +++ b/tests/Container/Stubs/AbstractRepository.php @@ -0,0 +1,8 @@ + Date: Sat, 17 Oct 2026 02:41:33 +0000 Subject: [PATCH 23/23] Update CHANGELOG --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac0e478a..fa88c992 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 5.4.16 - 2026-10-17 + +### What's Changed + +* Update CHANGELOG by @papac in https://github.com/bowphp/framework/pull/434 +* Container: fail clearly on an unbound interface or abstract class by @papac in https://github.com/bowphp/framework/pull/435 + +**Full Changelog**: https://github.com/bowphp/framework/compare/5.4.15...5.4.16 + ## 5.4.15 - 2026-10-13 ### What's Changed @@ -404,6 +413,7 @@ Database::transaction(fn() => $user->update(['name' => ''])); + ```