Skip to content

Instantly share code, notes, and snippets.

@scorphus
Created April 2, 2021 15:56
Show Gist options
  • Save scorphus/8c645b1a9f9192fb946266af00257300 to your computer and use it in GitHub Desktop.
Save scorphus/8c645b1a9f9192fb946266af00257300 to your computer and use it in GitHub Desktop.
Hacking FastAPI + Redoc
from openapi import get_redoc_html
def serve_docs_route():
return get_redoc_html("openapi_url", "title")
from application import serve_docs_route
from openapi import get_redoc_html
from pprint import pprint
from unittest.mock import Mock
from unittest.mock import patch
def read_redoc_lines():
with open("redoc_hack.html") as fd:
return fd.readlines()
def my_get_redoc_html(*args, **kwargs):
result = get_redoc_html(*args, **kwargs)
search = "</script>\n </body>\n </html>"
insert = " ".join(read_redoc_lines())
replace = f"</script>\n {insert}\n </body>\n </html>"
return result.replace(search, replace)
get_redoc_html_patcher = patch(
"application.get_redoc_html", Mock(side_effect=my_get_redoc_html)
)
get_redoc_html_mock = get_redoc_html_patcher.start()
print(serve_docs_route())
# you can stop the patcher, if necessary:
get_redoc_html_patcher.stop()
# if this was a test, you could assert things, such as:
get_redoc_html_mock.assert_called_once()
# and also inspect the calls:
pprint(get_redoc_html_mock.call_args_list)
def get_redoc_html(
openapi_url: str,
title: str,
redoc_js_url: str = "https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js",
redoc_favicon_url: str = "https://fastapi.tiangolo.com/img/favicon.png",
with_google_fonts: bool = True,
) -> str:
html = f"""
<!DOCTYPE html>
<html>
<head>
<title>{title}</title>
<!-- needed for adaptive design -->
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
"""
if with_google_fonts:
html += """
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
"""
html += f"""
<link rel="shortcut icon" href="{redoc_favicon_url}">
<!--
ReDoc doesn't change outer page styles
-->
<style>
body {{
margin: 0;
padding: 0;
}}
</style>
</head>
<body>
<redoc spec-url="{openapi_url}"></redoc>
<script src="{redoc_js_url}"> </script>
</body>
</html>
"""
return html
<script>
console.log("you've been hacked");
console.log("by an ugly hack");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment