Skip to content

Commit

Permalink
add test; ensure metaData is serialized as json object; update authz …
Browse files Browse the repository at this point in the history
…policies
  • Loading branch information
tobiasgv committed Nov 28, 2024
1 parent 60433f5 commit 748814a
Show file tree
Hide file tree
Showing 9 changed files with 141 additions and 62 deletions.
2 changes: 1 addition & 1 deletion src/Authorization/AuthorizationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ public function denyAccessUnlessHasRoleUser(): void

public function hasRoleUser(): bool
{
return $this->isGranted(Configuration::ROLE_USER);
return $this->isGrantedRole(Configuration::ROLE_USER);
}
}
2 changes: 1 addition & 1 deletion src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function getConfigTreeBuilder(): TreeBuilder
$treeBuilder = new TreeBuilder('dbp_relay_blob_connector_campusonline_dms');
$treeBuilder->getRootNode()
->append(AuthorizationConfigDefinition::create()
->addPolicy(self::ROLE_USER, 'false', 'Returns true if the current user is authorized to use the API')
->addRole(self::ROLE_USER, 'false', 'Returns true if the current user is authorized to use the API')
->getNodeDefinition());

return $treeBuilder;
Expand Down
9 changes: 8 additions & 1 deletion src/Entity/Document.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
use Dbp\Relay\BlobConnectorCampusonlineDmsBundle\Rest\DocumentProvider;
use Dbp\Relay\BlobConnectorCampusonlineDmsBundle\Rest\GetDocumentVersionContentController;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Attribute\Context;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

#[ApiResource(
shortName: 'BlobConnectorCampusonlineDmsDocument',
Expand Down Expand Up @@ -168,7 +171,10 @@
processor: DocumentProcessor::class
),
],
normalizationContext: ['groups' => ['BlobConnectorCampusonlineDmsDocument:output']],
normalizationContext: [
'groups' => ['BlobConnectorCampusonlineDmsDocument:output'],
AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true,
],
denormalizationContext: ['groups' => ['BlobConnectorCampusonlineDmsDocument:input']]
)]
class Document
Expand All @@ -179,6 +185,7 @@ class Document

#[ApiProperty(iris: ['https://schema.org/additionalProperty'])]
#[Groups(['BlobConnectorCampusonlineDmsDocument:output'])]
#[Context([Serializer::EMPTY_ARRAY_AS_OBJECT => true])]
private ?array $metaData = null;

#[ApiProperty(iris: ['https://schema.org/version'])]
Expand Down
9 changes: 8 additions & 1 deletion src/Entity/DocumentVersionInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
use Dbp\Relay\BlobConnectorCampusonlineDmsBundle\Rest\DeleteDocumentVersionController;
use Dbp\Relay\BlobConnectorCampusonlineDmsBundle\Rest\DocumentVersionInfoProvider;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Attribute\Context;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

#[ApiResource(
shortName: 'BlobConnectorCampusonlineDmsDocumentVersionInfo',
Expand All @@ -36,7 +39,10 @@
provider: DocumentVersionInfoProvider::class
),
],
normalizationContext: ['groups' => ['BlobConnectorCampusonlineDmsDocumentVersionInfo:output']],
normalizationContext: [
'groups' => ['BlobConnectorCampusonlineDmsDocumentVersionInfo:output'],
AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true,
],
)]
class DocumentVersionInfo
{
Expand All @@ -62,6 +68,7 @@ class DocumentVersionInfo

#[ApiProperty(iris: ['https://schema.org/additionalProperty'])]
#[Groups(['BlobConnectorCampusonlineDmsDocumentVersionInfo:output', 'BlobConnectorCampusonlineDmsDocument:output'])]
#[Context([Serializer::EMPTY_ARRAY_AS_OBJECT => true])]
private ?array $metaData = null;

public function getUid(): ?string
Expand Down
4 changes: 2 additions & 2 deletions src/Rest/CreateDocumentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function __invoke(Request $request): Document
$uploadedFile = Common::getAndValidateUploadedFile($request, 'binary_content');

$metadata = $request->request->get('metadata');
if ($metadata === null) {
if (!$metadata) {
throw new Error(Response::HTTP_BAD_REQUEST, 'parameter \'metadata\' must not be empty',
errorCode: 'REQUIRED_PARAMETER_MISSING', errorDetail: 'metadata');
}
Expand All @@ -59,7 +59,7 @@ public function __invoke(Request $request): Document

$documentVersionMetadataArray = null;
$documentVersionMetadata = $request->request->get('doc_version_metadata');
if ($documentVersionMetadata !== null) {
if ($documentVersionMetadata) {
try {
$documentVersionMetadataArray = json_decode($documentVersionMetadata, true, flags: JSON_THROW_ON_ERROR);
} catch (\JsonException) {
Expand Down
4 changes: 2 additions & 2 deletions src/Service/DocumentService.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ private function createDocumentVersion(Document $document, File $uploadedFile, s
}

try {
$metadataEncoded = json_encode($metadata, JSON_THROW_ON_ERROR);
$metadataEncoded = json_encode($metadata, JSON_THROW_ON_ERROR | JSON_FORCE_OBJECT);
} catch (\Exception $jsonException) {
throw new \RuntimeException(sprintf('encoding file metadata failed: %s', $jsonException->getMessage()));
}
Expand Down Expand Up @@ -220,7 +220,7 @@ private function createDocumentVersionInfoFromFileData(FileData $fileData, array
$documentVersionInfo->setVersionNumber($metadata[self::VERSION_NUMBER_METADATA_KEY]);
$documentVersionInfo->setMediaType($fileData->getMimeType());
$documentVersionInfo->setSize($fileData->getFileSize());
$documentVersionInfo->setMetaData($metadata[self::DOCUMENT_VERSION_METADATA_METADATA_KEY] ?? null);
$documentVersionInfo->setMetaData($metadata[self::DOCUMENT_VERSION_METADATA_METADATA_KEY] ?? []);

return $documentVersionInfo;
}
Expand Down
106 changes: 106 additions & 0 deletions tests/ApiTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

declare(strict_types=1);

namespace Dbp\Relay\BlobConnectorCampusonlineDmsBundle\Tests;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use Dbp\Relay\BlobBundle\TestUtils\TestEntityManager;
use Dbp\Relay\CoreBundle\TestUtils\TestClient;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Response;

class ApiTest extends ApiTestCase
{
private const TEST_FILE_NAME = 'test.txt';
private const TEST_FILE_PATH = __DIR__.'/'.self::TEST_FILE_NAME;
private const TEST_DOCUMENT_TYPE = 'doc_type';

private ?TestClient $testClient = null;

protected function setUp(): void
{
$this->testClient = new TestClient(self::createClient());
$this->testClient->setUpUser(userAttributes: ['MAY_USE_CO_DMS_API' => true]);
$this->testClient->getClient()->disableReboot();
TestEntityManager::setUpEntityManager($this->testClient->getContainer());
}

public function testCreateDocument(): void
{
$file = new UploadedFile(self::TEST_FILE_PATH, self::TEST_FILE_NAME);
$response = $this->testClient->request('POST', '/co-dms-api/api/documents', [
'headers' => [
'Content-Type' => 'multipart/form-data',
'Accept' => 'application/json',
],
'extra' => [
'files' => [
'binary_content' => $file,
],
'parameters' => [
'name' => self::TEST_FILE_NAME,
'document_type' => self::TEST_DOCUMENT_TYPE,
'metadata' => '{"foo": "bar"}',
'doc_version_metadata' => '{"bar": "baz"}',
],
],
]);
$this->assertEquals(Response::HTTP_CREATED, $response->getStatusCode());
$document = json_decode($response->getContent(false), true);
$documentUid = $document['uid'];
$this->assertNotEmpty($documentUid);
$this->assertEquals(['foo' => 'bar'], $document['metaData']);

$documentVersionUid = $document['latestVersion']['uid'];
$this->assertNotEmpty($documentVersionUid);
$this->assertEquals(self::TEST_FILE_NAME, $document['latestVersion']['name']);
$this->assertEquals('1', $document['latestVersion']['versionNumber']);
$this->assertEquals('text/plain', $document['latestVersion']['mediaType']);
$this->assertEquals($file->getSize(), $document['latestVersion']['size']);
$this->assertEquals(['bar' => 'baz'], $document['latestVersion']['metaData']);

$response = $this->testClient->get('/co-dms-api/api/documents/'.$documentUid, options: [
'headers' => [
'Accept' => 'application/json',
],
]);
$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
$document = json_decode($response->getContent(false), true);
$this->assertEquals($documentUid, $document['uid']);
$this->assertEquals(['foo' => 'bar'], $document['metaData']);
$this->assertEquals($documentVersionUid, $document['latestVersion']['uid']);
$this->assertEquals(self::TEST_FILE_NAME, $document['latestVersion']['name']);
$this->assertEquals('1', $document['latestVersion']['versionNumber']);
$this->assertEquals('text/plain', $document['latestVersion']['mediaType']);
$this->assertEquals($file->getSize(), $document['latestVersion']['size']);
$this->assertEquals(['bar' => 'baz'], $document['latestVersion']['metaData']);

$response = $this->testClient->get(
'/co-dms-api/api/documents/version/'.$documentVersionUid.'/metadata',
options: [
'headers' => [
'Accept' => 'application/json',
]]);
$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
$documentVersion = json_decode($response->getContent(false), true);
$this->assertNotEmpty($documentVersion['uid']);
$this->assertEquals(self::TEST_FILE_NAME, $documentVersion['name']);
$this->assertEquals('1', $documentVersion['versionNumber']);
$this->assertEquals('text/plain', $documentVersion['mediaType']);
$this->assertEquals($file->getSize(), $documentVersion['size']);
$this->assertEquals(['bar' => 'baz'], $documentVersion['metaData']);

/** @var \ApiPlatform\Symfony\Bundle\Test\Response $response */
$response = $this->testClient->get(
'/co-dms-api/api/documents/version/'.$documentVersionUid.'/content',
options: [
'headers' => [
'Accept' => 'application/octet-stream',
]]);
$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
assert($response->getKernelResponse() instanceof BinaryFileResponse);
$this->assertEquals($file->getContent(), $response->getKernelResponse()->getFile()->getContent());
}
}
50 changes: 13 additions & 37 deletions tests/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

use ApiPlatform\Symfony\Bundle\ApiPlatformBundle;
use Dbp\Relay\BlobBundle\DbpRelayBlobBundle;
use Dbp\Relay\BlobBundle\TestUtils\BlobTestUtils;
use Dbp\Relay\BlobConnectorCampusonlineDmsBundle\DbpRelayBlobConnectorCampusonlineDmsBundle;
use Dbp\Relay\BlobConnectorCampusonlineDmsBundle\Service\DocumentService;
use Dbp\Relay\CoreBundle\DbpRelayCoreBundle;
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle;
Expand Down Expand Up @@ -54,45 +56,19 @@ protected function configureContainer(ContainerConfigurator $container, LoaderIn
'annotations' => false,
]);

$container->extension('dbp_relay_blob_connector_campusonline_dms', []);

$container->extension('dbp_relay_blob', [
'database_url' => 'sqlite:///:memory:',
'reporting_interval' => '0 9 * * MON',
'cleanup_interval' => '0 * * * *',
'file_integrity_checks' => false,
'additional_auth' => false,
'integrity_check_interval' => '0 0 1 * *',
'bucket_size_check_interval' => '0 2 * * 1',
'quota_warning_interval' => '0 6 * * *',
'buckets' => [
'test-bucket' => [
'service' => 'Dbp\Relay\BlobBundle\Tests\DummyFileSystemService',
'internal_bucket_id' => '018e0ed8-e6d7-794f-8f60-42efe27ef49e',
'bucket_id' => 'test-bucket',
'key' => '08d848fd868d83646778b87dd0695b10f59c78e23b286e9884504d1bb43cce93',
'quota' => 500, // in MB
'output_validation' => true,
'notify_when_quota_over' => 70, // in percent of quota
'report_when_expiry_in' => 'P62D', // in Days, 62 = two 31 day months
'bucket_owner' => '[email protected]',
'link_expire_time' => 'PT1M',
'reporting' => [
'dsn' => 'smtp:localhost',
'from' => '[email protected]',
'to' => '[email protected]',
'subject' => 'Blob file deletion reporting',
'html_template' => 'emails/reporting.html.twig',
],
'integrity' => [
'dsn' => 'smtp:localhost',
'from' => '[email protected]',
'to' => '[email protected]',
'subject' => 'Blob file integrity check report',
'html_template' => 'emails/integrity.html.twig',
],
$container->extension('dbp_relay_blob_connector_campusonline_dms', [
'authorization' => [
'roles' => [
'ROLE_USER' => 'user.get("MAY_USE_CO_DMS_API")',
],
],
]);

$blobTestConfig = BlobTestUtils::getTestConfig();
$blobTestConfig['buckets'][0]['bucket_id'] = DocumentService::BUCKET_ID;
$blobTestConfig['buckets'][0]['additional_types'] = [
['document_version' => __DIR__.'/document_version.schema.json'],
];
$container->extension('dbp_relay_blob', $blobTestConfig);
}
}
17 changes: 0 additions & 17 deletions tests/Test.php

This file was deleted.

0 comments on commit 748814a

Please sign in to comment.