Skip to content
Open
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 All @@ -25,8 +26,10 @@
use OCP\Federation\Exceptions\ProviderCouldNotAddShareException;
use OCP\Federation\Exceptions\ProviderDoesNotExistsException;
use OCP\Federation\ICloudFederationFactory;
use OCP\Federation\ICloudFederationNotification;
use OCP\Federation\ICloudFederationProviderManager;
use OCP\Federation\ICloudIdManager;
use OCP\Federation\ISenderDomainAwareCloudFederationProvider;
use OCP\Federation\ISignedCloudFederationProvider;
use OCP\Federation\IValidationAwareCloudFederationProvider;
use OCP\IAppConfig;
Expand Down Expand Up @@ -283,31 +286,49 @@ 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) {
// check if all required parameters are set
if (
$notificationType === null
|| $resourceType === null
|| $providerId === null
|| !is_array($notification)
) {
$missingArguments = false;
if ($senderDomain !== null) {
// new format notification (OCM 1.5+)
if (
$notificationType === null
|| $senderDomain === ''
|| ($resourceType === null && $shareType === null)
) {
$missingArguments = true;
}
} else {
// old format notification (before OCM 1.5)
if (
$notificationType === null
|| $resourceType === null
|| $providerId === null
|| !is_array($notification)
) {
$missingArguments = true;
}
}
if ($missingArguments) {
return new JSONResponse(
[
'message' => 'Missing arguments',
Expand All @@ -316,11 +337,19 @@ public function receiveNotification($notificationType, $resourceType, $providerI
Http::STATUS_BAD_REQUEST
);
}
$notification ??= [];

$signedRequest = null;
if (!$this->appConfig->getValueBool('core', OCMSignatoryManager::APPCONFIG_SIGN_DISABLED, lazy: true)) {
try {
$identity = $this->resolveNotificationIdentity($resourceType, $notification);
$signedRequest = $this->ocmDiscoveryService->getIncomingSignedRequest($identity !== '' ? $identity : null);
if ($senderDomain !== null) {
$signedRequest = $this->ocmDiscoveryService->getIncomingSignedRequestFromDomain($senderDomain);
// sharedSecret is optional: when present, the host of the federation ID it resolves to must match senderDomain
$identity = $resourceType !== null && ($notification['sharedSecret'] ?? '') !== '' ? $this->resolveNotificationIdentity($resourceType, $notification) : '';
} else {
$identity = $this->resolveNotificationIdentity($resourceType, $notification);
$signedRequest = $this->ocmDiscoveryService->getIncomingSignedRequest($identity !== '' ? $identity : null);
}
if ($identity !== '') {
$this->ocmDiscoveryService->confirmRequestOrigin($signedRequest?->getOrigin(), $identity);
}
Expand All @@ -330,16 +359,34 @@ public function receiveNotification($notificationType, $resourceType, $providerI
}
}

if ($senderDomain !== null && $signedRequest !== null) {
$notificationObject = new SenderDomainAwareCloudFederationNotification($signedRequest->getOrigin(), $shareType);
} else {
$notificationObject = $this->factory->getCloudFederationNotification();
}
$notificationObject->setMessage($notificationType, $resourceType, $providerId, $notification);

try {
$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
$result = $provider->notificationReceived($notificationType, $providerId, $notification);
if ($senderDomain !== null) {
if (!$provider instanceof ISenderDomainAwareCloudFederationProvider || $signedRequest === null) {
throw new ActionNotSupportedException($notificationType);
}
$result = $provider->senderDomainAwareNotificationReceived($notificationType, $providerId, $notification, $signedRequest->getOrigin(), $shareType);
} else {
$result = $provider->notificationReceived($notificationType, $providerId, $notification);
}
} catch (ProviderDoesNotExistsException $e) {
// new format notifications are dispatched even without provider, since resourceType is optional
if ($notificationObject instanceof SenderDomainAwareCloudFederationNotification) {
$this->dispatchNotificationReceived($notificationObject);
}
return new JSONResponse(
[
'message' => $e->getMessage(),
'validationErrors' => [],
],
Http::STATUS_BAD_REQUEST
$senderDomain !== null ? Http::STATUS_NOT_IMPLEMENTED : Http::STATUS_BAD_REQUEST
);
} catch (ShareNotFound $e) {
$response = new JSONResponse(
Expand Down Expand Up @@ -384,16 +431,17 @@ public function receiveNotification($notificationType, $resourceType, $providerI
'cloud_federation_api.notification.received',
));

$this->dispatchNotificationReceived($notificationObject);

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

private function dispatchNotificationReceived(ICloudFederationNotification $notification): void {
try {
$notificationObject = $this->factory->getCloudFederationNotification();
$notificationObject->setMessage($notificationType, $resourceType, $providerId, $notification);
$notificationEvent = new OCMNotificationReceivedEvent($notificationObject);
$this->dispatcher->dispatchTyped($notificationEvent);
$this->dispatcher->dispatchTyped(new OCMNotificationReceivedEvent($notification));
} 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 @@ -15,20 +15,27 @@
use OCP\AppFramework\Http;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Federation\Exceptions\ProviderDoesNotExistsException;
use OCP\Federation\ICloudFederationFactory;
use OCP\Federation\ICloudFederationNotification;
use OCP\Federation\ICloudFederationProvider;
use OCP\Federation\ICloudFederationProviderManager;
use OCP\Federation\ICloudFederationShare;
use OCP\Federation\ICloudId;
use OCP\Federation\ICloudIdManager;
use OCP\Federation\ISenderDomainAwareCloudFederationNotification;
use OCP\Federation\ISenderDomainAwareCloudFederationProvider;
use OCP\Federation\ISignedCloudFederationProvider;
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 @@ -38,10 +45,12 @@ class RequestHandlerControllerTest extends TestCase {
private IUserManager&MockObject $userManager;
private ICloudFederationProviderManager&MockObject $providerManager;
private ICloudFederationProvider&MockObject $provider;
private SignedSenderDomainAwareCloudFederationProvider&MockObject $senderDomainAwareProvider;
private Config&MockObject $config;
private IEventDispatcher&MockObject $dispatcher;
private ICloudFederationFactory&MockObject $factory;
private ICloudIdManager&MockObject $cloudIdManager;
private IOCMDiscoveryService&MockObject $ocmDiscoveryService;
private RequestHandlerController $controller;

/** @var list<Event> */
Expand All @@ -54,17 +63,30 @@ protected function setUp(): void {
$this->userManager = $this->createMock(IUserManager::class);
$this->providerManager = $this->createMock(ICloudFederationProviderManager::class);
$this->provider = $this->createMock(ICloudFederationProvider::class);
$this->senderDomainAwareProvider = $this->createMock(SignedSenderDomainAwareCloudFederationProvider::class);
$this->config = $this->createMock(Config::class);
$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')
->with('core', OCMSignatoryManager::APPCONFIG_SIGN_DISABLED, false, true)
->willReturn(true);
->willReturn(false);

$this->providerManager->method('getCloudFederationProvider')
->willReturnCallback(fn (?string $resourceType): ICloudFederationProvider => match ($resourceType) {
'file' => $this->provider,
'circle' => $this->senderDomainAwareProvider,
default => throw new ProviderDoesNotExistsException($resourceType),
});
$this->factory->method('getCloudFederationNotification')->willReturn($this->createMock(ICloudFederationNotification::class));

$signedRequest = $this->createMock(IIncomingSignedRequest::class);
$signedRequest->method('getOrigin')->willReturn('remote.example');
$this->ocmDiscoveryService->method('getIncomingSignedRequestFromDomain')->with('remote.example')->willReturn($signedRequest);

$this->providerManager->method('getCloudFederationProvider')->with('file')->willReturn($this->provider);
$this->dispatcher->method('dispatchTyped')
->willReturnCallback(function (Event $event): void {
$this->dispatchedEvents[] = $event;
Expand All @@ -83,7 +105,7 @@ protected function setUp(): void {
$appConfig,
$this->factory,
$this->cloudIdManager,
$this->createMock(IOCMDiscoveryService::class),
$this->ocmDiscoveryService,
);
}

Expand Down Expand Up @@ -150,9 +172,8 @@ public function testReceiveNotificationLogsCriticalAction(): void {
->method('notificationReceived')
->with('SHARE_ACCEPTED', '12', ['sharedSecret' => 'secret'])
->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 +190,88 @@ 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());
}

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

public function testReceiveNotificationWithSenderDomain(): void {
$this->senderDomainAwareProvider->expects($this->once())
->method('senderDomainAwareNotificationReceived')
->with('CIRCLES_EVENT', null, ['event' => []], 'remote.example', null)
->willReturn(['result' => []]);

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

$this->assertSame(Http::STATUS_CREATED, $response->getStatus());
$this->assertSame(['result' => []], $response->getData());
$events = $this->getOCMNotificationReceivedEvents();
$this->assertCount(1, $events);
$notification = $events[0]->getNotification();
$this->assertInstanceOf(ISenderDomainAwareCloudFederationNotification::class, $notification);
$this->assertSame('remote.example', $notification->getSenderDomain());
}

public function testReceiveNotificationWithSenderDomainConfirmsSharedSecretOrigin(): void {
$this->senderDomainAwareProvider->method('getFederationIdFromSharedSecret')
->with('secret', ['sharedSecret' => 'secret'])
->willReturn('bob@remote.example');
$this->ocmDiscoveryService->expects($this->once())
->method('confirmRequestOrigin')
->with('remote.example', 'bob@remote.example');
$this->senderDomainAwareProvider->expects($this->once())->method('senderDomainAwareNotificationReceived')->willReturn([]);

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

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

public function testReceiveNotificationWithSenderDomainRejectsSharedSecretFromOtherOrigin(): void {
$this->senderDomainAwareProvider->method('getFederationIdFromSharedSecret')
->willReturn('bob@other.example');
$this->ocmDiscoveryService->method('confirmRequestOrigin')
->with('remote.example', 'bob@other.example')
->willThrowException(new IncomingRequestException('claimed origin does not match signed origin'));
$this->senderDomainAwareProvider->expects($this->never())->method('senderDomainAwareNotificationReceived');

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

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

public function testReceiveNotificationWithSenderDomainWithoutResourceTypeAndShareType(): void {
$response = $this->controller->receiveNotification('CIRCLES_EVENT', null, null, [], 'remote.example', null);

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

public function testReceiveNotificationWithSenderDomainForProviderNotSenderDomainAware(): void {
$this->provider->expects($this->never())->method('notificationReceived');

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

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

public function testReceiveNotificationWithSenderDomainWithoutProvider(): void {
$response = $this->controller->receiveNotification('SHARE_ACCEPTED', null, null, [], 'remote.example', 'user');

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

interface SignedSenderDomainAwareCloudFederationProvider extends ISenderDomainAwareCloudFederationProvider, ISignedCloudFederationProvider {
}
Loading
Loading