Skip to content
Merged
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
3 changes: 3 additions & 0 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,9 @@ Vrij en open source onder de EUPL-licentie.
<step>OCA\OpenRegister\Repair\BackfillTaskSubjectLocation</step>
<!-- A schedule in an app's own manifest has no publisher: say so, it does not run. -->
<step>OCA\OpenRegister\Repair\ReportUnpublishedSchedules</step>
<!-- Encrypts webhook and consumer secrets stored in clear and hashes stored
calendar feed tokens; idempotent. -->
<step>OCA\OpenRegister\Repair\ProtectStoredSecrets</step>
</post-migration>
<install>
<step>OCA\OpenRegister\Repair\ReconcileDeclaredBackgroundJobs</step>
Expand Down
2 changes: 2 additions & 0 deletions docs/Features/webhooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,8 @@ Example with array filter:

When you provide a `secret` during webhook creation, OpenRegister signs each payload with HMAC-SHA256 and includes the signature in the `X-Webhook-Signature` header.

The secret is stored encrypted with Nextcloud's `ICrypto` and decrypted only to sign a delivery; the API returns it as `***`. A secret the instance can no longer decrypt (for example after the instance secret changed) stops deliveries for that webhook instead of sending them unsigned; set the secret again to resume.

To verify signatures:

```python
Expand Down
92 changes: 89 additions & 3 deletions lib/Db/ConsumerMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@

namespace OCA\OpenRegister\Db;

use OCA\OpenRegister\Db\Support\SecretAtRest;
use OCA\OpenRegister\Kernel\Contracts\ListQuery;
use OCP\AppFramework\Db\Entity;
use OCP\AppFramework\Db\QBMapper;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
Expand All @@ -39,13 +41,97 @@
/**
* ConsumerMapper constructor.
*
* @param IDBConnection $db The database connection
* @param IDBConnection $db The database connection
* @param SecretAtRest|null $secrets Encrypts the secret configuration values at rest; null stores them as given
*/
public function __construct(IDBConnection $db) {
public function __construct(
IDBConnection $db,
private readonly ?SecretAtRest $secrets = null,
) {
parent::__construct(db: $db, tableName: 'openregister_consumers');

}//end __construct()

/**
* Insert a consumer with the secret values of its authorization configuration sealed.
*
* @param Consumer $entity The consumer.
*
* @return Consumer The inserted consumer, with its configuration open.
*
* @spec openspec/specs/auth-system/spec.md
*/
public function insert(Entity $entity): Entity {
$this->sealConfiguration(entity: $entity);
try {
return parent::insert(entity: $entity);
} finally {
$this->openConfiguration(entity: $entity);
}
}//end insert()

/**
* Update a consumer with the secret values of its authorization configuration sealed.
*
* @param Consumer $entity The consumer.
*
* @return Consumer The updated consumer, with its configuration open.
*
* @spec openspec/specs/auth-system/spec.md
*/
public function update(Entity $entity): Entity {
$this->sealConfiguration(entity: $entity);
try {
return parent::update(entity: $entity);
} finally {
$this->openConfiguration(entity: $entity);
}
}//end update()

/**
* Seal the secret values of a consumer's configuration before it is written.
*
* @param Entity $entity The consumer.
*
* @return void
*/
private function sealConfiguration(Entity $entity): void {
if ($this->secrets !== null && $entity instanceof Consumer) {
$entity->setAuthorizationConfiguration($this->secrets->sealConfiguration(configuration: $entity->getAuthorizationConfiguration()));
}
}//end sealConfiguration()

/**
* Open the secret values of a consumer's configuration again after it was written.
*
* @param Entity $entity The consumer.
*
* @return void
*/
private function openConfiguration(Entity $entity): void {
if ($this->secrets !== null && $entity instanceof Consumer) {
$entity->setAuthorizationConfiguration($this->secrets->openConfiguration(configuration: $entity->getAuthorizationConfiguration()));
}
}//end openConfiguration()

/**
* A stored row as a consumer, with the secret values of its configuration opened.
*
* @param array<string, mixed> $row The row.
*
* @return Entity The consumer.

Check failure on line 121 in lib/Db/ConsumerMapper.php

View workflow job for this annotation

GitHub Actions / quality / PHP Quality (psalm)

LessSpecificImplementedReturnType

lib/Db/ConsumerMapper.php:121:13: LessSpecificImplementedReturnType: The inherited return type 'OCA\OpenRegister\Db\Consumer' for OCP\AppFramework\Db\QBMapper::mapRowToEntity is more specific than the implemented return type for OCA\OpenRegister\Db\ConsumerMapper::maprowtoentity 'OCP\AppFramework\Db\Entity' (see https://psalm.dev/166)
*/
protected function mapRowToEntity(array $row): Entity {
$stored = ($row['authorization_configuration'] ?? null);
if ($this->secrets !== null && is_string($stored) === true && $stored !== '') {
$configuration = json_decode($stored, true);
if (is_array($configuration) === true) {
$row['authorization_configuration'] = json_encode($this->secrets->openConfiguration(configuration: $configuration));
}
}

return parent::mapRowToEntity(row: $row);
}//end mapRowToEntity()

/**
* Find a Consumer by its ID.
*
Expand Down
8 changes: 7 additions & 1 deletion lib/Db/MapperWiring.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
use OCA\OpenRegister\Db\Tenancy\TenancyServices;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use Psr\Container\ContainerInterface;
use OCA\OpenRegister\Db\Support\SecretAtRest;


/**
* The wiring behind MapperRegistrar.
Expand Down Expand Up @@ -142,7 +144,11 @@ private static function webhookMapper(ContainerInterface $container): WebhookMap
userSession: $container->get('OCP\IUserSession'),
groupManager: $container->get('OCP\IGroupManager')
),
appConfig: $container->get('OCP\IAppConfig')
appConfig: $container->get('OCP\IAppConfig'),
secrets: new SecretAtRest(
crypto: $container->get('OCP\Security\ICrypto'),
logger: $container->get('Psr\Log\LoggerInterface')
)
);
}//end webhookMapper()

Expand Down
176 changes: 176 additions & 0 deletions lib/Db/Support/SecretAtRest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
<?php

/**
* Secrets stored encrypted with Nextcloud's ICrypto.
*
* A sealed value carries a prefix, so a stored value that was written before
* encryption existed is told apart from one that was not, and sealing twice
* is a no-op. A value that cannot be opened stays sealed: whoever uses it then
* holds ciphertext, which signs and matches nothing.
*
* SPDX-License-Identifier: EUPL-1.2
* SPDX-FileCopyrightText: 2026 Conduction B.V.
*
* @category Db
* @package OCA\OpenRegister\Db\Support
*
* @author Conduction Development Team <info@conduction.nl>
* @copyright 2026 Conduction B.V.
* @license EUPL-1.2 https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*
* @version GIT: <git_id>
*
* @link https://www.OpenRegister.app
*
* @spec openspec/specs/auth-system/spec.md
*/

declare(strict_types=1);

namespace OCA\OpenRegister\Db\Support;

use OCP\Security\ICrypto;
use Psr\Log\LoggerInterface;
use Throwable;

/**
* Seals and opens stored secrets.
*
* @spec openspec/specs/auth-system/spec.md
*/
final class SecretAtRest {
/**
* The prefix of a sealed value.
*
* @var string
*/
public const PREFIX = 'orenc:v1:';

/**
* The value a webhook secret reads as when it cannot be opened.
*
* Sealed by its prefix, so a delivery that meets it is refused instead of sent unsigned.
*
* @var string
*/
public const UNREADABLE = self::PREFIX . 'unreadable';

/**
* The authorization configuration keys of a consumer whose values are secret.
*
* `publicKey` holds the shared secret for an HS* algorithm; for RS* it is a
* public key, and sealing it costs nothing.
*
* @var array<int, string>
*/
public const CONSUMER_SECRET_KEYS = ['apiKey', 'publicKey', 'secret', 'client_secret', 'password', 'private_key', 'token'];

/**
* Constructor.
*
* @param ICrypto $crypto Nextcloud's crypto service.
* @param LoggerInterface|null $logger Told when a stored secret cannot be opened.
*/
public function __construct(
private readonly ICrypto $crypto,
private readonly ?LoggerInterface $logger = null,
) {
}//end __construct()

/**
* Whether a stored value is sealed.
*
* @param mixed $value The stored value.
*
* @return bool
*
* @spec openspec/specs/auth-system/spec.md
*/
public static function isSealed(mixed $value): bool {
return is_string($value) === true && str_starts_with($value, self::PREFIX) === true;
}//end isSealed()

/**
* The value sealed; null, empty and already sealed values come back as they are.
*
* @param string|null $value The plain value.
*
* @return string|null The sealed value.
*
* @spec openspec/specs/auth-system/spec.md
*/
public function seal(?string $value): ?string {
if ($value === null || $value === '' || self::isSealed(value: $value) === true) {
return $value;
}

return self::PREFIX . $this->crypto->encrypt($value);
}//end seal()

/**
* The value opened; a plain value comes back as it is.
*
* A sealed value that cannot be opened reads as null (logged), never as its
* ciphertext: the ciphertext is visible to whoever may read the stored
* configuration, so it must not work as the secret.
*
* @param string|null $value The stored value.
*
* @return string|null The plain value, or null when it cannot be opened.
*
* @spec openspec/specs/auth-system/spec.md
*/
public function open(?string $value): ?string {
if (self::isSealed(value: $value) === false) {
return $value;
}

try {
return $this->crypto->decrypt(substr((string)$value, strlen(self::PREFIX)));
} catch (Throwable $e) {
$this->logger?->error(
message: '[SecretAtRest] A stored secret cannot be decrypted; it is treated as absent',
context: ['file' => __FILE__, 'line' => __LINE__, 'exception' => get_class($e)]
);
return null;
}
}//end open()

/**
* A consumer's authorization configuration with its secret values sealed.
*
* @param array<string, mixed> $configuration The configuration.
*
* @return array<string, mixed>
*
* @spec openspec/specs/auth-system/spec.md
*/
public function sealConfiguration(array $configuration): array {
foreach (self::CONSUMER_SECRET_KEYS as $key) {
if (is_string($configuration[$key] ?? null) === true) {
$configuration[$key] = $this->seal(value: $configuration[$key]);
}
}

return $configuration;
}//end sealConfiguration()

/**
* A consumer's authorization configuration with its secret values opened.
*
* @param array<string, mixed> $configuration The stored configuration.
*
* @return array<string, mixed>
*
* @spec openspec/specs/auth-system/spec.md
*/
public function openConfiguration(array $configuration): array {
foreach (self::CONSUMER_SECRET_KEYS as $key) {
if (is_string($configuration[$key] ?? null) === true) {
$configuration[$key] = $this->open(value: $configuration[$key]);
}
}

return $configuration;
}//end openConfiguration()
}//end class
Loading
Loading