Skip to content

fix(smtp): honor the local hostname during STARTTLS - #45909

Merged
Stream29 merged 3 commits into
langgenius:mainfrom
Wang-Zephyr:fix/smtp-starttls-local-hostname
Nov 10, 2026
Merged

Stream29 merged 3 commits into
langgenius:mainfrom
Wang-Zephyr:fix/smtp-starttls-local-hostname

Conversation

@Wang-Zephyr

@Wang-Zephyr Wang-Zephyr commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #45908

Summary

STARTTLS mail can be rejected by identity-checking relays even when the operator
sets SMTP_LOCAL_HOSTNAME: the two explicit EHLO calls send the remote server's
address instead of the configured client identity.

Use smtp.ehlo() before and after STARTTLS so smtplib uses the local hostname
already supplied at construction, including its default when no override is
set. Preserve TLS negotiation, authentication, message content and cleanup.
The behavior change is two calls; the method docstring documents the outcome
contract. No public settings or dependencies change.

Related #30957 / #30975 introduced the hostname override, but left these two
STARTTLS calls overriding it.

Verification

The new cases use real DifyConfig, SMTPClient, Python smtplib, loopback TCP,
ephemeral TLS certificates, STARTTLS/implicit SSL and MIME/envelope exchanges.
They do not mock the SMTP client or replace its settings module.
Certificate generation uses cryptography, an existing backend dependency;
tests require no external SMTP service or system openssl executable.

Coverage Result
Configured/default hostname × plain/STARTTLS/implicit SSL Correct wire identity; STARTTLS retains EHLO → upgrade → EHLO; MIME and envelope preserved
TLS, authentication, sender and DATA rejection Original error/status propagates; no duplicate send
QUIT disconnect after failure or acceptance Cleanup neither masks the failure nor turns acceptance into a retryable error
Empty/blank/nonempty credentials Existing authentication selection retained
Existing SMTP and alternate SendGrid tests Existing covered behavior remains green

Before the fix, the two STARTTLS identity cases fail with SMTPSenderRefused
550; the four plain/SSL controls pass. After the fix, all six pass.
There are 19 new real-protocol cases, 21 existing SMTP cases and four unchanged
SendGrid cases: 44 passed. Existing SendGrid cases mock their external SDK;
no live SendGrid validation is claimed.

From the repository root, using Python 3.13.18 and a small environment with
the matching lockfile versions of pytest, Ruff, Pyrefly, Pydantic/settings,
cryptography, httpx and SendGrid:

uv run --project api --no-sync python -m pytest --noconftest -o addopts= api/tests/unit_tests/libs/test_smtp.py api/tests/unit_tests/libs/test_sendgrid.py -q --tb=short
uv run --project api --no-sync python -m ruff check api/libs/smtp.py api/tests/unit_tests/libs/test_smtp.py
uv run --project api --no-sync python -m ruff format --check api/libs/smtp.py api/tests/unit_tests/libs/test_smtp.py
uv run --project api --no-sync python -m pyrefly check --config api/pyproject.toml --threads 1 api/libs/smtp.py
uv run --project api --no-sync python -m pyrefly check --config api/tests/unit_tests/pyrefly.toml --threads 1 --use-ignore-files=false --disable-project-excludes-heuristics=true api/tests/unit_tests/libs/test_smtp.py
git diff --check

Focused tests: 44 passed. Ruff lint/format: passed. Targeted Pyrefly:
0 diagnostics, with its visible PYTHONPATH environment warning.
--noconftest avoids the application's shared database/Redis fixture setup;
both selected library modules are self-contained and still load real settings.
Coverage options were disabled for this focused run. No new skips, weakened
assertions or production exception suppression were introduced.

The complete backend environment, application mail-task suite, full suite,
Docker integration and real external mail providers were not exercised.
These results are Windows/Python 3.13 source-level and local protocol proof,
not an end-to-end deployed Dify or cross-platform claim. The initial upstream CI passed API unit tests (both shards), controller tests
and integration tests. Python Style exposed missing annotations in the new
tests under the separate strict unit-test configuration. The follow-up adds
those annotations; local strict checking now reports 0 diagnostics and the
same focused suite passes all 44 cases. Updated-head CI is pending.

Screenshots

No visual change. Wire-level before/after:

Before, STARTTLS After, STARTTLS
EHLO uses the endpoint address before and after TLS; a relay enforcing the configured identity rejects mail EHLO uses the configured client identity before and after TLS; the same local relay accepts one message

Checklist

  • This change requires a documentation update, included: Dify Document
  • I understand that this PR may be closed in case there was no previous discussion or issues.
  • I've verified the change and added or updated tests where meaningful regression risk justifies coverage.
  • I've updated the documentation accordingly.
  • I ran make lint && make type-check (backend) and vp staged (frontend) to appease the lint gods

No separate user documentation is needed for honoring an existing setting; its
definition already describes the intended behavior. The method docstring was
updated. The last checklist item is intentionally unchecked: the exact focused
checks above ran, not full make targets or frontend checks.

AI assistance covered investigation, implementation, real-protocol regression
tests, focused checks and drafting.

From Codex

@github-actions github-actions Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Nov 9, 2026
crazywoola
crazywoola previously approved these changes Nov 9, 2026
@crazywoola
crazywoola enabled auto-merge November 9, 2026 11:36
@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-11-10 01:46:14.003359623 +0000
+++ /tmp/pyrefly_pr.txt	2026-11-10 01:46:01.295167744 +0000
@@ -2699,7 +2699,7 @@
 ERROR Object of class `FromClause` has no attribute `drop` [missing-attribute]
   --> tests/unit_tests/controllers/trigger/test_trigger.py:46:5
 ERROR `_RequestStub` is not assignable to attribute `request` with type `Request` [bad-assignment]
-  --> tests/unit_tests/controllers/trigger/test_webhook.py:70:22
+  --> tests/unit_tests/controllers/trigger/test_webhook.py:47:22
 ERROR Argument `None` is not assignable to parameter `type` with type `EndUserType | SQLCoreOperations[EndUserType]` in function `models.model.EndUser.__init__` [bad-argument-type]
    --> tests/unit_tests/controllers/web/test_wraps.py:387:81
 ERROR Expected 1 more positional argument [bad-argument-count]
@@ -4121,7 +4121,7 @@
 ERROR Argument `list[FromClause]` is not assignable to parameter `tables` with type `Sequence[Table] | None` in function `sqlalchemy.sql.schema.MetaData.create_all` [bad-argument-type]
   --> tests/unit_tests/core/rag/extractor/test_excel_extractor.py:17:56
 ERROR Argument `object | None` is not assignable to parameter `session` with type `Session | None` in function `core.rag.extractor.extract_processor.ExtractProcessor.extract` [bad-argument-type]
-   --> tests/unit_tests/core/rag/extractor/test_extract_processor.py:251:85
+   --> tests/unit_tests/core/rag/extractor/test_extract_processor.py:222:85
 ERROR Object of class `NoneType` has no attribute `strip` [missing-attribute]
   --> tests/unit_tests/core/rag/extractor/test_markdown_extractor.py:30:16
 ERROR Object of class `FunctionType` has no attribute `return_value` [missing-attribute]
@@ -5895,42 +5895,50 @@
   --> tests/unit_tests/services/tools/test_tools_transform_service.py:85:9
 ERROR Object of class `Mapping` has no attribute `startswith` [missing-attribute]
    --> tests/unit_tests/services/tools/test_tools_transform_service.py:819:20
+ERROR Argument `dict[str, Any]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.schedule_service.ScheduleService.to_schedule_config` [bad-argument-type]
+   --> tests/unit_tests/services/trigger/test_schedule_service.py:549:61
+ERROR Argument `dict[str, str | dict[str, str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.schedule_service.ScheduleService.to_schedule_config` [bad-argument-type]
+   --> tests/unit_tests/services/trigger/test_schedule_service.py:563:56
+ERROR Argument `dict[str, str | dict[str, str | dict[str, str]]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.schedule_service.ScheduleService.to_schedule_config` [bad-argument-type]
+   --> tests/unit_tests/services/trigger/test_schedule_service.py:580:61
+ERROR Argument `dict[str, str | dict[str, str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.schedule_service.ScheduleService.to_schedule_config` [bad-argument-type]
+   --> tests/unit_tests/services/trigger/test_schedule_service.py:592:56
 ERROR Argument `dict[str, dict[Unknown, Unknown]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.generate_webhook_response` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:589:83
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:507:83
 ERROR Argument `dict[str, dict[str, int | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.generate_webhook_response` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:599:83
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:517:83
 ERROR Argument `dict[str, dict[str, int | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.generate_webhook_response` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:609:83
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:527:83
 ERROR Argument `dict[str, dict[str, int | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.generate_webhook_response` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:618:83
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:536:83
 ERROR Argument `dict[str, dict[str, int | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.generate_webhook_response` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:627:83
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:545:83
 ERROR Argument `dict[str, dict[str, int | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.generate_webhook_response` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:637:83
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:555:83
 ERROR Argument `dict[str, dict[str, list[dict[str, bool | str]] | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.extract_and_validate_webhook_data` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:895:38
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:807:92
 ERROR Argument `dict[str, dict[str, str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.extract_and_validate_webhook_data` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:924:42
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:834:87
 ERROR Argument `dict[str, dict[str, str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.extract_and_validate_webhook_data` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:946:42
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:854:87
 ERROR Argument `dict[str, dict[str, list[dict[str, bool | str]] | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.extract_and_validate_webhook_data` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:966:45
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:872:90
 ERROR Argument `dict[str, dict[str, list[dict[str, bool | str]] | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.extract_and_validate_webhook_data` [bad-argument-type]
-   --> tests/unit_tests/services/trigger/test_webhook_service.py:987:41
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:891:95
 ERROR Argument `dict[str, dict[str, list[dict[str, bool | str]] | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.extract_and_validate_webhook_data` [bad-argument-type]
-    --> tests/unit_tests/services/trigger/test_webhook_service.py:1011:45
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:913:90
 ERROR Argument `dict[str, dict[str, list[dict[str, bool | str]] | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.extract_and_validate_webhook_data` [bad-argument-type]
-    --> tests/unit_tests/services/trigger/test_webhook_service.py:1032:45
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:932:90
 ERROR Argument `dict[str, dict[str, list[dict[str, bool | str]] | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.extract_and_validate_webhook_data` [bad-argument-type]
-    --> tests/unit_tests/services/trigger/test_webhook_service.py:1053:45
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:951:90
 ERROR Argument `dict[str, dict[str, list[dict[str, bool | str]] | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.extract_and_validate_webhook_data` [bad-argument-type]
-    --> tests/unit_tests/services/trigger/test_webhook_service.py:1073:41
+   --> tests/unit_tests/services/trigger/test_webhook_service.py:969:95
 ERROR Argument `dict[str, str | dict[str, str]]` is not assignable to parameter `webhook_data` with type `RawWebhookDataDict` in function `services.trigger.webhook_service.WebhookService._validate_http_metadata` [bad-argument-type]
-    --> tests/unit_tests/services/trigger/test_webhook_service.py:1356:61
+    --> tests/unit_tests/services/trigger/test_webhook_service.py:1249:61
 ERROR Argument `dict[str, dict[str, int] | dict[str, str]]` is not assignable to parameter `webhook_data` with type `RawWebhookDataDict` in function `services.trigger.webhook_service.WebhookService.build_workflow_inputs` [bad-argument-type]
-    --> tests/unit_tests/services/trigger/test_webhook_service.py:1368:59
+    --> tests/unit_tests/services/trigger/test_webhook_service.py:1261:59
 ERROR Argument `dict[str, dict[str, int | str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.trigger.webhook_service.WebhookService.generate_webhook_response` [bad-argument-type]
-    --> tests/unit_tests/services/trigger/test_webhook_service.py:1379:69
+    --> tests/unit_tests/services/trigger/test_webhook_service.py:1272:69
 ERROR Cannot find module `dify_graph.enums` [missing-import]
   --> tests/unit_tests/services/workflow/test_workflow_converter.py:36:5
 ERROR Cannot find module `dify_graph.model_runtime.entities.llm_entities` [missing-import]

@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 84.64% 84.60% -0.05%
Strict coverage 84.30% 84.26% -0.05%
Typed symbols 88,940 88,894 -46
Untyped symbols 16,203 16,252 +49
Modules 4443 4443 0

@crazywoola

Copy link
Copy Markdown
Member

Please fix the broken CI

@codecov

codecov Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.09%. Comparing base (effb39c) to head (75292c1).
⚠️ Report is 22 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #45909      +/-   ##
==========================================
- Coverage   90.09%   90.09%   -0.01%     
==========================================
  Files        6267     6269       +2     
  Lines      391981   392018      +37     
  Branches    78446    78450       +4     
==========================================
+ Hits       353152   353184      +32     
- Misses      32731    32741      +10     
+ Partials     6098     6093       -5     
Flag Coverage Δ
api 89.93% <100.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

auto-merge was automatically disabled November 9, 2026 12:22

Head branch was pushed to by a user without write access

Copy link
Copy Markdown
Contributor Author

@crazywoola Thanks for reviewing! Fixed the Python Style failure in ac7e5d1 by adding the missing type annotations to the new SMTP tests and relay helper. Production code and test assertions are unchanged in this follow-up.

Rechecked locally using the unit-test Pyrefly strict configuration: 0 diagnostics. The focused SMTP/SendGrid suite passes all 44 cases, and Ruff lint/format checks pass.

GitHub automatically dismissed the earlier approval when this commit was pushed. The updated workflows are currently awaiting maintainer approval to run; could you please approve the runs and take another look when convenient?

Comment thread api/libs/smtp.py Resolved
SMTP_LOCAL_HOSTNAME set to an empty string would reach smtplib as local_hostname="" and produce a bare ehlo with no hostname argument. Normalize blank values to None so smtplib falls back to its socket.getfqdn() default, and cover the empty value in the identity tests.

@Stream29 Stream29 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Stream29
Stream29 added this pull request to the merge queue Nov 10, 2026
Merged via the queue into langgenius:main with commit af37c00 Nov 10, 2026
51 checks passed
@wylswz wylswz mentioned this pull request Nov 17, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SMTP_LOCAL_HOSTNAME is ignored by EHLO in STARTTLS mode

3 participants