diff --git a/aries_cloudagent/admin/server.py b/aries_cloudagent/admin/server.py index 4e35200cc5..01b3b2196f 100644 --- a/aries_cloudagent/admin/server.py +++ b/aries_cloudagent/admin/server.py @@ -289,7 +289,15 @@ 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..7707315e12 100644 --- a/aries_cloudagent/admin/tests/test_admin_server.py +++ b/aries_cloudagent/admin/tests/test_admin_server.py @@ -340,6 +340,31 @@ 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: