This commit is contained in:
1 parent
b50e5bdfa2
commit
dd6258c98b
34 files changed
+734
-87
No files matched your search
@@ -1,6 +1,8 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"runtime"
|
||||
"strings"
|
||||
@@ -33,3 +35,31 @@ func TestLogFormatterPreservesStructuredEvidence(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeEventMetadataNeverInventsSuccessfulCompletion(t *testing.T) {
|
||||
for _, item := range []struct {
|
||||
message, result string
|
||||
data log.Fields
|
||||
}{
|
||||
{"包含成功文字但未提供完成信号", "recorded", nil},
|
||||
{"开始启动", "started", log.Fields{"action": "启动服务", "result": "started"}},
|
||||
{"连接失败", "failure", log.Fields{"action": "连接数据库", "result": "failure"}},
|
||||
} {
|
||||
entry := &log.Entry{Time: time.Now(), Level: log.WarnLevel, Context: context.Background(), Message: item.message, Data: item.data}
|
||||
data, err := (&logFormatter{}).Format(entry)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts := strings.Split(string(data), " @event ")
|
||||
var fields map[string]any
|
||||
if len(parts) != 2 || json.Unmarshal([]byte(parts[1]), &fields) != nil {
|
||||
t.Fatalf("无效元数据:%s", data)
|
||||
}
|
||||
if fields["result"] != item.result || fields["action"] == "" || fields["logSchema"] != float64(1) {
|
||||
t.Fatalf("结果错误:%+v", fields)
|
||||
}
|
||||
if _, changed := item.data["logSchema"]; changed {
|
||||
t.Fatal("格式器修改了调用者字段")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package logstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/textproto"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMailLogKeepsTriggerStageAndOutcomeWithoutRemoteSecrets(t *testing.T) {
|
||||
s := testStore(t)
|
||||
runtime := Start(s)
|
||||
defer runtime.Stop()
|
||||
for _, item := range []struct{ result, trigger, stage string }{
|
||||
{"accepted", "网页写信", "对外投递"},
|
||||
{"partial", "邮件规则转发", "对外投递"},
|
||||
{"failure", "SMTP 收信", "解析邮件"},
|
||||
{"discarded", "SMTP 收信", "收信策略"},
|
||||
} {
|
||||
MailResult(42, "outbound", "sender@example.com", 3, 100, item.result,
|
||||
MailDetails{Trigger: item.trigger, Stage: item.stage, AcceptedCount: 1})
|
||||
entries, err := s.Query(context.Background(), Query{Kind: "mail", Limit: 1})
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(entries[0].Payload, &payload) != nil {
|
||||
t.Fatal("无效邮件载荷")
|
||||
}
|
||||
if entries[0].Result != item.result || payload["trigger"] != item.trigger || payload["stage"] != item.stage || payload["outcome"] == "" || payload["acceptedCount"] != float64(1) {
|
||||
t.Fatalf("缺少操作或结果:%+v", payload)
|
||||
}
|
||||
}
|
||||
for _, cause := range []error{
|
||||
errors.New("private-token"), &textproto.Error{Code: 550, Msg: "private-token"},
|
||||
&net.DNSError{Err: "private-token", Name: "private-domain", IsNotFound: true},
|
||||
} {
|
||||
if reason := MailFailureReason(cause); reason == "" || strings.Contains(reason, "private-") {
|
||||
t.Fatal("远端敏感内容泄露")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/db/migration"
|
||||
@@ -69,8 +70,61 @@ func TestOperationLogUsesCompletedIdentityWithoutSensitivePayload(t *testing.T)
|
||||
if err := json.Unmarshal(entry.Payload, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if entry.Result != "success" || payload["actorName"] != "audit-probe" || len(payload) != 3 {
|
||||
if entry.Result != "success" || payload["actorName"] != "audit-probe" || len(payload) != 7 || payload["outcome"] != "操作已完成" || payload["trigger"] == "" || payload["object"] == "" || strings.Contains(string(entry.Payload), "must-not-store") {
|
||||
t.Fatalf("incorrect or excessive audit metadata: %+v", payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationResponseDistinguishesPendingHTTPFailureAndUnknown(t *testing.T) {
|
||||
database, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "results.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
migrations := migration.DefaultMigrations()
|
||||
for _, statement := range migrations[len(migrations)-1].StatementsFor(migration.DialectSQLite) {
|
||||
if _, err := database.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
store, err := logstore.New(database, migration.DialectSQLite)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime := logstore.Start(store)
|
||||
defer runtime.Stop()
|
||||
for _, item := range []struct {
|
||||
name, want string
|
||||
write func(http.ResponseWriter)
|
||||
}{
|
||||
{"pending", "pending", func(w http.ResponseWriter) {
|
||||
response.NewSuccessResponse(map[string]any{"pending": true, "challenge_id": "private-challenge"}).FPrint(w)
|
||||
}},
|
||||
{"failure", "failure", func(w http.ResponseWriter) {
|
||||
response.NewErrorResponse(response.ParamsError, "private-detail", "private-code").FPrint(w)
|
||||
}},
|
||||
{"http", "failure", func(w http.ResponseWriter) { http.Error(w, "private-detail", http.StatusForbidden) }},
|
||||
{"unknown", "unknown", func(w http.ResponseWriter) { _, _ = w.Write([]byte("not-a-business-response")) }},
|
||||
} {
|
||||
ctx := &appcontext.Context{UserID: 42, UserAccount: item.name}
|
||||
writer, finish := operationLog(ctx, httptest.NewRequest("POST", "/api/v1/login?password=private-query", strings.NewReader("private-request")), httptest.NewRecorder())
|
||||
item.write(writer)
|
||||
finish()
|
||||
entries, err := store.Query(context.Background(), logstore.Query{Kind: "operation", Limit: 1})
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry := entries[0]
|
||||
if entry.Result != item.want || strings.Contains(string(entry.Payload), "private-") || strings.Contains(string(entry.Payload), "not-a-business-response") {
|
||||
t.Fatalf("结果错误或泄露请求:%s %+v", item.name, entry)
|
||||
}
|
||||
}
|
||||
before, _ := store.Query(context.Background(), logstore.Query{Kind: "operation"})
|
||||
_, finish := operationLog(&appcontext.Context{}, httptest.NewRequest("POST", "/api/v1/email/list", nil), httptest.NewRecorder())
|
||||
finish()
|
||||
after, _ := store.Query(context.Background(), logstore.Query{Kind: "operation"})
|
||||
if len(before) != len(after) {
|
||||
t.Fatal("只读查询不能新增操作记录")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package send
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestDeliveryLogResultUsesConfirmedRecipientCount(t *testing.T) {
|
||||
for _, item := range []struct {
|
||||
accepted, total int
|
||||
failed bool
|
||||
want string
|
||||
}{
|
||||
{3, 3, false, "accepted"},
|
||||
{1, 3, true, "partial"},
|
||||
{1, 3, false, "partial"},
|
||||
{3, 3, true, "partial"},
|
||||
{0, 3, true, "failure"},
|
||||
{0, 3, false, "unknown"},
|
||||
{0, 0, false, "unknown"},
|
||||
} {
|
||||
if got := deliveryLogResult(item.accepted, item.total, item.failed); got != item.want {
|
||||
t.Fatalf("接收人数 %d/%d,失败=%v:得到 %s,期望 %s", item.accepted, item.total, item.failed, got, item.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package smtp_server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/db/migration"
|
||||
"git.pcux.cn/xuans/Smail/services/logstore"
|
||||
appcontext "git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
|
||||
type failedMailReader struct{}
|
||||
|
||||
func (failedMailReader) Read([]byte) (int, error) { return 0, errors.New("private-reader-error") }
|
||||
|
||||
func TestSMTPDataLogDistinguishesDiscardedMailAndReadFailure(t *testing.T) {
|
||||
engine, _ := newAuditTestEngine(t)
|
||||
config.Instance.SpamFilterLevel = 3
|
||||
migrations := migration.DefaultMigrations()
|
||||
for _, statement := range migrations[len(migrations)-1].StatementsFor(migration.DialectSQLite) {
|
||||
if _, err := engine.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
store, err := logstore.New(engine.DB().DB, migration.DialectSQLite)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime := logstore.Start(store)
|
||||
defer runtime.Stop()
|
||||
session := &Session{
|
||||
Ctx: &appcontext.Context{Context: context.Background()},
|
||||
From: "sender@example.net", To: []string{"absent@example.com"},
|
||||
RemoteAddress: &net.TCPAddr{IP: net.IPv4(192, 168, 1, 2), Port: 25},
|
||||
}
|
||||
message := "From: sender@example.net\r\nTo: absent@example.com\r\nSubject: private-subject\r\n\r\nprivate-body"
|
||||
if err := session.Data(bytes.NewBufferString(message)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertAuditCounts(t, engine, 0, 0)
|
||||
for _, result := range []string{"discarded", "failure"} {
|
||||
if result == "failure" && session.Data(failedMailReader{}) == nil {
|
||||
t.Fatal("读取失败未返回错误")
|
||||
}
|
||||
entries, err := store.Query(context.Background(), logstore.Query{Kind: "mail", Limit: 1})
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatal("缺少收信处理记录", err)
|
||||
}
|
||||
entry := entries[0]
|
||||
var details logstore.MailDetails
|
||||
if err := json.Unmarshal(entry.Payload, &details); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if entry.Result != result || details.Trigger != "SMTP 收信" || details.Stage == "" || details.Outcome == "" {
|
||||
t.Fatalf("收信状态错误:%+v", entry)
|
||||
}
|
||||
if strings.Contains(string(entry.Payload), "private-") {
|
||||
t.Fatal("收信日志泄露内容或原始错误")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package verification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/db/migration"
|
||||
"git.pcux.cn/xuans/Smail/services/logstore"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func TestRelayMailLogRecordsResultWithoutChallengeSecrets(t *testing.T) {
|
||||
database, err := sql.Open("sqlite", filepath.Join(t.TempDir(), "relay-logs.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
database.SetMaxOpenConns(1)
|
||||
migrations := migration.DefaultMigrations()
|
||||
for _, statement := range migrations[len(migrations)-1].StatementsFor(migration.DialectSQLite) {
|
||||
if _, err := database.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
store, err := logstore.New(database, migration.DialectSQLite)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime := logstore.Start(store)
|
||||
defer runtime.Stop()
|
||||
settings := SMTPSettings{Host: "localhost", Port: 25, Security: SecurityPlain, From: "sender@example.com", Username: "private-user", Password: "private-password"}
|
||||
for _, item := range []struct {
|
||||
cause error
|
||||
result string
|
||||
count int
|
||||
}{{nil, "accepted", 1}, {errors.New("private-remote-error"), "failure", 0}} {
|
||||
delivery, err := NewSMTPDelivery(settings)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var message []byte
|
||||
delivery.send = func(_ SMTPSettings, _ string, data []byte) error {
|
||||
message = data
|
||||
return item.cause
|
||||
}
|
||||
err = delivery.Delivery()(Challenge{Email: "private-recipient@example.com", ID: "private-challenge", Purpose: PurposeLogin}, "private-code")
|
||||
if !errors.Is(err, item.cause) {
|
||||
t.Fatal("发送结果被改变")
|
||||
}
|
||||
for _, value := range message {
|
||||
if value != 0 {
|
||||
t.Fatal("验证码邮件缓冲未清理")
|
||||
}
|
||||
}
|
||||
entries, err := store.Query(context.Background(), logstore.Query{Kind: "mail", Limit: 1})
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatal("缺少中继发送记录", err)
|
||||
}
|
||||
entry := entries[0]
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(entry.Payload, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if entry.Result != item.result || payload["acceptedCount"] != float64(item.count) || payload["stage"] != "SMTP 中继投递" || payload["trigger"] != "系统安全验证邮件" || payload["outcome"] == "" {
|
||||
t.Fatalf("中继日志结果不完整:%+v", entry)
|
||||
}
|
||||
if strings.Contains(string(entry.Payload), "private-") {
|
||||
t.Fatal("中继日志包含敏感信息")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -212,3 +212,28 @@ test('本页级别统计准确,压缩文件大小和空页区间明确', () =>
|
||||
assert.match(read('LogSettings.vue'), /本页日志统计/)
|
||||
assert.doesNotMatch(read('LogSettings.vue'), /lines\.join/)
|
||||
})
|
||||
|
||||
test('运行日志明确展示结构化操作和结果,不把级别或开始事件当作成功', () => {
|
||||
const header = '[2026-09-08T14:55:23Z] [warning][2026-09-08 22:55:23][app.go:39]'
|
||||
const data = { logSchema: 1, action: '启动服务', result: 'started', object: 'HTTP' }
|
||||
const raw = `${header}开始启动 @event ${JSON.stringify(data)}`
|
||||
const row = parseRuntimeLine(raw, 1)
|
||||
assert.equal(row.action, '启动服务')
|
||||
assert.equal(row.result, 'started')
|
||||
assert.equal(row.outcome, '开始启动')
|
||||
assert.equal(row.object, 'HTTP')
|
||||
assert.equal(row.raw, raw)
|
||||
for (const message of ['旧启动成功', '正文 {"result":"success"}', '截断 @event {"logSchema":1', '内容 @event null']) {
|
||||
const old = parseRuntimeLine(header + message, 1)
|
||||
assert.equal(old.result, 'unknown')
|
||||
assert.equal(old.outcome, message)
|
||||
}
|
||||
const { page } = fixture(async () => ({ errorNo: 0, data: {} }))
|
||||
assert.equal(page.resultLabel('pending'), '待验证')
|
||||
assert.equal(page.resultLabel('accepted'), '对端接收')
|
||||
assert.equal(page.resultLabel('partial'), '部分接收')
|
||||
assert.equal(page.displayOutcome({ payload: {} }), '历史记录未提供结果说明')
|
||||
assert.equal(page.displayObject({ payload: { stage: '解析邮件' } }), '解析邮件')
|
||||
assert.match(read('LogSettings.vue'), /runtimeDetail\.action/)
|
||||
assert.match(read('LogSettings.vue'), /runtimeDetail\.result/)
|
||||
})
|
||||
@@ -54,6 +54,10 @@ if ((suite === 'all' || suite === 'backend') && result === 0) {
|
||||
'backend/controllers/login_audit_test.go': 'test/backend/login_audit_test.go',
|
||||
'backend/controllers/logs_api_test.go': 'test/backend/logs_api_test.go',
|
||||
'backend/services/logstore/log_store_test.go': 'test/backend/log_store_test.go',
|
||||
'backend/services/logstore/mail_log_result_test.go': 'test/backend/mail_log_result_test.go',
|
||||
'backend/services/verification/mail_log_test.go': 'test/backend/verification_mail_log_test.go',
|
||||
'backend/utils/send/log_result_test.go': 'test/backend/send_log_result_test.go',
|
||||
'backend/listen/smtp_server/mail_log_test.go': 'test/backend/smtp_mail_log_test.go',
|
||||
'backend/services/logstore/log_store_integration_test.go': 'test/backend/log_store_integration_test.go',
|
||||
'backend/services/runtimelog/runtime_logs_test.go': 'test/backend/runtime_logs_test.go',
|
||||
'backend/services/runtimelog/migration_test.go': 'test/backend/runtime_log_migration_test.go',
|
||||
|
||||
Reference in new issue
Block a user