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
2 changes: 1 addition & 1 deletion appinfo/info.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ to join us in shaping a more versatile, stable, and secure app landscape.
*Your insights, suggestions, and contributions are invaluable to us.*

]]></description>
<version>32.0.0-dev.4</version>
<version>32.0.0-dev.5</version>
<licence>agpl</licence>
<author mail="[email protected]" homepage="https://github.com/andrey18106">Andrey Borysenko</author>
<author mail="[email protected]" homepage="https://github.com/bigcat88">Alexander Piskun</author>
Expand Down
4 changes: 2 additions & 2 deletions lib/Controller/PreferencesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@ public function __construct(
#[AppAPIAuth]
#[PublicPage]
#[NoCSRFRequired]
public function setUserConfigValue(string $configKey, mixed $configValue): DataResponse {
public function setUserConfigValue(string $configKey, mixed $configValue, ?int $sensitive = null): DataResponse {
if ($configKey === '') {
throw new OCSBadRequestException('Config key cannot be empty');
}
$userId = $this->userSession->getUser()->getUID();
$appId = $this->request->getHeader('EX-APP-ID');
$result = $this->exAppPreferenceService->setUserConfigValue($userId, $appId, $configKey, $configValue);
$result = $this->exAppPreferenceService->setUserConfigValue($userId, $appId, $configKey, $configValue, $sensitive);
if ($result instanceof ExAppPreference) {
return new DataResponse($result, Http::STATUS_OK);
}
Expand Down
8 changes: 8 additions & 0 deletions lib/Db/ExAppPreference.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,19 @@
* @method string getAppid()
* @method string getConfigkey()
* @method string getConfigvalue()
* @method int getSensitive()
* @method void setUserid(string $userid)
* @method void setAppid(string $appid)
* @method void setConfigkey(string $configkey)
* @method void setConfigvalue(string $configvalue)
* @method void setSensitive(int $sensitive)
*/
class ExAppPreference extends Entity implements JsonSerializable {
protected $userid;
protected $appid;
protected $configkey;
protected $configvalue;
protected $sensitive;

/**
* @param array $params
Expand All @@ -40,6 +43,7 @@ public function __construct(array $params = []) {
$this->addType('appid', 'string');
$this->addType('configkey', 'string');
$this->addType('configvalue', 'string');
$this->addType('sensitive', 'int');

if (isset($params['id'])) {
$this->setId($params['id']);
Expand All @@ -56,6 +60,9 @@ public function __construct(array $params = []) {
if (isset($params['configvalue'])) {
$this->setConfigvalue($params['configvalue']);
}
if (isset($params['sensitive'])) {
$this->setSensitive($params['sensitive']);
}
}

public function jsonSerialize(): array {
Expand All @@ -65,6 +72,7 @@ public function jsonSerialize(): array {
'appid' => $this->getAppid(),
'configkey' => $this->getConfigkey(),
'configvalue' => $this->getConfigvalue(),
'sensitive' => $this->getSensitive(),
];
}
}
10 changes: 10 additions & 0 deletions lib/Db/UI/SettingsForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ public function __construct(array $params = []) {
}
}

public function getSchemaField(string $fieldId): ?array {
$scheme = $this->getScheme();
foreach ($scheme['fields'] as $field) {
if ($field['id'] === $fieldId) {
return $field;
}
}
return null;
}

public function jsonSerialize(): array {
return [
'id' => $this->getId(),
Expand Down
28 changes: 26 additions & 2 deletions lib/Listener/DeclarativeSettings/GetValueListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,21 @@
use OCA\AppAPI\Service\UI\SettingsService;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Security\ICrypto;
use OCP\Settings\DeclarativeSettingsTypes;
use OCP\Settings\Events\DeclarativeSettingsGetValueEvent;
use Psr\Log\LoggerInterface;

/**
* @template-implements IEventListener<Event>
*/
class GetValueListener implements IEventListener {
public function __construct(
private readonly SettingsService $service,
private readonly SettingsService $service,
private readonly ExAppPreferenceService $preferenceService,
private readonly ExAppConfigService $configService,
private readonly ExAppConfigService $configService,
private readonly ICrypto $crypto,
private readonly LoggerInterface $logger,
) {
}

Expand All @@ -38,9 +42,20 @@ public function handle(Event $event): void {
return;
}
$formSchema = $settingsForm->getScheme();
$field = $settingsForm->getSchemaField($event->getFieldId());
$isSensitive = isset($field['sensitive']) && $field['sensitive'] === true;
if ($formSchema['section_type'] === DeclarativeSettingsTypes::SECTION_TYPE_ADMIN) {
$existingValue = $this->configService->getAppConfig($event->getApp(), $event->getFieldId());
if (!empty($existingValue)) {
if ($isSensitive) {
try {
$decryptedValue = $this->crypto->decrypt($existingValue->getConfigvalue());
$existingValue->setConfigvalue($decryptedValue);
} catch (\Exception $e) {
$this->logger->warning(sprintf('Failed to decrypt declarative setting for app %s, field %s', $event->getApp(), $event->getFieldId()), ['exception' => $e]);
$existingValue->setConfigvalue('');
}
}
$event->setValue($existingValue->getConfigvalue());
return;
}
Expand All @@ -51,6 +66,15 @@ public function handle(Event $event): void {
[$event->getFieldId()],
);
if (!empty($existingValue)) {
if ($isSensitive) {
try {
$decryptedValue = $this->crypto->decrypt($existingValue[0]['configvalue']);
$existingValue[0]['configvalue'] = $decryptedValue;
} catch (\Exception $e) {
$this->logger->warning('Failed to decrypt declarative setting for app ' . $event->getApp() . ', field ' . $event->getFieldId(), ['exception' => $e]);
$existingValue[0]['configvalue'] = '';
}
}
$event->setValue($existingValue[0]['configvalue']);
return;
}
Expand Down
26 changes: 22 additions & 4 deletions lib/Listener/DeclarativeSettings/SetValueListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,21 @@
use OCA\AppAPI\Service\UI\SettingsService;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Security\ICrypto;
use OCP\Settings\DeclarativeSettingsTypes;
use OCP\Settings\Events\DeclarativeSettingsSetValueEvent;
use Psr\Log\LoggerInterface;

/**
* @template-implements IEventListener<Event>
*/
class SetValueListener implements IEventListener {
public function __construct(
private readonly SettingsService $service,
private readonly SettingsService $service,
private readonly ExAppPreferenceService $preferenceService,
private readonly ExAppConfigService $configService,
private readonly ExAppConfigService $configService,
private readonly ICrypto $crypto,
private readonly LoggerInterface $logger,
) {
}

Expand All @@ -38,11 +42,25 @@ public function handle(Event $event): void {
return;
}
$formSchema = $settingsForm->getScheme();
$field = $settingsForm->getSchemaField($event->getFieldId());
$isSensitive = isset($field['sensitive']) && $field['sensitive'] === true;
$value = $event->getValue();
if ($isSensitive) {
try {
$value = $this->crypto->encrypt($value);
} catch (\Exception $e) {
$this->logger->warning(
sprintf('Failed to encrypt sensitive value for app %s, field %s', $event->getApp(), $event->getFieldId()),
['exception' => $e, 'app' => $event->getApp()]
);
return;
}
}
if ($formSchema['section_type'] === DeclarativeSettingsTypes::SECTION_TYPE_ADMIN) {
$this->configService->setAppConfigValue($event->getApp(), $event->getFieldId(), $event->getValue());
$this->configService->setAppConfigValue($event->getApp(), $event->getFieldId(), $value);
} else {
$this->preferenceService->setUserConfigValue(
$event->getUser()->getUID(), $event->getApp(), $event->getFieldId(), $event->getValue()
$event->getUser()->getUID(), $event->getApp(), $event->getFieldId(), $value
);
}
}
Expand Down
89 changes: 89 additions & 0 deletions lib/Migration/Version032002Date20250527174907.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

declare(strict_types=1);

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

namespace OCA\AppAPI\Migration;

use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\DB\Types;
use OCP\IDBConnection;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
use OCP\Security\ICrypto;

class Version032002Date20250527174907 extends SimpleMigrationStep {

public function __construct(
private IDBConnection $connection,
private ICrypto $crypto,
) {
}

/**
* @param IOutput $output
* @param Closure(): ISchemaWrapper $schemaClosure
* @param array $options
* @return null|ISchemaWrapper
*/
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options) {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();

if ($schema->hasTable('preferences_ex')) {
$table = $schema->getTable('preferences_ex');

if (!$table->hasColumn('sensitive')) {
$table->addColumn('sensitive', Types::SMALLINT, [
'notnull' => true,
'default' => 0,
]);
}
}

return $schema;
}

/**
* @param IOutput $output
* @param Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
* @param array $options
*
* @return null|ISchemaWrapper
*/
public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options) {
// encrypt appconfig_ex values that have sensitive flag set

$qbSelect = $this->connection->getQueryBuilder();
$qbSelect->select(['id', 'configvalue'])
->from('appconfig_ex')
->where($qbSelect->expr()->eq('sensitive', $qbSelect->createNamedParameter(1, Types::SMALLINT)));
$req = $qbSelect->executeQuery();

while ($row = $req->fetch()) {
$configValue = $row['configvalue'];
if (!empty($configValue)) {
try {
$encryptedValue = $this->crypto->encrypt($configValue);
$qbUpdate = $this->connection->getQueryBuilder();
$qbUpdate->update('appconfig_ex')
->set('configvalue', $qbUpdate->createNamedParameter($encryptedValue))
->where(
$qbUpdate->expr()->eq('id', $qbUpdate->createNamedParameter($row['id'], Types::INTEGER))
);
$qbUpdate->executeStatement();
} catch (\Exception $e) {
$output->warning(sprintf('Failed to encrypt sensitive value for app config id %s: %s', $row['id'], $e->getMessage()));
}
}
}

$req->closeCursor();
return null;
}
}
31 changes: 28 additions & 3 deletions lib/Service/ExAppConfigService.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\DB\Exception;
use OCP\Security\ICrypto;
use Psr\Log\LoggerInterface;

/**
Expand All @@ -25,15 +26,25 @@ class ExAppConfigService {
public function __construct(
private ExAppConfigMapper $mapper,
private LoggerInterface $logger,
private ICrypto $crypto,
) {
}

public function getAppConfigValues(string $appId, array $configKeys): ?array {
try {
return array_map(function (ExAppConfig $exAppConfig) {
$value = $exAppConfig->getConfigvalue() ?? '';
if ($value !== '' && $exAppConfig->getSensitive()) {
try {
$value = $this->crypto->decrypt($value);
} catch (\Exception $e) {
$this->logger->warning(sprintf('Failed to decrypt sensitive value for app %s, config key %s', $exAppConfig->getAppid(), $exAppConfig->getConfigkey()), ['exception' => $e]);
$value = '';
}
}
return [
'configkey' => $exAppConfig->getConfigkey(),
'configvalue' => $exAppConfig->getConfigvalue() ?? '',
'configvalue' => $value,
];
}, $this->mapper->findByAppConfigKeys($appId, $configKeys));
} catch (Exception) {
Expand All @@ -43,20 +54,30 @@ public function getAppConfigValues(string $appId, array $configKeys): ?array {

public function setAppConfigValue(string $appId, string $configKey, mixed $configValue, ?int $sensitive = null): ?ExAppConfig {
$appConfigEx = $this->getAppConfig($appId, $configKey);
if ($configValue !== '' && $sensitive) {
try {
$encryptedValue = $this->crypto->encrypt($configValue);
} catch (\Exception $e) {
$this->logger->error(sprintf('Failed to encrypt sensitive value for app %s, config key %s. Error: %s', $appId, $configKey, $e->getMessage()), ['exception' => $e]);
return null;
}
} else {
$encryptedValue = '';
}
if ($appConfigEx === null) {
try {
$appConfigEx = $this->mapper->insert(new ExAppConfig([
'appid' => $appId,
'configkey' => $configKey,
'configvalue' => $configValue ?? '',
'configvalue' => $sensitive ? $encryptedValue : $configValue ?? '',
'sensitive' => $sensitive ?? 0,
]));
} catch (Exception $e) {
$this->logger->error(sprintf('Failed to insert appconfig_ex value. Error: %s', $e->getMessage()), ['exception' => $e]);
return null;
}
} else {
$appConfigEx->setConfigvalue($configValue);
$appConfigEx->setConfigvalue($sensitive ? $encryptedValue : $configValue);
if ($sensitive !== null) {
$appConfigEx->setSensitive($sensitive);
}
Expand All @@ -65,6 +86,10 @@ public function setAppConfigValue(string $appId, string $configKey, mixed $confi
return null;
}
}
if ($sensitive) {
// setting original unencrypted value for API
$appConfigEx->setConfigvalue($configValue);
}
return $appConfigEx;
}

Expand Down
Loading
Loading