From 4f20cfbd85d5a92aa1927d6823d515423a5e74c9 Mon Sep 17 00:00:00 2001 From: Warnar Boekkooi Date: Mon, 6 Mar 2023 08:32:05 +0100 Subject: [PATCH] Ensure Vary header is set when using CORS with origin When CORS requirements are more complicated than setting `Access-Control-Allow-Origin` to `*` then we set the `Vary` to `Origin`. This avoids caching the wrong response. --- apisix/plugins/cors.lua | 7 +++---- t/plugin/cors3.t | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/apisix/plugins/cors.lua b/apisix/plugins/cors.lua index f0d911f5de92..8e2a468aa6ad 100644 --- a/apisix/plugins/cors.lua +++ b/apisix/plugins/cors.lua @@ -190,10 +190,6 @@ local function set_cors_headers(conf, ctx) end core.response.set_header("Access-Control-Allow-Origin", ctx.cors_allow_origins) - if ctx.cors_allow_origins ~= "*" then - core.response.add_header("Vary", "Origin") - end - core.response.set_header("Access-Control-Allow-Methods", allow_methods) core.response.set_header("Access-Control-Max-Age", conf.max_age) core.response.set_header("Access-Control-Expose-Headers", conf.expose_headers) @@ -308,6 +304,9 @@ function _M.header_filter(conf, ctx) conf.allow_origins_by_metadata, ctx, req_origin ) end + if conf.allow_origins ~= "*" then + core.response.add_header("Vary", "Origin") + end if allow_origins then ctx.cors_allow_origins = allow_origins set_cors_headers(conf, ctx) diff --git a/t/plugin/cors3.t b/t/plugin/cors3.t index 92210a1a3093..ae68dec3f549 100644 --- a/t/plugin/cors3.t +++ b/t/plugin/cors3.t @@ -163,7 +163,7 @@ Origin: http://foo.example.org hello world --- response_headers Access-Control-Allow-Origin: -Vary: +Vary: Origin Access-Control-Allow-Methods: Access-Control-Allow-Headers: Access-Control-Expose-Headers: @@ -254,7 +254,7 @@ Origin: http://foo.example.org hello world --- response_headers Access-Control-Allow-Origin: -Vary: +Vary: Origin Access-Control-Allow-Methods: Access-Control-Allow-Headers: Access-Control-Expose-Headers: