Skip to content

Commit 6d63dce

Browse files
fix: Clickjacking Attack
1 parent fe1bfcf commit 6d63dce

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

backend/apps/system/crud/assistant.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from common.utils.aes_crypto import simple_aes_decrypt
2222
from common.utils.utils import SQLBotLogUtil, equals_ignore_case, get_domain_list, string_to_numeric_hash
2323
from common.core.deps import Trans
24+
from common.core.response_middleware import ResponseMiddleware
2425

2526

2627
@cache(namespace=CacheNamespace.EMBEDDED_INFO, cacheName=CacheName.ASSISTANT_INFO, keyExpression="assistant_id")
@@ -87,13 +88,20 @@ def init_dynamic_cors(app: FastAPI):
8788
seen.add(domain)
8889
unique_domains.append(domain)
8990
cors_middleware = None
91+
response_middleware = None
9092
for middleware in app.user_middleware:
91-
if middleware.cls == CORSMiddleware:
93+
if not cors_middleware and middleware.cls == CORSMiddleware:
9294
cors_middleware = middleware
95+
if not response_middleware and middleware.cls == ResponseMiddleware:
96+
response_middleware = middleware
97+
if cors_middleware and response_middleware:
9398
break
99+
100+
updated_origins = list(set(settings.all_cors_origins + unique_domains))
94101
if cors_middleware:
95-
updated_origins = list(set(settings.all_cors_origins + unique_domains))
96102
cors_middleware.kwargs['allow_origins'] = updated_origins
103+
if response_middleware:
104+
response_middleware.kwargs['allow_origins'] = updated_origins
97105
except Exception as e:
98106
return False, e
99107

backend/common/core/response_middleware.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
22

3+
from redis import typing
34
from starlette.exceptions import HTTPException
45
from starlette.middleware.base import BaseHTTPMiddleware
56
from starlette.requests import Request
@@ -11,6 +12,7 @@
1112

1213
class ResponseMiddleware(BaseHTTPMiddleware):
1314
def __init__(self, app):
15+
self.allow_origins = ["'self'"]
1416
super().__init__(app)
1517

1618
async def dispatch(self, request, call_next):
@@ -76,7 +78,13 @@ async def dispatch(self, request, call_next):
7678
if k.lower() not in ("content-length", "content-type")
7779
}
7880
)
79-
81+
content_type = response.headers.get("content-type", "")
82+
static_content_types = ["text/html", "javascript", "typescript", "css"]
83+
if any(ct in content_type for ct in static_content_types):
84+
if self.allow_origins:
85+
frame_ancestors_value = " ".join(self.allow_origins)
86+
response.headers["Content-Security-Policy"] = f"frame-ancestors {frame_ancestors_value};"
87+
8088
return response
8189

8290

0 commit comments

Comments
 (0)