tkadkghdlf commited on
Commit
4cb3f5f
·
verified ·
1 Parent(s): 49c4aff

Sync DemoService 1a78db84103f1f2fa3960b4d4d7acbda2a2ee581

Browse files
api/auth-service/app/core/config.py CHANGED
@@ -28,6 +28,8 @@ class Settings(BaseSettings):
28
  smtp_use_tls: bool = True
29
  smtp_from_email: str | None = None
30
  smtp_from_name: str = "Run The Shape"
 
 
31
 
32
  google_oauth_client_id: str | None = None
33
 
 
28
  smtp_use_tls: bool = True
29
  smtp_from_email: str | None = None
30
  smtp_from_name: str = "Run The Shape"
31
+ resend_api_key: str | None = None
32
+ resend_from_email: str | None = None
33
 
34
  google_oauth_client_id: str | None = None
35
 
api/auth-service/app/services/email.py CHANGED
@@ -1,13 +1,53 @@
 
1
  import logging
2
  import smtplib
3
  from email.message import EmailMessage
 
 
4
 
5
  from app.core.config import settings
6
 
7
  logger = logging.getLogger(__name__)
8
 
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  def _send_email(to_email: str, subject: str, body: str) -> bool:
 
 
 
11
  if not settings.smtp_host or not settings.smtp_from_email:
12
  logger.warning("SMTP is not configured. Cannot send email to %s", to_email)
13
  return False
 
1
+ import json
2
  import logging
3
  import smtplib
4
  from email.message import EmailMessage
5
+ from urllib.error import HTTPError
6
+ from urllib.request import Request, urlopen
7
 
8
  from app.core.config import settings
9
 
10
  logger = logging.getLogger(__name__)
11
 
12
 
13
+ def _send_resend_email(to_email: str, subject: str, body: str) -> bool:
14
+ if not settings.resend_api_key or not settings.resend_from_email:
15
+ logger.error("Resend requires both RESEND_API_KEY and RESEND_FROM_EMAIL")
16
+ return False
17
+
18
+ request = Request(
19
+ "https://api.resend.com/emails",
20
+ data=json.dumps({
21
+ "from": f"{settings.smtp_from_name} <{settings.resend_from_email}>",
22
+ "to": [to_email],
23
+ "subject": subject,
24
+ "text": body,
25
+ }).encode("utf-8"),
26
+ headers={
27
+ "Authorization": f"Bearer {settings.resend_api_key}",
28
+ "Content-Type": "application/json",
29
+ "User-Agent": "RunTheShape-Auth/1.0",
30
+ },
31
+ method="POST",
32
+ )
33
+ try:
34
+ with urlopen(request, timeout=15) as response:
35
+ result = json.load(response)
36
+ if 200 <= response.status < 300 and isinstance(result, dict) and result.get("id"):
37
+ return True
38
+ logger.error("Resend returned an unexpected response (HTTP %s)", response.status)
39
+ except HTTPError as exc:
40
+ logger.error("Resend rejected email (HTTP %s)", exc.code)
41
+ exc.close()
42
+ except (OSError, ValueError) as exc:
43
+ logger.error("Resend email request failed (%s)", type(exc).__name__)
44
+ return False
45
+
46
+
47
  def _send_email(to_email: str, subject: str, body: str) -> bool:
48
+ if settings.resend_api_key or settings.resend_from_email:
49
+ return _send_resend_email(to_email, subject, body)
50
+
51
  if not settings.smtp_host or not settings.smtp_from_email:
52
  logger.warning("SMTP is not configured. Cannot send email to %s", to_email)
53
  return False
api/auth-service/tests/test_email_delivery.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import json
3
+ import unittest
4
+ from unittest.mock import patch
5
+ from urllib.error import HTTPError, URLError
6
+
7
+ from app.services import email
8
+
9
+
10
+ class EmailDeliveryTests(unittest.TestCase):
11
+ def setUp(self):
12
+ self.addCleanup(patch.stopall)
13
+ patch.object(email.settings, "resend_api_key", "test-key").start()
14
+ patch.object(email.settings, "resend_from_email", "no-reply@example.com").start()
15
+ self.http = patch.object(email, "urlopen").start()
16
+ self.smtp = patch.object(email.smtplib, "SMTP").start()
17
+
18
+ def test_verification_code_is_sent_via_https(self):
19
+ response = io.BytesIO(b'{"id":"test-message"}')
20
+ response.status = 200
21
+ self.http.return_value = response
22
+
23
+ self.assertTrue(email.send_email_verification_code("runner@example.net", "123456"))
24
+ request = self.http.call_args.args[0]
25
+ self.assertEqual(request.full_url, "https://api.resend.com/emails")
26
+ self.assertEqual(request.get_method(), "POST")
27
+ self.assertEqual(request.get_header("Authorization"), "Bearer test-key")
28
+ body = json.loads(request.data)
29
+ self.assertEqual(body["to"], ["runner@example.net"])
30
+ self.assertIn("no-reply@example.com", body["from"])
31
+ self.assertIn("123456", body["text"])
32
+ self.smtp.assert_not_called()
33
+
34
+ def test_provider_rejection_or_network_failure_does_not_fall_back(self):
35
+ for error in (HTTPError("https://api.resend.com/emails", 403, "", {}, None),
36
+ URLError("connection failed")):
37
+ with self.subTest(error=type(error).__name__):
38
+ self.http.side_effect = error
39
+ self.assertFalse(email.send_email_verification_code("runner@example.net", "123456"))
40
+ self.smtp.assert_not_called()
41
+
42
+ def test_missing_provider_configuration_fails_without_sending(self):
43
+ with patch.object(email.settings, "resend_from_email", None):
44
+ self.assertFalse(email.send_email_verification_code("runner@example.net", "123456"))
45
+ self.http.assert_not_called()
46
+ self.smtp.assert_not_called()
47
+
48
+ def test_unconfigured_https_preserves_smtp(self):
49
+ with (
50
+ patch.object(email.settings, "resend_api_key", None),
51
+ patch.object(email.settings, "resend_from_email", None),
52
+ patch.object(email.settings, "smtp_host", "smtp.example.com"),
53
+ patch.object(email.settings, "smtp_from_email", "no-reply@example.com"),
54
+ ):
55
+ self.assertTrue(email.send_password_reset_email("runner@example.net", "https://example.com/reset"))
56
+ self.smtp.return_value.__enter__.return_value.send_message.assert_called_once()
57
+ self.http.assert_not_called()
docs/DEMO_EMAIL_DELIVERY.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Email delivery on DemoService
2
+
3
+ The auth service supports Resend over HTTPS (443). Hugging Face Spaces
4
+ [networking](https://huggingface.co/docs/hub/spaces-overview#networking)
5
+ does not list Gmail SMTP port 587 among allowed outbound ports.
6
+
7
+ In the deployed Space's Settings → Variables and secrets, add:
8
+
9
+ - `RESEND_API_KEY`: a **secret** with sending permission for the verified domain.
10
+ - `RESEND_FROM_EMAIL`: a sender address on that verified domain.
11
+
12
+ Resend's default `resend.dev` sender cannot send to arbitrary recipients.
13
+ See [Resend's sender restrictions](https://resend.com/docs/knowledge-base/403-error-resend-dev-domain).
14
+ Do not put the key in Git or in any `NEXT_PUBLIC_*` setting.
15
+
16
+ With both values unset, local and other deployments keep using SMTP. With
17
+ either set, the app uses only the HTTPS path and requires both values. A
18
+ provider failure does not silently retry through SMTP or bypass verification.
19
+ This transport also serves password reset, so verify both flows after setting
20
+ the secrets. A successful provider API response means accepted for delivery,
21
+ not guaranteed inbox arrival.