From 942bff1e75f9ab6d769e442fc766c88639d65794 Mon Sep 17 00:00:00 2001 From: Jordy van der Pol Date: Wed, 25 Nov 2026 20:13:02 +0100 Subject: [PATCH 1/3] fix: prevent invalid ExApp forms from breaking settings pages Signed-off-by: Jordy van der Pol --- CHANGELOG.md | 2 + lib/Db/UI/SettingsFormMapper.php | 10 ++ .../RegisterDeclarativeSettingsListener.php | 20 ++- lib/Service/UI/SettingsFormValidator.php | 119 +++++++++++++++ lib/Service/UI/SettingsService.php | 58 +++++++- .../Controller/OCSSettingsControllerTest.php | 138 +++++++++++++++++- .../LoadSettingsValuesTest.php | 82 +++++++++++ ...egisterDeclarativeSettingsListenerTest.php | 52 +++++++ .../Service/UI/SettingsFormValidatorTest.php | 118 +++++++++++++++ 9 files changed, 589 insertions(+), 10 deletions(-) create mode 100644 lib/Service/UI/SettingsFormValidator.php create mode 100644 tests/php/Listener/DeclarativeSettings/LoadSettingsValuesTest.php create mode 100644 tests/php/Listener/DeclarativeSettings/RegisterDeclarativeSettingsListenerTest.php create mode 100644 tests/php/Service/UI/SettingsFormValidatorTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index d8893722f..af38994ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,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` answers `400` instead of `200` for a settings form that Nextcloud cannot display or that reuses a field ID of another form of the same ExApp. ### Fixed @@ -35,6 +36,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. ## [34.0.0] diff --git a/lib/Db/UI/SettingsFormMapper.php b/lib/Db/UI/SettingsFormMapper.php index ab0521dad..c23877bfc 100644 --- a/lib/Db/UI/SettingsFormMapper.php +++ b/lib/Db/UI/SettingsFormMapper.php @@ -57,6 +57,16 @@ public function findByAppidFormId(string $appId, string $formId): SettingsForm { ); } + /** + * @return list + * @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 */ diff --git a/lib/Listener/DeclarativeSettings/RegisterDeclarativeSettingsListener.php b/lib/Listener/DeclarativeSettings/RegisterDeclarativeSettingsListener.php index 1d27d3072..205d8ab6c 100644 --- a/lib/Listener/DeclarativeSettings/RegisterDeclarativeSettingsListener.php +++ b/lib/Listener/DeclarativeSettings/RegisterDeclarativeSettingsListener.php @@ -9,10 +9,12 @@ 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 @@ -20,6 +22,8 @@ readonly class RegisterDeclarativeSettingsListener implements IEventListener { public function __construct( private SettingsService $service, + private LoggerInterface $logger, + private SettingsFormValidator $validator, ) { } @@ -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, + ]); } } } diff --git a/lib/Service/UI/SettingsFormValidator.php b/lib/Service/UI/SettingsFormValidator.php new file mode 100644 index 000000000..df204dcc9 --- /dev/null +++ b/lib/Service/UI/SettingsFormValidator.php @@ -0,0 +1,119 @@ + $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; + } +} diff --git a/lib/Service/UI/SettingsService.php b/lib/Service/UI/SettingsService.php index 304a57902..5ad0ed270 100644 --- a/lib/Service/UI/SettingsService.php +++ b/lib/Service/UI/SettingsService.php @@ -17,6 +17,7 @@ use OCP\DB\Exception; use OCP\ICache; use OCP\ICacheFactory; +use OCP\Settings\DeclarativeSettingsTypes; use Psr\Log\LoggerInterface; class SettingsService { @@ -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'); @@ -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(); @@ -63,6 +81,30 @@ public function registerForm( return $settingsForm; } + /** + * @param list $storedForms + * @param list $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); diff --git a/tests/php/Controller/OCSSettingsControllerTest.php b/tests/php/Controller/OCSSettingsControllerTest.php index b0dfcf94b..75e3a20a0 100644 --- a/tests/php/Controller/OCSSettingsControllerTest.php +++ b/tests/php/Controller/OCSSettingsControllerTest.php @@ -9,20 +9,39 @@ namespace OCA\AppAPI\Tests\php\Controller; +use OC\AppFramework\Bootstrap\Coordinator; +use OC\Memcache\ArrayCache; +use OC\Settings\DeclarativeManager; use OCA\AppAPI\Controller\OCSSettingsController; +use OCA\AppAPI\Db\UI\SettingsForm; +use OCA\AppAPI\Db\UI\SettingsFormMapper; +use OCA\AppAPI\Listener\DeclarativeSettings\RegisterDeclarativeSettingsListener; +use OCA\AppAPI\Service\UI\SettingsFormValidator; use OCA\AppAPI\Service\UI\SettingsService; use OCP\AppFramework\Http; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\IAppConfig; +use OCP\ICacheFactory; +use OCP\IConfig; +use OCP\IGroupManager; use OCP\IRequest; +use OCP\IUser; +use OCP\Security\ICrypto; use OCP\Server; +use OCP\Settings\Events\DeclarativeSettingsRegisterFormEvent; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use Psr\Log\NullLogger; /** * Integration test for OCSSettingsController. Replaces nc_py_api/tests/actual_tests/ui_settings_test.py. */ #[Group('DB')] class OCSSettingsControllerTest extends TestCase { + use RegistersFakeExAppTrait; + private const TEST_APP_ID = 'phpunit_settings_test'; private const TEST_FORM_ID = 'phpunit_form_id'; @@ -43,7 +62,8 @@ protected function setUp(): void { } protected function tearDown(): void { - $this->service->unregisterForm(self::TEST_APP_ID, self::TEST_FORM_ID); + $this->service->unregisterExAppForms(self::TEST_APP_ID); + $this->service->unregisterExAppForms(self::TEST_APP_ID . '_other'); parent::tearDown(); } @@ -119,4 +139,120 @@ public function testRegisterReplacesExistingForm(): void { $scheme = $this->controller->getForm(self::TEST_FORM_ID)->getData(); self::assertSame('Second title', $scheme['title']); } + + public function testRejectsInvalidNewFormWithoutSavingIt(): void { + $scheme = $this->buildScheme(); + $scheme['section_type'] = 'unsupported'; + + $response = $this->controller->registerForm($scheme); + + self::assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus()); + self::assertSame(Http::STATUS_NOT_FOUND, $this->controller->getForm(self::TEST_FORM_ID)->getStatus()); + } + + public function testCanRepairPreviouslyStoredInvalidForm(): void { + $this->insertFakeExApp(self::TEST_APP_ID, 19743); + try { + $this->assertRepairWithWarmCache(); + } finally { + $this->deleteFakeExApp(self::TEST_APP_ID); + } + } + + private function assertRepairWithWarmCache(): void { + $mapper = Server::get(SettingsFormMapper::class); + $cache = new ArrayCache(); + $factory = $this->createStub(ICacheFactory::class); + $factory->method('isAvailable')->willReturn(true); + $factory->method('createDistributed')->willReturn($cache); + $logger = new NullLogger(); + $validator = new SettingsFormValidator(); + $service = new SettingsService($factory, $mapper, $logger, $validator); + $controller = new OCSSettingsController($this->request, $service); + $listener = new RegisterDeclarativeSettingsListener($service, $logger, $validator); + $user = $this->createStub(IUser::class); + $loadFormIds = static function () use ($listener, $user): array { + // A fresh request starts with an empty manager, but reads the same cache. + $manager = new DeclarativeManager( + Server::get(IEventDispatcher::class), + Server::get(IGroupManager::class), + Server::get(Coordinator::class), + Server::get(IConfig::class), + Server::get(IAppConfig::class), + new NullLogger(), + Server::get(ICrypto::class), + ); + $listener->handle(new DeclarativeSettingsRegisterFormEvent($manager)); + return $manager->getFormIDs($user, 'personal', 'phpunit_section')[self::TEST_APP_ID] ?? []; + }; + + $scheme = $this->buildScheme(); + $scheme['section_type'] = 'personal'; + $neighbour = $scheme; + $neighbour['id'] = 'healthy'; + $neighbour['fields'][0]['id'] = 'healthy_field'; + self::assertSame(Http::STATUS_OK, $controller->registerForm($neighbour)->getStatus()); + $legacy = $scheme; + unset($legacy['section_type']); + $record = $mapper->insert(new SettingsForm(['appid' => self::TEST_APP_ID, 'formid' => self::TEST_FORM_ID, 'scheme' => $legacy])); + + self::assertSame(['healthy'], $loadFormIds()); + self::assertTrue($cache->hasKey('/ex_settings_forms')); + self::assertSame(Http::STATUS_OK, $controller->registerForm($scheme)->getStatus()); + $repaired = $mapper->findByAppidFormId(self::TEST_APP_ID, self::TEST_FORM_ID); + self::assertSame($record->getId(), $repaired->getId()); + self::assertEqualsCanonicalizing(['healthy', self::TEST_FORM_ID], $loadFormIds()); + } + + public function testFieldIdCannotBeReusedAcrossFormsOfOneApp(): void { + $scheme = $this->buildScheme(); + self::assertSame(Http::STATUS_OK, $this->controller->registerForm($scheme)->getStatus()); + $before = $this->controller->getForm(self::TEST_FORM_ID)->getData(); + $scheme['id'] = 'second_form'; + self::assertSame(Http::STATUS_BAD_REQUEST, $this->controller->registerForm($scheme)->getStatus()); + self::assertSame(Http::STATUS_NOT_FOUND, $this->controller->getForm('second_form')->getStatus()); + self::assertSame($before, $this->controller->getForm(self::TEST_FORM_ID)->getData()); + $scheme['fields'][0]['id'] = 'another_field'; + self::assertSame(Http::STATUS_OK, $this->controller->registerForm($scheme)->getStatus()); + } + + public function testDifferentAppsCanUseTheSameFieldId(): void { + $scheme = $this->buildScheme(); + self::assertSame(Http::STATUS_OK, $this->controller->registerForm($scheme)->getStatus()); + $scheme['id'] = 'other_form'; + self::assertNotNull($this->service->registerForm(self::TEST_APP_ID . '_other', $scheme)); + } + + public static function fieldRegistrationCases(): array { + return [ + 'null default' => [['type' => 'text', 'default' => null], Http::STATUS_BAD_REQUEST], + 'unknown field storage' => [['type' => 'text', 'default' => '', 'storage_type' => 'relay'], Http::STATUS_BAD_REQUEST], + 'internal field storage' => [['type' => 'text', 'default' => '', 'storage_type' => 'internal'], Http::STATUS_OK], + 'explicit external storage and empty string' => [['type' => 'text', 'default' => '', 'storage_type' => 'external'], Http::STATUS_OK], + 'zero default' => [['type' => 'number', 'default' => 0], Http::STATUS_OK], + 'false default' => [['type' => 'checkbox', 'default' => false], Http::STATUS_OK], + ]; + } + + #[DataProvider('fieldRegistrationCases')] + public function testRegistersOnlyFieldsWithUsableDefaultsAndStorage(array $properties, int $expectedStatus): void { + $scheme = $this->buildScheme(); + $scheme['fields'] = [['id' => 'setting', 'title' => 'Setting'] + $properties]; + self::assertSame($expectedStatus, $this->controller->registerForm($scheme)->getStatus()); + } + + public function testInvalidUpdateIsRejectedAndPreservesExistingForm(): void { + $original = $this->buildScheme('Original title'); + self::assertSame(Http::STATUS_OK, $this->controller->registerForm($original)->getStatus()); + $before = $this->controller->getForm(self::TEST_FORM_ID)->getData(); + + $update = $original; + $update['section_type'] = 'unsupported'; + $response = $this->controller->registerForm($update); + + self::assertSame(Http::STATUS_BAD_REQUEST, $response->getStatus()); + $stored = $this->controller->getForm(self::TEST_FORM_ID); + self::assertSame(Http::STATUS_OK, $stored->getStatus()); + self::assertSame($before, $stored->getData()); + } } diff --git a/tests/php/Listener/DeclarativeSettings/LoadSettingsValuesTest.php b/tests/php/Listener/DeclarativeSettings/LoadSettingsValuesTest.php new file mode 100644 index 000000000..7842a64f3 --- /dev/null +++ b/tests/php/Listener/DeclarativeSettings/LoadSettingsValuesTest.php @@ -0,0 +1,82 @@ + [[]], + 'null default' => [['default' => null]], + 'unknown field storage' => [['default' => 'Available', 'storage_type' => 'relay']], + 'oversized personal internal key' => [['id' => str_repeat('x', 65), 'default' => '', 'storage_type' => 'internal']], + 'non-string sensitive internal default' => [['default' => false, 'sensitive' => true, 'storage_type' => 'internal']], + ]; + } + + #[DataProvider('invalidStoredFieldProperties')] + public function testLoadsHealthyFormAlongsideInvalidStoredForm(array $legacyProperties): void { + $forms = []; + foreach (['legacy', 'healthy'] as $id) { + $field = ['id' => $id . '_field', 'title' => 'Label', 'type' => 'text']; + if ($id === 'healthy') { + $field['default'] = 'Available'; + } else { + $field = array_replace($field, $legacyProperties); + } + $forms[$id] = new SettingsForm(['appid' => 'test_app', 'formid' => $id, 'scheme' => [ + 'id' => $id, 'title' => $id, 'section_type' => 'personal', 'section_id' => 'test_section', + 'priority' => 50, 'storage_type' => 'external', 'fields' => [$field], + ]]); + } + $service = $this->createStub(SettingsService::class); + $service->method('getRegisteredForms')->willReturn(array_values($forms)); + $service->method('getForm')->willReturnMap([ + ['test_app', 'legacy', $forms['legacy']], ['test_app', 'healthy', $forms['healthy']], + ]); + $logger = new NullLogger(); + $crypto = $this->createStub(ICrypto::class); + $preferences = $this->createStub(ExAppPreferenceService::class); + $preferences->method('getUserConfigValues')->willReturn([]); + $values = new GetValueListener($service, $preferences, $this->createStub(ExAppConfigService::class), $crypto, $logger); + $dispatcher = $this->createStub(IEventDispatcher::class); + $dispatcher->method('dispatchTyped')->willReturnCallback($values->handle(...)); + $manager = new DeclarativeManager($dispatcher, $this->createStub(IGroupManager::class), Server::get(Coordinator::class), + Server::get(IConfig::class), $this->createStub(IAppConfig::class), $logger, $crypto); + + (new RegisterDeclarativeSettingsListener($service, $logger, new SettingsFormValidator()))->handle(new DeclarativeSettingsRegisterFormEvent($manager)); + $user = $this->createStub(IUser::class); + $user->method('getUID')->willReturn('phpunit_settings_user'); + $loaded = $manager->getFormsWithValues($user, 'personal', 'test_section'); + + self::assertSame(['healthy'], array_column($loaded, 'id')); + self::assertSame('Available', $loaded[0]['fields'][0]['value']); + } +} diff --git a/tests/php/Listener/DeclarativeSettings/RegisterDeclarativeSettingsListenerTest.php b/tests/php/Listener/DeclarativeSettings/RegisterDeclarativeSettingsListenerTest.php new file mode 100644 index 000000000..e1f655cc6 --- /dev/null +++ b/tests/php/Listener/DeclarativeSettings/RegisterDeclarativeSettingsListenerTest.php @@ -0,0 +1,52 @@ +createStub(SettingsService::class); + $service->method('getRegisteredForms')->willReturn([ + new SettingsForm(['appid' => 'first_app', 'formid' => 'first', 'scheme' => ['id' => 'first']]), + new SettingsForm(['appid' => 'second_app', 'formid' => 'second', 'scheme' => ['id' => 'second']]), + ]); + + $registered = []; + $manager = $this->createStub(IDeclarativeManager::class); + $manager->method('registerSchema')->willReturnCallback(static function (string $app, array $schema) use (&$registered): void { + if ($app === 'first_app') { + throw new \Exception('Invalid schema. Please check the logs for more details.'); + } + $registered[$app][] = $schema['id']; + }); + + $logger = $this->createMock(LoggerInterface::class); + $logger->expects(self::once())->method('warning')->with(self::anything(), self::callback( + static fn (array $context): bool => $context['appId'] === 'first_app' + && $context['formId'] === 'first' + && $context['reason'] === 'Invalid schema. Please check the logs for more details.' + )); + // This test covers a rejection by Core after AppAPI validation has passed. + $validator = $this->createStub(SettingsFormValidator::class); + $validator->method('validate')->willReturn(null); + $listener = new RegisterDeclarativeSettingsListener($service, $logger, $validator); + $listener->handle(new DeclarativeSettingsRegisterFormEvent($manager)); + + self::assertSame(['second_app' => ['second']], $registered); + } +} diff --git a/tests/php/Service/UI/SettingsFormValidatorTest.php b/tests/php/Service/UI/SettingsFormValidatorTest.php new file mode 100644 index 000000000..ae33fd2f7 --- /dev/null +++ b/tests/php/Service/UI/SettingsFormValidatorTest.php @@ -0,0 +1,118 @@ + 'form', + 'section_type' => 'personal', + 'section_id' => 'section', + 'title' => 'Form', + 'priority' => 50, + 'storage_type' => 'external', + 'fields' => [[ + 'id' => 'field', + 'title' => 'Field', + 'type' => 'text', + 'default' => 'value', + ]], + ]; + + // Each case is a form and the reason it is rejected with, or null when it is accepted. + public static function schemas(): array { + return [ + // Accepted + 'valid form' => [self::FORM, null], + 'form id after app prefix' => [self::with(['id' => '2_één-form']), null], + '64-byte personal internal key' => [self::withField(['id' => str_repeat('é', 32), 'storage_type' => 'internal']), null], + 'empty sensitive internal default' => [self::withField(['storage_type' => 'internal', 'sensitive' => true, 'default' => '']), null], + 'empty title' => [self::with(['title' => '']), null], + 'no fields' => [self::with(['fields' => []]), null], + 'field stored internally' => [self::withField(['storage_type' => 'internal']), null], + 'field stored externally' => [self::withField(['storage_type' => 'external']), null], + 'select with plain string options' => [self::withField(['type' => 'select', 'options' => ['first', 'second']]), null], + 'radio with named options' => [self::withField(['type' => 'radio', 'default' => 'first', 'options' => [['name' => 'First', 'value' => 'first']]]), null], + + // Rejected: form + 'no id' => [self::without('id'), 'id must be a non-empty string'], + 'empty id' => [self::with(['id' => '']), 'id must be a non-empty string'], + 'form id with space' => [self::with(['id' => 'two words']), 'id must be usable in a CSS ID selector'], + 'no section id' => [self::without('section_id'), 'section_id must be a non-empty string'], + 'no section type' => [self::without('section_type'), 'section_type must be admin or personal'], + 'unknown section type' => [self::with(['section_type' => 'administrator']), 'section_type must be admin or personal'], + 'no title' => [self::without('title'), 'title must be a string'], + 'no priority' => [self::without('priority'), 'priority must be an integer'], + 'priority as string' => [self::with(['priority' => '50']), 'priority must be an integer'], + 'fields not a list' => [self::with(['fields' => ['first' => self::FORM['fields'][0]]]), 'fields must be a list'], + 'duplicate field id' => [self::with(['fields' => [self::FORM['fields'][0], self::FORM['fields'][0]]]), 'fields[1].id must be unique'], + + // Rejected: field + 'field with empty id' => [self::withField(['id' => '']), 'fields[0].id must be a non-empty string'], + '65-byte personal internal key' => [self::withField(['id' => str_repeat('é', 32) . 'a', 'storage_type' => 'internal']), 'fields[0].id exceeds the 64-byte limit for personal settings'], + 'non-string sensitive internal default' => [self::withField(['storage_type' => 'internal', 'sensitive' => true, 'default' => false]), 'fields[0].default must be a string for sensitive internal storage'], + 'field without title' => [self::withField(['title' => null]), 'fields[0].title must be a string'], + 'field without default' => [self::withField(['default' => null]), 'fields[0].default must be set and non-null'], + 'unknown field storage' => [self::withField(['storage_type' => 'relay']), 'fields[0].storage_type must be internal or external'], + 'null field storage' => [self::withField(['storage_type' => null]), 'fields[0].storage_type must be internal or external'], + 'unknown field type' => [self::withField(['type' => 'color']), 'fields[0].type is not supported'], + 'select without options' => [self::withField(['type' => 'select']), 'fields[0].options must be a list'], + 'checkbox group with unnamed option' => [self::withField(['type' => 'multi-checkbox', 'default' => '', 'options' => ['first']]), 'fields[0].options requires name/value pairs for multi-checkbox'], + 'radio with unnamed option' => [self::withField(['type' => 'radio', 'default' => 'first', 'options' => ['first']]), 'fields[0].options requires name/value pairs for radio'], + 'select with options that are not a list' => [self::withField(['type' => 'select', 'options' => ['first' => 'second']]), 'fields[0].options must be a list'], + 'option without name' => [self::withField(['type' => 'select', 'options' => [['value' => 'first']]]), 'fields[0].options requires strings or name/value pairs'], + 'sensitive checkbox' => [self::withField(['type' => 'checkbox', 'default' => false, 'sensitive' => true]), 'fields[0].sensitive is supported only for text and password fields'], + ]; + } + + #[DataProvider('schemas')] + public function testValidates(array $schema, ?string $expectedReason): void { + self::assertSame($expectedReason, (new SettingsFormValidator())->validate($schema)); + } + + public static function multipleChoiceDefaults(): array { + return [ + ['multi-select', '', true], + ['multi-select', ['first'], true], + ['multi-select', '["first"]', true], + ['multi-select', '{}', false], + ['multi-select', 'first', false], + ['multi-checkbox', '', true], + ['multi-checkbox', ['first' => false], true], + ['multi-checkbox', '{}', true], + ['multi-checkbox', [], false], + ['multi-checkbox', 'false', false], + ]; + } + + #[DataProvider('multipleChoiceDefaults')] + public function testMultipleChoiceDefault(string $type, mixed $default, bool $accepted): void { + $schema = self::withField(['type' => $type, 'default' => $default, 'options' => [['name' => 'First', 'value' => 'first']]]); + self::assertSame($accepted, (new SettingsFormValidator())->validate($schema) === null); + } + + // The base form with the given properties replaced. + private static function with(array $properties): array { + return array_replace(self::FORM, $properties); + } + + // The base form with the given properties replaced on its first field. + private static function withField(array $properties): array { + return self::with(['fields' => [array_replace(self::FORM['fields'][0], $properties)]]); + } + + // The base form without the given properties. + private static function without(string ...$keys): array { + return array_diff_key(self::FORM, array_flip($keys)); + } +} From edfc10277ef5ccdeb8cea24a3bb17b97384420ef Mon Sep 17 00:00:00 2001 From: Jordy van der Pol Date: Wed, 25 Nov 2026 20:25:17 +0100 Subject: [PATCH 2/3] Update changelog with a reference to the PR number #1218 Signed-off-by: Jordy van der Pol --- CHANGELOG.md | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index af38994ec..7b7e3b554 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. @@ -24,7 +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` answers `400` instead of `200` for a settings form that Nextcloud cannot display or that reuses a field ID of another form of the same ExApp. +- `POST /ocs/v2.php/apps/app_api/api/v1/ui/settings` answers `400` instead of `200` for a settings form that Nextcloud cannot display or that reuses a field ID of another form of the same ExApp. #1218 ### Fixed @@ -36,7 +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. +- 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] @@ -45,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 @@ -70,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 @@ -127,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 @@ -136,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] @@ -167,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 @@ -205,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 @@ -355,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] @@ -379,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. @@ -404,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 @@ -446,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 () +- Fixed database schema for MySQL () ## [1.0.1 - 2023-10-06] From 6caa33ddaf9edeaac88aed0e64c1e98a50c66718 Mon Sep 17 00:00:00 2001 From: Jordy van der Pol Date: Wed, 25 Nov 2026 20:33:55 +0100 Subject: [PATCH 3/3] Clarify when settings form registration returns 400 in the changelog Signed-off-by: Jordy van der Pol --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b7e3b554..0cc522e37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +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` answers `400` instead of `200` for a settings form that Nextcloud cannot display or that reuses a field ID of another form of the same ExApp. #1218 +- `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