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/CHANGELOG.md b/CHANGELOG.md index 8fcaba53..fa88c992 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,73 @@ 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 + +* 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 + +* 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 + +* 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 + +* 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 + +* 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 + +* 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 @@ -334,6 +401,13 @@ Database::transaction(fn() => $user->update(['name' => ''])); + + + + + + + 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 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 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/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/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/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/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/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..af9daf46 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'])) { @@ -88,6 +88,11 @@ protected function makePdo(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/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']); diff --git a/src/Database/QueryBuilder.php b/src/Database/QueryBuilder.php index 7b54926c..9ecb77a8 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 * @@ -341,6 +352,8 @@ public function where( ); } + $column = $this->assertSafeIdentifier($column, 'where'); + if ($value instanceof QueryBuilder) { $indicator = "(" . $value->toSql() . ")"; } else { @@ -404,6 +417,40 @@ 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 function assertSafeIdentifier(string $identifier, string $clause, bool $allowWildcard = false): string + { + $trimmed = trim($identifier); + + // 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." + ); + } + + return $trimmed; + } + /** * Formats the select request * @@ -464,6 +511,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; } } @@ -517,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 { @@ -536,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 { @@ -554,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; } @@ -577,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; } @@ -627,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 { @@ -655,11 +723,15 @@ 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; } + $column = $this->assertSafeIdentifier($column, 'whereIn'); + if (is_null($this->where)) { $this->where = $column . ' in (' . $in . ')'; } else { @@ -684,7 +756,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 = ''; @@ -698,6 +770,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; @@ -743,7 +818,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 = ''; @@ -757,6 +832,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 . ' '; @@ -779,7 +857,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 = ''; @@ -793,6 +871,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; @@ -877,7 +958,7 @@ public function group(string $column) public function groupBy(string $column): QueryBuilder { if (is_null($this->group)) { - $this->group = $column; + $this->group = $this->assertSafeIdentifier($column, 'groupBy'); } return $this; @@ -904,10 +985,21 @@ public function having( $comparator = '='; } + $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. + 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 +1018,8 @@ public function orderBy(string $column, string $type = 'asc'): QueryBuilder $type = 'asc'; } + $column = $this->assertSafeIdentifier($column, 'orderBy'); + if (is_null($this->order)) { $this->order = 'order by ' . $column . ' ' . strtolower($type); } else { @@ -955,6 +1049,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 @@ -977,6 +1072,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; } } @@ -1275,6 +1378,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); } } @@ -1317,8 +1422,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; @@ -1412,6 +1523,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)) { @@ -1436,6 +1548,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 { @@ -1550,6 +1664,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/Request.php b/src/Http/Request.php index 33bf2aad..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,34 +141,47 @@ 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 * * @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 +248,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. * @@ -221,13 +270,48 @@ 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(); } 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 +401,7 @@ private function scheme(): string */ public function hostname(): string { - return $_SERVER['HTTP_HOST']; + return $_SERVER['HTTP_HOST'] ?? ''; } /** @@ -327,9 +411,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 +423,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 +485,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 +513,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 +614,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 +656,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 +749,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 * 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/Queue/Adapters/BeanstalkdAdapter.php b/src/Queue/Adapters/BeanstalkdAdapter.php index 9ae58d0b..c80e0e59 100644 --- a/src/Queue/Adapters/BeanstalkdAdapter.php +++ b/src/Queue/Adapters/BeanstalkdAdapter.php @@ -7,7 +7,9 @@ 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; use Pheanstalk\Values\TubeName; use RuntimeException; @@ -25,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 * @@ -143,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); @@ -162,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 * @@ -180,12 +226,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 +241,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 +261,43 @@ 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; + } + } + /** * 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..6dc1a133 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 @@ -62,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 * @@ -97,7 +107,43 @@ abstract public function push(QueueTask $task): bool; */ public function serializeProducer(QueueTask $task): string { - return 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; } /** @@ -108,7 +154,65 @@ public function serializeProducer(QueueTask $task): string */ public function unserializeProducer(string $task): QueueTask { - return unserialize($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( + 'Queue payload failed integrity verification and was rejected.' + ); + } + + $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); } /** @@ -339,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 } @@ -355,6 +463,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 * @@ -387,15 +515,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()); } } 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/src/Security/Crypto.php b/src/Security/Crypto.php index 27a2dd25..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. * @@ -30,6 +39,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). */ @@ -50,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. * @@ -101,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); } @@ -136,6 +168,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/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/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/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/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/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 */ 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 @@ +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 b5231406..d242ee68 100644 --- a/tests/Database/Query/QueryBuilderTest.php +++ b/tests/Database/Query/QueryBuilderTest.php @@ -359,6 +359,61 @@ 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'); + } + + /** + * 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. + */ + 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/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/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); + } + } +} 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/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/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(); 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(); + } + } +} 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())); + } +}