修复审查发现的认证配置邮件协议及前端问题

补齐安全运行时清理、配置候选恢复、泛域名证书事务提交、邮件副本与协议边界、插件隐私和安装回滚回归,并更新修复状态及待验收清单。
This commit is contained in:
xuans committed 2026-09-06 13:02:02 +08:00
1 parent addfcea1cd
commit 6f79441585
71 files changed
+2853 -664

No files matched your search

+61 -4
View File
@@ -20,7 +20,10 @@ function fixture(get, pageKey = 'base', options = {}) {
let dispose = () => {}
const page = createPageWithKey(computed, () => {}, reactive, ref,
{ error: message => messages.push(message), warning: message => messages.push(message), success: () => {} },
{ confirm: options.confirm || (async () => {}) }, { get, ...options.http },
{ confirm: options.confirm || (async () => {}) }, {
get: path => path.endsWith('/pending') && !options.pendingGet ? Promise.resolve({ errorNo: 0, data: null }) : get(path),
...options.http
},
() => ({ hasCapability: options.hasCapability || (() => true) }), pageKey, callback => { dispose = callback })
return { page, messages, dispose: () => dispose() }
}
@@ -32,6 +35,51 @@ function deferred() {
return { promise, resolve, reject }
}
for (const failedRequest of ['/status', '/pending']) {
test(`候选保存成功后 ${failedRequest} 读取失败不能重新保存,刷新后可恢复或取消`, async () => {
let pending = null
let fail = false
let saves = 0
const { page } = fixture(() => {}, 'smtp', { http: {
get: async path => {
if (fail && path.endsWith(failedRequest)) throw new Error('模拟读取失败')
return { errorNo: 0, data: path.endsWith('/pending') ? pending : path.endsWith('/status') ? { activeGeneration: 1 } : { relay: { relayHost: 'old.example.com' } } }
},
put: async (path, body) => {
saves++
pending = { generation: 2, candidateId: 'pending-recovery', section: 'smtp', sameSession: true, payload: body.payload }
fail = true
return { errorNo: 0, data: pending }
},
post: async (path, body) => {
assert.equal(body.candidateId, 'pending-recovery')
if (body.action === 'resume') pending.sameSession = true
if (body.action === 'cancel') pending = null
return { errorNo: 0 }
}
} })
await page.loadAll()
page.updateField(['relay', 'relayHost'], 'new.example.com')
await page.saveConfig()
assert.equal(saves, 1)
page.updateField(['relay', 'relayHost'], 'blocked.example.com')
await page.saveConfig()
assert.equal(saves, 1)
assert.equal(page.formConfig.value.relay.relayHost, 'new.example.com')
fail = false
pending.sameSession = false
await page.refreshPage()
assert.equal(page.savedGeneration.value, 0)
assert.equal(page.pendingCandidate.value.candidateId, 'pending-recovery')
await page.managePending('resume')
assert.equal(page.savedGeneration.value, 2)
await page.managePending('cancel')
assert.equal(page.pendingCandidate.value, null)
page.updateField(['relay', 'relayHost'], 'editable.example.com')
assert.equal(page.formConfig.value.relay.relayHost, 'editable.example.com')
})
}
test('旧版配置仅请求状态,不并发请求分区、备份和审计', async () => {
const requests = []
const { page, messages } = fixture(async path => {
@@ -341,10 +389,16 @@ test('只读账号不得发送配置写入请求或读取无权限维护数据',
test('独立页保持验证、保存、应用端点和代次协议,敏感值不串页', async () => {
const requests = []
let pending = null
const { page } = fixture(async path => ({ errorNo: 0, data: path.endsWith('/status') ? { activeGeneration: 8 } : { relayPasswordStatus: 'configured' } }), 'smtp', {
http: {
post: async (path, body) => { requests.push({ path, body }); return { errorNo: 0, data: { valid: true } } },
put: async (path, body) => { requests.push({ path, body }); return { errorNo: 0, data: { generation: 9 } } }
get: async path => ({ errorNo: 0, data: path.endsWith('/pending') ? pending : path.endsWith('/status') ? { activeGeneration: 8 } : { relayPasswordStatus: 'configured' } }),
post: async (path, body) => { requests.push({ path, body }); if (path.endsWith('/apply')) pending = null; return { errorNo: 0, data: { valid: true } } },
put: async (path, body) => {
requests.push({ path, body })
pending = { generation: 9, candidateId: 'candidate-9', section: 'smtp', sameSession: true, payload: {} }
return { errorNo: 0, data: pending }
}
}
})
await page.loadAll()
@@ -359,7 +413,7 @@ test('独立页保持验证、保存、应用端点和代次协议,敏感值
assert.deepEqual(requests[0].body.payload, {})
assert.deepEqual(requests[0].body.secretChanges, { 'relay.password': { operation: 'replace', value: { plaintext: 'test-only-value' } } })
assert.deepEqual(requests[0].body.confirmation, { confirmed: true, method: 'recent_auth' })
assert.deepEqual(requests[2].body, { generation: 9 })
assert.deepEqual(requests[2].body, { generation: 9, candidateId: 'candidate-9' })
assert.equal(page.secretValue.value, '')
assert.equal(page.confirmed.value, false)
assert.equal(page.savedGeneration.value, 0)
@@ -381,6 +435,9 @@ test('可视化编辑按权限和工作状态保护,编辑会清除过期确
readonly.updateField(['relay', 'relayHost'], 'blocked.example.com')
assert.equal(readonly.editorText.value, '')
page.savedGeneration.value = 8
page.updateField(['relay', 'relayHost'], 'blocked.example.com')
assert.equal(page.editorText.value, original)
page.savedGeneration.value = 0
page.confirmed.value = true
page.validationResult.value = { valid: true }
page.updateField(['relay', 'relayHost'], 'new.example.com')
+77
View File
@@ -0,0 +1,77 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import { compileFunction } from 'node:vm'
import { createRequire } from 'node:module'
import { computed, reactive, ref } from './vue.mjs'
const root = new URL('../../frontend/src/views/components/PluginSettings/', import.meta.url)
const source = readFileSync(new URL('TelegramSettings/TelegramSettings.js', root), 'utf8')
const create = compileFunction(source.replace(/^import .*$/gm, '').replace('export function ', 'function ') + '\nreturn useTelegramSettings()',
['computed', 'onMounted', 'onBeforeUnmount', 'reactive', 'ref', 'ElMessage', 'http'])
test('Telegram 原生设置保留版本、限制用户字段,不依赖插件 iframe', async () => {
const requests = []
let conflict = false
const page = create(computed, () => {}, () => {}, reactive, ref, { success() {} }, {
get: async url => ({ errorNo: 0, data: url.endsWith('/bot') ? { username: 'smail_test_bot', botLink: 'javascript:alert(1)' }
: { version: 7, settings: { chatId: '123', sendAttachments: false, secret: '不得传回' } } }),
put: async (url, body) => {
requests.push({ url, body })
return conflict ? { errorNo: 400, errorMsg: '配置已被其他操作更新,请刷新后重试' }
: { errorNo: 0, data: { version: 8, settings: body.settings } }
},
post: async (url, body) => { requests.push({ url, body }); return { errorNo: 0 } }
})
await page.load()
assert.equal(page.ready.value, true)
assert.equal(page.botLink.value, 'https://t.me/smail_test_bot')
page.settings.sendAttachments = true
await page.submit('save')
assert.equal(requests[0].body.version, 7)
assert.deepEqual(Object.keys(requests[0].body.settings).sort(), ['chatId', 'disableLinkPreview', 'sendAttachments', 'showContent', 'spoilerContent'])
assert.equal(page.version.value, 8)
await page.submit('test')
assert.equal(requests[1].url, '/api/v1/plugin/settings/telegram_push/test')
assert.equal(page.version.value, 8)
conflict = true
await page.submit('save')
assert.match(page.errorMessage.value, /刷新/)
assert.equal(page.version.value, 8)
const count = requests.length
page.settings.chatId = 'invalid'
await page.submit('test')
assert.equal(requests.length, count)
})
test('Telegram 首次读取失败禁止覆盖存量设置,机器人故障不影响停用', async () => {
let fail = true
const page = create(computed, () => {}, () => {}, reactive, ref, { success() {} }, {
get: async url => {
if (fail || url.endsWith('/bot')) throw new Error('模拟离线')
return { errorNo: 0, data: { version: 0, settings: {} } }
},
put: async () => assert.fail('读取失败后不能保存')
})
await page.load()
await page.submit('save')
assert.equal(page.ready.value, false)
fail = false
await page.load()
assert.equal(page.ready.value, true)
assert.equal(page.botLink.value, '')
})
test('Telegram 模板独立编译,其他插件继续保持 sandbox 隔离', () => {
const require = createRequire(new URL('../../frontend/package.json', import.meta.url))
const { parse, compileScript, compileStyle } = require('@vue/compiler-sfc')
const parent = readFileSync(new URL('PluginSettings.vue', root), 'utf8')
assert.match(parent, /TelegramSettings v-else-if="entry.logicalID === 'telegram_push'"/)
assert.match(parent, /sandbox="allow-scripts"/)
assert.doesNotMatch(parent, /allow-same-origin/)
const { descriptor, errors } = parse(readFileSync(new URL('TelegramSettings/TelegramSettings.vue', root), 'utf8'))
assert.deepEqual(errors, [])
assert.doesNotThrow(() => compileScript(descriptor, { id: 'telegram-settings', inlineTemplate: true }))
assert.deepEqual(compileStyle({ source: readFileSync(new URL('TelegramSettings/TelegramSettings.css', root), 'utf8'), id: 'telegram-settings', scoped: true }).errors, [])
assert.doesNotMatch(source, /window\.parent|parent\.document|postMessage|localStorage/)
})
+127
View File
@@ -8,10 +8,137 @@ import (
"os"
"path/filepath"
"testing"
"time"
_ "modernc.org/sqlite"
)
func TestAuditPendingIdentityAndRecovery(t *testing.T) {
root := t.TempDir()
writeRuntimeFixture(t, root, validRuntimeConfig())
manager, err := NewConfigManager(root, ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}})
if err != nil {
t.Fatal(err)
}
actor := authorizedConfigActor()
payload, _ := json.Marshal(manager.Snapshot().Email)
req := UpdateRequest{Section: SectionEmail, ExpectedGeneration: 1, Payload: payload, Actor: actor}
first, err := manager.Update(context.Background(), req)
if err != nil {
t.Fatal(err)
}
confirmation := StepUpConfirmation{Confirmed: true, Method: "recent_auth"}
if err := manager.ManagePending(context.Background(), first.Generation, first.CandidateID, actor, confirmation, true); err != nil {
t.Fatal(err)
}
second, err := manager.Update(context.Background(), req)
if err != nil {
t.Fatal(err)
}
if first.CandidateID == second.CandidateID {
t.Fatal("不同候选不能复用标识")
}
if _, err := manager.ApplyPendingAuthorized(context.Background(), first.Generation, first.CandidateID, SectionEmail, actor); !errors.Is(err, ErrGenerationConflict) {
t.Fatalf("旧候选应用未拒绝: %v", err)
}
if err := manager.ManagePending(context.Background(), first.Generation, first.CandidateID, actor, confirmation, true); !errors.Is(err, ErrGenerationConflict) {
t.Fatalf("旧候选取消未拒绝: %v", err)
}
actor.SessionID = "renewed-session"
actor.RecentAuth = false
if err := manager.ManagePending(context.Background(), second.Generation, second.CandidateID, actor, confirmation, false); err == nil {
t.Fatal("跨会话恢复缺少近期认证")
}
actor.RecentAuth = true
if err := manager.ManagePending(context.Background(), second.Generation, second.CandidateID, actor, confirmation, false); err != nil {
t.Fatal(err)
}
if !manager.Pending(actor).SameSession {
t.Fatal("恢复没有绑定新会话")
}
manager.snapshots = &flakyRuntimeSnapshotStore{current: manager.Snapshot(), failures: 1}
if _, err := manager.ApplyPendingAuthorized(context.Background(), second.Generation, second.CandidateID, SectionEmail, actor); !errors.Is(err, ErrRuntimeSnapshotUnavailable) {
t.Fatal(err)
}
if err := manager.ManagePending(context.Background(), second.Generation, second.CandidateID, actor, confirmation, true); !errors.Is(err, ErrRuntimeSnapshotUnavailable) {
t.Fatalf("已落盘候选不应取消: %v", err)
}
manager.transactions.WithHooks(TransactionHooks{BeforePhase: func(TransactionPhase) error { return errors.New("不能再次提交") }})
if _, err := manager.ApplyPendingAuthorized(context.Background(), second.Generation, second.CandidateID, SectionEmail, actor); err != nil {
t.Fatalf("快照重试重新写盘: %v", err)
}
}
func TestAuditStagedSSLDoesNotReplaceCurrent(t *testing.T) {
previous := ROOT_PATH
ROOT_PATH = t.TempDir()
t.Cleanup(func() { ROOT_PATH = previous })
key, cert := testManagedCertificate(t, "mail.example.com", time.Now().Add(-time.Hour), time.Now().Add(time.Hour), 2048)
active, err := ImportManagedSSL(ManagedSSLModeDefault, key, cert, nil, nil)
if err != nil {
t.Fatal(err)
}
nextKey, nextCert := testManagedCertificate(t, "mail.example.com", time.Now().Add(-time.Hour), time.Now().Add(time.Hour), 2048)
staged, err := StageManagedSSL(ManagedSSLModeDefault, nextKey, nextCert, nil, nil)
if err != nil {
t.Fatal(err)
}
actual, err := os.ReadFile(active.CertificatePath)
if err != nil || string(actual) != string(cert) {
t.Fatal("暂存替换了现用证书")
}
if _, err := ResolveManagedSSLReferences(SSLConfig{Mode: staged.Mode, CertificateRef: staged.CertificateRef, PrivateKeyRef: active.PrivateKeyRef}); !errors.Is(err, ErrInvalidSSLReference) {
t.Fatalf("跨版本配对未拒绝: %v", err)
}
if _, err := ResolveManagedSSLReferences(SSLConfig{Mode: staged.Mode, CertificateRef: staged.CertificateRef, PrivateKeyRef: staged.PrivateKeyRef}); err != nil {
t.Fatal(err)
}
}
func TestAuditLegacySSLCommitPreservesLatestUnrelatedSettings(t *testing.T) {
previousRoot, previousSnapshot := ROOT_PATH, CurrentConfig()
ROOT_PATH = t.TempDir()
t.Cleanup(func() {
ROOT_PATH = previousRoot
PublishConfigSnapshot(previousSnapshot)
})
writeLegacyMigrationFixture(t, ROOT_PATH, map[string]any{
"domain": "example.test", "webDomain": "mail.example.test",
"sslType": SSLTypeAutoDNS, "httpsEnabled": 1, "httpPort": 8080,
})
expected, err := ReadConfig()
if err != nil {
t.Fatal(err)
}
next := *expected
next.SSL = SSLConfig{Mode: ManagedSSLModeDefault, Challenge: SSLChallengeDNS, DefaultDirectory: "config/ssl"}
// 模拟签发期间另一项设置先保存成功,续期不得用旧快照覆盖它。
live := *expected
live.HttpPort = 9080
if err := WriteConfig(&live); err != nil {
t.Fatal(err)
}
if err := WriteSSLConfig(expected, &next); err != nil {
t.Fatal(err)
}
stored, err := ReadConfig()
if err != nil {
t.Fatal(err)
}
if stored.HttpPort != 9080 || next.HttpPort != 9080 || CurrentConfig().HttpPort != 9080 || stored.SSL != next.SSL {
t.Fatalf("SSL 提交覆盖了其他设置:disk=%d next=%d runtime=%d", stored.HttpPort, next.HttpPort, CurrentConfig().HttpPort)
}
stale := *stored
live = *stored
live.WebDomain = "changed.example.test"
if err := WriteConfig(&live); err != nil {
t.Fatal(err)
}
if err := WriteSSLConfig(&stale, &stale); !errors.Is(err, ErrGenerationConflict) {
t.Fatalf("签发期间域名变化必须拒绝旧结果:%v", err)
}
}
// 审查专用:模拟配置落盘中断,只操作测试创建的临时配置根目录。
func TestAuditSuccessfulConfigRetryMustSurviveRestart(t *testing.T) {
root := t.TempDir()
+9
View File
@@ -22,6 +22,12 @@ import (
// 真实控制器约束对照:输错后绑定仍待验证,重新绑定失败,但原挑战可继续验证。
func TestAuditPendingExternalBindingRequiresExistingChallenge(t *testing.T) {
_, _, engine, user, _ := newPublicSecurityFixture(t)
previousDB := db.Instance
db.Instance = engine
t.Cleanup(func() { db.Instance = previousDB })
if err := engine.Sync2(new(models.UserEmail)); err != nil {
t.Fatal(err)
}
previous := securityRuntime
t.Cleanup(func() { securityRuntime = previous })
vault := externalemail.NewVaultWithKeys([]byte("01234567890123456789012345678901"), []byte("abcdefabcdefabcdefabcdefabcdefab"))
@@ -123,6 +129,9 @@ func TestAuditAuthorizedRoleChangeMustSucceed(t *testing.T) {
if result != 0 || stored.EffectiveRole() != access.RoleAdmin {
t.Fatal("符合近期认证和目标恢复码条件的超级管理员仍无法修改用户角色")
}
if stored.SessionVersion <= user.SessionVersion || stored.SecurityVersion <= user.SecurityVersion {
t.Fatal("纯角色变更必须同时提升会话版本和安全版本")
}
}
// 使用真实 TLS HTTP 客户端及标准 CookieJar 检查浏览器同样遵循的 Path 匹配。
+55 -19
View File
@@ -82,8 +82,14 @@ test('邮件列表挂载后,表格选中项必须用于全选和批量操作',
table.selectRow(rows[0])
assert.equal(page.selectedRows.value.length, 1)
requests.length = 0
assert.ok(page.taskTableDataRef.value, '真实模板必须连接组合函数返回的表格引用')
page.selectAll()
assert.equal(page.selectedRows.value.length, 2)
page.invertSelection()
assert.equal(page.selectedRows.value.length, 0)
assert.equal(cleared, 1)
assert.equal(toggled, 4)
page.selectAll()
page.markRead()
page.move(0, '归档')
page.del()
@@ -91,20 +97,11 @@ test('邮件列表挂载后,表格选中项必须用于全选和批量操作',
await Promise.resolve()
const actual = { connected: !!page.taskTableDataRef.value, cleared, toggled, requests: [...requests], warnings: [...messages] }
console.log(`list_actual=${JSON.stringify(actual)}`)
// 只在测试内连接缺失引用,证明操作函数和模拟表格本身可用,不修改页面源码。
page.taskTableDataRef.value = table
page.selectAll()
page.markRead()
page.move(0, '归档')
page.del()
await Promise.resolve()
await Promise.resolve()
assert.equal(cleared, 1)
assert.equal(toggled, 2)
assert.equal(cleared, 2)
assert.equal(toggled, 6)
for (const action of ['read', 'move', 'del']) assert.ok(requests.includes(`/api/v1/email/${action}`))
console.log('list_reference_control=true batch_requests_control=true')
assert.equal(actual.connected, true, '真实模板必须连接组合函数返回的表格引用')
assert.equal(actual.cleared, 1)
assert.equal(actual.cleared, 2)
assert.equal(actual.requests.filter(url => !url.endsWith('/list')).length, 3)
} finally {
app.unmount()
@@ -117,19 +114,22 @@ for (const action of ['edit', 'refresh']) {
const source = read('src/views/components/ConfigSettings/ConfigSettings.js')
.replace(/^import .*$/gm, '').replace('export function usePage', 'function usePage')
const initial = { generation: 1, policy: { smtpPort: 25, imapPort: 993, pop3Port: 995, maxMessageBytes: 0 } }
let pending = false
let pending = null
let applied = false
const errors = []
const transport = {
get: async url => ({ errorNo: 0, data: url.endsWith('/status') ? { activeGeneration: 1, setupState: 'ready' } : initial }),
put: async () => {
get: async url => ({ errorNo: 0, data: url.endsWith('/pending') ? pending : url.endsWith('/status') ? { activeGeneration: 1, setupState: 'ready' } : initial }),
put: async (url, body) => {
if (pending) return { errorNo: 409, errorMsg: '配置代次冲突' }
pending = true
return { errorNo: 0, data: { generation: 2, pending: true } }
pending = { generation: 2, candidateId: 'audit-candidate', sameSession: true, section: 'email', payload: body.payload }
return { errorNo: 0, data: pending }
},
post: async url => {
post: async (url, body) => {
assert.ok(url.endsWith('/apply'))
assert.equal(body.candidateId, pending.candidateId)
assert.equal(body.generation, pending.generation)
applied = true
pending = null
return { errorNo: 0, data: { generation: 2 } }
}
}
@@ -170,7 +170,7 @@ test('外部邮箱验证码输入错误后必须能够再次输入,而不是
Vue.computed, () => {}, Vue.reactive, Vue.ref, () => {},
{ prompt: async () => { prompts++; return { value: prompts === 1 ? 'incorrect' : 'correct' } } },
notification => notifications.push(notification.message), {},
{ post: async url => {
{ get: async () => ({ errorNo: 0, data: [] }), post: async url => {
if (url.endsWith('/bind')) {
if (bound) return { errorNo: 400, errorMsg: '外部邮箱绑定失败' }
bound = true
@@ -238,6 +238,42 @@ test('审计导出必须保存服务端返回的 Blob 内容', async () => {
for (const { actual, payload } of results) assert.equal(actual, payload, '下载文件必须保留真实审计记录,而不是 undefined')
})
for (const format of ['csv', 'json']) {
test(`审计 ${format} 导出的错误 Blob 不应下载,失败后允许重试`, async () => {
const source = read('src/views/components/ConfigSettings/ConfigSettings.js')
.replace(/^import .*$/gm, '').replace('export function usePage', 'function usePage')
const errors = []
const downloads = []
let clicked = 0
let requests = 0
const payload = format === 'csv' ? 'id,operation\n1,update\n' : '[{"id":1}]'
const page = compileFunction(source + '\nreturn usePage("audit")', [
'computed', 'onMounted', 'onBeforeUnmount', 'reactive', 'ref', 'ElMessage', 'ElMessageBox',
'http', 'useGlobalStatusStore', 'readFormConfig', 'updateFormConfig', 'validateFormConfig', 'URL', 'document'
])(
Vue.computed, () => {}, () => {}, Vue.reactive, Vue.ref,
{ success() {}, error: message => errors.push(message) }, {},
{ post: async () => ++requests === 1
? new Blob([JSON.stringify({ errorNo: 403, errorMsg: '无权导出审计记录' })], { type: 'application/json' })
: new Blob([payload], { type: format === 'csv' ? 'text/csv' : 'application/json' }) },
() => ({ hasCapability: () => true }), () => ({}), () => '', () => ({}),
{ createObjectURL: blob => { downloads.push(blob); return 'blob:audit' }, revokeObjectURL() {} },
{ createElement: () => ({ click: () => { clicked++ } }) }
)
await page.exportAudit(format)
assert.deepEqual(errors, ['无权导出审计记录'])
assert.equal(downloads.length, 0)
assert.equal(clicked, 0)
assert.equal(page.working.value, '')
await page.exportAudit(format)
assert.equal(requests, 2)
assert.equal(downloads.length, 1)
assert.equal(clicked, 1)
assert.equal(await downloads[0].text(), payload)
assert.equal(page.working.value, '')
})
}
// 挂载真实 SFC 的编译结果和真实组合函数,使用 Vue 自定义渲染器代替浏览器 DOM。
test('写信页挂载后,附件按钮必须连接到文件输入框', async () => {
const source = read('src/views/Editer/Editer.js').replace(/^import .*$/gm, '')
+141 -1
View File
@@ -1,6 +1,7 @@
package imap_server
import (
"reflect"
"testing"
"git.pcux.cn/xuans/Smail/db"
@@ -11,6 +12,140 @@ import (
"github.com/emersion/go-imap/v2"
)
func TestAuditLargeSelectedMailboxMustBatchUIDQueries(t *testing.T) {
user := models.User{Account: t.Name()}
if _, err := db.Instance.Insert(&user); err != nil {
t.Fatal(err)
}
message := models.Email{Subject: t.Name()}
if _, err := db.Instance.Insert(&message); err != nil {
t.Fatal(err)
}
const count = 10001
uids := make([]int, 0, count)
deleted := make(map[int]bool)
// 独立账户及共享邮件内容限制夹具体积,同时保留每个副本的真实 UID。
for start := 0; start < count; start += 400 {
batch := make([]models.UserEmail, min(400, count-start))
for index := range batch {
batch[index] = models.UserEmail{UserID: user.ID, EmailID: message.Id}
if position := start + index; position == 0 || position == 500 || position == count-1 {
batch[index].IsDeleted = 1
}
}
if _, err := db.Instance.Insert(&batch); err != nil {
t.Fatal(err)
}
}
relations, err := list.GetUEListByUID(&context.Context{UserID: user.ID}, "INBOX", 0, 0, nil)
if err != nil || len(relations) != count {
t.Fatalf("大邮箱夹具不完整:count=%d err=%v", len(relations), err)
}
for _, relation := range relations {
uids = append(uids, relation.ID)
if relation.IsDeleted == 1 {
deleted[relation.ID] = true
}
}
session := &serverSession{ctx: &context.Context{UserID: user.ID}, currentMailbox: "INBOX", mailboxUIDs: uids}
for _, numbers := range []imap.NumSet{
imap.SeqSet{{Start: 1, Stop: 0}},
imap.UIDSet{{Start: imap.UID(uids[0]), Stop: 0}},
} {
rows, err := session.selectedMessages(numbers)
if err != nil || len(rows) != count {
t.Fatalf("范围读取必须分批保留全部副本:count=%d err=%v", len(rows), err)
}
for index, row := range rows {
if row.UeId != uids[index] || row.SerialNumber != index+1 {
t.Fatalf("分批读取改变了 UID 或会话序号:index=%d uid=%d sequence=%d", index, row.UeId, row.SerialNumber)
}
}
}
if err := session.Expunge(nil, nil); err != nil {
t.Fatalf("大邮箱 EXPUNGE 不能被查询参数上限拒绝:%v", err)
}
if len(session.mailboxUIDs) != count-len(deleted) {
t.Fatalf("删除后快照数量错误:%d", len(session.mailboxUIDs))
}
for _, uid := range session.mailboxUIDs {
if deleted[uid] {
t.Fatalf("已清除的 UID 仍留在会话快照:%d", uid)
}
}
remaining, err := db.Instance.Where("user_id = ?", user.ID).Count(&models.UserEmail{})
if err != nil || remaining != int64(count-len(deleted)) {
t.Fatalf("大邮箱只能清除标记邮件:remaining=%d err=%v", remaining, err)
}
}
func TestAuditSnapshotSearchAndExpungeBoundaries(t *testing.T) {
first, last := auditIMAPMessage(t), auditIMAPMessage(t)
ctx := &context.Context{UserID: first.UserID}
snapshot := []int{first.ID, last.ID}
starUID := imap.UIDSet{{Start: 0, Stop: 0}}
starSequence := imap.SeqSet{{Start: 0, Stop: 0}}
for _, criteria := range []*imap.SearchCriteria{
{UID: []imap.UIDSet{starUID}},
{SeqNum: []imap.SeqSet{starSequence}},
} {
rows, err := list.SearchEmails(ctx, "INBOX", criteria, snapshot)
if err != nil || len(rows) != 1 || rows[0].ID != last.ID {
t.Fatalf("通配应选择快照最后一封:rows=%v err=%v", rows, err)
}
}
rows, err := list.SearchEmails(ctx, "INBOX", &imap.SearchCriteria{
UID: []imap.UIDSet{imap.UIDSetNum(imap.UID(first.ID))}, SeqNum: []imap.SeqSet{starSequence},
}, snapshot)
if err != nil || len(rows) != 0 {
t.Fatalf("UID 筛选不能缩小序号通配上界:rows=%v err=%v", rows, err)
}
session := &serverSession{ctx: ctx, currentMailbox: "INBOX", mailboxUIDs: append([]int{}, snapshot...)}
if _, err := db.Instance.ID(last.ID).Delete(&models.UserEmail{}); err != nil {
t.Fatal(err)
}
for _, criteria := range []*imap.SearchCriteria{
{UID: []imap.UIDSet{starUID}}, {SeqNum: []imap.SeqSet{starSequence}},
{Or: [][2]imap.SearchCriteria{{{UID: []imap.UIDSet{starUID}}, {SeqNum: []imap.SeqSet{starSequence}}}}},
} {
rows, err := list.SearchEmails(ctx, "INBOX", criteria, snapshot)
if err != nil || len(rows) != 0 {
t.Fatalf("未通知删除不能把通配目标前移:rows=%v err=%v", rows, err)
}
}
rows, err = list.SearchEmails(ctx, "INBOX", &imap.SearchCriteria{Not: []imap.SearchCriteria{{UID: []imap.UIDSet{starUID}}}}, snapshot)
if err != nil || len(rows) != 1 || rows[0].ID != first.ID {
t.Fatalf("NOT 必须使用同一快照:rows=%v err=%v", rows, err)
}
selected, err := session.selectedMessages(imap.SeqSetNum(2))
if err != nil || len(selected) != 0 {
t.Fatalf("FETCH/STORE 共用目标解析不能改变已删除序号:rows=%v err=%v", selected, err)
}
if _, err := db.Instance.ID(first.ID).Cols("is_deleted").Update(&models.UserEmail{IsDeleted: 1}); err != nil {
t.Fatal(err)
}
empty := imap.UIDSet{}
for _, set := range []*imap.UIDSet{&empty, &starUID} {
if err := session.Expunge(nil, set); err != nil {
t.Fatal(err)
}
if found, err := db.Instance.ID(first.ID).Exist(&models.UserEmail{}); err != nil || !found {
t.Fatalf("空集合或尾部通配不得删除其他邮件:found=%v err=%v", found, err)
}
}
// 极大反向区间按快照过滤,不能按数值展开或错误拒绝。
wide := imap.UIDSet{{Start: imap.UID(^uint32(0)), Stop: 1}}
if err := session.Expunge(nil, &wide); err != nil {
t.Fatal(err)
}
if found, err := db.Instance.ID(first.ID).Exist(&models.UserEmail{}); err != nil || found {
t.Fatalf("反向范围应删除匹配标记:found=%v err=%v", found, err)
}
if !reflect.DeepEqual(session.mailboxUIDs, []int{last.ID}) {
t.Fatalf("只移除已经通知删除的序号:%v", session.mailboxUIDs)
}
}
// 使用现有 TestMain 创建的临时 SQLite 和随机本地 TLS 端口,不连接开发服务。
func TestAuditCopyThenMoveMustKeepMailboxIdentity(t *testing.T) {
var user models.User
@@ -43,7 +178,12 @@ func TestAuditCopyThenMoveMustKeepMailboxIdentity(t *testing.T) {
if webMoveErr != nil {
t.Errorf("IMAP 复制后网页移动不应把自己的邮件判断为不属于自己: %v", webMoveErr)
}
_, err = clientLogin.Move(uid, "Deleted Messages").Wait()
// 网页移动已经移走原 UID;另建独立样本验证客户端回退,不能重复移动旧 UID。
moveRelation := auditIMAPMessage(t)
if _, err := clientLogin.Select("INBOX", nil).Wait(); err != nil {
t.Fatal(err)
}
_, err = clientLogin.Move(imap.UIDSetNum(imap.UID(moveRelation.ID)), "Deleted Messages").Wait()
t.Logf("copy_relation_count=%d move_error=%v", count, err)
if err != nil {
t.Fatalf("同一用户复制邮件后,移动原文件夹中的 UID 不应失败: %v", err)
+153
View File
@@ -0,0 +1,153 @@
package imap_server
import (
"bufio"
"crypto/tls"
"fmt"
"strings"
"testing"
"time"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/utils/context"
)
// 直接读取隔离 TLS 服务的线上响应,避免客户端库过滤动态 UID 集合。
func auditIMAPWire(t *testing.T) (*tls.Conn, *bufio.Reader) {
t.Helper()
conn, err := tls.Dial("tcp", imapTestAddr, &tls.Config{InsecureSkipVerify: true})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = conn.Close() })
if err := conn.SetDeadline(time.Now().Add(15 * time.Second)); err != nil {
t.Fatal(err)
}
reader := bufio.NewReader(conn)
if line, err := reader.ReadString('\n'); err != nil || !strings.HasPrefix(line, "* OK") {
t.Fatalf("TLS 欢迎响应无效:%q %v", line, err)
}
if _, err := fmt.Fprintf(conn, "a1 LOGIN testCase@test.domain %s\r\n", imapTestProtocolCode); err != nil {
t.Fatal("临时授权码登录写入失败")
}
auditIMAPTagged(t, reader, "a1")
if _, err := fmt.Fprint(conn, "a2 SELECT INBOX\r\n"); err != nil {
t.Fatal(err)
}
auditIMAPTagged(t, reader, "a2")
return conn, reader
}
func auditIMAPTagged(t *testing.T, reader *bufio.Reader, tag string) []string {
t.Helper()
var lines []string
for {
line, err := reader.ReadString('\n')
if err != nil {
t.Fatal(err)
}
lines = append(lines, line)
if strings.HasPrefix(line, tag+" ") {
if !strings.HasPrefix(line, tag+" OK") {
t.Fatalf("命令未成功:%q", line)
}
return lines
}
}
}
func TestAuditUIDFetchWildcardWire(t *testing.T) {
last := auditIMAPMessage(t)
conn, reader := auditIMAPWire(t)
if _, err := fmt.Fprint(conn, "a3 UID FETCH * (UID FLAGS)\r\n"); err != nil {
t.Fatal(err)
}
lines := auditIMAPTagged(t, reader, "a3")
count := 0
for _, line := range lines {
if strings.Contains(line, " FETCH (") {
count++
if !strings.Contains(line, fmt.Sprintf("UID %d", last.ID)) {
t.Fatalf("通配必须返回最大 UID:%q", line)
}
}
}
if count != 1 {
t.Fatalf("UID FETCH * 必须在线上返回一封邮件:%q", lines)
}
}
func auditBeginIdle(t *testing.T, conn *tls.Conn, reader *bufio.Reader, userID int, tag string) {
t.Helper()
if _, err := fmt.Fprintf(conn, "%s IDLE\r\n", tag); err != nil {
t.Fatal(err)
}
if line, err := reader.ReadString('\n'); err != nil || !strings.HasPrefix(line, "+") {
t.Fatalf("未进入 IDLE:%q %v", line, err)
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if _, ok := userConnects.Load(userID); ok {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("IDLE 未登记连接")
}
func TestAuditIDLEChangesDoneAndCleanup(t *testing.T) {
initial := auditIMAPMessage(t)
conn, reader := auditIMAPWire(t)
ctx := &context.Context{UserID: initial.UserID}
auditBeginIdle(t, conn, reader, initial.UserID, "a3")
// 先同步初始快照,再观察新增邮件,避免把进入 IDLE 前的变化重复计入。
if err := IdleNotice(ctx, initial.UserID, &models.Email{Id: initial.EmailID}); err != nil {
t.Fatal(err)
}
if line, err := reader.ReadString('\n'); err != nil || !strings.Contains(line, " EXISTS") {
t.Fatalf("初始通知无效:%q %v", line, err)
}
added := auditIMAPMessage(t)
if err := IdleNotice(ctx, initial.UserID, &models.Email{Id: added.EmailID}); err != nil {
t.Fatal(err)
}
if line, err := reader.ReadString('\n'); err != nil || !strings.Contains(line, " EXISTS") {
t.Fatalf("新增邮件未通知:%q %v", line, err)
}
if _, err := fmt.Fprint(conn, "DONE\r\n"); err != nil {
t.Fatal(err)
}
for _, line := range auditIMAPTagged(t, reader, "a3") {
if strings.Contains(line, " EXISTS") {
t.Fatalf("一次新增产生了重复 EXISTS:%q", line)
}
}
waitIdleConnectionsDeleted(t, initial.UserID)
auditBeginIdle(t, conn, reader, initial.UserID, "a4")
// 外部移动等价于从已选邮箱移除;不借助投递通知,由周期轮询发现变化。
if _, err := db.Instance.ID(added.ID).Cols("status").Update(&models.UserEmail{Status: 5}); err != nil {
t.Fatal(err)
}
if line, err := reader.ReadString('\n'); err != nil || !strings.Contains(line, " EXPUNGE") {
t.Fatalf("外部移除未产生 EXPUNGE:%q %v", line, err)
}
noticed := make(chan error, 1)
go func() { noticed <- IdleNotice(ctx, initial.UserID, &models.Email{Id: initial.EmailID}) }()
if _, err := fmt.Fprint(conn, "DONE\r\n"); err != nil {
t.Fatal(err)
}
auditIMAPTagged(t, reader, "a4")
if err := <-noticed; err != nil {
t.Fatal(err)
}
waitIdleConnectionsDeleted(t, initial.UserID)
if _, err := fmt.Fprint(conn, "a5 LOGOUT\r\n"); err != nil {
t.Fatal(err)
}
auditIMAPTagged(t, reader, "a5")
if _, exists := userConnects.Load(initial.UserID); exists {
t.Fatal("退出后仍残留 IDLE 连接")
}
}
+56
View File
@@ -0,0 +1,56 @@
package res_init
import (
"encoding/json"
"net/http/httptest"
"testing"
"git.pcux.cn/xuans/Smail/controllers"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/services/credentials"
"git.pcux.cn/xuans/Smail/services/externalemail"
"git.pcux.cn/xuans/Smail/services/recovery"
"git.pcux.cn/xuans/Smail/services/verification"
webauthnservice "git.pcux.cn/xuans/Smail/services/webauthn"
appcontext "git.pcux.cn/xuans/Smail/utils/context"
)
func TestAuditStopVerificationWithdrawsPublishedServices(t *testing.T) {
for _, active := range []bool{false, true} {
name := "without_cleanup_runtime"
if active {
name = "with_cleanup_runtime"
}
t.Run(name, func(t *testing.T) {
if active {
runtime, err := verification.NewRuntime(8)
if err != nil {
t.Fatal(err)
}
verificationRuntime = runtime
t.Cleanup(runtime.Stop)
}
credentialService = &credentials.Service{}
webAuthnRuntimeService = &webauthnservice.Service{}
controllers.ConfigureSecurityRuntime(&verification.Service{}, &externalemail.Repository{}, &recovery.Service{}, credentialService)
controllers.ConfigureWebAuthnRuntime(webAuthnRuntimeService)
t.Cleanup(func() {
controllers.ConfigureSecurityRuntime(nil, nil, nil, nil)
controllers.ConfigureWebAuthnRuntime(nil)
verificationRuntime, credentialService, webAuthnRuntimeService = nil, nil, nil
})
stopVerificationRuntime()
stopVerificationRuntime()
if verificationRuntime != nil || credentialService != nil || webAuthnRuntimeService != nil {
t.Fatal("停止必须清除全部运行时引用,且可以重复调用")
}
// 已停止的仓储不能继续进入服务调用,必须在控制器入口拒绝。
writer := httptest.NewRecorder()
controllers.ListExternalEmails(&appcontext.Context{UserID: 1}, writer, httptest.NewRequest("GET", "/", nil))
var result response.Response
if err := json.Unmarshal(writer.Body.Bytes(), &result); err != nil || result.ErrorNo != response.NeedLogin {
t.Fatalf("停止后的控制器没有拒绝旧服务访问:error=%v code=%d", err, result.ErrorNo)
}
})
}
}
+26 -2
View File
@@ -10,6 +10,30 @@ import (
"github.com/emersion/go-msgauth/dkim"
)
func TestAuditStableIMAPBytesAndCcPrivacy(t *testing.T) {
raw := auditRawMessage("Cc: Copy <copy@example.com>\r\n", "recipient@example.com")
parsed, err := NewEmailFromReader([]string{"recipient@example.com", "COPY@example.com", "hidden@example.com"}, strings.NewReader(raw), len(raw))
if err != nil {
t.Fatal(err)
}
if len(parsed.Bcc) != 1 || parsed.Bcc[0].EmailAddress != "hidden@example.com" {
t.Fatal("抄送地址被错误归类为密送")
}
first, err := parsed.BuildIMAPBytes(nil)
if err != nil {
t.Fatal(err)
}
for index := 0; index < 8; index++ {
next, err := parsed.BuildIMAPBytes(nil)
if err != nil || !bytes.Equal(first, next) {
t.Fatalf("同一封邮件 MIME 不稳定: %v", err)
}
}
if _, err := message.Read(bytes.NewReader(first)); err != nil {
t.Fatal(err)
}
}
func auditRawMessage(extraHeaders, to string) string {
return "From: sender@example.com\r\n" +
"To: " + to + "\r\n" +
@@ -81,8 +105,8 @@ func TestAuditQuotedRecipientNameMustNotSplitAddress(t *testing.T) {
func TestAuditInlineAttachmentMustPreserveContentID(t *testing.T) {
email := &Email{
From: &User{EmailAddress: "sender@example.com"},
To: []*User{{EmailAddress: "recipient@example.com"}},
From: &User{EmailAddress: "sender@example.com"},
To: []*User{{EmailAddress: "recipient@example.com"}},
MsgID: "audit-cid@example.com", HTML: []byte(`<img src="cid:audit-inline">`),
Attachments: []*Attachment{{Filename: "inline.png", ContentType: "image/png", ContentID: "audit-inline", Content: []byte{1, 2, 3}}},
}
+52 -13
View File
@@ -1,6 +1,7 @@
package pop3_server
import (
"slices"
"testing"
"git.pcux.cn/xuans/Smail/config"
@@ -10,8 +11,40 @@ import (
"git.pcux.cn/xuans/Smail/utils/context"
)
func TestAuditPOP3AdvertisesStandardReset(t *testing.T) {
commands, err := (action{}).Capa(&gopop.Session{InTls: true})
if err != nil || !slices.Contains(commands, "RSET") || slices.Contains(commands, "REST") {
t.Fatalf("必须公告标准 RSET 而非 REST:commands=%v err=%v", commands, err)
}
}
func TestAuditPOP3SnapshotKeepsHolesAndExcludesNewMail(t *testing.T) {
session, login := auditPOP3Session(t)
for _, id := range []int{101, 202, 303} {
auditPOP3Message(t, session, id, 0)
}
login()
if _, err := (action{}).List(session, ""); err != nil {
t.Fatal(err)
}
if err := (action{}).Delete(session, 2); err != nil {
t.Fatal(err)
}
auditPOP3Message(t, session, 404, 0)
rows, err := (action{}).List(session, "")
if err != nil || len(rows) != 2 || rows[0].Id != 1 || rows[1].Id != 3 {
t.Fatalf("会话序号变化: %v %v", rows, err)
}
if _, err := (action{}).List(session, "2"); err == nil {
t.Fatal("已删除编号仍可访问")
}
if _, err := (action{}).List(session, "4"); err == nil {
t.Fatal("新邮件进入了旧快照")
}
}
// 复用临时 SQLite 和协议授权码夹具,不访问用户运行库。
func auditPOP3Session(t *testing.T) *gopop.Session {
func auditPOP3Session(t *testing.T) (*gopop.Session, func()) {
t.Helper()
engine, user, code := newPOP3ProtocolAuthFixture(t)
oldDB, oldConfig := db.Instance, config.Instance
@@ -20,14 +53,16 @@ func auditPOP3Session(t *testing.T) *gopop.Session {
t.Cleanup(func() {
db.Instance, config.Instance = oldDB, oldConfig
})
session := &gopop.Session{User: "alice@example.com", InTls: true, Ctx: &context.Context{}}
if err := (action{}).Pass(session, code); err != nil {
t.Fatal(err)
session := &gopop.Session{User: "alice@example.com", InTls: true, Ctx: &context.Context{UserID: user.ID}}
return session, func() {
t.Helper()
if err := (action{}).Pass(session, code); err != nil {
t.Fatal(err)
}
if session.Ctx.(*context.Context).UserID != user.ID {
t.Fatal("临时会话未关联预期用户")
}
}
if session.Ctx.(*context.Context).UserID != user.ID {
t.Fatal("临时会话未关联预期用户")
}
return session
}
func auditPOP3Message(t *testing.T, session *gopop.Session, id int, status int8) {
@@ -43,9 +78,10 @@ func auditPOP3Message(t *testing.T, session *gopop.Session, id int, status int8)
}
func TestAuditPOP3MessageNumbersMustStartAtOne(t *testing.T) {
session := auditPOP3Session(t)
session, login := auditPOP3Session(t)
auditPOP3Message(t, session, 101, 0)
auditPOP3Message(t, session, 305, 0)
login()
rows, err := (action{}).List(session, "")
if err != nil || len(rows) != 2 {
t.Fatalf("列表前置条件失败: rows=%v err=%v", rows, err)
@@ -58,8 +94,9 @@ func TestAuditPOP3MessageNumbersMustStartAtOne(t *testing.T) {
}
func TestAuditPOP3MarkedDeletionMustHideMessage(t *testing.T) {
session := auditPOP3Session(t)
session, login := auditPOP3Session(t)
auditPOP3Message(t, session, 1, 0)
login()
if err := (action{}).Delete(session, 1); err != nil {
t.Fatal(err)
}
@@ -81,9 +118,10 @@ func TestAuditPOP3MarkedDeletionMustHideMessage(t *testing.T) {
}
func TestAuditPOP3STATMustMatchVisibleMailbox(t *testing.T) {
session := auditPOP3Session(t)
session, login := auditPOP3Session(t)
auditPOP3Message(t, session, 1, 0)
auditPOP3Message(t, session, 2, 5)
login()
rows, err := (action{}).List(session, "")
if err != nil {
t.Fatal(err)
@@ -93,17 +131,18 @@ func TestAuditPOP3STATMustMatchVisibleMailbox(t *testing.T) {
t.Fatal(err)
}
t.Logf("inbox_messages=1 junk_messages=1 list_count=%d stat_count=%d", len(rows), count)
if count != int64(len(rows)) {
if count != 1 || len(rows) != 1 {
t.Fatal("STAT 纳入垃圾箱邮件,但 LIST 排除了垃圾箱,邮箱视图不一致")
}
}
func TestAuditPOP3NegativeTOPMustNotPanic(t *testing.T) {
session := auditPOP3Session(t)
session, login := auditPOP3Session(t)
auditPOP3Message(t, session, 1, 0)
if _, err := db.Instance.ID(1).Cols("from_address").Update(&models.Email{FromAddress: "sender@example.com"}); err != nil {
t.Fatal(err)
}
login()
if _, err := (action{}).Top(session, 1, 0); err != nil {
t.Fatalf("正常 TOP 前置条件失败: %v", err)
}
+66
View File
@@ -2,6 +2,8 @@ package recovery
import (
"errors"
"sync"
"sync/atomic"
"testing"
"time"
@@ -10,6 +12,70 @@ import (
"git.pcux.cn/xuans/Smail/utils/password"
)
func TestAuditRecoveryDependenciesAreRaceSafeAndReentrant(t *testing.T) {
service, _, _, user := newRecoveryFixture(t)
var calls atomic.Int32
callback := func(userID int, account string) {
service.InvalidateUser(userID)
service.SetSecurityStateInvalidator(nil)
calls.Add(1)
}
verifier := &webauthnservice.Service{}
var workers sync.WaitGroup
workers.Add(2)
go func() {
defer workers.Done()
for index := 0; index < 1000; index++ {
service.SetSecurityStateInvalidator(callback)
service.SetWebAuthnVerifier(verifier)
service.SetWebAuthnVerifier(nil)
}
}()
go func() {
defer workers.Done()
for index := 0; index < 1000; index++ {
_ = service.currentWebAuthnVerifier()
service.invalidateSecurityState(user.ID, user.Account)
}
}()
workers.Wait()
service.SetSecurityStateInvalidator(callback)
ticket, err := service.issueTicketFor(user.ID, user.SessionVersion, "", 0, 0, "audit-browser")
if err != nil {
t.Fatal(err)
}
before := calls.Load()
if err := service.CompleteWithContext(ticket, "AuditPass123", "audit-browser"); err != nil {
t.Fatal(err)
}
if calls.Load() != before+1 {
t.Fatal("真实密码恢复提交必须执行一次可重入的失效回调")
}
}
func TestAuditRecoveryRejectsDisabledOrChangedSession(t *testing.T) {
for _, field := range []string{"disabled", "session_version"} {
t.Run(field, func(t *testing.T) {
service, _, engine, user := newRecoveryFixture(t)
ticket, err := service.issueTicketFor(user.ID, user.SessionVersion, "", 0, 0, "audit-browser")
if err != nil {
t.Fatal(err)
}
update := models.User{Disabled: 1, SessionVersion: user.SessionVersion + 1}
if _, err := engine.ID(user.ID).Cols(field).Update(&update); err != nil {
t.Fatal(err)
}
if err := service.CompleteWithContext(ticket, "AuditPass123", "audit-browser"); !errors.Is(err, ErrRecoveryDenied) {
t.Fatalf("旧票据应拒绝:%v", err)
}
var stored models.User
if found, err := engine.ID(user.ID).Get(&stored); err != nil || !found || stored.Password != user.Password {
t.Fatalf("拒绝后密码发生变化:found=%v err=%v", found, err)
}
})
}
}
// 审查专用:从已验证后签发票据的位置开始,仅验证撤销后的授权有效性。
// 本测试不模拟或绕过真实 WebAuthn 签名验证,也不调用真实服务。
func TestAuditRevokedWebAuthnMustInvalidateRecoveryTicket(t *testing.T) {
+5
View File
@@ -8,6 +8,8 @@ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
const directory = path.join(root, 'test-log', `audit-${stamp}-${process.pid}`)
await mkdir(directory, { recursive: true })
const replacements = {
'backend/res_init/audit_findings_test.go': 'test/review/lifecycle_findings_test.go',
'backend/hooks/wechat_push/audit_findings_test.go': 'test/review/wechat_findings_test.go',
'backend/hooks/framework/audit_findings_test.go': 'test/review/plugin_framework_findings_test.go',
'backend/utils/async/audit_findings_test.go': 'test/review/async_findings_test.go',
'backend/utils/address/audit_findings_test.go': 'test/review/address_findings_test.go',
@@ -22,6 +24,7 @@ const replacements = {
'backend/services/list/audit_findings_test.go': 'test/review/list_findings_test.go',
'backend/services/recovery/audit_findings_test.go': 'test/review/recovery_findings_test.go',
'backend/listen/imap_server/audit_findings_test.go': 'test/review/imap_findings_test.go',
'backend/listen/imap_server/audit_wire_findings_test.go': 'test/review/imap_wire_findings_test.go',
'backend/controllers/audit_findings_test.go': 'test/review/runtime_findings_test.go',
'backend/controllers/audit_controller_findings_test.go': 'test/review/controller_findings_test.go',
'backend/internal/gopop/audit_findings_test.go': 'test/review/pop3_parser_findings_test.go',
@@ -51,6 +54,8 @@ const addressOnly = process.argv.includes('--address-only')
const packages = frameworkOnly ? ['./hooks/framework'] : asyncOnly ? ['./utils/async'] : addressOnly ? ['./utils/address'] : totpOnly ? ['./services/totp'] : sslOnly ? ['./services/setup/ssl'] : setupOnly ? ['./services/setup'] : httpOnly ? ['./listen/http_server'] : controllersOnly ? ['./controllers'] : configOnly ? ['./config'] : migrationOnly ? ['./services/dbmigration'] : pop3Only ? ['./internal/gopop', './listen/pop3_server'] : messageOnly ? [
'./dto/parsemail', './listen/smtp_server'
] : [
'./res_init',
'./hooks/wechat_push',
'./services/dbmigration', './listen/http_server', './services/list', './services/recovery',
'./listen/imap_server', './controllers', './internal/gopop', './listen/pop3_server',
'./dto/parsemail', './listen/smtp_server', './config', './services/setup', './services/setup/ssl', './services/totp', './hooks/framework'
+77
View File
@@ -3,8 +3,85 @@ package controllers
import (
"sync"
"testing"
"time"
"git.pcux.cn/xuans/Smail/services/credentials"
"git.pcux.cn/xuans/Smail/services/externalemail"
"git.pcux.cn/xuans/Smail/services/recovery"
"git.pcux.cn/xuans/Smail/services/verification"
webauthnservice "git.pcux.cn/xuans/Smail/services/webauthn"
)
func TestAuditClearSecurityRuntimeRemovesEveryPublishedService(t *testing.T) {
previous := currentSecurityRuntime()
t.Cleanup(func() {
ConfigureSecurityRuntime(previous.verification, previous.external, previous.recovery, previous.credentials)
ConfigureWebAuthnRuntime(previous.webauthn)
})
ConfigureSecurityRuntime(&verification.Service{}, &externalemail.Repository{}, &recovery.Service{}, &credentials.Service{})
ConfigureWebAuthnRuntime(&webauthnservice.Service{})
loginVerificationState.Lock()
loginVerificationState.items["audit-stop"] = loginVerificationItem{ExpiresAt: time.Now().Add(time.Minute)}
loginVerificationState.Unlock()
ClearSecurityRuntime()
ClearSecurityRuntime()
if currentSecurityRuntime() != (securityRuntimeState{}) {
t.Fatal("安全服务必须整批撤下")
}
loginVerificationState.Lock()
defer loginVerificationState.Unlock()
if len(loginVerificationState.items) != 0 {
t.Fatal("停止后不能保留旧登录验证挑战")
}
}
func TestAuditSecurityRuntimeSnapshotPublication(t *testing.T) {
previous := currentSecurityRuntime()
t.Cleanup(func() {
ConfigureSecurityRuntime(previous.verification, previous.external, previous.recovery, previous.credentials)
ConfigureWebAuthnRuntime(previous.webauthn)
})
first := securityRuntimeState{
verification: &verification.Service{}, external: &externalemail.Repository{},
recovery: &recovery.Service{}, credentials: &credentials.Service{},
}
second := securityRuntimeState{
verification: &verification.Service{}, external: &externalemail.Repository{},
recovery: &recovery.Service{}, credentials: &credentials.Service{},
}
key := &webauthnservice.Service{}
ConfigureSecurityRuntime(first.verification, first.external, first.recovery, first.credentials)
ConfigureWebAuthnRuntime(key)
var workers sync.WaitGroup
for worker := 0; worker < 4; worker++ {
workers.Add(1)
go func(writer bool) {
defer workers.Done()
for index := 0; index < 1000; index++ {
if writer {
next := first
if index%2 == 0 {
next = second
}
ConfigureSecurityRuntime(next.verification, next.external, next.recovery, next.credentials)
continue
}
snapshot := currentSecurityRuntime()
if snapshot.webauthn != key {
t.Error("安全服务发布不能清空独立配置的安全密钥服务")
return
}
snapshot.webauthn = nil
if snapshot != first && snapshot != second {
t.Error("一次读取不能混合不同发布批次的服务指针")
return
}
}
}(worker%2 == 0)
}
workers.Wait()
}
// 并发模拟停止阶段清空安全服务与在途控制器获取服务;必须以 -race 运行。
func TestAuditWebAuthnRuntimePublication(t *testing.T) {
previous := webAuthnRuntime()
+4 -1
View File
@@ -59,7 +59,7 @@ func auditCertificateChain(t *testing.T, domain string, extraDomains ...string)
t.Fatal(err)
}
return certificate.Resource{
PrivateKey: pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privateDER}),
PrivateKey: pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: privateDER}),
Certificate: append(leafPEM, issuerPEM...), IssuerCertificate: issuerPEM,
}
}
@@ -126,6 +126,9 @@ func TestAuditFreshWildcardCertificateMustNotRequireRenewal(t *testing.T) {
// 只在临时根目录建立受控证书和真实分区配置,不接触运行中的实例。
func auditMigratedSSL(t *testing.T, mode string) (*config.Config, []byte) {
t.Helper()
oldManager := config.CurrentManager()
config.SetRuntimeManager(nil)
t.Cleanup(func() { config.SetRuntimeManager(oldManager) })
auditSSLRoot(t)
resource := auditCertificateChain(t, "imap.example.test", "smtp.imap.example.test", "pop.imap.example.test", "imap.imap.example.test")
reference, err := config.ImportManagedSSL(config.ManagedSSLModeDefault, resource.PrivateKey, resource.Certificate, nil, nil)
+40
View File
@@ -15,6 +15,8 @@ import (
"time"
"unicode/utf8"
xhtml "golang.org/x/net/html"
"git.pcux.cn/xuans/Smail/dto/parsemail"
"git.pcux.cn/xuans/Smail/models"
"github.com/go-telegram/bot"
@@ -150,3 +152,41 @@ func TestAuditTelegramTruncationMustKeepUTF8(t *testing.T) {
})
}
}
func TestAuditTelegramTruncationKeepsClosedMarkup(t *testing.T) {
hook, _ := auditTelegramHook(t)
for _, spoiler := range []bool{false, true} {
text := hook.buildSendText(&parsemail.Email{
Subject: strings.Repeat("<主题>&\"", 300),
To: []*parsemail.User{nil, {EmailAddress: "<script>@example.com"}},
Text: []byte(strings.Repeat("中文 & <正文> 😀", 1000)),
}, &model.TelegramPushSetting{ShowContent: true, SpoilerContent: spoiler})
if !utf8.ValidString(text) || len(text) > TELEGRAM_TEXT_MAX_SIZE {
t.Fatalf("通知长度或编码错误:%d", len(text))
}
parser := xhtml.NewTokenizer(strings.NewReader(text))
stack := []string{}
for {
switch parser.Next() {
case xhtml.ErrorToken:
if parser.Err() != io.EOF || len(stack) != 0 {
t.Fatalf("通知标签未完整闭合:%v %v", stack, parser.Err())
}
goto done
case xhtml.StartTagToken:
name, _ := parser.TagName()
if string(name) != "b" && string(name) != "tg-spoiler" {
t.Fatalf("外部内容被解释成标签:%s", name)
}
stack = append(stack, string(name))
case xhtml.EndTagToken:
name, _ := parser.TagName()
if len(stack) == 0 || stack[len(stack)-1] != string(name) {
t.Fatalf("标签不匹配:%s", name)
}
stack = stack[:len(stack)-1]
}
}
done:
}
}
+55
View File
@@ -0,0 +1,55 @@
package main
import (
"bytes"
"io"
"net/http"
"strings"
"testing"
"time"
appcontext "git.pcux.cn/xuans/Smail/utils/context"
log "github.com/sirupsen/logrus"
)
func TestAuditWeChatBusinessResponses(t *testing.T) {
for _, test := range []struct {
name, body string
status int
clear bool
}{
{"success", `{"errcode":0}`, 200, false},
{"expired", `{"errcode":42001,"errmsg":"private-body"}`, 200, true},
{"invalid", `{"errcode":40001}`, 200, true},
{"revoked", `{"errcode":40014}`, 200, true},
{"business", `{"errcode":43004,"errmsg":"private-body"}`, 200, false},
{"missing", `{}`, 200, false},
{"malformed", `not-json`, 200, false},
{"oversize", strings.Repeat("x", maxWeChatResponseBytes+1), 200, false},
{"http", `private-body`, 500, false},
} {
t.Run(test.name, func(t *testing.T) {
var output bytes.Buffer
logger := log.StandardLogger()
old := logger.Out
logger.SetOutput(&output)
defer logger.SetOutput(old)
calls := 0
hook := &WeChatPushHook{token: "private-token", tokenExpires: time.Now().Add(time.Hour).Unix()}
hook.httpClient = &http.Client{Transport: weChatRoundTripFunc(func(*http.Request) (*http.Response, error) {
calls++
return &http.Response{StatusCode: test.status, Body: io.NopCloser(strings.NewReader(test.body))}, nil
})}
hook.sendUserMsg(&appcontext.Context{}, "private-recipient", "private-message")
if calls != 1 || (hook.token == "") != test.clear {
t.Fatalf("响应处理错误: calls=%d cleared=%v", calls, hook.token == "")
}
if test.name != "success" && output.Len() == 0 {
t.Fatal("失败响应未记录")
}
if strings.Contains(output.String(), "private-") {
t.Fatal("日志泄露响应或凭据")
}
})
}
}
+3 -2
View File
@@ -25,7 +25,7 @@ foreach ($command in $commands) {
# 只执行真实事务语句,所有文件和服务操作均为内存函数桩,不执行安装脚本主体。
$transaction = [scriptblock]::Create($tries[0].Extent.Text)
$results = @()
foreach ($stage in @('stop', 'copy-main', 'copy-admin', 'backup-main', 'backup-admin', 'install-main')) {
foreach ($stage in @('stop', 'copy-main', 'copy-admin', 'backup-main', 'backup-admin', 'install-main', 'install-admin', 'service')) {
$results += & {
param($failureStage, $body)
$virtualRoot = [IO.Path]::GetFullPath((Join-Path $workspace 'test-log\virtual-install-audit'))
@@ -88,6 +88,7 @@ foreach ($stage in @('stop', 'copy-main', 'copy-admin', 'backup-main', 'backup-a
if ($LiteralPath -eq $mainTarget) { Invoke-Failure 'backup-main' }
if ($LiteralPath -eq $adminTarget) { Invoke-Failure 'backup-admin' }
if ($Destination -eq $mainTarget -and $LiteralPath -ne $mainBackup) { Invoke-Failure 'install-main' }
if ($Destination -eq $adminTarget -and $LiteralPath -ne $adminBackup) { Invoke-Failure 'install-admin' }
$state.Files[$Destination] = $state.Files[$LiteralPath]
$state.Files.Remove($LiteralPath)
$state.Operations.Add("move:$LiteralPath")
@@ -98,7 +99,7 @@ foreach ($stage in @('stop', 'copy-main', 'copy-admin', 'backup-main', 'backup-a
$state.Files.Remove($LiteralPath)
$state.Operations.Add("remove:$LiteralPath")
}
function Get-Service { throw '不得调用真实系统服务' }
function Get-Service { Invoke-Failure 'service'; throw '不得调用真实系统服务' }
function Invoke-Native { throw '不得调用原生系统工具' }
function Set-RestrictedAcl { throw '不得修改真实权限' }
function Start-Service { throw '不得启动真实服务' }