- 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.
This commit is contained in:
Dave Mc Nicoll committed 2026-10-22 15:03:18 +00:00
1 parent 9571c6a462
commit 4b86ac9e82
42 files changed
+1283 -100

No files matched your search

+4 -10
View File
@@ -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),
];
+21
View File
@@ -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}
+21
View File
@@ -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}
+21
View File
@@ -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}
+2 -2
View File
@@ -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);
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace Lean\Api\Attribute\Security;
#[\Attribute(\Attribute::TARGET_METHOD)]
class ActionLog
{
public function __construct(
#public string $key,
) {}
}
-1
View File
@@ -13,7 +13,6 @@ use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
## [Taxus(Entity\UserTypeEnum::Developer)]
#[RouteObj(base: "/lean/debug/errors")]
class Errors {
use \Lean\Api\Lib\ControllerTrait;
#[Route("/documentation", name: "lean.api:errors-doc", method: "GET", description: "Documentation section")]
@@ -10,14 +10,13 @@ use Notes\Security\Attribute\Taxus;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
#[Security(locked: false)]
#[RouteObj(base: "/lean/debug")]
class Debug {
#[RouteObj(base: "/lean")]
class LeanApi {
use \Lean\Api\Lib\ControllerTrait;
#[Route("/", name: "lean.api:debug-doc", method: "GET", description: "Documentation section")]
#[Route("/", name: "lean.api:doc", method: "GET", description: "Documentation section")]
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
{
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/lean-api.md", [ Entity\Error::class, ], [ Form\Debug\ErrorContext::class ]);
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/lean-api.md", [ ], [ ]);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace Lean\Api\Controller\Security;
use DI\Attribute\Inject;
use CSSLSJ\TransportScolaire\Api\{Entity, Form};
use Notes\Route\Attribute\Method\Route;
use Notes\Security\Attribute\Security;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
use Ulmus\User\Entity\UserInterface;
#[Security(locked: true)]
##[Taxus(Entity\UserTypeEnum::Developer)]
#[\Notes\Route\Attribute\Object\Route(base: "/lean/security/action-logs")]
class ActionLog {
use \Lean\Api\Lib\ControllerTrait;
#[Inject]
protected UserInterface $user;
#[Route("/documentation", name: "lean.api:security-action-log-doc", method: "GET", description: "Route de documentation pour cette section")]
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
{
return $this->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());
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace Lean\Api\Controller\Security;
use DI\Attribute\Inject;
use CSSLSJ\TransportScolaire\Api\{Entity, Form};
use Notes\Route\Attribute\Method\Route;
use Notes\Security\Attribute\Security;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
use Ulmus\User\Entity\UserInterface;
#[Security(locked: true)]
##[Taxus(Entity\UserTypeEnum::Developer)]
#[\Notes\Route\Attribute\Object\Route(base: "/lean/security/csrf")]
class CSRF {
use \Lean\Api\Lib\ControllerTrait;
#[Inject]
protected UserInterface $user;
#[Route("/documentation", name: "lean.api:security-csrf-doc", method: "GET", description: "Route de documentation pour cette section")]
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
{
return $this->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;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Lean\Api\Controller\Security;
use DI\Attribute\Inject;
use CSSLSJ\TransportScolaire\Api\{Entity, Form};
use Notes\Route\Attribute\Method\Route;
use Notes\Security\Attribute\Security;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
use Ulmus\User\Entity\UserInterface;
#[Security(locked: true)]
##[Taxus(Entity\UserTypeEnum::Developer)]
#[\Notes\Route\Attribute\Object\Route(base: "/lean/security/request-logs")]
class RequestLog {
use \Lean\Api\Lib\ControllerTrait;
#[Inject]
protected UserInterface $user;
#[Route("/documentation", name: "lean.api:security-request-log-doc", method: "GET", description: "Route de documentation pour cette section")]
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
{
return $this->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());
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace Lean\Api\Cronard;
use CSSLSJ\TransportScolaire\Api\{Controller\Api, Entity, Form, Lib};
use Notes\Breadcrumb\Attribute\Method\Breadcrumb;
use Notes\Cronard\Attribute\Method\Cronard;
use Notes\Route\Attribute\Method\Route;
use Notes\Route\Attribute\Object\Route as RouteObj;
use Notes\Security\Attribute\Taxus;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
use Storage\{Cookie, Session};
use TheBugs\Email\MailerInterface;
use function CSSLSJ\TransportScolaire\Api\View\{form, route};
##[Taxus(Entity\UserTypeEnum::Developer)]
#[RouteObj(base: "/lean/cronard")]
class System {
use Lib\ControllerTrait;
#[Route("/", name: "lean-api.cronard:documentation", method: "GET", description: "Route de documentation pour cette section")]
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
{
return $this->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);
}
}
+101
View File
@@ -0,0 +1,101 @@
<?php
namespace Lean\Api\Entity\Security;
use Lean\Api\Attribute\EntityField;
use Notes\Attribute\Ignore;
use Ulmus\Attribute\Obj\Table;
use Ulmus\Attribute\Property\{Field, Filter, FilterJoin, OrderBy, Relation, Join, Virtual, Where};
use Ulmus\Common\Sql;
use Ulmus\Entity\EntityInterface;
use Ulmus\Repository;
use Ulmus\User\Entity\UserInterface;
use Ulmus\SearchRequest;
#[Table(name: "lean_api_security_action_logs", adapter: "lean.api")]
class ApiActionLog implements EntityInterface, \JsonSerializable
{
use \Ulmus\EntityTrait;
#[Field\Id(name: "id")]
public int $id;
#[Field\ForeignKey(name: "object_id"), EntityField(field: "object_id")]
public int $objectId;
#[Field(name: "object_type"), EntityField(field: "object_type")]
public string $objectType;
#[Field\ForeignKey(name: "user_id"), EntityField(field: "user_id")]
public ? int $userId;
#[Field(name: "user_type", length: 100), EntityField(field: "user_type")]
public ? string $userType;
#[Field(name: "event", length: 100), EntityField]
public string $event;
#[Field(name: "method", length: 15), EntityField]
public string $method;
#[Field(name: "description"), EntityField]
public ? string $description;
#[Field(name: "data"), EntityField]
public array $data;
#[Field(name: "created_at")]
public \Ulmus\Entity\Field\Datetime $createdAt;
#[Relation("oneToOne", key: "user", foreignKey: "id")]
public UserInterface $userEntity;
public function getUser() : ? UserInterface
{
}
public function getHash() : string
{
return md5(sprintf("%d:%s", $this->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;
}
};
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
namespace Lean\Api\Entity\Security;
use Lean\Api\Entity\Field\Datetime;
use Lean\Api\Lib;
use Lean\Api\Attribute\EntityField;
use Notes\Attribute\Ignore;
use Ulmus\Attribute\Obj\Table;
use Ulmus\Attribute\Property\{Field};
use Ulmus\Entity\EntityInterface;
use Ulmus\SearchRequest;
#[Table(name: "lean_api_security_request_logs", adapter: "lean.api")]
class ApiRequestLog implements EntityInterface, \JsonSerializable
{
use \Ulmus\EntityTrait;
#[Field\PrimaryKey]
public int $id;
#[Field\ForeignKey(name: "user_id")]
#[EntityField(description: "ID de l'usagé (lorsque connecté) qui a lancé la requête", field: 'user_id')]
public ? int $userId = null;
#[Field(length: 10)]
#[EntityField(description: "Method HTTP")]
public string $method;
#[Field(length: 255)]
#[EntityField(description: "URI sans les paramètres")]
public string $endpoint;
#[Field(length: 15)]
#[EntityField(description: "IPv4 de l'usagé")]
public ? string $ipv4;
#[Field(length: 45)]
#[EntityField(description: "IPv6 de l'usagé")]
public ? string $ipv6;
#[Field(name: "request_headers")]
#[EntityField(field: "request_headers")]
public array $requestHeaders = [];
#[Field(name: "request_body")]
#[EntityField(field: "request_body")]
public array $requestBody = [];
#[Field(name: "status_code")]
#[EntityField(field: "status_code")]
public int $statusCode;
#[Field(name: "response_headers")]
#[EntityField(field: "response_headers")]
public array $responseHeaders = [];
#[Field(name: "response_body")]
#[EntityField(field: "response_body")]
public ? string $responseBody;
#[Field]
#[EntityField(field: "duration")]
public float $duration;
#[Field\UpdatedAt(name: "updated_at", readonly: true)]
#[EntityField(description: "Date de la dernière mise-à-jour pour cette donnée.")]
public ? Datetime $updatedAt;
#[Field\CreatedAt(name: "created_at", readonly: true)]
#[EntityField(description: "Date de création pour cette donnée.")]
public Datetime $createdAt;
#[Ignore]
public static function searchRequest(...$arguments) : SearchRequest\SearchRequestInterface
{
return new #[SearchRequest\Attribute\SearchRequestParameter(ApiRequestLog::class,)] class(... $arguments) extends SearchRequest\SearchRequest {
#[SearchRequest\Attribute\SearchWhere(parameter: 'id', description: "Récupère une requete par son id unique.", source: SearchRequest\Attribute\PropertyValueSource::RequestAttribute)]
public string $id;
#[SearchRequest\Attribute\SearchOrderBy(field: "createdAt")]
public string $orderByDate = "DESC";
#[SearchRequest\Attribute\SearchManual]
public int $page = 1;
#[SearchRequest\Attribute\SearchManual]
public int $limit = 50;
};
}
}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace Lean\Api\Exception;
class CSRFInvalidToken extends \Exception {}
+5
View File
@@ -0,0 +1,5 @@
<?php
namespace Lean\Api\Exception;
class CSRFMissingToken extends \Exception {}
-21
View File
@@ -1,21 +0,0 @@
<?php
namespace Lean\Api\Factory;
use Picea\Ui\Method\FormContextInterface;
use Picea\Ui\Method\FormInterface;
use Psr\Http\Message\ServerRequestInterface;
use Lean\LanguageHandler;
use Ulmus\Entity\EntityInterface;
use Lean\Api\Entity;
interface DebugFormFactoryInterface
{
public function __construct(ServerRequestInterface $request, LanguageHandler $languageHandler, MessageFactoryInterface $messageFactory,);
### ERROR SAVE
public function errorSave(Entity\Error|EntityInterface $entity): FormInterface;
public function errorSaveContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
public function errorDelete(Entity\Error|EntityInterface $entity): FormInterface;
public function errorDeleteContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
}
@@ -1,21 +1,14 @@
<?php
namespace Lean\Api\Factory;
namespace Lean\Api\Factory\FormFactories;
use Lean\Api\{Factory, Form, Entity, Lib};
use Lean\LanguageHandler;
use Picea\Ui\Method\FormContextInterface;
use Picea\Ui\Method\FormInterface;
use Psr\Http\Message\ServerRequestInterface;
use Ulmus\Entity\EntityInterface;
use Lean\Api\{Factory, Form, Entity, Lib};
class DebugFormFactory implements DebugFormFactoryInterface
{
public function __construct(
protected ServerRequestInterface $request,
protected LanguageHandler $languageHandler,
protected MessageFactoryInterface $messageFactory,
) {}
trait DebugTrait{
public function errorSave(EntityInterface|Entity\Error $entity): FormInterface
{
@@ -0,0 +1,53 @@
<?php
namespace Lean\Api\Factory\FormFactories;
use Picea\Ui\Method\FormContextInterface;
use Picea\Ui\Method\FormInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Ulmus\Entity\EntityInterface;
use Ulmus\User\Entity\UserInterface;
trait SecurityTrait
{
public function securityRequestLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiRequestLog $entity, ResponseInterface $response, UserInterface $user): FormInterface
{
return new \Lean\Api\Form\Security\SaveRequestLog($this->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);
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace Lean\Api\Factory;
use Lean\Api\Entity;
class LeanApiEntityFactory
{
public function __construct(
public string $error = Entity\Error::class,
public string $securityApiActionLog = Entity\Security\ApiActionLog::class,
public string $securityRequestLog = Entity\Security\ApiRequestLog::class,
) {}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace Lean\Api\Factory;
use DI\Attribute\Inject;
use Lean\LanguageHandler;
use Psr\Http\Message\ServerRequestInterface;
class LeanApiFormFactory implements LeanApiFormFactoryInterface
{
use FormFactories\DebugTrait, FormFactories\SecurityTrait;
#[Inject]
protected ServerRequestInterface $request;
#[Inject]
protected LanguageHandler $languageHandler;
#[Inject]
protected MessageFactoryInterface $messageFactory;
}
@@ -0,0 +1,32 @@
<?php
namespace Lean\Api\Factory;
use Picea\Ui\Method\FormContextInterface;
use Picea\Ui\Method\FormInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Ulmus\Entity\EntityInterface;
use Lean\Api\Entity;
use Ulmus\User\Entity\UserInterface;
interface LeanApiFormFactoryInterface
{
### SECURITY / REQUEST LOGS
public function securityRequestLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiRequestLog $entity, ResponseInterface $response, UserInterface $user): FormInterface;
public function securityRequestLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface;
### SECURITY / CSRF
public function securityCsrfGenerate(UserInterface $user): FormInterface;
public function securityCsrfGenerateContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface;
### SECURITY / ACTION LOGS
public function securityActionLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiActionLog $entity, UserInterface $user): FormInterface;
public function securityActionLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface;
### DEBUG / ERROR
public function errorSave(Entity\Error|EntityInterface $entity): FormInterface;
public function errorSaveContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
public function errorDelete(Entity\Error|EntityInterface $entity): FormInterface;
public function errorDeleteContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
}
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace Lean\Api\Form\Security;
use CSSLSJ\TransportScolaire\Api\{Entity};
use Lean\Api\Attribute\ContextField;
use Lean\Api\Lib\FormContext;
use Ulmus\Entity\EntityInterface;
use Ulmus\Event\Entity\DatasetFill;
use Ulmus\Ulmus;
#[ContextField(description: "")]
class ActionLogContext extends FormContext
{
protected EntityInterface $entity;
#[ContextField(mandatory: true)]
public string $event;
#[ContextField(mandatory: true)]
public string $method;
#[ContextField(mandatory: true)]
public int $object_id;
#[ContextField(mandatory: true)]
public string $object_type;
#[ContextField]
public ? int $user_id;
#[ContextField]
public string $user_type;
#[ContextField]
public string $description;
#[ContextField]
public array $data = [];
private DatasetFill $datasetFillEvent;
public function attachEntity(EntityInterface $entity) : void
{
$this->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);
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace Lean\Api\Form\Security;
use Lean\Api\{Entity};
use Lean\Api\Factory\MessageFactoryInterface;
use Lean\LanguageHandler;
use Picea\Ui\Method\FormContextInterface;
use Psr\Http\Message\ResponseInterface;
use Ulmus\User\Entity\UserInterface;
class CsrfGenerate extends \Lean\Api\Form\Save
{
protected string $contextClass = CsrfGenerateContext::class;
public function __construct(
protected LanguageHandler $languageHandler,
protected MessageFactoryInterface $message,
protected UserInterface $entity,
protected int $expires = (10 * 60), # 10 minutes
)
{
parent::__construct($this->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();
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Lean\Api\Form\Security;
use CSSLSJ\TransportScolaire\Api\{Entity};
use Lean\Api\Attribute\ContextField;
use Lean\Api\Exception\CSRFMissingToken;
use Lean\Api\Lib\FormContext;
use Ulmus\User\Entity\UserInterface;
#[ContextField(description: "")]
class CsrfGenerateContext extends FormContext
{
public function valid(? UserInterface $user = null): bool
{
return parent::valid();
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace Lean\Api\Form\Security;
use Lean\Api\{Entity};
use Lean\Api\Factory\MessageFactoryInterface;
use Lean\LanguageHandler;
use Picea\Ui\Method\FormContextInterface;
use Psr\Http\Message\ResponseInterface;
use Ulmus\User\Authorize\Bearer\JsonWebTokenDecoder;
use Ulmus\User\Entity\UserInterface;
class CsrfVerifyToken extends \Lean\Api\Form\Save
{
protected string $contextClass = CsrfVerifyTokenContext::class;
public function __construct(
protected LanguageHandler $languageHandler,
protected MessageFactoryInterface $message,
protected UserInterface $entity,
protected string $token,
)
{
parent::__construct($this->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;
}
}
@@ -0,0 +1,24 @@
<?php
namespace Lean\Api\Form\Security;
use CSSLSJ\TransportScolaire\Api\{Entity};
use Lean\Api\Attribute\ContextField;
use Lean\Api\Exception\CSRFMissingToken;
use Lean\Api\Lib\FormContext;
use Ulmus\User\Entity\UserInterface;
#[ContextField(description: "")]
class CsrfVerifyTokenContext extends FormContext
{
public function valid(? UserInterface $user = null): bool
{
if ( in_array($this->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();
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace Lean\Api\Form\Security;
use CSSLSJ\TransportScolaire\Api\{Entity};
use Lean\Api\Attribute\ContextField;
use Lean\Api\Lib\FormContext;
#[ContextField(description: "")]
class RequestLogContext extends FormContext
{
#[ContextField]
public ? int $user_id;
#[ContextField]
public string $method;
#[ContextField]
public string $endpoint;
#[ContextField]
public string $ipv4;
#[ContextField]
public string $ipv6;
#[ContextField]
public array $request_headers;
#[ContextField]
public array $request_body;
#[ContextField]
public int $status_code;
#[ContextField]
public array $response_headers;
#[ContextField]
public string $response_body;
#[ContextField]
public float $duration;
public function valid(? \Lean\Api\Entity\Security\ApiRequestLog $requestLog = null): bool
{
return parent::valid();
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace Lean\Api\Form\Security;
use Lean\Api\{Attribute\Action, Entity};
use Lean\Api\Factory\MessageFactoryInterface;
use Lean\LanguageHandler;
use Picea\Ui\Method\FormContextInterface;
use Psr\Http\Message\ResponseInterface;
use Ulmus\User\Entity\UserInterface;
class SaveActionLog extends \Lean\Api\Form\Save
{
protected string $contextClass = ActionLogContext::class;
public function __construct(
protected LanguageHandler $languageHandler,
protected MessageFactoryInterface $message,
protected Entity\Security\ApiActionLog $entity,
protected UserInterface $user,
)
{
parent::__construct($this->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;
}
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace Lean\Api\Form\Security;
use Lean\Api\{Entity};
use Lean\Api\Factory\MessageFactoryInterface;
use Lean\LanguageHandler;
use Picea\Ui\Method\FormContextInterface;
use Psr\Http\Message\ResponseInterface;
use Ulmus\User\Entity\UserInterface;
class SaveRequestLog extends \Lean\Api\Form\Save
{
public function __construct(
protected LanguageHandler $languageHandler,
protected MessageFactoryInterface $message,
protected Entity\Security\ApiRequestLog $entity,
protected ResponseInterface $response,
protected UserInterface $user,
)
{
parent::__construct($this->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'];
}
}
+38 -24
View File
@@ -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 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())));
}
@@ -125,7 +127,9 @@ trait LeanApiTrait
public function __construct(
public readonly SearchRequestInterface $search,
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);
}
}
}
+9
View File
@@ -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;
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace Lean\Api\Lib;
use Lean\Api\Factory\MessageFactoryInterface;
use Lean\LanguageHandler;
use Psr\Http\Message\ServerRequestInterface;
use Ulmus\Entity\EntityInterface;
class DeleteFormContext extends FormContext
{
public function valid(? EntityInterface $entity = null) : bool
{
if ( $entity === null ) {
$this->pushErrorMessage('lean.api.form.delete.error.entity');
}
return parent::valid();
}
}
+27 -13
View File
@@ -11,37 +11,38 @@ class RenderCORS
{
public function __construct(
protected ServerRequestInterface $request,
public string|array $origin = "http://localhost,https://localhost",
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 $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;
}
}
+8 -10
View File
@@ -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,7 +65,7 @@ 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(),
@@ -76,7 +75,7 @@ class ApiRenderer implements MiddlewareInterface {
'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);
}
}
+1
View File
@@ -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
{
@@ -0,0 +1,87 @@
<?php
namespace Lean\Api\Middleware\Security;
use Lean\Api\Controller\Security\ActionLog;
use Lean\Api\Factory\LeanApiFormFactoryInterface;
use Lean\Api\Form;
use DI\Attribute\Inject;
use Lean\Event\RoutingMapRoutes;
use Lean\Routing;
use Mcnd\Event\EventManager;
use Notes\ObjectReflection;
use Notes\ObjectResolver;
use Notes\Route\Attribute\Method\Route;
use Picea\Ui\Method\FormContextInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class ActionLogMiddleware implements MiddlewareInterface {
#[Inject]
protected readonly LeanApiFormFactoryInterface $leanApiFormFactory;
#[Inject]
protected readonly ActionLog $actionLogController;
#[Inject]
protected readonly EventManager $eventManager;
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
$eventHandler = $this->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);
}
}
}
};
}
}
@@ -0,0 +1,22 @@
<?php
namespace Lean\Api\Middleware\Security;
use Lean\Api\Lib\RenderCORS;
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 CORSMiddleware implements MiddlewareInterface
{
public function __construct(
protected RenderCORS $cors,
) {}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
return $this->cors->fromResponse($handler->handle($request));
}
}
@@ -0,0 +1,26 @@
<?php
namespace Lean\Api\Middleware\Security;
use Lean\Api\Controller\Security\CSRF;
use DI\Attribute\Inject;
use Lean\Api\Exception\{ CSRFMissingToken, CSRFInvalidToken };
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class CSRFMiddleware implements MiddlewareInterface {
#[Inject]
protected CSRF $csrfController;
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
if ( str_contains($request->getHeaderLine('Content-Type'), 'json') && ! getenv('LEAN_API_DISABLE_CSRF')) {
$this->csrfController->validate($request, ['token' => $request->getHeaderLine('X-CSRF-Token')]);
}
return $handler->handle($request);
}
}
@@ -0,0 +1,33 @@
<?php
namespace Lean\Api\Middleware\Security;
use Lean\Api\Controller\Security\RequestLog;
use DI\Attribute\Inject;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
class RequestLogMiddleware implements MiddlewareInterface {
#[Inject]
protected RequestLog $requestLogController;
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
$response = $handler->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;
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace Lean\Api\Middleware;
use Lean\Api\Controller\Security\RequestLog;
use DI\Attribute\Inject;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
#[\Deprecated]
class SecurityMiddleware implements MiddlewareInterface {
#[Inject]
protected RequestLog $requestLogController;
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
$response = $handler->handle($request);
try {
if ( str_contains($response->getHeaderLine('Content-Type'), 'json') ) {
$this->requestLogController->add($request, [ 'response' => $response ]);
}
}
catch(\Throwable $ex) {}
return $response;
}
}
+32 -4
View File
@@ -167,7 +167,6 @@
.then(body => {
if (aceMode === "json") {
body = JSON.stringify(JSON.parse(body), null, 2);
responseEditorElement.innerHTML = DOMEncode(body);
}
else if (aceMode === "html") {
@@ -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");