From f125c7d2ca81b8de6332c0c4e0003cc57a7b0060 Mon Sep 17 00:00:00 2001 From: Guilherme Date: Fri, 16 Oct 2026 14:44:46 -0300 Subject: [PATCH 1/5] feat: creates files and its tests for google authorizer --- src/modules/google_authorizer/__init__.py | 0 src/modules/google_authorizer/app/__init__.py | 0 .../app/google_authorizer_presenter.py | 32 ++++++++ .../app/google_authorizer_usecase.py | 58 ++++++++++++++ src/shared/infra/external/google/__init__.py | 0 .../external/google/google_id_token_client.py | 43 ++++++++++ .../app/test_google_authorizer_presenter.py | 25 ++++++ .../app/test_google_authorizer_usecase.py | 80 +++++++++++++++++++ .../google/test_google_id_token_client.py | 37 +++++++++ 9 files changed, 275 insertions(+) create mode 100644 src/modules/google_authorizer/__init__.py create mode 100644 src/modules/google_authorizer/app/__init__.py create mode 100644 src/modules/google_authorizer/app/google_authorizer_presenter.py create mode 100644 src/modules/google_authorizer/app/google_authorizer_usecase.py create mode 100644 src/shared/infra/external/google/__init__.py create mode 100644 src/shared/infra/external/google/google_id_token_client.py create mode 100644 tests/modules/google_authorizer/app/test_google_authorizer_presenter.py create mode 100644 tests/modules/google_authorizer/app/test_google_authorizer_usecase.py create mode 100644 tests/shared/infra/external/google/test_google_id_token_client.py diff --git a/src/modules/google_authorizer/__init__.py b/src/modules/google_authorizer/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/modules/google_authorizer/app/__init__.py b/src/modules/google_authorizer/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/modules/google_authorizer/app/google_authorizer_presenter.py b/src/modules/google_authorizer/app/google_authorizer_presenter.py new file mode 100644 index 0000000..6eeb499 --- /dev/null +++ b/src/modules/google_authorizer/app/google_authorizer_presenter.py @@ -0,0 +1,32 @@ +import logging +import os +from typing import Any + +from src.modules.google_authorizer.app.google_authorizer_usecase import ( + GoogleAuthorizerUsecase, +) +from src.shared.helpers.auth.iam_policy import generate_policy +from src.shared.infra.external.google.google_id_token_client import GoogleIdTokenClient + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +google_id_token_client = GoogleIdTokenClient( + client_id=os.environ.get("GOOGLE_CLIENT_ID", "") +) +usecase = GoogleAuthorizerUsecase(google_id_token_client=google_id_token_client) + + +def lambda_handler(event: dict[str, Any], _: Any) -> dict[str, Any]: + method_arn = event.get("methodArn") + if not isinstance(method_arn, str) or not method_arn: + raise ValueError("methodArn ausente no evento do authorizer") + + try: + return usecase( + authorization_token=event.get("authorizationToken"), + method_arn=method_arn, + ) + except Exception as error: + logger.warning("Autorização Google negada (%s)", type(error).__name__) + return generate_policy("user", "Deny", method_arn) diff --git a/src/modules/google_authorizer/app/google_authorizer_usecase.py b/src/modules/google_authorizer/app/google_authorizer_usecase.py new file mode 100644 index 0000000..afeaa10 --- /dev/null +++ b/src/modules/google_authorizer/app/google_authorizer_usecase.py @@ -0,0 +1,58 @@ +import re +from typing import Any + +from src.shared.helpers.auth.authorizer_user import build_authorizer_user_context +from src.shared.helpers.auth.iam_policy import generate_policy +from src.shared.infra.external.google.google_id_token_client import GoogleIdTokenClient + + +class GoogleAuthorizerUsecase: + def __init__(self, google_id_token_client: GoogleIdTokenClient): + self.google_id_token_client = google_id_token_client + + def __call__( + self, + authorization_token: str | None, + method_arn: str, + ) -> dict[str, Any]: + if not isinstance(authorization_token, str): + raise ValueError("Authorization inválido") + + match = re.fullmatch( + r"Bearer\s+(\S+)", + authorization_token.strip(), + re.IGNORECASE, + ) + if match is None: + raise ValueError("Bearer token ausente ou inválido") + + claims = self.google_id_token_client.verify_id_token(match.group(1)) + sub = claims.get("sub") + mail = claims.get("email") + name = claims.get("name") or "" + + if ( + not isinstance(sub, str) + or not sub.strip() + or not isinstance(mail, str) + or not mail.strip() + or claims.get("email_verified") is not True + ): + return generate_policy("user", "Deny", method_arn) + + if not isinstance(name, str): + name = "" + + sub = sub.strip() + mail = mail.strip().lower() + + return generate_policy( + principal_id=sub, + effect="Allow", + method_arn=method_arn, + context=build_authorizer_user_context( + sub=sub, + mail=mail, + name=name.strip(), + ), + ) diff --git a/src/shared/infra/external/google/__init__.py b/src/shared/infra/external/google/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/shared/infra/external/google/google_id_token_client.py b/src/shared/infra/external/google/google_id_token_client.py new file mode 100644 index 0000000..b89e2b5 --- /dev/null +++ b/src/shared/infra/external/google/google_id_token_client.py @@ -0,0 +1,43 @@ +from collections.abc import Callable, Mapping +from typing import Any, cast + +from google.auth.transport.requests import Request +from google.oauth2 import id_token + + +class GoogleIdTokenClient: + def __init__(self, client_id: str, request: Request | None = None): + self.client_id = client_id + self.request = request or Request() + + def _request_google_certificates( + self, + url: str, + method: str = "GET", + body: bytes | None = None, + headers: Mapping[str, str] | None = None, + **kwargs: Any, + ) -> Any: + kwargs.pop("timeout", None) + return self.request( + url, + method=method, + body=body, + headers=headers, + timeout=5, + **kwargs, + ) + + def verify_id_token(self, token: str) -> Mapping[str, Any]: + if not self.client_id: + raise ValueError("GOOGLE_CLIENT_ID não configurado") + + verify_google_token = cast( + Callable[[str, Callable[..., Any], str], Mapping[str, Any]], + id_token.verify_oauth2_token, # type: ignore[reportUnknownMemberType] + ) + return verify_google_token( + token, + self._request_google_certificates, + self.client_id, + ) diff --git a/tests/modules/google_authorizer/app/test_google_authorizer_presenter.py b/tests/modules/google_authorizer/app/test_google_authorizer_presenter.py new file mode 100644 index 0000000..61af01f --- /dev/null +++ b/tests/modules/google_authorizer/app/test_google_authorizer_presenter.py @@ -0,0 +1,25 @@ +from unittest.mock import Mock + +import pytest + +from src.modules.google_authorizer.app import google_authorizer_presenter as presenter + +ARN = "arn:aws:execute-api:sa-east-1:123456789012:api/dev/GET/users" + + +def test_presenter_denies_google_failure_without_logging_token(monkeypatch, caplog): + usecase = Mock(side_effect=ValueError("secret-google-token")) + monkeypatch.setattr(presenter, "usecase", usecase) + + result = presenter.lambda_handler( + {"methodArn": ARN, "authorizationToken": "Bearer secret-google-token"}, + None, + ) + + assert result["policyDocument"]["Statement"][0]["Effect"] == "Deny" + assert "secret-google-token" not in caplog.text + + +def test_presenter_missing_arn_is_configuration_error(): + with pytest.raises(ValueError, match="methodArn"): + presenter.lambda_handler({}, None) diff --git a/tests/modules/google_authorizer/app/test_google_authorizer_usecase.py b/tests/modules/google_authorizer/app/test_google_authorizer_usecase.py new file mode 100644 index 0000000..5f8ec61 --- /dev/null +++ b/tests/modules/google_authorizer/app/test_google_authorizer_usecase.py @@ -0,0 +1,80 @@ +import json +from unittest.mock import Mock + +import pytest + +from src.modules.google_authorizer.app.google_authorizer_usecase import ( + GoogleAuthorizerUsecase, +) + +ARN = "arn:aws:execute-api:sa-east-1:123456789012:api/dev/GET/users" +CLAIMS = { + "sub": "google-subject-id", + "email": "Alice@Example.com", + "email_verified": True, + "name": " Alice User ", +} + + +def make_usecase(claims=None): + google_id_token_client = Mock() + google_id_token_client.verify_id_token.return_value = ( + CLAIMS if claims is None else claims + ) + return GoogleAuthorizerUsecase(google_id_token_client), google_id_token_client + + +def test_valid_google_claims_build_expected_context(): + usecase, client = make_usecase() + + result = usecase("Bearer google-id-token", ARN) + + client.verify_id_token.assert_called_once_with("google-id-token") + statement = result["policyDocument"]["Statement"][0] + assert statement["Effect"] == "Allow" + assert statement["Resource"] == ARN + assert json.loads(result["context"]["user"]) == { + "sub": "google-subject-id", + "mail": "alice@example.com", + "name": "Alice User", + } + + +def test_google_sub_is_not_required_to_be_uuid(): + usecase, _ = make_usecase({**CLAIMS, "sub": "opaque-google-sub"}) + + result = usecase("Bearer google-id-token", ARN) + + assert result["principalId"] == "opaque-google-sub" + + +@pytest.mark.parametrize( + "changes", + [ + {"email_verified": False}, + {"email": None}, + {"email": 123}, + {"sub": None}, + {"sub": ""}, + ], +) +def test_invalid_google_claims_are_denied(changes): + usecase, _ = make_usecase({**CLAIMS, **changes}) + + result = usecase("Bearer google-id-token", ARN) + + assert result["policyDocument"]["Statement"][0]["Effect"] == "Deny" + assert "context" not in result + + +@pytest.mark.parametrize( + "authorization_token", + [None, "", "google-id-token", "Bearer ", "Bearer token two"], +) +def test_invalid_bearer_does_not_call_google(authorization_token): + usecase, client = make_usecase() + + with pytest.raises(ValueError): + usecase(authorization_token, ARN) + + client.verify_id_token.assert_not_called() diff --git a/tests/shared/infra/external/google/test_google_id_token_client.py b/tests/shared/infra/external/google/test_google_id_token_client.py new file mode 100644 index 0000000..af4f926 --- /dev/null +++ b/tests/shared/infra/external/google/test_google_id_token_client.py @@ -0,0 +1,37 @@ +from unittest.mock import Mock, patch + +import pytest + +from src.shared.infra.external.google.google_id_token_client import GoogleIdTokenClient + + +@patch("src.shared.infra.external.google.google_id_token_client.id_token.verify_oauth2_token") +def test_verifies_google_id_token_against_configured_client_id(verify_token): + claims = {"sub": "google-subject"} + verify_token.return_value = claims + client = GoogleIdTokenClient(client_id="google-client-id") + response = object() + client.request = Mock(return_value=response) + + result = client.verify_id_token("google-id-token") + + assert result == claims + verify_token.assert_called_once() + token, request, audience = verify_token.call_args.args + assert token == "google-id-token" + assert audience == "google-client-id" + assert request("https://www.googleapis.com/oauth2/v1/certs") is response + client.request.assert_called_once_with( + "https://www.googleapis.com/oauth2/v1/certs", + method="GET", + body=None, + headers=None, + timeout=5, + ) + + +def test_requires_google_client_id(): + client = GoogleIdTokenClient(client_id="") + + with pytest.raises(ValueError, match="GOOGLE_CLIENT_ID"): + client.verify_id_token("google-id-token") From 36ec84479fc3c1e28f11fed78c534dedc5fb784c Mon Sep 17 00:00:00 2001 From: Guilherme Date: Fri, 16 Oct 2026 14:47:19 -0300 Subject: [PATCH 2/5] update: updates requirements for google authorizer --- .github/workflows/CD.yml | 1 + requirements-app.txt | 1 + requirements-dev.txt | 1 + tests/conftest.py | 4 ++++ 4 files changed, 7 insertions(+) create mode 100644 tests/conftest.py diff --git a/.github/workflows/CD.yml b/.github/workflows/CD.yml index 414d0d1..6404357 100644 --- a/.github/workflows/CD.yml +++ b/.github/workflows/CD.yml @@ -85,3 +85,4 @@ jobs: GITHUB_REF_NAME: ${{ github.ref_name }} MSS_NAME: ${{ github.event.repository.name }} GRAPH_MICROSOFT_ENDPOINT: ${{ vars.GRAPH_MICROSOFT_ENDPOINT }} + GOOGLE_CLIENT_ID: ${{ vars.GOOGLE_CLIENT_ID }} diff --git a/requirements-app.txt b/requirements-app.txt index 8ddb8fa..31cc0da 100644 --- a/requirements-app.txt +++ b/requirements-app.txt @@ -4,3 +4,4 @@ email-validator==2.2.0 urllib3>=2.0.0 # só usado por ObservabilityAWS (wrapper); testes locais usam ObservabilityMock aws-lambda-powertools>=3.0.0 +google-auth[requests]>=2.0.0 diff --git a/requirements-dev.txt b/requirements-dev.txt index 4678fdc..47c0ac1 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -3,3 +3,4 @@ pytest==8.4.1 pytest-cov==6.2.1 boto3==1.43.60 +python-dotenv diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..33fc9bc --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,4 @@ +import os + + +os.environ["STAGE"] = "TEST" From ad1c0298dc98f374f60470f56f433a52c9fdd096 Mon Sep 17 00:00:00 2001 From: Guilherme Date: Mon, 19 Oct 2026 15:43:47 -0300 Subject: [PATCH 3/5] update: updates adjust layer file --- iac/adjust_layer_directory.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/iac/adjust_layer_directory.py b/iac/adjust_layer_directory.py index 0d817fe..ee4352e 100644 --- a/iac/adjust_layer_directory.py +++ b/iac/adjust_layer_directory.py @@ -3,11 +3,10 @@ import subprocess from pathlib import Path -BUILD_DIRECTORY = "build" -PYTHON_TOP_LEVEL_DIR = os.path.join(BUILD_DIRECTORY, "python") +PROJECT_ROOT = Path(__file__).resolve().parents[1] +BUILD_DIRECTORY = PROJECT_ROOT / "iac" / "build" +PYTHON_TOP_LEVEL_DIR = BUILD_DIRECTORY / "python" REQUIREMENTS_FILE = "requirements-app.txt" - -PROJECT_ROOT = Path(__file__).parent.parent SHARED_CODE_SOURCE = os.path.join(PROJECT_ROOT, "src", "shared") @@ -18,10 +17,10 @@ def adjust_layer_directory(): A função junta o código local compartilhado e as dependências externas (pip) na estrutura de pastas que a Lambda espera (/python). """ - if os.path.exists(BUILD_DIRECTORY): + if BUILD_DIRECTORY.exists(): shutil.rmtree(BUILD_DIRECTORY) - shared_code_intermediate_dir = os.path.join(PYTHON_TOP_LEVEL_DIR, "src") + shared_code_intermediate_dir = PYTHON_TOP_LEVEL_DIR / "src" os.makedirs(shared_code_intermediate_dir) print(f"Copiando código de: {SHARED_CODE_SOURCE}") @@ -40,7 +39,7 @@ def adjust_layer_directory(): "-r", requirements_path, "-t", - PYTHON_TOP_LEVEL_DIR, + str(PYTHON_TOP_LEVEL_DIR), "--no-cache-dir", "--platform", "manylinux2014_x86_64", From 4ace5a1359c07c4328cf65d40b564916d143dd49 Mon Sep 17 00:00:00 2001 From: Guilherme Date: Mon, 19 Oct 2026 15:45:08 -0300 Subject: [PATCH 4/5] feat: create google authorizer function --- iac/components/lambda_construct.py | 42 +++++++++++++++++++++++++----- iac/stack/iac_stack.py | 1 + 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/iac/components/lambda_construct.py b/iac/components/lambda_construct.py index bdc79c9..a04aa37 100644 --- a/iac/components/lambda_construct.py +++ b/iac/components/lambda_construct.py @@ -1,3 +1,4 @@ +from pathlib import Path from typing import Optional from aws_cdk import ( @@ -8,6 +9,8 @@ from constructs import Construct from aws_cdk.aws_apigateway import Resource, LambdaIntegration +PROJECT_ROOT = Path(__file__).resolve().parents[2] + class LambdaConstruct(Construct): @@ -22,15 +25,15 @@ def create_lambda_function( environment_variables: dict, subfolder: str = "", ) -> lambda_.Function: - code = ( - lambda_.Code.from_asset(f"../src/modules/{subfolder}/{module_name}") - if subfolder - else lambda_.Code.from_asset(f"../src/modules/{module_name}") - ) + module_path = PROJECT_ROOT / "src" / "modules" + if subfolder: + module_path /= subfolder + module_path /= module_name + return lambda_.Function( self, module_name.title().replace("_", ""), - code=code, + code=lambda_.Code.from_asset(str(module_path)), handler=f"app.{module_name}_presenter.lambda_handler", function_name=f"{module_name}-{self.stack_name}-{self.stage}"[:63], runtime=lambda_.Runtime.PYTHON_3_13, @@ -81,10 +84,35 @@ def __init__( self, id=f"{stack_name}_LambdaLayer_{stage}", layer_version_name=f"{stack_name}-LambdaLayer-{self.stage}", - code=lambda_.Code.from_asset("./build"), + code=lambda_.Code.from_asset(str(PROJECT_ROOT / "iac" / "build")), compatible_runtimes=[lambda_.Runtime.PYTHON_3_13], ) + self.google_authorizer_function = lambda_.Function( + self, + id="GoogleAuthorizerLambda", + function_name=f"google-authorizer-{stack_name}-{stage}"[:63], + code=lambda_.Code.from_asset( + str(PROJECT_ROOT / "src" / "modules" / "google_authorizer") + ), + handler="app.google_authorizer_presenter.lambda_handler", + runtime=lambda_.Runtime.PYTHON_3_13, + architecture=lambda_.Architecture.X86_64, + layers=[self.lambda_layer], + environment={ + "GOOGLE_CLIENT_ID": environment_variables.get("GOOGLE_CLIENT_ID", ""), + }, + timeout=Duration.seconds(15), + memory_size=512, + ) + self.google_authorizer = apigw.TokenAuthorizer( + self, + "GoogleTokenAuthorizer", + handler=self.google_authorizer_function, + identity_source=apigw.IdentitySource.header("Authorization"), + results_cache_ttl=Duration.seconds(0), + ) + users_resource = api_gateway_resource.add_resource("users") user_id_resource = users_resource.add_resource("{user_id}") diff --git a/iac/stack/iac_stack.py b/iac/stack/iac_stack.py index db79b33..5c6ca26 100644 --- a/iac/stack/iac_stack.py +++ b/iac/stack/iac_stack.py @@ -46,6 +46,7 @@ def __init__( "GRAPH_MICROSOFT_ENDPOINT", "https://graph.microsoft.com/v1.0/me", ), + "GOOGLE_CLIENT_ID": os.environ.get("GOOGLE_CLIENT_ID", ""), } self.lambda_construct = LambdaConstruct( From 7667e85c7c16e4c96f70fd0673777a5cdd643f09 Mon Sep 17 00:00:00 2001 From: Guilherme Date: Mon, 26 Oct 2026 18:55:36 -0300 Subject: [PATCH 5/5] fix: fix import from google authorizer usecase --- .../google_authorizer/app/google_authorizer_presenter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/modules/google_authorizer/app/google_authorizer_presenter.py b/src/modules/google_authorizer/app/google_authorizer_presenter.py index 6eeb499..8f94271 100644 --- a/src/modules/google_authorizer/app/google_authorizer_presenter.py +++ b/src/modules/google_authorizer/app/google_authorizer_presenter.py @@ -2,7 +2,7 @@ import os from typing import Any -from src.modules.google_authorizer.app.google_authorizer_usecase import ( +from .google_authorizer_usecase import ( GoogleAuthorizerUsecase, ) from src.shared.helpers.auth.iam_policy import generate_policy