完成配置迁移、插件安全整改与初始化向导优化
This commit is contained in:
1 parent
ce1b557ea9
commit
84440d8761
71 files changed
+14140
-836
No files matched your search
@@ -129,3 +129,29 @@ func TestUnixControlSocketUsesRestrictedPermissions(t *testing.T) {
|
||||
t.Fatalf("control socket permissions = %04o, want 0600", socketInfo.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnixServerStopsWhenContextIsCancelled(t *testing.T) {
|
||||
path := t.TempDir() + "/control.sock"
|
||||
server, err := ListenUnix(path, []uint32{uint32(os.Getuid())})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- server.Serve(ctx, func(string) error { return nil }, NewSessionGuard(time.Minute))
|
||||
}()
|
||||
|
||||
cancel()
|
||||
if err := server.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("server stop error = %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("server did not stop after cancellation")
|
||||
}
|
||||
}
|
||||
@@ -116,6 +116,8 @@ func (s *UnixServer) handle(conn net.Conn, handler ResetHandler, guard *SessionG
|
||||
_ = EncodeResponse(conn, Response{Code: "UNAUTHORIZED", Message: "本机调用者身份不受信任"})
|
||||
return
|
||||
}
|
||||
_ = conn.SetDeadline(time.Now().Add(controlRequestTimeout))
|
||||
defer conn.SetDeadline(time.Time{})
|
||||
nonce, err := guard.Issue()
|
||||
if err != nil {
|
||||
_ = EncodeResponse(conn, Response{Code: "CHANNEL_UNAVAILABLE", Message: "\u91cd\u7f6e\u901a\u9053\u4e0d\u53ef\u7528"})
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package plugin
|
||||
|
||||
import shared "git.pcux.cn/xuans/Smail/plugins/catalog"
|
||||
|
||||
var (
|
||||
ErrUnknownPluginID = shared.ErrUnknownPluginID
|
||||
ErrInvalidPluginTarget = shared.ErrInvalidPluginTarget
|
||||
)
|
||||
|
||||
type Definition = shared.Definition
|
||||
|
||||
func Definitions() []Definition {
|
||||
return shared.Definitions()
|
||||
}
|
||||
|
||||
func Lookup(logicalID string) (Definition, bool) {
|
||||
return shared.Lookup(logicalID)
|
||||
}
|
||||
|
||||
func ExecutableName(logicalID, goos string) (string, error) {
|
||||
return shared.ExecutableName(logicalID, goos)
|
||||
}
|
||||
|
||||
func CurrentExecutableName(logicalID string) (string, error) {
|
||||
return shared.CurrentExecutableName(logicalID)
|
||||
}
|
||||
|
||||
func EnabledDefinitions(values []string, goos string) ([]Definition, error) {
|
||||
return shared.EnabledDefinitions(values, goos)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExecutableNameUsesFixedPlatformMapping(t *testing.T) {
|
||||
cases := []struct {
|
||||
logicalID string
|
||||
goos string
|
||||
want string
|
||||
}{
|
||||
{logicalID: "spam_block", goos: "windows", want: "spam_block.exe"},
|
||||
{logicalID: "wechat_push", goos: "linux", want: "wechat_push"},
|
||||
{logicalID: "telegram_push", goos: "windows", want: "pmail_telegram_push.exe"},
|
||||
{logicalID: "telegram_push", goos: "darwin", want: "pmail_telegram_push"},
|
||||
}
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.logicalID+"/"+testCase.goos, func(t *testing.T) {
|
||||
got, err := ExecutableName(testCase.logicalID, testCase.goos)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != testCase.want {
|
||||
t.Fatalf("executable = %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnabledDefinitionsOnlyAcceptsRegisteredIdentifiers(t *testing.T) {
|
||||
definitions, err := EnabledDefinitions([]string{"spam_block.exe", "wechat_push", "pmail_telegram_push.exe"}, "windows")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(definitions) != 3 || definitions[0].LogicalID != "spam_block" || definitions[1].LogicalID != "telegram_push" || definitions[2].LogicalID != "wechat_push" {
|
||||
t.Fatalf("definitions = %+v", definitions)
|
||||
}
|
||||
for _, value := range []string{"../spam_block", "Spam_Block", "unknown", "spam_block", "spam_block"} {
|
||||
_, err := EnabledDefinitions([]string{value}, "linux")
|
||||
if value == "spam_block" {
|
||||
if err != nil {
|
||||
t.Fatalf("logical ID was rejected: %v", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !errors.Is(err, ErrInvalidPluginTarget) && !errors.Is(err, ErrUnknownPluginID) {
|
||||
t.Fatalf("value %q error = %v", value, err)
|
||||
}
|
||||
}
|
||||
if _, err := EnabledDefinitions([]string{"spam_block", "spam_block.exe"}, "windows"); !errors.Is(err, ErrInvalidPluginTarget) {
|
||||
t.Fatalf("duplicate error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefinitionsReturnsIndependentCopies(t *testing.T) {
|
||||
definitions := Definitions()
|
||||
definitions[1].Capabilities[0] = "changed"
|
||||
again := Definitions()
|
||||
if again[1].Capabilities[0] != "network" {
|
||||
t.Fatalf("catalog was mutated: %+v", again)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,755 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
const (
|
||||
telegramPluginID = "telegram_push"
|
||||
userSettingsSchemaVersion uint32 = 1
|
||||
maxBulkTargets = 100
|
||||
)
|
||||
|
||||
var (
|
||||
ErrPluginStoreUnavailable = errors.New("plugin configuration store unavailable")
|
||||
ErrUnknownPluginField = errors.New("unknown plugin configuration field")
|
||||
ErrInvalidTelegramChatID = errors.New("invalid Telegram chat ID")
|
||||
ErrPluginSettingConflict = errors.New("plugin setting version conflict")
|
||||
ErrPluginBulkPreviewDenied = errors.New("plugin bulk preview denied")
|
||||
ErrPluginBulkTicketInvalid = errors.New("plugin bulk ticket is invalid or expired")
|
||||
ErrLegacyPluginSecretConflict = errors.New("legacy plugin secret conflicts with existing secret")
|
||||
)
|
||||
|
||||
var telegramChatIDPattern = regexp.MustCompile(`^-?[1-9][0-9]{0,18}$`)
|
||||
|
||||
// SecretStatus 仅描述敏感配置是否已设置,绝不包含密文或明文。
|
||||
type SecretStatus struct {
|
||||
PluginID string `json:"pluginId"`
|
||||
FieldName string `json:"fieldName"`
|
||||
Configured bool `json:"configured"`
|
||||
Version uint64 `json:"version"`
|
||||
}
|
||||
|
||||
// TelegramUserSettings 是 Telegram 插件唯一允许由用户维护的设置。
|
||||
type TelegramUserSettings struct {
|
||||
ChatID string `json:"chatId"`
|
||||
}
|
||||
|
||||
// UserSettingsStatus 返回用户本人可见的设置与乐观锁版本。
|
||||
type UserSettingsStatus struct {
|
||||
PluginID string `json:"pluginId"`
|
||||
Settings TelegramUserSettings `json:"settings"`
|
||||
Version uint64 `json:"version"`
|
||||
}
|
||||
|
||||
// BulkPreview 是短时一次性批量执行票据的非敏感预览。
|
||||
type BulkPreview struct {
|
||||
Ticket string `json:"ticket"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
Targets []BulkPreviewTarget `json:"targets"`
|
||||
}
|
||||
|
||||
type BulkPreviewTarget struct {
|
||||
UserID int `json:"userId"`
|
||||
Version uint64 `json:"version"`
|
||||
WillWrite bool `json:"willWrite"`
|
||||
}
|
||||
|
||||
type pluginBulkTicket struct {
|
||||
ActorUserID int
|
||||
PluginID string
|
||||
Settings string
|
||||
Overwrite bool
|
||||
Targets []bulkTarget
|
||||
Digest string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type bulkTarget struct {
|
||||
UserID int
|
||||
Version uint64
|
||||
}
|
||||
|
||||
// ConfigService 是插件全局 Secret 和用户设置的唯一写服务。
|
||||
// HTTP 路由在 CG-025 完成能力接入前不得直接暴露本服务的写方法。
|
||||
type ConfigService struct {
|
||||
engine *xorm.Engine
|
||||
vault *credential.Vault
|
||||
now func() time.Time
|
||||
ticketsMu sync.Mutex
|
||||
tickets map[string]pluginBulkTicket
|
||||
}
|
||||
|
||||
func NewConfigService(engine *xorm.Engine, vault *credential.Vault) (*ConfigService, error) {
|
||||
if engine == nil || vault == nil {
|
||||
return nil, ErrPluginStoreUnavailable
|
||||
}
|
||||
return &ConfigService{
|
||||
engine: engine,
|
||||
vault: vault,
|
||||
now: func() time.Time { return time.Now().UTC() },
|
||||
tickets: make(map[string]pluginBulkTicket),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ImportLegacySecrets atomically stores compatibility-only V2 file secrets in plugin_secret.
|
||||
// Existing values may only be reused when their plaintext matches the source value.
|
||||
func (s *ConfigService) ImportLegacySecrets(ctx context.Context, values []config.LegacyPluginSecret) error {
|
||||
if s == nil || s.engine == nil || s.vault == nil || len(values) == 0 {
|
||||
return ErrPluginStoreUnavailable
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
entries := append([]config.LegacyPluginSecret(nil), values...)
|
||||
sort.Slice(entries, func(left, right int) bool {
|
||||
if entries[left].PluginID == entries[right].PluginID {
|
||||
return entries[left].FieldName < entries[right].FieldName
|
||||
}
|
||||
return entries[left].PluginID < entries[right].PluginID
|
||||
})
|
||||
seen := make(map[string]struct{}, len(entries))
|
||||
for _, entry := range entries {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateSecretField(entry.PluginID, entry.FieldName); err != nil || entry.Plaintext == "" || len(entry.Plaintext) > 4096 {
|
||||
return ErrUnknownPluginField
|
||||
}
|
||||
key := entry.PluginID + "\x00" + entry.FieldName
|
||||
if _, exists := seen[key]; exists {
|
||||
return ErrLegacyPluginSecretConflict
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
|
||||
session := s.engine.NewSession()
|
||||
defer session.Close()
|
||||
if err := session.Begin(); err != nil {
|
||||
return fmt.Errorf("begin legacy plugin secret transaction: %w", err)
|
||||
}
|
||||
rollback := func(cause error) error {
|
||||
_ = session.Rollback()
|
||||
return cause
|
||||
}
|
||||
now := s.currentTime()
|
||||
for _, entry := range entries {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
record := models.PluginSecret{}
|
||||
found, err := session.Where("plugin_id = ? AND field_name = ?", entry.PluginID, entry.FieldName).Get(&record)
|
||||
if err != nil {
|
||||
return rollback(fmt.Errorf("load legacy plugin secret: %w", err))
|
||||
}
|
||||
if found {
|
||||
plaintext, decryptErr := s.vault.Decrypt(record.KeyVersion, record.Ciphertext)
|
||||
if decryptErr != nil || plaintext != entry.Plaintext {
|
||||
return rollback(ErrLegacyPluginSecretConflict)
|
||||
}
|
||||
continue
|
||||
}
|
||||
ciphertext, encryptErr := s.vault.Encrypt(entry.Plaintext)
|
||||
if encryptErr != nil {
|
||||
return rollback(ErrPluginStoreUnavailable)
|
||||
}
|
||||
record = models.PluginSecret{
|
||||
PluginID: entry.PluginID, FieldName: entry.FieldName, Ciphertext: ciphertext, KeyVersion: s.vault.Version(),
|
||||
RecordVersion: 1, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if _, err = session.Insert(&record); err != nil {
|
||||
return rollback(ErrLegacyPluginSecretConflict)
|
||||
}
|
||||
}
|
||||
if err := session.Commit(); err != nil {
|
||||
return fmt.Errorf("commit legacy plugin secret transaction: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) GetSecretStatus(pluginID, fieldName string) (SecretStatus, error) {
|
||||
if err := validateSecretField(pluginID, fieldName); err != nil {
|
||||
return SecretStatus{}, err
|
||||
}
|
||||
record, found, err := s.findSecret(pluginID, fieldName)
|
||||
if err != nil {
|
||||
return SecretStatus{}, err
|
||||
}
|
||||
if !found {
|
||||
return SecretStatus{PluginID: pluginID, FieldName: fieldName}, nil
|
||||
}
|
||||
return SecretStatus{PluginID: pluginID, FieldName: fieldName, Configured: true, Version: record.RecordVersion}, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) ChangeSecret(pluginID, fieldName string, change config.SecretChange, expectedVersion uint64) (SecretStatus, error) {
|
||||
if err := validateSecretField(pluginID, fieldName); err != nil {
|
||||
return SecretStatus{}, err
|
||||
}
|
||||
if s == nil || s.engine == nil || s.vault == nil {
|
||||
return SecretStatus{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
current, found, err := s.findSecret(pluginID, fieldName)
|
||||
if err != nil {
|
||||
return SecretStatus{}, err
|
||||
}
|
||||
currentVersion := uint64(0)
|
||||
stored := config.StoredSecret{}
|
||||
if found {
|
||||
currentVersion = current.RecordVersion
|
||||
stored = config.StoredSecret{Ciphertext: current.Ciphertext, Version: current.KeyVersion, UpdatedAt: current.UpdatedAt}
|
||||
}
|
||||
if currentVersion != expectedVersion {
|
||||
return SecretStatus{}, ErrPluginSettingConflict
|
||||
}
|
||||
updated, err := config.ApplySecretChange(s.vault, stored, change, config.SecretPolicy{AllowClear: true, MaxLength: 4096}, s.currentTime())
|
||||
if err != nil {
|
||||
return SecretStatus{}, err
|
||||
}
|
||||
|
||||
session := s.engine.NewSession()
|
||||
defer session.Close()
|
||||
if err = session.Begin(); err != nil {
|
||||
return SecretStatus{}, fmt.Errorf("begin plugin secret transaction: %w", err)
|
||||
}
|
||||
rollback := func(cause error) (SecretStatus, error) {
|
||||
_ = session.Rollback()
|
||||
return SecretStatus{}, cause
|
||||
}
|
||||
if !updated.Configured() {
|
||||
if found {
|
||||
affected, deleteErr := session.ID(current.ID).Where("record_version = ?", expectedVersion).Delete(&models.PluginSecret{})
|
||||
if deleteErr != nil {
|
||||
return rollback(fmt.Errorf("clear plugin secret: %w", deleteErr))
|
||||
}
|
||||
if affected != 1 {
|
||||
return rollback(ErrPluginSettingConflict)
|
||||
}
|
||||
}
|
||||
if err = session.Commit(); err != nil {
|
||||
return SecretStatus{}, fmt.Errorf("commit plugin secret clear: %w", err)
|
||||
}
|
||||
return SecretStatus{PluginID: pluginID, FieldName: fieldName}, nil
|
||||
}
|
||||
|
||||
now := s.currentTime()
|
||||
if !found {
|
||||
record := models.PluginSecret{
|
||||
PluginID: pluginID, FieldName: fieldName, Ciphertext: updated.Ciphertext, KeyVersion: updated.Version,
|
||||
RecordVersion: 1, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if _, err = session.Insert(&record); err != nil {
|
||||
return rollback(ErrPluginSettingConflict)
|
||||
}
|
||||
if err = session.Commit(); err != nil {
|
||||
return SecretStatus{}, fmt.Errorf("commit plugin secret create: %w", err)
|
||||
}
|
||||
return SecretStatus{PluginID: pluginID, FieldName: fieldName, Configured: true, Version: record.RecordVersion}, nil
|
||||
}
|
||||
newVersion := currentVersion + 1
|
||||
affected, updateErr := session.ID(current.ID).Where("record_version = ?", expectedVersion).Cols("ciphertext", "key_version", "record_version", "updated_at").Update(&models.PluginSecret{
|
||||
Ciphertext: updated.Ciphertext, KeyVersion: updated.Version, RecordVersion: newVersion, UpdatedAt: now,
|
||||
})
|
||||
if updateErr != nil {
|
||||
return rollback(fmt.Errorf("update plugin secret: %w", updateErr))
|
||||
}
|
||||
if affected != 1 {
|
||||
return rollback(ErrPluginSettingConflict)
|
||||
}
|
||||
if err = session.Commit(); err != nil {
|
||||
return SecretStatus{}, fmt.Errorf("commit plugin secret update: %w", err)
|
||||
}
|
||||
return SecretStatus{PluginID: pluginID, FieldName: fieldName, Configured: true, Version: newVersion}, nil
|
||||
}
|
||||
|
||||
// openSecretForPlugin 仅供同进程的受控插件 DTO 组装逻辑使用,不能直接映射为 API 响应。
|
||||
func (s *ConfigService) openSecretForPlugin(pluginID, fieldName string) (string, error) {
|
||||
if err := validateSecretField(pluginID, fieldName); err != nil {
|
||||
return "", err
|
||||
}
|
||||
record, found, err := s.findSecret(pluginID, fieldName)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !found {
|
||||
return "", config.ErrSecretUnavailable
|
||||
}
|
||||
return config.OpenStoredSecret(s.vault, config.StoredSecret{Ciphertext: record.Ciphertext, Version: record.KeyVersion, UpdatedAt: record.UpdatedAt})
|
||||
}
|
||||
|
||||
func (s *ConfigService) GetOwnTelegramSettings(actorUserID int) (UserSettingsStatus, error) {
|
||||
if actorUserID <= 0 {
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
return s.getTelegramSettings(actorUserID)
|
||||
}
|
||||
|
||||
// UpdateOwnTelegramSettings 的 actorUserID 必须来自已验证 Session,调用方不得传入目标用户 ID。
|
||||
func (s *ConfigService) UpdateOwnTelegramSettings(actorUserID int, settings TelegramUserSettings, expectedVersion uint64) (UserSettingsStatus, error) {
|
||||
|
||||
if actorUserID <= 0 {
|
||||
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
|
||||
}
|
||||
|
||||
actor, found, err := s.findUser(actorUserID)
|
||||
|
||||
if err != nil {
|
||||
|
||||
return UserSettingsStatus{}, err
|
||||
|
||||
}
|
||||
|
||||
if !found || actor.Disabled != 0 {
|
||||
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
|
||||
}
|
||||
|
||||
if err = access.Authorize(access.Request{ActorRole: actor.EffectiveRole(), Capability: access.CapabilityPluginWriteOwn, OwnResource: true}); err != nil {
|
||||
|
||||
return UserSettingsStatus{}, err
|
||||
|
||||
}
|
||||
|
||||
return s.updateTelegramSettings(actorUserID, settings, expectedVersion)
|
||||
}
|
||||
|
||||
// UpdateTelegramSettingsForUser 查询目标账户的当前角色后才进行跨用户授权。
|
||||
func (s *ConfigService) UpdateTelegramSettingsForUser(actor models.User, targetUserID int, settings TelegramUserSettings, expectedVersion uint64) (UserSettingsStatus, error) {
|
||||
if actor.ID <= 0 || targetUserID <= 0 {
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
target, found, err := s.findUser(targetUserID)
|
||||
if err != nil {
|
||||
return UserSettingsStatus{}, err
|
||||
}
|
||||
if !found || target.Disabled != 0 {
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
}
|
||||
if err = access.Authorize(access.Request{
|
||||
ActorRole: actor.EffectiveRole(), Capability: access.CapabilityPluginWriteAnyUser, TargetRole: target.EffectiveRole(),
|
||||
}); err != nil {
|
||||
return UserSettingsStatus{}, err
|
||||
}
|
||||
return s.updateTelegramSettings(targetUserID, settings, expectedVersion)
|
||||
}
|
||||
|
||||
func (s *ConfigService) PreviewBulkTelegramSettings(actor models.User, targetUserIDs []int, settings TelegramUserSettings, overwrite bool) (BulkPreview, error) {
|
||||
if actor.ID <= 0 || actor.EffectiveRole() != access.RoleSuperAdmin {
|
||||
return BulkPreview{}, ErrPluginBulkPreviewDenied
|
||||
}
|
||||
payload, err := encodeTelegramSettings(settings)
|
||||
if err != nil {
|
||||
return BulkPreview{}, err
|
||||
}
|
||||
ids, err := normalizeTargetIDs(targetUserIDs)
|
||||
if err != nil {
|
||||
return BulkPreview{}, err
|
||||
}
|
||||
targets := make([]bulkTarget, 0, len(ids))
|
||||
previewTargets := make([]BulkPreviewTarget, 0, len(ids))
|
||||
for _, userID := range ids {
|
||||
user, found, findErr := s.findUser(userID)
|
||||
if findErr != nil {
|
||||
return BulkPreview{}, findErr
|
||||
}
|
||||
if !found || user.Disabled != 0 {
|
||||
return BulkPreview{}, ErrPluginBulkPreviewDenied
|
||||
}
|
||||
if authErr := access.Authorize(access.Request{ActorRole: actor.EffectiveRole(), Capability: access.CapabilityPluginWriteAnyUser, TargetRole: user.EffectiveRole()}); authErr != nil {
|
||||
return BulkPreview{}, authErr
|
||||
}
|
||||
current, hasCurrent, getErr := s.findUserSetting(telegramPluginID, userID)
|
||||
if getErr != nil {
|
||||
return BulkPreview{}, getErr
|
||||
}
|
||||
version := uint64(0)
|
||||
if hasCurrent {
|
||||
version = current.Version
|
||||
}
|
||||
targets = append(targets, bulkTarget{UserID: userID, Version: version})
|
||||
previewTargets = append(previewTargets, BulkPreviewTarget{UserID: userID, Version: version, WillWrite: overwrite || !hasCurrent})
|
||||
}
|
||||
now := s.currentTime()
|
||||
ticket, err := randomTicket()
|
||||
if err != nil {
|
||||
return BulkPreview{}, fmt.Errorf("generate plugin bulk ticket: %w", err)
|
||||
}
|
||||
expiresAt := now.Add(5 * time.Minute)
|
||||
entry := pluginBulkTicket{ActorUserID: actor.ID, PluginID: telegramPluginID, Settings: payload, Overwrite: overwrite, Targets: targets, ExpiresAt: expiresAt}
|
||||
entry.Digest = bulkTicketDigest(entry)
|
||||
s.ticketsMu.Lock()
|
||||
s.removeExpiredTicketsLocked(now)
|
||||
s.tickets[ticket] = entry
|
||||
s.ticketsMu.Unlock()
|
||||
return BulkPreview{Ticket: ticket, ExpiresAt: expiresAt, Targets: previewTargets}, nil
|
||||
}
|
||||
|
||||
// ExecuteBulkTelegramSettings 仅接收预览票据;目标集合、覆盖策略和版本均不能由执行请求修改。
|
||||
func (s *ConfigService) ExecuteBulkTelegramSettings(actorUserID int, ticket string) error {
|
||||
if actorUserID <= 0 || strings.TrimSpace(ticket) == "" {
|
||||
return ErrPluginBulkTicketInvalid
|
||||
}
|
||||
now := s.currentTime()
|
||||
s.ticketsMu.Lock()
|
||||
s.removeExpiredTicketsLocked(now)
|
||||
entry, found := s.tickets[ticket]
|
||||
if !found || entry.ActorUserID != actorUserID || entry.ExpiresAt.Before(now) || entry.Digest != bulkTicketDigest(entry) {
|
||||
s.ticketsMu.Unlock()
|
||||
return ErrPluginBulkTicketInvalid
|
||||
}
|
||||
delete(s.tickets, ticket)
|
||||
s.ticketsMu.Unlock()
|
||||
|
||||
actor, actorFound, err := s.findUser(actorUserID)
|
||||
|
||||
if err != nil {
|
||||
|
||||
return err
|
||||
|
||||
}
|
||||
|
||||
if !actorFound || actor.Disabled != 0 || actor.EffectiveRole() != access.RoleSuperAdmin {
|
||||
|
||||
return ErrPluginBulkPreviewDenied
|
||||
|
||||
}
|
||||
|
||||
session := s.engine.NewSession()
|
||||
defer session.Close()
|
||||
if err := session.Begin(); err != nil {
|
||||
return fmt.Errorf("begin plugin bulk transaction: %w", err)
|
||||
}
|
||||
rollback := func(cause error) error {
|
||||
_ = session.Rollback()
|
||||
return cause
|
||||
}
|
||||
for _, target := range entry.Targets {
|
||||
if !entry.Overwrite && target.Version != 0 {
|
||||
continue
|
||||
}
|
||||
if err := updateTelegramSettingsOnSession(session, s.vault, target.UserID, entry.Settings, target.Version, now); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
}
|
||||
if err := session.Commit(); err != nil {
|
||||
return fmt.Errorf("commit plugin bulk transaction: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) getTelegramSettings(userID int) (UserSettingsStatus, error) {
|
||||
|
||||
record, found, err := s.findUserSetting(telegramPluginID, userID)
|
||||
|
||||
if err != nil {
|
||||
|
||||
return UserSettingsStatus{}, err
|
||||
|
||||
}
|
||||
|
||||
if !found || !record.Enabled {
|
||||
|
||||
return UserSettingsStatus{PluginID: telegramPluginID}, nil
|
||||
|
||||
}
|
||||
|
||||
if record.SchemaVersion != userSettingsSchemaVersion {
|
||||
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
|
||||
}
|
||||
|
||||
plaintext, err := s.vault.Decrypt(credential.CurrentVersion, record.SettingsCiphertext)
|
||||
|
||||
if err != nil {
|
||||
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
|
||||
}
|
||||
|
||||
fingerprint, err := s.vault.Fingerprint(plaintext)
|
||||
|
||||
if err != nil || fingerprint != record.SettingsHash {
|
||||
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
|
||||
}
|
||||
|
||||
settings, err := decodeTelegramSettings(plaintext)
|
||||
|
||||
if err != nil {
|
||||
|
||||
return UserSettingsStatus{}, ErrPluginStoreUnavailable
|
||||
|
||||
}
|
||||
|
||||
return UserSettingsStatus{PluginID: telegramPluginID, Settings: settings, Version: record.Version}, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) updateTelegramSettings(userID int, settings TelegramUserSettings, expectedVersion uint64) (UserSettingsStatus, error) {
|
||||
|
||||
payload, err := encodeTelegramSettings(settings)
|
||||
|
||||
if err != nil {
|
||||
|
||||
return UserSettingsStatus{}, err
|
||||
|
||||
}
|
||||
|
||||
session := s.engine.NewSession()
|
||||
|
||||
defer session.Close()
|
||||
|
||||
if err = session.Begin(); err != nil {
|
||||
|
||||
return UserSettingsStatus{}, fmt.Errorf("begin user plugin setting transaction: %w", err)
|
||||
|
||||
}
|
||||
|
||||
if err = updateTelegramSettingsOnSession(session, s.vault, userID, payload, expectedVersion, s.currentTime()); err != nil {
|
||||
|
||||
_ = session.Rollback()
|
||||
|
||||
return UserSettingsStatus{}, err
|
||||
|
||||
}
|
||||
|
||||
if err = session.Commit(); err != nil {
|
||||
|
||||
return UserSettingsStatus{}, fmt.Errorf("commit user plugin setting: %w", err)
|
||||
|
||||
}
|
||||
|
||||
return s.getTelegramSettings(userID)
|
||||
}
|
||||
|
||||
func updateTelegramSettingsOnSession(session *xorm.Session, vault *credential.Vault, userID int, payload string, expectedVersion uint64, now time.Time) error {
|
||||
|
||||
if session == nil || vault == nil {
|
||||
|
||||
return ErrPluginStoreUnavailable
|
||||
|
||||
}
|
||||
|
||||
ciphertext, err := vault.Encrypt(payload)
|
||||
|
||||
if err != nil {
|
||||
|
||||
return ErrPluginStoreUnavailable
|
||||
|
||||
}
|
||||
|
||||
fingerprint, err := vault.Fingerprint(payload)
|
||||
|
||||
if err != nil {
|
||||
|
||||
return ErrPluginStoreUnavailable
|
||||
|
||||
}
|
||||
|
||||
current := models.PluginUserSetting{}
|
||||
|
||||
found, err := session.Where("plugin_id = ? AND user_id = ?", telegramPluginID, userID).Get(¤t)
|
||||
|
||||
if err != nil {
|
||||
|
||||
return fmt.Errorf("load user plugin setting: %w", err)
|
||||
|
||||
}
|
||||
|
||||
if !found {
|
||||
|
||||
if expectedVersion != 0 {
|
||||
|
||||
return ErrPluginSettingConflict
|
||||
|
||||
}
|
||||
|
||||
record := models.PluginUserSetting{PluginID: telegramPluginID, UserID: userID, SchemaVersion: userSettingsSchemaVersion, SettingsCiphertext: ciphertext, SettingsHash: fingerprint, Enabled: true, Version: 1, CreatedAt: now, UpdatedAt: now}
|
||||
|
||||
if _, err = session.Insert(&record); err != nil {
|
||||
|
||||
return ErrPluginSettingConflict
|
||||
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
if current.Version != expectedVersion {
|
||||
|
||||
return ErrPluginSettingConflict
|
||||
|
||||
}
|
||||
|
||||
affected, err := session.ID(current.ID).Where("version = ?", expectedVersion).Cols("schema_version", "settings_ciphertext", "settings_hash", "enabled", "version", "updated_at").Update(&models.PluginUserSetting{SchemaVersion: userSettingsSchemaVersion, SettingsCiphertext: ciphertext, SettingsHash: fingerprint, Enabled: true, Version: expectedVersion + 1, UpdatedAt: now})
|
||||
|
||||
if err != nil {
|
||||
|
||||
return fmt.Errorf("update user plugin setting: %w", err)
|
||||
|
||||
}
|
||||
|
||||
if affected != 1 {
|
||||
|
||||
return ErrPluginSettingConflict
|
||||
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) OpenSecretForPlugin(pluginID, fieldName string) (string, error) {
|
||||
return s.openSecretForPlugin(pluginID, fieldName)
|
||||
}
|
||||
|
||||
func (s *ConfigService) findSecret(pluginID, fieldName string) (models.PluginSecret, bool, error) {
|
||||
if s == nil || s.engine == nil {
|
||||
return models.PluginSecret{}, false, ErrPluginStoreUnavailable
|
||||
}
|
||||
record := models.PluginSecret{}
|
||||
found, err := s.engine.Where("plugin_id = ? AND field_name = ?", pluginID, fieldName).Get(&record)
|
||||
if err != nil {
|
||||
return models.PluginSecret{}, false, fmt.Errorf("load plugin secret: %w", err)
|
||||
}
|
||||
return record, found, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) findUserSetting(pluginID string, userID int) (models.PluginUserSetting, bool, error) {
|
||||
if s == nil || s.engine == nil {
|
||||
return models.PluginUserSetting{}, false, ErrPluginStoreUnavailable
|
||||
}
|
||||
record := models.PluginUserSetting{}
|
||||
found, err := s.engine.Where("plugin_id = ? AND user_id = ?", pluginID, userID).Get(&record)
|
||||
if err != nil {
|
||||
return models.PluginUserSetting{}, false, fmt.Errorf("load user plugin setting: %w", err)
|
||||
}
|
||||
return record, found, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) findUser(userID int) (models.User, bool, error) {
|
||||
user := models.User{}
|
||||
found, err := s.engine.ID(userID).Get(&user)
|
||||
if err != nil {
|
||||
return models.User{}, false, fmt.Errorf("load plugin target user: %w", err)
|
||||
}
|
||||
return user, found, nil
|
||||
}
|
||||
|
||||
func (s *ConfigService) currentTime() time.Time {
|
||||
if s != nil && s.now != nil {
|
||||
return s.now().UTC()
|
||||
}
|
||||
return time.Now().UTC()
|
||||
}
|
||||
|
||||
func validateSecretField(pluginID, fieldName string) error {
|
||||
if _, ok := Lookup(pluginID); !ok {
|
||||
return ErrUnknownPluginID
|
||||
}
|
||||
switch pluginID {
|
||||
case "wechat_push":
|
||||
if fieldName == "appSecret" {
|
||||
return nil
|
||||
}
|
||||
case telegramPluginID:
|
||||
if fieldName == "botToken" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrUnknownPluginField
|
||||
}
|
||||
|
||||
func encodeTelegramSettings(settings TelegramUserSettings) (string, error) {
|
||||
if !telegramChatIDPattern.MatchString(strings.TrimSpace(settings.ChatID)) || settings.ChatID != strings.TrimSpace(settings.ChatID) {
|
||||
return "", ErrInvalidTelegramChatID
|
||||
}
|
||||
encoded, err := json.Marshal(settings)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
func decodeTelegramSettings(raw string) (TelegramUserSettings, error) {
|
||||
decoder := json.NewDecoder(strings.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
var settings TelegramUserSettings
|
||||
if err := decoder.Decode(&settings); err != nil {
|
||||
return TelegramUserSettings{}, err
|
||||
}
|
||||
if decoder.More() {
|
||||
return TelegramUserSettings{}, ErrInvalidTelegramChatID
|
||||
}
|
||||
_, err := encodeTelegramSettings(settings)
|
||||
return settings, err
|
||||
}
|
||||
|
||||
func normalizeTargetIDs(values []int) ([]int, error) {
|
||||
if len(values) == 0 || len(values) > maxBulkTargets {
|
||||
return nil, ErrPluginBulkPreviewDenied
|
||||
}
|
||||
seen := make(map[int]struct{}, len(values))
|
||||
for _, value := range values {
|
||||
if value <= 0 {
|
||||
return nil, ErrPluginBulkPreviewDenied
|
||||
}
|
||||
if _, exists := seen[value]; exists {
|
||||
return nil, ErrPluginBulkPreviewDenied
|
||||
}
|
||||
seen[value] = struct{}{}
|
||||
}
|
||||
result := append([]int(nil), values...)
|
||||
sort.Ints(result)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func randomTicket() (string, error) {
|
||||
value := make([]byte, 32)
|
||||
if _, err := rand.Read(value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(value), nil
|
||||
}
|
||||
|
||||
func bulkTicketDigest(entry pluginBulkTicket) string {
|
||||
payload := struct {
|
||||
ActorUserID int
|
||||
PluginID string
|
||||
Settings string
|
||||
Overwrite bool
|
||||
Targets []bulkTarget
|
||||
ExpiresAt time.Time
|
||||
}{entry.ActorUserID, entry.PluginID, entry.Settings, entry.Overwrite, entry.Targets, entry.ExpiresAt}
|
||||
encoded, _ := json.Marshal(payload)
|
||||
digest := sha256.Sum256(encoded)
|
||||
return hex.EncodeToString(digest[:])
|
||||
}
|
||||
|
||||
func (s *ConfigService) removeExpiredTicketsLocked(now time.Time) {
|
||||
for ticket, entry := range s.tickets {
|
||||
if !entry.ExpiresAt.After(now) {
|
||||
delete(s.tickets, ticket)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/db/migration"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
_ "modernc.org/sqlite"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func TestConfigServiceStoresPluginSecretsAsCiphertext(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
status, err := service.ChangeSecret("telegram_push", "botToken", config.SecretChange{
|
||||
Operation: config.SecretReplace,
|
||||
Value: &config.SecretInput{Plaintext: "telegram-token-for-test"},
|
||||
}, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !status.Configured || status.Version != 1 {
|
||||
t.Fatalf("status = %+v", status)
|
||||
}
|
||||
if _, err = service.ChangeSecret("telegram_push", "unknown", config.SecretChange{}, 0); !errors.Is(err, ErrUnknownPluginField) {
|
||||
t.Fatalf("unknown field error = %v", err)
|
||||
}
|
||||
|
||||
record := models.PluginSecret{}
|
||||
found, err := engine.Where("plugin_id = ? AND field_name = ?", "telegram_push", "botToken").Get(&record)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("load secret record: found=%v err=%v", found, err)
|
||||
}
|
||||
if record.Ciphertext == "telegram-token-for-test" || record.Ciphertext == "" || record.KeyVersion == 0 {
|
||||
t.Fatalf("secret is not safely stored: %+v", record)
|
||||
}
|
||||
visible, err := service.GetSecretStatus("telegram_push", "botToken")
|
||||
if err != nil || !visible.Configured || visible.Version != record.RecordVersion {
|
||||
t.Fatalf("visible status = %+v, err=%v", visible, err)
|
||||
}
|
||||
if _, err = engine.ID(record.ID).Cols("ciphertext").Update(&models.PluginSecret{Ciphertext: "smail:v1:tampered"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = service.openSecretForPlugin("telegram_push", "botToken"); err == nil {
|
||||
t.Fatal("tampered ciphertext was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigServiceEncryptsTelegramUserSettingsAndRejectsTampering(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
user := insertPluginTestUser(t, engine, "user", access.RoleUser)
|
||||
status, err := service.UpdateOwnTelegramSettings(user.ID, TelegramUserSettings{ChatID: "-100123456"}, 0)
|
||||
if err != nil || status.Version != 1 {
|
||||
t.Fatalf("update status = %+v, err=%v", status, err)
|
||||
}
|
||||
record := models.PluginUserSetting{}
|
||||
found, err := engine.Where("plugin_id = ? AND user_id = ?", telegramPluginID, user.ID).Get(&record)
|
||||
if err != nil || !found {
|
||||
t.Fatalf("load user setting: found=%v err=%v", found, err)
|
||||
}
|
||||
if record.SettingsCiphertext == `{"chatId":"-100123456"}` || record.SettingsCiphertext == "" || record.SettingsHash == "" || !record.Enabled || record.SchemaVersion != userSettingsSchemaVersion {
|
||||
t.Fatalf("user setting is not safely stored: %+v", record)
|
||||
}
|
||||
if _, err = engine.ID(record.ID).Cols("settings_hash").Update(&models.PluginUserSetting{SettingsHash: "tampered"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = service.GetOwnTelegramSettings(user.ID); !errors.Is(err, ErrPluginStoreUnavailable) {
|
||||
t.Fatalf("tampered user setting error = %v", err)
|
||||
}
|
||||
}
|
||||
func TestConfigServiceEnforcesUserSettingRolesAndVersions(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
super := insertPluginTestUser(t, engine, "root", access.RoleSuperAdmin)
|
||||
admin := insertPluginTestUser(t, engine, "admin", access.RoleAdmin)
|
||||
secondAdmin := insertPluginTestUser(t, engine, "admin2", access.RoleAdmin)
|
||||
user := insertPluginTestUser(t, engine, "user", access.RoleUser)
|
||||
|
||||
own, err := service.UpdateOwnTelegramSettings(user.ID, TelegramUserSettings{ChatID: "123456"}, 0)
|
||||
if err != nil || own.Version != 1 {
|
||||
t.Fatalf("own update = %+v, err=%v", own, err)
|
||||
}
|
||||
updated, err := service.UpdateTelegramSettingsForUser(admin, user.ID, TelegramUserSettings{ChatID: "-100123456"}, own.Version)
|
||||
if err != nil || updated.Version != 2 {
|
||||
t.Fatalf("admin update = %+v, err=%v", updated, err)
|
||||
}
|
||||
if _, err = service.UpdateTelegramSettingsForUser(admin, secondAdmin.ID, TelegramUserSettings{ChatID: "1"}, 0); !access.IsDenied(err, access.CodeTargetRoleDenied) {
|
||||
t.Fatalf("admin writes admin error = %v", err)
|
||||
}
|
||||
if _, err = service.UpdateTelegramSettingsForUser(user, admin.ID, TelegramUserSettings{ChatID: "1"}, 0); !access.IsDenied(err, access.CodeAccessDenied) {
|
||||
t.Fatalf("user cross-account error = %v", err)
|
||||
}
|
||||
if _, err = service.UpdateTelegramSettingsForUser(super, secondAdmin.ID, TelegramUserSettings{ChatID: "2"}, 0); err != nil {
|
||||
t.Fatalf("super update admin: %v", err)
|
||||
}
|
||||
if _, err = service.UpdateOwnTelegramSettings(user.ID, TelegramUserSettings{ChatID: "777"}, own.Version); !errors.Is(err, ErrPluginSettingConflict) {
|
||||
t.Fatalf("stale version error = %v", err)
|
||||
}
|
||||
if _, err = service.UpdateOwnTelegramSettings(user.ID, TelegramUserSettings{ChatID: "001"}, updated.Version); !errors.Is(err, ErrInvalidTelegramChatID) {
|
||||
t.Fatalf("invalid chat ID error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigServiceBulkTicketIsBoundOneTimeAndVersioned(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
super := insertPluginTestUser(t, engine, "root", access.RoleSuperAdmin)
|
||||
first := insertPluginTestUser(t, engine, "first", access.RoleUser)
|
||||
second := insertPluginTestUser(t, engine, "second", access.RoleUser)
|
||||
|
||||
preview, err := service.PreviewBulkTelegramSettings(super, []int{second.ID, first.ID}, TelegramUserSettings{ChatID: "123"}, false)
|
||||
if err != nil || len(preview.Targets) != 2 || preview.Targets[0].UserID != first.ID {
|
||||
t.Fatalf("preview = %+v, err=%v", preview, err)
|
||||
}
|
||||
if err = service.ExecuteBulkTelegramSettings(super.ID, preview.Ticket); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = service.ExecuteBulkTelegramSettings(super.ID, preview.Ticket); !errors.Is(err, ErrPluginBulkTicketInvalid) {
|
||||
t.Fatalf("ticket replay error = %v", err)
|
||||
}
|
||||
firstStatus, err := service.GetOwnTelegramSettings(first.ID)
|
||||
if err != nil || firstStatus.Version != 1 || firstStatus.Settings.ChatID != "123" {
|
||||
t.Fatalf("first setting = %+v, err=%v", firstStatus, err)
|
||||
}
|
||||
|
||||
conflicting, err := service.PreviewBulkTelegramSettings(super, []int{first.ID}, TelegramUserSettings{ChatID: "456"}, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = service.UpdateOwnTelegramSettings(first.ID, TelegramUserSettings{ChatID: "789"}, firstStatus.Version); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = service.ExecuteBulkTelegramSettings(super.ID, conflicting.Ticket); !errors.Is(err, ErrPluginSettingConflict) {
|
||||
t.Fatalf("bulk version conflict error = %v", err)
|
||||
}
|
||||
if err = service.ExecuteBulkTelegramSettings(first.ID, conflicting.Ticket); !errors.Is(err, ErrPluginBulkTicketInvalid) {
|
||||
t.Fatalf("actor-bound ticket error = %v", err)
|
||||
}
|
||||
|
||||
base := time.Date(2026, time.August, 28, 8, 0, 0, 0, time.UTC)
|
||||
service.now = func() time.Time { return base }
|
||||
expiring, err := service.PreviewBulkTelegramSettings(super, []int{second.ID}, TelegramUserSettings{ChatID: "999"}, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.now = func() time.Time { return base.Add(6 * time.Minute) }
|
||||
if err = service.ExecuteBulkTelegramSettings(super.ID, expiring.Ticket); !errors.Is(err, ErrPluginBulkTicketInvalid) {
|
||||
t.Fatalf("expired ticket error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newPluginConfigService(t *testing.T) (*ConfigService, *xorm.Engine) {
|
||||
t.Helper()
|
||||
engine, err := xorm.NewEngine("sqlite", filepath.Join(t.TempDir(), "plugin-config.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = engine.Close() })
|
||||
runner := migration.Runner{DB: engine.DB().DB, Dialect: migration.DialectSQLite, Migrations: migration.DefaultMigrations()}
|
||||
if _, err = runner.Run(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vault, err := credential.NewVault(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service, err := NewConfigService(engine, vault)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return service, engine
|
||||
}
|
||||
|
||||
func insertPluginTestUser(t *testing.T, engine *xorm.Engine, account string, role access.Role) models.User {
|
||||
t.Helper()
|
||||
user := models.User{Account: account, Name: account, Password: "hash"}
|
||||
user.ApplyRole(role)
|
||||
if _, err := engine.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
+511
-3
@@ -1,7 +1,18 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
stdcontext "context"
|
||||
"database/sql"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
@@ -11,8 +22,49 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
"git.pcux.cn/xuans/Smail/utils/errors"
|
||||
"git.pcux.cn/xuans/Smail/utils/validation"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
type DatabaseSettings struct {
|
||||
Type string
|
||||
DSN string
|
||||
Mode string
|
||||
User string
|
||||
Host string
|
||||
Port string
|
||||
Password string
|
||||
Name string
|
||||
}
|
||||
|
||||
type databaseSetupError struct {
|
||||
Message string
|
||||
Cause error
|
||||
}
|
||||
|
||||
func (e *databaseSetupError) Error() string {
|
||||
if e.Cause == nil {
|
||||
return e.Message
|
||||
}
|
||||
return fmt.Sprintf("%s: %v", e.Message, e.Cause)
|
||||
}
|
||||
|
||||
func (e *databaseSetupError) Unwrap() error {
|
||||
return e.Cause
|
||||
}
|
||||
|
||||
func databaseError(message string, cause error) error {
|
||||
return &databaseSetupError{Message: message, Cause: cause}
|
||||
}
|
||||
|
||||
func DatabaseSetupErrorMessage(err error) string {
|
||||
var setupErr *databaseSetupError
|
||||
if errors.As(err, &setupErr) {
|
||||
return setupErr.Message
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetDatabaseSettings(ctx *context.Context) (string, string, error) {
|
||||
configData, err := config.ReadConfig()
|
||||
if err != nil {
|
||||
@@ -24,7 +76,67 @@ func GetDatabaseSettings(ctx *context.Context) (string, string, error) {
|
||||
return configData.DbType, configData.DbDSN, nil
|
||||
}
|
||||
|
||||
func GetDatabaseSettingsDetail(ctx *context.Context) (map[string]string, error) {
|
||||
dbType, dbDSN, err := GetDatabaseSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := map[string]string{
|
||||
"db_type": dbType,
|
||||
"db_dsn": dbDSN,
|
||||
"db_mode": "dsn",
|
||||
}
|
||||
if dbType == config.DBTypeSQLite {
|
||||
if strings.TrimSpace(result["db_dsn"]) == "" {
|
||||
result["db_dsn"] = config.ROOT_PATH + "./config/smail.db"
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
if dbType == config.DBTypePostgres {
|
||||
parsed, ok := parsePostgresURL(dbDSN)
|
||||
if !ok {
|
||||
return result, nil
|
||||
}
|
||||
host, port := splitDatabaseAddress(parsed.Host)
|
||||
result["db_mode"] = "fields"
|
||||
result["db_dsn"] = ""
|
||||
result["db_user"] = parsed.User.Username()
|
||||
result["db_host"] = host
|
||||
result["db_port"] = port
|
||||
result["db_name"] = strings.TrimPrefix(parsed.Path, "/")
|
||||
return result, nil
|
||||
}
|
||||
if dbType != config.DBTypeMySQL {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
parsed, err := mysql.ParseDSN(dbDSN)
|
||||
if err != nil {
|
||||
return map[string]string{
|
||||
"db_type": dbType,
|
||||
"db_dsn": "",
|
||||
"db_mode": "fields",
|
||||
"db_host": "127.0.0.1",
|
||||
"db_port": "3306",
|
||||
"db_name": "smail",
|
||||
}, nil
|
||||
}
|
||||
host, port := splitMySQLAddress(parsed.Addr)
|
||||
result["db_mode"] = "fields"
|
||||
// MySQL 密码不能通过初始化接口返回,页面重新提交时由后端尝试复用原密码。
|
||||
result["db_dsn"] = ""
|
||||
result["db_user"] = parsed.User
|
||||
result["db_host"] = host
|
||||
result["db_port"] = port
|
||||
result["db_name"] = parsed.DBName
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func GetAdminPassword(ctx *context.Context) (string, error) {
|
||||
if db.Instance == nil {
|
||||
return "", databaseError("\u6570\u636e\u5e93\u5c1a\u672a\u521d\u59cb\u5316\uff0c\u8bf7\u5148\u5b8c\u6210\u6570\u636e\u5e93\u8bbe\u7f6e", nil)
|
||||
}
|
||||
users := []*models.User{}
|
||||
if err := db.Instance.Find(&users); err != nil {
|
||||
return "", errors.Wrap(err)
|
||||
@@ -40,6 +152,13 @@ var adminSetupMutex sync.Mutex
|
||||
func SetAdminPassword(ctx *context.Context, account, pwd string) error {
|
||||
adminSetupMutex.Lock()
|
||||
defer adminSetupMutex.Unlock()
|
||||
if db.Instance == nil {
|
||||
return databaseError("\u6570\u636e\u5e93\u5c1a\u672a\u521d\u59cb\u5316\uff0c\u8bf7\u5148\u5b8c\u6210\u6570\u636e\u5e93\u8bbe\u7f6e", nil)
|
||||
}
|
||||
|
||||
if err := validateAdminPassword(pwd); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
account, err := validation.NormalizeAccount(account)
|
||||
if err != nil {
|
||||
@@ -62,27 +181,416 @@ func SetAdminPassword(ctx *context.Context, account, pwd string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAdminPassword(pwd string) error {
|
||||
passwordSize := len([]byte(pwd))
|
||||
if passwordSize < 8 || passwordSize > 12 {
|
||||
return databaseError("管理员密码长度必须为 8 到 12 个字节", nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func SetDatabaseSettings(ctx *context.Context, dbType, dbDSN string) error {
|
||||
return SetDatabaseSettingsWithOptions(ctx, DatabaseSettings{
|
||||
Type: dbType,
|
||||
DSN: dbDSN,
|
||||
})
|
||||
}
|
||||
|
||||
var databaseSetupMutex sync.Mutex
|
||||
|
||||
func SetDatabaseSettingsWithOptions(ctx *context.Context, settings DatabaseSettings) error {
|
||||
databaseSetupMutex.Lock()
|
||||
defer databaseSetupMutex.Unlock()
|
||||
|
||||
configData, err := config.ReadConfig()
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
dbType := strings.TrimSpace(settings.Type)
|
||||
if !array.InArray(dbType, config.DBTypes) {
|
||||
return errors.New("dbtype error")
|
||||
}
|
||||
|
||||
dbDSN := strings.TrimSpace(settings.DSN)
|
||||
if settings.Mode == "fields" {
|
||||
switch dbType {
|
||||
case config.DBTypeMySQL:
|
||||
dbDSN, err = buildMySQLDSN(settings, configData.DbDSN)
|
||||
case config.DBTypePostgres:
|
||||
dbDSN, err = buildPostgresDSN(settings, configData.DbDSN)
|
||||
}
|
||||
if err != nil {
|
||||
return databaseError(strings.SplitN(err.Error(), " at ", 2)[0], err)
|
||||
}
|
||||
}
|
||||
if dbType == config.DBTypeSQLite {
|
||||
if dbDSN == "" {
|
||||
dbDSN = config.ROOT_PATH + "./config/smail.db"
|
||||
}
|
||||
if err = prepareSQLiteDatabase(dbDSN); err != nil {
|
||||
return databaseError("准备 SQLite 数据文件失败", err)
|
||||
}
|
||||
}
|
||||
if dbDSN == "" {
|
||||
return errors.New("DSN error")
|
||||
}
|
||||
configData.DbType = dbType
|
||||
configData.DbDSN = dbDSN
|
||||
if err = config.WriteConfig(configData); err != nil {
|
||||
switch dbType {
|
||||
case config.DBTypeMySQL:
|
||||
if err = ensureMySQLDatabase(dbDSN); err != nil {
|
||||
return err
|
||||
}
|
||||
case config.DBTypePostgres:
|
||||
if err = ensurePostgresDatabase(dbDSN); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
previousConfig := *configData
|
||||
candidateConfig := *configData
|
||||
candidateConfig.DbType = dbType
|
||||
candidateConfig.DbDSN = dbDSN
|
||||
if err = config.WriteConfig(&candidateConfig); err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
if err = config.Init(); err != nil {
|
||||
restoreDatabaseConfig(&previousConfig)
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
closeDatabaseInstance()
|
||||
if err = db.Init(""); err != nil {
|
||||
restoreDatabaseConfig(&previousConfig)
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func closeDatabaseInstance() {
|
||||
if db.Instance == nil {
|
||||
return
|
||||
}
|
||||
_ = db.Instance.Close()
|
||||
db.Instance = nil
|
||||
}
|
||||
|
||||
func buildPostgresDSN(settings DatabaseSettings, previousDSN string) (string, error) {
|
||||
user := strings.TrimSpace(settings.User)
|
||||
if user == "" {
|
||||
return "", errors.New("PostgreSQL 用户不能为空")
|
||||
}
|
||||
host := strings.TrimSpace(settings.Host)
|
||||
if host == "" {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
host = normalizeDatabaseHost(host)
|
||||
portText := strings.TrimSpace(settings.Port)
|
||||
if portText == "" {
|
||||
portText = "5432"
|
||||
}
|
||||
port, err := strconv.Atoi(portText)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return "", errors.New("PostgreSQL 端口必须是 1 到 65535 之间的数字")
|
||||
}
|
||||
databaseName := strings.TrimSpace(settings.Name)
|
||||
if databaseName == "" {
|
||||
databaseName = "smail"
|
||||
}
|
||||
if !validPostgresIdentifier(databaseName) {
|
||||
return "", errors.New("数据库名只能包含字母、数字和下划线")
|
||||
}
|
||||
|
||||
password := settings.Password
|
||||
previous, previousOK := parsePostgresURL(previousDSN)
|
||||
if password == "" && previousOK && postgresSettingsMatch(previous, user, host, strconv.Itoa(port), databaseName) {
|
||||
if previousPassword, ok := previous.User.Password(); ok {
|
||||
password = previousPassword
|
||||
}
|
||||
}
|
||||
query := url.Values{}
|
||||
if previousOK && previous.RawQuery != "" {
|
||||
query = previous.Query()
|
||||
}
|
||||
if query.Get("sslmode") == "" {
|
||||
query.Set("sslmode", "disable")
|
||||
}
|
||||
parsed := &url.URL{
|
||||
Scheme: "postgres",
|
||||
User: url.UserPassword(user, password),
|
||||
Host: net.JoinHostPort(host, strconv.Itoa(port)),
|
||||
Path: "/" + databaseName,
|
||||
RawQuery: query.Encode(),
|
||||
}
|
||||
return parsed.String(), nil
|
||||
}
|
||||
|
||||
func parsePostgresURL(dsn string) (*url.URL, bool) {
|
||||
parsed, err := url.Parse(strings.TrimSpace(dsn))
|
||||
if err != nil || (parsed.Scheme != "postgres" && parsed.Scheme != "postgresql") || parsed.Host == "" || parsed.User == nil {
|
||||
return nil, false
|
||||
}
|
||||
name := strings.TrimPrefix(parsed.Path, "/")
|
||||
return parsed, name != ""
|
||||
}
|
||||
|
||||
func postgresSettingsMatch(parsed *url.URL, user, host, port, name string) bool {
|
||||
parsedHost, parsedPort := splitDatabaseAddress(parsed.Host)
|
||||
return parsed.User.Username() == user && parsedHost == host && parsedPort == port && strings.TrimPrefix(parsed.Path, "/") == name
|
||||
}
|
||||
|
||||
func splitDatabaseAddress(address string) (string, string) {
|
||||
address = strings.TrimSpace(address)
|
||||
if host, port, err := net.SplitHostPort(address); err == nil {
|
||||
return strings.Trim(host, "[]"), port
|
||||
}
|
||||
if address == "" {
|
||||
return "127.0.0.1", "5432"
|
||||
}
|
||||
return strings.Trim(address, "[]"), "5432"
|
||||
}
|
||||
|
||||
func normalizeDatabaseHost(host string) string {
|
||||
if len(host) >= 2 && strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
|
||||
return host[1 : len(host)-1]
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func validPostgresIdentifier(value string) bool {
|
||||
if len(value) == 0 || len(value) > 63 {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if (char < 'a' || char > 'z') && (char < 'A' || char > 'Z') && (char < '0' || char > '9') && char != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func prepareSQLiteDatabase(dsn string) error {
|
||||
dsn = strings.TrimSpace(dsn)
|
||||
if dsn == ":memory:" || strings.HasPrefix(dsn, "file::memory:") {
|
||||
return nil
|
||||
}
|
||||
path := dsn
|
||||
if strings.HasPrefix(path, "file:") {
|
||||
path = strings.TrimPrefix(path, "file:")
|
||||
path = strings.SplitN(path, "?", 2)[0]
|
||||
}
|
||||
if path == "" || path == ":memory:" {
|
||||
return nil
|
||||
}
|
||||
directory := filepath.Dir(path)
|
||||
if directory == "." || directory == "" {
|
||||
return nil
|
||||
}
|
||||
return os.MkdirAll(directory, 0750)
|
||||
}
|
||||
|
||||
func buildMySQLDSN(settings DatabaseSettings, previousDSN string) (string, error) {
|
||||
user := strings.TrimSpace(settings.User)
|
||||
if user == "" {
|
||||
return "", errors.New("MySQL 用户不能为空")
|
||||
}
|
||||
host := strings.TrimSpace(settings.Host)
|
||||
if host == "" {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
host = normalizeMySQLHost(host)
|
||||
portText := strings.TrimSpace(settings.Port)
|
||||
if portText == "" {
|
||||
portText = "3306"
|
||||
}
|
||||
port, err := strconv.Atoi(portText)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return "", errors.New("MySQL 端口必须是 1 到 65535 之间的数字")
|
||||
}
|
||||
databaseName := strings.TrimSpace(settings.Name)
|
||||
if databaseName == "" {
|
||||
databaseName = "smail"
|
||||
}
|
||||
if !validMySQLIdentifier(databaseName) {
|
||||
return "", errors.New("数据库名只能包含字母、数字和下划线")
|
||||
}
|
||||
|
||||
password := settings.Password
|
||||
if password == "" {
|
||||
password = previousMySQLPassword(previousDSN, user, host, strconv.Itoa(port), databaseName)
|
||||
}
|
||||
dsnConfig := mysql.NewConfig()
|
||||
dsnConfig.User = user
|
||||
dsnConfig.Passwd = password
|
||||
dsnConfig.Net = "tcp"
|
||||
dsnConfig.Addr = net.JoinHostPort(host, strconv.Itoa(port))
|
||||
dsnConfig.DBName = databaseName
|
||||
dsnConfig.ParseTime = true
|
||||
dsnConfig.Loc = time.Local
|
||||
dsnConfig.Params = map[string]string{"charset": "utf8mb4"}
|
||||
return dsnConfig.FormatDSN(), nil
|
||||
}
|
||||
|
||||
func previousMySQLPassword(previousDSN, user, host, port, databaseName string) string {
|
||||
previous, err := mysql.ParseDSN(previousDSN)
|
||||
if err != nil || previous.User != user || previous.DBName != databaseName {
|
||||
return ""
|
||||
}
|
||||
previousHost, previousPort := splitMySQLAddress(previous.Addr)
|
||||
if previousHost != host || previousPort != port {
|
||||
return ""
|
||||
}
|
||||
return previous.Passwd
|
||||
}
|
||||
|
||||
func splitMySQLAddress(address string) (string, string) {
|
||||
address = strings.TrimSpace(address)
|
||||
if host, port, err := net.SplitHostPort(address); err == nil {
|
||||
return strings.Trim(host, "[]"), port
|
||||
}
|
||||
if address == "" {
|
||||
return "127.0.0.1", "3306"
|
||||
}
|
||||
return strings.Trim(address, "[]"), "3306"
|
||||
}
|
||||
|
||||
func normalizeMySQLHost(host string) string {
|
||||
host = strings.TrimSpace(host)
|
||||
if len(host) >= 2 && strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
|
||||
return host[1 : len(host)-1]
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func validMySQLIdentifier(value string) bool {
|
||||
if len(value) == 0 || len(value) > 64 {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if (char < 'a' || char > 'z') && (char < 'A' || char > 'Z') && (char < '0' || char > '9') && char != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var openMySQLSetupDatabase = func(dsn string) (setupDatabase, error) {
|
||||
return sql.Open("mysql", dsn)
|
||||
}
|
||||
|
||||
var openPostgresSetupDatabase = func(dsn string) (setupDatabase, error) {
|
||||
return sql.Open("postgres", dsn)
|
||||
}
|
||||
|
||||
func ensurePostgresDatabase(dsn string) error {
|
||||
parsed, ok := parsePostgresURL(dsn)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
databaseName := strings.TrimPrefix(parsed.Path, "/")
|
||||
if !validPostgresIdentifier(databaseName) {
|
||||
return databaseError("PostgreSQL 数据库名无效", nil)
|
||||
}
|
||||
|
||||
requestContext, cancel := stdcontext.WithTimeout(stdcontext.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
target, err := openPostgresSetupDatabase(dsn)
|
||||
if err != nil {
|
||||
return databaseError("连接 PostgreSQL 数据库失败", err)
|
||||
}
|
||||
defer func() { _ = target.Close() }()
|
||||
if err = target.PingContext(requestContext); err == nil {
|
||||
return nil
|
||||
} else {
|
||||
var postgresErr *pq.Error
|
||||
if !stderrors.As(err, &postgresErr) || string(postgresErr.Code) != "3D000" {
|
||||
return databaseError("连接 PostgreSQL 数据库失败,请检查用户、密码、主机、端口和数据库名", err)
|
||||
}
|
||||
}
|
||||
|
||||
adminURL := *parsed
|
||||
adminURL.Path = "/postgres"
|
||||
adminURL.RawPath = ""
|
||||
admin, err := openPostgresSetupDatabase(adminURL.String())
|
||||
if err != nil {
|
||||
return databaseError("连接 PostgreSQL 服务器失败", err)
|
||||
}
|
||||
defer func() { _ = admin.Close() }()
|
||||
if err = admin.PingContext(requestContext); err != nil {
|
||||
return databaseError("连接 PostgreSQL 服务器失败,请检查用户、密码、主机和端口", err)
|
||||
}
|
||||
query := `CREATE DATABASE "` + databaseName + `"`
|
||||
if _, err = admin.ExecContext(requestContext, query); err != nil {
|
||||
var postgresErr *pq.Error
|
||||
if !stderrors.As(err, &postgresErr) || string(postgresErr.Code) != "42P04" {
|
||||
return databaseError("自动创建 PostgreSQL 数据库失败,请确认当前用户具有建库权限", err)
|
||||
}
|
||||
}
|
||||
if err = target.PingContext(requestContext); err != nil {
|
||||
return databaseError("PostgreSQL 数据库创建后仍无法连接", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type setupDatabase interface {
|
||||
PingContext(stdcontext.Context) error
|
||||
ExecContext(stdcontext.Context, string, ...any) (sql.Result, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
func ensureMySQLDatabase(dsn string) error {
|
||||
parsed, err := mysql.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
return databaseError("MySQL 连接信息格式错误", err)
|
||||
}
|
||||
if parsed.DBName == "" || !validMySQLIdentifier(parsed.DBName) {
|
||||
return databaseError("MySQL 数据库名无效", nil)
|
||||
}
|
||||
|
||||
requestContext, cancel := stdcontext.WithTimeout(stdcontext.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
target, err := openMySQLSetupDatabase(dsn)
|
||||
if err != nil {
|
||||
return databaseError("连接 MySQL 数据库失败", err)
|
||||
}
|
||||
defer func() { _ = target.Close() }()
|
||||
if err = target.PingContext(requestContext); err == nil {
|
||||
return nil
|
||||
} else {
|
||||
var mysqlErr *mysql.MySQLError
|
||||
if !errors.As(err, &mysqlErr) || mysqlErr.Number != 1049 {
|
||||
return databaseError("连接 MySQL 数据库失败,请检查用户、密码、主机、端口和数据库名", err)
|
||||
}
|
||||
}
|
||||
|
||||
adminConfig := parsed.Clone()
|
||||
adminConfig.DBName = ""
|
||||
admin, err := openMySQLSetupDatabase(adminConfig.FormatDSN())
|
||||
if err != nil {
|
||||
return databaseError("连接 MySQL 服务器失败", err)
|
||||
}
|
||||
defer func() { _ = admin.Close() }()
|
||||
if err = admin.PingContext(requestContext); err != nil {
|
||||
return databaseError("连接 MySQL 服务器失败,请检查用户、密码、主机和端口", err)
|
||||
}
|
||||
query := "CREATE DATABASE IF NOT EXISTS `" + parsed.DBName + "` DEFAULT CHARACTER SET utf8mb4"
|
||||
if _, err = admin.ExecContext(requestContext, query); err != nil {
|
||||
return databaseError("自动创建 MySQL 数据库失败,请确认当前用户具有建库权限", err)
|
||||
}
|
||||
if err = target.PingContext(requestContext); err != nil {
|
||||
return databaseError("MySQL 数据库创建后仍无法连接", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func restoreDatabaseConfig(previous *config.Config) {
|
||||
if previous == nil {
|
||||
return
|
||||
}
|
||||
closeDatabaseInstance()
|
||||
if err := config.WriteConfig(previous); err != nil {
|
||||
return
|
||||
}
|
||||
_ = config.Init()
|
||||
if previous.DbType != "" && previous.DbDSN != "" {
|
||||
_ = db.Init("")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
stderrors "errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
type fakeSetupDB struct {
|
||||
pingErrors []error
|
||||
pingCalls int
|
||||
execQueries []string
|
||||
execError error
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (database *fakeSetupDB) PingContext(context.Context) error {
|
||||
index := database.pingCalls
|
||||
database.pingCalls++
|
||||
if index < len(database.pingErrors) {
|
||||
return database.pingErrors[index]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (database *fakeSetupDB) ExecContext(_ context.Context, query string, _ ...any) (sql.Result, error) {
|
||||
database.execQueries = append(database.execQueries, query)
|
||||
return fakeSetupResult(0), database.execError
|
||||
}
|
||||
|
||||
func (database *fakeSetupDB) Close() error {
|
||||
database.closed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeSetupResult int64
|
||||
|
||||
func (result fakeSetupResult) LastInsertId() (int64, error) {
|
||||
return int64(result), nil
|
||||
}
|
||||
|
||||
func (result fakeSetupResult) RowsAffected() (int64, error) {
|
||||
return int64(result), nil
|
||||
}
|
||||
|
||||
func TestBuildMySQLDSNUsesStructuredFields(t *testing.T) {
|
||||
dsn, err := buildMySQLDSN(DatabaseSettings{
|
||||
User: "root",
|
||||
Host: "[2001:db8::1]",
|
||||
Port: "03306",
|
||||
Password: "p@ss:/?#[]",
|
||||
Name: "smail_1",
|
||||
}, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
parsed, err := mysql.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsed.User != "root" || parsed.Passwd != "p@ss:/?#[]" {
|
||||
t.Fatalf("unexpected credentials in DSN: user=%q password=%q", parsed.User, parsed.Passwd)
|
||||
}
|
||||
if parsed.Addr != "[2001:db8::1]:3306" {
|
||||
t.Fatalf("unexpected address: %q", parsed.Addr)
|
||||
}
|
||||
if parsed.DBName != "smail_1" || !parsed.ParseTime {
|
||||
t.Fatalf("unexpected database options: name=%q parseTime=%v", parsed.DBName, parsed.ParseTime)
|
||||
}
|
||||
if !strings.Contains(dsn, "charset=utf8mb4") {
|
||||
t.Fatalf("charset option is missing from DSN: %q", dsn)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPostgresDSNUsesStructuredFields(t *testing.T) {
|
||||
dsn, err := buildPostgresDSN(DatabaseSettings{
|
||||
User: "smail",
|
||||
Host: "[2001:db8::2]",
|
||||
Port: "05432",
|
||||
Password: "p@ss:/?#[]",
|
||||
Name: "smail_1",
|
||||
}, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsed, ok := parsePostgresURL(dsn)
|
||||
if !ok {
|
||||
t.Fatalf("invalid PostgreSQL DSN: %q", dsn)
|
||||
}
|
||||
password, hasPassword := parsed.User.Password()
|
||||
host, port := splitDatabaseAddress(parsed.Host)
|
||||
if parsed.User.Username() != "smail" || !hasPassword || password != "p@ss:/?#[]" {
|
||||
t.Fatalf("unexpected credentials in DSN: %q", dsn)
|
||||
}
|
||||
if host != "2001:db8::2" || port != "5432" || strings.TrimPrefix(parsed.Path, "/") != "smail_1" {
|
||||
t.Fatalf("unexpected connection settings: host=%q port=%q name=%q", host, port, parsed.Path)
|
||||
}
|
||||
if parsed.Query().Get("sslmode") != "disable" {
|
||||
t.Fatalf("unexpected sslmode: %q", parsed.Query().Get("sslmode"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPostgresDSNReusesMatchingPassword(t *testing.T) {
|
||||
dsn, err := buildPostgresDSN(DatabaseSettings{
|
||||
User: "smail",
|
||||
Host: "127.0.0.1",
|
||||
Port: "5432",
|
||||
Name: "smail",
|
||||
}, "postgres://smail:stored-secret@127.0.0.1:5432/smail?sslmode=require")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsed, ok := parsePostgresURL(dsn)
|
||||
if !ok {
|
||||
t.Fatalf("invalid PostgreSQL DSN: %q", dsn)
|
||||
}
|
||||
password, _ := parsed.User.Password()
|
||||
if password != "stored-secret" || parsed.Query().Get("sslmode") != "require" {
|
||||
t.Fatalf("stored PostgreSQL settings were not reused: %q", dsn)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsurePostgresDatabaseCreatesMissingDatabase(t *testing.T) {
|
||||
target := &fakeSetupDB{pingErrors: []error{&pq.Error{Code: "3D000"}, nil}}
|
||||
admin := &fakeSetupDB{}
|
||||
openCalls := 0
|
||||
withPostgresSetupOpener(t, func(dsn string) (setupDatabase, error) {
|
||||
openCalls++
|
||||
parsed, ok := parsePostgresURL(dsn)
|
||||
if !ok {
|
||||
return nil, stderrors.New("invalid PostgreSQL test DSN")
|
||||
}
|
||||
if strings.TrimPrefix(parsed.Path, "/") == "postgres" {
|
||||
return admin, nil
|
||||
}
|
||||
return target, nil
|
||||
})
|
||||
|
||||
if err := ensurePostgresDatabase("postgres://smail:secret@127.0.0.1:5432/smail?sslmode=disable"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if openCalls != 2 || target.pingCalls != 2 || admin.pingCalls != 1 {
|
||||
t.Fatalf("unexpected connection flow: opens=%d targetPings=%d adminPings=%d", openCalls, target.pingCalls, admin.pingCalls)
|
||||
}
|
||||
if len(admin.execQueries) != 1 || admin.execQueries[0] != `CREATE DATABASE "smail"` {
|
||||
t.Fatalf("unexpected creation query: %#v", admin.execQueries)
|
||||
}
|
||||
}
|
||||
|
||||
func withPostgresSetupOpener(t *testing.T, opener func(string) (setupDatabase, error)) {
|
||||
t.Helper()
|
||||
original := openPostgresSetupDatabase
|
||||
openPostgresSetupDatabase = opener
|
||||
t.Cleanup(func() {
|
||||
openPostgresSetupDatabase = original
|
||||
})
|
||||
}
|
||||
|
||||
func TestBuildMySQLDSNAppliesDefaults(t *testing.T) {
|
||||
dsn, err := buildMySQLDSN(DatabaseSettings{User: "root"}, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
parsed, err := mysql.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsed.Addr != "127.0.0.1:3306" || parsed.DBName != "smail" {
|
||||
t.Fatalf("unexpected defaults: address=%q database=%q", parsed.Addr, parsed.DBName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMySQLDSNReusesMatchingPassword(t *testing.T) {
|
||||
previous := mysql.NewConfig()
|
||||
previous.User = "root"
|
||||
previous.Passwd = "stored-secret"
|
||||
previous.Net = "tcp"
|
||||
previous.Addr = "[::1]:3306"
|
||||
previous.DBName = "smail"
|
||||
|
||||
dsn, err := buildMySQLDSN(DatabaseSettings{
|
||||
User: "root",
|
||||
Host: "::1",
|
||||
Port: "03306",
|
||||
Name: "smail",
|
||||
}, previous.FormatDSN())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsed, err := mysql.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if parsed.Passwd != "stored-secret" {
|
||||
t.Fatal("matching stored password was not reused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildMySQLDSNRejectsInvalidInput(t *testing.T) {
|
||||
tests := []DatabaseSettings{
|
||||
{User: "root", Port: "0", Name: "smail"},
|
||||
{User: "root", Port: "65536", Name: "smail"},
|
||||
{User: "root", Port: "3306", Name: "smail-test"},
|
||||
{Port: "3306", Name: "smail"},
|
||||
}
|
||||
for _, settings := range tests {
|
||||
if _, err := buildMySQLDSN(settings, ""); err == nil {
|
||||
t.Fatalf("invalid settings were accepted: %+v", settings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureMySQLDatabaseSkipsCreationWhenDatabaseExists(t *testing.T) {
|
||||
target := &fakeSetupDB{}
|
||||
openCalls := 0
|
||||
withMySQLSetupOpener(t, func(string) (setupDatabase, error) {
|
||||
openCalls++
|
||||
return target, nil
|
||||
})
|
||||
|
||||
if err := ensureMySQLDatabase(testMySQLDSN(t, "secret")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if openCalls != 1 {
|
||||
t.Fatalf("unexpected open count: %d", openCalls)
|
||||
}
|
||||
if len(target.execQueries) != 0 || !target.closed {
|
||||
t.Fatal("existing database should not trigger creation and must be closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureMySQLDatabaseCreatesMissingDatabase(t *testing.T) {
|
||||
target := &fakeSetupDB{pingErrors: []error{&mysql.MySQLError{Number: 1049}, nil}}
|
||||
admin := &fakeSetupDB{}
|
||||
openCalls := 0
|
||||
withMySQLSetupOpener(t, func(dsn string) (setupDatabase, error) {
|
||||
openCalls++
|
||||
parsed, err := mysql.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parsed.DBName == "" {
|
||||
return admin, nil
|
||||
}
|
||||
return target, nil
|
||||
})
|
||||
|
||||
if err := ensureMySQLDatabase(testMySQLDSN(t, "secret")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if openCalls != 2 || target.pingCalls != 2 || admin.pingCalls != 1 {
|
||||
t.Fatalf("unexpected connection flow: opens=%d targetPings=%d adminPings=%d", openCalls, target.pingCalls, admin.pingCalls)
|
||||
}
|
||||
if len(admin.execQueries) != 1 || admin.execQueries[0] != "CREATE DATABASE IF NOT EXISTS `smail` DEFAULT CHARACTER SET utf8mb4" {
|
||||
t.Fatalf("unexpected creation query: %#v", admin.execQueries)
|
||||
}
|
||||
if !target.closed || !admin.closed {
|
||||
t.Fatal("setup database connections were not closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureMySQLDatabaseReturnsSafeCreationError(t *testing.T) {
|
||||
target := &fakeSetupDB{pingErrors: []error{&mysql.MySQLError{Number: 1049}}}
|
||||
admin := &fakeSetupDB{execError: stderrors.New("secret-password")}
|
||||
withMySQLSetupOpener(t, func(dsn string) (setupDatabase, error) {
|
||||
parsed, err := mysql.ParseDSN(dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parsed.DBName == "" {
|
||||
return admin, nil
|
||||
}
|
||||
return target, nil
|
||||
})
|
||||
|
||||
err := ensureMySQLDatabase(testMySQLDSN(t, "secret-password"))
|
||||
if err == nil {
|
||||
t.Fatal("database creation error was not returned")
|
||||
}
|
||||
message := DatabaseSetupErrorMessage(err)
|
||||
if message == "" || strings.Contains(message, "secret-password") {
|
||||
t.Fatalf("unsafe user-facing error message: %q", message)
|
||||
}
|
||||
}
|
||||
|
||||
func withMySQLSetupOpener(t *testing.T, opener func(string) (setupDatabase, error)) {
|
||||
t.Helper()
|
||||
original := openMySQLSetupDatabase
|
||||
openMySQLSetupDatabase = opener
|
||||
t.Cleanup(func() {
|
||||
openMySQLSetupDatabase = original
|
||||
})
|
||||
}
|
||||
|
||||
func testMySQLDSN(t *testing.T, password string) string {
|
||||
t.Helper()
|
||||
dsn, err := buildMySQLDSN(DatabaseSettings{
|
||||
User: "root",
|
||||
Host: "127.0.0.1",
|
||||
Port: "3306",
|
||||
Password: password,
|
||||
Name: "smail",
|
||||
}, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return dsn
|
||||
}
|
||||
|
||||
func TestPrepareSQLiteDatabaseCreatesParentDirectory(t *testing.T) {
|
||||
databasePath := filepath.Join(t.TempDir(), "nested", "config", "smail.db")
|
||||
if err := prepareSQLiteDatabase(databasePath); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Dir(databasePath)); err != nil {
|
||||
t.Fatalf("SQLite parent directory was not prepared: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,20 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
func TestValidateAdminPasswordLengthBoundaries(t *testing.T) {
|
||||
for _, candidate := range []string{"12345678", "123456789012"} {
|
||||
if err := validateAdminPassword(candidate); err != nil {
|
||||
t.Fatalf("password length %d was rejected: %v", len(candidate), err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, candidate := range []string{"1234567", "1234567890123"} {
|
||||
if err := validateAdminPassword(candidate); err == nil {
|
||||
t.Fatalf("password length %d was accepted", len(candidate))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetAdminPasswordValidatesAndPreventsDuplicates(t *testing.T) {
|
||||
oldConfig := config.Instance
|
||||
config.Instance = &config.Config{DbType: config.DBTypeSQLite, DbDSN: filepath.Join(t.TempDir(), "setup.db")}
|
||||
@@ -21,16 +35,16 @@ func TestSetAdminPasswordValidatesAndPreventsDuplicates(t *testing.T) {
|
||||
t.Cleanup(func() { _ = db.Instance.Close() })
|
||||
|
||||
ctx := &context.Context{}
|
||||
if err := SetAdminPassword(ctx, ".invalid", "StrongPass123"); err == nil {
|
||||
if err := SetAdminPassword(ctx, ".invalid", "StrongP12"); err == nil {
|
||||
t.Fatal("invalid administrator account was accepted")
|
||||
}
|
||||
if err := SetAdminPassword(ctx, "admin-user", "short"); err == nil {
|
||||
t.Fatal("short administrator password was accepted")
|
||||
}
|
||||
if err := SetAdminPassword(ctx, "admin-user", "StrongPass123"); err != nil {
|
||||
if err := SetAdminPassword(ctx, "admin-user", "StrongP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetAdminPassword(ctx, "second-admin", "StrongPass456"); err == nil {
|
||||
if err := SetAdminPassword(ctx, "second-admin", "StrongP45"); err == nil {
|
||||
t.Fatal("duplicate administrator initialization was accepted")
|
||||
}
|
||||
|
||||
@@ -38,7 +52,20 @@ func TestSetAdminPasswordValidatesAndPreventsDuplicates(t *testing.T) {
|
||||
if _, err := db.Instance.Where("account = ?", "admin-user").Get(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if user.ID == 0 || user.IsAdmin != 1 || !password.Verify(user.Password, "StrongPass123") {
|
||||
if user.ID == 0 || user.IsAdmin != 1 || !password.Verify(user.Password, "StrongP12") {
|
||||
t.Fatal("administrator was not initialized correctly")
|
||||
}
|
||||
}
|
||||
func TestAdminPasswordRequiresInitializedDatabase(t *testing.T) {
|
||||
oldInstance := db.Instance
|
||||
db.Instance = nil
|
||||
t.Cleanup(func() { db.Instance = oldInstance })
|
||||
|
||||
ctx := &context.Context{}
|
||||
if _, err := GetAdminPassword(ctx); err == nil {
|
||||
t.Fatal("admin account lookup succeeded without an initialized database")
|
||||
}
|
||||
if err := SetAdminPassword(ctx, "admin-user", "StrongP12"); err == nil {
|
||||
t.Fatal("admin account creation succeeded without an initialized database")
|
||||
}
|
||||
}
|
||||
+150
-14
@@ -1,10 +1,12 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
stdcontext "context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/i18n"
|
||||
@@ -22,6 +24,10 @@ type DNSItem struct {
|
||||
Tips string `json:"tips"`
|
||||
}
|
||||
|
||||
const dnsRecordTTL = 600
|
||||
|
||||
const unresolvedWebIPv4 = "[未解析到 Web 域名公网 IPv4]"
|
||||
|
||||
func GetDNSSettings(ctx *context.Context) (map[string][]*DNSItem, error) {
|
||||
configData, err := config.ReadConfig()
|
||||
if err != nil {
|
||||
@@ -35,35 +41,90 @@ func GetDNSSettings(ctx *context.Context) (map[string][]*DNSItem, error) {
|
||||
|
||||
ipv4 := ip.GetIPv4()
|
||||
ipv6 := ip.GetIPv6()
|
||||
webIPv4 := resolvePublicIPv4(configData.WebDomain)
|
||||
ipTips := i18n.GetText(ctx.Lang, "ip_taps")
|
||||
ret := make(map[string][]*DNSItem, len(configData.Domains))
|
||||
for _, domain := range configData.Domains {
|
||||
ret[domain] = buildDNSItems(configData, domain, dkimPublicKey, ipv4, ipv6, ipTips)
|
||||
ret[domain] = buildDNSItemsWithWebIPv4(configData, domain, dkimPublicKey, ipv4, ipv6, ipTips, webIPv4)
|
||||
}
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func buildDNSItems(configData *config.Config, domain, dkimPublicKey, ipv4, ipv6, ipTips string) []*DNSItem {
|
||||
address := strings.TrimSpace(ipv4)
|
||||
return buildDNSItemsWithWebIPv4(configData, domain, dkimPublicKey, ipv4, ipv6, ipTips, nil)
|
||||
}
|
||||
|
||||
func buildDNSItemsWithWebIPv4(configData *config.Config, domain, dkimPublicKey, ipv4, ipv6, ipTips string, webIPv4 []string) []*DNSItem {
|
||||
address := normalizeDNSAddress(ipv4)
|
||||
if address == "" {
|
||||
address = "[Your Server IP]"
|
||||
address = "[\u672a\u68c0\u6d4b\u5230\u516c\u7f51 IPv4]"
|
||||
}
|
||||
return []*DNSItem{
|
||||
{Type: "A", Host: strings.ReplaceAll(configData.WebDomain, "."+configData.Domain, ""), Value: address, TTL: 3600, Tips: ipTips},
|
||||
{Type: "A", Host: "smtp", Value: address, TTL: 3600, Tips: ipTips},
|
||||
{Type: "A", Host: "imap", Value: address, TTL: 3600, Tips: ipTips},
|
||||
{Type: "A", Host: "pop", Value: address, TTL: 3600, Tips: ipTips},
|
||||
{Type: "A", Host: "@", Value: address, TTL: 3600, Tips: ipTips},
|
||||
{Type: "MX", Host: "@", Value: fmt.Sprintf("smtp.%s", domain), TTL: 3600},
|
||||
{Type: "TXT", Host: "@", Value: buildSPFRecord(ipv4, ipv6), TTL: 3600},
|
||||
{Type: "TXT", Host: "_dmarc", Value: "v=DMARC1; p=quarantine", TTL: 3600},
|
||||
{Type: "TXT", Host: "default._domainkey", Value: dkimPublicKey, TTL: 3600},
|
||||
|
||||
items := make([]*DNSItem, 0, 10)
|
||||
appendARecord := func(host string) {
|
||||
for _, item := range items {
|
||||
if item.Type == "A" && item.Host == host {
|
||||
return
|
||||
}
|
||||
}
|
||||
items = append(items, &DNSItem{
|
||||
Type: "A",
|
||||
Host: host,
|
||||
Value: address,
|
||||
TTL: dnsRecordTTL,
|
||||
Tips: ipTips,
|
||||
})
|
||||
}
|
||||
|
||||
webHost := dnsHostForDomain(configData.WebDomain, domain)
|
||||
if webHost == "@" {
|
||||
appendARecord(webHost)
|
||||
} else if addresses := normalizeDNSAddresses(webIPv4); len(addresses) > 0 {
|
||||
for _, webAddress := range addresses {
|
||||
items = append(items, &DNSItem{
|
||||
Type: "A",
|
||||
Host: webHost,
|
||||
Value: webAddress,
|
||||
TTL: dnsRecordTTL,
|
||||
Tips: ipTips,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
items = append(items, &DNSItem{
|
||||
Type: "A",
|
||||
Host: webHost,
|
||||
Value: unresolvedWebIPv4,
|
||||
TTL: dnsRecordTTL,
|
||||
Tips: "Web 域名未解析到公网 IPv4,请确认域名解析状态",
|
||||
})
|
||||
}
|
||||
appendARecord("smtp")
|
||||
appendARecord("imap")
|
||||
appendARecord("pop")
|
||||
appendARecord("@")
|
||||
|
||||
if ipv6Address := buildSPFAddressMechanism(ipv6); strings.HasPrefix(ipv6Address, "ip6:") {
|
||||
items = append(items, &DNSItem{
|
||||
Type: "AAAA",
|
||||
Host: "@",
|
||||
Value: strings.TrimPrefix(ipv6Address, "ip6:"),
|
||||
TTL: dnsRecordTTL,
|
||||
Tips: ipTips,
|
||||
})
|
||||
}
|
||||
|
||||
items = append(items,
|
||||
&DNSItem{Type: "MX", Host: "@", Value: fmt.Sprintf("smtp.%s | 1", domain), TTL: dnsRecordTTL},
|
||||
&DNSItem{Type: "TXT", Host: "@", Value: buildSPFRecord(ipv4, ipv6), TTL: dnsRecordTTL},
|
||||
&DNSItem{Type: "TXT", Host: "_dmarc", Value: buildDMARCRecord(domain), TTL: dnsRecordTTL},
|
||||
&DNSItem{Type: "TXT", Host: "default._domainkey", Value: dkimPublicKey, TTL: dnsRecordTTL},
|
||||
)
|
||||
return items
|
||||
}
|
||||
|
||||
func buildSPFRecord(ipv4, ipv6 string) string {
|
||||
mechanisms := []string{"v=spf1", "a", "mx"}
|
||||
mechanisms := []string{"v=spf1"}
|
||||
if mechanism := buildSPFAddressMechanism(ipv4); mechanism != "" {
|
||||
mechanisms = append(mechanisms, mechanism)
|
||||
}
|
||||
@@ -74,6 +135,81 @@ func buildSPFRecord(ipv4, ipv6 string) string {
|
||||
return strings.Join(mechanisms, " ")
|
||||
}
|
||||
|
||||
func buildDMARCRecord(domain string) string {
|
||||
return fmt.Sprintf("v=DMARC1; p=quarantine; rua=mailto:admin@%s", domain)
|
||||
}
|
||||
|
||||
func normalizeDNSAddress(value string) string {
|
||||
address, err := netip.ParseAddr(strings.TrimSpace(value))
|
||||
if err != nil || !isPublicDNSAddress(address) || !address.Is4() {
|
||||
return ""
|
||||
}
|
||||
return address.String()
|
||||
}
|
||||
|
||||
func normalizeDNSAddresses(values []string) []string {
|
||||
addresses := make([]string, 0, len(values))
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
for _, value := range values {
|
||||
address := normalizeDNSAddress(value)
|
||||
if address == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[address]; exists {
|
||||
continue
|
||||
}
|
||||
seen[address] = struct{}{}
|
||||
addresses = append(addresses, address)
|
||||
}
|
||||
return addresses
|
||||
}
|
||||
|
||||
func resolvePublicIPv4(host string) []string {
|
||||
return resolvePublicIPv4WithLookup(host, func(ctx stdcontext.Context, target string) ([]net.IP, error) {
|
||||
return net.DefaultResolver.LookupIP(ctx, "ip4", target)
|
||||
})
|
||||
}
|
||||
|
||||
func resolvePublicIPv4WithLookup(host string, lookup func(stdcontext.Context, string) ([]net.IP, error)) []string {
|
||||
host = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(host)), ".")
|
||||
if host == "" || lookup == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := stdcontext.WithTimeout(stdcontext.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
addresses, err := lookup(ctx, host)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
values := make([]string, 0, len(addresses))
|
||||
for _, address := range addresses {
|
||||
if address == nil {
|
||||
continue
|
||||
}
|
||||
values = append(values, address.String())
|
||||
}
|
||||
return normalizeDNSAddresses(values)
|
||||
}
|
||||
|
||||
func dnsHostForDomain(webDomain, domain string) string {
|
||||
webDomain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(webDomain)), ".")
|
||||
domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
|
||||
if webDomain == "" || webDomain == domain {
|
||||
return "@"
|
||||
}
|
||||
|
||||
suffix := "." + domain
|
||||
if strings.HasSuffix(webDomain, suffix) {
|
||||
host := strings.TrimSuffix(webDomain, suffix)
|
||||
if host != "" {
|
||||
return host
|
||||
}
|
||||
}
|
||||
return webDomain
|
||||
}
|
||||
|
||||
func buildSPFAddressMechanism(value string) string {
|
||||
address, err := netip.ParseAddr(strings.TrimSpace(value))
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
stdcontext "context"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
@@ -8,7 +10,7 @@ import (
|
||||
|
||||
func TestBuildSPFRecordIncludesPublicIPv4AndIPv6(t *testing.T) {
|
||||
value := buildSPFRecord("203.0.113.15", "2001:db8::15")
|
||||
want := "v=spf1 a mx ip4:203.0.113.15 ip6:2001:db8::15 ~all"
|
||||
want := "v=spf1 ip4:203.0.113.15 ip6:2001:db8::15 ~all"
|
||||
if value != want {
|
||||
t.Fatalf("SPF record = %q, want %q", value, want)
|
||||
}
|
||||
@@ -21,11 +23,11 @@ func TestBuildSPFRecordSkipsUnsafeAddresses(t *testing.T) {
|
||||
ipv6 string
|
||||
want string
|
||||
}{
|
||||
{name: "empty", want: "v=spf1 a mx ~all"},
|
||||
{name: "private IPv4", ipv4: "192.168.1.20", want: "v=spf1 a mx ~all"},
|
||||
{name: "link local IPv6", ipv6: "fe80::1", want: "v=spf1 a mx ~all"},
|
||||
{name: "only IPv4", ipv4: "198.51.100.9", want: "v=spf1 a mx ip4:198.51.100.9 ~all"},
|
||||
{name: "only IPv6", ipv6: "2001:db8::9", want: "v=spf1 a mx ip6:2001:db8::9 ~all"},
|
||||
{name: "empty", want: "v=spf1 ~all"},
|
||||
{name: "private IPv4", ipv4: "192.168.1.20", want: "v=spf1 ~all"},
|
||||
{name: "link local IPv6", ipv6: "fe80::1", want: "v=spf1 ~all"},
|
||||
{name: "only IPv4", ipv4: "198.51.100.9", want: "v=spf1 ip4:198.51.100.9 ~all"},
|
||||
{name: "only IPv6", ipv6: "2001:db8::9", want: "v=spf1 ip6:2001:db8::9 ~all"},
|
||||
}
|
||||
for _, item := range cases {
|
||||
t.Run(item.name, func(t *testing.T) {
|
||||
@@ -49,13 +51,91 @@ func TestBuildDNSItemsIncludesSPFAndQuarantineDMARC(t *testing.T) {
|
||||
values[item.Host] = item.Value
|
||||
}
|
||||
}
|
||||
if value := values["@"]; value != "v=spf1 a mx ip4:203.0.113.10 ip6:2001:db8::10 ~all" {
|
||||
if value := values["@"]; value != "v=spf1 ip4:203.0.113.10 ip6:2001:db8::10 ~all" {
|
||||
t.Fatalf("SPF TXT value = %q", value)
|
||||
}
|
||||
if value := values["_dmarc"]; value != "v=DMARC1; p=quarantine" {
|
||||
if value := values["_dmarc"]; value != "v=DMARC1; p=quarantine; rua=mailto:admin@example.com" {
|
||||
t.Fatalf("DMARC TXT value = %q", value)
|
||||
}
|
||||
if value := values["default._domainkey"]; value != "v=DKIM1; k=rsa; p=test" {
|
||||
t.Fatalf("DKIM TXT value = %q", value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildDNSItemsCreatesExpectedRecordShape(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Domain: "example.com",
|
||||
WebDomain: "panel.example.com",
|
||||
}
|
||||
items := buildDNSItemsWithWebIPv4(cfg, "example.com", "v=DKIM1; k=rsa; p=test", "198.51.100.20", "2001:db8::20", "", []string{"203.0.113.20"})
|
||||
|
||||
if len(items) != 10 {
|
||||
t.Fatalf("DNS item count = %d, want 10", len(items))
|
||||
}
|
||||
if items[0].Host != "panel" || items[0].Type != "A" || items[0].Value != "203.0.113.20" {
|
||||
t.Fatalf("web A record = %#v", items[0])
|
||||
}
|
||||
if items[4].Host != "@" || items[4].Type != "A" || items[4].Value != "198.51.100.20" {
|
||||
t.Fatalf("root A record = %#v", items[4])
|
||||
}
|
||||
if items[5].Type != "AAAA" || items[5].Host != "@" || items[5].Value != "2001:db8::20" {
|
||||
t.Fatalf("root AAAA record = %#v", items[5])
|
||||
}
|
||||
if items[6].Value != "smtp.example.com | 1" || items[6].TTL != dnsRecordTTL {
|
||||
t.Fatalf("MX record = %#v", items[6])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildDNSItemsDoesNotReuseMailIPForUnresolvedWebDomain(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Domain: "example.net",
|
||||
WebDomain: "panel.example.net",
|
||||
}
|
||||
items := buildDNSItemsWithWebIPv4(cfg, "example.net", "v=DKIM1; k=rsa; p=test", "198.51.100.30", "", "", nil)
|
||||
|
||||
if items[0].Host != "panel" || items[0].Value != unresolvedWebIPv4 {
|
||||
t.Fatalf("unresolved web A record = %#v", items[0])
|
||||
}
|
||||
if items[1].Host != "smtp" || items[1].Value != "198.51.100.30" {
|
||||
t.Fatalf("mail A record = %#v", items[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvePublicIPv4UsesActualLookupResults(t *testing.T) {
|
||||
lookup := func(ctx stdcontext.Context, host string) ([]net.IP, error) {
|
||||
if host != "panel.example.org" {
|
||||
t.Fatalf("lookup host = %q", host)
|
||||
}
|
||||
return []net.IP{
|
||||
net.ParseIP("203.0.113.40"),
|
||||
net.ParseIP("192.168.1.40"),
|
||||
net.ParseIP("203.0.113.40"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
values := resolvePublicIPv4WithLookup("Panel.Example.Org.", lookup)
|
||||
if len(values) != 1 || values[0] != "203.0.113.40" {
|
||||
t.Fatalf("resolved public IPv4 = %#v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSHostForDomain(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
web string
|
||||
domain string
|
||||
want string
|
||||
}{
|
||||
{name: "subdomain", web: "mail.example.com", domain: "example.com", want: "mail"},
|
||||
{name: "root", web: "example.com", domain: "example.com", want: "@"},
|
||||
{name: "trailing dot", web: "mail.example.com.", domain: "example.com.", want: "mail"},
|
||||
{name: "external domain", web: "panel.other.example", domain: "example.com", want: "panel.other.example"},
|
||||
}
|
||||
for _, item := range cases {
|
||||
t.Run(item.name, func(t *testing.T) {
|
||||
if value := dnsHostForDomain(item.web, item.domain); value != item.want {
|
||||
t.Fatalf("DNS host = %q, want %q", value, item.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -61,16 +61,37 @@ func SetSSL(sslType, priKey, crtKey string) error {
|
||||
if sslType == config.SSLTypeAutoHTTP || sslType == config.SSLTypeUser || sslType == config.SSLTypeAutoDNS {
|
||||
cfg.SSLType = sslType
|
||||
} else {
|
||||
return errors.New("SSL Type Error!")
|
||||
return errors.New("SSL 类型错误")
|
||||
}
|
||||
|
||||
if cfg.SSLType != config.SSLTypeUser {
|
||||
clearLegacySSLPaths(cfg)
|
||||
cfg.SSL = config.SSLConfig{
|
||||
Mode: config.ManagedSSLModeDefault,
|
||||
DefaultDirectory: "config/ssl",
|
||||
}
|
||||
}
|
||||
if cfg.SSLType == config.SSLTypeUser {
|
||||
if isAbsoluteUserCertificatePath(priKey) || isAbsoluteUserCertificatePath(crtKey) {
|
||||
return errors.New("用户证书路径必须使用受控相对路径")
|
||||
}
|
||||
privatePath, publicPath, err := validateUserCertificatePaths(priKey, crtKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.SSLPrivateKeyPath = privatePath
|
||||
cfg.SSLPublicKeyPath = publicPath
|
||||
privatePEM, err := os.ReadFile(privatePath)
|
||||
if err != nil {
|
||||
return errors.New("读取 SSL 私钥失败")
|
||||
}
|
||||
publicPEM, err := os.ReadFile(publicPath)
|
||||
if err != nil {
|
||||
return errors.New("读取 SSL 证书失败")
|
||||
}
|
||||
reference, err := config.ImportManagedSSL(config.ManagedSSLModeUpload, privatePEM, publicPEM, nil, sslDomains(cfg))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
applyManagedSSLReference(cfg, reference)
|
||||
// 手动设置证书的情况下后台地址默认不启用https
|
||||
cfg.HttpsEnabled = 1
|
||||
}
|
||||
@@ -83,6 +104,40 @@ func SetSSL(sslType, priKey, crtKey string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// clearLegacySSLPaths 只清理新受控模式不再使用的旧聚合路径字段。
|
||||
func clearLegacySSLPaths(cfg *config.Config) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
cfg.SSLPrivateKeyPath = ""
|
||||
cfg.SSLPublicKeyPath = ""
|
||||
}
|
||||
|
||||
// applyManagedSSLReference 将证书切换结果写入内部引用,不持久化服务器路径。
|
||||
func applyManagedSSLReference(cfg *config.Config, reference config.ManagedSSLReference) {
|
||||
if cfg == nil {
|
||||
return
|
||||
}
|
||||
clearLegacySSLPaths(cfg)
|
||||
cfg.SSL = config.SSLConfig{
|
||||
Mode: reference.Mode,
|
||||
DefaultDirectory: "config/ssl",
|
||||
CertificateRef: reference.CertificateRef,
|
||||
PrivateKeyRef: reference.PrivateKeyRef,
|
||||
}
|
||||
if reference.Mode == config.ManagedSSLModeUpload {
|
||||
cfg.SSL.CustomDirectory = "config/ssl/managed/upload"
|
||||
}
|
||||
}
|
||||
|
||||
func isAbsoluteUserCertificatePath(value string) bool {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" || filepath.IsAbs(value) || filepath.VolumeName(value) != "" {
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(value, `\\`) || strings.HasPrefix(value, "//")
|
||||
}
|
||||
|
||||
func validateUserCertificatePaths(privatePath, publicPath string) (string, string, error) {
|
||||
rootPath, err := filepath.Abs(filepath.Clean(config.ROOT_PATH))
|
||||
if err != nil {
|
||||
@@ -173,7 +228,46 @@ func validateUserCertificatePaths(privatePath, publicPath string) (string, strin
|
||||
}
|
||||
|
||||
func writeCertificateFiles(cfg *config.Config, privateKey, certificate, issuer []byte) error {
|
||||
return writeCertificateBundle(cfg, privateKey, certificate, issuer)
|
||||
if cfg == nil {
|
||||
return errors.New("SSL 配置不能为空")
|
||||
}
|
||||
reference, err := config.ImportManagedSSL(config.ManagedSSLModeDefault, privateKey, certificate, issuer, sslDomains(cfg))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
applyManagedSSLReference(cfg, reference)
|
||||
if err := config.WriteConfig(cfg); err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sslDomains(cfg *config.Config) []string {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
domains := make([]string, 0, len(cfg.Domains)*3+1)
|
||||
appendDomain := func(domain string) {
|
||||
domain = strings.TrimSpace(domain)
|
||||
if domain == "" {
|
||||
return
|
||||
}
|
||||
if _, exists := seen[domain]; exists {
|
||||
return
|
||||
}
|
||||
seen[domain] = struct{}{}
|
||||
domains = append(domains, domain)
|
||||
}
|
||||
appendDomain(cfg.WebDomain)
|
||||
appendDomain(cfg.Domain)
|
||||
for _, domain := range cfg.Domains {
|
||||
appendDomain(domain)
|
||||
appendDomain("smtp." + domain)
|
||||
appendDomain("pop." + domain)
|
||||
appendDomain("imap." + domain)
|
||||
}
|
||||
return domains
|
||||
}
|
||||
func renewCertificate(privateKey *ecdsa.PrivateKey, cfg *config.Config) error {
|
||||
|
||||
@@ -333,8 +427,13 @@ func GenSSL(update bool) error {
|
||||
}
|
||||
|
||||
if !update {
|
||||
privateFile, errpi := os.ReadFile(cfg.SSLPrivateKeyPath)
|
||||
public, errpu := os.ReadFile(cfg.SSLPublicKeyPath)
|
||||
privatePath, publicPath, pathErr := config.ResolveRuntimeSSLPaths(cfg)
|
||||
privateFile, errpi := os.ReadFile(privatePath)
|
||||
public, errpu := os.ReadFile(publicPath)
|
||||
if pathErr != nil {
|
||||
errpi = pathErr
|
||||
errpu = pathErr
|
||||
}
|
||||
// 当前存在证书数据,就不生成了
|
||||
if errpi == nil && errpu == nil && len(privateFile) > 0 && len(public) > 0 {
|
||||
return nil
|
||||
@@ -361,7 +460,7 @@ func CheckSSLCrtInfo() (int, time.Time, bool, error) {
|
||||
return -1, time.Now(), true, errors.Wrap(err)
|
||||
}
|
||||
// load cert and key by tls.LoadX509KeyPair
|
||||
tlsCert, err := tls.LoadX509KeyPair(cfg.SSLPublicKeyPath, cfg.SSLPrivateKeyPath)
|
||||
tlsCert, err := config.LoadRuntimeTLSCertificate(cfg)
|
||||
if err != nil {
|
||||
return -1, time.Now(), true, errors.Wrap(err)
|
||||
}
|
||||
|
||||
@@ -49,6 +49,55 @@ func writeTestCertificate(t *testing.T, root string, bits int) (string, string)
|
||||
return keyPath, certPath
|
||||
}
|
||||
|
||||
func TestIsAbsoluteUserCertificatePathRejectsWindowsPaths(t *testing.T) {
|
||||
cases := []string{
|
||||
`C:\outside\private.key`,
|
||||
`D:/outside/public.crt`,
|
||||
`\\server\share\private.key`,
|
||||
`//server/share/public.crt`,
|
||||
}
|
||||
for _, value := range cases {
|
||||
if !isAbsoluteUserCertificatePath(value) {
|
||||
t.Errorf("path %q was accepted", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsAbsoluteUserCertificatePathRejectsEmptyAndAcceptsRelative(t *testing.T) {
|
||||
if !isAbsoluteUserCertificatePath("") {
|
||||
t.Fatal("empty path must be rejected")
|
||||
}
|
||||
if isAbsoluteUserCertificatePath(`config/ssl/upload/private.key`) {
|
||||
t.Fatal("controlled relative path must not be treated as absolute")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyManagedSSLReferenceDoesNotPersistLegacyPaths(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
SSLPrivateKeyPath: "config/ssl/private.key",
|
||||
SSLPublicKeyPath: "config/ssl/public.crt",
|
||||
}
|
||||
reference := config.ManagedSSLReference{
|
||||
Mode: config.ManagedSSLModeUpload,
|
||||
CertificateRef: "config/ssl/managed/upload/current/public.crt",
|
||||
PrivateKeyRef: "config/ssl/managed/upload/current/private.key",
|
||||
CertificatePath: `C:\server\config\ssl\managed\upload\current\public.crt`,
|
||||
PrivateKeyPath: `C:\server\config\ssl\managed\upload\current\private.key`,
|
||||
}
|
||||
|
||||
applyManagedSSLReference(cfg, reference)
|
||||
|
||||
if cfg.SSLPrivateKeyPath != "" || cfg.SSLPublicKeyPath != "" {
|
||||
t.Fatal("新受控 SSL 配置不应保留旧聚合路径")
|
||||
}
|
||||
if cfg.SSL.Mode != config.ManagedSSLModeUpload || cfg.SSL.CertificateRef != reference.CertificateRef || cfg.SSL.PrivateKeyRef != reference.PrivateKeyRef {
|
||||
t.Fatalf("受控 SSL 内部引用写入错误: %+v", cfg.SSL)
|
||||
}
|
||||
if cfg.SSL.CustomDirectory != "config/ssl/managed/upload" {
|
||||
t.Fatalf("自定义受控目录写入错误: %s", cfg.SSL.CustomDirectory)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateUserCertificatePaths(t *testing.T) {
|
||||
oldRoot := config.ROOT_PATH
|
||||
root := t.TempDir()
|
||||
|
||||
Reference in new issue
Block a user