完善配置审计与数据库迁移安全链路
This commit is contained in:
1 parent
84440d8761
commit
3af1fc4147
117 files changed
+4703
-1110
No files matched your search
@@ -90,7 +90,7 @@ func TestAdminPluginRestartScope(t *testing.T) {
|
||||
|
||||
func TestManagementEndpointCatalog(t *testing.T) {
|
||||
endpoints := ManagementEndpoints()
|
||||
if len(endpoints) != 18 {
|
||||
if len(endpoints) != 32 {
|
||||
t.Fatalf("unexpected endpoint count: %d", len(endpoints))
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
@@ -112,6 +112,10 @@ func TestManagementEndpointCatalog(t *testing.T) {
|
||||
if !ok || endpoint.Capability != CapabilityConfigWriteGlobal {
|
||||
t.Fatal("configuration validation endpoint was not matched")
|
||||
}
|
||||
endpoint, ok = LookupEndpoint("POST", "/api/v1/system/restart")
|
||||
if !ok || endpoint.Capability != CapabilityServiceRestart {
|
||||
t.Fatal("system restart endpoint was not matched")
|
||||
}
|
||||
endpoint, ok = LookupEndpoint("GET", "/api/v1/config/email")
|
||||
if !ok || endpoint.Capability != CapabilityConfigRead {
|
||||
t.Fatal("configuration section endpoint was not matched")
|
||||
|
||||
@@ -26,7 +26,21 @@ var managementEndpoints = []Endpoint{
|
||||
{Method: "GET", Path: "/api/v1/config/:section", Capability: CapabilityConfigRead},
|
||||
{Method: "PUT", Path: "/api/v1/config/:section", Capability: CapabilityConfigWriteGlobal},
|
||||
{Method: "GET", Path: "/api/v1/audits/config", Capability: CapabilityAuditRead},
|
||||
{Method: "GET", Path: "/api/v1/audits/config/:id", Capability: CapabilityAuditRead},
|
||||
{Method: "POST", Path: "/api/v1/audits/config", Capability: CapabilityAuditExport},
|
||||
{Method: "POST", Path: "/api/v1/audits/config/export", Capability: CapabilityAuditExport},
|
||||
{Method: "POST", Path: "/api/v1/settings/modify_password", Capability: CapabilityPasswordChangeOwn},
|
||||
{Method: "POST", Path: "/api/v1/system/restart", Capability: CapabilityServiceRestart},
|
||||
{Method: "POST", Path: "/api/v1/system/restart/preview", Capability: CapabilityServiceRestart},
|
||||
{Method: "POST", Path: "/api/v1/database/migrations/preview", Capability: CapabilityDatabaseMigrate},
|
||||
{Method: "POST", Path: "/api/v1/database/migrations", Capability: CapabilityDatabaseMigrate},
|
||||
{Method: "GET", Path: "/api/v1/database/migrations/:id", Capability: CapabilityDatabaseMigrate},
|
||||
{Method: "POST", Path: "/api/v1/user/create", Capability: CapabilityUserManage},
|
||||
{Method: "POST", Path: "/api/v1/user/edit", Capability: CapabilityUserManage},
|
||||
{Method: "POST", Path: "/api/v1/user/info", Capability: CapabilityUserRead},
|
||||
{Method: "POST", Path: "/api/v1/user/list", Capability: CapabilityUserRead},
|
||||
{Method: "GET", Path: "/api/v1/plugin/list", Capability: CapabilityPluginRead},
|
||||
{Method: "*", Path: "/api/v1/plugin/settings/", Capability: CapabilityPluginWriteOwn},
|
||||
}
|
||||
|
||||
func ManagementEndpoints() []Endpoint {
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
package adminreset
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
func ReadProtectedPassword() (string, error) {
|
||||
@@ -36,9 +36,27 @@ func askPassword(prompt string) (string, error) {
|
||||
if err != nil {
|
||||
return "", errors.New("受保护密码代理不可用")
|
||||
}
|
||||
output = bytes.TrimSpace(output)
|
||||
if len(output) == 0 || len(output) > 256 {
|
||||
output = stripPasswordLineEnding(output)
|
||||
value := string(output)
|
||||
defer clearBytes(output)
|
||||
if password.ValidateUserPassword(value) != nil {
|
||||
return "", errors.New("密码长度无效")
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func stripPasswordLineEnding(value []byte) []byte {
|
||||
if len(value) > 0 && value[len(value)-1] == '\n' {
|
||||
value = value[:len(value)-1]
|
||||
}
|
||||
if len(value) > 0 && value[len(value)-1] == '\r' {
|
||||
value = value[:len(value)-1]
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func clearBytes(value []byte) {
|
||||
for index := range value {
|
||||
value[index] = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build linux
|
||||
|
||||
package adminreset
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStripPasswordLineEndingPreservesPasswordWhitespace(t *testing.T) {
|
||||
value := []byte(" Pass123 \r\n")
|
||||
got := string(stripPasswordLineEnding(value))
|
||||
if got != " Pass123 " {
|
||||
t.Fatalf("password output = %q, want surrounding spaces preserved", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripPasswordLineEndingDoesNotTrimOtherWhitespace(t *testing.T) {
|
||||
value := []byte("\tPass123\t")
|
||||
got := string(stripPasswordLineEnding(value))
|
||||
if got != "\tPass123\t" {
|
||||
t.Fatalf("password output = %q, want non-line-ending whitespace preserved", got)
|
||||
}
|
||||
}
|
||||
@@ -6,20 +6,21 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func ReadProtectedPassword() (string, error) {
|
||||
if !term.IsTerminal(int(os.Stdin.Fd())) {
|
||||
return "", errors.New("\u53d7\u4fdd\u62a4\u7684\u5bc6\u7801\u8f93\u5165\u9700\u8981\u4ea4\u4e92\u5f0f\u63a7\u5236\u53f0")
|
||||
return "", errors.New("受保护的密码输入需要交互式控制台")
|
||||
}
|
||||
first, err := readWindowsPassword("\u8bf7\u8f93\u5165\u65b0\u7684\u8d85\u7ea7\u7ba1\u7406\u5458\u5bc6\u7801")
|
||||
first, err := readWindowsPassword("请输入新的超级管理员密码")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
second, err := readWindowsPassword("\u8bf7\u518d\u6b21\u8f93\u5165\u65b0\u7684\u8d85\u7ea7\u7ba1\u7406\u5458\u5bc6\u7801")
|
||||
second, err := readWindowsPassword("请再次输入新的超级管理员密码")
|
||||
if err != nil {
|
||||
clearPassword(&first)
|
||||
return "", err
|
||||
@@ -27,7 +28,7 @@ func ReadProtectedPassword() (string, error) {
|
||||
if first == "" || first != second {
|
||||
clearPassword(&first)
|
||||
clearPassword(&second)
|
||||
return "", errors.New("\u5bc6\u7801\u4e3a\u7a7a\u6216\u4e24\u6b21\u8f93\u5165\u4e0d\u4e00\u81f4")
|
||||
return "", errors.New("密码为空或两次输入不一致")
|
||||
}
|
||||
clearPassword(&second)
|
||||
return first, nil
|
||||
@@ -38,14 +39,14 @@ func readWindowsPassword(prompt string) (string, error) {
|
||||
value, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||
fmt.Fprintln(os.Stderr)
|
||||
if err != nil {
|
||||
return "", errors.New("\u53d7\u4fdd\u62a4\u7684\u5bc6\u7801\u8f93\u5165\u5931\u8d25")
|
||||
return "", errors.New("受保护的密码输入失败")
|
||||
}
|
||||
normalized := strings.TrimSpace(string(value))
|
||||
normalized := string(value)
|
||||
for i := range value {
|
||||
value[i] = 0
|
||||
}
|
||||
if len([]byte(normalized)) < 8 || len([]byte(normalized)) > 256 {
|
||||
return "", errors.New("\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8 \u5230 256 \u4e2a\u5b57\u7b26")
|
||||
if password.ValidateUserPassword(normalized) != nil {
|
||||
return "", errors.New("\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8 \u5230 12 \u4e2a\u5b57\u7b26")
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
@@ -12,12 +12,15 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
)
|
||||
|
||||
const (
|
||||
ProtocolVersion = 1
|
||||
maxControlMessageSize = 16 << 10
|
||||
controlRequestTimeout = 15 * time.Second
|
||||
ProtocolVersion = 1
|
||||
maxControlMessageSize = 16 << 10
|
||||
controlRequestTimeout = 15 * time.Second
|
||||
defaultSessionCapacity = 128
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -26,6 +29,7 @@ var (
|
||||
ErrReplay = errors.New("reset request replayed")
|
||||
ErrExpiredSession = errors.New("reset session expired")
|
||||
ErrUnsupported = errors.New("local reset channel is unsupported")
|
||||
ErrSessionCapacity = errors.New("reset session capacity exceeded")
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
@@ -44,17 +48,31 @@ type Response struct {
|
||||
type ResetHandler func(newPassword string) error
|
||||
|
||||
type SessionGuard struct {
|
||||
mu sync.Mutex
|
||||
pending map[string]time.Time
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
mu sync.Mutex
|
||||
pending map[string]time.Time
|
||||
ttl time.Duration
|
||||
capacity int
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewSessionGuard(ttl time.Duration) *SessionGuard {
|
||||
return NewSessionGuardWithCapacity(ttl, defaultSessionCapacity)
|
||||
}
|
||||
|
||||
// NewSessionGuardWithCapacity 创建带有并发会话上限的短时会话守卫。
|
||||
func NewSessionGuardWithCapacity(ttl time.Duration, capacity int) *SessionGuard {
|
||||
if ttl <= 0 {
|
||||
ttl = 2 * time.Minute
|
||||
}
|
||||
return &SessionGuard{pending: make(map[string]time.Time), ttl: ttl, now: time.Now}
|
||||
if capacity <= 0 {
|
||||
capacity = defaultSessionCapacity
|
||||
}
|
||||
return &SessionGuard{
|
||||
pending: make(map[string]time.Time, capacity),
|
||||
ttl: ttl,
|
||||
capacity: capacity,
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
func (g *SessionGuard) Issue() (string, error) {
|
||||
@@ -65,6 +83,9 @@ func (g *SessionGuard) Issue() (string, error) {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
g.pruneLocked(now)
|
||||
if len(g.pending) >= g.capacity {
|
||||
return "", ErrSessionCapacity
|
||||
}
|
||||
for attempt := 0; attempt < 3; attempt++ {
|
||||
nonce, err := NewNonce()
|
||||
if err != nil {
|
||||
@@ -133,7 +154,7 @@ func DecodeRequest(r io.Reader) (Request, error) {
|
||||
if err := decodeControlJSON(data, &request); err != nil {
|
||||
return Request{}, ErrInvalidRequest
|
||||
}
|
||||
if request.Version != ProtocolVersion || strings.TrimSpace(request.Nonce) == "" || len([]byte(request.NewPassword)) < 8 || len([]byte(request.NewPassword)) > 256 {
|
||||
if request.Version != ProtocolVersion || strings.TrimSpace(request.Nonce) == "" || password.ValidateUserPassword(request.NewPassword) != nil {
|
||||
return Request{}, ErrInvalidRequest
|
||||
}
|
||||
return request, nil
|
||||
@@ -196,7 +217,7 @@ func handleResetConnection(conn io.ReadWriter, setDeadline func(time.Time) error
|
||||
}
|
||||
nonce, err := guard.Issue()
|
||||
if err != nil {
|
||||
_ = EncodeResponse(conn, Response{Code: "CHANNEL_UNAVAILABLE", Message: "\u91cd\u7f6e\u901a\u9053\u4e0d\u53ef\u7528"})
|
||||
_ = EncodeResponse(conn, Response{Code: "CHANNEL_UNAVAILABLE", Message: "重置通道不可用"})
|
||||
return
|
||||
}
|
||||
defer guard.Discard(nonce)
|
||||
@@ -205,20 +226,20 @@ func handleResetConnection(conn io.ReadWriter, setDeadline func(time.Time) error
|
||||
}
|
||||
request, err := DecodeRequest(conn)
|
||||
if err != nil || request.Nonce != nonce {
|
||||
_ = EncodeResponse(conn, Response{Code: "INVALID_REQUEST", Message: "\u91cd\u7f6e\u8bf7\u6c42\u65e0\u6548"})
|
||||
_ = EncodeResponse(conn, Response{Code: "INVALID_REQUEST", Message: "重置请求无效"})
|
||||
return
|
||||
}
|
||||
if err := guard.Consume(request.Nonce); err != nil {
|
||||
_ = EncodeResponse(conn, Response{Code: "REPLAY_OR_EXPIRED", Message: "\u91cd\u7f6e\u4f1a\u8bdd\u5df2\u5931\u6548\u6216\u5df2\u4f7f\u7528"})
|
||||
_ = EncodeResponse(conn, Response{Code: "REPLAY_OR_EXPIRED", Message: "重置会话已失效或已使用"})
|
||||
return
|
||||
}
|
||||
password := request.NewPassword
|
||||
defer clearPassword(&password)
|
||||
if err := handler(password); err != nil {
|
||||
_ = EncodeResponse(conn, Response{Code: "RESET_FAILED", Message: "\u8d85\u7ea7\u7ba1\u7406\u5458\u5bc6\u7801\u91cd\u7f6e\u5931\u8d25"})
|
||||
_ = EncodeResponse(conn, Response{Code: "RESET_FAILED", Message: "超级管理员密码重置失败"})
|
||||
return
|
||||
}
|
||||
_ = EncodeResponse(conn, Response{OK: true, Message: "\u8d85\u7ea7\u7ba1\u7406\u5458\u5bc6\u7801\u5df2\u91cd\u7f6e"})
|
||||
_ = EncodeResponse(conn, Response{OK: true, Message: "超级管理员密码已重置"})
|
||||
}
|
||||
|
||||
func clearPassword(password *string) {
|
||||
|
||||
@@ -39,6 +39,32 @@ func TestSessionGuardRejectsExpiredNonce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionGuardRejectsNewSessionsWhenCapacityIsFull(t *testing.T) {
|
||||
guard := NewSessionGuardWithCapacity(time.Minute, 2)
|
||||
if _, err := guard.Issue(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := guard.Issue(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := guard.Issue(); !errors.Is(err, ErrSessionCapacity) {
|
||||
t.Fatalf("capacity error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionGuardPrunesExpiredSessionsBeforeCapacityCheck(t *testing.T) {
|
||||
guard := NewSessionGuardWithCapacity(time.Second, 1)
|
||||
now := time.Unix(100, 0)
|
||||
guard.now = func() time.Time { return now }
|
||||
if _, err := guard.Issue(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = now.Add(2 * time.Second)
|
||||
if _, err := guard.Issue(); err != nil {
|
||||
t.Fatalf("expired session blocked a new session: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolRejectsUnknownFieldsInvalidVersionAndTrailingData(t *testing.T) {
|
||||
cases := []string{
|
||||
`{"version":1,"nonce":"n","new_password":"Password123","extra":true}`,
|
||||
@@ -52,6 +78,30 @@ func TestProtocolRejectsUnknownFieldsInvalidVersionAndTrailingData(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolEnforcesUnifiedPasswordLength(t *testing.T) {
|
||||
valid := []string{
|
||||
`{"version":1,"nonce":"n","new_password":"12345678"}`,
|
||||
`{"version":1,"nonce":"n","new_password":"123456789012"}`,
|
||||
`{"version":1,"nonce":"n","new_password":"\u5bc6\u7801aa"}`,
|
||||
}
|
||||
for _, input := range valid {
|
||||
if _, err := DecodeRequest(strings.NewReader(input)); err != nil {
|
||||
t.Fatalf("valid password request was rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{
|
||||
`{"version":1,"nonce":"n","new_password":"1234567"}`,
|
||||
`{"version":1,"nonce":"n","new_password":"1234567890123"}`,
|
||||
`{"version":1,"nonce":"n","new_password":"\u5bc6\u7801\u5bc6\u7801a"}`,
|
||||
}
|
||||
for _, input := range invalid {
|
||||
if _, err := DecodeRequest(strings.NewReader(input)); !errors.Is(err, ErrInvalidRequest) {
|
||||
t.Fatalf("invalid password request returned %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolRejectsOversizedFrame(t *testing.T) {
|
||||
input := bytes.Repeat([]byte{'x'}, maxControlMessageSize+1)
|
||||
if _, err := DecodeRequest(bytes.NewReader(input)); err == nil {
|
||||
|
||||
@@ -120,7 +120,7 @@ func (s *UnixServer) handle(conn net.Conn, handler ResetHandler, guard *SessionG
|
||||
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"})
|
||||
_ = EncodeResponse(conn, Response{Code: "CHANNEL_UNAVAILABLE", Message: "重置通道不可用"})
|
||||
return
|
||||
}
|
||||
defer guard.Discard(nonce)
|
||||
@@ -133,7 +133,7 @@ func (s *UnixServer) handle(conn net.Conn, handler ResetHandler, guard *SessionG
|
||||
return
|
||||
}
|
||||
if request.Nonce != nonce {
|
||||
_ = EncodeResponse(conn, Response{Code: "INVALID_REQUEST", Message: "\u91cd\u7f6e\u8bf7\u6c42\u65e0\u6548"})
|
||||
_ = EncodeResponse(conn, Response{Code: "INVALID_REQUEST", Message: "重置请求无效"})
|
||||
return
|
||||
}
|
||||
if err := guard.Consume(request.Nonce); err != nil {
|
||||
|
||||
@@ -66,7 +66,7 @@ func (s *WindowsServer) Serve(ctx context.Context, handler ResetHandler, guard *
|
||||
func handleWindowsConnection(conn net.Conn, handler ResetHandler, guard *SessionGuard) {
|
||||
defer conn.Close()
|
||||
if err := authorizeWindowsConnection(conn); err != nil {
|
||||
_ = EncodeResponse(conn, Response{Code: "UNAUTHORIZED", Message: "\u672c\u673a\u8c03\u7528\u8005\u8eab\u4efd\u4e0d\u53d7\u4fe1\u4efb"})
|
||||
_ = EncodeResponse(conn, Response{Code: "UNAUTHORIZED", Message: "本机调用者身份不受信任"})
|
||||
return
|
||||
}
|
||||
handleResetConnection(conn, conn.SetDeadline, handler, guard)
|
||||
|
||||
@@ -114,7 +114,7 @@ func Authenticate(account, plain string) (*models.User, error) {
|
||||
|
||||
// HashPassword 统一生成新密码哈希。
|
||||
func HashPassword(plain string) (string, error) {
|
||||
return password.Hash(plain)
|
||||
return password.HashUserPassword(plain)
|
||||
}
|
||||
|
||||
// SetPassword 为用户设置新密码。
|
||||
|
||||
@@ -25,10 +25,10 @@ func TestAuthenticateUsesArgon2idOnly(t *testing.T) {
|
||||
})
|
||||
|
||||
user := models.User{Account: "test-user", Name: "测试用户", IsAdmin: 1}
|
||||
if err := SetPassword(&user, "correct-password"); err != nil {
|
||||
if err := SetPassword(&user, "CorrectP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(user.Password, "$argon2id$") || !password.Verify(user.Password, "correct-password") {
|
||||
if !strings.HasPrefix(user.Password, "$argon2id$") || !password.Verify(user.Password, "CorrectP12") {
|
||||
t.Fatal("测试密码哈希格式或校验失败")
|
||||
}
|
||||
if _, err := db.Instance.Insert(&user); err != nil {
|
||||
@@ -42,10 +42,10 @@ func TestAuthenticateUsesArgon2idOnly(t *testing.T) {
|
||||
if loaded.ID == 0 || !strings.HasPrefix(loaded.Password, "$argon2id$") {
|
||||
t.Fatalf("测试用户未正确写入")
|
||||
}
|
||||
if _, err := Authenticate("test-user", "correct-password"); err != nil {
|
||||
if _, err := Authenticate("test-user", "CorrectP12"); err != nil {
|
||||
t.Fatalf("新密码认证失败: %v", err)
|
||||
}
|
||||
if _, err := Authenticate("test-user", "wrong-password"); err == nil {
|
||||
if _, err := Authenticate("test-user", "WrongPass12"); err == nil {
|
||||
t.Fatal("错误密码不应认证成功")
|
||||
}
|
||||
if _, err := Authenticate("test-user", ""); err == nil {
|
||||
|
||||
@@ -29,20 +29,20 @@ func TestAuthenticateUsesUniformCredentialErrors(t *testing.T) {
|
||||
}
|
||||
|
||||
active := models.User{Account: "active-user", Name: "active"}
|
||||
if err := SetPassword(&active, "correct-password"); err != nil {
|
||||
if err := SetPassword(&active, "CorrectP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disabled := models.User{Account: "disabled-user", Name: "disabled", Disabled: 1}
|
||||
if err := SetPassword(&disabled, "correct-password"); err != nil {
|
||||
if err := SetPassword(&disabled, "CorrectP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Instance.Insert(&active, &disabled); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, wrongErr := Authenticate("active-user", "wrong-password")
|
||||
_, missingErr := Authenticate("missing-user", "wrong-password")
|
||||
_, disabledErr := Authenticate("disabled-user", "wrong-password")
|
||||
_, wrongErr := Authenticate("active-user", "WrongPass12")
|
||||
_, missingErr := Authenticate("missing-user", "WrongPass12")
|
||||
_, disabledErr := Authenticate("disabled-user", "WrongPass12")
|
||||
if wrongErr == nil || missingErr == nil || disabledErr == nil {
|
||||
t.Fatal("credential failure unexpectedly authenticated")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
package dbmigration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusPreviewed Status = "previewed"
|
||||
StatusCreated Status = "created"
|
||||
StatusCopying Status = "copying"
|
||||
StatusVerifying Status = "verifying"
|
||||
StatusSwitching Status = "switching"
|
||||
StatusSucceeded Status = "succeeded"
|
||||
StatusFailed Status = "failed"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidRequest = errors.New("database migration request is invalid")
|
||||
ErrInvalidTargetName = errors.New("database migration target name is invalid")
|
||||
ErrImmutableSetting = errors.New("database migration may change only the database name")
|
||||
ErrMigrationNotFound = errors.New("database migration not found")
|
||||
ErrPreviewInvalid = errors.New("database migration preview is invalid")
|
||||
ErrPreviewExpired = errors.New("database migration preview expired")
|
||||
ErrMigrationState = errors.New("database migration state is invalid")
|
||||
ErrExecutorUnavailable = errors.New("database migration executor unavailable")
|
||||
ErrSourceDatabase = errors.New("source database configuration is invalid")
|
||||
)
|
||||
|
||||
const previewLifetime = 10 * time.Minute
|
||||
|
||||
var targetNamePattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_-]{0,62}$`)
|
||||
var sqliteTargetNamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
|
||||
|
||||
type DatabaseIdentity struct {
|
||||
Type config.DatabaseType `json:"type"`
|
||||
Host string `json:"host,omitempty"`
|
||||
Port uint16 `json:"port,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
LocalRef string `json:"localRef,omitempty"`
|
||||
}
|
||||
|
||||
type Plan struct {
|
||||
Source DatabaseIdentity
|
||||
Target DatabaseIdentity
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
ID string `json:"id"`
|
||||
Status Status `json:"status"`
|
||||
Source DatabaseIdentity `json:"source"`
|
||||
Target DatabaseIdentity `json:"target"`
|
||||
CurrentGeneration uint64 `json:"currentGeneration"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
ErrorCode string `json:"errorCode,omitempty"`
|
||||
}
|
||||
|
||||
type Runner interface {
|
||||
Run(context.Context, Plan, func(Status) error) error
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
mu sync.RWMutex
|
||||
records map[string]*record
|
||||
runner Runner
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type record struct {
|
||||
Record
|
||||
tokenHash [32]byte
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
var current struct {
|
||||
sync.RWMutex
|
||||
value *Service
|
||||
}
|
||||
|
||||
func NewService(runner Runner) *Service {
|
||||
return &Service{records: make(map[string]*record), runner: runner, now: func() time.Time { return time.Now().UTC() }}
|
||||
}
|
||||
|
||||
func SetCurrent(service *Service) {
|
||||
current.Lock()
|
||||
current.value = service
|
||||
current.Unlock()
|
||||
}
|
||||
|
||||
func Current() *Service {
|
||||
current.RLock()
|
||||
defer current.RUnlock()
|
||||
return current.value
|
||||
}
|
||||
|
||||
func (s *Service) Preview(_ context.Context, source config.DatabaseConfig, currentGeneration uint64, targetName string) (Record, string, error) {
|
||||
if s == nil || currentGeneration == 0 {
|
||||
return Record{}, "", ErrInvalidRequest
|
||||
}
|
||||
if err := config.ValidateDatabaseConfig(source); err != nil {
|
||||
return Record{}, "", ErrSourceDatabase
|
||||
}
|
||||
targetName = strings.TrimSpace(targetName)
|
||||
if (source.Type == config.DatabaseTypeSQLite && !sqliteTargetNamePattern.MatchString(targetName)) || (source.Type != config.DatabaseTypeSQLite && !targetNamePattern.MatchString(targetName)) {
|
||||
return Record{}, "", ErrInvalidTargetName
|
||||
}
|
||||
plan, err := buildPlan(source, targetName)
|
||||
if err != nil {
|
||||
return Record{}, "", err
|
||||
}
|
||||
id, err := randomID("dbmig-")
|
||||
if err != nil {
|
||||
return Record{}, "", ErrInvalidRequest
|
||||
}
|
||||
token, err := randomID("preview-")
|
||||
if err != nil {
|
||||
return Record{}, "", ErrInvalidRequest
|
||||
}
|
||||
now := s.currentTime()
|
||||
item := &record{Record: Record{ID: id, Status: StatusPreviewed, Source: plan.Source, Target: plan.Target, CurrentGeneration: currentGeneration, CreatedAt: now, UpdatedAt: now}, tokenHash: sha256.Sum256([]byte(token)), expiresAt: now.Add(previewLifetime)}
|
||||
s.mu.Lock()
|
||||
s.records[id] = item
|
||||
s.mu.Unlock()
|
||||
return cloneRecord(item.Record), token, nil
|
||||
}
|
||||
|
||||
func (s *Service) Execute(ctx context.Context, id, token string) (Record, error) {
|
||||
if s == nil || strings.TrimSpace(id) == "" || strings.TrimSpace(token) == "" {
|
||||
return Record{}, ErrInvalidRequest
|
||||
}
|
||||
now := s.currentTime()
|
||||
s.mu.Lock()
|
||||
item, ok := s.records[id]
|
||||
if !ok {
|
||||
s.mu.Unlock()
|
||||
return Record{}, ErrMigrationNotFound
|
||||
}
|
||||
if item.Status != StatusPreviewed {
|
||||
snapshot := cloneRecord(item.Record)
|
||||
s.mu.Unlock()
|
||||
return snapshot, ErrMigrationState
|
||||
}
|
||||
if now.After(item.expiresAt) {
|
||||
item.Status = StatusFailed
|
||||
item.ErrorCode = "PREVIEW_EXPIRED"
|
||||
item.UpdatedAt = now
|
||||
s.mu.Unlock()
|
||||
return cloneRecord(item.Record), ErrPreviewExpired
|
||||
}
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
if subtle.ConstantTimeCompare(hash[:], item.tokenHash[:]) != 1 {
|
||||
s.mu.Unlock()
|
||||
return Record{}, ErrPreviewInvalid
|
||||
}
|
||||
item.tokenHash = [32]byte{}
|
||||
item.Status = StatusCreated
|
||||
item.UpdatedAt = now
|
||||
plan := Plan{Source: item.Source, Target: item.Target}
|
||||
s.mu.Unlock()
|
||||
|
||||
if err := s.setStatus(id, StatusCopying); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
if s.runner == nil {
|
||||
return s.fail(id, ErrExecutorUnavailable)
|
||||
}
|
||||
if err := s.runner.Run(ctx, plan, func(status Status) error { return s.setStatus(id, status) }); err != nil {
|
||||
return s.fail(id, err)
|
||||
}
|
||||
if err := s.setStatus(id, StatusSucceeded); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
return s.Get(id)
|
||||
}
|
||||
|
||||
func (s *Service) Get(id string) (Record, error) {
|
||||
if s == nil || strings.TrimSpace(id) == "" {
|
||||
return Record{}, ErrInvalidRequest
|
||||
}
|
||||
s.mu.RLock()
|
||||
item, ok := s.records[id]
|
||||
if !ok {
|
||||
s.mu.RUnlock()
|
||||
return Record{}, ErrMigrationNotFound
|
||||
}
|
||||
value := cloneRecord(item.Record)
|
||||
s.mu.RUnlock()
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (s *Service) setStatus(id string, status Status) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
item, ok := s.records[id]
|
||||
if !ok {
|
||||
return ErrMigrationNotFound
|
||||
}
|
||||
if !validStatusTransition(item.Status, status) {
|
||||
return ErrMigrationState
|
||||
}
|
||||
item.Status = status
|
||||
item.UpdatedAt = s.currentTime()
|
||||
return nil
|
||||
}
|
||||
|
||||
func validStatusTransition(current, next Status) bool {
|
||||
if current == StatusFailed || current == StatusSucceeded || next == StatusPreviewed || next == StatusFailed {
|
||||
return false
|
||||
}
|
||||
return statusRank(next) >= statusRank(current)
|
||||
}
|
||||
|
||||
func statusRank(status Status) int {
|
||||
switch status {
|
||||
case StatusCreated:
|
||||
return 1
|
||||
case StatusCopying:
|
||||
return 2
|
||||
case StatusVerifying:
|
||||
return 3
|
||||
case StatusSwitching:
|
||||
return 4
|
||||
case StatusSucceeded:
|
||||
return 5
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) fail(id string, err error) (Record, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
item, ok := s.records[id]
|
||||
if !ok {
|
||||
return Record{}, ErrMigrationNotFound
|
||||
}
|
||||
item.Status = StatusFailed
|
||||
item.ErrorCode = migrationErrorCode(err)
|
||||
item.UpdatedAt = s.currentTime()
|
||||
return cloneRecord(item.Record), err
|
||||
}
|
||||
|
||||
func (s *Service) currentTime() time.Time {
|
||||
if s.now == nil {
|
||||
return time.Now().UTC()
|
||||
}
|
||||
return s.now().UTC()
|
||||
}
|
||||
|
||||
func buildPlan(source config.DatabaseConfig, targetName string) (Plan, error) {
|
||||
source = config.NormalizeDatabaseConfig(source)
|
||||
identity := DatabaseIdentity{Type: source.Type, Host: source.Host, Port: source.Port, Username: source.Username, Name: source.Name, LocalRef: source.LocalRef}
|
||||
target := identity
|
||||
if source.Type == config.DatabaseTypeSQLite {
|
||||
target.LocalRef = targetName
|
||||
} else {
|
||||
target.Name = targetName
|
||||
}
|
||||
if target.Type != source.Type || target.Host != source.Host || target.Port != source.Port || target.Username != source.Username {
|
||||
return Plan{}, ErrImmutableSetting
|
||||
}
|
||||
return Plan{Source: identity, Target: target}, nil
|
||||
}
|
||||
|
||||
func randomID(prefix string) (string, error) {
|
||||
value := make([]byte, 16)
|
||||
if _, err := rand.Read(value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return prefix + hex.EncodeToString(value), nil
|
||||
}
|
||||
|
||||
func cloneRecord(value Record) Record {
|
||||
return value
|
||||
}
|
||||
|
||||
func migrationErrorCode(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, ErrExecutorUnavailable):
|
||||
return "EXECUTOR_UNAVAILABLE"
|
||||
case errors.Is(err, ErrPreviewExpired):
|
||||
return "PREVIEW_EXPIRED"
|
||||
default:
|
||||
return "MIGRATION_FAILED"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package dbmigration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/utils/credential"
|
||||
)
|
||||
|
||||
type testRunner struct{}
|
||||
|
||||
func (testRunner) Run(_ context.Context, _ Plan, update func(Status) error) error {
|
||||
if err := update(StatusCopying); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := update(StatusVerifying); err != nil {
|
||||
return err
|
||||
}
|
||||
return update(StatusSwitching)
|
||||
}
|
||||
|
||||
func testDatabase(t *testing.T) config.DatabaseConfig {
|
||||
t.Helper()
|
||||
vault, err := credential.NewVault(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ciphertext, err := vault.Encrypt("password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return config.DatabaseConfig{
|
||||
Type: config.DatabaseTypeMySQL,
|
||||
Host: "db.internal",
|
||||
Port: 3306,
|
||||
Username: "smail",
|
||||
Name: "smail",
|
||||
Password: config.StoredSecret{Ciphertext: ciphertext, Version: vault.Version(), UpdatedAt: time.Unix(1, 0).UTC()},
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewAndExecuteUseOnlyDatabaseName(t *testing.T) {
|
||||
service := NewService(testRunner{})
|
||||
service.now = func() time.Time { return time.Date(2026, 8, 30, 0, 0, 0, 0, time.UTC) }
|
||||
record, token, err := service.Preview(context.Background(), testDatabase(t), 7, "smail_next")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if record.Status != StatusPreviewed || record.Source.Name != "smail" || record.Target.Name != "smail_next" {
|
||||
t.Fatalf("unexpected preview: %+v", record)
|
||||
}
|
||||
if record.Source.Host != record.Target.Host || record.Source.Port != record.Target.Port || record.Source.Username != record.Target.Username {
|
||||
t.Fatalf("immutable database settings changed: %+v", record)
|
||||
}
|
||||
if token == "" {
|
||||
t.Fatal("preview token is empty")
|
||||
}
|
||||
completed, err := service.Execute(context.Background(), record.ID, token)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if completed.Status != StatusSucceeded {
|
||||
t.Fatalf("migration status = %s, want succeeded", completed.Status)
|
||||
}
|
||||
if _, err := service.Execute(context.Background(), record.ID, token); !errors.Is(err, ErrMigrationState) {
|
||||
t.Fatalf("replayed token returned %v, want state error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewRejectsUnsafeTargetName(t *testing.T) {
|
||||
service := NewService(testRunner{})
|
||||
if _, _, err := service.Preview(context.Background(), testDatabase(t), 1, "smail;drop"); !errors.Is(err, ErrInvalidTargetName) {
|
||||
t.Fatalf("unsafe target returned %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedExecutionKeepsSafeState(t *testing.T) {
|
||||
service := NewService(nil)
|
||||
record, token, err := service.Preview(context.Background(), testDatabase(t), 1, "smail_next")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed, err := service.Execute(context.Background(), record.ID, token)
|
||||
if !errors.Is(err, ErrExecutorUnavailable) {
|
||||
t.Fatalf("execution returned %v, want executor unavailable", err)
|
||||
}
|
||||
if failed.Status != StatusFailed || failed.ErrorCode != "EXECUTOR_UNAVAILABLE" {
|
||||
t.Fatalf("unexpected failed state: %+v", failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSQLitePreviewChangesOnlyLocalReference(t *testing.T) {
|
||||
service := NewService(testRunner{})
|
||||
source := config.DatabaseConfig{Type: config.DatabaseTypeSQLite, LocalRef: "smail.db"}
|
||||
record, _, err := service.Preview(context.Background(), source, 1, "smail-next.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if record.Target.LocalRef != "smail-next.db" || record.Target.Type != config.DatabaseTypeSQLite || record.Target.Name != "" {
|
||||
t.Fatalf("unexpected sqlite target: %+v", record.Target)
|
||||
}
|
||||
}
|
||||
|
||||
type invalidTransitionRunner struct{}
|
||||
|
||||
func (invalidTransitionRunner) Run(_ context.Context, _ Plan, update func(Status) error) error {
|
||||
return update(StatusCreated)
|
||||
}
|
||||
|
||||
func TestMigrationRejectsBackwardStatusTransition(t *testing.T) {
|
||||
service := NewService(invalidTransitionRunner{})
|
||||
record, token, err := service.Preview(context.Background(), testDatabase(t), 1, "smail_next")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed, err := service.Execute(context.Background(), record.ID, token)
|
||||
if !errors.Is(err, ErrMigrationState) {
|
||||
t.Fatalf("execution returned %v, want state error", err)
|
||||
}
|
||||
if failed.Status != StatusFailed || failed.ErrorCode != "MIGRATION_FAILED" {
|
||||
t.Fatalf("unexpected failed migration: %+v", failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationRecordsRemainIndependentDuringConcurrentExecution(t *testing.T) {
|
||||
service := NewService(testRunner{})
|
||||
first, firstToken, err := service.Preview(context.Background(), testDatabase(t), 1, "smail_first")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, secondToken, err := service.Preview(context.Background(), testDatabase(t), 1, "smail_second")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
results := make(chan struct {
|
||||
record Record
|
||||
err error
|
||||
}, 2)
|
||||
go func() {
|
||||
record, err := service.Execute(context.Background(), first.ID, firstToken)
|
||||
results <- struct {
|
||||
record Record
|
||||
err error
|
||||
}{record: record, err: err}
|
||||
}()
|
||||
go func() {
|
||||
record, err := service.Execute(context.Background(), second.ID, secondToken)
|
||||
results <- struct {
|
||||
record Record
|
||||
err error
|
||||
}{record: record, err: err}
|
||||
}()
|
||||
for range 2 {
|
||||
result := <-results
|
||||
if result.err != nil {
|
||||
t.Fatalf("concurrent execution failed: %v", result.err)
|
||||
}
|
||||
if result.record.Status != StatusSucceeded {
|
||||
t.Fatalf("unexpected concurrent status: %+v", result.record)
|
||||
}
|
||||
if result.record.Target.Name != "smail_first" && result.record.Target.Name != "smail_second" {
|
||||
t.Fatalf("unexpected concurrent target: %+v", result.record.Target)
|
||||
}
|
||||
}
|
||||
firstState, err := service.Get(first.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secondState, err := service.Get(second.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if firstState.Target.Name != "smail_first" || secondState.Target.Name != "smail_second" {
|
||||
t.Fatalf("migration records crossed: first=%+v second=%+v", firstState.Target, secondState.Target)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -49,7 +50,17 @@ type SecretStatus struct {
|
||||
|
||||
// TelegramUserSettings 是 Telegram 插件唯一允许由用户维护的设置。
|
||||
type TelegramUserSettings struct {
|
||||
ChatID string `json:"chatId"`
|
||||
ChatID string `json:"chatId"`
|
||||
ShowContent bool `json:"showContent"`
|
||||
SpoilerContent bool `json:"spoilerContent"`
|
||||
SendAttachments bool `json:"sendAttachments"`
|
||||
DisableLinkPreview bool `json:"disableLinkPreview"`
|
||||
}
|
||||
|
||||
// TelegramUserSettingsEntry 用于在插件启动或配置更新后同步用户设置。
|
||||
type TelegramUserSettingsEntry struct {
|
||||
UserID int
|
||||
Settings TelegramUserSettings
|
||||
}
|
||||
|
||||
// UserSettingsStatus 返回用户本人可见的设置与乐观锁版本。
|
||||
@@ -300,6 +311,38 @@ func (s *ConfigService) GetOwnTelegramSettings(actorUserID int) (UserSettingsSta
|
||||
return s.getTelegramSettings(actorUserID)
|
||||
}
|
||||
|
||||
// ListTelegramUserSettings 返回已配置的 Telegram 用户设置,不返回任何密钥。
|
||||
func (s *ConfigService) ListTelegramUserSettings() ([]TelegramUserSettingsEntry, error) {
|
||||
if s == nil || s.engine == nil || s.vault == nil {
|
||||
return nil, ErrPluginStoreUnavailable
|
||||
}
|
||||
var records []models.PluginUserSetting
|
||||
if err := s.engine.Where("plugin_id = ? AND enabled = ?", telegramPluginID, true).Find(&records); err != nil {
|
||||
return nil, fmt.Errorf("load Telegram user settings: %w", err)
|
||||
}
|
||||
entries := make([]TelegramUserSettingsEntry, 0, len(records))
|
||||
for _, record := range records {
|
||||
if record.SchemaVersion != userSettingsSchemaVersion {
|
||||
return nil, ErrPluginStoreUnavailable
|
||||
}
|
||||
plaintext, err := s.vault.Decrypt(credential.CurrentVersion, record.SettingsCiphertext)
|
||||
if err != nil {
|
||||
return nil, ErrPluginStoreUnavailable
|
||||
}
|
||||
fingerprint, err := s.vault.Fingerprint(plaintext)
|
||||
if err != nil || fingerprint != record.SettingsHash {
|
||||
return nil, ErrPluginStoreUnavailable
|
||||
}
|
||||
settings, err := decodeTelegramSettings(plaintext)
|
||||
if err != nil {
|
||||
return nil, ErrPluginStoreUnavailable
|
||||
}
|
||||
entries = append(entries, TelegramUserSettingsEntry{UserID: record.UserID, Settings: settings})
|
||||
}
|
||||
sort.Slice(entries, func(left, right int) bool { return entries[left].UserID < entries[right].UserID })
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// UpdateOwnTelegramSettings 的 actorUserID 必须来自已验证 Session,调用方不得传入目标用户 ID。
|
||||
func (s *ConfigService) UpdateOwnTelegramSettings(actorUserID int, settings TelegramUserSettings, expectedVersion uint64) (UserSettingsStatus, error) {
|
||||
|
||||
@@ -680,8 +723,13 @@ func validateSecretField(pluginID, fieldName string) error {
|
||||
return ErrUnknownPluginField
|
||||
}
|
||||
|
||||
func ValidateTelegramUserSettings(settings TelegramUserSettings) error {
|
||||
_, err := encodeTelegramSettings(settings)
|
||||
return err
|
||||
}
|
||||
func encodeTelegramSettings(settings TelegramUserSettings) (string, error) {
|
||||
if !telegramChatIDPattern.MatchString(strings.TrimSpace(settings.ChatID)) || settings.ChatID != strings.TrimSpace(settings.ChatID) {
|
||||
settings.ChatID = strings.TrimSpace(settings.ChatID)
|
||||
if settings.ChatID != "" && !telegramChatIDPattern.MatchString(settings.ChatID) {
|
||||
return "", ErrInvalidTelegramChatID
|
||||
}
|
||||
encoded, err := json.Marshal(settings)
|
||||
@@ -698,7 +746,7 @@ func decodeTelegramSettings(raw string) (TelegramUserSettings, error) {
|
||||
if err := decoder.Decode(&settings); err != nil {
|
||||
return TelegramUserSettings{}, err
|
||||
}
|
||||
if decoder.More() {
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
return TelegramUserSettings{}, ErrInvalidTelegramChatID
|
||||
}
|
||||
_, err := encodeTelegramSettings(settings)
|
||||
|
||||
@@ -74,6 +74,58 @@ func TestConfigServiceEncryptsTelegramUserSettingsAndRejectsTampering(t *testing
|
||||
t.Fatalf("tampered user setting error = %v", err)
|
||||
}
|
||||
}
|
||||
func TestConfigServiceAllowsEmptyTelegramChatIDToDisablePush(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
user := insertPluginTestUser(t, engine, "disabled-push", access.RoleUser)
|
||||
|
||||
status, err := service.UpdateOwnTelegramSettings(user.ID, TelegramUserSettings{}, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("empty chat ID update failed: %v", err)
|
||||
}
|
||||
if status.Settings.ChatID != "" || status.Version != 1 {
|
||||
t.Fatalf("unexpected empty chat ID status: %+v", status)
|
||||
}
|
||||
entries, err := service.ListTelegramUserSettings()
|
||||
if err != nil || len(entries) != 1 || entries[0].Settings.ChatID != "" {
|
||||
t.Fatalf("stored empty chat ID settings = %+v, err=%v", entries, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigServiceRejectsTrailingTelegramSettingsJSON(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
user := insertPluginTestUser(t, engine, "trailing-json", access.RoleUser)
|
||||
if _, err := service.UpdateOwnTelegramSettings(user.ID, TelegramUserSettings{ChatID: "123"}, 0); err != nil {
|
||||
t.Fatal(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 setting record: found=%v err=%v", found, err)
|
||||
}
|
||||
plaintext, err := service.vault.Decrypt(credential.CurrentVersion, record.SettingsCiphertext)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
badPlaintext := plaintext + " {}"
|
||||
ciphertext, err := service.vault.Encrypt(badPlaintext)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fingerprint, err := service.vault.Fingerprint(badPlaintext)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = engine.ID(record.ID).Cols("settings_ciphertext", "settings_hash").Update(&models.PluginUserSetting{
|
||||
SettingsCiphertext: ciphertext,
|
||||
SettingsHash: fingerprint,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = service.GetOwnTelegramSettings(user.ID); !errors.Is(err, ErrPluginStoreUnavailable) {
|
||||
t.Fatalf("trailing JSON was accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigServiceEnforcesUserSettingRolesAndVersions(t *testing.T) {
|
||||
service, engine := newPluginConfigService(t)
|
||||
super := insertPluginTestUser(t, engine, "root", access.RoleSuperAdmin)
|
||||
|
||||
@@ -284,7 +284,7 @@ func (s *Service) CompleteWithContext(ticketID, newPassword, browserContext stri
|
||||
if s == nil || s.engine == nil || s.credentials == nil || strings.TrimSpace(ticketID) == "" {
|
||||
return ErrInvalidRequest
|
||||
}
|
||||
if len([]byte(newPassword)) < 8 || len([]byte(newPassword)) > 256 {
|
||||
if password.ValidateUserPassword(newPassword) != nil {
|
||||
return ErrInvalidNewPassword
|
||||
}
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -28,7 +28,7 @@ func newRecoveryFixture(t *testing.T) (*Service, *verification.Service, *xorm.En
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
password, err := auth.HashPassword("OldPassword@123")
|
||||
password, err := auth.HashPassword("OldPass123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -85,10 +85,10 @@ func TestRecoveryRejectsCrossUserVerificationAndConsumesTicketOnce(t *testing.T)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := recoveryService.Complete(ticketID, "NewPassword@123"); err != nil {
|
||||
if err := recoveryService.Complete(ticketID, "NewPass123"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := recoveryService.Complete(ticketID, "AnotherPassword@123"); !errors.Is(err, ErrRecoveryExpired) {
|
||||
if err := recoveryService.Complete(ticketID, "NextPass123"); !errors.Is(err, ErrRecoveryExpired) {
|
||||
t.Fatalf("replayed recovery ticket error = %v", err)
|
||||
}
|
||||
var sessions []models.Sessions
|
||||
@@ -118,7 +118,7 @@ func TestRecoveryTicketConcurrentConsumptionHasOneWinner(t *testing.T) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
results <- recoveryService.Complete(ticketID, "ConcurrentPassword@123")
|
||||
results <- recoveryService.Complete(ticketID, "RacePass123")
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
@@ -145,7 +145,7 @@ func TestRecoveryDeniesSuperAdministrator(t *testing.T) {
|
||||
deliveries++
|
||||
return nil
|
||||
}
|
||||
password, err := auth.HashPassword("SuperPassword@123")
|
||||
password, err := auth.HashPassword("SuperPass12")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -352,7 +352,7 @@ func TestRecoveryRevokesExistingStrongRecoveryCredentials(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.Complete(ticketID, "RecoveredPassword@123"); err != nil {
|
||||
if err := service.Complete(ticketID, "RecoverP123"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if configured, err := service.credentials.HasValidRecoveryCode(user.ID); err != nil || configured {
|
||||
@@ -379,7 +379,7 @@ func TestRecoveryTicketRejectsChangedSessionVersion(t *testing.T) {
|
||||
if _, err := engine.ID(user.ID).Cols("session_version").Update(&models.User{SessionVersion: user.SessionVersion + 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.Complete(ticketID, "ChangedVersion@123"); !errors.Is(err, ErrRecoveryDenied) {
|
||||
if err := service.Complete(ticketID, "VersionP123"); !errors.Is(err, ErrRecoveryDenied) {
|
||||
t.Fatalf("版本变化后的票据错误 = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -406,10 +406,10 @@ func TestRecoveryBindsChallengeAndTicketToBrowserContext(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.CompleteWithContext(ticketID, "ContextPassword@123", "browser-b"); !errors.Is(err, ErrRecoveryDenied) {
|
||||
if err := service.CompleteWithContext(ticketID, "ContextP123", "browser-b"); !errors.Is(err, ErrRecoveryDenied) {
|
||||
t.Fatalf("different browser ticket result = %v", err)
|
||||
}
|
||||
if err := service.CompleteWithContext(ticketID, "ContextPassword@123", "browser-a"); err != nil {
|
||||
if err := service.CompleteWithContext(ticketID, "ContextP123", "browser-a"); err != nil {
|
||||
t.Fatalf("matching browser ticket result = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -61,10 +61,10 @@ func TestWebAuthnRecoveryIssuesOneTimeTicketAndRevokesCredentials(t *testing.T)
|
||||
if err != nil || ticketID == "" || verifier.finishCalls != 1 {
|
||||
t.Fatalf("verify webauthn recovery: ticket=%q calls=%d err=%v", ticketID, verifier.finishCalls, err)
|
||||
}
|
||||
if err := service.Complete(ticketID, "WebAuthnPassword@123"); err != nil {
|
||||
if err := service.Complete(ticketID, "WebAuthnP12"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.Complete(ticketID, "ReplayPassword@123"); !errors.Is(err, ErrRecoveryExpired) {
|
||||
if err := service.Complete(ticketID, "ReplayP123"); !errors.Is(err, ErrRecoveryExpired) {
|
||||
t.Fatalf("replayed ticket error = %v", err)
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ func TestWebAuthnRecoveryTicketExpiresAndSuperAdminIsDenied(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.now = func() time.Time { return time.Now().Add(authorizationTTL + time.Second) }
|
||||
if err := service.Complete(ticketID, "ExpiredPassword@123"); !errors.Is(err, ErrRecoveryExpired) {
|
||||
if err := service.Complete(ticketID, "ExpireP123"); !errors.Is(err, ErrRecoveryExpired) {
|
||||
t.Fatalf("expired ticket error = %v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,27 @@ type Trigger interface {
|
||||
Request(context.Context) error
|
||||
}
|
||||
|
||||
// Preview 描述固定的 Smail 重启目标,但不执行重启动作。
|
||||
type Preview struct {
|
||||
Target string `json:"target"`
|
||||
Action string `json:"action"`
|
||||
ActiveGeneration uint64 `json:"activeGeneration"`
|
||||
PendingServices []string `json:"pendingServices,omitempty"`
|
||||
ServiceManager string `json:"serviceManager"`
|
||||
TriggerAvailable bool `json:"triggerAvailable"`
|
||||
}
|
||||
|
||||
func BuildPreview(activeGeneration uint64, pendingServices []string, triggerAvailable bool) Preview {
|
||||
return Preview{
|
||||
Target: "smail",
|
||||
Action: "restart",
|
||||
ActiveGeneration: activeGeneration,
|
||||
PendingServices: append([]string(nil), pendingServices...),
|
||||
ServiceManager: "固定服务管理器",
|
||||
TriggerAvailable: triggerAvailable,
|
||||
}
|
||||
}
|
||||
|
||||
type SignalTrigger struct {
|
||||
channel chan<- bool
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package restart
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSignalTriggerRequest(t *testing.T) {
|
||||
channel := make(chan bool, 1)
|
||||
trigger := NewSignalTrigger(channel)
|
||||
if err := trigger.Request(context.Background()); err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
select {
|
||||
case value := <-channel:
|
||||
if !value {
|
||||
t.Fatal("restart signal was false")
|
||||
}
|
||||
default:
|
||||
t.Fatal("restart signal was not sent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignalTriggerUnavailable(t *testing.T) {
|
||||
if err := (*SignalTrigger)(nil).Request(context.Background()); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("expected unavailable error, got %v", err)
|
||||
}
|
||||
if err := NewSignalTrigger(nil).Request(context.Background()); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("expected unavailable error for nil channel, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignalTriggerCanceled(t *testing.T) {
|
||||
channel := make(chan bool)
|
||||
trigger := NewSignalTrigger(channel)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := trigger.Request(ctx); !errors.Is(err, ErrCanceled) {
|
||||
t.Fatalf("expected canceled error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentTriggerRegistry(t *testing.T) {
|
||||
SetCurrent(nil)
|
||||
if Current() != nil {
|
||||
t.Fatal("expected empty current trigger")
|
||||
}
|
||||
first := NewSignalTrigger(make(chan bool, 1))
|
||||
second := NewSignalTrigger(make(chan bool, 1))
|
||||
SetCurrent(first)
|
||||
if Current() != first {
|
||||
t.Fatal("first trigger was not registered")
|
||||
}
|
||||
SetCurrent(second)
|
||||
if Current() != second {
|
||||
t.Fatal("current trigger was not replaced")
|
||||
}
|
||||
SetCurrent(nil)
|
||||
if Current() != nil {
|
||||
t.Fatal("current trigger was not cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPreviewUsesFixedRestartTarget(t *testing.T) {
|
||||
pending := []string{"smtp", "imap"}
|
||||
preview := BuildPreview(9, pending, false)
|
||||
if preview.Target != "smail" || preview.Action != "restart" || preview.ActiveGeneration != 9 || preview.ServiceManager != "固定服务管理器" {
|
||||
t.Fatalf("unexpected restart preview: %+v", preview)
|
||||
}
|
||||
if preview.TriggerAvailable || len(preview.PendingServices) != 2 {
|
||||
t.Fatalf("unexpected restart preview availability: %+v", preview)
|
||||
}
|
||||
preview.PendingServices[0] = "changed"
|
||||
if pending[0] == "changed" {
|
||||
t.Fatal("preview shares pending service slice")
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/utils/array"
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
"git.pcux.cn/xuans/Smail/utils/errors"
|
||||
"git.pcux.cn/xuans/Smail/utils/password"
|
||||
"git.pcux.cn/xuans/Smail/utils/validation"
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"github.com/lib/pq"
|
||||
@@ -182,8 +183,8 @@ func SetAdminPassword(ctx *context.Context, account, pwd string) error {
|
||||
}
|
||||
|
||||
func validateAdminPassword(pwd string) error {
|
||||
passwordSize := len([]byte(pwd))
|
||||
if passwordSize < 8 || passwordSize > 12 {
|
||||
if err := password.ValidateUserPassword(pwd); err != nil {
|
||||
|
||||
return databaseError("管理员密码长度必须为 8 到 12 个字节", nil)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
const DefaultOperationalCleanupInterval = time.Hour
|
||||
|
||||
type OperationalCleanupRunner struct {
|
||||
mu sync.Mutex
|
||||
store *EventStore
|
||||
rateLimits *PersistentRateLimiter
|
||||
interval time.Duration
|
||||
@@ -31,18 +32,23 @@ func (r *OperationalCleanupRunner) Start() {
|
||||
return
|
||||
}
|
||||
r.once.Do(func() {
|
||||
r.mu.Lock()
|
||||
r.stop = make(chan struct{})
|
||||
r.done = make(chan struct{})
|
||||
stop, done := r.stop, r.done
|
||||
interval := r.interval
|
||||
r.mu.Unlock()
|
||||
|
||||
go func() {
|
||||
defer close(r.done)
|
||||
defer close(done)
|
||||
r.runOnce()
|
||||
ticker := time.NewTicker(r.interval)
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
r.runOnce()
|
||||
case <-r.stop:
|
||||
case <-stop:
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -51,13 +57,20 @@ func (r *OperationalCleanupRunner) Start() {
|
||||
}
|
||||
|
||||
func (r *OperationalCleanupRunner) Stop() {
|
||||
if r == nil || r.stop == nil {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
close(r.stop)
|
||||
<-r.done
|
||||
r.stop = nil
|
||||
r.done = nil
|
||||
r.mu.Lock()
|
||||
stop, done := r.stop, r.done
|
||||
if stop == nil {
|
||||
r.mu.Unlock()
|
||||
return
|
||||
}
|
||||
r.stop, r.done = nil, nil
|
||||
r.mu.Unlock()
|
||||
|
||||
close(stop)
|
||||
<-done
|
||||
}
|
||||
|
||||
func (r *OperationalCleanupRunner) runOnce() {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -84,3 +85,25 @@ func TestCleanupStateInsertQueryUsesPostgresPlaceholders(t *testing.T) {
|
||||
t.Fatalf("postgres cleanup query contains empty placeholders: %q", query)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationalCleanupRunnerStopIsIdempotentAndConcurrentSafe(t *testing.T) {
|
||||
engine := newCleanupEngine(t)
|
||||
defer engine.Close()
|
||||
store, err := NewEventStore(engine)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := NewOperationalCleanupRunner(store)
|
||||
runner.Start()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
runner.Stop()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
runner.Stop()
|
||||
}
|
||||
@@ -34,7 +34,7 @@ const (
|
||||
maxSessions = 1024
|
||||
)
|
||||
|
||||
// Config 闁诲氦顫夐惌顔剧不?WebAuthn 婵炴挻纰嶇换鍡欑矉閸℃稒鍎?RP 闂佸憡鐟ラ崐褰掑汲閻旂厧妞介悘鐐舵濞堝爼鏌熺拠鈥虫灈闁伙附鍨块弻锕傚Ψ瑜庣粣妤冩喐閻楀牊纾搁柍?
|
||||
// Config 保存 WebAuthn 信赖方和凭据加密存储配置。
|
||||
type Config struct {
|
||||
RPID string
|
||||
RPDisplayName string
|
||||
@@ -42,7 +42,7 @@ type Config struct {
|
||||
VaultRoot string
|
||||
}
|
||||
|
||||
// Service 闁荤姵鍔楅崰鏇㈡儗?WebAuthn 濠电偛顦崝宀勫船娴犲违濞达絿鍎ら銏㈡喐閻楀牊纾搁柍褜鍏涚粈渚€宕甸悢鐓庣妞ゆ梻鍘ч~锝夋倵闂堟稒顥滈柣掳鍔戝畷鎺楀Ω閵夛箑顏梺閫涘嫎閸婃繈寮ㄩ姀銈呂?
|
||||
// Service 管理 WebAuthn 注册、登录和凭据生命周期。
|
||||
type Service struct {
|
||||
engine *xorm.Engine
|
||||
vault string
|
||||
@@ -69,7 +69,7 @@ const (
|
||||
discoverableLoginCeremony
|
||||
)
|
||||
|
||||
// NewService 闂佸憡甯楃粙鎴犵磽?WebAuthn 闂佸搫鐗嗙粔瀛樻叏閻旂厧违闁稿本绋戦鐘绘煙鐎涙◤顏堝箯?SessionData 闂佸憡鐟禍娆戞崲濮樻墎鍋撳☉娅亜锕㈤鍛氦婵炴垶鍩冮弻銈夋煕閹邦剚鍣归柣掳鍔戞俊?
|
||||
// NewService 创建 WebAuthn 服务并校验必要配置。
|
||||
func NewService(engine *xorm.Engine, cfg Config) (*Service, error) {
|
||||
if engine == nil || strings.TrimSpace(cfg.RPID) == "" || strings.TrimSpace(cfg.RPDisplayName) == "" || len(cfg.RPOrigins) == 0 || strings.TrimSpace(cfg.VaultRoot) == "" {
|
||||
return nil, ErrUnavailable
|
||||
@@ -86,7 +86,7 @@ func NewService(engine *xorm.Engine, cfg Config) (*Service, error) {
|
||||
return &Service{engine: engine, vault: cfg.VaultRoot, authn: authn, sessions: make(map[string]ceremony), now: time.Now}, nil
|
||||
}
|
||||
|
||||
// BeginRegistration 閻庢鍠掗崑鎾斥攽椤旂⒈鍎愰柡浣哄仱瀹曟浠﹂崜褋鍋婄紓浣割儏椤戝懘鎳熼悢鍛婁氦闁哄倹瀵х粈鈧繛鎴炴尭缁夊綊鍩€椤掆偓缁绘垵危閹达附鍎嶉柛鏇ㄥ亜閺佸爼鎮楀☉娅偐妲愰幍顔藉珰?ID闂?
|
||||
// BeginRegistration 开始指定用户的 WebAuthn 注册流程。
|
||||
func (s *Service) BeginRegistration(userID int) (*protocol.CredentialCreation, string, error) {
|
||||
user, err := s.loadUser(userID)
|
||||
if err != nil {
|
||||
@@ -107,7 +107,7 @@ func (s *Service) BeginRegistration(userID int) (*protocol.CredentialCreation, s
|
||||
return creation, sessionID, nil
|
||||
}
|
||||
|
||||
// FinishRegistration 闂佸搫绋勭换婵嬫偘濞嗗緷纭呯疀濮樺吋缍岄梺闈╃祷閸斿矂骞栭柨瀣劅闁哄倽鍎荤€氭瑥菐閸ャ劎绠撻柣掳鍔戝畷婵嬫偐閼碱剚顫氶梺鍛婂焾閸樿棄鐣垫笟鈧俊?
|
||||
// FinishRegistration 完成指定用户的 WebAuthn 注册流程。
|
||||
func (s *Service) FinishRegistration(userID int, sessionID string, request *http.Request, displayName string) (*models.WebAuthnCredential, error) {
|
||||
item, err := s.takeSession(sessionID, registrationCeremony, userID)
|
||||
if err != nil {
|
||||
@@ -163,7 +163,7 @@ func (s *Service) FinishRegistration(userID int, sessionID string, request *http
|
||||
return record, nil
|
||||
}
|
||||
|
||||
// BeginLogin 閻庢鍠掗崑鎾斥攽椤旂⒈鍎忛柛鎴節閹矂濡疯閺嗗繘鏌熼幘顕呮婵?WebAuthn 闂佽皫鍡╁殭缂傚秴绉撮湁濞达綀銆€閺屻倝鏌?
|
||||
// BeginLogin 开始指定用户的 WebAuthn 登录流程。
|
||||
func (s *Service) BeginLogin(userID int) (*protocol.CredentialAssertion, string, error) {
|
||||
user, err := s.loadUser(userID)
|
||||
if err != nil {
|
||||
@@ -184,7 +184,7 @@ func (s *Service) BeginLogin(userID int) (*protocol.CredentialAssertion, string,
|
||||
return assertion, sessionID, nil
|
||||
}
|
||||
|
||||
// FinishLogin 闂佸搫绋勭换婵嬫偘濞嗘挸妫樻い鎾閺嬪懘鏌曢崱鏇犲妽婵炴彃娼″顒勫箥椤曞懎濮伴梺鍛婅壘缁夌兘顢橀幖浣告瀬闁哄鍎荤€氭瑩姊洪幓鎺斝㈤柛鐔告崌瀹曟繈鎮╅懠顒侇潥闂佸憡鍩堥崢钘夌暤娓氣偓婵?
|
||||
// FinishLogin 完成指定用户的 WebAuthn 登录流程。
|
||||
func (s *Service) FinishLogin(userID int, sessionID string, request *http.Request) (*models.WebAuthnCredential, error) {
|
||||
item, err := s.takeSession(sessionID, loginCeremony, userID)
|
||||
if err != nil {
|
||||
@@ -291,7 +291,7 @@ func (s *Service) FinishDiscoverableLogin(sessionID string, request *http.Reques
|
||||
return &user, record, nil
|
||||
}
|
||||
|
||||
// ListCredentials 闁哄鏅滈弻銊ッ洪弽顓熷殗閺夊牄鍔嶅▍娑㈡煕閹搭厼骞楃€规挷鑳跺Σ鎰板閻樼數鈹涢梺鎸庣☉婵傛梻绮径瀣氦闁哄倹瀵х粈鈧梺绋挎禋閸撶喖骞愬鍫濈闁哄诞鍐炬奖闁诲酣娼уΛ娆忣焽濡ゅ懎妫樻繛鍡楃М閸?
|
||||
// ListCredentials 列出指定用户的非敏感 WebAuthn 凭据摘要。
|
||||
func (s *Service) ListCredentials(userID int) ([]models.WebAuthnCredential, error) {
|
||||
if s == nil || s.engine == nil || userID <= 0 {
|
||||
return nil, ErrInvalidRequest
|
||||
@@ -306,7 +306,7 @@ func (s *Service) ListCredentials(userID int) ([]models.WebAuthnCredential, erro
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// RenameCredential 闂佸憡鐟禍婊堝储閹寸姵濯肩紒瀣仢濞堝爼鏌熺拠鈥虫灍濠⒀冪Ф娴狅箓鎮欓崹顐f闂佸湱顥愬〒褰掑箞閵娾晛缁╅柣鐔哄閸婂磭绱掓径搴$劷闁?
|
||||
// RenameCredential 修改指定用户凭据的显示名称。
|
||||
func (s *Service) RenameCredential(userID, credentialID int, displayName string) error {
|
||||
if userID <= 0 || credentialID <= 0 || strings.TrimSpace(displayName) == "" || len([]byte(displayName)) > 128 {
|
||||
return ErrInvalidRequest
|
||||
@@ -319,7 +319,7 @@ func (s *Service) RenameCredential(userID, credentialID int, displayName string)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RevokeCredential 闂侀€涘嫎閸婃繈寮ㄩ姀锝冧汗闁规儳鍟块·鍛存煟椤剙濡介柛鈺傜洴閹啴宕熼鍡╀紘婵$偑鍊楅幊鎾诲吹閻旂厧绠叉い鏇炴缁€澶愭煙娣囧崬鈧繈寮ㄩ姀锛勨枖鐎广儱鎳庣拋鏌ユ⒑椤愩垺顥撻柍?
|
||||
// RevokeCredential 撤销指定用户的一项 WebAuthn 凭据。
|
||||
func (s *Service) RevokeCredential(userID, credentialID int) error {
|
||||
if userID <= 0 || credentialID <= 0 {
|
||||
return ErrInvalidRequest
|
||||
@@ -333,7 +333,7 @@ func (s *Service) RevokeCredential(userID, credentialID int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RevokeAllCredentials 闂侀€涘嫎閸婃繈寮ㄩ姀銈嗗仺闁靛绠戦悡鏇㈡煟閵娿儱顏╅柛娆忕箻閺屽牓濡搁敂鐣岀暢闂?WebAuthn 闂佸憡鍩堥崢钘夌暤娓氣偓婵?
|
||||
// RevokeAllCredentials 撤销指定用户的全部 WebAuthn 凭据。
|
||||
func (s *Service) RevokeAllCredentials(userID int) error {
|
||||
if userID <= 0 {
|
||||
return ErrInvalidRequest
|
||||
|
||||
Reference in new issue
Block a user