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

+68
View File
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Security;
use Camelia\Controllers\Exception\Unauthorized;
use Camelia\Controllers\Middleware;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
/**
* Authenticates a `Authorization: Bearer <token>` header.
*
* The library owns the HTTP contract only: extracting the header, rejecting a missing or malformed
* token with 401, and attaching the authenticated identity to the request. How a token is verified
* (JWT, database row, static secret) is a `callable` the application supplies, so no cryptography
* or session store is baked in here.
*
* ```php
* new BearerAuth(fn (string $token): ?array => $jwt->verify($token));
* ```
*/
final readonly class BearerAuth implements Middleware
{
/** Request attribute carrying the resolved identity. */
public const ATTRIBUTE = 'user';
/** @var callable(string): (array<string, mixed>|null) */
private mixed $resolver;
/**
* @param callable(string): (array<string, mixed>|null) $resolver Returns the identity, or null
* when the token is invalid or expired.
*/
public function __construct(callable $resolver)
{
$this->resolver = $resolver;
}
public function process(Request $request, callable $next): Response
{
$header = $request->header('Authorization');
if ($header === null || $header === '') {
return $this->reject('An Authorization header is required.');
}
if (preg_match('/^Bearer\s+(\S+)$/i', $header, $matches) !== 1) {
return $this->reject('The Authorization header must use the Bearer scheme.');
}
$identity = ($this->resolver)((string) $matches[1]);
if (!is_array($identity)) {
return $this->reject('The provided token is invalid or expired.');
}
return $next($request->withAttribute(self::ATTRIBUTE, $identity));
}
private function reject(string $message): Response
{
$error = new Unauthorized($message);
return new Response($error->toArray(), $error->status(), $error->headers());
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Security;
use Camelia\Controllers\Middleware;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
/**
* Adds CORS headers and answers `OPTIONS` preflight requests.
*
* A wildcard origin (`*`) is never combined with credentials: browsers reject that pair, so the
* constructor downgrades credentials to `false` when the origin is `*`, instead of emitting an
* invalid header.
*/
final readonly class Cors implements Middleware
{
/**
* @param list<string> $allowedOrigins Exact origins, or `['*']`.
* @param list<string> $allowedMethods
* @param list<string> $allowedHeaders
*/
public function __construct(
private array $allowedOrigins = ['*'],
private array $allowedMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
private array $allowedHeaders = ['Content-Type', 'Authorization'],
private bool $allowCredentials = false,
private int $maxAge = 86400,
) {}
public function process(Request $request, callable $next): Response
{
$origin = $request->header('Origin');
$headers = $this->headersFor($origin);
// A preflight never reaches the handler: there is nothing to authorize yet.
if ($request->method() === 'OPTIONS') {
return new Response(null, 204, $headers);
}
$response = $next($request);
foreach ($headers as $name => $value) {
$response = $response->withHeader($name, $value);
}
return $response;
}
/** @return array<string, string> */
private function headersFor(?string $origin): array
{
$allowAll = in_array('*', $this->allowedOrigins, true);
$isAllowed =
$allowAll || $origin !== null && in_array($origin, $this->allowedOrigins, true);
$headers = [
'Access-Control-Allow-Methods' => implode(', ', $this->allowedMethods),
'Access-Control-Allow-Headers' => implode(', ', $this->allowedHeaders),
'Access-Control-Max-Age' => (string) $this->maxAge,
'Vary' => 'Origin',
];
// Echo the exact origin when credentials are on: `*` is illegal with them.
if ($this->allowCredentials) {
if (!$isAllowed || $origin === null) {
return $headers;
}
return $headers
+ [
'Access-Control-Allow-Origin' => $origin,
'Access-Control-Allow-Credentials' => 'true',
];
}
if ($isAllowed) {
$headers['Access-Control-Allow-Origin'] = $allowAll ? '*' : (string) $origin;
}
return $headers;
}
}
+115
View File
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Security;
use Camelia\Controllers\Exception\BadRequest;
use Camelia\Controllers\Middleware;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
/**
* Fixed-window rate limiter.
*
* In-process only: the counter lives in a PHP array, so it resets with the process and does not
* coordinate across workers. That is deliberate — the library has no dependency on Redis or APCu.
*
* shortcut: the counter is per process, so behind N workers the effective limit is N times the
* configured one. Upgrade to a shared store (Redis/APCu) when the API runs on more than one worker.
*/
final class RateLimit implements Middleware
{
/** @var array<string, array{count: int, resetAt: int}> */
private array $buckets = [];
public function __construct(
private readonly int $limit = 60,
private readonly int $windowSeconds = 60,
private readonly ?\Closure $clock = null,
private readonly ?\Closure $keyResolver = null,
) {
if ($this->limit < 1) {
throw new BadRequest('The rate limit must be at least 1.');
}
if ($this->windowSeconds < 1) {
throw new BadRequest('The rate-limit window must be at least 1 second.');
}
}
public function process(Request $request, callable $next): Response
{
$key = $this->keyFor($request);
$now = $this->now();
$bucket = $this->buckets[$key] ?? null;
if ($bucket === null || $now >= $bucket['resetAt']) {
$bucket = ['count' => 0, 'resetAt' => $now + $this->windowSeconds];
}
$bucket['count']++;
$this->buckets[$key] = $bucket;
$remaining = max(0, $this->limit - $bucket['count']);
$headers = [
'X-RateLimit-Limit' => (string) $this->limit,
'X-RateLimit-Remaining' => (string) $remaining,
'X-RateLimit-Reset' => (string) $bucket['resetAt'],
];
if ($bucket['count'] > $this->limit) {
$retryAfter = max(1, $bucket['resetAt'] - $now);
return new Response(
[
'code' => 'too_many_requests',
'message' => sprintf('Too many requests. Retry in %d seconds.', $retryAfter),
],
429,
$headers + ['Retry-After' => (string) $retryAfter],
);
}
$response = $next($request);
foreach ($headers as $name => $value) {
$response = $response->withHeader($name, $value);
}
return $response;
}
/** Seconds until the current window resets for this key; 0 when there is no active window. */
public function resetIn(Request $request): int
{
$bucket = $this->buckets[$this->keyFor($request)] ?? null;
if ($bucket === null) {
return 0;
}
return max(0, $bucket['resetAt'] - $this->now());
}
/**
* Defaults to the client address, then falls back to a single shared bucket. The address comes
* from a request attribute because the library never reads `$_SERVER`.
*/
private function keyFor(Request $request): string
{
if ($this->keyResolver !== null) {
return (string) ($this->keyResolver)($request);
}
$address = $request->attribute('client_ip');
return is_string($address) && $address !== '' ? $address : 'anonymous';
}
private function now(): int
{
return $this->clock === null ? time() : (int) ($this->clock)();
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Camelia\Controllers\Security;
use Camelia\Controllers\Exception\BadRequest;
use Camelia\Controllers\Exception\Unauthorized;
use Camelia\Controllers\Middleware;
use Camelia\Controllers\Request;
use Camelia\Controllers\Response;
/**
* Rejects a request whose authenticated identity lacks a required role.
*
* Runs after {@see BearerAuth}: it reads the identity from the request attribute that middleware
* set. It fails closed — a request with no identity is 401, never 200.
*/
final readonly class RequireRole implements Middleware
{
/** Attribute holding the identity; matches {@see BearerAuth::ATTRIBUTE}. */
public const ATTRIBUTE = 'user';
/** Attribute holding the identity's roles. */
public const ROLE_ATTRIBUTE = 'roles';
/** @param list<string> $roles Roles accepted; any one of them is enough. */
public function __construct(
private array $roles,
) {
if ($this->roles === []) {
throw new BadRequest('At least one role is required.');
}
}
public function process(Request $request, callable $next): Response
{
$identity = $request->attribute(self::ATTRIBUTE);
if (!is_array($identity)) {
return $this->error(new Unauthorized('Authentication is required.'));
}
$granted = $this->rolesOf($identity);
foreach ($this->roles as $role) {
if (in_array($role, $granted, true)) {
return $next($request);
}
}
return $this->error(new Unauthorized(sprintf('This action requires one of these roles: %s.', implode(
', ',
$this->roles,
))));
}
/**
* Reads roles from the identity under either `roles` or `role`. A single string is accepted so
* an identity carrying one role does not have to be reshaped by the adapter.
*
* @param array<array-key, mixed> $identity
* @return list<string>
*/
private function rolesOf(array $identity): array
{
$raw = $identity[self::ROLE_ATTRIBUTE] ?? $identity['role'] ?? [];
if (is_string($raw)) {
return [$raw];
}
if (!is_array($raw)) {
return [];
}
return array_values(array_filter($raw, is_string(...)));
}
private function error(Unauthorized $error): Response
{
return new Response($error->toArray(), $error->status(), $error->headers());
}
}