补齐IMAP和POP3配置并统一邮件协议监听端口

This commit is contained in:
xuans committed 2026-09-06 15:53:59 +08:00
1 parent 9b60eb2177
commit 24829c1199
27 files changed
+868 -80

No files matched your search

+201
View File
@@ -0,0 +1,201 @@
package integration_test
import (
"bufio"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"fmt"
"math/big"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/listen/imap_server"
"git.pcux.cn/xuans/Smail/listen/pop3_server"
"git.pcux.cn/xuans/Smail/listen/smtp_server"
)
// 使用空白临时配置和临时证书,在非默认端口调用生产监听入口;不连接真实账号库。
func TestConfiguredMailListenerPortsAcceptProtocolConnections(t *testing.T) {
root := t.TempDir()
ports := reservePorts(t, 6)
meta := config.SectionMeta{Schema: config.CurrentSectionSchema, Generation: 1}
smtp := config.SMTPSectionConfig{Meta: meta, Listener: config.SMTPListenerConfig{
Port: ports[0], STARTTLSPort: ports[1], TLSPort: ports[2],
}}
email := config.EmailSectionConfig{Meta: meta, IMAP: config.IMAPListenerConfig{TLSPort: ports[3]}, POP3: config.POP3ListenerConfig{Port: ports[4], TLSPort: ports[5]}}
ssl := config.SSLSectionConfig{Meta: meta, TLS: config.SSLConfig{Mode: "default", DefaultDirectory: "config/ssl"}}
rootConfig := config.RootConfig{
ConfigVersion: config.CurrentConfigVersion, SchemaVersion: config.CurrentSchemaVersion, Generation: 1, SetupState: config.SetupStateBootstrap,
Database: config.DatabaseConfig{Type: config.DatabaseTypeSQLite, LocalRef: "unused.db"},
Domains: config.DomainConfig{Primary: "mail.example.com", Web: "mail.example.com", Accepted: []string{"mail.example.com"}},
Security: config.SecurityConfig{PasswordVersion: "argon2id"},
Sections: map[config.Section]config.SectionRef{},
}
directory := filepath.Join(root, "config")
if err := os.MkdirAll(directory, 0700); err != nil {
t.Fatal(err)
}
for section, value := range map[config.Section]any{
config.SectionSMTP: smtp, config.SectionEmail: email, config.SectionSSL: ssl,
config.SectionPlugins: config.PluginsSectionConfig{Meta: meta},
} {
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
name, _ := config.FixedSectionFile(section)
if err := os.WriteFile(filepath.Join(directory, name), data, 0600); err != nil {
t.Fatal(err)
}
rootConfig.Sections[section] = config.SectionRef{File: name, Schema: 1, Generation: 1, SHA256: config.SectionDigest(data)}
}
data, err := json.Marshal(rootConfig)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(directory, "config.json"), data, 0600); err != nil {
t.Fatal(err)
}
manager, err := config.NewConfigManager(root, config.ConfigLoaderOptions{})
if err != nil {
t.Fatal(err)
}
previousManager, previousConfig, previousRoot := config.CurrentManager(), config.CurrentConfig(), config.ROOT_PATH
t.Cleanup(func() {
config.SetRuntimeManager(previousManager)
config.PublishConfigSnapshot(previousConfig)
config.ROOT_PATH = previousRoot
})
config.ROOT_PATH = root
config.SetRuntimeManager(manager)
certificate, key := writeCertificate(t, root)
config.PublishConfigSnapshot(&config.Config{SSLPublicKeyPath: certificate, SSLPrivateKeyPath: key})
cases := []struct {
name string
port int
tls bool
prefix string
start func() error
}{
{"smtp", ports[0], false, "220", smtp_server.Start},
{"smtp_starttls", ports[1], false, "220", smtp_server.StartWithTLSNew},
{"smtp_tls", ports[2], true, "220", smtp_server.StartWithTLS},
{"imap_tls", ports[3], true, "* OK", imap_server.StarTLS},
{"pop3_stls", ports[4], false, "+OK", pop3_server.Start},
{"pop3_tls", ports[5], true, "+OK", pop3_server.StartWithTls},
}
var results []<-chan error
t.Cleanup(func() {
smtp_server.Stop()
imap_server.Stop()
pop3_server.Stop()
for _, result := range results {
select {
case <-result:
case <-time.After(3 * time.Second):
t.Error("listener did not stop before configuration cleanup")
}
}
})
for _, item := range cases {
t.Run(item.name, func(t *testing.T) {
result := make(chan error, 1)
results = append(results, result)
go func() {
defer close(result)
result <- item.start()
}()
address := fmt.Sprintf("127.0.0.1:%d", item.port)
var conn net.Conn
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
select {
case err := <-result:
t.Fatalf("listener exited before connection: %v", err)
default:
}
dialer := &net.Dialer{Timeout: 200 * time.Millisecond}
if item.tls {
conn, err = tls.DialWithDialer(dialer, "tcp", address, &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS12})
} else {
conn, err = dialer.Dial("tcp", address)
}
if err == nil {
break
}
time.Sleep(25 * time.Millisecond)
}
if err != nil {
t.Fatalf("connect custom port: %v", err)
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(3 * time.Second))
greeting, err := bufio.NewReader(conn).ReadString('\n')
if err != nil || !strings.HasPrefix(greeting, item.prefix) {
t.Fatalf("protocol greeting = %q, error = %v", greeting, err)
}
t.Logf("%s accepted protocol connection on custom port %d", item.name, item.port)
})
}
}
func reservePorts(t *testing.T, count int) []int {
t.Helper()
var ports []int
var listeners []net.Listener
defer func() {
for _, listener := range listeners {
_ = listener.Close()
}
}()
for range count {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
listeners = append(listeners, listener)
ports = append(ports, listener.Addr().(*net.TCPAddr).Port)
}
return ports
}
func writeCertificate(t *testing.T, root string) (string, string) {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
template := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "localhost"}, DNSNames: []string{"localhost"},
NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
t.Fatal(err)
}
certificatePath, keyPath := filepath.Join(root, "certificate.pem"), filepath.Join(root, "key.pem")
for path, block := range map[string]*pem.Block{
certificatePath: {Type: "CERTIFICATE", Bytes: der}, keyPath: {Type: "PRIVATE KEY", Bytes: keyDER},
} {
if err := os.WriteFile(path, pem.EncodeToMemory(block), 0600); err != nil {
t.Fatal(err)
}
}
return certificatePath, keyPath
}
+17 -4
View File
@@ -10,7 +10,7 @@ const { readFormConfig, getFieldGroups, updateFormConfig, validateFormConfig } =
source.replaceAll('export function ', 'function ') + '\nreturn { readFormConfig, getFieldGroups, updateFormConfig, validateFormConfig }'
)()
test('五个分区使用分组表单,控件和样式能编译且不再提供 JSON 编辑器', () => {
test('七个页面使用分组表单,控件和样式能编译且不再提供 JSON 编辑器', () => {
const require = createRequire(new URL('../../frontend/package.json', import.meta.url))
const { parse, compileScript, compileStyle } = require('@vue/compiler-sfc')
for (const name of ['ConfigForm', 'ConfigField', 'ConfigEditor']) {
@@ -22,7 +22,7 @@ test('五个分区使用分组表单,控件和样式能编译且不再提供 J
assert.deepEqual(compileStyle({ source: css, id: `data-v-${name}`, scoped: true }).errors, [])
assert.doesNotMatch(template, /&#x[0-9a-f]+;|type="textarea"|配置 JSON 编辑器/i)
}
for (const section of ['base', 'smtp', 'email', 'ssl', 'plugins']) {
for (const section of ['base', 'smtp', 'imap', 'pop3', 'email', 'ssl', 'plugins']) {
const groups = getFieldGroups(section, { plugins: { spam_block: { settings: null } } })
assert.ok(groups.length)
const keys = groups.flatMap(group => group.fields.map(field => field.path.join('.')))
@@ -32,6 +32,19 @@ test('五个分区使用分组表单,控件和样式能编译且不再提供 J
}
})
test('各协议仅编辑自己的监听端口,邮箱策略没有重复端口输入项', () => {
const config = { listener: { port: 25, starttlsPort: 587, tlsPort: 465 }, relay: { relayPort: 465 }, imap: { tlsPort: 993 }, pop3: { port: 110, tlsPort: 995 }, policy: { smtpPort: 25, imapPort: 143, pop3Port: 110 } }
const text = JSON.stringify(config)
assert.equal(updateFormConfig(text, 'email', ['policy', 'smtpPort'], 2525), text)
assert.equal(updateFormConfig(text, 'imap', ['pop3', 'port'], 1110), text)
assert.equal(updateFormConfig(text, 'pop3', ['imap', 'tlsPort'], 1993), text)
const edited = readFormConfig(updateFormConfig(text, 'smtp', ['listener', 'tlsPort'], 2465))
assert.equal(edited.listener.tlsPort, 2465)
assert.equal(edited.relay.relayPort, 465)
assert.deepEqual(getFieldGroups('email', config).flatMap(group => group.fields).filter(field => /port/i.test(field.path.join('.'))), [])
assert.ok(validateFormConfig('smtp', { ...config, listener: { ...config.listener, tlsPort: 587 } })['listener.tlsPort'])
})
test('文本输入的左右留白属于原生输入框,不影响数字、选择和开关控件', () => {
const require = createRequire(new URL('../../frontend/package.json', import.meta.url))
const { parse, compileStyle } = require('@vue/compiler-sfc')
@@ -151,9 +164,9 @@ test('开关、数字、空数字和列表保持真实类型,代理 HTTPS 正
assert.equal(readFormConfig(text).http.port, null)
assert.ok(validateFormConfig('base', readFormConfig(text))['http.port'])
for (const value of ['25', 0, -1, 65536, 1.5, null]) {
assert.ok(validateFormConfig('email', { policy: { smtpPort: value, imapPort: 143, pop3Port: 110 } })['policy.smtpPort'])
assert.ok(validateFormConfig('imap', { imap: { tlsPort: value } })['imap.tlsPort'])
}
assert.ok(validateFormConfig('email', { policy: { smtpPort: 143, imapPort: 143, pop3Port: 110 } })['policy.imapPort'])
assert.ok(validateFormConfig('pop3', { imap: { tlsPort: 993 }, pop3: { port: 993, tlsPort: 995 } })['pop3.port'])
assert.deepEqual(validateFormConfig('email', { policy: { smtpPort: 25, imapPort: 143, pop3Port: 110 } }), {})
})
+4 -3
View File
@@ -5,7 +5,7 @@ import { compileFunction } from 'node:vm'
import { computed, reactive, ref } from './vue.mjs'
const source = readFileSync(new URL('../../frontend/src/views/components/ConfigSettings/ConfigNavigation.js', import.meta.url), 'utf8')
const components = ['BaseConfig', 'SmtpConfig', 'EmailConfig', 'SslConfig', 'PluginsConfig', 'ConfigMaintenance']
const components = ['BaseConfig', 'SmtpConfig', 'ImapConfig', 'Pop3Config', 'EmailConfig', 'SslConfig', 'PluginsConfig', 'ConfigMaintenance']
const createNavigation = compileFunction(
source.replace(/^import .*$/gm, '').replace('export function useNavigation', 'function useNavigation') + '\nreturn useNavigation()',
['computed', 'nextTick', 'ref', 'useGlobalStatusStore', ...components]
@@ -18,9 +18,10 @@ function fixture(capabilities = ['config.read']) {
return { page, allowed }
}
test('五个菜单对应五个不同页面组件,无权限的维护入口不可打开', async () => {
test('七个菜单对应七个不同页面组件,无权限的维护入口不可打开', async () => {
const { page, allowed } = fixture()
assert.equal(new Set(page.sectionOptions.value.map(item => item.component)).size, 5)
assert.equal(new Set(page.sectionOptions.value.map(item => item.component)).size, 7)
assert.deepEqual(page.sectionOptions.value.map(item => item.value), ['base', 'smtp', 'imap', 'pop3', 'email', 'ssl', 'plugins'])
assert.equal(page.maintenanceOptions.value.length, 0)
await page.selectSection('audit')
await page.selectSection('invalid')
+98 -9
View File
@@ -219,9 +219,9 @@ test('同一页重复加载时,过期失败不覆盖最新请求', async () =>
assert.deepEqual(JSON.parse(page.editorText.value), { enabled: true })
})
test('五个配置页固定分区并按需加载,所有分区均提供中文说明', async () => {
test('七个配置页按需加载,协议页复用正确分区且提供中文说明', async () => {
const requests = []
for (const key of ['base', 'smtp', 'email', 'ssl', 'plugins']) {
for (const key of ['base', 'smtp', 'imap', 'pop3', 'email', 'ssl', 'plugins']) {
const { page } = fixture(async path => { requests.push(path); return { errorNo: 0, data: {} } }, key)
await page.loadAll()
assert.equal(page.selectedSection.value, key)
@@ -230,8 +230,78 @@ test('五个配置页固定分区并按需加载,所有分区均提供中文
assert.equal(page.confirmed.value, false)
assert.equal(page.savedGeneration.value, 0)
}
assert.deepEqual(requests, ['base', 'smtp', 'email', 'ssl', 'plugins']
.flatMap(key => ['/api/v1/config/status', `/api/v1/config/${key}`]))
assert.deepEqual(requests, ['base', 'smtp', 'imap', 'pop3', 'email', 'ssl', 'plugins']
.flatMap(key => ['/api/v1/config/status', `/api/v1/config/${['imap', 'pop3'].includes(key) ? 'email' : key}`, ...(key === 'email' ? ['/api/v1/config/smtp'] : [])]))
})
for (const key of ['imap', 'pop3']) {
test(`${key} 页面验证、保存、候选恢复及应用均使用邮箱分区且保留其他字段`, async () => {
const requests = []
let pending = null
let active = { meta: { schema: 1, generation: 1 }, policy: { maxMessageBytes: 1234 }, imap: { tlsPort: 993 }, pop3: { port: 110, tlsPort: 995 } }
const { page } = fixture(() => {}, key, { http: {
get: async path => ({ errorNo: 0, data: path.endsWith('/pending') ? pending : path.endsWith('/status') ? { activeGeneration: active.meta.generation } : structuredClone(active) }),
put: async (path, body) => {
requests.push(path)
assert.equal(body.expectedGeneration, 1)
assert.deepEqual(body.payload.policy, active.policy)
assert.deepEqual(body.payload[key === 'imap' ? 'pop3' : 'imap'], active[key === 'imap' ? 'pop3' : 'imap'])
pending = { generation: 2, candidateId: 'mail-candidate', section: 'email', sameSession: true, payload: body.payload }
return { errorNo: 0, data: pending }
},
post: async (path, body) => {
requests.push(path)
if (path.endsWith('/apply')) {
assert.equal(body.candidateId, 'mail-candidate')
active = { ...pending.payload, meta: { schema: 1, generation: 2 } }
pending = null
}
return { errorNo: 0, data: { valid: true } }
}
} })
await page.loadAll()
page.updateField([key, 'tlsPort'], key === 'imap' ? 1993 : 1995)
await page.validateConfig()
await page.saveConfig()
await page.refreshPage()
assert.equal(page.savedGeneration.value, 2)
page.updateField([key, 'tlsPort'], 8888)
assert.notEqual(page.formConfig.value[key].tlsPort, 8888)
await page.applyConfig()
assert.equal(page.status.activeGeneration, 2)
assert.equal(page.savedGeneration.value, 0)
assert.deepEqual(requests, ['/api/v1/config/email/validate', '/api/v1/config/email', '/api/v1/config/email/apply'])
})
}
test('邮箱策略从三种协议配置汇总已应用端口,不能修改或被候选值误导', async () => {
const config = { meta: { generation: 3 }, policy: { smtpPort: 25, imapPort: 143, pop3Port: 110 }, imap: { tlsPort: 1993 }, pop3: { port: 1110, tlsPort: 1995 } }
const { page } = fixture(() => {}, 'email', { http: { get: async path => ({ errorNo: 0, data:
path.endsWith('/status') ? { activeGeneration: 3 } : path.endsWith('/smtp') ? { meta: { generation: 3 }, listener: { port: 2525, starttlsPort: 2587, tlsPort: 2465 }, relay: { relayPort: 9999 } } :
path.endsWith('/pending') ? { section: 'email', generation: 4, sameSession: true, payload: { ...config, imap: { tlsPort: 2993 } } } : config
}) } })
await page.loadAll()
assert.deepEqual(page.mailPortSummary.value.flatMap(service => service.ports.map(port => port.value)), [2525, 2587, 2465, 1993, 1110, 1995])
assert.equal(page.formConfig.value.imap.tlsPort, 2993)
const before = page.editorText.value
for (const path of [['policy', 'smtpPort'], ['policy', 'imapPort'], ['imap', 'tlsPort']]) page.updateField(path, 8888)
assert.equal(page.editorText.value, before)
})
test('邮箱策略拒绝不同代次的端口汇总,后续加载失败清除旧汇总', async () => {
let generation = 2
const { page } = fixture(async path => ({ errorNo: 0, data: path.endsWith('/smtp')
? { meta: { generation }, listener: { port: 2525 } }
: { meta: { generation: 1 }, imap: { tlsPort: 1993 }, pop3: { port: 1110, tlsPort: 1995 } } }), 'email')
await page.loadSection()
assert.match(page.sectionError.value, /代次/)
assert.equal(page.mailPortSummary.value, null)
generation = 1
await page.loadSection()
assert.ok(page.mailPortSummary.value)
generation = 3
await page.loadSection()
assert.equal(page.mailPortSummary.value, null)
})
test('迁移预览票据返回模板,迁移执行取消时不发送写入请求', async () => {
@@ -312,7 +382,7 @@ test('独立页模板可编译,编辑器不再连接维护面板且权限绑
assert.ok(maintenance.includes(`pageKey === '${key}' && ${capability}`))
}
assert.match(maintenance, /v-if="canExportAudit"/)
for (const name of ['BaseConfig', 'SmtpConfig', 'EmailConfig', 'SslConfig', 'PluginsConfig', 'ConfigMaintenance']) {
for (const name of ['BaseConfig', 'SmtpConfig', 'ImapConfig', 'Pop3Config', 'EmailConfig', 'SslConfig', 'PluginsConfig', 'ConfigMaintenance', 'MailPortSummary']) {
const page = readFileSync(new URL(`${name}/${name}.vue`, root), 'utf8')
const { descriptor, errors } = parse(page)
assert.deepEqual(errors, [])
@@ -496,16 +566,16 @@ test('可视化编辑按权限和工作状态保护,编辑会清除过期确
test('前端无效字段阻止网络请求,修正字段后同步清除错误', async () => {
const requests = []
const { page } = fixture(async () => ({ errorNo: 0, data: { policy: { smtpPort: 25, imapPort: 143, pop3Port: 110 } } }), 'email', {
const { page } = fixture(async () => ({ errorNo: 0, data: { imap: { tlsPort: 993 } } }), 'imap', {
http: { post: async path => { requests.push(path); return { errorNo: 0, data: { valid: true } } } }
})
await page.loadAll()
page.updateField(['policy', 'smtpPort'], null)
page.updateField(['imap', 'tlsPort'], null)
await page.validateConfig()
await page.saveConfig()
assert.deepEqual(requests, [])
assert.ok(page.formErrors.value['policy.smtpPort'])
page.updateField(['policy', 'smtpPort'], 2525)
assert.ok(page.formErrors.value['imap.tlsPort'])
page.updateField(['imap', 'tlsPort'], 1993)
assert.deepEqual(page.formErrors.value, {})
await page.validateConfig()
assert.deepEqual(requests, ['/api/v1/config/email/validate'])
@@ -595,3 +665,22 @@ test('保存后更改密码或填写内容不能应用旧候选', async () => {
assert.equal(page.savedGeneration.value, 0)
assert.deepEqual(requests, [])
})
test('共用邮箱分区的候选明确提示其他页面的改动,忽略代次与字段顺序', async () => {
const active = { meta: { generation: 1 }, imap: { tlsPort: 993 }, pop3: { port: 110, tlsPort: 995 }, policy: { maxMessageBytes: 1234 } }
for (const key of ['imap', 'pop3', 'email']) {
const { page } = fixture(async path => ({ errorNo: 0, data: path.endsWith('/smtp') ? { meta: { generation: 1 }, listener: {} } : active }), key)
await page.loadSection()
page.pendingCandidate.value = { section: 'email', payload: { ...active, meta: { generation: 2 }, pop3: { tlsPort: 995, port: 110 } } }
assert.match(page.pendingScopeHint.value, /协议端口和邮箱策略未变化/)
page.pendingCandidate.value.payload = { ...active, pop3: { port: 1110, tlsPort: 1995 }, policy: { maxMessageBytes: 5678 } }
assert.match(page.pendingScopeHint.value, /本次候选涉及:POP3 配置、邮箱策略。/)
assert.match(page.pendingScopeHint.value, /请逐页核对;应用时会一起生效/)
page.pendingCandidate.value = { section: 'smtp' }
assert.equal(page.pendingScopeHint.value, '')
page.pendingCandidate.value = { section: 'email' }
assert.match(page.pendingScopeHint.value, /候选内容尚未完整读取/)
}
const template = readFileSync(new URL('../../frontend/src/views/components/ConfigSettings/ConfigEditor/ConfigEditor.vue', import.meta.url), 'utf8')
assert.match(template, /:title="pendingScopeHint"/)
})