From 4b86ac9e82f60e33748d9d8fc8d655f979a3c104 Mon Sep 17 00:00:00 2001 From: Dave Mc Nicoll Date: Thu, 22 Oct 2026 15:03:18 +0000 Subject: [PATCH] - Added a new CSRF token verification Middleware. - Added a new ActionLog middleware to catch every modifying request and save the changes made and the user who did. - Added a new RequestLog to catch every request made whenever required. --- meta/definitions/software.php | 14 +-- meta/docs/security/action-logs.md | 21 ++++ meta/docs/security/csrf.md | 21 ++++ meta/docs/security/request-logs.md | 21 ++++ src/Action/Console/EntityGenerate.php | 4 +- src/Attribute/Security/ActionLog.php | 11 ++ src/Controller/Debug/Errors.php | 1 - src/Controller/{Debug.php => LeanApi.php} | 45 ++++---- src/Controller/Security/ActionLog.php | 55 ++++++++++ src/Controller/Security/CSRF.php | 59 ++++++++++ src/Controller/Security/RequestLog.php | 57 ++++++++++ src/Cronard/System.php | 33 ++++++ src/Entity/Security/ApiActionLog.php | 101 ++++++++++++++++++ src/Entity/Security/ApiRequestLog.php | 92 ++++++++++++++++ src/Exception/CSRFInvalidToken.php | 5 + src/Exception/CSRFMissingToken.php | 5 + src/Factory/DebugFormFactoryInterface.php | 21 ---- .../DebugTrait.php} | 13 +-- src/Factory/FormFactories/SecurityTrait.php | 53 +++++++++ src/Factory/LeanApiEntityFactory.php | 14 +++ src/Factory/LeanApiFormFactory.php | 21 ++++ src/Factory/LeanApiFormFactoryInterface.php | 32 ++++++ src/Form/Security/ActionLogContext.php | 83 ++++++++++++++ src/Form/Security/CsrfGenerate.php | 40 +++++++ src/Form/Security/CsrfGenerateContext.php | 18 ++++ src/Form/Security/CsrfVerifyToken.php | 42 ++++++++ src/Form/Security/CsrfVerifyTokenContext.php | 24 +++++ src/Form/Security/RequestLogContext.php | 49 +++++++++ src/Form/Security/SaveActionLog.php | 35 ++++++ src/Form/Security/SaveRequestLog.php | 44 ++++++++ src/LeanApiTrait.php | 66 +++++++----- src/Lib/ControllerTrait.php | 9 ++ src/Lib/DeleteFormContext.php | 20 ++++ src/Lib/RenderCORS.php | 42 +++++--- src/Middleware/ApiRenderer.php | 32 +++--- src/Middleware/CORS.php | 1 + .../Security/ActionLogMiddleware.php | 87 +++++++++++++++ src/Middleware/Security/CORSMiddleware.php | 22 ++++ src/Middleware/Security/CSRFMiddleware.php | 26 +++++ .../Security/RequestLogMiddleware.php | 33 ++++++ src/Middleware/SecurityMiddleware.php | 31 ++++++ view/lean-api/request_debugger.phtml | 76 ++++++++----- 42 files changed, 1331 insertions(+), 148 deletions(-) create mode 100644 meta/docs/security/action-logs.md create mode 100644 meta/docs/security/csrf.md create mode 100644 meta/docs/security/request-logs.md create mode 100644 src/Attribute/Security/ActionLog.php rename src/Controller/{Debug.php => LeanApi.php} (68%) create mode 100644 src/Controller/Security/ActionLog.php create mode 100644 src/Controller/Security/CSRF.php create mode 100644 src/Controller/Security/RequestLog.php create mode 100644 src/Cronard/System.php create mode 100644 src/Entity/Security/ApiActionLog.php create mode 100644 src/Entity/Security/ApiRequestLog.php create mode 100644 src/Exception/CSRFInvalidToken.php create mode 100644 src/Exception/CSRFMissingToken.php delete mode 100644 src/Factory/DebugFormFactoryInterface.php rename src/Factory/{DebugFormFactory.php => FormFactories/DebugTrait.php} (76%) create mode 100644 src/Factory/FormFactories/SecurityTrait.php create mode 100644 src/Factory/LeanApiEntityFactory.php create mode 100644 src/Factory/LeanApiFormFactory.php create mode 100644 src/Factory/LeanApiFormFactoryInterface.php create mode 100644 src/Form/Security/ActionLogContext.php create mode 100644 src/Form/Security/CsrfGenerate.php create mode 100644 src/Form/Security/CsrfGenerateContext.php create mode 100644 src/Form/Security/CsrfVerifyToken.php create mode 100644 src/Form/Security/CsrfVerifyTokenContext.php create mode 100644 src/Form/Security/RequestLogContext.php create mode 100644 src/Form/Security/SaveActionLog.php create mode 100644 src/Form/Security/SaveRequestLog.php create mode 100644 src/Lib/DeleteFormContext.php create mode 100644 src/Middleware/Security/ActionLogMiddleware.php create mode 100644 src/Middleware/Security/CORSMiddleware.php create mode 100644 src/Middleware/Security/CSRFMiddleware.php create mode 100644 src/Middleware/Security/RequestLogMiddleware.php create mode 100644 src/Middleware/SecurityMiddleware.php diff --git a/meta/definitions/software.php b/meta/definitions/software.php index a9c4299..a8828d0 100644 --- a/meta/definitions/software.php +++ b/meta/definitions/software.php @@ -51,21 +51,15 @@ return [ ], ], - 'lean.api:storage' => function($c) { - $adapter = new ConnectionAdapter('lean.api', $c->get('config')['ulmus'], false); - $adapter->resolveConfiguration(); - - return $adapter; - }, - 'app.middlewares' => \DI\add([ - Lean\Api\Middleware\CORS::class, + # Lean\Api\Middleware\Security\CORSMiddleware::class, + # Lean\Api\Middleware\Security\RequestLogMiddleware::class, ]), - Lean\Api\Lib\RenderCORS::class => DI\create(Lean\Api\Lib\RenderCORS::class)->constructor(get(\Psr\Http\Message\ServerRequestInterface::class), env('LEAN_API_CORS_ORIGIN', '*')), Lean\ApplicationStrategy\NotFoundDecoratorInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\NotFoundDecorator::class), Lean\ApplicationStrategy\MethodNotAllowedInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\MethodNotAllowedDecorator::class), Lean\Api\Factory\MessageFactoryInterface::class => DI\autowire(Lean\Api\Lib\Message::class), - Lean\Api\Factory\DebugFormFactoryInterface::class => DI\autowire(Lean\Api\Factory\DebugFormFactory::class), + Lean\Api\Factory\LeanApiFormFactoryInterface::class => DI\autowire(Lean\Api\Factory\LeanApiFormFactory::class), + Lean\Api\Lib\RenderCORS::class => DI\create(Lean\Api\Lib\RenderCORS::class)->constructor(get(\Psr\Http\Message\ServerRequestInterface::class), env('LEAN_API_CORS_ORIGIN', '*')), # League\Route\Strategy\ApplicationStrategy::class => DI\autowire(Lean\Api\ApplicationStrategy::class), ]; \ No newline at end of file diff --git a/meta/docs/security/action-logs.md b/meta/docs/security/action-logs.md new file mode 100644 index 0000000..c4673bc --- /dev/null +++ b/meta/docs/security/action-logs.md @@ -0,0 +1,21 @@ +# LEAN API + +## An action logger to keep important actions in checks / allow easy notifications handling + +[Documentation](../../) / Security / Action logs + +-------------------------------------------------------------------------------- + +### Available routes + +{route:descriptor} + +{request:debugger} + +### Forms + +{form:descriptor} + +### Entity + +{entity:descriptor} \ No newline at end of file diff --git a/meta/docs/security/csrf.md b/meta/docs/security/csrf.md new file mode 100644 index 0000000..0ef05e9 --- /dev/null +++ b/meta/docs/security/csrf.md @@ -0,0 +1,21 @@ +# LEAN API + +## CSRF Token generation for non-idempotent requests + +[Documentation](../../) / Security / CRSF + +-------------------------------------------------------------------------------- + +### Available routes + +{route:descriptor} + +{request:debugger} + +### Forms + +{form:descriptor} + +### Entity + +{entity:descriptor} \ No newline at end of file diff --git a/meta/docs/security/request-logs.md b/meta/docs/security/request-logs.md new file mode 100644 index 0000000..86278ce --- /dev/null +++ b/meta/docs/security/request-logs.md @@ -0,0 +1,21 @@ +# LEAN API + +## Logging request logs allowing deeper forensic than simple request logs + +[Documentation](../../) / Security / Requests + +-------------------------------------------------------------------------------- + +### Available routes + +{route:descriptor} + +{request:debugger} + +### Forms + +{form:descriptor} + +### Entity + +{entity:descriptor} \ No newline at end of file diff --git a/src/Action/Console/EntityGenerate.php b/src/Action/Console/EntityGenerate.php index 1180a11..417d45f 100644 --- a/src/Action/Console/EntityGenerate.php +++ b/src/Action/Console/EntityGenerate.php @@ -80,12 +80,12 @@ class EntityGenerate } if (isset($this->formNamespace)) { - $formPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->formNamespace), $this->formNamespace ]); + $formPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->formNamespace), str_replace('\\', DIRECTORY_SEPARATOR, $this->formNamespace) ]); $formPath = $this->readline(sprintf("Path of Forms (default: %s) : ", $formPath), $formPath); } if (isset($this->factoryNamespace)) { - $factoryPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->factoryNamespace), $this->factoryNamespace ]); + $factoryPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->factoryNamespace), str_replace('\\', DIRECTORY_SEPARATOR, $this->factoryNamespace) ]); $factoryPath = $this->readline(sprintf("Path of Factory (default: %s) : ", $factoryPath), $factoryPath); } diff --git a/src/Attribute/Security/ActionLog.php b/src/Attribute/Security/ActionLog.php new file mode 100644 index 0000000..51ab92b --- /dev/null +++ b/src/Attribute/Security/ActionLog.php @@ -0,0 +1,11 @@ +renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/lean-api.md", [ Entity\Error::class, ], [ Form\Debug\ErrorContext::class ]); - } -} +renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/lean-api.md", [ ], [ ]); + } +} diff --git a/src/Controller/Security/ActionLog.php b/src/Controller/Security/ActionLog.php new file mode 100644 index 0000000..250477e --- /dev/null +++ b/src/Controller/Security/ActionLog.php @@ -0,0 +1,55 @@ +renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/security/action-logs.md", [ \Lean\Api\Entity\Security\ApiRequestLog::class ], [ \Lean\Api\Form\Security\RequestLogContext::class ]); + } + + #[Route("/", name: "lean.api:security-action-log-list", method: [ "GET" ], description: "Affiche la liste de toute les journaux d'actions")] + public function list(ServerRequestInterface $request, array $arguments): ResponseInterface + { + $result = $this->searchEntitiesFromRequest($request, $this->leanApiEntityFactory->securityApiActionLog) + ->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityApiActionLog]; + + return $this->outputSearchResult($result); + } + + #[Route("/{id:\d+}", name: "lean.api:security-action-log-single", method: [ "GET" ], description: "Permet de récupérer une action par son id")] + public function single(ServerRequestInterface $request, array $arguments): ResponseInterface + { + $result = $this->searchEntityFromRequest($request, $this->leanApiEntityFactory->securityApiActionLog) + ->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityApiActionLog]; + + return $this->outputSearchResult($result); + } + + # No routes needed, every modifying request hits this method + public function add(ServerRequestInterface $request, array $arguments) : ResponseInterface + { + $entity = new $this->leanApiEntityFactory->securityApiActionLog(); + + $this->form($this->leanApiFormFactory->securityActionLogSave($entity, $this->user), $request->getAttribute('lean-api.security-action:context')); + + return $this->output($entity, (int) $entity->isLoaded()); + } + +} diff --git a/src/Controller/Security/CSRF.php b/src/Controller/Security/CSRF.php new file mode 100644 index 0000000..36d4c85 --- /dev/null +++ b/src/Controller/Security/CSRF.php @@ -0,0 +1,59 @@ +renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/security/csrf.md", [ ], [ ]); + } + + #[Route("/", name: "lean.api:security-csrf-generate", method: [ "GET" ], description: "Generate a CSRF token")] + public function generate(ServerRequestInterface $request, array $arguments): ResponseInterface + { + $context = $this->leanApiFormFactory->securityCsrfGenerateContext($request->withMethod('PUT')); + + return $this->output([ + 'token' => $this->form($this->leanApiFormFactory->securityCsrfGenerate($this->user), $context)->executionStatus + ], 1); + } + + #[Route("/{token}", name: "lean.api:security-csrf-test-token", method: [ "POST", "PUT", "DELETE", "PATCH" ], description: "Verify a CSRF token")] + public function test(ServerRequestInterface $request, array $arguments) : ResponseInterface + { + try { + $valid = $this->validate($request->withHeader('X-CSRF-Token', $arguments['token']), $arguments); + } + catch (\Throwable $ex) { + $valid = false; + } + + return $this->output([ + 'valid' => $valid + ], 1); + } + + public function validate(ServerRequestInterface $request, array $arguments) : bool + { + $context = $this->leanApiFormFactory->securityCsrfVerifyTokenContext($request); + + # This form call WILL throw an exception if anything is wrong (missing, invalid, outdated) with the CSRF token. + return (bool) $this->form($this->leanApiFormFactory->securityCsrfVerifyToken($this->user, $arguments['token']), $context)->executionStatus; + } +} diff --git a/src/Controller/Security/RequestLog.php b/src/Controller/Security/RequestLog.php new file mode 100644 index 0000000..f35927b --- /dev/null +++ b/src/Controller/Security/RequestLog.php @@ -0,0 +1,57 @@ +renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/security/request-logs.md", [ \Lean\Api\Entity\Security\ApiRequestLog::class ], [ \Lean\Api\Form\Security\RequestLogContext::class ]); + } + + #[Route("/", name: "lean.api:security-request-log-list", method: [ "GET" ], description: "Affiche la liste de toute les journaux de requête")] + public function list(ServerRequestInterface $request, array $arguments): ResponseInterface + { + $result = $this->searchEntitiesFromRequest($request, $this->leanApiEntityFactory->securityRequestLog) + ->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityRequestLog]; + + return $this->outputSearchResult($result); + } + + #[Route("/{id:\d+}", name: "lean.api:security-request-log-single", method: [ "GET" ], description: "Permet de récupérer une requête par son id")] + public function single(ServerRequestInterface $request, array $arguments): ResponseInterface + { + $result = $this->searchEntityFromRequest($request, $this->leanApiEntityFactory->securityRequestLog) + ->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityRequestLog]; + + return $this->outputSearchResult($result); + } + + # No routes needed, every request hits this method + public function add(ServerRequestInterface $request, array $arguments) : ResponseInterface + { + $entity = new $this->leanApiEntityFactory->securityRequestLog(); + + $context = $this->leanApiFormFactory->securityRequestLogSaveContext($request->withAttribute('api:request-log-original-method', $request->getMethod())-> withMethod('PUT')); + + $this->form($this->leanApiFormFactory->securityRequestLogSave($entity, $arguments['response'], $this->user), $context); + + return $this->output($entity, (int) $entity->isLoaded()); + } + +} diff --git a/src/Cronard/System.php b/src/Cronard/System.php new file mode 100644 index 0000000..aca4155 --- /dev/null +++ b/src/Cronard/System.php @@ -0,0 +1,33 @@ +renderMarkdown(getenv("PROJECT_PATH") . "/meta/docs/cronard.md", [ ], []); + } + + #[Cronard('0 0 1 * *')] + #[Route("/clean/request-logs", name: "lean-api.cronard:clean-request-logs", method: ["DELETE"], description: "Fait le ménage automatiquement des logs de requêtes datant de plus d'un an")] + public function clean_request_logs(ServerRequestInterface $request, array $arguments): ResponseInterface + { + # return $this->outputSearchResult($results); + } +} diff --git a/src/Entity/Security/ApiActionLog.php b/src/Entity/Security/ApiActionLog.php new file mode 100644 index 0000000..6e335a8 --- /dev/null +++ b/src/Entity/Security/ApiActionLog.php @@ -0,0 +1,101 @@ +id, $this->objectType)); + } + + #[Ignore] + public static function searchRequest(...$arguments) : SearchRequest\SearchRequestInterface + { + return new #[SearchRequest\Attribute\SearchRequestParameter(ApiActionLog::class, description: "Les établissements peuvent être recherchés/filtrés de différentes manière en requête GET en empruntant la route de liste complète.")] class(... $arguments) extends SearchRequest\SearchRequest { + + #[SearchRequest\Attribute\SearchWhere(source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)] + public string $event; + + #[SearchRequest\Attribute\SearchWhere(source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)] + public string $method; + + #[SearchRequest\Attribute\SearchWhere(parameter: "object_type", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)] + public string $objectType; + + #[SearchRequest\Attribute\SearchWhere(parameter: "object_id", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)] + public int $objectId; + + #[SearchRequest\Attribute\SearchWhere(parameter: "user_id", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)] + public int $userId; + + #[SearchRequest\Attribute\SearchWhere(parameter: "user_id", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)] + public string $userType; + + #[SearchRequest\Attribute\SearchOrderBy(field: "createdAt")] + public SearchRequest\Attribute\OrderByEnum $orderByDate = SearchRequest\Attribute\OrderByEnum::Descending; + + #[SearchRequest\Attribute\SearchManual] + public int $page = 1; + + #[SearchRequest\Attribute\SearchManual] + public int $limit = 0; + + public function filter(Repository $repository) : Repository + { + return $repository; + } + }; + } +} \ No newline at end of file diff --git a/src/Entity/Security/ApiRequestLog.php b/src/Entity/Security/ApiRequestLog.php new file mode 100644 index 0000000..8d70bcb --- /dev/null +++ b/src/Entity/Security/ApiRequestLog.php @@ -0,0 +1,92 @@ +languageHandler, $this->messageFactory, $entity, $response, $user); + } + + public function securityRequestLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface + { + return new \Lean\Api\Form\Security\RequestLogContext($this->languageHandler, $this->messageFactory, $request ?: $this->request, $formName); + } + + public function securityCsrfGenerate(UserInterface $user): FormInterface + { + return new \Lean\Api\Form\Security\CsrfGenerate($this->languageHandler, $this->messageFactory, $user, 30); + } + + public function securityCsrfGenerateContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface + { + return new \Lean\Api\Form\Security\CsrfGenerateContext($this->languageHandler, $this->messageFactory, $request ?: $this->request, $formName); + } + + public function securityCsrfVerifyToken(UserInterface $user, string $token): FormInterface + { + return new \Lean\Api\Form\Security\CsrfVerifyToken($this->languageHandler, $this->messageFactory, $user, $token); + } + + public function securityCsrfVerifyTokenContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface + { + return new \Lean\Api\Form\Security\CsrfVerifyTokenContext($this->languageHandler, $this->messageFactory, $request ?: $this->request, $formName); + } + + public function securityActionLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiActionLog $entity, UserInterface $user): FormInterface + { + return new \Lean\Api\Form\Security\SaveActionLog($this->languageHandler, $this->messageFactory, $entity, $user); + } + + public function securityActionLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface + { + return new \Lean\Api\Form\Security\ActionLogContext($this->languageHandler, $this->messageFactory, $request->withParsedBody([]) ?: $this->request, $formName); + } +} \ No newline at end of file diff --git a/src/Factory/LeanApiEntityFactory.php b/src/Factory/LeanApiEntityFactory.php new file mode 100644 index 0000000..a4b641d --- /dev/null +++ b/src/Factory/LeanApiEntityFactory.php @@ -0,0 +1,14 @@ +entity = $entity; + + $this->datasetFillEvent = new class() implements \Ulmus\Event\Entity\DatasetFill + { + public readonly array $data; + + public function execute(\Generator $generator, \Ulmus\Entity\EntityInterface $entity): void + { + $this->data = $entity::repository()->generateDatasetDiff($entity); + } + }; + + $this->entity->eventRegister($this->datasetFillEvent); + } + + public function initializeEntity(\Lean\Api\Entity\Security\ApiActionLog $actionLog) : void + { + if (isset($this->entity) && $this->entity->isLoaded()) { + if ($pk = array_key_first($this->entity::resolveEntity()->getPrimaryKeyField())) { + if (isset($this->entity->$pk)) { + $this->object_id = $this->entity->$pk; + $this->object_type = $this->entity::class; + + if (isset($this->datasetFillEvent->data)) { + $this->data = $this->datasetFillEvent->data; + } + } + } + } + else { + throw new \InvalidArgumentException("An EntityInterface must be provided using the attachEntity() method."); + } + } + + public function valid(? \Lean\Api\Entity\Security\ApiActionLog $actionLog = null): bool + { + return isset($this->object_id) && isset($this->object_type); + } +} \ No newline at end of file diff --git a/src/Form/Security/CsrfGenerate.php b/src/Form/Security/CsrfGenerate.php new file mode 100644 index 0000000..de57b06 --- /dev/null +++ b/src/Form/Security/CsrfGenerate.php @@ -0,0 +1,40 @@ +languageHandler, $this->message); + } + + public function initialize(FormContextInterface $context): void { } + + public function execute(FormContextInterface $context): mixed + { + $ts = ( new \Datetime() )->getTimestamp(); + + $jwt = new \Ulmus\User\Authorize\Bearer\JsonWebTokenEncoder([ + 'sub' => $this->getEntity()->isLoaded() ? $this->getEntity()->id : null, + 'iat' => $ts, + 'exp' => $ts + $this->expires, + ], hash('sha512', getenv('LEAN_RANDOM'))); + + return $jwt->encode(); + } +} diff --git a/src/Form/Security/CsrfGenerateContext.php b/src/Form/Security/CsrfGenerateContext.php new file mode 100644 index 0000000..c927ac2 --- /dev/null +++ b/src/Form/Security/CsrfGenerateContext.php @@ -0,0 +1,18 @@ +languageHandler, $this->message); + } + + public function initialize(FormContextInterface $context): void { } + + public function execute(FormContextInterface $context): bool + { + $decoder = new JsonWebTokenDecoder($this->token, hash('sha512', getenv('LEAN_RANDOM'))); + + $decoder->decode(); + # Validate JWT + # throw error if any + + # Validate expires + # throw expires error if any + + return true; + } +} diff --git a/src/Form/Security/CsrfVerifyTokenContext.php b/src/Form/Security/CsrfVerifyTokenContext.php new file mode 100644 index 0000000..4db3968 --- /dev/null +++ b/src/Form/Security/CsrfVerifyTokenContext.php @@ -0,0 +1,24 @@ +getRequest()->getMethod(), [ 'POST', 'PUT', 'DELETE', 'PATCH' ]) ) { + if (! $this->getRequest()->hasHeader('X-CSRF-Token')) { + throw new CSRFMissingToken("A CSRF token must be provided to run non-safe methods."); + } + } + + return parent::valid(); + } +} \ No newline at end of file diff --git a/src/Form/Security/RequestLogContext.php b/src/Form/Security/RequestLogContext.php new file mode 100644 index 0000000..4f8efa7 --- /dev/null +++ b/src/Form/Security/RequestLogContext.php @@ -0,0 +1,49 @@ +languageHandler, $this->message); + } + + public function initialize(FormContextInterface|ActionLogContext $context): void + { + parent::initialize($context); + + if ($this->user->isLoaded()) { + $context->user_id = $this->user->id; + $context->user_type = $this->user::class; + } + } +} diff --git a/src/Form/Security/SaveRequestLog.php b/src/Form/Security/SaveRequestLog.php new file mode 100644 index 0000000..345939b --- /dev/null +++ b/src/Form/Security/SaveRequestLog.php @@ -0,0 +1,44 @@ +languageHandler, $this->message); + + $this->contextClass = RequestLogContext::class; + } + + public function initialize(FormContextInterface|RequestLogContext $context): void + { + parent::initialize($context); + + $request = $context->getRequest(); + + $context->user_id = $this->user->isLoaded() ? $this->user->id : null; + $context->method = $request->getAttribute('api:request-log-original-method'); + $context->endpoint = $request->getUri(); + $context->ipv4 = $request->getHeaderLine('x-forwarded-for') ?: $request->getServerParams()['REMOTE_ADDR']; + $context->request_headers = array_replace($request->getHeaders(), [ 'authorization' => "{removed}", ]); + $context->request_body = $request->getBody()->getSize() > 100000 ? "{too large}" : $request->getParsedBody(); + $context->status_code = $this->response->getStatusCode(); + $context->response_headers = $this->response->getHeaders(); + $context->response_body = substr($this->response->getBody()->getContents(), 0, 100000); + $context->duration = microtime(true) - $request->getServerParams()['REQUEST_TIME']; + } +} diff --git a/src/LeanApiTrait.php b/src/LeanApiTrait.php index ea79fde..b610c2c 100644 --- a/src/LeanApiTrait.php +++ b/src/LeanApiTrait.php @@ -21,35 +21,31 @@ trait LeanApiTrait protected ContainerInterface $container; #[Ignore] - public function renderMarkdown(string $filepath, array $entities = [], array $forms = [], int $code = 200, array $headers = []) : ResponseInterface + public function renderMarkdown(string $filepath, array $entities = [], array $forms = [], int $code = 200, array $headers = []): ResponseInterface { - if ( ! class_exists(CommonMarkConverter::class)) { + if (!class_exists(CommonMarkConverter::class)) { throw new \BadFunctionCallException("League\CommonMark seems to be missing, please install dependency before trying to render Markdown content"); } - $markdown = ( new CommonMarkConverter() )->convert(file_get_contents($filepath))->getContent(); + $markdown = (new CommonMarkConverter())->convert(file_get_contents($filepath))->getContent(); - if (str_contains($markdown, '{route:descriptor}')) - { + if (str_contains($markdown, '{route:descriptor}')) { $markdown = str_replace('{route:descriptor}', $this->renderRawView('lean-api/route_descriptor', [ 'routes' => (new RouteDescriptor($this, $this->picea->compiler->getExtensionFromToken('url'), $this->container))->getRoutes() ]), $markdown); } - if (str_contains($markdown, '{request:debugger}')) - { + if (str_contains($markdown, '{request:debugger}')) { $markdown = str_replace('{request:debugger}', $this->renderRawView('lean-api/request_debugger', []), $markdown); } - if (str_contains($markdown, '{entity:descriptor}')) - { + if (str_contains($markdown, '{entity:descriptor}')) { $markdown = str_replace('{entity:descriptor}', $this->renderRawView('lean-api/entity_descriptor', [ 'entities' => (new EntityDescriptor())->getEntities(... $entities) ]), $markdown); } - if (str_contains($markdown, '{form:descriptor}')) - { + if (str_contains($markdown, '{form:descriptor}')) { $markdown = str_replace('{form:descriptor}', $this->renderRawView('lean-api/form_descriptor', [ 'forms' => (new FormDescriptor())->getForms(... $forms) ]), $markdown); @@ -59,7 +55,7 @@ trait LeanApiTrait } #[Ignore] - protected function output(\JsonSerializable|array $data, int $count) : ResponseInterface + protected function output(\JsonSerializable|array $data, int $count): ResponseInterface { return $this->renderJson([ 'data' => $data, @@ -68,18 +64,18 @@ trait LeanApiTrait } #[Ignore] - protected function outputSearchResult(ApiSearchRequestInterface $apiSearchRequest) : ResponseInterface + protected function outputSearchResult(ApiSearchRequestInterface $apiSearchRequest): ResponseInterface { return $this->output($apiSearchRequest->getResult(), $apiSearchRequest->getSearch()->count); } #[Ignore] - protected function searchEntityFromRequest(ServerRequestInterface $request, string $entityType, ? string $resultKey = null) : ServerRequestInterface + protected function searchEntityFromRequest(ServerRequestInterface $request, string $entityType, ?string $resultKey = null): ServerRequestInterface { $search = $entityType::searchRequest()->fromRequest($request); - $entity = $entityType::repository()->filterServerRequest($search)->loadOne() ?? false; + $entity = $entityType::repository()->filterServerRequest($search, false)->loadOne() ?? false; - if (! $entity ) { + if (!$entity) { throw new \InvalidArgumentException(sprintf("L'entré pour l'entité demandé (%s) est introuvable avec le ou les arguments fournis '%s'", $entityType, json_encode($request->getAttributes(), \JSON_PARTIAL_OUTPUT_ON_ERROR))); } @@ -87,11 +83,17 @@ trait LeanApiTrait $request = $request->withAttribute("lean.searchRequest", $this->searchEntityResult()); } + if ($request->getAttribute('lean-api.security-action:context')) { + $request->getAttribute('lean-api.security-action:context')->attachEntity($entity); + } + $request->getAttribute("lean.searchRequest")[$resultKey ?: $entityType] = new class($search, $entity) implements ApiSearchRequestInterface { public function __construct( public readonly SearchRequestInterface $search, - public readonly EntityInterface $entity, - ) {} + public readonly EntityInterface $entity, + ) + { + } public function getSearch(): SearchRequestInterface { @@ -108,12 +110,12 @@ trait LeanApiTrait } #[Ignore] - protected function searchEntitiesFromRequest(ServerRequestInterface $request, string $entityType, ? string $resultKey = null) : ServerRequestInterface + protected function searchEntitiesFromRequest(ServerRequestInterface $request, string $entityType, ?string $resultKey = null, bool $count = true): ServerRequestInterface { $search = $entityType::searchRequest()->fromRequest($request); - $entity = $entityType::repository()->filterServerRequest($search)->loadAll(); + $entity = $entityType::repository()->filterServerRequest($search, $count)->loadAll(); - if (! $entity ) { + if (!$entity) { throw new \InvalidArgumentException(sprintf("L'entré pour l'entité demandé (%s) est introuvable avec le ou les arguments fournis '%s'", $entityType, json_encode($request->getAttributes()))); } @@ -124,8 +126,10 @@ trait LeanApiTrait $request->getAttribute("lean.searchRequest")[$resultKey ?: $entityType] = new class($search, $entity) implements ApiSearchRequestInterface { public function __construct( public readonly SearchRequestInterface $search, - public readonly EntityCollection $collection, - ) {} + public readonly EntityCollection $collection, + ) + { + } public function getSearch(): SearchRequestInterface { @@ -142,8 +146,9 @@ trait LeanApiTrait } #[Ignore] - protected function searchEntityResult() :\ArrayObject { - return new class()extends \ArrayObject implements ApiSearchRequestInterface { + protected function searchEntityResult(): \ArrayObject + { + return new class() extends \ArrayObject implements ApiSearchRequestInterface { public function getSearch(): SearchRequestInterface { @@ -154,7 +159,8 @@ trait LeanApiTrait return $this[array_key_last($this->getArrayCopy())]->getSearch(); } - public function getResult() : EntityInterface|EntityCollection { + public function getResult(): EntityInterface|EntityCollection + { if ($this->count() !== 1) { throw new \LogicException("Search results contains more than one results. Impossible to continue without precising which one you needs."); } @@ -163,4 +169,12 @@ trait LeanApiTrait } }; } + + #[Ignore] + protected function attachActionEntity(ServerRequestInterface $request, EntityInterface $entity): void + { + if ($request->getAttribute('lean-api.security-action:attribute')) { + $request->getAttribute('lean-api.security-action:context')->attachEntity($entity); + } + } } \ No newline at end of file diff --git a/src/Lib/ControllerTrait.php b/src/Lib/ControllerTrait.php index b246fbe..c766dc9 100644 --- a/src/Lib/ControllerTrait.php +++ b/src/Lib/ControllerTrait.php @@ -2,6 +2,9 @@ namespace Lean\Api\Lib; +use DI\Attribute\Inject; +use Lean\Api\Factory\LeanApiFormFactoryInterface; +use Lean\Api\Factory\LeanApiEntityFactory; use Notes\Route\Attribute\Object\Route; #[Route(method: ['GET', 'POST', ])] @@ -10,4 +13,10 @@ trait ControllerTrait use \Lean\ControllerTrait, \Lean\Api\LeanApiTrait { \Lean\Api\LeanApiTrait::renderMarkdown insteadof \Lean\ControllerTrait; } + + #[Inject] + protected LeanApiFormFactoryInterface $leanApiFormFactory; + + #[Inject] + protected LeanApiEntityFactory $leanApiEntityFactory; } \ No newline at end of file diff --git a/src/Lib/DeleteFormContext.php b/src/Lib/DeleteFormContext.php new file mode 100644 index 0000000..d435ec0 --- /dev/null +++ b/src/Lib/DeleteFormContext.php @@ -0,0 +1,20 @@ +pushErrorMessage('lean.api.form.delete.error.entity'); + } + + return parent::valid(); + } +} \ No newline at end of file diff --git a/src/Lib/RenderCORS.php b/src/Lib/RenderCORS.php index 788f10b..b22c5e7 100644 --- a/src/Lib/RenderCORS.php +++ b/src/Lib/RenderCORS.php @@ -11,37 +11,38 @@ class RenderCORS { public function __construct( protected ServerRequestInterface $request, - public string|array $origin = "http://localhost,https://localhost", - public bool $allowCredentials = true, - public string|array $methods = [ "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", ], - public string|array $headers = [ "Content-Type", "Authorization", "X-Requested-With" ], + public string|array $origin = [ "http://localhost", "https://localhost" ], + public bool $allowCredentials = true, + public string|array $methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS",], + public string|array $headers = ["Content-Type", "Authorization", "X-Requested-With", "X-CSRF-Token"], ) { - if (is_string($this->origin)) { + if (is_string($origin)) { $this->origin = explode(',', $this->origin); } } - public function renderHeader(ServerRequestInterface $request) : void + public function renderHeader(ServerRequestInterface $request): void { - $matched = $this->matchOrigin($this->request->getServerParams()['HTTP_ORIGIN'] ?? null, $this->origin); + $matched = $this->matchOrigin($this->getOrigin($request), $this->origin); - if (! $matched) { + if (!$matched) { return; } + var_dump($matched);die(); $render = fn(string|array $e) => is_string($e) ? $e : sprintf('%s', implode(', ', $e)); - header('Access-Control-Allow-Origin: ' . $matched); + header(sprintf('Access-Control-Allow-Origin: %s', $matched)); header(sprintf('Access-Control-Allow-Methods: %s', $render($this->methods))); header(sprintf('Access-Control-Allow-Headers: %s', $render($this->headers))); - header('Access-Control-Allow-Credentials: ' . ($this->allowCredentials ? 'true' : 'false')); + header(sprintf('Access-Control-Allow-Credentials: %s', $this->allowCredentials ? 'true' : 'false')); } - public function fromResponse(ResponseInterface $response, bool $emptyResponse = false) : ResponseInterface + public function fromResponse(ResponseInterface $response, bool $emptyResponse = false): ResponseInterface { - $matched = $this->matchOrigin($this->request->getServerParams()['HTTP_ORIGIN'] ?? null, $this->origin); + $matched = $this->matchOrigin($this->getOrigin($this->request), $this->origin); - if (! $matched) { + if (!$matched) { return $response; } @@ -66,7 +67,7 @@ class RenderCORS return null; } - foreach ((array) $allowList as $rule) { + foreach ((array)$allowList as $rule) { if ($rule === '*') { return '*'; } @@ -89,5 +90,18 @@ class RenderCORS return null; } + protected function getOrigin(ServerRequestInterface $request): string + { + $server = $request->getServerParams(); + + if (isset($server['HTTP_ORIGIN'])) { + return $server['HTTP_ORIGIN']; + } + + $protocol = $server['HTTP_X_FORWARDED_PROTO'] ?? ((!empty($server['HTTPS']) && $server['HTTPS'] !== 'off') ? 'https' : 'http'); + $host = $server['HTTP_X_FORWARDED_HOST'] ?? $server['HTTP_HOST'] ?? $server['SERVER_NAME']; + + return $protocol . '://' . $host; + } } diff --git a/src/Middleware/ApiRenderer.php b/src/Middleware/ApiRenderer.php index 9725cd4..bf5473b 100644 --- a/src/Middleware/ApiRenderer.php +++ b/src/Middleware/ApiRenderer.php @@ -2,6 +2,7 @@ namespace Lean\Api\Middleware; +use DI\Attribute\Inject; use Laminas\Diactoros\Response\JsonResponse; use Lean\Factory\HttpFactory; use Picea\Ui\Method\FormHandler; @@ -10,15 +11,12 @@ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; -use Lean\Api\{Controller\Debug, Factory\DebugFormFactoryInterface, Form, Entity}; +use Lean\Api\{Factory\LeanApiFormFactoryInterface, Form, Entity}; class ApiRenderer implements MiddlewareInterface { - public function __construct( - protected ContainerInterface $container, - # protected DebugFormFactoryInterface $debugFormFactory, - ) { - } + #[Inject] + protected LeanApiFormFactoryInterface $leanApiFormFactory; public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface { @@ -27,7 +25,7 @@ class ApiRenderer implements MiddlewareInterface { } catch(\Throwable $ex) { if (static::awaitingJson($request)) { - $this->saveError($request, $ex); + # $this->saveError($request, $ex); return HttpFactory::createJsonResponse([ 'status' => 'failed', @@ -36,6 +34,7 @@ class ApiRenderer implements MiddlewareInterface { # 'error_id' => $errorId, 'message' => $ex->getMessage(), ] + (getenv('DEBUG') ? [ + 'type' => $ex::class, 'file' => $ex->getFile(), 'line' => $ex->getLine(), 'code' => $ex->getCode(), @@ -66,17 +65,17 @@ class ApiRenderer implements MiddlewareInterface { if ($debugFormFactory = $this->container->get(DebugFormFactoryInterface::class)) { $request = $request->withMethod('PUT')->withParsedBody([]); - $context = $debugFormFactory->errorSaveContext($request); + $context = $this->leanApiFormFactory->errorSaveContext($request); - $context->sets([ - 'message' => $exception->getMessage(), - 'code' => $exception->getCode(), - 'file' => $exception->getFile(), - 'line' => $exception->getLine(), - 'trace' => $exception->getTrace(), - ]); + $context->sets([ + 'message' => $exception->getMessage(), + 'code' => $exception->getCode(), + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + 'trace' => $exception->getTrace(), + ]); - $form = $debugFormFactory->errorSave($entity = new Entity\Error()); + $form = $this->leanApiFormFactory->errorSave($entity = new Entity\Error()); new FormHandler($request, $form, $context); } @@ -96,7 +95,6 @@ class ApiRenderer implements MiddlewareInterface { $item = static::encodeHtml($item); } elseif (is_string($item)) { - dump($item); $item = htmlspecialchars($item); } } diff --git a/src/Middleware/CORS.php b/src/Middleware/CORS.php index 8e429f5..61496a6 100644 --- a/src/Middleware/CORS.php +++ b/src/Middleware/CORS.php @@ -7,6 +7,7 @@ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; +use Lean\Api\{ Entity}; class CORS implements MiddlewareInterface { diff --git a/src/Middleware/Security/ActionLogMiddleware.php b/src/Middleware/Security/ActionLogMiddleware.php new file mode 100644 index 0000000..b8fe154 --- /dev/null +++ b/src/Middleware/Security/ActionLogMiddleware.php @@ -0,0 +1,87 @@ +createEventHandler($request); + + $this->eventManager->eventRegister($eventHandler); + + $handler = $handler->handle($request); + + try { + if ($handler->getStatusCode() < 300) { + if (isset($eventHandler->request)) { + if ($eventHandler->request->getAttribute('lean-api.security-action:attribute')) { + $this->actionLogController->add($eventHandler->request, []); + } + } + } + } + catch(\Throwable $ex) { + if (getenv('DEBUG')) { + throw $ex; + } + } + + return $handler; + } + + protected function createEventHandler(ServerRequestInterface $request) : object + { + return new class($this->leanApiFormFactory->securityActionLogSaveContext($request)) implements RoutingMapRoutes { + + public readonly ServerRequestInterface $request; + + public function __construct( + public readonly Form\Security\ActionLogContext $context, + ) {} + + public function execute(Routing $routing, ContainerInterface $container, ServerRequestInterface &$request, Route $attribute): void + { + if (in_array($request->getMethod(), [ 'PATCH', 'POST', 'PUT', 'DELETE' ])) { + $objectReflection = ObjectReflection::fromClass($attribute->class, null)->reflectClass(); + $actionLog = $objectReflection->methods[$attribute->classMethod]->getAttribute(\Lean\Api\Attribute\Security\ActionLog::class); + + if ($actionLog) { + $this->context->event = $attribute->name; + $this->context->method = $request->getMethod(); + + $request = $this->request = $request + ->withAttribute('lean-api.security-action:attribute', $actionLog->object) + ->withAttribute('lean-api.security-action:context', $this->context); + } + } + } + }; + } +} diff --git a/src/Middleware/Security/CORSMiddleware.php b/src/Middleware/Security/CORSMiddleware.php new file mode 100644 index 0000000..934855a --- /dev/null +++ b/src/Middleware/Security/CORSMiddleware.php @@ -0,0 +1,22 @@ +cors->fromResponse($handler->handle($request)); + } +} diff --git a/src/Middleware/Security/CSRFMiddleware.php b/src/Middleware/Security/CSRFMiddleware.php new file mode 100644 index 0000000..ffe8421 --- /dev/null +++ b/src/Middleware/Security/CSRFMiddleware.php @@ -0,0 +1,26 @@ +getHeaderLine('Content-Type'), 'json') && ! getenv('LEAN_API_DISABLE_CSRF')) { + $this->csrfController->validate($request, ['token' => $request->getHeaderLine('X-CSRF-Token')]); + } + + return $handler->handle($request); + } +} diff --git a/src/Middleware/Security/RequestLogMiddleware.php b/src/Middleware/Security/RequestLogMiddleware.php new file mode 100644 index 0000000..4dc8599 --- /dev/null +++ b/src/Middleware/Security/RequestLogMiddleware.php @@ -0,0 +1,33 @@ +handle($request); + + # Skip 404 + if ($response->getStatusCode() < 400 || $response->getStatusCode() >= 500) { + try { + if ( str_contains($response->getHeaderLine('Content-Type'), 'json') ) { + $this->requestLogController->add($request, [ 'response' => $response ]); + } + } + catch(\Throwable $ex) {} + } + + return $response; + } +} diff --git a/src/Middleware/SecurityMiddleware.php b/src/Middleware/SecurityMiddleware.php new file mode 100644 index 0000000..286dc12 --- /dev/null +++ b/src/Middleware/SecurityMiddleware.php @@ -0,0 +1,31 @@ +handle($request); + + try { + if ( str_contains($response->getHeaderLine('Content-Type'), 'json') ) { + $this->requestLogController->add($request, [ 'response' => $response ]); + } + } + catch(\Throwable $ex) {} + + return $response; + } +} diff --git a/view/lean-api/request_debugger.phtml b/view/lean-api/request_debugger.phtml index 6a3e8b4..488a128 100644 --- a/view/lean-api/request_debugger.phtml +++ b/view/lean-api/request_debugger.phtml @@ -156,31 +156,30 @@ } launchRequest(requestMethod, input.value, editor.getValue()) - .then((response) => { - responseHead.querySelector('.response-code').innerText = response.status; - responseHead.querySelector('.response-message').innerText = response.statusText; + .then((response) => { + responseHead.querySelector('.response-code').innerText = response.status; + responseHead.querySelector('.response-message').innerText = response.statusText; - aceMode = parseContentType(response); + aceMode = parseContentType(response); - return response.text(); - }) - .then(body => { - if (aceMode === "json") { - body = JSON.stringify(JSON.parse(body), null, 2); + return response.text(); + }) + .then(body => { + if (aceMode === "json") { + body = JSON.stringify(JSON.parse(body), null, 2); + responseEditorElement.innerHTML = DOMEncode(body); + } + else if (aceMode === "html") { + let b64 = btoa(unescape(encodeURIComponent(body))); - responseEditorElement.innerHTML = DOMEncode(body); - } - else if (aceMode === "html") { - let b64 = btoa(unescape(encodeURIComponent(body))); + responseEditorElement.innerHTML = `` + } + else { + responseEditorElement.innerText = body; + } - responseEditorElement.innerHTML = `` - } - else { - responseEditorElement.innerText = body; - } - - formatResponse("ace/mode/" + aceMode); - }).finally(() => requestDebugger.classList.remove("loading")); + formatResponse("ace/mode/" + aceMode); + }).finally(() => requestDebugger.classList.remove("loading")); responseResponse.classList.toggle('hide', false); }); @@ -197,13 +196,41 @@ } }); + async function fetchCSRFToken() { + let headers = { + "Content-Type": "application/json" + }; + + if (token.value) { + headers['X-CSRF-Token'] = token.value; + } + + let responseData = { + method: "GET", + mode: "cors", + cache: "no-cache", + credentials: "same-origin", + headers: headers, + redirect: "follow", + referrerPolicy: "no-referrer" + }; + + let fetching = await fetch("{% route 'lean.api:security-csrf-generate' %}", responseData).then(j => j.json()) + + if (fetching.data.token === undefined) { + throw new Error("An error occured trying to fetch a CSRF token."); + } + + return fetching.data.token; + } + async function launchRequest(method = "POST", url = "", body = "{}") { let headers = { "Content-Type": "application/json" }; if (token.value) { - headers['Authorization'] = `Bearer ${token.value}`; + headers['X-CSRF-Token'] = token.value; } method = method.toUpperCase(); @@ -212,14 +239,15 @@ method: method, mode: "cors", cache: "no-cache", - credentials: headers.Authorization ? "omit" : "same-origin", + credentials: "same-origin", headers: headers, redirect: "follow", referrerPolicy: "no-referrer" }; - if ( [ "HEAD", "GET" ].indexOf(method) === -1 ) { + if ( [ "HEAD", "GET", "OPTIONS", "TRACE", "CONNECT" ].indexOf(method) === -1 ) { responseData.body = body; + responseData.headers['X-CSRF-Token'] = await fetchCSRFToken(); } requestDebugger.classList.add("loading");