From 0254c9db372bf4e0a45f0ed58b8e866ec1616a38 Mon Sep 17 00:00:00 2001 From: john court Date: Wed, 22 Dec 2021 17:50:17 +1000 Subject: [PATCH] Add fix for #1575 to allow OPTIONS method to work when x-api-key is configured Signed-off-by: john court --- aries_cloudagent/admin/server.py | 7 ++++++- .../admin/tests/test_admin_server.py | 20 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/aries_cloudagent/admin/server.py b/aries_cloudagent/admin/server.py index 4e35200cc5..f552cf211a 100644 --- a/aries_cloudagent/admin/server.py +++ b/aries_cloudagent/admin/server.py @@ -289,7 +289,12 @@ async def check_token(request: web.Request, handler): header_admin_api_key = request.headers.get("x-api-key") valid_key = const_compare(self.admin_api_key, header_admin_api_key) - if valid_key or is_unprotected_path(request.path): + # We have to allow OPTIONS method access to paths without a key since + # browsers performing CORS requests will never include the original + # x-api-key header from the method that triggered the preflight + # OPTIONS check. + if (valid_key or is_unprotected_path(request.path) + or (request.method == "OPTIONS")): return await handler(request) else: raise web.HTTPUnauthorized() diff --git a/aries_cloudagent/admin/tests/test_admin_server.py b/aries_cloudagent/admin/tests/test_admin_server.py index fff43f97d4..9b24f215d7 100644 --- a/aries_cloudagent/admin/tests/test_admin_server.py +++ b/aries_cloudagent/admin/tests/test_admin_server.py @@ -340,6 +340,26 @@ async def test_visit_secure_mode(self): ) as response: assert response.status == 200 + # Make sure that OPTIONS requests used by browsers for CORS + # are allowed without a x-api-key even when x-api-key security is enabled + async with self.client_session.options( + f"http://127.0.0.1:{self.port}/status", + headers={"Access-Control-Request-Headers": "x-api-key", + "Access-Control-Request-Method": "GET", + "Connection": "keep-alive", + "Host": f"http://127.0.0.1:{self.port}/status", + "Origin": "http://localhost:3000", + "Referer": "http://localhost:3000/", + "Sec-Fetch-Dest": "empty", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Site": "same-site"} + ) as response: + assert response.status == 200 + assert response.headers["Access-Control-Allow-Credentials"] == "true" + assert response.headers["Access-Control-Allow-Headers"] == "X-API-KEY" + assert response.headers["Access-Control-Allow-Methods"] == "GET" + assert response.headers["Access-Control-Allow-Origin"] == "http://localhost:3000" + async with self.client_session.ws_connect( f"http://127.0.0.1:{self.port}/ws", headers={"x-api-key": "test-api-key"} ) as ws: