Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(event_handler): escape OpenAPI schema on Swagger UI #3606

Merged
merged 3 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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