diff --git a/.github/workflows/workflow_build.yaml b/.github/workflows/workflow_build.yaml index a90ee74..bee0603 100644 --- a/.github/workflows/workflow_build.yaml +++ b/.github/workflows/workflow_build.yaml @@ -1,4 +1,4 @@ -name: Publish Docker Image to AWS ECR Private +name: Deploy Lambda ZIP on: workflow_dispatch: @@ -7,7 +7,7 @@ on: - main jobs: build: - name: Build and push Docker image + name: Package and deploy Lambda ZIP runs-on: ubuntu-latest environment: certified-builder-py steps: @@ -22,25 +22,37 @@ jobs: aws-region: us-east-1 audience: sts.amazonaws.com - - name: Login to Amazon ECR Private - run: aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.us-east-1.amazonaws.com - - - name: Build Docker image + - name: Prepare package directories run: | - docker build -t ${{ secrets.ECR_REPOSITORY_BUILDER }}:latest . - docker tag ${{ secrets.ECR_REPOSITORY_BUILDER }}:latest ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.us-east-1.amazonaws.com/${{ secrets.ECR_REPOSITORY_BUILDER }}:latest - - - name: Push Docker image + rm -rf dist + mkdir -p dist/package + + - name: Build Lambda ZIP run: | - docker push ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.us-east-1.amazonaws.com/${{ secrets.ECR_REPOSITORY_BUILDER }}:latest + docker run --rm \ + -v "$PWD:/work" \ + -w /work \ + python:3.13-slim \ + bash -lc ' + set -euo pipefail + apt-get update >/dev/null + apt-get install -y zip >/dev/null + python -m pip install --upgrade pip >/dev/null + python -m pip install --no-cache-dir -r requirements.txt -t dist/package >/dev/null + cp -R aws certified_builder models dist/package/ + cp lambda_function.py config.py requirements.txt dist/package/ + cd dist/package + zip -qr ../lambda.zip . + ' - - name: Update Lambda function + - name: Deploy Lambda ZIP run: | aws lambda update-function-code \ - --function-name tech-floripa-certified-builder-dev \ - --image-uri ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.us-east-1.amazonaws.com/${{ secrets.ECR_REPOSITORY_BUILDER }}:latest - + --function-name tech-floripa-certificates-builder-dev \ + --zip-file fileb://dist/lambda.zip + aws lambda wait function-updated \ + --function-name tech-floripa-certificates-builder-dev + - name: Complete run: | - echo "Docker image has been pushed to AWS ECR Private and Lambda function has been updated" - + echo "Lambda ZIP deployed successfully" diff --git a/Dockerfile b/Dockerfile index 30a1384..623b62d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,36 +1,36 @@ -FROM public.ecr.aws/lambda/python:3.13 - -# Install system dependencies -RUN dnf update -y && \ - dnf install -y \ - freetype-devel \ - libjpeg-turbo-devel \ - zlib-devel \ - gcc \ - make \ - python3-devel \ - fontconfig && \ - dnf clean all - -# Set working directory -WORKDIR ${LAMBDA_TASK_ROOT} - -# Copy requirements first to leverage Docker cache +FROM python:3.13-slim + +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + build-essential \ + curl \ + fontconfig \ + libfreetype6-dev \ + libjpeg62-turbo-dev \ + zlib1g-dev && \ + rm -rf /var/lib/apt/lists/* + +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 +ENV PYTHONPATH=/var/task +ENV FONTCONFIG_PATH=/etc/fonts +ENV AWS_LAMBDA_RUNTIME_API="" + +WORKDIR /var/task + COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt +RUN pip install --no-cache-dir awslambdaric + +ADD https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie /usr/local/bin/aws-lambda-rie +RUN chmod +x /usr/local/bin/aws-lambda-rie -# Copy the entire application COPY . . +COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh +RUN chmod +x /usr/local/bin/docker-entrypoint.sh -# Create necessary directories RUN mkdir -p /tmp/certificates && \ chmod 777 /tmp/certificates -# Set environment variables -ENV PYTHONPATH=${LAMBDA_TASK_ROOT} -ENV FONTCONFIG_PATH=/etc/fonts -ENV PYTHONDONTWRITEBYTECODE=1 -ENV PYTHONUNBUFFERED=1 - -# Set the CMD to your handler +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] CMD [ "lambda_function.lambda_handler" ] diff --git a/certified_builder/certificates_on_solana.py b/certified_builder/certificates_on_solana.py index 76210c2..b02ea45 100644 --- a/certified_builder/certificates_on_solana.py +++ b/certified_builder/certificates_on_solana.py @@ -1,4 +1,9 @@ import logging +import socket +import ssl +import time +from urllib.parse import urlparse + import httpx from retry import retry from pydantic import BaseModel @@ -6,6 +11,8 @@ logger = logging.getLogger(__name__) +RESPONSE_BODY_LOG_LIMIT = 500 + class CertificatesOnSolanaException(Exception): """Custom exception for CertificatesOnSolana errors.""" @@ -15,10 +22,75 @@ def __init__( message: str = "Error registering certificate on Solana", details: str = "", cause: Exception = None, + stage: str = "unexpected", ): - super().__init__(message) + super().__init__(f"{message} [stage={stage}]: {details}") self.details = details self.cause = cause + self.stage = stage + + +def _exception_chain(exc: BaseException) -> list: + """Return exc followed by its __cause__/__context__ chain. + + Stops at context hidden with `raise ... from None`, as tracebacks do. + """ + chain = [] + while exc is not None and exc not in chain: + chain.append(exc) + if exc.__cause__ is not None: + exc = exc.__cause__ + elif exc.__suppress_context__: + exc = None + else: + exc = exc.__context__ + return chain + + +def _classify_error(exc: BaseException) -> str: + """Name the layer where the registration failed.""" + chain = _exception_chain(exc) + if any(isinstance(e, socket.gaierror) for e in chain): + return "dns" + if any(isinstance(e, ssl.SSLError) for e in chain): + return "tls" + if isinstance(exc, httpx.TimeoutException): + return "timeout" + if isinstance(exc, httpx.ConnectError): + return "connect" + if isinstance(exc, httpx.HTTPStatusError): + if exc.response.status_code in (401, 403): + return "auth" + return "http_status" + if isinstance(exc, httpx.RequestError): + return "network" + if isinstance(exc, ValueError): + return "response_parse" + return "unexpected" + + +def _describe_chain(exc: BaseException) -> str: + return " <- ".join( + f"{type(e).__module__}.{type(e).__name__}(errno={getattr(e, 'errno', None)})" + for e in _exception_chain(exc) + ) + + +def _loggable_body(response) -> str | None: + """Response body safe to log. + + Other 4xx responses (400, 422...) may echo the request payload, which + carries the participant's name and email, so only their shape is logged. + """ + if response is None: + return None + status = response.status_code + if status >= 500 or status in (401, 403): + return response.text[:RESPONSE_BODY_LOG_LIMIT] + return ( + f"" + ) class CertificatesOnSolana: @@ -34,10 +106,6 @@ class CertificatesOnSolana: logger=logger, ) def register_certificate_on_solana(certificate_data: dict) -> dict: - logger.info( - "Registering certificate on Solana blockchain with data: %s", - certificate_data, - ) """ Registers a certificate on the Solana blockchain. @@ -47,6 +115,16 @@ def register_certificate_on_solana(certificate_data: dict) -> dict: Returns: dict: A dictionary with the registration result. """ + target = urlparse(config.SERVICE_URL_REGISTRATION_API_SOLANA) + logger.info( + "Registering certificate on Solana: host=%s path=%s certificate_code=%s event=%s", + target.netloc, + target.path, + certificate_data.get("certificate_code"), + certificate_data.get("event"), + ) + started = time.monotonic() + response = None try: with httpx.Client(timeout=60.0) as client: response = client.post( @@ -62,5 +140,18 @@ def register_certificate_on_solana(certificate_data: dict) -> dict: solana_response = response.json() return solana_response except Exception as e: - logger.error(f"Error registering certificate on Solana: {str(e)}") - raise CertificatesOnSolanaException(details=str(e), cause=e) + stage = _classify_error(e) + status = getattr(response, "status_code", None) + body = _loggable_body(response) + logger.exception( + "Error registering certificate on Solana: stage=%s host=%s elapsed_ms=%d " + "status=%s certificate_code=%s chain=%s body=%s", + stage, + target.netloc, + (time.monotonic() - started) * 1000, + status, + certificate_data.get("certificate_code"), + _describe_chain(e), + body, + ) + raise CertificatesOnSolanaException(details=str(e), cause=e, stage=stage) diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100644 index 0000000..6f87689 --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu + +handler="${1:-lambda_function.lambda_handler}" + +if [ -z "${AWS_LAMBDA_RUNTIME_API:-}" ]; then + exec /usr/local/bin/aws-lambda-rie python -m awslambdaric "$handler" +fi + +exec python -m awslambdaric "$handler" diff --git a/lambda_function.py b/lambda_function.py index 2d5253a..7c10560 100644 --- a/lambda_function.py +++ b/lambda_function.py @@ -71,16 +71,6 @@ def create_participant_object(participant_data): if participant_data.get("time_checkin") else None ), - checkin_latitude=( - float(participant_data.get("checkin_latitude")) - if participant_data.get("checkin_latitude") - else None - ), - checkin_longitude=( - float(participant_data.get("checkin_longitude")) - if participant_data.get("checkin_longitude") - else None - ), ) # Create Participant object @@ -88,8 +78,6 @@ def create_participant_object(participant_data): first_name=participant_data.get("first_name"), last_name=participant_data.get("last_name"), email=participant_data.get("email"), - phone=participant_data.get("phone"), - cpf=participant_data.get("cpf", ""), certificate=certificate, event=event, ) diff --git a/models/event.py b/models/event.py index 16a0818..320c28e 100644 --- a/models/event.py +++ b/models/event.py @@ -9,5 +9,3 @@ class Event(BaseModel): product_name: str date: datetime time_checkin: Optional[datetime] = None - checkin_latitude: Optional[float] = None - checkin_longitude: Optional[float] = None diff --git a/models/participant.py b/models/participant.py index c98cce9..9252261 100644 --- a/models/participant.py +++ b/models/participant.py @@ -17,8 +17,6 @@ class Participant(BaseModel): first_name: str last_name: str email: EmailStr - phone: str - cpf: str validation_code: Optional[str] = Field( default_factory=lambda: "".join(random.choices(string.hexdigits, k=9)), init=False, diff --git a/readme.md b/readme.md index f989139..1954a3d 100644 --- a/readme.md +++ b/readme.md @@ -13,8 +13,7 @@ Sistema de geração automática de certificados para eventos usando AWS Lambda - Registro na blockchain Solana para autenticação - Processamento de mensagens SQS - Execução em container Docker -- Deploy automatizado para AWS Lambda -- Integração com AWS ECR +- Deploy automatizado para AWS Lambda via ZIP package - Envio de mensagens para fila de notificação com dados do certificado ## Estrutura do Projeto @@ -55,7 +54,6 @@ project_root/ - qrcode (Geração de QR codes) - Docker - AWS Lambda -- AWS ECR - AWS SQS - [Solana Blockchain (Registro de certificados)](https://github.com/p4ndabk/certificates-on-solana) @@ -142,7 +140,7 @@ pip install -r requirements.txt 3. Execute com Docker: ```bash -docker build -t certified-builder . && docker run -p 9000:8080 certified-builder +docker compose up --build ``` 4. Teste localmente: @@ -155,9 +153,9 @@ curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d O deploy é automatizado através do GitHub Actions: 1. Push para a branch main dispara o workflow -2. Imagem Docker é construída -3. Upload para AWS ECR -4. Atualização da função Lambda +2. Um pacote ZIP compatível com Lambda é gerado em ambiente Linux +3. O workflow executa `aws lambda update-function-code` +4. A função `tech-floripa-certificates-builder-dev` recebe o novo código ## Estrutura do Certificado Gerado @@ -181,4 +179,3 @@ O deploy é automatizado através do GitHub Actions: ## Licença Este projeto está sob a licença MIT. Veja o arquivo `LICENSE` para mais detalhes. - diff --git a/tests/test_certificates_on_solana.py b/tests/test_certificates_on_solana.py index f7fd706..fbd09b4 100644 --- a/tests/test_certificates_on_solana.py +++ b/tests/test_certificates_on_solana.py @@ -64,7 +64,9 @@ def test_register_certificate_success(sample_payload, monkeypatch): assert call_kwargs["json"] == sample_payload -def test_register_certificate_http_error_raises(sample_payload, monkeypatch): +def test_register_certificate_http_error_raises( + sample_payload, monkeypatch, no_retry_sleep +): monkeypatch.setattr( module_under_test.config, "SERVICE_URL_REGISTRATION_API_SOLANA", @@ -99,3 +101,142 @@ def _raise(): CertificatesOnSolana.register_certificate_on_solana(sample_payload) assert "boom" in str(exc.value.details) + + +@pytest.fixture +def no_retry_sleep(monkeypatch): + import retry.api + + monkeypatch.setattr(retry.api.time, "sleep", lambda _: None) + + +def _client_raising_on_post(error): + mock_client_instance = MagicMock() + mock_client_instance.post.side_effect = error + mock_client_instance.__enter__.return_value = mock_client_instance + mock_client_instance.__exit__.return_value = False + return mock_client_instance + + +def test_register_certificate_dns_failure_stage(sample_payload, no_retry_sleep): + import socket + import httpx + + dns_error = httpx.ConnectError("[Errno -2] Name or service not known") + dns_error.__cause__ = socket.gaierror(-2, "Name or service not known") + + with patch( + "certified_builder.certificates_on_solana.httpx.Client", + return_value=_client_raising_on_post(dns_error), + ): + with pytest.raises(CertificatesOnSolanaException) as exc: + CertificatesOnSolana.register_certificate_on_solana(sample_payload) + + assert exc.value.stage == "dns" + assert "[stage=dns]" in str(exc.value) + + +def test_register_certificate_auth_failure_stage(sample_payload, no_retry_sleep): + import httpx + + request = httpx.Request("POST", "https://example.test/solana/register") + response = httpx.Response(401, request=request, json={"detail": "Invalid API Key"}) + + mock_client_instance = MagicMock() + mock_client_instance.post.return_value = response + mock_client_instance.__enter__.return_value = mock_client_instance + mock_client_instance.__exit__.return_value = False + + with patch( + "certified_builder.certificates_on_solana.httpx.Client", + return_value=mock_client_instance, + ): + with pytest.raises(CertificatesOnSolanaException) as exc: + CertificatesOnSolana.register_certificate_on_solana(sample_payload) + + assert exc.value.stage == "auth" + + +def test_register_certificate_failure_log_has_no_secrets( + sample_payload, no_retry_sleep, caplog +): + import httpx + + with patch( + "certified_builder.certificates_on_solana.httpx.Client", + return_value=_client_raising_on_post(httpx.ConnectError("refused")), + ): + with pytest.raises(CertificatesOnSolanaException): + CertificatesOnSolana.register_certificate_on_solana(sample_payload) + + assert "stage=connect" in caplog.text + assert "test-api-key" not in caplog.text + assert sample_payload["email"] not in caplog.text + assert sample_payload["name"] not in caplog.text + + +def _client_returning(response): + mock_client_instance = MagicMock() + mock_client_instance.post.return_value = response + mock_client_instance.__enter__.return_value = mock_client_instance + mock_client_instance.__exit__.return_value = False + return mock_client_instance + + +def test_register_certificate_4xx_body_echoing_payload_not_logged( + sample_payload, no_retry_sleep, caplog +): + import httpx + + request = httpx.Request("POST", "https://example.test/solana/register") + response = httpx.Response( + 422, + request=request, + json={"detail": [{"loc": ["body", "email"], "input": sample_payload["email"]}]}, + ) + + with patch( + "certified_builder.certificates_on_solana.httpx.Client", + return_value=_client_returning(response), + ): + with pytest.raises(CertificatesOnSolanaException) as exc: + CertificatesOnSolana.register_certificate_on_solana(sample_payload) + + assert exc.value.stage == "http_status" + assert "body=