feat: initial commit of camelia/controllers

Framework-agnostic REST controller toolkit in vanilla PHP.

- Router with path parameters, 404 and 405 with an Allow header.
- Immutable Request, JsonRequest and Response; nothing is printed.
- CrudController over a ResourceGateway port the application implements.
- Composable Middleware/Pipeline chain.
- Security middlewares: BearerAuth, RequireRole, RateLimit, Cors.
- Transport middlewares: Logging, ContentNegotiation.
- Nine typed HTTP exceptions with snake_case JSON bodies.
- Declares PHP >=8.3 and no dependency on an ORM: ports are local.
- MIT license.
This commit is contained in:
dgarcia committed 2026-11-15 10:14:27 -03:00
commit 341d1bdc2c
52 files changed
+7552

No files matched your search

+181
View File
@@ -0,0 +1,181 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit;
use Camelia\Controllers\CrudController;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use Camelia\Controllers\Router;
use Camelia\Controllers\Tests\Fixture\ArrayGateway;
use PHPUnit\Framework\TestCase;
final class CrudControllerTest extends TestCase
{
private ArrayGateway $gateway;
protected function setUp(): void
{
$this->gateway = new ArrayGateway([
1 => ['id' => 1, 'nombre' => 'Taladro'],
2 => ['id' => 2, 'nombre' => 'Sierra'],
]);
}
private function controller(): CrudController
{
return new class($this->gateway) extends CrudController {
public function __construct(ArrayGateway $gateway)
{
parent::__construct($gateway, 'articulos');
}
};
}
public function testIndexReturnsPaginatedCollection(): void
{
$response = $this->controller()->render(new JsonRequest(path: '/articulos'));
self::assertSame(200, $response->status());
self::assertSame(2, $response->body()['total']);
self::assertSame(1, $response->body()['page']);
self::assertSame(20, $response->body()['per_page']);
self::assertSame(1, $response->body()['total_pages']);
self::assertFalse($response->body()['has_next']);
self::assertFalse($response->body()['has_prev']);
self::assertCount(2, $response->body()['items']);
}
public function testPerPageIsClampedToMaximum(): void
{
$response = $this->controller()->render(new JsonRequest(query: ['per_page' => '99999']));
self::assertSame(1000, $response->body()['per_page']);
}
public function testInvalidPageFallsBackToOne(): void
{
$response = $this->controller()->render(new JsonRequest(query: ['page' => 'abc']));
self::assertSame(1, $response->body()['page']);
}
public function testShowReturnsRecord(): void
{
$response = $this->controller()->render($this->withId('GET', '1'));
self::assertSame(200, $response->status());
self::assertSame('Taladro', $response->body()['nombre']);
}
public function testShowMissingRecordIs404(): void
{
$response = $this->controller()->render($this->withId('GET', '99'));
self::assertSame(404, $response->status());
self::assertSame('not_found', $response->body()['code']);
}
public function testStoreReturns201WithLocation(): void
{
$response = $this->controller()->render(new JsonRequest(
method: 'POST',
path: '/articulos',
body: ['nombre' => 'Lijadora'],
));
self::assertSame(201, $response->status());
self::assertSame('/articulos/3', $response->headers()['Location']);
self::assertSame('Lijadora', $response->body()['nombre']);
}
public function testUpdateReturnsRecord(): void
{
$response = $this->viaRouter('PUT', '/articulos/1', ['nombre' => 'Taladro Bosch']);
self::assertSame(200, $response->status());
self::assertSame('Taladro Bosch', $response->body()['nombre']);
}
public function testUpdateMissingIs404(): void
{
$response = $this->viaRouter('PATCH', '/articulos/99', ['nombre' => 'x']);
self::assertSame(404, $response->status());
}
public function testDestroyReturns204(): void
{
$response = $this->controller()->render($this->withId('DELETE', '1'));
self::assertSame(204, $response->status());
self::assertNull($response->body());
}
public function testDestroyMissingIs404(): void
{
$response = $this->controller()->render($this->withId('DELETE', '99'));
self::assertSame(404, $response->status());
}
public function testUpdateWithoutIdIs400(): void
{
$response = $this->controller()->render(new JsonRequest(method: 'PUT', path: '/articulos'));
self::assertSame(400, $response->status());
}
public function testRouterDrivesFullCrudFlow(): void
{
$router = new Router();
$controller = $this->controller();
$router->get('/articulos', $controller);
$router->post('/articulos', $controller);
$router->get('/articulos/{id}', $controller);
$router->delete('/articulos/{id}', $controller);
self::assertSame(
2,
$router->dispatch(new JsonRequest(path: '/articulos'))->body()['total'],
);
$created = $router->dispatch(new JsonRequest(method: 'POST', path: '/articulos', body: [
'nombre' => 'Martillo',
]));
self::assertSame(201, $created->status());
$deleted = $router->dispatch(new JsonRequest(method: 'DELETE', path: '/articulos/3'));
self::assertSame(204, $deleted->status());
self::assertSame(
2,
$router->dispatch(new JsonRequest(path: '/articulos'))->body()['total'],
);
}
private function withId(string $method, string $id): Request
{
return (new JsonRequest(method: $method, path: '/articulos/' . $id))->withAttribute(
'id',
$id,
);
}
/**
* Drives the request through a real router, so the `{id}` attribute is populated the same way
* production does it.
*
* @param array<string, mixed> $body
*/
private function viaRouter(string $method, string $path, array $body = []): Response
{
$router = new Router();
$controller = $this->controller();
$router->add($method, '/articulos/{id}', $controller);
return $router->dispatch(new JsonRequest(method: $method, path: $path, body: $body));
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit;
use Camelia\Controllers\JsonRequest;
use PHPUnit\Framework\TestCase;
final class JsonRequestTest extends TestCase
{
public function testReadsInjectedArraysOnly(): void
{
$request = new JsonRequest(
method: 'post',
path: '/articulos',
query: ['page' => '2'],
body: ['nombre' => 'Taladro'],
);
self::assertSame('POST', $request->method());
self::assertSame('/articulos', $request->path());
self::assertSame('2', $request->query('page'));
self::assertSame(['nombre' => 'Taladro'], $request->body());
}
public function testQueryFallsBackToDefault(): void
{
$request = new JsonRequest();
self::assertNull($request->query('missing'));
self::assertSame('x', $request->query('missing', 'x'));
}
public function testHeaderLookupIsCaseInsensitive(): void
{
$request = new JsonRequest(headers: ['accept' => 'application/json']);
self::assertSame('application/json', $request->header('Accept'));
self::assertSame('application/json', $request->header('ACCEPT'));
self::assertNull($request->header('X-Missing'));
}
public function testWithAttributeIsImmutable(): void
{
$original = new JsonRequest(path: '/articulos');
$withId = $original->withAttribute('id', '7');
self::assertNull($original->attribute('id'));
self::assertSame('7', $withId->attribute('id'));
}
public function testWithAttributeKeepsPreviousAttributes(): void
{
$request = (new JsonRequest())
->withAttribute('a', '1')
->withAttribute('b', '2');
self::assertSame('1', $request->attribute('a'));
self::assertSame('2', $request->attribute('b'));
}
}
@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit\Middleware;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Middleware\ContentNegotiation;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use PHPUnit\Framework\TestCase;
final class ContentNegotiationTest extends TestCase
{
private static function ok(Request $request): Response
{
return new Response(['ok' => true]);
}
public function testAddsContentType(): void
{
$response = (new ContentNegotiation())->process(new JsonRequest(), self::ok(...));
self::assertSame(200, $response->status());
self::assertSame('application/json; charset=utf-8', $response->headers()['Content-Type']);
}
public function testMissingAcceptHeaderIsAccepted(): void
{
$response = (new ContentNegotiation())->process(new JsonRequest(), self::ok(...));
self::assertSame(200, $response->status());
}
public function testJsonAcceptIsAccepted(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => 'application/json']),
self::ok(...),
);
self::assertSame(200, $response->status());
}
public function testBrowserAcceptIsAccepted(): void
{
$accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => $accept]),
self::ok(...),
);
self::assertSame(200, $response->status());
}
public function testIncompatibleAcceptIs406(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => 'application/xml']),
static function (): Response {
self::fail('The handler must not run when the client rejects JSON.');
},
);
self::assertSame(406, $response->status());
self::assertSame('not_acceptable', $response->body()['code']);
}
public function testZeroQualityIsRejected(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => 'application/json;q=0']),
static function (): Response {
self::fail('A q=0 entry means not acceptable.');
},
);
self::assertSame(406, $response->status());
}
public function testNonZeroQualityIsAccepted(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(headers: ['accept' => 'application/json;q=0.5']),
self::ok(...),
);
self::assertSame(200, $response->status());
}
public function testExistingContentTypeIsPreserved(): void
{
$response = (new ContentNegotiation())->process(
new JsonRequest(),
static fn(): Response => new Response(['ok' => true], 200, [
'Content-Type' => 'application/problem+json',
]),
);
self::assertSame('application/problem+json', $response->headers()['Content-Type']);
}
public function testContentTypeCanBeDisabled(): void
{
$response = (new ContentNegotiation(addContentType: false))->process(
new JsonRequest(),
self::ok(...),
);
self::assertFalse($response->hasHeader('Content-Type'));
}
}
+116
View File
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit\Middleware;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Middleware\Logging;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use PHPUnit\Framework\TestCase;
final class LoggingTest extends TestCase
{
/** @var list<array{level: string, message: string, context: array<string, mixed>}> */
private array $logs = [];
private float $now = 100.0;
private function logging(): Logging
{
return new Logging(
function (string $level, string $message, array $context): void {
$this->logs[] = ['level' => $level, 'message' => $message, 'context' => $context];
},
fn(): float => $this->now,
);
}
private static function ok(Request $request): Response
{
return new Response(['ok' => true]);
}
public function testRecordsSuccessfulRequest(): void
{
$response = $this->logging()->process(
new JsonRequest(method: 'GET', path: '/articulos'),
self::ok(...),
);
self::assertSame(200, $response->status());
self::assertCount(1, $this->logs);
self::assertSame('info', $this->logs[0]['level']);
self::assertSame('GET /articulos 200', $this->logs[0]['message']);
self::assertSame('/articulos', $this->logs[0]['context']['path']);
self::assertSame(200, $this->logs[0]['context']['status']);
}
public function testClientErrorLogsWarning(): void
{
$this->logging()->process(
new JsonRequest(path: '/x'),
static fn(): Response => new Response(['e' => 1], 404),
);
self::assertSame('warning', $this->logs[0]['level']);
}
public function testServerErrorLogsError(): void
{
$this->logging()->process(
new JsonRequest(path: '/x'),
static fn(): Response => new Response(null, 500),
);
self::assertSame('error', $this->logs[0]['level']);
}
public function testDurationIsMeasured(): void
{
$reads = [100.0, 120.5, 120.5, 163.0];
$logging = new Logging(function (string $level, string $message, array $context): void {
$this->logs[] = ['level' => $level, 'message' => $message, 'context' => $context];
}, static function () use (&$reads): float {
return (float) array_shift($reads);
});
$logging->process(new JsonRequest(), static fn(): Response => new Response(null));
self::assertSame(20.5, $this->logs[0]['context']['duration_ms']);
$logging->process(new JsonRequest(), static fn(): Response => new Response(null));
self::assertSame(42.5, $this->logs[1]['context']['duration_ms']);
}
public function testThrowableIsLoggedAndRethrown(): void
{
$logging = $this->logging();
try {
$logging->process(new JsonRequest(path: '/boom'), static function (): Response {
throw new \RuntimeException('exploded');
});
self::fail('The exception must propagate: the router owns error mapping.');
} catch (\RuntimeException $exception) {
self::assertSame('exploded', $exception->getMessage());
}
self::assertCount(1, $this->logs);
self::assertSame(500, $this->logs[0]['context']['status']);
self::assertSame('error', $this->logs[0]['level']);
}
public function testReturnsHandlerResponseUnchanged(): void
{
$original = new Response(['x' => 1], 201, ['Location' => '/a/1']);
$response = $this->logging()->process(
new JsonRequest(),
static fn(): Response => $original,
);
self::assertSame($original, $response);
}
}
+99
View File
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Middleware;
use Camelia\Controllers\Pipeline;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use PHPUnit\Framework\TestCase;
final class PipelineTest extends TestCase
{
public function testRunsHandlerWhenEmpty(): void
{
$pipeline = new Pipeline();
$response = $pipeline->process(
new JsonRequest(),
static fn(): Response => new Response(['ok' => true]),
);
self::assertSame(['ok' => true], $response->body());
self::assertTrue($pipeline->isEmpty());
}
public function testRunsMiddlewaresOutsideIn(): void
{
$order = [];
$first = new Recorder('first', $order);
$second = new Recorder('second', $order);
$pipeline = new Pipeline([$first, $second]);
$pipeline->process(new JsonRequest(), static function (Request $request) use (
&$order,
): Response {
$order[] = 'handler';
return new Response(null);
});
self::assertSame(
['first:before', 'second:before', 'handler', 'second:after', 'first:after'],
$order,
);
}
public function testMiddlewareCanShortCircuit(): void
{
$blocked = new class implements Middleware {
public function process(Request $request, callable $next): Response
{
return new Response(['blocked' => true], 403);
}
};
$pipeline = new Pipeline([$blocked]);
$response = $pipeline->process(new JsonRequest(), static function (): Response {
self::fail('The handler must not run when a middleware short-circuits.');
});
self::assertSame(403, $response->status());
}
public function testWithReturnsCopy(): void
{
$order = [];
$base = new Pipeline();
$withOne = $base->with(new Recorder('x', $order));
self::assertTrue($base->isEmpty());
self::assertCount(1, $withOne->middlewares());
}
}
final class Recorder implements Middleware
{
/**
* The array is shared by reference with the test, so appending to it is the only operation.
*
* @param list<string> $order Passed by reference so the test observes the shared log.
*/
public function __construct(
private readonly string $name,
/** @phpstan-ignore property.onlyWritten */
private array &$order,
) {}
public function process(Request $request, callable $next): Response
{
$this->order[] = $this->name . ':before';
$response = $next($request);
$this->order[] = $this->name . ':after';
return $response;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit;
use Camelia\Controllers\Exception\BadRequest;
use Camelia\Controllers\Exception\NotFound;
use Camelia\Controllers\Exception\ServerError;
use Camelia\Controllers\Exception\ValidationFailed;
use Camelia\Controllers\Response;
use PHPUnit\Framework\TestCase;
final class ResponseTest extends TestCase
{
public function testBodyAndStatus(): void
{
$response = new Response(['ok' => true], 201);
self::assertSame(['ok' => true], $response->body());
self::assertSame(201, $response->status());
self::assertTrue($response->isSuccessful());
}
public function testNoContentHasNoBody(): void
{
$response = Response::noContent();
self::assertSame(204, $response->status());
self::assertNull($response->body());
self::assertSame('', $response->toJson());
}
public function testToJsonKeepsUnicodeAndSlashes(): void
{
$response = new Response(['nombre' => 'Taladro Ñ', 'url' => '/a/b']);
self::assertSame('{"nombre":"Taladro Ñ","url":"/a/b"}', $response->toJson());
}
public function testWithHeaderReturnsCopy(): void
{
$original = new Response(['ok' => true]);
$modified = $original->withHeader('X-Trace', 'abc');
self::assertFalse($original->hasHeader('X-Trace'));
self::assertTrue($modified->hasHeader('X-Trace'));
self::assertSame('abc', $modified->headers()['X-Trace']);
}
public function testHttpErrorsExposeStatusAndCode(): void
{
$notFound = new NotFound('missing');
self::assertSame(404, $notFound->status());
self::assertSame('not_found', $notFound->errorCode());
$badRequest = new BadRequest();
self::assertSame(400, $badRequest->status());
$serverError = ServerError::fromThrowable(new \RuntimeException('secret detail'));
self::assertSame(500, $serverError->status());
self::assertSame('An unexpected error occurred.', $serverError->getMessage());
self::assertStringNotContainsString(
'secret',
(string) json_encode($serverError->toArray()),
);
}
public function testValidationFailedCarriesFieldErrors(): void
{
$error = new ValidationFailed(['nombre' => ['Required.']]);
$payload = $error->toArray();
self::assertSame(422, $error->status());
self::assertSame(['nombre' => ['Required.']], $payload['errors']);
self::assertSame('validation_failed', $payload['code']);
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit;
use Camelia\Controllers\Controller;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use Camelia\Controllers\Route;
use PHPUnit\Framework\TestCase;
final class RouteTest extends TestCase
{
public function testMatchesStaticPath(): void
{
$route = new Route('GET', '/articulos', new NoopController());
self::assertSame([], $route->matches('/articulos'));
self::assertNull($route->matches('/clientes'));
self::assertNull($route->matches('/articulos/7'));
}
public function testCapturesParameters(): void
{
$route = new Route('GET', '/articulos/{id}', new NoopController());
self::assertSame(['id' => '7'], $route->matches('/articulos/7'));
self::assertSame(['id' => 'abc'], $route->matches('/articulos/abc'));
self::assertNull($route->matches('/articulos'));
self::assertNull($route->matches('/articulos/7/detalle'));
}
public function testCapturesMultipleParameters(): void
{
$route = new Route(
'GET',
'/facturas/{facturaId}/detalles/{detalleId}',
new NoopController(),
);
self::assertSame(
['facturaId' => '3', 'detalleId' => '9'],
$route->matches('/facturas/3/detalles/9'),
);
}
public function testLiteralDotsAreEscaped(): void
{
$route = new Route('GET', '/archivos/reporte.json', new NoopController());
self::assertSame([], $route->matches('/archivos/reporte.json'));
self::assertNull($route->matches('/archivos/reporteXjson'));
}
public function testParameterNamesAreExposed(): void
{
$route = new Route('POST', '/a/{uno}/b/{dos}', new NoopController());
self::assertSame(['uno', 'dos'], $route->parameters());
self::assertSame('POST', $route->method());
}
}
final class NoopController extends Controller
{
public function render(Request $request): Response
{
return Response::noContent();
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit;
use Camelia\Controllers\Controller;
use Camelia\Controllers\Exception\NotFound;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use Camelia\Controllers\Router;
use PHPUnit\Framework\TestCase;
final class RouterTest extends TestCase
{
public function testDispatchesToController(): void
{
$router = new Router();
$router->get('/articulos/{id}', new FixedController(['id' => 'seen'], 200));
$response = $router->dispatch(new JsonRequest(path: '/articulos/7'));
self::assertSame(200, $response->status());
self::assertSame(['id' => 'seen'], $response->body());
}
public function testHandlerReceivesRouteAttribute(): void
{
$router = new Router();
$router->get(
'/articulos/{id}',
static fn(Request $r): Response => new Response([
'id' => $r->attribute('id'),
]),
);
$response = $router->dispatch(new JsonRequest(path: '/articulos/42'));
self::assertSame(['id' => '42'], $response->body());
}
public function testUnknownPathIs404(): void
{
$router = new Router();
$router->get('/articulos', new FixedController([], 200));
$response = $router->dispatch(new JsonRequest(path: '/clientes'));
self::assertSame(404, $response->status());
self::assertSame('not_found', $response->body()['code']);
}
public function testWrongMethodIs405WithAllowHeader(): void
{
$router = new Router();
$router->get('/articulos', new FixedController([], 200));
$router->post('/articulos', new FixedController([], 201));
$response = $router->dispatch(new JsonRequest(method: 'DELETE', path: '/articulos'));
self::assertSame(405, $response->status());
self::assertSame('method_not_allowed', $response->body()['code']);
self::assertSame('GET, POST, HEAD', $response->headers()['Allow']);
}
public function testHttpErrorThrownByHandlerBecomesResponse(): void
{
$router = new Router();
$router->get('/x', static function (): Response {
throw NotFound::route('/x');
});
$response = $router->dispatch(new JsonRequest(path: '/x'));
self::assertSame(404, $response->status());
}
public function testUnexpectedThrowableBecomes500WithoutLeakingDetail(): void
{
$router = new Router();
$router->get('/x', static function (): Response {
throw new \RuntimeException('internal detail');
});
$response = $router->dispatch(new JsonRequest(path: '/x'));
self::assertSame(500, $response->status());
self::assertSame('server_error', $response->body()['code']);
self::assertStringNotContainsString('internal detail', $response->toJson());
}
public function testVerbsAreChainable(): void
{
$router = new Router();
$controller = new FixedController([], 200);
self::assertSame($router, $router->get('/a', $controller)->post('/a', $controller));
self::assertCount(2, $router->routes());
}
}
final class FixedController extends Controller
{
public function __construct(
private readonly mixed $payload,
private readonly int $status,
) {}
public function render(Request $request): Response
{
return new Response($this->payload, $this->status);
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit\Security;
use Camelia\Controllers\Exception\BadRequest;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use Camelia\Controllers\Router;
use Camelia\Controllers\Security\BearerAuth;
use PHPUnit\Framework\TestCase;
final class BearerAuthTest extends TestCase
{
private static function passThrough(Request $request): Response
{
return new Response(['ok' => true]);
}
public function testMissingHeaderIs401(): void
{
$auth = new BearerAuth(static fn(string $token): array => ['id' => 1]);
$response = $auth->process(new JsonRequest(), self::passThrough(...));
self::assertSame(401, $response->status());
self::assertSame('unauthorized', $response->body()['code']);
self::assertSame('Bearer', $response->headers()['WWW-Authenticate']);
}
public function testNonBearerSchemeIs401(): void
{
$auth = new BearerAuth(static fn(string $token): array => ['id' => 1]);
$response = $auth->process(
new JsonRequest(headers: ['authorization' => 'Basic dXNlcjpwYXNz']),
self::passThrough(...),
);
self::assertSame(401, $response->status());
self::assertStringContainsString('Bearer scheme', $response->body()['message']);
}
public function testInvalidTokenIs401(): void
{
$auth = new BearerAuth(static fn(string $token): ?array => null);
$response = $auth->process(
new JsonRequest(headers: ['authorization' => 'Bearer expired']),
self::passThrough(...),
);
self::assertSame(401, $response->status());
self::assertStringContainsString('invalid or expired', $response->body()['message']);
}
public function testValidTokenAttachesIdentity(): void
{
$auth = new BearerAuth(static fn(string $token): array => [
'id' => 7,
'roles' => ['admin'],
]);
$response = $auth->process(
new JsonRequest(headers: ['authorization' => 'Bearer good-token']),
static function (Request $request): Response {
return new Response($request->attribute(BearerAuth::ATTRIBUTE));
},
);
self::assertSame(200, $response->status());
self::assertSame(['id' => 7, 'roles' => ['admin']], $response->body());
}
public function testSchemeIsCaseInsensitive(): void
{
$auth = new BearerAuth(static fn(string $token): array => ['id' => 1]);
$response = $auth->process(
new JsonRequest(headers: ['authorization' => 'bearer abc']),
self::passThrough(...),
);
self::assertSame(200, $response->status());
}
public function testRouterRejectsBeforeReachingController(): void
{
$router = (new Router())->withMiddleware(
new BearerAuth(static fn(string $token): ?array => null),
);
$router->get('/x', static fn(): Response => new Response(['leaked' => true]));
$response = $router->dispatch(new JsonRequest(path: '/x'));
self::assertSame(401, $response->status());
self::assertStringNotContainsString('leaked', $response->toJson());
}
public function testRouterAllowsValidToken(): void
{
$router = (new Router())->withMiddleware(new BearerAuth(static fn(string $token): array => [
'id' => 1,
]));
$router->get(
'/x',
static fn(Request $request): Response => new Response($request->attribute(
BearerAuth::ATTRIBUTE,
)),
);
$response = $router->dispatch(new JsonRequest(path: '/x', headers: [
'authorization' => 'Bearer t',
]));
self::assertSame(200, $response->status());
self::assertSame(['id' => 1], $response->body());
}
public function testEmptyRoleListIsRejectedAtConstruction(): void
{
$this->expectException(BadRequest::class);
new \Camelia\Controllers\Security\RequireRole([]);
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit\Security;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use Camelia\Controllers\Security\Cors;
use PHPUnit\Framework\TestCase;
final class CorsTest extends TestCase
{
private static function passThrough(Request $request): Response
{
return new Response(['ok' => true]);
}
public function testPreflightIsAnsweredWithoutHandler(): void
{
$cors = new Cors();
$response = $cors->process(
new JsonRequest(method: 'OPTIONS', headers: ['origin' => 'https://app.test']),
static function (): Response {
self::fail('A preflight must not reach the handler.');
},
);
self::assertSame(204, $response->status());
self::assertSame('*', $response->headers()['Access-Control-Allow-Origin']);
self::assertStringContainsString(
'PATCH',
$response->headers()['Access-Control-Allow-Methods'],
);
}
public function testWildcardOriginIsAddedToResponse(): void
{
$response = (new Cors())->process(
new JsonRequest(headers: ['origin' => 'https://app.test']),
self::passThrough(...),
);
self::assertSame(200, $response->status());
self::assertSame('*', $response->headers()['Access-Control-Allow-Origin']);
self::assertSame('Origin', $response->headers()['Vary']);
}
public function testDisallowedOriginGetsNoAllowOrigin(): void
{
$cors = new Cors(allowedOrigins: ['https://app.test']);
$response = $cors->process(
new JsonRequest(headers: ['origin' => 'https://evil.test']),
self::passThrough(...),
);
self::assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
}
public function testAllowedOriginIsEchoed(): void
{
$cors = new Cors(allowedOrigins: ['https://app.test']);
$response = $cors->process(
new JsonRequest(headers: ['origin' => 'https://app.test']),
self::passThrough(...),
);
self::assertSame('https://app.test', $response->headers()['Access-Control-Allow-Origin']);
}
public function testCredentialsWithWildcardEchoesOriginInstead(): void
{
$cors = new Cors(allowedOrigins: ['*'], allowCredentials: true);
$response = $cors->process(
new JsonRequest(headers: ['origin' => 'https://app.test']),
self::passThrough(...),
);
// `*` plus credentials is rejected by browsers, so the exact origin must be echoed.
self::assertSame('https://app.test', $response->headers()['Access-Control-Allow-Origin']);
self::assertSame('true', $response->headers()['Access-Control-Allow-Credentials']);
}
public function testCredentialsWithoutOriginSendsNoAllowOrigin(): void
{
$cors = new Cors(allowedOrigins: ['*'], allowCredentials: true);
$response = $cors->process(new JsonRequest(), self::passThrough(...));
self::assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
}
}
+113
View File
@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit\Security;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use Camelia\Controllers\Security\RateLimit;
use PHPUnit\Framework\TestCase;
final class RateLimitTest extends TestCase
{
private int $now = 1000;
private static function passThrough(Request $request): Response
{
return new Response(['ok' => true], 200, ['X-Custom' => 'kept']);
}
private function limiter(int $limit = 3, int $window = 60): RateLimit
{
return new RateLimit(limit: $limit, windowSeconds: $window, clock: fn(): int => $this->now);
}
public function testAllowsUpToLimit(): void
{
$limiter = $this->limiter(3);
for ($i = 1; $i <= 3; ++$i) {
self::assertSame(
200,
$limiter->process(new JsonRequest(), self::passThrough(...))->status(),
);
}
}
public function testExceedingLimitIs429(): void
{
$limiter = $this->limiter(2);
$limiter->process(new JsonRequest(), self::passThrough(...));
$limiter->process(new JsonRequest(), self::passThrough(...));
$response = $limiter->process(new JsonRequest(), self::passThrough(...));
self::assertSame(429, $response->status());
self::assertSame('too_many_requests', $response->body()['code']);
self::assertSame('60', $response->headers()['Retry-After']);
}
public function testHeadersPresentOnSuccess(): void
{
$response = $this->limiter(10)->process(new JsonRequest(), self::passThrough(...));
self::assertSame('10', $response->headers()['X-RateLimit-Limit']);
self::assertSame('9', $response->headers()['X-RateLimit-Remaining']);
self::assertSame('1060', $response->headers()['X-RateLimit-Reset']);
}
public function testKeepsHandlerHeaders(): void
{
$response = $this->limiter(10)->process(new JsonRequest(), self::passThrough(...));
self::assertSame('kept', $response->headers()['X-Custom']);
}
public function testWindowResetsAfterExpiry(): void
{
$limiter = $this->limiter(1);
self::assertSame(
200,
$limiter->process(new JsonRequest(), self::passThrough(...))->status(),
);
self::assertSame(
429,
$limiter->process(new JsonRequest(), self::passThrough(...))->status(),
);
$this->now += 61;
self::assertSame(
200,
$limiter->process(new JsonRequest(), self::passThrough(...))->status(),
);
}
public function testBucketsAreSeparatedByClientAddress(): void
{
$limiter = $this->limiter(1);
$first = (new JsonRequest())->withAttribute('client_ip', '10.0.0.1');
$second = (new JsonRequest())->withAttribute('client_ip', '10.0.0.2');
self::assertSame(200, $limiter->process($first, self::passThrough(...))->status());
self::assertSame(200, $limiter->process($second, self::passThrough(...))->status());
self::assertSame(429, $limiter->process($first, self::passThrough(...))->status());
}
public function testResetInReportsRemainingWindow(): void
{
$limiter = $this->limiter(1);
$request = new JsonRequest();
self::assertSame(0, $limiter->resetIn($request));
$limiter->process($request, self::passThrough(...));
self::assertSame(60, $limiter->resetIn($request));
$this->now += 20;
self::assertSame(40, $limiter->resetIn($request));
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Tests\Unit\Security;
use Camelia\Controllers\JsonRequest;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
use Camelia\Controllers\Security\RequireRole;
use PHPUnit\Framework\TestCase;
final class RequireRoleTest extends TestCase
{
private static function passThrough(Request $request): Response
{
return new Response(['ok' => true]);
}
private static function withUser(mixed $user): Request
{
return (new JsonRequest())->withAttribute('user', $user);
}
public function testNoIdentityIs401(): void
{
$response = (new RequireRole(['admin']))->process(
new JsonRequest(),
self::passThrough(...),
);
self::assertSame(401, $response->status());
self::assertStringContainsString(
'Authentication is required',
$response->body()['message'],
);
}
public function testMissingRoleIs401(): void
{
$middleware = new RequireRole(['admin']);
$response = $middleware->process(
self::withUser(['id' => 1, 'roles' => ['vendedor']]),
self::passThrough(...),
);
self::assertSame(401, $response->status());
self::assertStringContainsString('admin', $response->body()['message']);
}
public function testGrantedRolePasses(): void
{
$middleware = new RequireRole(['admin', 'gerente']);
$response = $middleware->process(
self::withUser(['id' => 1, 'roles' => ['gerente']]),
self::passThrough(...),
);
self::assertSame(200, $response->status());
}
public function testSingleRoleStringIsAccepted(): void
{
$middleware = new RequireRole(['admin']);
$response = $middleware->process(
self::withUser(['role' => 'admin']),
self::passThrough(...),
);
self::assertSame(200, $response->status());
}
public function testMalformedRolesFailClosed(): void
{
$middleware = new RequireRole(['admin']);
$response = $middleware->process(
self::withUser(['roles' => 'admin']),
self::passThrough(...),
);
// A string is a valid single role; the point is that no exception escapes.
self::assertSame(200, $response->status());
$broken = $middleware->process(
self::withUser(['roles' => [42, null]]),
self::passThrough(...),
);
self::assertSame(401, $broken->status());
}
public function testIdentityMustBeArray(): void
{
$middleware = new RequireRole(['admin']);
$response = $middleware->process(self::withUser('admin'), self::passThrough(...));
self::assertSame(401, $response->status());
}
}