mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
fix(security): cors misconfiguration allows credentialed cross-or
The API base handler sets `Access-Control-Allow-Credentials: true` together with `Access-Control-Allow-Origin: *`. Browsers treat this combination as invalid/insecure and it often leads to unsafe CORS behavior when later changed to reflected origins. This is especially risky because `authorization` is explicitly allowed in request headers. Affected files: base_handler.py Signed-off-by: tuanaiseo <221258316+tuanaiseo@users.noreply.github.com>
This commit is contained in:
parent
c5f82369e5
commit
6044d0e42f
1 changed files with 14 additions and 4 deletions
|
|
@ -7,18 +7,28 @@ class BaseHandler:
|
|||
self.config = config
|
||||
self.logger = setup_logging()
|
||||
|
||||
def _add_cors_headers(self, response):
|
||||
def _add_cors_headers(self, response, request=None):
|
||||
"""添加CORS头信息"""
|
||||
response.headers["Access-Control-Allow-Headers"] = (
|
||||
"client-id, content-type, device-id, authorization"
|
||||
)
|
||||
response.headers["Access-Control-Allow-Credentials"] = "true"
|
||||
response.headers["Access-Control-Allow-Origin"] = "*"
|
||||
|
||||
trusted_origins = self.config.get("trusted_origins") or self.config.get(
|
||||
"cors_allowed_origins"
|
||||
) or []
|
||||
if isinstance(trusted_origins, str):
|
||||
trusted_origins = [trusted_origins]
|
||||
|
||||
origin = request.headers.get("Origin") if request else None
|
||||
if origin in trusted_origins:
|
||||
response.headers["Access-Control-Allow-Origin"] = origin
|
||||
response.headers["Access-Control-Allow-Credentials"] = "true"
|
||||
response.headers["Vary"] = "Origin"
|
||||
|
||||
async def handle_options(self, request):
|
||||
"""处理OPTIONS请求,添加CORS头信息"""
|
||||
response = web.Response(body=b"", content_type="text/plain")
|
||||
self._add_cors_headers(response)
|
||||
self._add_cors_headers(response, request)
|
||||
# 添加允许的方法
|
||||
response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
|
||||
return response
|
||||
|
|
|
|||
Loading…
Reference in a new issue