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
23 changes: 11 additions & 12 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
- SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->

# Change Log

All notable changes to this project will be documented in this file.
Expand All @@ -24,6 +25,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- The ExApp proxy accepts `HEAD` on routes that list `GET` and reads a route's verb as a list of methods, as HaRP does. #1144
- The HaRP version check in the admin overview warns about HaRP older than 0.4.8, which checks the HTTP method of requests to ExApps. #1149
- Failed HaRP shared key checks answer 429 after too many attempts. #1130
- `POST /ocs/v2.php/apps/app_api/api/v1/ui/settings` returns `400` if the form fails schema validation or reuses a field ID from another form already registered by the same ExApp. #1218

### Fixed

Expand All @@ -35,6 +37,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- The ExApp proxy returns an ExApp's redirect to the browser instead of following it, as HaRP does. #1195
- `occ app_api:app:unregister --rm-data` also removes the volume of a Kubernetes ExApp whose deployment is already gone. #1130
- ExApps use the changed settings of their deploy daemon, such as a new HaRP shared key, right away instead of cached old ones. #1205
- A stored ExApp settings form that Nextcloud cannot display no longer breaks the admin and personal settings pages: AppAPI skips that form and logs the ExApp, the form and the reason. #1218

## [34.0.0]

Expand All @@ -43,7 +46,6 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Direct Docker access via Docker Socket Proxy is deprecated and scheduled for removal in Nextcloud 35. Migrate `docker-install` daemons to HaRP.
- AIO Docker Socket Proxy auto-registration (`AIODockerActions::registerAIODaemonConfig`) is deprecated in favor of the HaRP-based AIO daemon.


## [3.2.0 - 2024-09-10]

### Added
Expand All @@ -68,10 +70,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

- ApiScopes are deprecated and removed. #373


## [3.1.0 - 2024-08-15]

**Breaking change**: Task processing API for NC30 AI API. (llm2 and translate2 apps)
**Breaking change**: Task processing API for NC30 AI API. (llm2 and translate2 apps)

### Added

Expand Down Expand Up @@ -125,7 +126,6 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- ExAppProxy: preserve original `Authentication` passed to ExApp via Docker Socket Proxy. #334
- ExAppProxy: send all headers and raw data to ExApp. #330


## [2.7.0 - 2024-07-01]

### Fixed
Expand All @@ -134,7 +134,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Fix ExApp proxy to preserve the url params. #296
- Added missing pass through of cookies in ExApp proxy. #296
- Added missing multipart/form-data support for ExApp proxy. #296
- Fixed HTTP caching issue for application/json requests in ExApp proxy. #296
- Fixed HTTP caching issue for application/json requests in ExApp proxy. #296
- Fixed TopMenu API to allow using iframes. #311

## [2.6.0 - 2024-05-10]
Expand Down Expand Up @@ -165,7 +165,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added

- Different compute device configuration for Daemon (NVIDIA, AMD, CPU). #267
- Ability to add optional parameters when registering a daemon, for example *OVERRIDE_APP_HOST*. #269
- Ability to add optional parameters when registering a daemon, for example _OVERRIDE_APP_HOST_. #269
- API for registering OCC commands. #272
- Correct support of the Docker `HEALTHCHECK` instruction. #273
- Support of pulling "custom" images for the selected compute device. #274
Expand Down Expand Up @@ -203,7 +203,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [2.3.1 - 2024-03-18]

## Added
## Added

- `TEXT_PROCESSING` and `MACHINE_TRANSLATION` API scopes. #249

Expand Down Expand Up @@ -353,7 +353,7 @@ Maintenance update of npm packages to support NC28
### Changed

- Changed AIO auto-created daemon with gpu enabled to separate one (#134)
- Changed AIO detection to use new env (#150)
- Changed AIO detection to use new env (#150)

## [1.4.1 - 2023-12-07]

Expand All @@ -377,7 +377,6 @@ This release contains breaking changes, all ExApps should be updated accordingly
- Oracle DB fixes and adjustments with additional tests.
- Tons of other bugfixes, adjustments and CI tests.


## [1.4.0 - 2023-12-06]

This release contains breaking changes, all ExApps should be updated accordingly to it.
Expand All @@ -402,7 +401,7 @@ This release contains breaking changes, all ExApps should be updated accordingly

### Changed

- Reworked: algorithm of `app:register` and occ cli command, "/init" endpoint now is optional. #128
- Reworked: algorithm of `app:register` and occ cli command, "/init" endpoint now is optional. #128
- Reworked: `app_api:app:unregister` occ cli command, make it much robust. #127

### Fixed
Expand Down Expand Up @@ -444,8 +443,8 @@ This release contains breaking changes, all ExApps should be updated accordingly

### Fixed

- Fixed incorrect error message in admin settings (https://github.com/cloud-py-api/app_api/issues/100)
- Fixed database schema for MySQL (https://github.com/cloud-py-api/app_api/issues/94)
- Fixed incorrect error message in admin settings (<https://github.com/cloud-py-api/app_api/issues/100>)
- Fixed database schema for MySQL (<https://github.com/cloud-py-api/app_api/issues/94>)

## [1.0.1 - 2023-10-06]

Expand Down
10 changes: 10 additions & 0 deletions lib/Db/UI/SettingsFormMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,16 @@ public function findByAppidFormId(string $appId, string $formId): SettingsForm {
);
}

/**
* @return list<SettingsForm>
* @throws Exception
*/
public function findByAppId(string $appId): array {
$qb = $this->db->getQueryBuilder();
return $this->findEntities($qb->select('*')->from($this->tableName)
->where($qb->expr()->eq('appid', $qb->createNamedParameter($appId))));
}

/**
* @throws Exception
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,21 @@

namespace OCA\AppAPI\Listener\DeclarativeSettings;

use OCA\AppAPI\Service\UI\SettingsFormValidator;
use OCA\AppAPI\Service\UI\SettingsService;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Settings\Events\DeclarativeSettingsRegisterFormEvent;
use Psr\Log\LoggerInterface;

/**
* @template-implements IEventListener<Event>
*/
readonly class RegisterDeclarativeSettingsListener implements IEventListener {
public function __construct(
private SettingsService $service,
private LoggerInterface $logger,
private SettingsFormValidator $validator,
) {
}

Expand All @@ -29,7 +33,21 @@ public function handle(Event $event): void {
}

foreach ($this->service->getRegisteredForms() as $form) {
$event->registerSchema($form->getAppid(), $form->getScheme());
try {
$schema = $form->getScheme();
$reason = $this->validator->validate($schema);
if ($reason === null) {
$event->registerSchema($form->getAppid(), $schema);
continue;
}
} catch (\Exception|\TypeError $e) {
$reason = $e->getMessage();
}
$this->logger->warning('Skipping settings form {formId} from ExApp {appId}: {reason}', [
'formId' => $form->getFormid(),
'appId' => $form->getAppid(),
'reason' => $reason,
]);
}
}
}
119 changes: 119 additions & 0 deletions lib/Service/UI/SettingsFormValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php

declare(strict_types=1);

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

namespace OCA\AppAPI\Service\UI;

use OCP\Settings\DeclarativeSettingsTypes as Types;

/**
* Check ExApp schemas both before storage and when loading previously stored forms.
* Registration in Core alone does not check everything needed later: sorting uses
* the priority, and AppAPI needs a non-null default when no value has been saved.
*/
class SettingsFormValidator {
private const CHOICE_TYPES = [Types::SELECT, Types::MULTI_SELECT, Types::RADIO, Types::MULTI_CHECKBOX];
private const INPUT_TYPES = [Types::TEXT, Types::PASSWORD, Types::EMAIL, Types::TEL, Types::URL, Types::NUMBER, Types::CHECKBOX];

/** Return a diagnostic without including any submitted field values. */
public function validate(array $schema): ?string {
foreach (['id', 'section_id'] as $key) {
if (!is_string($schema[$key] ?? null) || $schema[$key] === '') {
return "$key must be a non-empty string";
}
}
// Core uses the form ID after an app prefix in an unescaped CSS ID selector.
if (preg_match('/\A[a-zA-Z0-9_\-\x{0080}-\x{10FFFF}]+\z/u', $schema['id']) !== 1) {
return 'id must be usable in a CSS ID selector';
}
if (!is_string($schema['title'] ?? null)) {
return 'title must be a string';
}
if (!in_array($schema['section_type'] ?? null, [Types::SECTION_TYPE_ADMIN, Types::SECTION_TYPE_PERSONAL], true)) {
return 'section_type must be admin or personal';
}
if (!is_int($schema['priority'] ?? null)) {
return 'priority must be an integer';
}
if (!is_array($schema['fields'] ?? null) || !array_is_list($schema['fields'])) {
return 'fields must be a list';
}
$ids = [];
foreach ($schema['fields'] as $index => $field) {
if (!is_array($field) || !is_string($field['id'] ?? null) || $field['id'] === '') {
return "fields[$index].id must be a non-empty string";
}
if (isset($ids[$field['id']])) {
return "fields[$index].id must be unique";
}
$ids[$field['id']] = true;
if (!is_string($field['title'] ?? null)) {
return "fields[$index].title must be a string";
}
if (!isset($field['default'])) {
return "fields[$index].default must be set and non-null";
}
if (array_key_exists('storage_type', $field) && !in_array($field['storage_type'], [Types::STORAGE_TYPE_INTERNAL, Types::STORAGE_TYPE_EXTERNAL], true)) {
return "fields[$index].storage_type must be internal or external";
}
if (($field['storage_type'] ?? null) === Types::STORAGE_TYPE_INTERNAL) {
if ($schema['section_type'] === Types::SECTION_TYPE_PERSONAL && strlen($field['id']) > 64) {
return "fields[$index].id exceeds the 64-byte limit for personal settings";
}
if (($field['sensitive'] ?? false) === true && !is_string($field['default'])) {
return "fields[$index].default must be a string for sensitive internal storage";
}
}
$type = $field['type'] ?? null;
if (($type === Types::MULTI_SELECT || $type === Types::MULTI_CHECKBOX) && !$this->hasUsableChoiceDefault($type, $field['default'])) {
return $type === Types::MULTI_SELECT
? "fields[$index].default must represent a list or be an empty string"
: "fields[$index].default must represent an object or be an empty string";
}
if (in_array($type, self::CHOICE_TYPES, true)) {
if (!is_array($field['options'] ?? null) || !array_is_list($field['options'])) {
return "fields[$index].options must be a list";
}
$requiresNamedOptions = $type === Types::MULTI_CHECKBOX || $type === Types::RADIO;
foreach ($field['options'] as $option) {
if (!$requiresNamedOptions && is_string($option)) {
continue;
}
if (!is_array($option) || !is_string($option['name'] ?? null) || !array_key_exists('value', $option)) {
return $requiresNamedOptions
? "fields[$index].options requires name/value pairs for $type"
: "fields[$index].options requires strings or name/value pairs";
}
}
} elseif (!in_array($type, self::INPUT_TYPES, true)) {
return "fields[$index].type is not supported";
}
if (($field['sensitive'] ?? false) === true && !in_array($type, [Types::TEXT, Types::PASSWORD], true)) {
return "fields[$index].sensitive is supported only for text and password fields";
}
}
return null;
}

private function hasUsableChoiceDefault(string $type, mixed $default): bool {
// The controls initialize an empty selection themselves for this value.
if ($default === '') {
return true;
}
if (is_array($default)) {
// GetValueListener encodes PHP lists as JSON arrays and maps as JSON objects.
return array_is_list($default) === ($type === Types::MULTI_SELECT);
}
if (!is_string($default)) {
return false;
}
// A client may already have encoded the default. Preserve the distinction between [] and {}.
$decoded = json_decode($default);
return $type === Types::MULTI_SELECT ? is_array($decoded) : $decoded instanceof \stdClass;
}
}
58 changes: 50 additions & 8 deletions lib/Service/UI/SettingsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use OCP\DB\Exception;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\Settings\DeclarativeSettingsTypes;
use Psr\Log\LoggerInterface;

class SettingsService {
Expand All @@ -26,6 +27,7 @@ public function __construct(
ICacheFactory $cacheFactory,
private readonly SettingsFormMapper $mapper,
private readonly LoggerInterface $logger,
private readonly SettingsFormValidator $validator,
) {
if ($cacheFactory->isAvailable()) {
$this->cache = $cacheFactory->createDistributed(Application::APP_ID . '/ex_settings_forms');
Expand All @@ -36,21 +38,37 @@ public function registerForm(
string $appId,
array $formScheme,
): ?SettingsForm {
$formId = $formScheme['id'];
$formScheme['storage_type'] = 'external'; // DeclarativeSettingsTypes::STORAGE_TYPE_EXTERNAL;
try {
$settingsForm = $this->mapper->findByAppidFormId($appId, $formId);
} catch (DoesNotExistException|MultipleObjectsReturnedException|Exception) {
$settingsForm = null;
$formScheme['storage_type'] = DeclarativeSettingsTypes::STORAGE_TYPE_EXTERNAL;
$error = $this->validator->validate($formScheme);
if ($error !== null) {
$this->logger->warning('Rejected settings form {formId} from ExApp {appId}: {reason}', [
'formId' => is_string($formScheme['id'] ?? null) ? $formScheme['id'] : '(unknown)',
'appId' => $appId,
'reason' => $error,
]);
return null;
}
$formId = $formScheme['id'];
try {
$storedForms = $this->mapper->findByAppId($appId);
$conflict = $this->findFieldIdConflict($storedForms, $formId, array_column($formScheme['fields'], 'id'));
if ($conflict !== null) {
$this->logger->warning('Rejected settings form {formId} from ExApp {appId}: field {fieldId} already belongs to form {otherFormId}', [
'appId' => $appId,
'formId' => $formId,
] + $conflict);
return null;
}
$newSettingsForm = new SettingsForm([
'appid' => $appId,
'formid' => $formId,
'scheme' => $formScheme,
]);
if ($settingsForm !== null) {
$newSettingsForm->setId($settingsForm->getId());
foreach ($storedForms as $stored) {
if ($stored->getFormid() === $formId) {
$newSettingsForm->setId($stored->getId());
break;
}
}
$settingsForm = $this->mapper->insertOrUpdate($newSettingsForm);
$this->resetCacheEnabled();
Expand All @@ -63,6 +81,30 @@ public function registerForm(
return $settingsForm;
}

/**
* @param list<SettingsForm> $storedForms
* @param list<string> $fieldIds
* @return array{fieldId: string, otherFormId: string}|null
*/
private function findFieldIdConflict(array $storedForms, string $formId, array $fieldIds): ?array {
$ids = array_fill_keys($fieldIds, true);
foreach ($storedForms as $stored) {
if ($stored->getFormid() === $formId) {
continue;
}
$fields = $stored->getScheme()['fields'] ?? null;
if (!is_array($fields)) {
continue;
}
foreach (array_column($fields, 'id') as $fieldId) {
if (is_string($fieldId) && isset($ids[$fieldId])) {
return ['fieldId' => $fieldId, 'otherFormId' => $stored->getFormid()];
}
}
}
return null;
}

public function unregisterForm(string $appId, string $formId): ?SettingsForm {
try {
$settingsForm = $this->getForm($appId, $formId);
Expand Down
Loading