From 49d10edb4daa5680737839e4c359333a643cc258 Mon Sep 17 00:00:00 2001 From: "Misha M.-Kupriyanov" Date: Tue, 3 Dec 2024 15:58:59 +0100 Subject: [PATCH] fix(files): strict check of default values Not ok: in_array("foo", [true, false]); // returns true ok: in_array("foo", [true, false], true); // returns false Signed-off-by: Misha M.-Kupriyanov --- apps/files/lib/Service/UserConfig.php | 7 ++++- apps/files/tests/Service/UserConfigTest.php | 31 +++++++++++++++++++-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/apps/files/lib/Service/UserConfig.php b/apps/files/lib/Service/UserConfig.php index 0abcfb2a6ad..77775c352ab 100644 --- a/apps/files/lib/Service/UserConfig.php +++ b/apps/files/lib/Service/UserConfig.php @@ -115,7 +115,12 @@ class UserConfig { throw new \InvalidArgumentException('Unknown config key'); } - if (!in_array($value, $this->getAllowedConfigValues($key))) { + $isBoolValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + if ($isBoolValue !== null) { + $value = $isBoolValue; + } + + if (!in_array($value, $this->getAllowedConfigValues($key), true)) { throw new \InvalidArgumentException('Invalid config value'); } diff --git a/apps/files/tests/Service/UserConfigTest.php b/apps/files/tests/Service/UserConfigTest.php index 18438d9c05e..feaa1cd6220 100644 --- a/apps/files/tests/Service/UserConfigTest.php +++ b/apps/files/tests/Service/UserConfigTest.php @@ -112,12 +112,37 @@ class UserConfigTest extends \Test\TestCase { $userConfig->setConfig('unknown_key', true); } - public function testSetsConfigSuccessfully(): void { + public function testThrowsInvalidArgumentExceptionForInvalidConfigValue(): void { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid config value'); + + $userConfig = new UserConfig($this->configMock, $this->userSessionMock); + $userConfig->setConfig('crop_image_previews', 'foo'); + } + + public static function validBoolConfigValues(): array { + return [ + ['true', '1'], + ['false', '0'], + ['1', '1'], + ['0', '0'], + ['yes', '1'], + ['no', '0'], + [true, '1'], + [false, '0'], + ]; + } + + /** + * @dataProvider validBoolConfigValues + */ + public function testSetsConfigWithBooleanValuesSuccessfully($boolValue, $expectedValue): void { $this->configMock->expects($this->once()) ->method('setUserValue') - ->with($this->userUID, Application::APP_ID, 'crop_image_previews', '1'); + ->with($this->userUID, Application::APP_ID, 'crop_image_previews', $expectedValue); + $userConfig = new UserConfig($this->configMock, $this->userSessionMock); - $userConfig->setConfig('crop_image_previews', true); + $userConfig->setConfig('crop_image_previews', $boolValue); } public function testGetsConfigsWithDefaultValuesSuccessfully(): void {