Skip to content

Commit d64a6a1

Browse files
authored
Merge pull request #10 from bentoluizv/fix/validate-certificate-background
fix: recusa lote de certificados com fundo fora de 1200×627
2 parents 32def70 + 4b254a9 commit d64a6a1

8 files changed

Lines changed: 322 additions & 70 deletions

File tree

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ dependencies = [
99
"aws-lambda-typing>=2.20.0",
1010
"boto3>=1.40.9",
1111
"httpx>=0.28.1",
12+
"pillow>=12.3.0",
1213
"pydantic>=2.11.7",
1314
"pydantic-settings>=2.10.1",
1415
"retry>=0.9.2",
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import logging
2+
from io import BytesIO
3+
from typing import Iterable
4+
5+
import httpx
6+
from PIL import Image, UnidentifiedImageError
7+
8+
from src.domain.exception.invalid_certificate_background import InvalidCertificateBackground
9+
10+
logger = logging.getLogger(__name__)
11+
12+
# O builder posiciona nome, logo, QR e código em pixels fixos para este tamanho.
13+
REQUIRED_SIZE = (1200, 627)
14+
ALLOWED_FORMATS = {"PNG", "JPEG"}
15+
16+
17+
class ValidateCertificateBackground:
18+
"""
19+
Confere, antes de gravar e enfileirar o lote, se o fundo do certificado segue
20+
o padrão Tech Floripa. Cada URL distinta é baixada uma única vez.
21+
"""
22+
23+
def __init__(self, timeout: float = 30.0):
24+
self.timeout = timeout
25+
26+
def execute(self, backgrounds: Iterable[str]) -> None:
27+
for url in dict.fromkeys(backgrounds):
28+
self.__validate(url)
29+
30+
def __validate(self, url: str) -> None:
31+
if not url or not url.strip():
32+
raise InvalidCertificateBackground(
33+
"Fundo do certificado não informado. Cadastre no evento a URL de uma "
34+
"imagem PNG ou JPG de exatamente 1200×627 px."
35+
)
36+
37+
try:
38+
with httpx.Client(timeout=self.timeout, follow_redirects=True) as client:
39+
response = client.get(url)
40+
response.raise_for_status()
41+
image = Image.open(BytesIO(response.content))
42+
except (httpx.HTTPError, UnidentifiedImageError) as e:
43+
logger.warning(f"Fundo do certificado inacessível ou ilegível ({url}): {e}")
44+
raise InvalidCertificateBackground(
45+
f"Não foi possível baixar ou abrir o fundo do certificado ({url}). "
46+
"Confira se a URL aponta para uma imagem PNG ou JPG pública.",
47+
url=url,
48+
)
49+
50+
if image.format not in ALLOWED_FORMATS:
51+
raise InvalidCertificateBackground(
52+
f"Fundo do certificado em formato {image.format}; use PNG ou JPG.",
53+
url=url,
54+
)
55+
56+
if image.size != REQUIRED_SIZE:
57+
width, height = image.size
58+
raise InvalidCertificateBackground(
59+
f"Fundo do certificado com {width}×{height} px; o padrão Tech Floripa "
60+
f"exige exatamente {REQUIRED_SIZE[0]}×{REQUIRED_SIZE[1]} px (PNG ou JPG).",
61+
url=url,
62+
)
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from typing import Optional
2+
3+
4+
class InvalidCertificateBackground(Exception):
5+
"""O fundo do certificado não segue o padrão Tech Floripa (1200x627, PNG ou JPG)."""
6+
7+
def __init__(self, message: str, url: Optional[str] = None):
8+
self.message = message
9+
self.url = url
10+
super().__init__(self.__str__())
11+
12+
def __str__(self) -> str:
13+
return self.message

‎src/infrastructure/container/dependency_container.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ def _register_services(self):
5353
self._services['list_user_certificates'] = self._create_list_user_certificates
5454
self._services['fetch_order_tech_floripa'] = self._create_fetch_order_tech_floripa
5555
self._services['download_certificate'] = self._create_download_certificate
56+
self._services['validate_certificate_background'] = self._create_validate_certificate_background
5657

5758
def get(self, service_name: str) -> Any:
5859
"""
@@ -152,6 +153,11 @@ def _create_download_certificate(self):
152153
from src.application.download_certificate import DownloadCertificate
153154
return DownloadCertificate()
154155

156+
def _create_validate_certificate_background(self):
157+
"""Cria uma instância do ValidateCertificateBackground."""
158+
from src.application.validate_certificate_background import ValidateCertificateBackground
159+
return ValidateCertificateBackground()
160+
155161
def _create_fetch_order_tech_floripa(self):
156162
"""
157163
Cria uma instância do FetchOrderTechFloripa.

‎src/main/handler/certificate.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
from src.application.fetch_certificate import FetchCertificate
2121
from src.application.download_certificate import DownloadCertificate
2222
from src.application.list_user_certificates import ListUserCertificates
23+
from src.application.validate_certificate_background import ValidateCertificateBackground
2324
from src.infrastructure.container.dependency_container import container
2425

2526

@@ -156,6 +157,12 @@ def create_certificates_handler(request: CreateCertificatesRequest) -> BuildOrde
156157

157158
create_certificate: CreateCertificate = container.get('create_certificate')
158159
send_for_build_certificate: SendForBuildCertificate = container.get('send_for_build_certificate')
160+
validate_certificate_background: ValidateCertificateBackground = container.get('validate_certificate_background')
161+
162+
# Recusa o lote antes de gravar ou enfileirar qualquer coisa se o fundo estiver fora do padrão
163+
validate_certificate_background.execute(
164+
cert.certificate_background for cert in request.certificates
165+
)
159166

160167
# Converte os certificados recebidos para TechOrdersResponse
161168
tech_orders: List[TechOrdersResponse] = [

‎src/main/presentation/controller/certificate.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from src.domain.response.build_order import BuildOrderResponse
3030
from src.domain.response.failed import FailedResponse
3131
from src.domain.exception.certificate_not_found import CertificateNotFound
32+
from src.domain.exception.invalid_certificate_background import InvalidCertificateBackground
3233

3334

3435
logger = logging.getLogger(__name__)
@@ -50,7 +51,7 @@ def create_certificate() -> BuildOrderResponse:
5051

5152

5253
@app.post(f"{config.PREFIX_API_VERSION}/certificate/create-batch")
53-
def create_certificates() -> BuildOrderResponse:
54+
def create_certificates() -> BuildOrderResponse | FailedResponse:
5455
"""
5556
Endpoint para receber uma lista de certificados e processá-los.
5657
Recebe uma lista de objetos de certificado e processa cada um deles.
@@ -59,6 +60,17 @@ def create_certificates() -> BuildOrderResponse:
5960
request: CreateCertificatesRequest = parse(app.current_event.body, CreateCertificatesRequest)
6061
response: BuildOrderResponse = create_certificates_handler(request)
6162
return response
63+
except InvalidCertificateBackground as e:
64+
logger.warning(f"Lote recusado, fundo do certificado fora do padrão: {e}")
65+
return Response(
66+
status_code=422,
67+
content_type="application/json",
68+
body=FailedResponse(
69+
details=e.url or "",
70+
message=e.message,
71+
status=422
72+
)
73+
)
6274
except Exception as e:
6375
logger.error(f"Erro ao processar a requisição de certificados em lote: {e}")
6476
return FailedResponse(
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import sys
2+
import unittest
3+
from io import BytesIO
4+
from pathlib import Path
5+
from unittest.mock import MagicMock, patch
6+
7+
import httpx
8+
from PIL import Image
9+
10+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
11+
12+
from src.application.validate_certificate_background import ValidateCertificateBackground
13+
from src.domain.exception.invalid_certificate_background import InvalidCertificateBackground
14+
15+
16+
def _image_bytes(size, image_format="PNG") -> bytes:
17+
buffer = BytesIO()
18+
Image.new("RGB", size, (255, 255, 255)).save(buffer, format=image_format)
19+
return buffer.getvalue()
20+
21+
22+
def _response(url: str, content: bytes, status_code: int = 200) -> httpx.Response:
23+
return httpx.Response(status_code, content=content, request=httpx.Request("GET", url))
24+
25+
26+
class ValidateCertificateBackgroundTestCase(unittest.TestCase):
27+
URL = "https://tech.floripa.br/wp-content/uploads/fundo.png"
28+
29+
def setUp(self):
30+
self.validator = ValidateCertificateBackground()
31+
patcher = patch("src.application.validate_certificate_background.httpx.Client")
32+
self.client_class = patcher.start()
33+
self.addCleanup(patcher.stop)
34+
self.client = MagicMock()
35+
self.client_class.return_value.__enter__.return_value = self.client
36+
37+
def _serve(self, content: bytes, status_code: int = 200):
38+
self.client.get.side_effect = lambda url: _response(url, content, status_code)
39+
40+
def test_accepts_png_with_standard_size(self):
41+
self._serve(_image_bytes((1200, 627)))
42+
self.validator.execute([self.URL])
43+
44+
def test_accepts_jpeg_with_standard_size(self):
45+
self._serve(_image_bytes((1200, 627), "JPEG"))
46+
self.validator.execute([self.URL])
47+
48+
def test_rejects_off_standard_size_with_actual_dimensions(self):
49+
self._serve(_image_bytes((2000, 1414)))
50+
with self.assertRaises(InvalidCertificateBackground) as ctx:
51+
self.validator.execute([self.URL])
52+
self.assertIn("2000×1414", ctx.exception.message)
53+
self.assertIn("1200×627", ctx.exception.message)
54+
self.assertEqual(ctx.exception.url, self.URL)
55+
56+
def test_rejects_other_formats(self):
57+
self._serve(_image_bytes((1200, 627), "GIF"))
58+
with self.assertRaises(InvalidCertificateBackground) as ctx:
59+
self.validator.execute([self.URL])
60+
self.assertIn("GIF", ctx.exception.message)
61+
62+
def test_rejects_empty_background(self):
63+
for value in ("", " "):
64+
with self.assertRaises(InvalidCertificateBackground) as ctx:
65+
self.validator.execute([value])
66+
self.assertIn("não informado", ctx.exception.message)
67+
self.client.get.assert_not_called()
68+
69+
def test_rejects_unreachable_url(self):
70+
self._serve(b"not found", status_code=404)
71+
with self.assertRaises(InvalidCertificateBackground) as ctx:
72+
self.validator.execute([self.URL])
73+
self.assertIn("Não foi possível baixar", ctx.exception.message)
74+
75+
def test_rejects_content_that_is_not_an_image(self):
76+
self._serve(b"<html>login</html>")
77+
with self.assertRaises(InvalidCertificateBackground):
78+
self.validator.execute([self.URL])
79+
80+
def test_downloads_each_distinct_url_once(self):
81+
self._serve(_image_bytes((1200, 627)))
82+
self.validator.execute([self.URL, self.URL, self.URL])
83+
self.assertEqual(self.client.get.call_count, 1)
84+
85+
86+
if __name__ == "__main__":
87+
unittest.main()

0 commit comments

Comments
 (0)