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

feat(event_handler): add support for persisting authorization session in OpenAPI #4312

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
4 changes: 4 additions & 0 deletions aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -1753,6 +1753,7 @@ def enable_swagger(
security_schemes: Optional[Dict[str, "SecurityScheme"]] = None,
security: Optional[List[Dict[str, List[str]]]] = None,
oauth2_config: Optional["OAuth2Config"] = None,
persist_authorization: bool = False,
):
"""
Returns the OpenAPI schema as a JSON serializable dict
Expand Down Expand Up @@ -1793,6 +1794,8 @@ def enable_swagger(
A declaration of which security mechanisms are applied globally across the API.
oauth2_config: OAuth2Config, optional
The OAuth2 configuration for the Swagger UI.
persist_authorization: bool, optional
Whether to persist authorization data on browser close/refresh.
"""
from aws_lambda_powertools.event_handler.openapi.compat import model_json
from aws_lambda_powertools.event_handler.openapi.models import Server
Expand Down Expand Up @@ -1871,6 +1874,7 @@ def swagger_handler():
swagger_css,
swagger_base_url,
oauth2_config,
persist_authorization,
)

return Response(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ def generate_swagger_html(
swagger_css: str,
swagger_base_url: str,
oauth2_config: Optional[OAuth2Config],
persist_authorization: bool = False,
) -> str:
"""
Generate Swagger UI HTML page
Expand All @@ -28,6 +29,8 @@ def generate_swagger_html(
The base URL for Swagger UI
oauth2_config: OAuth2Config, optional
The OAuth2 configuration.
persist_authorization: bool, optional
Whether to persist authorization data on browser close/refresh.
"""

# If Swagger base URL is present, generate HTML content with linked CSS and JavaScript files
Expand Down Expand Up @@ -86,6 +89,7 @@ def generate_swagger_html(
SwaggerUIBundle.plugins.DownloadUrl
],
withCredentials: true,
persistAuthorization: {str(persist_authorization).lower()},
oauth2RedirectUrl: baseUrl + "?format=oauth2-redirect",
}}

Expand Down
13 changes: 7 additions & 6 deletions docs/core/event_handler/api_gateway.md
Original file line number Diff line number Diff line change
Expand Up @@ -524,12 +524,13 @@ Behind the scenes, the [data validation](#data-validation) feature auto-generate

There are some important **caveats** that you should know before enabling it:

| Caveat | Description |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Swagger UI is **publicly accessible by default** | When using `enable_swagger` method, you can [protect sensitive API endpoints by implementing a custom middleware](#customizing-swagger-ui) using your preferred authorization mechanism. |
| **No micro-functions support** yet | Swagger UI is enabled on a per resolver instance which will limit its accuracy here. |
| You need to expose a **new route** | You'll need to expose the following path to Lambda: `/swagger`; ignore if you're routing this path already. |
| JS and CSS files are **embedded within Swagger HTML** | If you are not using an external CDN to serve Swagger UI assets, we embed JS and CSS directly into the HTML. To enhance performance, please consider enabling the `compress` option to minimize the size of HTTP requests. |
| Caveat | Description |
| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Swagger UI is **publicly accessible by default** | When using `enable_swagger` method, you can [protect sensitive API endpoints by implementing a custom middleware](#customizing-swagger-ui) using your preferred authorization mechanism. |
| **No micro-functions support** yet | Swagger UI is enabled on a per resolver instance which will limit its accuracy here. |
| You need to expose a **new route** | You'll need to expose the following path to Lambda: `/swagger`; ignore if you're routing this path already. |
| JS and CSS files are **embedded within Swagger HTML** | If you are not using an external CDN to serve Swagger UI assets, we embed JS and CSS directly into the HTML. To enhance performance, please consider enabling the `compress` option to minimize the size of HTTP requests. |
| Authorization data is **lost** on browser close/refresh | Use `enable_swagger(persist_authorization=True)` to persist authorization data, like OAuath 2.0 access tokens. |

```python hl_lines="12-13" title="enabling_swagger.py"
--8<-- "examples/event_handler_rest/src/enabling_swagger.py"
Expand Down
12 changes: 12 additions & 0 deletions tests/functional/event_handler/test_openapi_swagger.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,18 @@ def test_openapi_swagger_with_rest_api_stage():
assert "ui.specActions.updateUrl('/prod/swagger?format=json')" in result["body"]


def test_openapi_swagger_with_persist_authorization():
app = APIGatewayRestResolver(enable_validation=True)
app.enable_swagger(persist_authorization=True)

event = load_event("apiGatewayProxyEvent.json")
event["path"] = "/swagger"

result = app(event, {})
assert result["statusCode"] == 200
assert "persistAuthorization: true" in result["body"]


def test_openapi_swagger_oauth2_without_powertools_dev():
with pytest.raises(ValueError) as exc:
OAuth2Config(app_name="OAuth2 app", client_id="client_id", client_secret="verysecret")
Expand Down