Skip to content

Commit e34f719

Browse files
fix(event_handler): escape OpenAPI schema on Swagger UI (#3606)
* fix(event_handler): escape OpenAPI schema on Swagger UI * fix: avoid the json loads/dumps --------- Co-authored-by: Leandro Damascena <[email protected]>
1 parent 37e23b6 commit e34f719

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

aws_lambda_powertools/event_handler/api_gateway.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1627,7 +1627,7 @@ def swagger_handler():
16271627

16281628
openapi_servers = servers or [Server(url=(base_path or "/"))]
16291629

1630-
spec = self.get_openapi_json_schema(
1630+
spec = self.get_openapi_schema(
16311631
title=title,
16321632
version=version,
16331633
openapi_version=openapi_version,

aws_lambda_powertools/event_handler/openapi/swagger_ui/html.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,35 @@
1-
def generate_swagger_html(spec: str, js_url: str, css_url: str) -> str:
1+
from typing import TYPE_CHECKING
2+
3+
if TYPE_CHECKING:
4+
from aws_lambda_powertools.event_handler.openapi.models import OpenAPI
5+
6+
7+
def generate_swagger_html(spec: "OpenAPI", js_url: str, css_url: str) -> str:
28
"""
39
Generate Swagger UI HTML page
410
511
Parameters
612
----------
7-
spec: str
8-
The OpenAPI spec in the JSON format
13+
spec: OpenAPI
14+
The OpenAPI spec
915
js_url: str
1016
The URL to the Swagger UI JavaScript file
1117
css_url: str
1218
The URL to the Swagger UI CSS file
1319
"""
20+
21+
from aws_lambda_powertools.event_handler.openapi.compat import model_json
22+
23+
# The .replace('</', '<\\/') part is necessary to prevent a potential issue where the JSON string contains
24+
# </script> or similar tags. Escaping the forward slash in </ as <\/ ensures that the JSON does not inadvertently
25+
# close the script tag, and the JSON remains a valid string within the JavaScript code.
26+
escaped_spec = model_json(
27+
spec,
28+
by_alias=True,
29+
exclude_none=True,
30+
indent=2,
31+
).replace("</", "<\\/")
32+
1433
return f"""
1534
<!DOCTYPE html>
1635
<html>
@@ -41,9 +60,7 @@ def generate_swagger_html(spec: str, js_url: str, css_url: str) -> str:
4160
layout: "BaseLayout",
4261
showExtensions: true,
4362
showCommonExtensions: true,
44-
spec: JSON.parse(`
45-
{spec}
46-
`.trim()),
63+
spec: {escaped_spec},
4764
presets: [
4865
SwaggerUIBundle.presets.apis,
4966
SwaggerUIBundle.SwaggerUIStandalonePreset

0 commit comments

Comments
 (0)