Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
namespace OCA\CloudFederationAPI\Controller;

use OC\AppFramework\Http\Attributes\FederationRateLimit;
use OC\Federation\SenderDomainAwareCloudFederationNotification;
use OC\OCM\OCMSignatoryManager;
use OCA\CloudFederationAPI\Config;
use OCA\CloudFederationAPI\ResponseDefinitions;
Expand Down Expand Up @@ -283,24 +284,37 @@ public function addShare($shareWith, $name, $description, $providerId, $owner, $
}

/**
* Send a notification about an existing share
* Send a notification about a known share or resource
*
* @param string $notificationType Notification type, e.g. SHARE_ACCEPTED
* @param string $resourceType calendar, file, contact,...
* @param string|null $resourceType calendar, file, contact,...
* @param string|null $providerId ID of the share
* @param array<string, mixed>|null $notification The actual payload of the notification
* @param string|null $senderDomain Domain of the sending server
* @param string|null $shareType Type of the recipient the notification is about, e.g. user
*
* @return JSONResponse<Http::STATUS_CREATED, array<string, mixed>, array{}>|JSONResponse<Http::STATUS_BAD_REQUEST, CloudFederationAPIValidationError, array{}>|JSONResponse<Http::STATUS_FORBIDDEN|Http::STATUS_NOT_IMPLEMENTED, CloudFederationAPIError, array{}>
*
* 201: The notification was successfully received
* 400: Bad request due to invalid parameters, e.g. when `type` is invalid or missing
* 403: Getting resource is not allowed
* 501: The resource type is not supported
* 501: The resource type or the notification type is not supported
*/
#[NoCSRFRequired]
#[PublicPage]
#[BruteForceProtection(action: 'receiveFederatedShareNotification')]
public function receiveNotification($notificationType, $resourceType, $providerId, ?array $notification) {
public function receiveNotification($notificationType, $resourceType, $providerId, ?array $notification, $senderDomain, $shareType) {
// Notifications with senderDomain field (OCM 1.5+) are handled only by listeners of
// OCMNotificationReceivedEvent, which provide the response sent back to the sender.
// See https://github.com/cs3org/OCM-API/blob/v1.5.0/IETF-OCM.md#notifications
if ($senderDomain !== null) {
return $this->receiveSenderDomainNotification($notificationType, $resourceType, $providerId, $notification, $senderDomain, $shareType);
}

// Notifications without senderDomain field (before OCM 1.5) are handled by the
// ICloudFederationProvider of the resource type, which provides the response.
// OCMNotificationReceivedEvent is dispatched afterwards, but its listener results are ignored.

// check if all required parameters are set
if (
$notificationType === null
Expand Down Expand Up @@ -333,6 +347,83 @@ public function receiveNotification($notificationType, $resourceType, $providerI
try {
$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
$result = $provider->notificationReceived($notificationType, $providerId, $notification);
} catch (\Exception $e) {
return $this->notificationExceptionResponse($e);
}

$this->dispatcher->dispatchTyped(new CriticalActionPerformedEvent(
'A federated %s notification was received for the %s share with provider ID "%s"',
[
'notificationType' => $notificationType,
'resourceType' => $resourceType,
'providerId' => $providerId,
],
false,
'cloud_federation_api.notification.received',
));

try {
$notificationObject = $this->factory->getCloudFederationNotification();
$notificationObject->setMessage($notificationType, $resourceType, $providerId, $notification);
$notificationEvent = new OCMNotificationReceivedEvent($notificationObject);
$this->dispatcher->dispatchTyped($notificationEvent);
} catch (\Exception $e) {
$this->logger->warning('error while dispatching OCM notification received event', ['exception' => $e]);
}

return new JSONResponse($result, Http::STATUS_CREATED);
}

/**
* Send a notification with senderDomain field to listeners of {@see OCMNotificationReceivedEvent}
*
* @param array<string, mixed>|null $notification
* @return JSONResponse<Http::STATUS_CREATED, array<string, mixed>, array{}>|JSONResponse<Http::STATUS_BAD_REQUEST, CloudFederationAPIValidationError, array{}>|JSONResponse<Http::STATUS_FORBIDDEN|Http::STATUS_NOT_IMPLEMENTED, CloudFederationAPIError, array{}>
*/
private function receiveSenderDomainNotification(?string $notificationType, ?string $resourceType, ?string $providerId, ?array $notification, string $senderDomain, ?string $shareType): JSONResponse {
// check if all required parameters are set
if (
$notificationType === null
|| $senderDomain === ''
|| ($resourceType === null && $shareType === null)
) {
return new JSONResponse(
[
'message' => 'Missing arguments',
'validationErrors' => [],
],
Http::STATUS_BAD_REQUEST
);
}

try {
Comment thread
cristianscheid marked this conversation as resolved.
Resolved
$signedRequest = $this->ocmDiscoveryService->getIncomingSignedRequestFromDomain($senderDomain);
} catch (IncomingRequestException $e) {
$this->logger->warning('incoming request exception', ['exception' => $e]);
return new JSONResponse(['message' => $e->getMessage(), 'validationErrors' => []], Http::STATUS_BAD_REQUEST);
}

try {
$notificationObject = new SenderDomainAwareCloudFederationNotification($signedRequest->getOrigin(), $shareType);
$notificationObject->setMessage($notificationType, $resourceType, $providerId, $notification ?? []);
$notificationEvent = new OCMNotificationReceivedEvent($notificationObject);
$this->dispatcher->dispatchTyped($notificationEvent);
$result = $notificationEvent->getResult() ?? throw new ActionNotSupportedException($notificationType);
Comment thread
cristianscheid marked this conversation as resolved.
Resolved
} catch (\Exception $e) {
return $this->notificationExceptionResponse($e);
}

return new JSONResponse($result, Http::STATUS_CREATED);
}

/**
* Map an exception thrown while handling a notification to its response
*
* @return JSONResponse<Http::STATUS_BAD_REQUEST, CloudFederationAPIValidationError, array{}>|JSONResponse<Http::STATUS_FORBIDDEN|Http::STATUS_NOT_IMPLEMENTED, CloudFederationAPIError, array{}>
*/
private function notificationExceptionResponse(\Exception $e): JSONResponse {
try {
throw $e;
} catch (ProviderDoesNotExistsException $e) {
return new JSONResponse(
[
Expand Down Expand Up @@ -372,28 +463,6 @@ public function receiveNotification($notificationType, $resourceType, $providerI
Http::STATUS_BAD_REQUEST
);
}

$this->dispatcher->dispatchTyped(new CriticalActionPerformedEvent(
'A federated %s notification was received for the %s share with provider ID "%s"',
[
'notificationType' => $notificationType,
'resourceType' => $resourceType,
'providerId' => $providerId,
],
false,
'cloud_federation_api.notification.received',
));

try {
$notificationObject = $this->factory->getCloudFederationNotification();
$notificationObject->setMessage($notificationType, $resourceType, $providerId, $notification);
$notificationEvent = new OCMNotificationReceivedEvent($notificationObject);
$this->dispatcher->dispatchTyped($notificationEvent);
} catch (\Exception $e) {
$this->logger->warning('error while dispatching OCM notification received event', ['exception' => $e]);
}

return new JSONResponse($result, Http::STATUS_CREATED);
}

/**
Expand Down
18 changes: 14 additions & 4 deletions apps/cloud_federation_api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@
"/index.php/ocm/notifications": {
"post": {
"operationId": "request_handler-receive-notification",
"summary": "Send a notification about an existing share",
"summary": "Send a notification about a known share or resource",
"tags": [
"request_handler"
],
Expand All @@ -244,8 +244,7 @@
"schema": {
"type": "object",
"required": [
"notificationType",
"resourceType"
"notificationType"
],
"properties": {
"notificationType": {
Expand All @@ -254,6 +253,7 @@
},
"resourceType": {
"type": "string",
"nullable": true,
"description": "calendar, file, contact,..."
},
"providerId": {
Expand All @@ -268,6 +268,16 @@
"additionalProperties": {
"type": "object"
}
},
"senderDomain": {
"type": "string",
"nullable": true,
"description": "Domain of the sending server"
},
"shareType": {
"type": "string",
"nullable": true,
"description": "Type of the recipient the notification is about, e.g. user"
}
}
}
Expand Down Expand Up @@ -309,7 +319,7 @@
}
},
"501": {
"description": "The resource type is not supported",
"description": "The resource type or the notification type is not supported",
"content": {
"application/json": {
"schema": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,17 @@
use OCP\Federation\ICloudFederationShare;
use OCP\Federation\ICloudId;
use OCP\Federation\ICloudIdManager;
use OCP\Federation\ISenderDomainAwareCloudFederationNotification;
use OCP\IAppConfig;
use OCP\IGroupManager;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\Log\Audit\CriticalActionPerformedEvent;
use OCP\OCM\Events\OCMNotificationReceivedEvent;
use OCP\OCM\IOCMDiscoveryService;
use OCP\Security\Signature\Exceptions\IncomingRequestException;
use OCP\Security\Signature\IIncomingSignedRequest;
use OCP\Share\Exceptions\ShareNotFound;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
Expand All @@ -42,10 +46,13 @@ class RequestHandlerControllerTest extends TestCase {
private IEventDispatcher&MockObject $dispatcher;
private ICloudFederationFactory&MockObject $factory;
private ICloudIdManager&MockObject $cloudIdManager;
private IOCMDiscoveryService&MockObject $ocmDiscoveryService;
private RequestHandlerController $controller;

/** @var list<Event> */
private array $dispatchedEvents = [];
/** @var array<string, mixed>|null result set by the simulated OCMNotificationReceivedEvent listener */
private ?array $listenerResult = null;

#[\Override]
protected function setUp(): void {
Expand All @@ -58,6 +65,7 @@ protected function setUp(): void {
$this->dispatcher = $this->createMock(IEventDispatcher::class);
$this->factory = $this->createMock(ICloudFederationFactory::class);
$this->cloudIdManager = $this->createMock(ICloudIdManager::class);
$this->ocmDiscoveryService = $this->createMock(IOCMDiscoveryService::class);

$appConfig = $this->createMock(IAppConfig::class);
$appConfig->method('getValueBool')
Expand All @@ -68,6 +76,9 @@ protected function setUp(): void {
$this->dispatcher->method('dispatchTyped')
->willReturnCallback(function (Event $event): void {
$this->dispatchedEvents[] = $event;
if ($event instanceof OCMNotificationReceivedEvent && $this->listenerResult !== null) {
$event->setResult($this->listenerResult);
}
});

$this->controller = new RequestHandlerController(
Expand All @@ -83,7 +94,7 @@ protected function setUp(): void {
$appConfig,
$this->factory,
$this->cloudIdManager,
$this->createMock(IOCMDiscoveryService::class),
$this->ocmDiscoveryService,
);
}

Expand All @@ -97,6 +108,22 @@ private function getAuditEvents(): array {
));
}

/**
* @return list<OCMNotificationReceivedEvent>
*/
private function getNotificationEvents(): array {
return array_values(array_filter(
$this->dispatchedEvents,
static fn (Event $event): bool => $event instanceof OCMNotificationReceivedEvent,
));
}

private function mockSignedRequestFrom(string $origin): void {
$signedRequest = $this->createMock(IIncomingSignedRequest::class);
$signedRequest->method('getOrigin')->willReturn($origin);
$this->ocmDiscoveryService->method('getIncomingSignedRequestFromDomain')->willReturn($signedRequest);
}

public function testAddShareLogsCriticalAction(): void {
$this->config->method('getSupportedShareTypes')->with('file')->willReturn(['user']);
$cloudId = $this->createMock(ICloudId::class);
Expand Down Expand Up @@ -152,7 +179,7 @@ public function testReceiveNotificationLogsCriticalAction(): void {
->willReturn([]);
$this->factory->method('getCloudFederationNotification')->willReturn($this->createMock(ICloudFederationNotification::class));

$response = $this->controller->receiveNotification('SHARE_ACCEPTED', 'file', '12', ['sharedSecret' => 'secret']);
$response = $this->controller->receiveNotification('SHARE_ACCEPTED', 'file', '12', ['sharedSecret' => 'secret'], null, null);

$this->assertSame(Http::STATUS_CREATED, $response->getStatus());
$auditEvents = $this->getAuditEvents();
Expand All @@ -169,9 +196,56 @@ public function testReceiveNotificationLogsCriticalAction(): void {
public function testReceiveNotificationForUnknownShareDoesNotLog(): void {
$this->provider->method('notificationReceived')->willThrowException(new ShareNotFound());

$response = $this->controller->receiveNotification('SHARE_ACCEPTED', 'file', '12', ['sharedSecret' => 'secret']);
$response = $this->controller->receiveNotification('SHARE_ACCEPTED', 'file', '12', ['sharedSecret' => 'secret'], null, null);

$this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus());
$this->assertSame([], $this->getAuditEvents());
}

public function testReceiveSenderDomainNotificationReturnsListenerResult(): void {
$this->mockSignedRequestFrom('remote.example');
$this->listenerResult = ['status' => 'ok'];
$this->provider->expects($this->never())->method('notificationReceived');

$response = $this->controller->receiveNotification('USER_REMOVED', 'circle', null, ['key' => 'value'], 'remote.example', 'user');

$this->assertSame(Http::STATUS_CREATED, $response->getStatus());
$this->assertSame(['status' => 'ok'], $response->getData());
$notificationEvents = $this->getNotificationEvents();
$this->assertCount(1, $notificationEvents);
$notification = $notificationEvents[0]->getNotification();
$this->assertInstanceOf(ISenderDomainAwareCloudFederationNotification::class, $notification);
$this->assertSame('remote.example', $notification->getSenderDomain());
$this->assertSame('USER_REMOVED', $notification->getNotificationType());
$this->assertSame('circle', $notification->getResourceType());
$this->assertSame('user', $notification->getShareType());
$this->assertSame(['key' => 'value'], $notification->getNotification());
}

public function testReceiveSenderDomainNotificationWithoutListenerResult(): void {
$this->mockSignedRequestFrom('remote.example');

$response = $this->controller->receiveNotification('USER_REMOVED', 'circle', null, [], 'remote.example', null);

$this->assertSame(Http::STATUS_NOT_IMPLEMENTED, $response->getStatus());
}

public function testReceiveSenderDomainNotificationWithInvalidSignature(): void {
$this->ocmDiscoveryService->method('getIncomingSignedRequestFromDomain')
->willThrowException(new IncomingRequestException('Invalid signature'));

$response = $this->controller->receiveNotification('USER_REMOVED', 'circle', null, [], 'remote.example', null);

$this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus());
$this->assertSame([], $this->getNotificationEvents());
}

public function testReceiveSenderDomainNotificationWithoutResourceOrShareType(): void {
$this->ocmDiscoveryService->expects($this->never())->method('getIncomingSignedRequestFromDomain');

$response = $this->controller->receiveNotification('USER_REMOVED', null, null, [], 'remote.example', null);

$this->assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus());
$this->assertSame([], $this->getNotificationEvents());
}
}
2 changes: 2 additions & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,7 @@
'OCP\\Federation\\ICloudId' => $baseDir . '/lib/public/Federation/ICloudId.php',
'OCP\\Federation\\ICloudIdManager' => $baseDir . '/lib/public/Federation/ICloudIdManager.php',
'OCP\\Federation\\ICloudIdResolver' => $baseDir . '/lib/public/Federation/ICloudIdResolver.php',
'OCP\\Federation\\ISenderDomainAwareCloudFederationNotification' => $baseDir . '/lib/public/Federation/ISenderDomainAwareCloudFederationNotification.php',
'OCP\\Federation\\ISignedCloudFederationProvider' => $baseDir . '/lib/public/Federation/ISignedCloudFederationProvider.php',
'OCP\\Federation\\IValidationAwareCloudFederationProvider' => $baseDir . '/lib/public/Federation/IValidationAwareCloudFederationProvider.php',
'OCP\\Files' => $baseDir . '/lib/public/Files.php',
Expand Down Expand Up @@ -1902,6 +1903,7 @@
'OC\\Federation\\CloudFederationShare' => $baseDir . '/lib/private/Federation/CloudFederationShare.php',
'OC\\Federation\\CloudId' => $baseDir . '/lib/private/Federation/CloudId.php',
'OC\\Federation\\CloudIdManager' => $baseDir . '/lib/private/Federation/CloudIdManager.php',
'OC\\Federation\\SenderDomainAwareCloudFederationNotification' => $baseDir . '/lib/private/Federation/SenderDomainAwareCloudFederationNotification.php',
'OC\\FilesMetadata\\FilesMetadataManager' => $baseDir . '/lib/private/FilesMetadata/FilesMetadataManager.php',
'OC\\FilesMetadata\\Job\\UpdateSingleMetadata' => $baseDir . '/lib/private/FilesMetadata/Job/UpdateSingleMetadata.php',
'OC\\FilesMetadata\\Listener\\MetadataDelete' => $baseDir . '/lib/private/FilesMetadata/Listener/MetadataDelete.php',
Expand Down
Loading
Loading