From 1c584976507845db44ace6ef97e7e24d73363df6 Mon Sep 17 00:00:00 2001 From: Laurence Isla Date: Fri, 27 Oct 2023 20:53:45 -0500 Subject: [PATCH] allow all origins when server-cors-allowed-origins is an empty string --- src/PostgREST/Config.hs | 7 ++++++- test/io/test_io.py | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/PostgREST/Config.hs b/src/PostgREST/Config.hs index ad88a67cb0..8c6aa24efe 100644 --- a/src/PostgREST/Config.hs +++ b/src/PostgREST/Config.hs @@ -271,7 +271,7 @@ parser optPath env dbSettings roleSettings roleIsolationLvl = <*> parseOpenAPIMode "openapi-mode" <*> (fromMaybe False <$> optBool "openapi-security-active") <*> parseOpenAPIServerProxyURI "openapi-server-proxy-uri" - <*> (fmap splitOnCommas <$> optValue "server-cors-allowed-origins") + <*> parseCORSAllowedOrigins "server-cors-allowed-origins" <*> (fromMaybe "!4" <$> optString "server-host") <*> (fromMaybe 3000 <$> optInt "server-port") <*> (fmap (CI.mk . encodeUtf8) <$> optString "server-trace-header") @@ -353,6 +353,11 @@ parser optPath env dbSettings roleSettings roleIsolationLvl = Nothing -> pure [JSPKey "role"] Just rck -> either (fail . show) pure $ pRoleClaimKey rck + parseCORSAllowedOrigins k = + optString k >>= \case + Nothing -> pure Nothing + Just orig -> pure $ Just (T.strip <$> T.splitOn "," orig) + optWithAlias :: C.Parser C.Config (Maybe a) -> C.Parser C.Config (Maybe a) -> C.Parser C.Config (Maybe a) optWithAlias orig alias = orig >>= \case diff --git a/test/io/test_io.py b/test/io/test_io.py index fb818dcc5c..91b5421ada 100644 --- a/test/io/test_io.py +++ b/test/io/test_io.py @@ -1239,6 +1239,27 @@ def test_preflight_request_with_cors_allowed_origin_config(defaultenv): ) +def test_preflight_request_with_empty_cors_allowed_origin_config(defaultenv): + "OPTIONS preflight request should allow all origins when config is present but empty" + + env = { + **defaultenv, + "PGRST_SERVER_CORS_ALLOWED_ORIGINS": "", + } + + headers = { + "Accept": "*/*", + "Origin": "http://anyorigin.com", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "Content-Type", + } + + with run(env=env) as postgrest: + response = postgrest.session.options("/items", headers=headers) + assert response.headers["Access-Control-Allow-Origin"] == "*" + assert "POST" in response.headers["Access-Control-Allow-Methods"] + + def test_no_preflight_request_with_CORS_config_should_return_header(defaultenv): "GET no preflight request should return Access-Control-Allow-Origin equal to origin"