From 7d1bba9442735259fa82b50e041dce54ad31cf16 Mon Sep 17 00:00:00 2001 From: Sebastian Hofpe Date: Mon, 4 Mar 2024 15:38:27 +0100 Subject: [PATCH] Add logic to handle single-use headers The code now includes a mechanism to handle HTTP headers that are allowed to be used only once. This is done by storing such headers separately and checking their sense status before sending them again. This will prevent any issues arising from multiple instances of the same header. https://stackoverflow.com/questions/15682496/will-duplicate-access-control-allow-origin-headers-break-cors --- src/JK/RestServer/HeaderManager.php | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/JK/RestServer/HeaderManager.php b/src/JK/RestServer/HeaderManager.php index a4e7da7..376d50a 100644 --- a/src/JK/RestServer/HeaderManager.php +++ b/src/JK/RestServer/HeaderManager.php @@ -13,6 +13,11 @@ final class HeaderManager /** @var array Colletion of HTTP headers */ private $headers = array(); + /** These headers are only once allowed */ + private $singleHeader = [ + "Access-Control-Allow-Origin" + ]; + /** * Sets some defaults */ @@ -121,7 +126,23 @@ public function sendAllHeaders() } foreach ($this->headers as $name => $value) { - header($name . ': ' . $value); + if (!$this->isSingleHeaderAndNotAlreadySent($name)) { + header($name . ': ' . $value); + } } } + + /** + * Bugfix: Remove duplicates of headers which are required to be single + * + * https://stackoverflow.com/questions/15682496/will-duplicate-access-control-allow-origin-headers-break-cors + */ + private function isSingleHeaderAndNotAlreadySent(string $name): bool + { + if (!in_array($name, $this->singleHeader)) { + return false; + } + + return array_key_exists($name, array_keys(headers_list())); + } }