Skip to content
Draft
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
2 changes: 2 additions & 0 deletions apps/sharing/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
'OCA\\Sharing\\Command\\UpdateShareState' => $baseDir . '/../lib/Command/UpdateShareState.php',
'OCA\\Sharing\\Command\\UpdateShareUserStatus' => $baseDir . '/../lib/Command/UpdateShareUserStatus.php',
'OCA\\Sharing\\Controller\\ApiV1Controller' => $baseDir . '/../lib/Controller/ApiV1Controller.php',
'OCA\\Sharing\\Federation\\FederationSharingService' => $baseDir . '/../lib/Federation/FederationSharingService.php',
'OCA\\Sharing\\Listener\\FederationSharingListener' => $baseDir . '/../lib/Listener/FederationSharingListener.php',
'OCA\\Sharing\\Middleware\\ShareApiEnabledMiddleware' => $baseDir . '/../lib/Middleware/ShareApiEnabledMiddleware.php',
'OCA\\Sharing\\Migration\\Version1000Date20250929161325' => $baseDir . '/../lib/Migration/Version1000Date20250929161325.php',
'OCA\\Sharing\\Migration\\Version1000Date20260731171922' => $baseDir . '/../lib/Migration/Version1000Date20260731171922.php',
Expand Down
2 changes: 2 additions & 0 deletions apps/sharing/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ class ComposerStaticInitSharing
'OCA\\Sharing\\Command\\UpdateShareState' => __DIR__ . '/..' . '/../lib/Command/UpdateShareState.php',
'OCA\\Sharing\\Command\\UpdateShareUserStatus' => __DIR__ . '/..' . '/../lib/Command/UpdateShareUserStatus.php',
'OCA\\Sharing\\Controller\\ApiV1Controller' => __DIR__ . '/..' . '/../lib/Controller/ApiV1Controller.php',
'OCA\\Sharing\\Federation\\FederationSharingService' => __DIR__ . '/..' . '/../lib/Federation/FederationSharingService.php',
'OCA\\Sharing\\Listener\\FederationSharingListener' => __DIR__ . '/..' . '/../lib/Listener/FederationSharingListener.php',
'OCA\\Sharing\\Middleware\\ShareApiEnabledMiddleware' => __DIR__ . '/..' . '/../lib/Middleware/ShareApiEnabledMiddleware.php',
'OCA\\Sharing\\Migration\\Version1000Date20250929161325' => __DIR__ . '/..' . '/../lib/Migration/Version1000Date20250929161325.php',
'OCA\\Sharing\\Migration\\Version1000Date20260731171922' => __DIR__ . '/..' . '/../lib/Migration/Version1000Date20260731171922.php',
Expand Down
5 changes: 5 additions & 0 deletions apps/sharing/lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@

namespace OCA\Sharing\AppInfo;

use NCU\Sharing\Event\ShareRecipientAddedEvent;
use NCU\Sharing\Event\ShareStateUpdatedEvent;
use OC\Sharing\SharingManager;
use OCA\Sharing\Capabilities;
use OCA\Sharing\Listener\FederationSharingListener;
use OCA\Sharing\Middleware\ShareApiEnabledMiddleware;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
Expand All @@ -31,6 +34,8 @@ public function register(IRegistrationContext $context): void {
$context->registerMiddleware(ShareApiEnabledMiddleware::class);

$context->registerEventListener(BeforeUserDeletedEvent::class, SharingManager::class);
$context->registerEventListener(ShareStateUpdatedEvent::class, FederationSharingListener::class);
$context->registerEventListener(ShareRecipientAddedEvent::class, FederationSharingListener::class);
}

#[\Override]
Expand Down
180 changes: 180 additions & 0 deletions apps/sharing/lib/Federation/FederationSharingService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Sharing\Federation;

use InvalidArgumentException;
use NCU\Sharing\ISharingRegistry;
use NCU\Sharing\Permission\ISharePermissionType;
use NCU\Sharing\Recipient\ShareRecipient;
use NCU\Sharing\Share;
use NCU\Sharing\ShareUser;
use NCU\Sharing\Source\ShareSource;
use OC\Core\Sharing\Permission\ReshareSharePermissionType;
use OC\Core\Sharing\Recipient\UserShareRecipientType;
use OCA\Files\Sharing\Permission\NodeCreateSharePermissionType;
use OCA\Files\Sharing\Permission\NodeDeleteSharePermissionType;
use OCA\Files\Sharing\Permission\NodeReadSharePermissionType;
use OCA\Files\Sharing\Permission\NodeUpdateSharePermissionType;
use OCA\Files\Sharing\Source\NodeShareSourceType;
use OCP\AppFramework\Http;
use OCP\Constants;
use OCP\Federation\ICloudFederationFactory;
use OCP\Federation\ICloudFederationProviderManager;
use OCP\Federation\ICloudFederationShare;
use OCP\Federation\ICloudIdManager;
use OCP\IUserManager;
use OCP\OCM\Exceptions\OCMProviderException;
use OCP\Share\IManager;
use Psr\Log\LoggerInterface;

final readonly class FederationSharingService {
public const string PROVIDER_ID_PREFIX = 'unified';

public const string RESOURCE_TYPE_FILE = 'file';

private const array SHARE_TYPES = [
UserShareRecipientType::class => 'user',
// GroupShareRecipientType::class => 'group',
];

/**
* Map ISharePermissionType classes to the permission bitmask
* expected by ICloudFederationFactory::getCloudFederationShare()
*
* @var array<class-string<ISharePermissionType>, int>
*/
private const array PERMISSIONS = [
NodeReadSharePermissionType::class => Constants::PERMISSION_READ,
NodeUpdateSharePermissionType::class => Constants::PERMISSION_UPDATE,
NodeCreateSharePermissionType::class => Constants::PERMISSION_CREATE,
NodeDeleteSharePermissionType::class => Constants::PERMISSION_DELETE,
ReshareSharePermissionType::class => Constants::PERMISSION_SHARE,
];

public function __construct(
private ICloudFederationFactory $federationFactory,
private ICloudFederationProviderManager $federationProviderManager,
private ICloudIdManager $cloudIdManager,
private ISharingRegistry $registry,
private IUserManager $userManager,
private IManager $legacyManager,
private LoggerInterface $logger,
) {
}

/**
* Sends one OCM share per source to the remote recipient's OCM /shares endpoint
*/
public function sendShare(Share $share, ShareRecipient $recipient): void {
if ($recipient->instance === null || $recipient->secret === null || !$recipient->initiator instanceof ShareUser || $recipient->id === null) {
return;
}

$shareType = self::SHARE_TYPES[$recipient->class] ?? null;
if ($shareType === null) {
$this->logger->debug('Recipient type {class} can not be shared with remotely', ['class' => $recipient->class]);
return;
}

if (!$this->isOutgoingSharingAllowed($shareType)) {
$this->logger->debug('Outgoing federated {shareType} shares are disabled', ['shareType' => $shareType]);
return;
}

$permissions = $this->getPermissions($share, $recipient);
foreach ($share->sources as $source) {
if ($source->class !== NodeShareSourceType::class) {
continue;
}

$federationShare = $this->federationFactory->getCloudFederationShare(
$recipient->value . '@' . $recipient->instance,
$this->getResourceName($source),
'',
self::getProviderId($share->id, $recipient->id, $source->value),
$this->getCloudId($share->owner),
$this->getDisplayName($share->owner),
$this->getCloudId($recipient->initiator),
$this->getDisplayName($recipient->initiator),
$recipient->secret,
$shareType,
self::RESOURCE_TYPE_FILE,
$permissions,
);

$this->send($federationShare);
}
}

/**
* Format: unified:{shareId}:{recipientId}:{sourceValue}
*/
public static function getProviderId(string $shareId, string $recipientId, string $sourceValue): string {
return self::PROVIDER_ID_PREFIX . ':' . $shareId . ':' . $recipientId . ':' . $sourceValue;
}

private function send(ICloudFederationShare $federationShare): void {
$context = [
'providerId' => $federationShare->getProviderId(),
'recipient' => $federationShare->getShareWith(),
];

try {
$response = $this->federationProviderManager->sendCloudShare($federationShare);
} catch (OCMProviderException|InvalidArgumentException $e) {
$this->logger->warning('Failed to send share {providerId} to {recipient}', $context + ['exception' => $e]);
return;
}

$context['status'] = $response->getStatusCode();
$context['body'] = $response->getBody();
if ($response->getStatusCode() === Http::STATUS_CREATED) {
$this->logger->info('Sent share {providerId} to {recipient}', $context);
} else {
$this->logger->warning('Remote rejected share {providerId} for {recipient} with status {status}', $context);
}
}

private function isOutgoingSharingAllowed(string $shareType): bool {
return match ($shareType) {
'user' => $this->legacyManager->outgoingServer2ServerSharesAllowed(),
'group' => $this->legacyManager->outgoingServer2ServerGroupSharesAllowed(),
};
}

private function getResourceName(ShareSource $source): string {
return ($this->registry->getSourceTypes()[$source->class] ?? null)?->getSourceMetadata($source->value)?->getDisplayName() ?? $source->value;
}

private function getCloudId(ShareUser $user): string {
return $this->cloudIdManager->getCloudId($user->userId, $user->instance)->getId();
}

private function getDisplayName(ShareUser $user): string {
if ($user->instance !== null) {
return $user->userId;
}

return $this->userManager->getDisplayName($user->userId) ?? $user->userId;
}

private function getPermissions(Share $share, ShareRecipient $recipient): int {
$disabledPermissions = $recipient->getDisabledPermissions();

$permissions = 0;
foreach ($share->permissions as $permission) {
if ($permission->enabled && !isset($disabledPermissions[$permission->class])) {
$permissions |= self::PERMISSIONS[$permission->class] ?? 0;

Check failure on line 174 in apps/sharing/lib/Federation/FederationSharingService.php

View workflow job for this annotation

GitHub Actions / static-code-analysis-strict

InvalidArrayOffset

apps/sharing/lib/Federation/FederationSharingService.php:174:21: InvalidArrayOffset: Cannot access value on variable OCA\Sharing\Federation\FederationSharingService::PERMISSIONS using a class-string<NCU\Sharing\Permission\ISharePermissionType> offset, expecting 'OCA\\Files\\Sharing\\Permission\\NodeCreateSharePermissionType'|'OCA\\Files\\Sharing\\Permission\\NodeDeleteSharePermissionType'|'OCA\\Files\\Sharing\\Permission\\NodeReadSharePermissionType'|'OCA\\Files\\Sharing\\Permission\\NodeUpdateSharePermissionType'|'OC\\Core\\Sharing\\Permission\\ReshareSharePermissionType' (see https://psalm.dev/115)

Check failure on line 174 in apps/sharing/lib/Federation/FederationSharingService.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

InvalidArrayOffset

apps/sharing/lib/Federation/FederationSharingService.php:174:21: InvalidArrayOffset: Cannot access value on variable OCA\Sharing\Federation\FederationSharingService::PERMISSIONS using a class-string<NCU\Sharing\Permission\ISharePermissionType> offset, expecting 'OCA\\Files\\Sharing\\Permission\\NodeCreateSharePermissionType'|'OCA\\Files\\Sharing\\Permission\\NodeDeleteSharePermissionType'|'OCA\\Files\\Sharing\\Permission\\NodeReadSharePermissionType'|'OCA\\Files\\Sharing\\Permission\\NodeUpdateSharePermissionType'|'OC\\Core\\Sharing\\Permission\\ReshareSharePermissionType' (see https://psalm.dev/115)
}
}

return $permissions;
}
}
55 changes: 55 additions & 0 deletions apps/sharing/lib/Listener/FederationSharingListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Sharing\Listener;

use NCU\Sharing\Event\ShareRecipientAddedEvent;
use NCU\Sharing\Event\ShareStateUpdatedEvent;
use NCU\Sharing\Recipient\ShareRecipient;
use NCU\Sharing\ShareState;
use OCA\Sharing\Federation\FederationSharingService;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;

/**
* Sends shares to remote recipients' OCM /shares endpoint
*
* @template-implements IEventListener<ShareStateUpdatedEvent|ShareRecipientAddedEvent>
*/
final readonly class FederationSharingListener implements IEventListener {
public function __construct(
private FederationSharingService $federationSharingService,
) {
}

#[\Override]
public function handle(Event $event): void {
if ($event instanceof ShareStateUpdatedEvent) {
$share = $event->getShare();
if ($share->state !== ShareState::Active || $event->getPreviousState() === ShareState::Active) {
return;
}

$remoteRecipients = array_filter($share->recipients, static fn (ShareRecipient $recipient): bool => $recipient->instance !== null);
foreach ($remoteRecipients as $recipient) {
$this->federationSharingService->sendShare($share, $recipient);
}
}

if ($event instanceof ShareRecipientAddedEvent) {
$share = $event->getShare();
$recipient = $event->getRecipient();
if ($share->state !== ShareState::Active || $recipient->instance === null) {
return;
}

$this->federationSharingService->sendShare($share, $recipient);
}
}
}
2 changes: 2 additions & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
'NCU\\Security\\Signature\\ISignatureManager' => $baseDir . '/lib/unstable/Security/Signature/ISignatureManager.php',
'NCU\\Security\\Signature\\ISignedRequest' => $baseDir . '/lib/unstable/Security/Signature/ISignedRequest.php',
'NCU\\Security\\Signature\\Model\\Signatory' => $baseDir . '/lib/unstable/Security/Signature/Model/Signatory.php',
'NCU\\Sharing\\Event\\ShareRecipientAddedEvent' => $baseDir . '/lib/unstable/Sharing/Event/ShareRecipientAddedEvent.php',
'NCU\\Sharing\\Event\\ShareStateUpdatedEvent' => $baseDir . '/lib/unstable/Sharing/Event/ShareStateUpdatedEvent.php',
'NCU\\Sharing\\Event\\SharesDefaultSetEvent' => $baseDir . '/lib/unstable/Sharing/Event/SharesDefaultSetEvent.php',
'NCU\\Sharing\\Exception\\AShareException' => $baseDir . '/lib/unstable/Sharing/Exception/AShareException.php',
'NCU\\Sharing\\Exception\\ShareInvalidException' => $baseDir . '/lib/unstable/Sharing/Exception/ShareInvalidException.php',
Expand Down
2 changes: 2 additions & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'NCU\\Security\\Signature\\ISignatureManager' => __DIR__ . '/../../..' . '/lib/unstable/Security/Signature/ISignatureManager.php',
'NCU\\Security\\Signature\\ISignedRequest' => __DIR__ . '/../../..' . '/lib/unstable/Security/Signature/ISignedRequest.php',
'NCU\\Security\\Signature\\Model\\Signatory' => __DIR__ . '/../../..' . '/lib/unstable/Security/Signature/Model/Signatory.php',
'NCU\\Sharing\\Event\\ShareRecipientAddedEvent' => __DIR__ . '/../../..' . '/lib/unstable/Sharing/Event/ShareRecipientAddedEvent.php',
'NCU\\Sharing\\Event\\ShareStateUpdatedEvent' => __DIR__ . '/../../..' . '/lib/unstable/Sharing/Event/ShareStateUpdatedEvent.php',
'NCU\\Sharing\\Event\\SharesDefaultSetEvent' => __DIR__ . '/../../..' . '/lib/unstable/Sharing/Event/SharesDefaultSetEvent.php',
'NCU\\Sharing\\Exception\\AShareException' => __DIR__ . '/../../..' . '/lib/unstable/Sharing/Exception/AShareException.php',
'NCU\\Sharing\\Exception\\ShareInvalidException' => __DIR__ . '/../../..' . '/lib/unstable/Sharing/Exception/ShareInvalidException.php',
Expand Down
10 changes: 8 additions & 2 deletions lib/private/Sharing/SharingBackend.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ public function onSourceDeleted(ShareSource $source): array {
}

#[\Override]
public function addShareRecipient(string $id, ShareRecipient $recipient): void {
public function addShareRecipient(string $id, ShareRecipient $recipient): string {
$this->assertInTransaction();

if ($recipient->secret === null) {
Expand All @@ -236,11 +236,13 @@ public function addShareRecipient(string $id, ShareRecipient $recipient): void {
throw new RuntimeException('The initiator must not be null.');
}

$recipientId = $this->snowflakeGenerator->nextId();

try {
$qb = $this->connection->getQueryBuilder();

$values = [
'id' => $qb->createNamedParameter($this->snowflakeGenerator->nextId()),
'id' => $qb->createNamedParameter($recipientId),
'share_id' => $qb->createNamedParameter($id),
'recipient_class_id' => $qb->createNamedParameter($this->classMapper->getClassId($recipient->class), IQueryBuilder::PARAM_INT),
'recipient_value' => $qb->createNamedParameter($recipient->value),
Expand All @@ -264,6 +266,8 @@ public function addShareRecipient(string $id, ShareRecipient $recipient): void {

throw $exception;
}

return $recipientId;
}

#[\Override]
Expand Down Expand Up @@ -980,6 +984,7 @@ private function list(
$initiatorInstance,
),
[],
$recipientId,
);

$shareRecipientTypeClasses[$shareId] ??= [];
Expand Down Expand Up @@ -1037,6 +1042,7 @@ private function list(
$recipient->secret,
$recipient->initiator,
$permissions,
$recipient->id,
);
}
}
Expand Down
Loading
Loading