Skip to content

Commit

Permalink
fix(event_handler): escape OpenAPI schema on Swagger UI (#3606)
Browse files Browse the repository at this point in the history
* fix(event_handler): escape OpenAPI schema on Swagger UI

* fix: avoid the json loads/dumps

---------

Co-authored-by: Leandro Damascena <lcdama@amazon.pt>
  • Loading branch information
rubenfonseca and leandrodamascena authored Jan 9, 2024
1 parent 37e23b6 commit e34f719
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
2 changes: 1 addition & 1 deletion aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -1627,7 +1627,7 @@ def swagger_handler():

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

spec = self.get_openapi_json_schema(
spec = self.get_openapi_schema(
title=title,
version=version,
openapi_version=openapi_version,
Expand Down
29 changes: 23 additions & 6 deletions aws_lambda_powertools/event_handler/openapi/swagger_ui/html.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,35 @@
def generate_swagger_html(spec: str, js_url: str, css_url: str) -> str:
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from aws_lambda_powertools.event_handler.openapi.models import OpenAPI


def generate_swagger_html(spec: "OpenAPI", js_url: str, css_url: str) -> str:
"""
Generate Swagger UI HTML page
Parameters
----------
spec: str
The OpenAPI spec in the JSON format
spec: OpenAPI
The OpenAPI spec
js_url: str
The URL to the Swagger UI JavaScript file
css_url: str
The URL to the Swagger UI CSS file
"""

from aws_lambda_powertools.event_handler.openapi.compat import model_json

# The .replace('</', '<\\/') part is necessary to prevent a potential issue where the JSON string contains
# </script> or similar tags. Escaping the forward slash in </ as <\/ ensures that the JSON does not inadvertently
# close the script tag, and the JSON remains a valid string within the JavaScript code.
escaped_spec = model_json(
spec,
by_alias=True,
exclude_none=True,
indent=2,
).replace("</", "<\\/")

return f"""
<!DOCTYPE html>
<html>
Expand Down Expand Up @@ -41,9 +60,7 @@ def generate_swagger_html(spec: str, js_url: str, css_url: str) -> str:
layout: "BaseLayout",
showExtensions: true,
showCommonExtensions: true,
spec: JSON.parse(`
{spec}
`.trim()),
spec: {escaped_spec},
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
Expand Down

0 comments on commit e34f719

Please sign in to comment.