Skip to content

Commit

Permalink
signatories
Browse files Browse the repository at this point in the history
Signed-off-by: Maxence Lange <maxence@artificial-owl.com>
  • Loading branch information
ArtificialOwl committed Jul 4, 2024
1 parent 8b3055c commit a3dda22
Show file tree
Hide file tree
Showing 42 changed files with 2,004 additions and 85 deletions.
15 changes: 14 additions & 1 deletion apps/cloud_federation_api/lib/Capabilities.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,24 @@

namespace OCA\CloudFederationAPI;

use OC\OCM\OCMSignatoryManager;
use OC\Security\Signature\Model\Signatory;
use OCP\Capabilities\ICapability;
use OCP\IURLGenerator;
use OCP\OCM\Exceptions\OCMArgumentException;
use OCP\OCM\IOCMProvider;
use OCP\Security\Signature\Exceptions\SignatoryException;
use OCP\Security\Signature\Model\ISignatory;
use Psr\Log\LoggerInterface;

class Capabilities implements ICapability {
public const API_VERSION = '1.0-proposal1';
public const API_VERSION = '1.1'; // informative, real version.

public function __construct(
private IURLGenerator $urlGenerator,
private IOCMProvider $provider,
private readonly OCMSignatoryManager $ocmSignatoryManager,
private readonly LoggerInterface $logger,
) {
}

Expand Down Expand Up @@ -60,6 +67,12 @@ public function getCapabilities() {

$this->provider->addResourceType($resource);

try {
$this->provider->setSignatory($this->ocmSignatoryManager->getLocalSignatory());
} catch (SignatoryException $e) {
$this->logger->warning('cannot generate local signatory', ['exception' => $e]);
}

return ['ocm' => $this->provider->jsonSerialize()];
}
}
138 changes: 137 additions & 1 deletion apps/cloud_federation_api/lib/Controller/RequestHandlerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
namespace OCA\CloudFederationAPI\Controller;

use OC\OCM\OCMSignatoryManager;
use OCA\CloudFederationAPI\Config;
use OCA\CloudFederationAPI\ResponseDefinitions;
use OCP\AppFramework\Controller;
Expand All @@ -19,11 +20,20 @@
use OCP\Federation\ICloudFederationFactory;
use OCP\Federation\ICloudFederationProviderManager;
use OCP\Federation\ICloudIdManager;
use OCP\IAppConfig;
use OCP\IGroupManager;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\Security\Signature\Exceptions\IncomingRequestException;
use OCP\Security\Signature\Exceptions\SignatoryNotFoundException;
use OCP\Security\Signature\Exceptions\SignatureException;
use OCP\Security\Signature\Exceptions\SignatureNotFoundException;
use OCP\Security\Signature\ISignatureManager;
use OCP\Security\Signature\Model\IIncomingSignedRequest;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IProviderFactory;
use OCP\Share\IShare;
use Psr\Log\LoggerInterface;

/**
Expand All @@ -46,8 +56,12 @@ public function __construct(
private IURLGenerator $urlGenerator,
private ICloudFederationProviderManager $cloudFederationProviderManager,
private Config $config,
private readonly IAppConfig $appConfig,
private ICloudFederationFactory $factory,
private ICloudIdManager $cloudIdManager
private ICloudIdManager $cloudIdManager,
private readonly ISignatureManager $signatureManager,
private readonly OCMSignatoryManager $signatoryManager,
private readonly IProviderFactory $shareProviderFactory,
) {
parent::__construct($appName, $request);
}
Expand Down Expand Up @@ -77,6 +91,15 @@ public function __construct(
* 501: Share type or the resource type is not supported
*/
public function addShare($shareWith, $name, $description, $providerId, $owner, $ownerDisplayName, $sharedBy, $sharedByDisplayName, $protocol, $shareType, $resourceType) {
try {
$signedRequest = $this->getSignedRequest();
$this->confirmSignedOrigin($signedRequest, 'owner', $owner);
} catch (IncomingRequestException $e) {
$this->logger->warning('incoming request exception', ['exception' => $e]);
return new JSONResponse(['message' => $e->getMessage(), 'validationErrors' => []],
Http::STATUS_BAD_REQUEST);
}

// check if all required parameters are set
if ($shareWith === null ||

Check failure on line 104 in apps/cloud_federation_api/lib/Controller/RequestHandlerController.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

TypeDoesNotContainNull

apps/cloud_federation_api/lib/Controller/RequestHandlerController.php:104:7: TypeDoesNotContainNull: Type string for $owner is never null (see https://psalm.dev/090)
$name === null ||
Expand All @@ -99,6 +122,7 @@ public function addShare($shareWith, $name, $description, $providerId, $owner, $
);
}


$supportedShareTypes = $this->config->getSupportedShareTypes($resourceType);
if (!in_array($shareType, $supportedShareTypes)) {
return new JSONResponse(
Expand Down Expand Up @@ -201,6 +225,15 @@ public function addShare($shareWith, $name, $description, $providerId, $owner, $
* 501: The resource type is not supported
*/
public function receiveNotification($notificationType, $resourceType, $providerId, ?array $notification) {
try {
$signedRequest = $this->getSignedRequest();
$this->confirmShareOrigin($signedRequest, $notification['sharedSecret'] ?? '');
} catch (IncomingRequestException $e) {
$this->logger->warning('incoming request exception', ['exception' => $e]);
return new JSONResponse(['message' => $e->getMessage(), 'validationErrors' => []],
Http::STATUS_BAD_REQUEST);
}

// check if all required parameters are set
if ($notificationType === null ||
$resourceType === null ||
Expand Down Expand Up @@ -279,4 +312,107 @@ private function mapUid($uid) {

return $uid;
}


/**
* @return IIncomingSignedRequest|null null if remote does not (and never did) support signed request
* @throws IncomingRequestException
*/
private function getSignedRequest(): ?IIncomingSignedRequest {
try {
return $this->signatureManager->getIncomingSignedRequest($this->signatoryManager);
} catch (SignatureNotFoundException|SignatoryNotFoundException $e) {
// remote does not support signed request.
// currently we still accept unsigned request until lazy appconfig
// core.enforce_signed_ocm_request is set to true (default: false)
if ($this->appConfig->getValueBool('enforce_signed_ocm_request', false, lazy: true)) {

Check failure

Code scanning / Psalm

InvalidArgument Error

Argument 2 of OCP\IAppConfig::getValueBool cannot be false, string value expected

Check failure on line 328 in apps/cloud_federation_api/lib/Controller/RequestHandlerController.php

View workflow job for this annotation

GitHub Actions / static-code-analysis

InvalidArgument

apps/cloud_federation_api/lib/Controller/RequestHandlerController.php:328:69: InvalidArgument: Argument 2 of OCP\IAppConfig::getValueBool cannot be false, string value expected (see https://psalm.dev/004)
$this->logger->notice('ignored unsigned request', ['exception' => $e]);
throw new IncomingRequestException('Unsigned request');
}
} catch (SignatureException $e) {
$this->logger->notice('wrongly signed request', ['exception' => $e]);
throw new IncomingRequestException('Invalid signature');
}
return null;
}


/**
* confirm that the value related to $key entry from the payload is in format userid@hostname
* and compare hostname with the origin of the signed request.
*
* If request is not signed, we still verify that the hostname from the extracted value does,
* actually, not support signed request
*
* @param IIncomingSignedRequest|null $signedRequest
* @param string $key
*
* @throws IncomingRequestException
*/
private function confirmSignedOrigin(?IIncomingSignedRequest $signedRequest, string $key, string $value): void {
if ($signedRequest === null) {
$instance = $this->getHostFromFederationId($value);
try {
$this->signatureManager->searchSignatory($instance);
throw new IncomingRequestException('instance is supposed to sign its request');
} catch (SignatoryNotFoundException) {
return;
}
}

$body = json_decode($signedRequest->getBody(), true) ?? [];
$entry = trim($body[$key] ?? '', '@');
if ($this->getHostFromFederationId($entry) !== $signedRequest->getOrigin()) {
throw new IncomingRequestException('share initiation from different instance');
}
}


/**
* confirm that the value related to share token is in format userid@hostname
* and compare hostname with the origin of the signed request.
*
* If request is not signed, we still verify that the hostname from the extracted value does,
* actually, not support signed request
*
* @param IIncomingSignedRequest|null $signedRequest
* @param string $key
*
* @return void
* @throws IncomingRequestException
*/
private function confirmShareOrigin(?IIncomingSignedRequest $signedRequest, string $token): void {
if ($token === '') {
throw new BadRequestException(['sharedSecret']);
}

$provider = $this->shareProviderFactory->getProviderForType(IShare::TYPE_REMOTE);
$share = $provider->getShareByToken($token);
$entry = $share->getSharedWith();

$instance = $this->getHostFromFederationId($entry);
if ($signedRequest === null) {
try {
$this->signatureManager->searchSignatory($instance);
throw new IncomingRequestException('instance is supposed to sign its request');
} catch (SignatoryNotFoundException) {
return;
}
} elseif ($instance !== $signedRequest->getOrigin()) {
throw new IncomingRequestException('token sharedWith from different instance');
}
}

/**
* @param string $entry
* @return string
* @throws IncomingRequestException
*/
private function getHostFromFederationId(string $entry): string {
if (!str_contains($entry, '@')) {
throw new IncomingRequestException('entry does not contains @');
}
[, $instance] = explode('@', $entry, 2);

Check notice

Code scanning / Psalm

PossiblyUndefinedArrayOffset Note

Possibly undefined array key
return $instance;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,6 @@ public function notificationReceived($notificationType, $providerId, array $noti
return $this->updateResharePermissions($providerId, $notification);
}


throw new BadRequestException([$notificationType]);
}

Expand Down
5 changes: 4 additions & 1 deletion apps/files_sharing/lib/External/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ class Cache extends \OC\Files\Cache\Cache {
public function __construct($storage, ICloudId $cloudId) {
$this->cloudId = $cloudId;
$this->storage = $storage;
[, $remote] = explode('://', $cloudId->getRemote(), 2);
$remote = $cloudId->getRemote();
if (str_contains($remote, '://')) {
[, $remote] = explode('://', $cloudId->getRemote(), 2);

Check notice

Code scanning / Psalm

PossiblyUndefinedArrayOffset Note

Possibly undefined array key
}
$this->remote = $remote;
$this->remoteUser = $cloudId->getUser();
parent::__construct($storage);
Expand Down
1 change: 1 addition & 0 deletions apps/files_sharing/lib/External/Storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ public function __construct($options) {
parent::__construct(
[
'secure' => ((parse_url($remote, PHP_URL_SCHEME) ?? 'https') === 'https'),
'verify' => !$this->config->getSystemValueBool('sharing.federation.allowSelfSignedCertificates', false),
'host' => $host,
'root' => $webDavEndpoint,
'user' => $options['token'],
Expand Down
11 changes: 6 additions & 5 deletions core/Controller/OCMController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use OCP\AppFramework\Http\Attribute\FrontpageRoute;
use OCP\AppFramework\Http\DataResponse;
use OCP\Capabilities\ICapability;
use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IRequest;
use OCP\Server;
Expand All @@ -29,7 +30,7 @@
class OCMController extends Controller {
public function __construct(
IRequest $request,
private IConfig $config,
private readonly IAppConfig $appConfig,
private LoggerInterface $logger
) {
parent::__construct('core', $request);
Expand All @@ -52,10 +53,10 @@ public function __construct(
public function discovery(): DataResponse {
try {
$cap = Server::get(
$this->config->getAppValue(
'core',
'ocm_providers',
'\OCA\CloudFederationAPI\Capabilities'
$this->appConfig->getValueString(
'core', 'ocm_providers',
\OCA\CloudFederationAPI\Capabilities::class,
lazy: true
)
);

Expand Down
Loading

0 comments on commit a3dda22

Please sign in to comment.