feat: 支持创建邮箱 API 的子域名后缀匹配开关 (#929)

* feat: 支持创建邮箱 API 的子域名后缀匹配开关

* fix: 修复 review 提到的开关三态与域名校验问题

* fix: 补充域名归一化与子域名匹配回归测试

* fix: 修复后台开关跟随 env 回退与 account_settings 半成功保存

* fix: 收口账号设置刷新提示与子域名状态重复读取

* fix: 拦截超长域名并透传账号设置刷新失败
This commit is contained in:
majorcheng
2026-04-04 00:11:23 +08:00
committed by GitHub
parent d2c940aa2c
commit 1a7cfb8c95
21 changed files with 776 additions and 23 deletions
+40
View File
@@ -20,6 +20,40 @@ services:
start_period: 10s
retries: 20
worker-subdomain:
build:
context: ..
dockerfile: e2e/Dockerfile.worker
ports:
- "8789:8789"
command: ["pnpm", "exec", "wrangler", "dev", "--port", "8789", "--ip", "0.0.0.0"]
depends_on:
- mailpit
healthcheck:
test: ["CMD", "curl", "-sf", "http://localhost:8789/health_check"]
interval: 3s
timeout: 5s
start_period: 10s
retries: 20
worker-env-off:
build:
context: ..
dockerfile: e2e/Dockerfile.worker
ports:
- "8788:8788"
command: ["pnpm", "exec", "wrangler", "dev", "--port", "8788", "--ip", "0.0.0.0"]
volumes:
- ./fixtures/wrangler.toml.e2e.env-off:/app/worker/wrangler.toml:ro
depends_on:
- mailpit
healthcheck:
test: ["CMD", "curl", "-sf", "http://localhost:8788/health_check"]
interval: 3s
timeout: 5s
start_period: 10s
retries: 20
frontend:
build:
context: ..
@@ -73,6 +107,8 @@ services:
dockerfile: e2e/Dockerfile.e2e
environment:
WORKER_URL: http://worker:8787
WORKER_URL_SUBDOMAIN: http://worker-subdomain:8789
WORKER_URL_ENV_OFF: http://worker-env-off:8788
FRONTEND_URL: https://frontend:5173
MAILPIT_API: http://mailpit:8025/api
SMTP_PROXY_HOST: smtp-proxy
@@ -85,6 +121,10 @@ services:
depends_on:
worker:
condition: service_healthy
worker-subdomain:
condition: service_healthy
worker-env-off:
condition: service_healthy
frontend:
condition: service_started
smtp-proxy:
+2
View File
@@ -2,6 +2,8 @@ import { APIRequestContext } from '@playwright/test';
import WebSocket from 'ws';
export const WORKER_URL = process.env.WORKER_URL!;
export const WORKER_URL_SUBDOMAIN = process.env.WORKER_URL_SUBDOMAIN || '';
export const WORKER_URL_ENV_OFF = process.env.WORKER_URL_ENV_OFF || '';
export const FRONTEND_URL = process.env.FRONTEND_URL!;
export const MAILPIT_API = process.env.MAILPIT_API!;
export const TEST_DOMAIN = 'test.example.com';
+34
View File
@@ -0,0 +1,34 @@
name = "cloudflare_temp_email_env_off"
main = "src/worker.ts"
compatibility_date = "2025-04-01"
compatibility_flags = [ "nodejs_compat" ]
keep_vars = true
[vars]
PREFIX = "tmp"
DEFAULT_DOMAINS = ["test.example.com"]
DOMAINS = ["test.example.com"]
ENABLE_CREATE_ADDRESS_SUBDOMAIN_MATCH = false
JWT_SECRET = "e2e-test-secret-key-env-off"
BLACK_LIST = ""
ENABLE_USER_CREATE_EMAIL = true
ENABLE_USER_DELETE_EMAIL = true
ENABLE_AUTO_REPLY = true
DEFAULT_SEND_BALANCE = 10
ENABLE_ADDRESS_PASSWORD = true
DISABLE_ADMIN_PASSWORD_CHECK = true
ADMIN_PASSWORDS = '["e2e-admin-pass"]'
ENABLE_WEBHOOK = true
E2E_TEST_MODE = true
SMTP_CONFIG = """
{"test.example.com":{"host":"mailpit","port":1025,"secure":false}}
"""
[[kv_namespaces]]
binding = "KV"
id = "e2e-test-kv-env-off-00000000-0000-0000-0000-000000000000"
[[d1_databases]]
binding = "DB"
database_name = "e2e-temp-email-env-off"
database_id = "e2e-test-db-env-off-00000000-0000-0000-0000-000000000000"
+44
View File
@@ -14,6 +14,36 @@ for i in $(seq 1 60); do
sleep 1
done
if [ -n "${WORKER_URL_SUBDOMAIN:-}" ]; then
echo "==> Waiting for subdomain worker at $WORKER_URL_SUBDOMAIN ..."
for i in $(seq 1 60); do
if curl -sf "$WORKER_URL_SUBDOMAIN/health_check" > /dev/null 2>&1; then
echo " Subdomain worker ready after ${i}s"
break
fi
if [ "$i" -eq 60 ]; then
echo "ERROR: Subdomain worker not ready after 60s"
exit 1
fi
sleep 1
done
fi
if [ -n "${WORKER_URL_ENV_OFF:-}" ]; then
echo "==> Waiting for env-off worker at $WORKER_URL_ENV_OFF ..."
for i in $(seq 1 60); do
if curl -sf "$WORKER_URL_ENV_OFF/health_check" > /dev/null 2>&1; then
echo " Env-off worker ready after ${i}s"
break
fi
if [ "$i" -eq 60 ]; then
echo "ERROR: Env-off worker not ready after 60s"
exit 1
fi
sleep 1
done
fi
echo "==> Waiting for frontend at $FRONTEND_URL ..."
for i in $(seq 1 60); do
if curl -skf "$FRONTEND_URL" > /dev/null 2>&1; then
@@ -44,5 +74,19 @@ curl -sf -X POST "$WORKER_URL/admin/db_initialize" > /dev/null
curl -sf -X POST "$WORKER_URL/admin/db_migration" > /dev/null
echo " Database initialized"
if [ -n "${WORKER_URL_SUBDOMAIN:-}" ]; then
echo "==> Initializing subdomain worker database"
curl -sf -X POST "$WORKER_URL_SUBDOMAIN/admin/db_initialize" > /dev/null
curl -sf -X POST "$WORKER_URL_SUBDOMAIN/admin/db_migration" > /dev/null
echo " Subdomain worker database initialized"
fi
if [ -n "${WORKER_URL_ENV_OFF:-}" ]; then
echo "==> Initializing env-off worker database"
curl -sf -X POST "$WORKER_URL_ENV_OFF/admin/db_initialize" > /dev/null
curl -sf -X POST "$WORKER_URL_ENV_OFF/admin/db_migration" > /dev/null
echo " Env-off database initialized"
fi
echo "==> Running Playwright tests"
exec npx playwright test "$@"
+198
View File
@@ -0,0 +1,198 @@
import { test, expect } from '@playwright/test';
import { TEST_DOMAIN, WORKER_URL, WORKER_URL_ENV_OFF, WORKER_URL_SUBDOMAIN } from '../../fixtures/test-helpers';
const SUBDOMAIN = `team.${TEST_DOMAIN}`;
const NESTED_SUBDOMAIN = `deep.team.${TEST_DOMAIN}`;
const MIXED_CASE_SUBDOMAIN = `TeAm.${TEST_DOMAIN.toUpperCase()}`;
const INVALID_LOOKALIKE_DOMAIN = `bad${TEST_DOMAIN}`;
const INVALID_EMPTY_PREFIX_DOMAIN = `.${TEST_DOMAIN}`;
const INVALID_EMPTY_LABEL_DOMAIN = `a..b.${TEST_DOMAIN}`;
const INVALID_OVERLONG_DOMAIN = `${'a.'.repeat(119)}${TEST_DOMAIN}`;
const CREATE_ADDRESS_WORKER_URL = WORKER_URL_SUBDOMAIN || WORKER_URL;
let originalCreateAddressStoredEnabled: boolean | undefined;
let originalEnvOffStoredEnabled: boolean | undefined;
async function getAccountSettings(request: any, workerUrl: string) {
const res = await request.get(`${workerUrl}/admin/account_settings`);
expect(res.ok()).toBe(true);
return await res.json();
}
function buildAccountSettingsPayload(
current: any,
addressCreationSettings?: { enableSubdomainMatch?: boolean | null },
overrides: Record<string, unknown> = {}
) {
return {
blockList: current.blockList || [],
sendBlockList: current.sendBlockList || [],
verifiedAddressList: current.verifiedAddressList || [],
fromBlockList: current.fromBlockList || [],
noLimitSendAddressList: current.noLimitSendAddressList || [],
emailRuleSettings: current.emailRuleSettings || {},
...(typeof addressCreationSettings !== 'undefined'
? { addressCreationSettings }
: {}),
...overrides,
};
}
async function saveSubdomainMatchSetting(
request: any,
workerUrl: string,
enableSubdomainMatch: boolean | null
) {
const current = await getAccountSettings(request, workerUrl);
const res = await request.post(`${workerUrl}/admin/account_settings`, {
data: buildAccountSettingsPayload(current, {
enableSubdomainMatch,
}),
});
expect(res.ok()).toBe(true);
}
async function restoreSubdomainMatchSetting(
request: any,
workerUrl: string,
originalValue: boolean | undefined
) {
if (typeof originalValue === 'boolean') {
await saveSubdomainMatchSetting(request, workerUrl, originalValue);
return;
}
await saveSubdomainMatchSetting(request, workerUrl, null);
}
test.describe('Create Address Subdomain Match', () => {
test.beforeAll(async ({ request }) => {
const createAddressSettings = await getAccountSettings(request, CREATE_ADDRESS_WORKER_URL);
originalCreateAddressStoredEnabled = createAddressSettings.addressCreationSubdomainMatchStatus?.storedEnabled;
if (WORKER_URL_ENV_OFF) {
const envOffSettings = await getAccountSettings(request, WORKER_URL_ENV_OFF);
originalEnvOffStoredEnabled = envOffSettings.addressCreationSubdomainMatchStatus?.storedEnabled;
}
});
test.afterEach(async ({ request }) => {
await restoreSubdomainMatchSetting(request, CREATE_ADDRESS_WORKER_URL, originalCreateAddressStoredEnabled);
if (WORKER_URL_ENV_OFF) {
await restoreSubdomainMatchSetting(request, WORKER_URL_ENV_OFF, originalEnvOffStoredEnabled);
}
});
test('admin can clear override and return to env fallback', async ({ request }) => {
await saveSubdomainMatchSetting(request, CREATE_ADDRESS_WORKER_URL, true);
await saveSubdomainMatchSetting(request, CREATE_ADDRESS_WORKER_URL, null);
const settings = await getAccountSettings(request, CREATE_ADDRESS_WORKER_URL);
expect(settings.addressCreationSubdomainMatchStatus?.storedEnabled).toBeUndefined();
const res = await request.post(`${CREATE_ADDRESS_WORKER_URL}/admin/new_address`, {
data: { name: `subenvfb${Date.now()}`, domain: SUBDOMAIN },
});
expect(res.ok()).toBe(false);
expect(await res.text()).toContain('Invalid domain');
});
test('invalid addressCreationSettings payload does not partially persist earlier settings', async ({ request }) => {
const current = await getAccountSettings(request, CREATE_ADDRESS_WORKER_URL);
const uniqueBlockedKeyword = `should-not-persist-${Date.now()}`;
const res = await request.post(`${CREATE_ADDRESS_WORKER_URL}/admin/account_settings`, {
data: buildAccountSettingsPayload(
current,
{ enableSubdomainMatch: 'invalid-value' as any },
{
blockList: [...(current.blockList || []), uniqueBlockedKeyword],
}
),
});
expect(res.status()).toBe(400);
const after = await getAccountSettings(request, CREATE_ADDRESS_WORKER_URL);
expect(after.blockList || []).toEqual(current.blockList || []);
expect(after.addressCreationSubdomainMatchStatus?.storedEnabled).toBe(
current.addressCreationSubdomainMatchStatus?.storedEnabled
);
});
test('persisted false still keeps exact match only', async ({ request }) => {
await saveSubdomainMatchSetting(request, CREATE_ADDRESS_WORKER_URL, false);
const uniqueName = `subdomain-default-${Date.now()}`;
const res = await request.post(`${CREATE_ADDRESS_WORKER_URL}/admin/new_address`, {
data: { name: uniqueName, domain: SUBDOMAIN },
});
expect(res.ok()).toBe(false);
expect(await res.text()).toContain('Invalid domain');
});
test('admin switch enables suffix subdomain match for both admin and user create APIs', async ({ request }) => {
await saveSubdomainMatchSetting(request, CREATE_ADDRESS_WORKER_URL, true);
const adminName = `subdomain-admin-${Date.now()}`;
const adminRes = await request.post(`${CREATE_ADDRESS_WORKER_URL}/admin/new_address`, {
data: { name: adminName, domain: SUBDOMAIN },
});
expect(adminRes.ok()).toBe(true);
const adminBody = await adminRes.json();
expect(adminBody.address).toContain(`@${SUBDOMAIN}`);
expect(adminBody.address_id).toBeGreaterThan(0);
const userName = `subdomain-user-${Date.now()}`;
const userRes = await request.post(`${CREATE_ADDRESS_WORKER_URL}/api/new_address`, {
data: { name: userName, domain: NESTED_SUBDOMAIN },
});
expect(userRes.ok()).toBe(true);
const userBody = await userRes.json();
expect(userBody.address).toContain(`@${NESTED_SUBDOMAIN}`);
expect(userBody.address_id).toBeGreaterThan(0);
const mixedCaseRes = await request.post(`${CREATE_ADDRESS_WORKER_URL}/admin/new_address`, {
data: { name: `subcase${Date.now()}`, domain: MIXED_CASE_SUBDOMAIN },
});
expect(mixedCaseRes.ok()).toBe(true);
const mixedCaseBody = await mixedCaseRes.json();
expect(mixedCaseBody.address).toContain(`@${SUBDOMAIN}`);
const invalidRes = await request.post(`${CREATE_ADDRESS_WORKER_URL}/admin/new_address`, {
data: { name: `subinvalid${Date.now()}`, domain: INVALID_LOOKALIKE_DOMAIN },
});
expect(invalidRes.ok()).toBe(false);
expect(await invalidRes.text()).toContain('Invalid domain');
const invalidEmptyPrefixRes = await request.post(`${CREATE_ADDRESS_WORKER_URL}/admin/new_address`, {
data: { name: `subempty${Date.now()}`, domain: INVALID_EMPTY_PREFIX_DOMAIN },
});
expect(invalidEmptyPrefixRes.ok()).toBe(false);
expect(await invalidEmptyPrefixRes.text()).toContain('Invalid domain');
const invalidEmptyLabelRes = await request.post(`${CREATE_ADDRESS_WORKER_URL}/admin/new_address`, {
data: { name: `sublabel${Date.now()}`, domain: INVALID_EMPTY_LABEL_DOMAIN },
});
expect(invalidEmptyLabelRes.ok()).toBe(false);
expect(await invalidEmptyLabelRes.text()).toContain('Invalid domain');
const invalidOverlongRes = await request.post(`${CREATE_ADDRESS_WORKER_URL}/admin/new_address`, {
data: { name: `sublong${Date.now()}`, domain: INVALID_OVERLONG_DOMAIN },
});
expect(invalidOverlongRes.ok()).toBe(false);
expect(await invalidOverlongRes.text()).toContain('Invalid domain');
});
test('env false works as hard kill switch even if admin setting is enabled', async ({ request }) => {
test.skip(!WORKER_URL_ENV_OFF, 'WORKER_URL_ENV_OFF is not configured');
await saveSubdomainMatchSetting(request, WORKER_URL_ENV_OFF, true);
const res = await request.post(`${WORKER_URL_ENV_OFF}/admin/new_address`, {
data: { name: `subdomain-env-off-${Date.now()}`, domain: SUBDOMAIN },
});
expect(res.ok()).toBe(false);
expect(await res.text()).toContain('Invalid domain');
});
});