Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Classes/Configuration/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@

class Configuration
{
public const DEFAULT_FILE_TOKEN_LIFETIME = 86400;

public const MAXIMUM_FILE_TOKEN_LIFETIME = 315360000;

public static function getOperationHandlers(): array
{
return self::getClassNamesSortedByPriority($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['t3api']['operationHandlers']);
Expand All @@ -29,6 +33,20 @@ public static function getCors(): array
return $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['t3api']['cors'];
}

/**
* Lifetime of file tokens in seconds (`fileToken.lifetime`) - an invalid value (not a positive number) falls back
* to the default, a value above 10 years is limited to 10 years.
*/
public static function getFileTokenLifetime(): int
{
$lifetime = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['t3api']['fileToken']['lifetime'] ?? null;
if (!is_numeric($lifetime) || (int)$lifetime <= 0) {
return self::DEFAULT_FILE_TOKEN_LIFETIME;
}

return min((int)$lifetime, self::MAXIMUM_FILE_TOKEN_LIFETIME);
}

protected static function getClassNamesSortedByPriority(?array $items): array
{
$items = $items ?? [];
Expand Down
16 changes: 16 additions & 0 deletions Classes/Dispatcher/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use SourceBroker\T3api\Exception\InternalServerErrorException;
use SourceBroker\T3api\Serializer\ContextBuilder\DeserializationContextBuilder;
use SourceBroker\T3api\Serializer\ContextBuilder\SerializationContextBuilder;
use SourceBroker\T3api\Service\FileTokenServiceTrait;
use SourceBroker\T3api\Service\OperationResponseCache;
use SourceBroker\T3api\Service\RequestLanguageService;
use SourceBroker\T3api\Service\RouteService;
Expand All @@ -32,6 +33,7 @@
class Bootstrap extends AbstractDispatcher implements LoggerAwareInterface
{
use LoggerAwareTrait;
use FileTokenServiceTrait;

protected ResponseInterface $response;

Expand Down Expand Up @@ -61,6 +63,20 @@ public function __construct(
* @throws \Throwable
*/
public function process(ServerRequestInterface $inputRequest): ResponseInterface
{
// Granted files and issued file tokens belong to one request (also when PHP process serves many requests)
$this->getFileTokenService()->reset();
try {
return $this->processRequest($inputRequest);
} finally {
$this->getFileTokenService()->reset();
}
}

/**
* @throws \Throwable
*/
protected function processRequest(ServerRequestInterface $inputRequest): ResponseInterface
{
try {
$request = $this->httpFoundationFactory->createRequest($inputRequest);
Expand Down
27 changes: 5 additions & 22 deletions Classes/Serializer/Handler/AbstractDomainObjectHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@
use SourceBroker\T3api\Service\PropertyInfoService;
use SourceBroker\T3api\Service\SerializerService;
use TYPO3\CMS\Extbase\DomainObject\AbstractDomainObject;
use TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy;
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;

class AbstractDomainObjectHandler extends AbstractHandler implements DeserializeHandlerInterface
{
Expand Down Expand Up @@ -203,25 +201,10 @@ private function isObjectInContextScope(
return $assignable;
}

$property = $parentObject->_getCleanProperty($propertyMetadata->name);

// Compared by UID - the related object may be an instance of another class (e.g. an API resource class
// declared as `type` in YAML metadata) than the one in the relation.
if ($property instanceof ObjectStorage) {
foreach ($property as $relatedObject) {
if ($relatedObject instanceof AbstractDomainObject && $relatedObject->getUid() === $object->getUid()) {
return true;
}
}

return false;
}

// `LazyLoadingProxy::getUid()` does not load the related object.
if ($property instanceof AbstractDomainObject || $property instanceof LazyLoadingProxy) {
return $object->getUid() === $property->getUid();
}

return false;
return in_array(
(int)$object->getUid(),
$this->getInlineRelationService()->getCleanRelationUids($parentObject, $propertyMetadata->name),
true
);
}
}
111 changes: 107 additions & 4 deletions Classes/Serializer/Handler/FileReferenceHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@

use JMS\Serializer\DeserializationContext;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\Visitor\DeserializationVisitorInterface;
use JMS\Serializer\Visitor\SerializationVisitorInterface;
use SourceBroker\T3api\Exception\BadRequestException;
use SourceBroker\T3api\Exception\ValidationException;
use SourceBroker\T3api\Serializer\Subscriber\FileTokenSubscriber;
use SourceBroker\T3api\Service\FileReferenceService;
use SourceBroker\T3api\Service\FileTokenServiceTrait;
use SourceBroker\T3api\Service\SerializerService;
use SourceBroker\T3api\Service\UrlService;
use TYPO3\CMS\Core\Resource\FileReference as Typo3FileReference;
Expand All @@ -32,6 +35,7 @@
class FileReferenceHandler extends AbstractHandler implements SerializeHandlerInterface, DeserializeHandlerInterface
{
use InlineRelationServiceTrait;
use FileTokenServiceTrait;

/**
* @var string
Expand Down Expand Up @@ -77,6 +81,11 @@ public function serialize(
$out['file']['name'] = $originalFile->getName();
$out['file']['mimeType'] = $originalFile->getMimeType();
$out['file']['size'] = $originalFile->getSize();
$fileToken = $this->getFileTokenService()
->getTokenForResponse((int)$originalFile->getUid(), FileTokenSubscriber::isEnabledForAllFiles($context));
if ($fileToken !== null) {
$out['file']['fileToken'] = $fileToken;
}

if (preg_match('#video/.*#', $originalFile->getMimeType())) {
$fileRenderer = GeneralUtility::makeInstance(RendererRegistry::class)->getRenderer($originalFile);
Expand Down Expand Up @@ -127,7 +136,7 @@ public function deserialize(

if (
!is_subclass_of($type['params']['targetType'], Folder::class)
&& !is_subclass_of($type['params']['targetType'], File::class)
&& !is_a($type['params']['targetType'], File::class, true)
&& !is_subclass_of($type['params']['targetType'], FileReference::class)
) {
throw new \RuntimeException(
Expand All @@ -150,21 +159,35 @@ public function deserialize(
return null;
}

// Also Extbase's `File` itself - it is mapped to `sys_file` as well
if (is_a($type['params']['targetType'], File::class, true)) {
return $this->deserializeFile($data, $type['params']['targetType'], $context);
}

if (!is_numeric($data) && !is_array($data)) {
throw $this->createInvalidRelationException($data, $context, 1793700006);
}

$isNew = is_array($data) && empty($data['uid']);

if ($isNew) {
// Checked here, not in `createSysFileReference()`, so the check is kept when the method is overridden
if (!empty($data['uidLocal'])) {
$this->assertFileToken((int)$data['uidLocal'], $data['fileToken'] ?? null);
}

return $this->createSysFileReference($data, $type['params']['targetType'], $context);
}

$uid = (int)(is_numeric($data) ? $data : $data['uid']);
$uid = is_numeric($data) ? (int)$data : (is_numeric($data['uid']) ? (int)$data['uid'] : 0);

if ($uid > 0) {
$fileReference = $this->persistenceManager->getObjectByIdentifier(
$uid,
ExtbaseFileReference::class,
false
);
// @todo `File` and `Folder` properties are looked up as file references as well - kept unchanged here
// @todo `Folder` properties are looked up as file references as well - kept unchanged here
if (!is_subclass_of($type['params']['targetType'], FileReference::class)) {
return $fileReference;
}
Expand All @@ -179,7 +202,67 @@ public function deserialize(

return $fileReference;
}
return null;

throw $this->createInvalidRelationException($data, $context, 1793700007);
}

/**
* A property with a file (`sys_file`, not a reference) keeps its current file(s); another file can be set only
* with the token returned for it by the API: `{"uid": 15, "fileToken": "..."}`.
*
* @throws ValidationException
* @throws BadRequestException
*/
protected function deserializeFile(mixed $data, string $targetType, DeserializationContext $context): File
{
$fileUid = match (true) {
is_numeric($data) => (int)$data,
is_array($data) && is_numeric($data['uid'] ?? null) => (int)$data['uid'],
default => 0,
};
if ($fileUid <= 0) {
throw $this->createInvalidRelationException($data, $context, 1793700005);
}

if (!in_array($fileUid, $this->getCurrentFileUids($context), true)) {
$this->assertFileToken($fileUid, is_array($data) ? ($data['fileToken'] ?? null) : null);
}

$file = $this->persistenceManager->getObjectByIdentifier($fileUid, $targetType, false);
if (!$file instanceof File) {
throw new BadRequestException(
'relation_not_found',
[(string)$fileUid, implode('.', $context->getCurrentPath())],
1793700004
);
}

return $file;
}

/**
* UIDs of the files of the deserialized property as loaded from the database.
*
* @return int[]
*/
protected function getCurrentFileUids(DeserializationContext $context): array
{
$parent = $this->getInlineRelationService()->getContextParent($context);
$metadataStack = $context->getMetadataStack();
$propertyMetadata = $metadataStack->isEmpty() ? null : $metadataStack->top();

return $parent !== null && $propertyMetadata instanceof PropertyMetadata
? $this->getInlineRelationService()->getCleanRelationUids($parent, $propertyMetadata->name)
: [];
}

protected function createInvalidRelationException(mixed $data, DeserializationContext $context, int $code): BadRequestException
{
return new BadRequestException(
'invalid_relation',
[gettype($data), implode('.', $context->getCurrentPath())],
$code
);
}

/**
Expand Down Expand Up @@ -230,6 +313,26 @@ protected function createSysFileReference(
return $fileReference;
}

/**
* A new reference requires the token returned for the file by the API (upload response, operation offering files
* with `fileTokens`).
*
* @throws ValidationException
*/
protected function assertFileToken(int $fileUid, mixed $fileToken): void
{
if (is_string($fileToken) && $fileToken !== '' && $this->getFileTokenService()->isValidToken($fileToken, $fileUid)) {
return;
}

$result = new Result();
$result->forProperty('fileToken')->addError(
new Error('Property `fileToken` is missing or invalid - use the token returned for the file by the API', 1793700002)
);

throw new ValidationException($result, 1793700003);
}

/**
* Removes already existing file reference if property is not a collection but relation to single file
*/
Expand Down
8 changes: 7 additions & 1 deletion Classes/Serializer/Subscriber/FileReferenceSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ public static function getSubscribedEvents(): array
*/
public function onPreSerialize(PreSerializeEvent $event): void
{
// A file (not a reference) is serialized like any other object, also in collections and relations - the same
// output as for an item operation, with `fileToken` added by `FileTokenSubscriber`.
if (is_a($event->getType()['name'], File::class, true)) {
return;
}

$this->changeTypeToHandleAllFileReferenceExtendingClasses($event);
}

Expand All @@ -54,7 +60,7 @@ protected function changeTypeToHandleAllFileReferenceExtendingClasses(Event $eve
if (
(
is_subclass_of($event->getType()['name'], Folder::class)
|| is_subclass_of($event->getType()['name'], File::class)
|| is_a($event->getType()['name'], File::class, true)
|| is_subclass_of($event->getType()['name'], FileReference::class)
)
&& $event->getContext()->getDepth() > 1
Expand Down
Loading
Loading