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:
commit
341d1bdc2c
52 files changed
+7552
No files matched your search
@@ -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([]);
|
||||
}
|
||||
}
|
||||
@@ -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'));
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user