Skip to content
Open
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
1 change: 1 addition & 0 deletions .github/workflows/CD.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
13 changes: 6 additions & 7 deletions iac/adjust_layer_directory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand All @@ -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}")
Expand All @@ -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",
Expand Down
42 changes: 35 additions & 7 deletions iac/components/lambda_construct.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from pathlib import Path
from typing import Optional

from aws_cdk import (
Expand All @@ -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):

Expand All @@ -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,
Expand Down Expand Up @@ -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}")

Expand Down
1 change: 1 addition & 0 deletions iac/stack/iac_stack.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
1 change: 1 addition & 0 deletions requirements-app.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
pytest==8.4.1
pytest-cov==6.2.1
boto3==1.43.60
python-dotenv
Empty file.
Empty file.
32 changes: 32 additions & 0 deletions src/modules/google_authorizer/app/google_authorizer_presenter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import logging
import os
from typing import Any

from .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)
58 changes: 58 additions & 0 deletions src/modules/google_authorizer/app/google_authorizer_usecase.py
Original file line number Diff line number Diff line change
@@ -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(),
),
)
Empty file.
43 changes: 43 additions & 0 deletions src/shared/infra/external/google/google_id_token_client.py
Original file line number Diff line number Diff line change
@@ -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,
)
4 changes: 4 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import os


os.environ["STAGE"] = "TEST"
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading