From 6691c985dddb4a45b7fd97d47972fd00c5205972 Mon Sep 17 00:00:00 2001 From: Khushboo Verma <43381712+vermakhushboo@users.noreply.github.com> Date: Tue, 6 Aug 2024 13:49:28 +0530 Subject: [PATCH] Add headers validator --- app/controllers/api/functions.php | 3 +- src/Appwrite/Functions/Validator/Headers.php | 90 ++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 src/Appwrite/Functions/Validator/Headers.php diff --git a/app/controllers/api/functions.php b/app/controllers/api/functions.php index 307aee6e84..1f0121cab1 100644 --- a/app/controllers/api/functions.php +++ b/app/controllers/api/functions.php @@ -10,6 +10,7 @@ use Appwrite\Event\Usage; use Appwrite\Event\Validator\FunctionEvent; use Appwrite\Extend\Exception; use Appwrite\Extend\Exception as AppwriteException; +use Appwrite\Functions\Validator\Headers; use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Platform\Tasks\ScheduleExecutions; use Appwrite\Task\Validator\Cron; @@ -1628,7 +1629,7 @@ App::post('/v1/functions/:functionId/executions') } // 'headers' validator - $validator = new Assoc(); + $validator = new Headers(); if (!$validator->isValid($headers)) { throw new Exception($validator->getDescription(), 400); } diff --git a/src/Appwrite/Functions/Validator/Headers.php b/src/Appwrite/Functions/Validator/Headers.php new file mode 100644 index 0000000000..1a491ed687 --- /dev/null +++ b/src/Appwrite/Functions/Validator/Headers.php @@ -0,0 +1,90 @@ +allowEmpty = $allowEmpty; + } + + /** + * Get Description. + * + * Returns validator description + * + * @return string + */ + public function getDescription(): string + { + return 'Invalid header format. Header keys can only contain alphanumeric characters, underscores, and hyphens. Header keys cannot start with "x-appwrite-" prefix.'; + } + + /** + * Is valid. + * + * @param mixed $value + * + * @return bool + */ + public function isValid($value): bool + { + if ($this->allowEmpty && empty($value)) { + return true; + } + + if (\is_string($value)) { + $value = \json_decode($value, true); + } + + if (\json_last_error() == JSON_ERROR_NONE) { + if (\is_array($value)) { + foreach ($value as $key => $val) { + // Check for invalid characters in key and value + if (!preg_match('/^[a-zA-Z0-9_-]+$/', $key)) { + return false; + } + // Check for x-appwrite- prefix + if (0 === strpos($key, 'x-appwrite-')) { + return false; + } + } + } + } + return \json_last_error() == JSON_ERROR_NONE; + } + + /** + * Is array + * + * Function will return true if object is array. + * + * @return bool + */ + public function isArray(): bool + { + return false; + } + + /** + * Get Type + * + * Returns validator type. + * + * @return string + */ + public function getType(): string + { + return self::TYPE_OBJECT; + } +}