|
| 1 | +# ruff: noqa: E501 |
| 2 | +import warnings |
| 3 | +from typing import Dict, Optional, Sequence |
| 4 | + |
| 5 | +from pydantic import BaseModel, Field, validator |
| 6 | + |
| 7 | +from aws_lambda_powertools.event_handler.openapi.pydantic_loader import PYDANTIC_V2 |
| 8 | +from aws_lambda_powertools.shared.functions import powertools_dev_is_set |
| 9 | + |
| 10 | + |
| 11 | +# Based on https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/ |
| 12 | +class OAuth2Config(BaseModel): |
| 13 | + """ |
| 14 | + OAuth2 configuration for Swagger UI |
| 15 | + """ |
| 16 | + |
| 17 | + # The client ID for the OAuth2 application |
| 18 | + clientId: Optional[str] = Field(alias="client_id", default=None) |
| 19 | + |
| 20 | + # The client secret for the OAuth2 application. This is sensitive information and requires the explicit presence |
| 21 | + # of the POWERTOOLS_DEV environment variable. |
| 22 | + clientSecret: Optional[str] = Field(alias="client_secret", default=None) |
| 23 | + |
| 24 | + # The realm in which the OAuth2 application is registered. Optional. |
| 25 | + realm: Optional[str] = Field(default=None) |
| 26 | + |
| 27 | + # The name of the OAuth2 application |
| 28 | + appName: str = Field(alias="app_name") |
| 29 | + |
| 30 | + # The scopes that the OAuth2 application requires. Defaults to an empty list. |
| 31 | + scopes: Sequence[str] = Field(default=[]) |
| 32 | + |
| 33 | + # Additional query string parameters to be included in the OAuth2 request. Defaults to an empty dictionary. |
| 34 | + additionalQueryStringParams: Dict[str, str] = Field(alias="additional_query_string_params", default={}) |
| 35 | + |
| 36 | + # Whether to use basic authentication with the access code grant type. Defaults to False. |
| 37 | + useBasicAuthenticationWithAccessCodeGrant: bool = Field( |
| 38 | + alias="use_basic_authentication_with_access_code_grant", |
| 39 | + default=False, |
| 40 | + ) |
| 41 | + |
| 42 | + # Whether to use PKCE with the authorization code grant type. Defaults to False. |
| 43 | + usePkceWithAuthorizationCodeGrant: bool = Field(alias="use_pkce_with_authorization_code_grant", default=False) |
| 44 | + |
| 45 | + if PYDANTIC_V2: |
| 46 | + model_config = {"extra": "allow"} |
| 47 | + else: |
| 48 | + |
| 49 | + class Config: |
| 50 | + extra = "allow" |
| 51 | + allow_population_by_field_name = True |
| 52 | + |
| 53 | + @validator("clientSecret", always=True) |
| 54 | + def client_secret_only_on_dev(cls, v: Optional[str]) -> Optional[str]: |
| 55 | + if not v: |
| 56 | + return None |
| 57 | + |
| 58 | + if not powertools_dev_is_set(): |
| 59 | + raise ValueError( |
| 60 | + "cannot use client_secret without POWERTOOLS_DEV mode. See " |
| 61 | + "https://docs.powertools.aws.dev/lambda/python/latest/#optimizing-for-non-production-environments", |
| 62 | + ) |
| 63 | + else: |
| 64 | + warnings.warn( |
| 65 | + "OAuth2Config is using client_secret and POWERTOOLS_DEV is set. This reveals sensitive information. " |
| 66 | + "DO NOT USE THIS OUTSIDE LOCAL DEVELOPMENT", |
| 67 | + stacklevel=2, |
| 68 | + ) |
| 69 | + return v |
| 70 | + |
| 71 | + |
| 72 | +def generate_oauth2_redirect_html() -> str: |
| 73 | + """ |
| 74 | + Generates the HTML content for the OAuth2 redirect page. |
| 75 | +
|
| 76 | + Source: https://github.com/swagger-api/swagger-ui/blob/master/dist/oauth2-redirect.html |
| 77 | + """ |
| 78 | + return """ |
| 79 | +<!doctype html> |
| 80 | +<html lang="en-US"> |
| 81 | +<head> |
| 82 | + <title>Swagger UI: OAuth2 Redirect</title> |
| 83 | +</head> |
| 84 | +<body> |
| 85 | +<script> |
| 86 | + 'use strict'; |
| 87 | + function run () { |
| 88 | + var oauth2 = window.opener.swaggerUIRedirectOauth2; |
| 89 | + var sentState = oauth2.state; |
| 90 | + var redirectUrl = oauth2.redirectUrl; |
| 91 | + var isValid, qp, arr; |
| 92 | +
|
| 93 | + if (/code|token|error/.test(window.location.hash)) { |
| 94 | + qp = window.location.hash.substring(1).replace('?', '&'); |
| 95 | + } else { |
| 96 | + qp = location.search.substring(1); |
| 97 | + } |
| 98 | +
|
| 99 | + arr = qp.split("&"); |
| 100 | + arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';}); |
| 101 | + qp = qp ? JSON.parse('{' + arr.join() + '}', |
| 102 | + function (key, value) { |
| 103 | + return key === "" ? value : decodeURIComponent(value); |
| 104 | + } |
| 105 | + ) : {}; |
| 106 | +
|
| 107 | + isValid = qp.state === sentState; |
| 108 | +
|
| 109 | + if (( |
| 110 | + oauth2.auth.schema.get("flow") === "accessCode" || |
| 111 | + oauth2.auth.schema.get("flow") === "authorizationCode" || |
| 112 | + oauth2.auth.schema.get("flow") === "authorization_code" |
| 113 | + ) && !oauth2.auth.code) { |
| 114 | + if (!isValid) { |
| 115 | + oauth2.errCb({ |
| 116 | + authId: oauth2.auth.name, |
| 117 | + source: "auth", |
| 118 | + level: "warning", |
| 119 | + message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server." |
| 120 | + }); |
| 121 | + } |
| 122 | +
|
| 123 | + if (qp.code) { |
| 124 | + delete oauth2.state; |
| 125 | + oauth2.auth.code = qp.code; |
| 126 | + oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl}); |
| 127 | + } else { |
| 128 | + let oauthErrorMsg; |
| 129 | + if (qp.error) { |
| 130 | + oauthErrorMsg = "["+qp.error+"]: " + |
| 131 | + (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") + |
| 132 | + (qp.error_uri ? "More info: "+qp.error_uri : ""); |
| 133 | + } |
| 134 | +
|
| 135 | + oauth2.errCb({ |
| 136 | + authId: oauth2.auth.name, |
| 137 | + source: "auth", |
| 138 | + level: "error", |
| 139 | + message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server." |
| 140 | + }); |
| 141 | + } |
| 142 | + } else { |
| 143 | + oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl}); |
| 144 | + } |
| 145 | + window.close(); |
| 146 | + } |
| 147 | +
|
| 148 | + if (document.readyState !== 'loading') { |
| 149 | + run(); |
| 150 | + } else { |
| 151 | + document.addEventListener('DOMContentLoaded', function () { |
| 152 | + run(); |
| 153 | + }); |
| 154 | + } |
| 155 | +</script> |
| 156 | +</body> |
| 157 | +</html> |
| 158 | + """.strip() |
0 commit comments